rsh.cc 13 KB

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