rsh.cc 13 KB

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