rsh.cc 13 KB

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