rsh.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 the description
  195. char S[512];
  196. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  197. va_end(args);
  198. if (Sync == true)
  199. strcat(S," 2> /dev/null || echo\n");
  200. else
  201. strcat(S," 2> /dev/null\n");
  202. // Send it off
  203. unsigned long Len = strlen(S);
  204. unsigned long Start = 0;
  205. while (Len != 0)
  206. {
  207. if (WaitFd(WriteFd,true,TimeOut) == false)
  208. {
  209. Close();
  210. return _error->Error(_("Connection timeout"));
  211. }
  212. int Res = write(WriteFd,S + Start,Len);
  213. if (Res <= 0)
  214. {
  215. _error->Errno("write",_("Write error"));
  216. Close();
  217. return false;
  218. }
  219. Len -= Res;
  220. Start += Res;
  221. }
  222. if (Sync == true)
  223. return ReadLine(Text);
  224. return true;
  225. }
  226. /*}}}*/
  227. // RSHConn::Size - Return the size of the file /*{{{*/
  228. // ---------------------------------------------------------------------
  229. /* Right now for successful transfer the file size must be known in
  230. advance. */
  231. bool RSHConn::Size(const char *Path,unsigned long long &Size)
  232. {
  233. // Query the size
  234. std::string Msg;
  235. Size = 0;
  236. if (WriteMsg(Msg,true,"find %s -follow -printf '%%s\\n'",Path) == false)
  237. return false;
  238. // FIXME: Sense if the bad reply is due to a File Not Found.
  239. char *End;
  240. Size = strtoull(Msg.c_str(),&End,10);
  241. if (End == Msg.c_str())
  242. return _error->Error(_("File not found"));
  243. return true;
  244. }
  245. /*}}}*/
  246. // RSHConn::ModTime - Get the modification time in UTC /*{{{*/
  247. // ---------------------------------------------------------------------
  248. /* */
  249. bool RSHConn::ModTime(const char *Path, time_t &Time)
  250. {
  251. Time = time(&Time);
  252. // Query the mod time
  253. std::string Msg;
  254. if (WriteMsg(Msg,true,"TZ=UTC find %s -follow -printf '%%TY%%Tm%%Td%%TH%%TM%%TS\\n'",Path) == false)
  255. return false;
  256. // Parse it
  257. return FTPMDTMStrToTime(Msg.c_str(), Time);
  258. }
  259. /*}}}*/
  260. // RSHConn::Get - Get a file /*{{{*/
  261. // ---------------------------------------------------------------------
  262. /* */
  263. bool RSHConn::Get(const char *Path,FileFd &To,unsigned long long Resume,
  264. Hashes &Hash,bool &Missing, unsigned long long Size)
  265. {
  266. Missing = false;
  267. // Round to a 2048 byte block
  268. Resume = Resume - (Resume % 2048);
  269. if (To.Truncate(Resume) == false)
  270. return false;
  271. if (To.Seek(0) == false)
  272. return false;
  273. if (Resume != 0) {
  274. if (Hash.AddFD(To,Resume) == false) {
  275. _error->Errno("read",_("Problem hashing file"));
  276. return false;
  277. }
  278. }
  279. // FIXME: Detect file-not openable type errors.
  280. std::string Jnk;
  281. if (WriteMsg(Jnk,false,"dd if=%s bs=2048 skip=%u", Path, Resume / 2048) == false)
  282. return false;
  283. // Copy loop
  284. unsigned long long MyLen = Resume;
  285. unsigned char Buffer[4096];
  286. while (MyLen < Size)
  287. {
  288. // Wait for some data..
  289. if (WaitFd(ReadFd,false,TimeOut) == false)
  290. {
  291. Close();
  292. return _error->Error(_("Data socket timed out"));
  293. }
  294. // Read the data..
  295. int Res = read(ReadFd,Buffer,sizeof(Buffer));
  296. if (Res == 0)
  297. {
  298. Close();
  299. return _error->Error(_("Connection closed prematurely"));
  300. }
  301. if (Res < 0)
  302. {
  303. if (errno == EAGAIN)
  304. continue;
  305. break;
  306. }
  307. MyLen += Res;
  308. Hash.Add(Buffer,Res);
  309. if (To.Write(Buffer,Res) == false)
  310. {
  311. Close();
  312. return false;
  313. }
  314. }
  315. return true;
  316. }
  317. /*}}}*/
  318. // RSHMethod::RSHMethod - Constructor /*{{{*/
  319. // ---------------------------------------------------------------------
  320. /* */
  321. RSHMethod::RSHMethod() : pkgAcqMethod("1.0",SendConfig)
  322. {
  323. signal(SIGTERM,SigTerm);
  324. signal(SIGINT,SigTerm);
  325. Server = 0;
  326. FailFd = -1;
  327. }
  328. /*}}}*/
  329. // RSHMethod::Configuration - Handle a configuration message /*{{{*/
  330. // ---------------------------------------------------------------------
  331. bool RSHMethod::Configuration(std::string Message)
  332. {
  333. char ProgStr[100];
  334. if (pkgAcqMethod::Configuration(Message) == false)
  335. return false;
  336. snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Timeout", Prog);
  337. TimeOut = _config->FindI(ProgStr,TimeOut);
  338. snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Options", Prog);
  339. RshOptions = _config->Tree(ProgStr);
  340. return true;
  341. }
  342. /*}}}*/
  343. // RSHMethod::SigTerm - Clean up and timestamp the files on exit /*{{{*/
  344. // ---------------------------------------------------------------------
  345. /* */
  346. void RSHMethod::SigTerm(int)
  347. {
  348. if (FailFd == -1)
  349. _exit(100);
  350. // Transfer the modification times
  351. struct timeval times[2];
  352. times[0].tv_sec = FailTime;
  353. times[1].tv_sec = FailTime;
  354. times[0].tv_usec = times[1].tv_usec = 0;
  355. utimes(FailFile.c_str(), times);
  356. close(FailFd);
  357. _exit(100);
  358. }
  359. /*}}}*/
  360. // RSHMethod::Fetch - Fetch a URI /*{{{*/
  361. // ---------------------------------------------------------------------
  362. /* */
  363. bool RSHMethod::Fetch(FetchItem *Itm)
  364. {
  365. URI Get = Itm->Uri;
  366. const char *File = Get.Path.c_str();
  367. FetchResult Res;
  368. Res.Filename = Itm->DestFile;
  369. Res.IMSHit = false;
  370. // Connect to the server
  371. if (Server == 0 || Server->Comp(Get) == false) {
  372. delete Server;
  373. Server = new RSHConn(Get);
  374. }
  375. // Could not connect is a transient error..
  376. if (Server->Open() == false) {
  377. Server->Close();
  378. Fail(true);
  379. return true;
  380. }
  381. // We say this mainly because the pause here is for the
  382. // ssh connection that is still going
  383. Status(_("Connecting to %s"), Get.Host.c_str());
  384. // Get the files information
  385. unsigned long long Size;
  386. if (Server->Size(File,Size) == false ||
  387. Server->ModTime(File,FailTime) == false)
  388. {
  389. //Fail(true);
  390. //_error->Error(_("File not found")); // Will be handled by Size
  391. return false;
  392. }
  393. Res.Size = Size;
  394. // See if it is an IMS hit
  395. if (Itm->LastModified == FailTime) {
  396. Res.Size = 0;
  397. Res.IMSHit = true;
  398. URIDone(Res);
  399. return true;
  400. }
  401. // See if the file exists
  402. struct stat Buf;
  403. if (stat(Itm->DestFile.c_str(),&Buf) == 0) {
  404. if (Size == (unsigned long long)Buf.st_size && FailTime == Buf.st_mtime) {
  405. Res.Size = Buf.st_size;
  406. Res.LastModified = Buf.st_mtime;
  407. Res.ResumePoint = Buf.st_size;
  408. URIDone(Res);
  409. return true;
  410. }
  411. // Resume?
  412. if (FailTime == Buf.st_mtime && Size > (unsigned long long)Buf.st_size)
  413. Res.ResumePoint = Buf.st_size;
  414. }
  415. // Open the file
  416. Hashes Hash;
  417. {
  418. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  419. if (_error->PendingError() == true)
  420. return false;
  421. URIStart(Res);
  422. FailFile = Itm->DestFile;
  423. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  424. FailFd = Fd.Fd();
  425. bool Missing;
  426. if (Server->Get(File,Fd,Res.ResumePoint,Hash,Missing,Res.Size) == false)
  427. {
  428. Fd.Close();
  429. // Timestamp
  430. struct timeval times[2];
  431. times[0].tv_sec = FailTime;
  432. times[1].tv_sec = FailTime;
  433. times[0].tv_usec = times[1].tv_usec = 0;
  434. utimes(FailFile.c_str(), times);
  435. // If the file is missing we hard fail otherwise transient fail
  436. if (Missing == true)
  437. return false;
  438. Fail(true);
  439. return true;
  440. }
  441. Res.Size = Fd.Size();
  442. struct timeval times[2];
  443. times[0].tv_sec = FailTime;
  444. times[1].tv_sec = FailTime;
  445. times[0].tv_usec = times[1].tv_usec = 0;
  446. utimes(Fd.Name().c_str(), times);
  447. FailFd = -1;
  448. }
  449. Res.LastModified = FailTime;
  450. Res.TakeHashes(Hash);
  451. URIDone(Res);
  452. return true;
  453. }
  454. /*}}}*/
  455. int main(int, const char *argv[])
  456. {
  457. setlocale(LC_ALL, "");
  458. RSHMethod Mth;
  459. Prog = strrchr(argv[0],'/');
  460. Prog++;
  461. return Mth.Run();
  462. }