rsh.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: rsh.cc,v 1.6.2.1 2004/01/16 18:58:50 mdz Exp $
  4. /* ######################################################################
  5. RSH method - Transfer files via rsh compatible program
  6. Written by Ben Collins <bcollins@debian.org>, Copyright (c) 2000
  7. Licensed under the GNU General Public License v2 [no exception clauses]
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include Files /*{{{*/
  11. #include <config.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/hashes.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <sys/stat.h>
  17. #include <sys/time.h>
  18. #include <utime.h>
  19. #include <unistd.h>
  20. #include <signal.h>
  21. #include <stdio.h>
  22. #include <errno.h>
  23. #include <stdarg.h>
  24. #include "rsh.h"
  25. #include <apti18n.h>
  26. /*}}}*/
  27. const char *Prog;
  28. unsigned long TimeOut = 120;
  29. Configuration::Item const *RshOptions = 0;
  30. time_t RSHMethod::FailTime = 0;
  31. std::string RSHMethod::FailFile;
  32. int RSHMethod::FailFd = -1;
  33. // RSHConn::RSHConn - Constructor /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. RSHConn::RSHConn(URI Srv) : Len(0), WriteFd(-1), ReadFd(-1),
  37. ServerName(Srv), Process(-1) {}
  38. /*}}}*/
  39. // RSHConn::RSHConn - Destructor /*{{{*/
  40. // ---------------------------------------------------------------------
  41. /* */
  42. RSHConn::~RSHConn()
  43. {
  44. Close();
  45. }
  46. /*}}}*/
  47. // RSHConn::Close - Forcibly terminate the connection /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* Often this is called when things have gone wrong to indicate that the
  50. connection is no longer usable. */
  51. void RSHConn::Close()
  52. {
  53. if (Process == -1)
  54. return;
  55. close(WriteFd);
  56. close(ReadFd);
  57. kill(Process,SIGINT);
  58. ExecWait(Process,"",true);
  59. WriteFd = -1;
  60. ReadFd = -1;
  61. Process = -1;
  62. }
  63. /*}}}*/
  64. // RSHConn::Open - Connect to a host /*{{{*/
  65. // ---------------------------------------------------------------------
  66. /* */
  67. bool RSHConn::Open()
  68. {
  69. // Use the already open connection if possible.
  70. if (Process != -1)
  71. return true;
  72. if (Connect(ServerName.Host,ServerName.User) == false)
  73. return false;
  74. return true;
  75. }
  76. /*}}}*/
  77. // RSHConn::Connect - Fire up rsh and connect /*{{{*/
  78. // ---------------------------------------------------------------------
  79. /* */
  80. bool RSHConn::Connect(std::string Host, std::string User)
  81. {
  82. // Create the pipes
  83. int Pipes[4] = {-1,-1,-1,-1};
  84. if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
  85. {
  86. _error->Errno("pipe",_("Failed to create IPC pipe to subprocess"));
  87. for (int I = 0; I != 4; I++)
  88. close(Pipes[I]);
  89. return false;
  90. }
  91. for (int I = 0; I != 4; I++)
  92. SetCloseExec(Pipes[I],true);
  93. Process = ExecFork();
  94. // The child
  95. if (Process == 0)
  96. {
  97. const char *Args[400];
  98. unsigned int i = 0;
  99. dup2(Pipes[1],STDOUT_FILENO);
  100. dup2(Pipes[2],STDIN_FILENO);
  101. // Probably should do
  102. // dup2(open("/dev/null",O_RDONLY),STDERR_FILENO);
  103. Args[i++] = Prog;
  104. // Insert user-supplied command line options
  105. Configuration::Item const *Opts = RshOptions;
  106. if (Opts != 0)
  107. {
  108. Opts = Opts->Child;
  109. for (; Opts != 0; Opts = Opts->Next)
  110. {
  111. if (Opts->Value.empty() == true)
  112. continue;
  113. Args[i++] = Opts->Value.c_str();
  114. }
  115. }
  116. if (User.empty() == false) {
  117. Args[i++] = "-l";
  118. Args[i++] = User.c_str();
  119. }
  120. if (Host.empty() == false) {
  121. Args[i++] = Host.c_str();
  122. }
  123. Args[i++] = "/bin/sh";
  124. Args[i] = 0;
  125. execvp(Args[0],(char **)Args);
  126. exit(100);
  127. }
  128. ReadFd = Pipes[0];
  129. WriteFd = Pipes[3];
  130. SetNonBlock(Pipes[0],true);
  131. SetNonBlock(Pipes[3],true);
  132. close(Pipes[1]);
  133. close(Pipes[2]);
  134. return true;
  135. }
  136. /*}}}*/
  137. // RSHConn::ReadLine - Very simple buffered read with timeout /*{{{*/
  138. // ---------------------------------------------------------------------
  139. /* */
  140. bool RSHConn::ReadLine(std::string &Text)
  141. {
  142. if (Process == -1 || ReadFd == -1)
  143. return false;
  144. // Suck in a line
  145. while (Len < sizeof(Buffer))
  146. {
  147. // Scan the buffer for a new line
  148. for (unsigned int I = 0; I != Len; I++)
  149. {
  150. // Escape some special chars
  151. if (Buffer[I] == 0)
  152. Buffer[I] = '?';
  153. // End of line?
  154. if (Buffer[I] != '\n')
  155. continue;
  156. I++;
  157. Text = std::string(Buffer,I);
  158. memmove(Buffer,Buffer+I,Len - I);
  159. Len -= I;
  160. return true;
  161. }
  162. // Wait for some data..
  163. if (WaitFd(ReadFd,false,TimeOut) == false)
  164. {
  165. Close();
  166. return _error->Error(_("Connection timeout"));
  167. }
  168. // Suck it back
  169. int Res = read(ReadFd,Buffer + Len,sizeof(Buffer) - Len);
  170. if (Res <= 0)
  171. {
  172. _error->Errno("read",_("Read error"));
  173. Close();
  174. return false;
  175. }
  176. Len += Res;
  177. }
  178. return _error->Error(_("A response overflowed the buffer."));
  179. }
  180. /*}}}*/
  181. // RSHConn::WriteMsg - Send a message with optional remote sync. /*{{{*/
  182. // ---------------------------------------------------------------------
  183. /* The remote sync flag appends a || echo which will insert blank line
  184. once the command completes. */
  185. bool RSHConn::WriteMsg(std::string &Text,bool Sync,const char *Fmt,...)
  186. {
  187. va_list args;
  188. va_start(args,Fmt);
  189. // sprintf the description
  190. char S[512];
  191. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  192. if (Sync == true)
  193. strcat(S," 2> /dev/null || echo\n");
  194. else
  195. strcat(S," 2> /dev/null\n");
  196. // Send it off
  197. unsigned long Len = strlen(S);
  198. unsigned long Start = 0;
  199. while (Len != 0)
  200. {
  201. if (WaitFd(WriteFd,true,TimeOut) == false)
  202. {
  203. Close();
  204. return _error->Error(_("Connection timeout"));
  205. }
  206. int Res = write(WriteFd,S + Start,Len);
  207. if (Res <= 0)
  208. {
  209. _error->Errno("write",_("Write error"));
  210. Close();
  211. return false;
  212. }
  213. Len -= Res;
  214. Start += Res;
  215. }
  216. if (Sync == true)
  217. return ReadLine(Text);
  218. return true;
  219. }
  220. /*}}}*/
  221. // RSHConn::Size - Return the size of the file /*{{{*/
  222. // ---------------------------------------------------------------------
  223. /* Right now for successfull transfer the file size must be known in
  224. advance. */
  225. bool RSHConn::Size(const char *Path,unsigned long long &Size)
  226. {
  227. // Query the size
  228. std::string Msg;
  229. Size = 0;
  230. if (WriteMsg(Msg,true,"find %s -follow -printf '%%s\\n'",Path) == false)
  231. return false;
  232. // FIXME: Sense if the bad reply is due to a File Not Found.
  233. char *End;
  234. Size = strtoull(Msg.c_str(),&End,10);
  235. if (End == Msg.c_str())
  236. return _error->Error(_("File not found"));
  237. return true;
  238. }
  239. /*}}}*/
  240. // RSHConn::ModTime - Get the modification time in UTC /*{{{*/
  241. // ---------------------------------------------------------------------
  242. /* */
  243. bool RSHConn::ModTime(const char *Path, time_t &Time)
  244. {
  245. Time = time(&Time);
  246. // Query the mod time
  247. std::string Msg;
  248. if (WriteMsg(Msg,true,"TZ=UTC find %s -follow -printf '%%TY%%Tm%%Td%%TH%%TM%%TS\\n'",Path) == false)
  249. return false;
  250. // Parse it
  251. return FTPMDTMStrToTime(Msg.c_str(), Time);
  252. }
  253. /*}}}*/
  254. // RSHConn::Get - Get a file /*{{{*/
  255. // ---------------------------------------------------------------------
  256. /* */
  257. bool RSHConn::Get(const char *Path,FileFd &To,unsigned long long Resume,
  258. Hashes &Hash,bool &Missing, unsigned long long Size)
  259. {
  260. Missing = false;
  261. // Round to a 2048 byte block
  262. Resume = Resume - (Resume % 2048);
  263. if (To.Truncate(Resume) == false)
  264. return false;
  265. if (To.Seek(0) == false)
  266. return false;
  267. if (Resume != 0) {
  268. if (Hash.AddFD(To.Fd(),Resume) == false) {
  269. _error->Errno("read",_("Problem hashing file"));
  270. return false;
  271. }
  272. }
  273. // FIXME: Detect file-not openable type errors.
  274. std::string Jnk;
  275. if (WriteMsg(Jnk,false,"dd if=%s bs=2048 skip=%u", Path, Resume / 2048) == false)
  276. return false;
  277. // Copy loop
  278. unsigned long long MyLen = Resume;
  279. unsigned char Buffer[4096];
  280. while (MyLen < Size)
  281. {
  282. // Wait for some data..
  283. if (WaitFd(ReadFd,false,TimeOut) == false)
  284. {
  285. Close();
  286. return _error->Error(_("Data socket timed out"));
  287. }
  288. // Read the data..
  289. int Res = read(ReadFd,Buffer,sizeof(Buffer));
  290. if (Res == 0)
  291. {
  292. Close();
  293. return _error->Error(_("Connection closed prematurely"));
  294. }
  295. if (Res < 0)
  296. {
  297. if (errno == EAGAIN)
  298. continue;
  299. break;
  300. }
  301. MyLen += Res;
  302. Hash.Add(Buffer,Res);
  303. if (To.Write(Buffer,Res) == false)
  304. {
  305. Close();
  306. return false;
  307. }
  308. }
  309. return true;
  310. }
  311. /*}}}*/
  312. // RSHMethod::RSHMethod - Constructor /*{{{*/
  313. // ---------------------------------------------------------------------
  314. /* */
  315. RSHMethod::RSHMethod() : pkgAcqMethod("1.0",SendConfig)
  316. {
  317. signal(SIGTERM,SigTerm);
  318. signal(SIGINT,SigTerm);
  319. Server = 0;
  320. FailFd = -1;
  321. };
  322. /*}}}*/
  323. // RSHMethod::Configuration - Handle a configuration message /*{{{*/
  324. // ---------------------------------------------------------------------
  325. bool RSHMethod::Configuration(std::string Message)
  326. {
  327. char ProgStr[100];
  328. if (pkgAcqMethod::Configuration(Message) == false)
  329. return false;
  330. snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Timeout", Prog);
  331. TimeOut = _config->FindI(ProgStr,TimeOut);
  332. snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Options", Prog);
  333. RshOptions = _config->Tree(ProgStr);
  334. return true;
  335. }
  336. /*}}}*/
  337. // RSHMethod::SigTerm - Clean up and timestamp the files on exit /*{{{*/
  338. // ---------------------------------------------------------------------
  339. /* */
  340. void RSHMethod::SigTerm(int sig)
  341. {
  342. if (FailFd == -1)
  343. _exit(100);
  344. close(FailFd);
  345. // Timestamp
  346. struct utimbuf UBuf;
  347. UBuf.actime = FailTime;
  348. UBuf.modtime = FailTime;
  349. utime(FailFile.c_str(),&UBuf);
  350. _exit(100);
  351. }
  352. /*}}}*/
  353. // RSHMethod::Fetch - Fetch a URI /*{{{*/
  354. // ---------------------------------------------------------------------
  355. /* */
  356. bool RSHMethod::Fetch(FetchItem *Itm)
  357. {
  358. URI Get = Itm->Uri;
  359. const char *File = Get.Path.c_str();
  360. FetchResult Res;
  361. Res.Filename = Itm->DestFile;
  362. Res.IMSHit = false;
  363. // Connect to the server
  364. if (Server == 0 || Server->Comp(Get) == false) {
  365. delete Server;
  366. Server = new RSHConn(Get);
  367. }
  368. // Could not connect is a transient error..
  369. if (Server->Open() == false) {
  370. Server->Close();
  371. Fail(true);
  372. return true;
  373. }
  374. // We say this mainly because the pause here is for the
  375. // ssh connection that is still going
  376. Status(_("Connecting to %s"), Get.Host.c_str());
  377. // Get the files information
  378. unsigned long long Size;
  379. if (Server->Size(File,Size) == false ||
  380. Server->ModTime(File,FailTime) == false)
  381. {
  382. //Fail(true);
  383. //_error->Error(_("File not found")); // Will be handled by Size
  384. return false;
  385. }
  386. Res.Size = Size;
  387. // See if it is an IMS hit
  388. if (Itm->LastModified == FailTime) {
  389. Res.Size = 0;
  390. Res.IMSHit = true;
  391. URIDone(Res);
  392. return true;
  393. }
  394. // See if the file exists
  395. struct stat Buf;
  396. if (stat(Itm->DestFile.c_str(),&Buf) == 0) {
  397. if (Size == (unsigned long long)Buf.st_size && FailTime == Buf.st_mtime) {
  398. Res.Size = Buf.st_size;
  399. Res.LastModified = Buf.st_mtime;
  400. Res.ResumePoint = Buf.st_size;
  401. URIDone(Res);
  402. return true;
  403. }
  404. // Resume?
  405. if (FailTime == Buf.st_mtime && Size > (unsigned long long)Buf.st_size)
  406. Res.ResumePoint = Buf.st_size;
  407. }
  408. // Open the file
  409. Hashes Hash;
  410. {
  411. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  412. if (_error->PendingError() == true)
  413. return false;
  414. URIStart(Res);
  415. FailFile = Itm->DestFile;
  416. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  417. FailFd = Fd.Fd();
  418. bool Missing;
  419. if (Server->Get(File,Fd,Res.ResumePoint,Hash,Missing,Res.Size) == false)
  420. {
  421. Fd.Close();
  422. // Timestamp
  423. struct utimbuf UBuf;
  424. UBuf.actime = FailTime;
  425. UBuf.modtime = FailTime;
  426. utime(FailFile.c_str(),&UBuf);
  427. // If the file is missing we hard fail otherwise transient fail
  428. if (Missing == true)
  429. return false;
  430. Fail(true);
  431. return true;
  432. }
  433. Res.Size = Fd.Size();
  434. }
  435. Res.LastModified = FailTime;
  436. Res.TakeHashes(Hash);
  437. // Timestamp
  438. struct utimbuf UBuf;
  439. UBuf.actime = FailTime;
  440. UBuf.modtime = FailTime;
  441. utime(Queue->DestFile.c_str(),&UBuf);
  442. FailFd = -1;
  443. URIDone(Res);
  444. return true;
  445. }
  446. /*}}}*/
  447. int main(int argc, const char *argv[])
  448. {
  449. setlocale(LC_ALL, "");
  450. RSHMethod Mth;
  451. Prog = strrchr(argv[0],'/');
  452. Prog++;
  453. return Mth.Run();
  454. }