ftp.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.13 1999/05/29 03:25:03 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",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. Close();
  257. return _error->Errno("read","Read error");
  258. }
  259. Len += Res;
  260. }
  261. return _error->Error("A response overflowed the buffer.");
  262. }
  263. /*}}}*/
  264. // FTPConn::ReadResp - Read a full response from the server /*{{{*/
  265. // ---------------------------------------------------------------------
  266. /* This reads a reply code from the server, it handles both p */
  267. bool FTPConn::ReadResp(unsigned int &Ret,string &Text)
  268. {
  269. // Grab the first line of the response
  270. string Msg;
  271. if (ReadLine(Msg) == false)
  272. return false;
  273. // Get the ID code
  274. char *End;
  275. Ret = strtol(Msg.c_str(),&End,10);
  276. if (End - Msg.c_str() != 3)
  277. return _error->Error("Protocol corruption");
  278. // All done ?
  279. Text = Msg.c_str()+4;
  280. if (*End == ' ')
  281. {
  282. if (Debug == true)
  283. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  284. return true;
  285. }
  286. if (*End != '-')
  287. return _error->Error("Protocol corruption");
  288. /* Okay, here we do the continued message trick. This is foolish, but
  289. proftpd follows the protocol as specified and wu-ftpd doesn't, so
  290. we filter. I wonder how many clients break if you use proftpd and
  291. put a '- in the 3rd spot in the message? */
  292. char Leader[4];
  293. strncpy(Leader,Msg.c_str(),3);
  294. Leader[3] = 0;
  295. while (ReadLine(Msg) == true)
  296. {
  297. // Short, it must be using RFC continuation..
  298. if (Msg.length() < 4)
  299. {
  300. Text += Msg;
  301. continue;
  302. }
  303. // Oops, finished
  304. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == ' ')
  305. {
  306. Text += Msg.c_str()+4;
  307. break;
  308. }
  309. // This message has the wu-ftpd style reply code prefixed
  310. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == '-')
  311. {
  312. Text += Msg.c_str()+4;
  313. continue;
  314. }
  315. // Must be RFC style prefixing
  316. Text += Msg;
  317. }
  318. if (Debug == true && _error->PendingError() == false)
  319. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  320. return !_error->PendingError();
  321. }
  322. /*}}}*/
  323. // FTPConn::WriteMsg - Send a message to the server /*{{{*/
  324. // ---------------------------------------------------------------------
  325. /* Simple printf like function.. */
  326. bool FTPConn::WriteMsg(unsigned int &Ret,string &Text,const char *Fmt,...)
  327. {
  328. va_list args;
  329. va_start(args,Fmt);
  330. // sprintf the description
  331. char S[400];
  332. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  333. strcat(S,"\r\n");
  334. if (Debug == true)
  335. cerr << "-> '" << QuoteString(S,"") << "'" << endl;
  336. // Send it off
  337. unsigned long Len = strlen(S);
  338. unsigned long Start = 0;
  339. while (Len != 0)
  340. {
  341. if (WaitFd(ServerFd,true,TimeOut) == false)
  342. {
  343. Close();
  344. return _error->Error("Connection timeout");
  345. }
  346. int Res = write(ServerFd,S + Start,Len);
  347. if (Res <= 0)
  348. {
  349. Close();
  350. return _error->Errno("write","Write Error");
  351. }
  352. Len -= Res;
  353. Start += Res;
  354. }
  355. return ReadResp(Ret,Text);
  356. }
  357. /*}}}*/
  358. // FTPConn::GoPasv - Enter Passive mode /*{{{*/
  359. // ---------------------------------------------------------------------
  360. /* Try to enter passive mode, the return code does not indicate if passive
  361. mode could or could not be established, only if there was a fatal error.
  362. Borrowed mostly from lftp. We have to enter passive mode every time
  363. we make a data connection :| */
  364. bool FTPConn::GoPasv()
  365. {
  366. // Try to enable pasv mode
  367. unsigned int Tag;
  368. string Msg;
  369. if (WriteMsg(Tag,Msg,"PASV") == false)
  370. return false;
  371. // Unsupported function
  372. string::size_type Pos = Msg.find('(');
  373. if (Tag >= 400 || Pos == string::npos)
  374. {
  375. memset(&PasvAddr,0,sizeof(PasvAddr));
  376. return true;
  377. }
  378. // Scan it
  379. unsigned a0,a1,a2,a3,p0,p1;
  380. if (sscanf(Msg.c_str() + Pos,"(%u,%u,%u,%u,%u,%u)",&a0,&a1,&a2,&a3,&p0,&p1) != 6)
  381. {
  382. memset(&PasvAddr,0,sizeof(PasvAddr));
  383. return true;
  384. }
  385. // lftp used this horrid byte order manipulation.. Ik.
  386. PasvAddr.sin_family = AF_INET;
  387. unsigned char *a;
  388. unsigned char *p;
  389. a = (unsigned char *)&PasvAddr.sin_addr;
  390. p = (unsigned char *)&PasvAddr.sin_port;
  391. // Some evil servers return 0 to mean their addr
  392. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  393. {
  394. PasvAddr.sin_addr = Peer.sin_addr;
  395. }
  396. else
  397. {
  398. a[0] = a0;
  399. a[1] = a1;
  400. a[2] = a2;
  401. a[3] = a3;
  402. }
  403. p[0] = p0;
  404. p[1] = p1;
  405. return true;
  406. }
  407. /*}}}*/
  408. // FTPConn::Size - Return the size of a file /*{{{*/
  409. // ---------------------------------------------------------------------
  410. /* Grab the file size from the server, 0 means no size or empty file */
  411. bool FTPConn::Size(const char *Path,unsigned long &Size)
  412. {
  413. // Query the size
  414. unsigned int Tag;
  415. string Msg;
  416. Size = 0;
  417. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  418. return false;
  419. char *End;
  420. Size = strtol(Msg.c_str(),&End,10);
  421. if (Tag >= 400 || End == Msg.c_str())
  422. Size = 0;
  423. return true;
  424. }
  425. /*}}}*/
  426. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  427. // ---------------------------------------------------------------------
  428. /* Like Size no error is returned if the command is not supported. If the
  429. command fails then time is set to the current time of day to fool
  430. date checks. */
  431. bool FTPConn::ModTime(const char *Path, time_t &Time)
  432. {
  433. Time = time(&Time);
  434. // Query the mod time
  435. unsigned int Tag;
  436. string Msg;
  437. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  438. return false;
  439. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  440. return true;
  441. // Parse it
  442. struct tm tm;
  443. memset(&tm,0,sizeof(tm));
  444. if (sscanf(Msg.c_str(),"%4d%2d%2d%2d%2d%2d",&tm.tm_year,&tm.tm_mon,
  445. &tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec) != 6)
  446. return true;
  447. tm.tm_year -= 1900;
  448. tm.tm_mon--;
  449. /* We use timegm from the GNU C library, libapt-pkg will provide this
  450. symbol if it does not exist */
  451. Time = timegm(&tm);
  452. return true;
  453. }
  454. /*}}}*/
  455. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  456. // ---------------------------------------------------------------------
  457. /* Create the data connection. Call FinalizeDataFd after this though.. */
  458. bool FTPConn::CreateDataFd()
  459. {
  460. close(DataFd);
  461. DataFd = -1;
  462. // Attempt to enter passive mode.
  463. if (TryPassive == true)
  464. {
  465. if (GoPasv() == false)
  466. return false;
  467. // Oops, didn't work out, don't bother trying again.
  468. if (PasvAddr.sin_port == 0)
  469. TryPassive = false;
  470. }
  471. // Passive mode?
  472. if (PasvAddr.sin_port != 0)
  473. {
  474. // Get a socket
  475. if ((DataFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  476. return _error->Errno("socket","Could not create a socket");
  477. // Connect to the server
  478. SetNonBlock(DataFd,true);
  479. if (connect(DataFd,(sockaddr *)&PasvAddr,sizeof(PasvAddr)) < 0 &&
  480. errno != EINPROGRESS)
  481. return _error->Errno("socket","Could not create a socket");
  482. /* This implements a timeout for connect by opening the connection
  483. nonblocking */
  484. if (WaitFd(ServerFd,true,TimeOut) == false)
  485. return _error->Error("Could not connect data socket, connection timed out");
  486. unsigned int Err;
  487. unsigned int Len = sizeof(Err);
  488. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  489. return _error->Errno("getsockopt","Failed");
  490. if (Err != 0)
  491. return _error->Error("Could not connect.");
  492. return true;
  493. }
  494. // Port mode :<
  495. close(DataListenFd);
  496. DataListenFd = -1;
  497. // Get a socket
  498. if ((DataListenFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  499. return _error->Errno("socket","Could not create a socket");
  500. // Bind and listen
  501. sockaddr_in Addr;
  502. memset(&Addr,0,sizeof(Addr));
  503. if (bind(DataListenFd,(sockaddr *)&Addr,sizeof(Addr)) < 0)
  504. return _error->Errno("bind","Could not bind a socket");
  505. if (listen(DataListenFd,1) < 0)
  506. return _error->Errno("listen","Could not listen on the socket");
  507. SetNonBlock(DataListenFd,true);
  508. // Determine the name to send to the remote
  509. sockaddr_in Addr2;
  510. socklen_t Jnk = sizeof(Addr);
  511. if (getsockname(DataListenFd,(sockaddr *)&Addr,&Jnk) < 0)
  512. return _error->Errno("getsockname","Could not determine the socket's name");
  513. Jnk = sizeof(Addr2);
  514. if (getsockname(ServerFd,(sockaddr *)&Addr2,&Jnk) < 0)
  515. return _error->Errno("getsockname","Could not determine the socket's name");
  516. // This bit ripped from qftp
  517. unsigned long badr = ntohl(*(unsigned long *)&Addr2.sin_addr);
  518. unsigned long bp = ntohs(Addr.sin_port);
  519. // Send the port command
  520. unsigned int Tag;
  521. string Msg;
  522. if (WriteMsg(Tag,Msg,"PORT %d,%d,%d,%d,%d,%d",
  523. (int) (badr >> 24) & 0xff, (int) (badr >> 16) & 0xff,
  524. (int) (badr >> 8) & 0xff, (int) badr & 0xff,
  525. (int) (bp >> 8) & 0xff, (int) bp & 0xff) == false)
  526. return false;
  527. if (Tag >= 400)
  528. return _error->Error("Unable to send port command");
  529. return true;
  530. }
  531. /*}}}*/
  532. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  533. // ---------------------------------------------------------------------
  534. /* If the connection is in port mode this waits for the other end to hook
  535. up to us. */
  536. bool FTPConn::Finalize()
  537. {
  538. // Passive mode? Do nothing
  539. if (PasvAddr.sin_port != 0)
  540. return true;
  541. // Close any old socket..
  542. close(DataFd);
  543. DataFd = -1;
  544. // Wait for someone to connect..
  545. if (WaitFd(DataListenFd,false,TimeOut) == false)
  546. return _error->Error("Data socket connect timed out");
  547. // Accept the connection
  548. struct sockaddr_in Addr;
  549. socklen_t Len = sizeof(Addr);
  550. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  551. if (DataFd < 0)
  552. return _error->Errno("accept","Unable to accept connection");
  553. close(DataListenFd);
  554. DataListenFd = -1;
  555. return true;
  556. }
  557. /*}}}*/
  558. // FTPConn::Get - Get a file /*{{{*/
  559. // ---------------------------------------------------------------------
  560. /* This opens a data connection, sends REST and RETR and then
  561. transfers the file over. */
  562. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume,
  563. MD5Summation &MD5,bool &Missing)
  564. {
  565. Missing = false;
  566. if (CreateDataFd() == false)
  567. return false;
  568. unsigned int Tag;
  569. string Msg;
  570. if (Resume != 0)
  571. {
  572. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  573. return false;
  574. if (Tag >= 400)
  575. Resume = 0;
  576. }
  577. if (To.Truncate(Resume) == false)
  578. return false;
  579. if (To.Seek(0) == false)
  580. return false;
  581. if (Resume != 0)
  582. {
  583. if (MD5.AddFD(To.Fd(),Resume) == false)
  584. {
  585. _error->Errno("read","Problem hashing file");
  586. return false;
  587. }
  588. }
  589. // Send the get command
  590. if (WriteMsg(Tag,Msg,"RETR %s",Path) == false)
  591. return false;
  592. if (Tag >= 400)
  593. {
  594. if (Tag == 550)
  595. Missing = true;
  596. return _error->Error("Unable to fetch file, server said '%s'",Msg.c_str());
  597. }
  598. // Finish off the data connection
  599. if (Finalize() == false)
  600. return false;
  601. // Copy loop
  602. unsigned char Buffer[4096];
  603. while (1)
  604. {
  605. // Wait for some data..
  606. if (WaitFd(DataFd,false,TimeOut) == false)
  607. {
  608. Close();
  609. return _error->Error("Data socket timed out");
  610. }
  611. // Read the data..
  612. int Res = read(DataFd,Buffer,sizeof(Buffer));
  613. if (Res == 0)
  614. break;
  615. if (Res < 0)
  616. {
  617. if (errno == EAGAIN)
  618. continue;
  619. break;
  620. }
  621. MD5.Add(Buffer,Res);
  622. if (To.Write(Buffer,Res) == false)
  623. {
  624. Close();
  625. return false;
  626. }
  627. }
  628. // All done
  629. close(DataFd);
  630. DataFd = -1;
  631. // Read the closing message from the server
  632. if (ReadResp(Tag,Msg) == false)
  633. return false;
  634. if (Tag >= 400)
  635. return _error->Error("Data transfer failed, server said '%s'",Msg.c_str());
  636. return true;
  637. }
  638. /*}}}*/
  639. // FtpMethod::FtpMethod - Constructor /*{{{*/
  640. // ---------------------------------------------------------------------
  641. /* */
  642. FtpMethod::FtpMethod() : pkgAcqMethod("1.0",SendConfig)
  643. {
  644. signal(SIGTERM,SigTerm);
  645. signal(SIGINT,SigTerm);
  646. Server = 0;
  647. FailFd = -1;
  648. }
  649. /*}}}*/
  650. // FtpMethod::SigTerm - Handle a fatal signal /*{{{*/
  651. // ---------------------------------------------------------------------
  652. /* This closes and timestamps the open file. This is neccessary to get
  653. resume behavoir on user abort */
  654. void FtpMethod::SigTerm(int)
  655. {
  656. if (FailFd == -1)
  657. exit(100);
  658. close(FailFd);
  659. // Timestamp
  660. struct utimbuf UBuf;
  661. UBuf.actime = FailTime;
  662. UBuf.modtime = FailTime;
  663. utime(FailFile.c_str(),&UBuf);
  664. exit(100);
  665. }
  666. /*}}}*/
  667. // FtpMethod::Configuration - Handle a configuration message /*{{{*/
  668. // ---------------------------------------------------------------------
  669. /* We stash the desired pipeline depth */
  670. bool FtpMethod::Configuration(string Message)
  671. {
  672. if (pkgAcqMethod::Configuration(Message) == false)
  673. return false;
  674. TimeOut = _config->FindI("Acquire::Ftp::Timeout",TimeOut);
  675. return true;
  676. }
  677. /*}}}*/
  678. // FtpMethod::Fetch - Fetch a file /*{{{*/
  679. // ---------------------------------------------------------------------
  680. /* Fetch a single file, called by the base class.. */
  681. bool FtpMethod::Fetch(FetchItem *Itm)
  682. {
  683. URI Get = Itm->Uri;
  684. const char *File = Get.Path.c_str();
  685. FetchResult Res;
  686. Res.Filename = Itm->DestFile;
  687. Res.IMSHit = false;
  688. // Connect to the server
  689. if (Server == 0 || Server->Comp(Get) == false)
  690. {
  691. delete Server;
  692. Server = new FTPConn(Get);
  693. }
  694. // Could not connect is a transient error..
  695. if (Server->Open(this) == false)
  696. {
  697. Server->Close();
  698. Fail(true);
  699. return true;
  700. }
  701. // Get the files information
  702. Status("Query");
  703. unsigned long Size;
  704. if (Server->Size(File,Size) == false ||
  705. Server->ModTime(File,FailTime) == false)
  706. {
  707. Fail(true);
  708. return true;
  709. }
  710. Res.Size = Size;
  711. // See if it is an IMS hit
  712. if (Itm->LastModified == FailTime)
  713. {
  714. Res.Size = 0;
  715. Res.IMSHit = true;
  716. URIDone(Res);
  717. return true;
  718. }
  719. // See if the file exists
  720. struct stat Buf;
  721. if (stat(Itm->DestFile.c_str(),&Buf) == 0)
  722. {
  723. if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime)
  724. {
  725. Res.Size = Buf.st_size;
  726. Res.LastModified = Buf.st_mtime;
  727. URIDone(Res);
  728. return true;
  729. }
  730. // Resume?
  731. if (FailTime == Buf.st_mtime && Size > (unsigned)Buf.st_size)
  732. Res.ResumePoint = Buf.st_size;
  733. }
  734. // Open the file
  735. MD5Summation MD5;
  736. {
  737. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  738. if (_error->PendingError() == true)
  739. return false;
  740. URIStart(Res);
  741. FailFile = Itm->DestFile;
  742. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  743. FailFd = Fd.Fd();
  744. bool Missing;
  745. if (Server->Get(File,Fd,Res.ResumePoint,MD5,Missing) == false)
  746. {
  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. time(&UBuf.actime);
  760. UBuf.actime = FailTime;
  761. UBuf.modtime = FailTime;
  762. utime(Queue->DestFile.c_str(),&UBuf);
  763. FailFd = -1;
  764. URIDone(Res);
  765. return true;
  766. }
  767. /*}}}*/
  768. int main(int argc,const char *argv[])
  769. {
  770. /* See if we should be come the http client - we do this for http
  771. proxy urls */
  772. if (getenv("ftp_proxy") != 0)
  773. {
  774. URI Proxy = string(getenv("ftp_proxy"));
  775. if (Proxy.Access == "http")
  776. {
  777. // Copy over the environment setting
  778. char S[300];
  779. snprintf(S,sizeof(S),"http_proxy=%s",getenv("ftp_proxy"));
  780. putenv(S);
  781. // Run the http method
  782. string Path = flNotFile(argv[0]) + "/http";
  783. execl(Path.c_str(),Path.c_str(),0);
  784. cerr << "Unable to invoke " << Path << endl;
  785. exit(100);
  786. }
  787. }
  788. FtpMethod Mth;
  789. return Mth.Run();
  790. }