rsh.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 <sys/stat.h>
  14. #include <sys/time.h>
  15. #include <utime.h>
  16. #include <unistd.h>
  17. #include <signal.h>
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #include <stdarg.h>
  21. #include "rsh.h"
  22. #include <apti18n.h>
  23. /*}}}*/
  24. const char *Prog;
  25. unsigned long TimeOut = 120;
  26. Configuration::Item const *RshOptions = 0;
  27. time_t RSHMethod::FailTime = 0;
  28. std::string RSHMethod::FailFile;
  29. int RSHMethod::FailFd = -1;
  30. // RSHConn::RSHConn - Constructor /*{{{*/
  31. // ---------------------------------------------------------------------
  32. /* */
  33. RSHConn::RSHConn(URI Srv) : Len(0), WriteFd(-1), ReadFd(-1),
  34. ServerName(Srv), Process(-1) {}
  35. /*}}}*/
  36. // RSHConn::RSHConn - Destructor /*{{{*/
  37. // ---------------------------------------------------------------------
  38. /* */
  39. RSHConn::~RSHConn()
  40. {
  41. Close();
  42. }
  43. /*}}}*/
  44. // RSHConn::Close - Forcibly terminate the connection /*{{{*/
  45. // ---------------------------------------------------------------------
  46. /* Often this is called when things have gone wrong to indicate that the
  47. connection is no longer usable. */
  48. void RSHConn::Close()
  49. {
  50. if (Process == -1)
  51. return;
  52. close(WriteFd);
  53. close(ReadFd);
  54. kill(Process,SIGINT);
  55. ExecWait(Process,"",true);
  56. WriteFd = -1;
  57. ReadFd = -1;
  58. Process = -1;
  59. }
  60. /*}}}*/
  61. // RSHConn::Open - Connect to a host /*{{{*/
  62. // ---------------------------------------------------------------------
  63. /* */
  64. bool RSHConn::Open()
  65. {
  66. // Use the already open connection if possible.
  67. if (Process != -1)
  68. return true;
  69. if (Connect(ServerName.Host,ServerName.User) == false)
  70. return false;
  71. return true;
  72. }
  73. /*}}}*/
  74. // RSHConn::Connect - Fire up rsh and connect /*{{{*/
  75. // ---------------------------------------------------------------------
  76. /* */
  77. bool RSHConn::Connect(std::string Host, std::string User)
  78. {
  79. // Create the pipes
  80. int Pipes[4] = {-1,-1,-1,-1};
  81. if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
  82. {
  83. _error->Errno("pipe",_("Failed to create IPC pipe to subprocess"));
  84. for (int I = 0; I != 4; I++)
  85. close(Pipes[I]);
  86. return false;
  87. }
  88. for (int I = 0; I != 4; I++)
  89. SetCloseExec(Pipes[I],true);
  90. Process = ExecFork();
  91. // The child
  92. if (Process == 0)
  93. {
  94. const char *Args[400];
  95. unsigned int i = 0;
  96. dup2(Pipes[1],STDOUT_FILENO);
  97. dup2(Pipes[2],STDIN_FILENO);
  98. // Probably should do
  99. // dup2(open("/dev/null",O_RDONLY),STDERR_FILENO);
  100. Args[i++] = Prog;
  101. // Insert user-supplied command line options
  102. Configuration::Item const *Opts = RshOptions;
  103. if (Opts != 0)
  104. {
  105. Opts = Opts->Child;
  106. for (; Opts != 0; Opts = Opts->Next)
  107. {
  108. if (Opts->Value.empty() == true)
  109. continue;
  110. Args[i++] = Opts->Value.c_str();
  111. }
  112. }
  113. if (User.empty() == false) {
  114. Args[i++] = "-l";
  115. Args[i++] = User.c_str();
  116. }
  117. if (Host.empty() == false) {
  118. Args[i++] = Host.c_str();
  119. }
  120. Args[i++] = "/bin/sh";
  121. Args[i] = 0;
  122. execvp(Args[0],(char **)Args);
  123. exit(100);
  124. }
  125. ReadFd = Pipes[0];
  126. WriteFd = Pipes[3];
  127. SetNonBlock(Pipes[0],true);
  128. SetNonBlock(Pipes[3],true);
  129. close(Pipes[1]);
  130. close(Pipes[2]);
  131. return true;
  132. }
  133. /*}}}*/
  134. // RSHConn::ReadLine - Very simple buffered read with timeout /*{{{*/
  135. // ---------------------------------------------------------------------
  136. /* */
  137. bool RSHConn::ReadLine(std::string &Text)
  138. {
  139. if (Process == -1 || ReadFd == -1)
  140. return false;
  141. // Suck in a line
  142. while (Len < sizeof(Buffer))
  143. {
  144. // Scan the buffer for a new line
  145. for (unsigned int I = 0; I != Len; I++)
  146. {
  147. // Escape some special chars
  148. if (Buffer[I] == 0)
  149. Buffer[I] = '?';
  150. // End of line?
  151. if (Buffer[I] != '\n')
  152. continue;
  153. I++;
  154. Text = std::string(Buffer,I);
  155. memmove(Buffer,Buffer+I,Len - I);
  156. Len -= I;
  157. return true;
  158. }
  159. // Wait for some data..
  160. if (WaitFd(ReadFd,false,TimeOut) == false)
  161. {
  162. Close();
  163. return _error->Error(_("Connection timeout"));
  164. }
  165. // Suck it back
  166. int Res = read(ReadFd,Buffer + Len,sizeof(Buffer) - Len);
  167. if (Res <= 0)
  168. {
  169. _error->Errno("read",_("Read error"));
  170. Close();
  171. return false;
  172. }
  173. Len += Res;
  174. }
  175. return _error->Error(_("A response overflowed the buffer."));
  176. }
  177. /*}}}*/
  178. // RSHConn::WriteMsg - Send a message with optional remote sync. /*{{{*/
  179. // ---------------------------------------------------------------------
  180. /* The remote sync flag appends a || echo which will insert blank line
  181. once the command completes. */
  182. bool RSHConn::WriteMsg(std::string &Text,bool Sync,const char *Fmt,...)
  183. {
  184. va_list args;
  185. va_start(args,Fmt);
  186. // sprintf the description
  187. char S[512];
  188. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  189. if (Sync == true)
  190. strcat(S," 2> /dev/null || echo\n");
  191. else
  192. strcat(S," 2> /dev/null\n");
  193. // Send it off
  194. unsigned long Len = strlen(S);
  195. unsigned long Start = 0;
  196. while (Len != 0)
  197. {
  198. if (WaitFd(WriteFd,true,TimeOut) == false)
  199. {
  200. Close();
  201. return _error->Error(_("Connection timeout"));
  202. }
  203. int Res = write(WriteFd,S + Start,Len);
  204. if (Res <= 0)
  205. {
  206. _error->Errno("write",_("Write error"));
  207. Close();
  208. return false;
  209. }
  210. Len -= Res;
  211. Start += Res;
  212. }
  213. if (Sync == true)
  214. return ReadLine(Text);
  215. return true;
  216. }
  217. /*}}}*/
  218. // RSHConn::Size - Return the size of the file /*{{{*/
  219. // ---------------------------------------------------------------------
  220. /* Right now for successfull transfer the file size must be known in
  221. advance. */
  222. bool RSHConn::Size(const char *Path,unsigned long long &Size)
  223. {
  224. // Query the size
  225. std::string Msg;
  226. Size = 0;
  227. if (WriteMsg(Msg,true,"find %s -follow -printf '%%s\\n'",Path) == false)
  228. return false;
  229. // FIXME: Sense if the bad reply is due to a File Not Found.
  230. char *End;
  231. Size = strtoull(Msg.c_str(),&End,10);
  232. if (End == Msg.c_str())
  233. return _error->Error(_("File not found"));
  234. return true;
  235. }
  236. /*}}}*/
  237. // RSHConn::ModTime - Get the modification time in UTC /*{{{*/
  238. // ---------------------------------------------------------------------
  239. /* */
  240. bool RSHConn::ModTime(const char *Path, time_t &Time)
  241. {
  242. Time = time(&Time);
  243. // Query the mod time
  244. std::string Msg;
  245. if (WriteMsg(Msg,true,"TZ=UTC find %s -follow -printf '%%TY%%Tm%%Td%%TH%%TM%%TS\\n'",Path) == false)
  246. return false;
  247. // Parse it
  248. return FTPMDTMStrToTime(Msg.c_str(), Time);
  249. }
  250. /*}}}*/
  251. // RSHConn::Get - Get a file /*{{{*/
  252. // ---------------------------------------------------------------------
  253. /* */
  254. bool RSHConn::Get(const char *Path,FileFd &To,unsigned long long Resume,
  255. Hashes &Hash,bool &Missing, unsigned long 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. std::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 long long 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(std::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 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 long long)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 long long)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. setlocale(LC_ALL, "");
  447. RSHMethod Mth;
  448. Prog = strrchr(argv[0],'/');
  449. Prog++;
  450. return Mth.Run();
  451. }