rsh.cc 13 KB

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