rsh.cc 14 KB

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