ftp.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.19 2000/01/10 03:44:54 jgg Exp $
  4. /* ######################################################################
  5. HTTP Aquire Method - This is the FTP aquire method for APT.
  6. This is a very simple implementation that does not try to optimize
  7. at all. Commands are sent syncronously with the FTP server (as the
  8. rfc recommends, but it is not really necessary..) and no tricks are
  9. done to speed things along.
  10. RFC 2428 describes the IPv6 FTP behavior
  11. ##################################################################### */
  12. /*}}}*/
  13. // Include Files /*{{{*/
  14. #include <apt-pkg/fileutl.h>
  15. #include <apt-pkg/acquire-method.h>
  16. #include <apt-pkg/error.h>
  17. #include <apt-pkg/md5.h>
  18. #include <sys/stat.h>
  19. #include <sys/time.h>
  20. #include <utime.h>
  21. #include <unistd.h>
  22. #include <signal.h>
  23. #include <stdio.h>
  24. #include <errno.h>
  25. #include <stdarg.h>
  26. // Internet stuff
  27. #include <netinet/in.h>
  28. #include <sys/socket.h>
  29. #include <arpa/inet.h>
  30. #include <netdb.h>
  31. #include "rfc2553emu.h"
  32. #include "connect.h"
  33. #include "ftp.h"
  34. /*}}}*/
  35. unsigned long TimeOut = 120;
  36. URI Proxy;
  37. string FtpMethod::FailFile;
  38. int FtpMethod::FailFd = -1;
  39. time_t FtpMethod::FailTime = 0;
  40. // FTPConn::FTPConn - Constructor /*{{{*/
  41. // ---------------------------------------------------------------------
  42. /* */
  43. FTPConn::FTPConn(URI Srv) : Len(0), ServerFd(-1), DataFd(-1),
  44. DataListenFd(-1), ServerName(Srv)
  45. {
  46. Debug = _config->FindB("Debug::Acquire::Ftp",false);
  47. memset(&PasvAddr,0,sizeof(PasvAddr));
  48. }
  49. /*}}}*/
  50. // FTPConn::~FTPConn - Destructor /*{{{*/
  51. // ---------------------------------------------------------------------
  52. /* */
  53. FTPConn::~FTPConn()
  54. {
  55. Close();
  56. }
  57. /*}}}*/
  58. // FTPConn::Close - Close down the connection /*{{{*/
  59. // ---------------------------------------------------------------------
  60. /* Just tear down the socket and data socket */
  61. void FTPConn::Close()
  62. {
  63. close(ServerFd);
  64. ServerFd = -1;
  65. close(DataFd);
  66. DataFd = -1;
  67. close(DataListenFd);
  68. DataListenFd = -1;
  69. memset(&PasvAddr,0,sizeof(PasvAddr));
  70. }
  71. /*}}}*/
  72. // FTPConn::Open - Open a new connection /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* Connect to the server using a non-blocking connection and perform a
  75. login. */
  76. bool FTPConn::Open(pkgAcqMethod *Owner)
  77. {
  78. // Use the already open connection if possible.
  79. if (ServerFd != -1)
  80. return true;
  81. Close();
  82. // Determine the proxy setting
  83. if (getenv("ftp_proxy") == 0)
  84. {
  85. string DefProxy = _config->Find("Acquire::ftp::Proxy");
  86. string SpecificProxy = _config->Find("Acquire::ftp::Proxy::" + ServerName.Host);
  87. if (SpecificProxy.empty() == false)
  88. {
  89. if (SpecificProxy == "DIRECT")
  90. Proxy = "";
  91. else
  92. Proxy = SpecificProxy;
  93. }
  94. else
  95. Proxy = DefProxy;
  96. }
  97. else
  98. Proxy = getenv("ftp_proxy");
  99. // Determine what host and port to use based on the proxy settings
  100. int Port = 0;
  101. string Host;
  102. if (Proxy.empty() == true)
  103. {
  104. if (ServerName.Port != 0)
  105. Port = ServerName.Port;
  106. Host = ServerName.Host;
  107. }
  108. else
  109. {
  110. if (Proxy.Port != 0)
  111. Port = Proxy.Port;
  112. Host = Proxy.Host;
  113. }
  114. // Connect to the remote server
  115. if (Connect(Host,Port,"ftp",21,ServerFd,TimeOut,Owner) == false)
  116. return false;
  117. socklen_t Len = sizeof(Peer);
  118. if (getpeername(ServerFd,(sockaddr *)&Peer,&Len) != 0)
  119. return _error->Errno("getpeername","Unable to determine the peer name");
  120. Owner->Status("Logging in");
  121. return Login();
  122. }
  123. /*}}}*/
  124. // FTPConn::Login - Login to the remote server /*{{{*/
  125. // ---------------------------------------------------------------------
  126. /* This performs both normal login and proxy login using a simples script
  127. stored in the config file. */
  128. bool FTPConn::Login()
  129. {
  130. unsigned int Tag;
  131. string Msg;
  132. // Setup the variables needed for authentication
  133. string User = "anonymous";
  134. string Pass = "apt_get_ftp_2.0@debian.linux.user";
  135. // Fill in the user/pass
  136. if (ServerName.User.empty() == false)
  137. User = ServerName.User;
  138. if (ServerName.Password.empty() == false)
  139. Pass = ServerName.Password;
  140. // Perform simple login
  141. if (Proxy.empty() == true)
  142. {
  143. // Read the initial response
  144. if (ReadResp(Tag,Msg) == false)
  145. return false;
  146. if (Tag >= 400)
  147. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  148. // Send the user
  149. if (WriteMsg(Tag,Msg,"USER %s",User.c_str()) == false)
  150. return false;
  151. if (Tag >= 400)
  152. return _error->Error("USER failed, server said: %s",Msg.c_str());
  153. // Send the Password
  154. if (WriteMsg(Tag,Msg,"PASS %s",Pass.c_str()) == false)
  155. return false;
  156. if (Tag >= 400)
  157. return _error->Error("PASS failed, server said: %s",Msg.c_str());
  158. // Enter passive mode
  159. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  160. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  161. else
  162. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  163. }
  164. else
  165. {
  166. // Read the initial response
  167. if (ReadResp(Tag,Msg) == false)
  168. return false;
  169. if (Tag >= 400)
  170. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  171. // Perform proxy script execution
  172. Configuration::Item const *Opts = _config->Tree("Acquire::ftp::ProxyLogin");
  173. if (Opts == 0 || Opts->Child == 0)
  174. return _error->Error("A proxy server was specified but no login "
  175. "script, Acquire::ftp::ProxyLogin is empty.");
  176. Opts = Opts->Child;
  177. // Iterate over the entire login script
  178. for (; Opts != 0; Opts = Opts->Next)
  179. {
  180. if (Opts->Value.empty() == true)
  181. continue;
  182. // Substitute the variables into the command
  183. char SitePort[20];
  184. if (ServerName.Port != 0)
  185. sprintf(SitePort,"%u",ServerName.Port);
  186. else
  187. strcpy(SitePort,"21");
  188. string Tmp = Opts->Value;
  189. Tmp = SubstVar(Tmp,"$(PROXY_USER)",Proxy.User);
  190. Tmp = SubstVar(Tmp,"$(PROXY_PASS)",Proxy.Password);
  191. Tmp = SubstVar(Tmp,"$(SITE_USER)",User);
  192. Tmp = SubstVar(Tmp,"$(SITE_PASS)",Pass);
  193. Tmp = SubstVar(Tmp,"$(SITE_PORT)",SitePort);
  194. Tmp = SubstVar(Tmp,"$(SITE)",ServerName.Host);
  195. // Send the command
  196. if (WriteMsg(Tag,Msg,"%s",Tmp.c_str()) == false)
  197. return false;
  198. if (Tag >= 400)
  199. return _error->Error("Login script command '%s' failed, server said: %s",Tmp.c_str(),Msg.c_str());
  200. }
  201. // Enter passive mode
  202. TryPassive = false;
  203. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  204. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  205. else
  206. {
  207. if (_config->Exists("Acquire::FTP::Proxy::Passive") == true)
  208. TryPassive = _config->FindB("Acquire::FTP::Proxy::Passive",true);
  209. else
  210. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  211. }
  212. }
  213. // Binary mode
  214. if (WriteMsg(Tag,Msg,"TYPE I") == false)
  215. return false;
  216. if (Tag >= 400)
  217. return _error->Error("TYPE failed, server said: %s",Msg.c_str());
  218. return true;
  219. }
  220. /*}}}*/
  221. // FTPConn::ReadLine - Read a line from the server /*{{{*/
  222. // ---------------------------------------------------------------------
  223. /* This performs a very simple buffered read. */
  224. bool FTPConn::ReadLine(string &Text)
  225. {
  226. if (ServerFd == -1)
  227. return false;
  228. // Suck in a line
  229. while (Len < sizeof(Buffer))
  230. {
  231. // Scan the buffer for a new line
  232. for (unsigned int I = 0; I != Len; I++)
  233. {
  234. // Escape some special chars
  235. if (Buffer[I] == 0)
  236. Buffer[I] = '?';
  237. // End of line?
  238. if (Buffer[I] != '\n')
  239. continue;
  240. I++;
  241. Text = string(Buffer,I);
  242. memmove(Buffer,Buffer+I,Len - I);
  243. Len -= I;
  244. return true;
  245. }
  246. // Wait for some data..
  247. if (WaitFd(ServerFd,false,TimeOut) == false)
  248. {
  249. Close();
  250. return _error->Error("Connection timeout");
  251. }
  252. // Suck it back
  253. int Res = read(ServerFd,Buffer + Len,sizeof(Buffer) - Len);
  254. if (Res <= 0)
  255. {
  256. _error->Errno("read","Read error");
  257. Close();
  258. return false;
  259. }
  260. Len += Res;
  261. }
  262. return _error->Error("A response overflowed the buffer.");
  263. }
  264. /*}}}*/
  265. // FTPConn::ReadResp - Read a full response from the server /*{{{*/
  266. // ---------------------------------------------------------------------
  267. /* This reads a reply code from the server, it handles both p */
  268. bool FTPConn::ReadResp(unsigned int &Ret,string &Text)
  269. {
  270. // Grab the first line of the response
  271. string Msg;
  272. if (ReadLine(Msg) == false)
  273. return false;
  274. // Get the ID code
  275. char *End;
  276. Ret = strtol(Msg.c_str(),&End,10);
  277. if (End - Msg.c_str() != 3)
  278. return _error->Error("Protocol corruption");
  279. // All done ?
  280. Text = Msg.c_str()+4;
  281. if (*End == ' ')
  282. {
  283. if (Debug == true)
  284. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  285. return true;
  286. }
  287. if (*End != '-')
  288. return _error->Error("Protocol corruption");
  289. /* Okay, here we do the continued message trick. This is foolish, but
  290. proftpd follows the protocol as specified and wu-ftpd doesn't, so
  291. we filter. I wonder how many clients break if you use proftpd and
  292. put a '- in the 3rd spot in the message? */
  293. char Leader[4];
  294. strncpy(Leader,Msg.c_str(),3);
  295. Leader[3] = 0;
  296. while (ReadLine(Msg) == true)
  297. {
  298. // Short, it must be using RFC continuation..
  299. if (Msg.length() < 4)
  300. {
  301. Text += Msg;
  302. continue;
  303. }
  304. // Oops, finished
  305. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == ' ')
  306. {
  307. Text += Msg.c_str()+4;
  308. break;
  309. }
  310. // This message has the wu-ftpd style reply code prefixed
  311. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == '-')
  312. {
  313. Text += Msg.c_str()+4;
  314. continue;
  315. }
  316. // Must be RFC style prefixing
  317. Text += Msg;
  318. }
  319. if (Debug == true && _error->PendingError() == false)
  320. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  321. return !_error->PendingError();
  322. }
  323. /*}}}*/
  324. // FTPConn::WriteMsg - Send a message to the server /*{{{*/
  325. // ---------------------------------------------------------------------
  326. /* Simple printf like function.. */
  327. bool FTPConn::WriteMsg(unsigned int &Ret,string &Text,const char *Fmt,...)
  328. {
  329. va_list args;
  330. va_start(args,Fmt);
  331. // sprintf the description
  332. char S[400];
  333. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  334. strcat(S,"\r\n");
  335. if (Debug == true)
  336. cerr << "-> '" << QuoteString(S,"") << "'" << endl;
  337. // Send it off
  338. unsigned long Len = strlen(S);
  339. unsigned long Start = 0;
  340. while (Len != 0)
  341. {
  342. if (WaitFd(ServerFd,true,TimeOut) == false)
  343. {
  344. Close();
  345. return _error->Error("Connection timeout");
  346. }
  347. int Res = write(ServerFd,S + Start,Len);
  348. if (Res <= 0)
  349. {
  350. _error->Errno("write","Write Error");
  351. Close();
  352. return false;
  353. }
  354. Len -= Res;
  355. Start += Res;
  356. }
  357. return ReadResp(Ret,Text);
  358. }
  359. /*}}}*/
  360. // FTPConn::GoPasv - Enter Passive mode /*{{{*/
  361. // ---------------------------------------------------------------------
  362. /* Try to enter passive mode, the return code does not indicate if passive
  363. mode could or could not be established, only if there was a fatal error.
  364. Borrowed mostly from lftp. We have to enter passive mode every time
  365. we make a data connection :| */
  366. bool FTPConn::GoPasv()
  367. {
  368. // Try to enable pasv mode
  369. unsigned int Tag;
  370. string Msg;
  371. if (WriteMsg(Tag,Msg,"PASV") == false)
  372. return false;
  373. // Unsupported function
  374. string::size_type Pos = Msg.find('(');
  375. if (Tag >= 400 || Pos == string::npos)
  376. {
  377. memset(&PasvAddr,0,sizeof(PasvAddr));
  378. return true;
  379. }
  380. // Scan it
  381. unsigned a0,a1,a2,a3,p0,p1;
  382. if (sscanf(Msg.c_str() + Pos,"(%u,%u,%u,%u,%u,%u)",&a0,&a1,&a2,&a3,&p0,&p1) != 6)
  383. {
  384. memset(&PasvAddr,0,sizeof(PasvAddr));
  385. return true;
  386. }
  387. // lftp used this horrid byte order manipulation.. Ik.
  388. PasvAddr.sin_family = AF_INET;
  389. unsigned char *a;
  390. unsigned char *p;
  391. a = (unsigned char *)&PasvAddr.sin_addr;
  392. p = (unsigned char *)&PasvAddr.sin_port;
  393. // Some evil servers return 0 to mean their addr
  394. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  395. {
  396. PasvAddr.sin_addr = Peer.sin_addr;
  397. }
  398. else
  399. {
  400. a[0] = a0;
  401. a[1] = a1;
  402. a[2] = a2;
  403. a[3] = a3;
  404. }
  405. p[0] = p0;
  406. p[1] = p1;
  407. return true;
  408. }
  409. /*}}}*/
  410. // FTPConn::Size - Return the size of a file /*{{{*/
  411. // ---------------------------------------------------------------------
  412. /* Grab the file size from the server, 0 means no size or empty file */
  413. bool FTPConn::Size(const char *Path,unsigned long &Size)
  414. {
  415. // Query the size
  416. unsigned int Tag;
  417. string Msg;
  418. Size = 0;
  419. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  420. return false;
  421. char *End;
  422. Size = strtol(Msg.c_str(),&End,10);
  423. if (Tag >= 400 || End == Msg.c_str())
  424. Size = 0;
  425. return true;
  426. }
  427. /*}}}*/
  428. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  429. // ---------------------------------------------------------------------
  430. /* Like Size no error is returned if the command is not supported. If the
  431. command fails then time is set to the current time of day to fool
  432. date checks. */
  433. bool FTPConn::ModTime(const char *Path, time_t &Time)
  434. {
  435. Time = time(&Time);
  436. // Query the mod time
  437. unsigned int Tag;
  438. string Msg;
  439. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  440. return false;
  441. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  442. return true;
  443. // Parse it
  444. StrToTime(Msg,Time);
  445. return true;
  446. }
  447. /*}}}*/
  448. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  449. // ---------------------------------------------------------------------
  450. /* Create the data connection. Call FinalizeDataFd after this though.. */
  451. bool FTPConn::CreateDataFd()
  452. {
  453. close(DataFd);
  454. DataFd = -1;
  455. // Attempt to enter passive mode.
  456. if (TryPassive == true)
  457. {
  458. if (GoPasv() == false)
  459. return false;
  460. // Oops, didn't work out, don't bother trying again.
  461. if (PasvAddr.sin_port == 0)
  462. TryPassive = false;
  463. }
  464. // Passive mode?
  465. if (PasvAddr.sin_port != 0)
  466. {
  467. // Get a socket
  468. if ((DataFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  469. return _error->Errno("socket","Could not create a socket");
  470. // Connect to the server
  471. SetNonBlock(DataFd,true);
  472. if (connect(DataFd,(sockaddr *)&PasvAddr,sizeof(PasvAddr)) < 0 &&
  473. errno != EINPROGRESS)
  474. return _error->Errno("socket","Could not create a socket");
  475. /* This implements a timeout for connect by opening the connection
  476. nonblocking */
  477. if (WaitFd(ServerFd,true,TimeOut) == false)
  478. return _error->Error("Could not connect data socket, connection timed out");
  479. unsigned int Err;
  480. unsigned int Len = sizeof(Err);
  481. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  482. return _error->Errno("getsockopt","Failed");
  483. if (Err != 0)
  484. return _error->Error("Could not connect.");
  485. return true;
  486. }
  487. // Port mode :<
  488. close(DataListenFd);
  489. DataListenFd = -1;
  490. // Get a socket
  491. if ((DataListenFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  492. return _error->Errno("socket","Could not create a socket");
  493. // Bind and listen
  494. sockaddr_in Addr;
  495. memset(&Addr,0,sizeof(Addr));
  496. if (bind(DataListenFd,(sockaddr *)&Addr,sizeof(Addr)) < 0)
  497. return _error->Errno("bind","Could not bind a socket");
  498. if (listen(DataListenFd,1) < 0)
  499. return _error->Errno("listen","Could not listen on the socket");
  500. SetNonBlock(DataListenFd,true);
  501. // Determine the name to send to the remote
  502. sockaddr_in Addr2;
  503. socklen_t Jnk = sizeof(Addr);
  504. if (getsockname(DataListenFd,(sockaddr *)&Addr,&Jnk) < 0)
  505. return _error->Errno("getsockname","Could not determine the socket's name");
  506. Jnk = sizeof(Addr2);
  507. if (getsockname(ServerFd,(sockaddr *)&Addr2,&Jnk) < 0)
  508. return _error->Errno("getsockname","Could not determine the socket's name");
  509. // This bit ripped from qftp
  510. unsigned long badr = ntohl(*(unsigned long *)&Addr2.sin_addr);
  511. unsigned long bp = ntohs(Addr.sin_port);
  512. // Send the port command
  513. unsigned int Tag;
  514. string Msg;
  515. if (WriteMsg(Tag,Msg,"PORT %d,%d,%d,%d,%d,%d",
  516. (int) (badr >> 24) & 0xff, (int) (badr >> 16) & 0xff,
  517. (int) (badr >> 8) & 0xff, (int) badr & 0xff,
  518. (int) (bp >> 8) & 0xff, (int) bp & 0xff) == false)
  519. return false;
  520. if (Tag >= 400)
  521. return _error->Error("Unable to send port command");
  522. return true;
  523. }
  524. /*}}}*/
  525. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  526. // ---------------------------------------------------------------------
  527. /* If the connection is in port mode this waits for the other end to hook
  528. up to us. */
  529. bool FTPConn::Finalize()
  530. {
  531. // Passive mode? Do nothing
  532. if (PasvAddr.sin_port != 0)
  533. return true;
  534. // Close any old socket..
  535. close(DataFd);
  536. DataFd = -1;
  537. // Wait for someone to connect..
  538. if (WaitFd(DataListenFd,false,TimeOut) == false)
  539. return _error->Error("Data socket connect timed out");
  540. // Accept the connection
  541. struct sockaddr_in Addr;
  542. socklen_t Len = sizeof(Addr);
  543. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  544. if (DataFd < 0)
  545. return _error->Errno("accept","Unable to accept connection");
  546. close(DataListenFd);
  547. DataListenFd = -1;
  548. return true;
  549. }
  550. /*}}}*/
  551. // FTPConn::Get - Get a file /*{{{*/
  552. // ---------------------------------------------------------------------
  553. /* This opens a data connection, sends REST and RETR and then
  554. transfers the file over. */
  555. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume,
  556. MD5Summation &MD5,bool &Missing)
  557. {
  558. Missing = false;
  559. if (CreateDataFd() == false)
  560. return false;
  561. unsigned int Tag;
  562. string Msg;
  563. if (Resume != 0)
  564. {
  565. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  566. return false;
  567. if (Tag >= 400)
  568. Resume = 0;
  569. }
  570. if (To.Truncate(Resume) == false)
  571. return false;
  572. if (To.Seek(0) == false)
  573. return false;
  574. if (Resume != 0)
  575. {
  576. if (MD5.AddFD(To.Fd(),Resume) == false)
  577. {
  578. _error->Errno("read","Problem hashing file");
  579. return false;
  580. }
  581. }
  582. // Send the get command
  583. if (WriteMsg(Tag,Msg,"RETR %s",Path) == false)
  584. return false;
  585. if (Tag >= 400)
  586. {
  587. if (Tag == 550)
  588. Missing = true;
  589. return _error->Error("Unable to fetch file, server said '%s'",Msg.c_str());
  590. }
  591. // Finish off the data connection
  592. if (Finalize() == false)
  593. return false;
  594. // Copy loop
  595. unsigned char Buffer[4096];
  596. while (1)
  597. {
  598. // Wait for some data..
  599. if (WaitFd(DataFd,false,TimeOut) == false)
  600. {
  601. Close();
  602. return _error->Error("Data socket timed out");
  603. }
  604. // Read the data..
  605. int Res = read(DataFd,Buffer,sizeof(Buffer));
  606. if (Res == 0)
  607. break;
  608. if (Res < 0)
  609. {
  610. if (errno == EAGAIN)
  611. continue;
  612. break;
  613. }
  614. MD5.Add(Buffer,Res);
  615. if (To.Write(Buffer,Res) == false)
  616. {
  617. Close();
  618. return false;
  619. }
  620. }
  621. // All done
  622. close(DataFd);
  623. DataFd = -1;
  624. // Read the closing message from the server
  625. if (ReadResp(Tag,Msg) == false)
  626. return false;
  627. if (Tag >= 400)
  628. return _error->Error("Data transfer failed, server said '%s'",Msg.c_str());
  629. return true;
  630. }
  631. /*}}}*/
  632. // FtpMethod::FtpMethod - Constructor /*{{{*/
  633. // ---------------------------------------------------------------------
  634. /* */
  635. FtpMethod::FtpMethod() : pkgAcqMethod("1.0",SendConfig)
  636. {
  637. signal(SIGTERM,SigTerm);
  638. signal(SIGINT,SigTerm);
  639. Server = 0;
  640. FailFd = -1;
  641. }
  642. /*}}}*/
  643. // FtpMethod::SigTerm - Handle a fatal signal /*{{{*/
  644. // ---------------------------------------------------------------------
  645. /* This closes and timestamps the open file. This is neccessary to get
  646. resume behavoir on user abort */
  647. void FtpMethod::SigTerm(int)
  648. {
  649. if (FailFd == -1)
  650. _exit(100);
  651. close(FailFd);
  652. // Timestamp
  653. struct utimbuf UBuf;
  654. UBuf.actime = FailTime;
  655. UBuf.modtime = FailTime;
  656. utime(FailFile.c_str(),&UBuf);
  657. _exit(100);
  658. }
  659. /*}}}*/
  660. // FtpMethod::Configuration - Handle a configuration message /*{{{*/
  661. // ---------------------------------------------------------------------
  662. /* We stash the desired pipeline depth */
  663. bool FtpMethod::Configuration(string Message)
  664. {
  665. if (pkgAcqMethod::Configuration(Message) == false)
  666. return false;
  667. TimeOut = _config->FindI("Acquire::Ftp::Timeout",TimeOut);
  668. return true;
  669. }
  670. /*}}}*/
  671. // FtpMethod::Fetch - Fetch a file /*{{{*/
  672. // ---------------------------------------------------------------------
  673. /* Fetch a single file, called by the base class.. */
  674. bool FtpMethod::Fetch(FetchItem *Itm)
  675. {
  676. URI Get = Itm->Uri;
  677. const char *File = Get.Path.c_str();
  678. FetchResult Res;
  679. Res.Filename = Itm->DestFile;
  680. Res.IMSHit = false;
  681. // Connect to the server
  682. if (Server == 0 || Server->Comp(Get) == false)
  683. {
  684. delete Server;
  685. Server = new FTPConn(Get);
  686. }
  687. // Could not connect is a transient error..
  688. if (Server->Open(this) == false)
  689. {
  690. Server->Close();
  691. Fail(true);
  692. return true;
  693. }
  694. // Get the files information
  695. Status("Query");
  696. unsigned long Size;
  697. if (Server->Size(File,Size) == false ||
  698. Server->ModTime(File,FailTime) == false)
  699. {
  700. Fail(true);
  701. return true;
  702. }
  703. Res.Size = Size;
  704. // See if it is an IMS hit
  705. if (Itm->LastModified == FailTime)
  706. {
  707. Res.Size = 0;
  708. Res.IMSHit = true;
  709. URIDone(Res);
  710. return true;
  711. }
  712. // See if the file exists
  713. struct stat Buf;
  714. if (stat(Itm->DestFile.c_str(),&Buf) == 0)
  715. {
  716. if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime)
  717. {
  718. Res.Size = Buf.st_size;
  719. Res.LastModified = Buf.st_mtime;
  720. Res.ResumePoint = Buf.st_size;
  721. URIDone(Res);
  722. return true;
  723. }
  724. // Resume?
  725. if (FailTime == Buf.st_mtime && Size > (unsigned)Buf.st_size)
  726. Res.ResumePoint = Buf.st_size;
  727. }
  728. // Open the file
  729. MD5Summation MD5;
  730. {
  731. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  732. if (_error->PendingError() == true)
  733. return false;
  734. URIStart(Res);
  735. FailFile = Itm->DestFile;
  736. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  737. FailFd = Fd.Fd();
  738. bool Missing;
  739. if (Server->Get(File,Fd,Res.ResumePoint,MD5,Missing) == false)
  740. {
  741. Fd.Close();
  742. // Timestamp
  743. struct utimbuf UBuf;
  744. UBuf.actime = FailTime;
  745. UBuf.modtime = FailTime;
  746. utime(FailFile.c_str(),&UBuf);
  747. // If the file is missing we hard fail otherwise transient fail
  748. if (Missing == true)
  749. return false;
  750. Fail(true);
  751. return true;
  752. }
  753. Res.Size = Fd.Size();
  754. }
  755. Res.LastModified = FailTime;
  756. Res.MD5Sum = MD5.Result();
  757. // Timestamp
  758. struct utimbuf UBuf;
  759. UBuf.actime = FailTime;
  760. UBuf.modtime = FailTime;
  761. utime(Queue->DestFile.c_str(),&UBuf);
  762. FailFd = -1;
  763. URIDone(Res);
  764. return true;
  765. }
  766. /*}}}*/
  767. int main(int argc,const char *argv[])
  768. {
  769. /* See if we should be come the http client - we do this for http
  770. proxy urls */
  771. if (getenv("ftp_proxy") != 0)
  772. {
  773. URI Proxy = string(getenv("ftp_proxy"));
  774. if (Proxy.Access == "http")
  775. {
  776. // Copy over the environment setting
  777. char S[300];
  778. snprintf(S,sizeof(S),"http_proxy=%s",getenv("ftp_proxy"));
  779. putenv(S);
  780. // Run the http method
  781. string Path = flNotFile(argv[0]) + "/http";
  782. execl(Path.c_str(),Path.c_str(),0);
  783. cerr << "Unable to invoke " << Path << endl;
  784. exit(100);
  785. }
  786. }
  787. FtpMethod Mth;
  788. return Mth.Run();
  789. }