ftp.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.1 1999/03/15 06:00:59 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. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/acquire-method.h>
  15. #include <apt-pkg/error.h>
  16. #include <apt-pkg/md5.h>
  17. #include "ftp.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. /*}}}*/
  32. unsigned long TimeOut = 120;
  33. URI Proxy;
  34. bool Debug;
  35. // FTPConn::FTPConn - Constructor /*{{{*/
  36. // ---------------------------------------------------------------------
  37. /* */
  38. FTPConn::FTPConn(URI Srv) : Len(0), ServerFd(-1), DataFd(-1),
  39. DataListenFd(-1), ServerName(Srv)
  40. {
  41. Debug = true;
  42. memset(&PasvAddr,0,sizeof(PasvAddr));
  43. }
  44. /*}}}*/
  45. // FTPConn::~FTPConn - Destructor /*{{{*/
  46. // ---------------------------------------------------------------------
  47. /* */
  48. FTPConn::~FTPConn()
  49. {
  50. Close();
  51. }
  52. /*}}}*/
  53. // FTPConn::Close - Close down the connection /*{{{*/
  54. // ---------------------------------------------------------------------
  55. /* Just tear down the socket and data socket */
  56. void FTPConn::Close()
  57. {
  58. close(ServerFd);
  59. ServerFd = -1;
  60. close(DataFd);
  61. DataFd = -1;
  62. close(DataListenFd);
  63. DataListenFd = -1;
  64. memset(&PasvAddr,0,sizeof(PasvAddr));
  65. }
  66. /*}}}*/
  67. // FTPConn::Open - Open a new connection /*{{{*/
  68. // ---------------------------------------------------------------------
  69. /* Connect to the server using a non-blocking connection and perform a
  70. login. */
  71. string LastHost;
  72. in_addr LastHostA;
  73. bool FTPConn::Open()
  74. {
  75. // Use the already open connection if possible.
  76. if (ServerFd != -1)
  77. return true;
  78. Close();
  79. // Determine the proxy setting
  80. if (getenv("ftp_proxy") == 0)
  81. {
  82. string DefProxy = _config->Find("Acquire::ftp::Proxy");
  83. string SpecificProxy = _config->Find("Acquire::ftp::Proxy::" + ServerName.Host);
  84. if (SpecificProxy.empty() == false)
  85. {
  86. if (SpecificProxy == "DIRECT")
  87. Proxy = "";
  88. else
  89. Proxy = SpecificProxy;
  90. }
  91. else
  92. Proxy = DefProxy;
  93. }
  94. else
  95. Proxy = getenv("ftp_proxy");
  96. // Determine what host and port to use based on the proxy settings
  97. int Port = 21;
  98. string Host;
  99. if (Proxy.empty() == true)
  100. {
  101. if (ServerName.Port != 0)
  102. Port = ServerName.Port;
  103. else
  104. ServerName.Port = Port;
  105. Host = ServerName.Host;
  106. }
  107. else
  108. {
  109. if (Proxy.Port != 0)
  110. Port = Proxy.Port;
  111. Host = Proxy.Host;
  112. }
  113. /* We used a cached address record.. Yes this is against the spec but
  114. the way we have setup our rotating dns suggests that this is more
  115. sensible */
  116. if (LastHost != Host)
  117. {
  118. // Owner->Status("Connecting to %s",Host.c_str());
  119. // Lookup the host
  120. hostent *Addr = gethostbyname(Host.c_str());
  121. if (Addr == 0 || Addr->h_addr_list[0] == 0)
  122. return _error->Error("Could not resolve '%s'",Host.c_str());
  123. LastHost = Host;
  124. LastHostA = *(in_addr *)(Addr->h_addr_list[0]);
  125. }
  126. // Owner->Status("Connecting to %s (%s)",Host.c_str(),inet_ntoa(LastHostA));
  127. // Get a socket
  128. if ((ServerFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  129. return _error->Errno("socket","Could not create a socket");
  130. // Connect to the server
  131. struct sockaddr_in server;
  132. server.sin_family = AF_INET;
  133. server.sin_port = htons(Port);
  134. server.sin_addr = LastHostA;
  135. SetNonBlock(ServerFd,true);
  136. if (connect(ServerFd,(sockaddr *)&server,sizeof(server)) < 0 &&
  137. errno != EINPROGRESS)
  138. return _error->Errno("socket","Could not create a socket");
  139. Peer = server;
  140. /* This implements a timeout for connect by opening the connection
  141. nonblocking */
  142. if (WaitFd(ServerFd,true,TimeOut) == false)
  143. return _error->Error("Could not connect, connection timed out");
  144. unsigned int Err;
  145. unsigned int Len = sizeof(Err);
  146. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  147. return _error->Errno("getsockopt","Failed");
  148. if (Err != 0)
  149. return _error->Error("Could not connect.");
  150. return Login();
  151. }
  152. /*}}}*/
  153. // FTPConn::Login - Login to the remote server /*{{{*/
  154. // ---------------------------------------------------------------------
  155. /* This performs both normal login and proxy login using a simples script
  156. stored in the config file. */
  157. bool FTPConn::Login()
  158. {
  159. unsigned int Tag;
  160. string Msg;
  161. // Setup the variables needed for authentication
  162. string User = "anonymous";
  163. string Pass = "apt_get_ftp_2.0@debian.linux.user";
  164. // Fill in the user/pass
  165. if (ServerName.User.empty() == false)
  166. User = ServerName.User;
  167. if (ServerName.Password.empty() == false)
  168. Pass = ServerName.Password;
  169. // Perform simple login
  170. if (Proxy.empty() == true)
  171. {
  172. // Read the initial response
  173. if (ReadResp(Tag,Msg) == false)
  174. return false;
  175. if (Tag >= 400)
  176. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  177. // Send the user
  178. if (WriteMsg(Tag,Msg,"USER %s",User.c_str()) == false)
  179. return false;
  180. if (Tag >= 400)
  181. return _error->Error("USER failed, server said: %s",Msg.c_str());
  182. // Send the Password
  183. if (WriteMsg(Tag,Msg,"PASS %s",Pass.c_str()) == false)
  184. return false;
  185. if (Tag >= 400)
  186. return _error->Error("PASS failed, server said: %s",Msg.c_str());
  187. // Enter passive mode
  188. TryPassive = false;
  189. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true &&
  190. _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true) == true)
  191. {
  192. TryPassive = true;
  193. }
  194. else
  195. {
  196. if (_config->FindB("Acquire::FTP::Passive",true) == true)
  197. TryPassive = true;
  198. }
  199. }
  200. else
  201. {
  202. // Read the initial response
  203. if (ReadResp(Tag,Msg) == false)
  204. return false;
  205. if (Tag >= 400)
  206. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  207. // Perform proxy script execution
  208. Configuration::Item const *Opts = _config->Tree("Acquire::ftp::ProxyLogin");
  209. if (Opts == 0 || Opts->Child == 0)
  210. return _error->Error("A proxy server was specified but no login "
  211. "script, Acquire::ftp::ProxyLogin is empty.");
  212. Opts = Opts->Child;
  213. // Iterate over the entire login script
  214. for (; Opts != 0; Opts = Opts->Next)
  215. {
  216. if (Opts->Value.empty() == true)
  217. continue;
  218. // Substitute the variables into the command
  219. char SitePort[20];
  220. sprintf(SitePort,"%u",ServerName.Port);
  221. string Tmp = Opts->Value;
  222. Tmp = SubstVar(Tmp,"$(PROXY_USER)",Proxy.User);
  223. Tmp = SubstVar(Tmp,"$(PROXY_PASS)",Proxy.Password);
  224. Tmp = SubstVar(Tmp,"$(SITE_USER)",User);
  225. Tmp = SubstVar(Tmp,"$(SITE_PASS)",Pass);
  226. Tmp = SubstVar(Tmp,"$(SITE_PORT)",SitePort);
  227. Tmp = SubstVar(Tmp,"$(SITE)",ServerName.Host);
  228. // Send the command
  229. if (WriteMsg(Tag,Msg,"%s",Tmp.c_str()) == false)
  230. return false;
  231. if (Tag >= 400)
  232. return _error->Error("Login script command '%s' failed, server said: %s",Tmp.c_str(),Msg.c_str());
  233. }
  234. // Enter passive mode
  235. TryPassive = false;
  236. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true &&
  237. _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true) == true)
  238. {
  239. TryPassive = true;
  240. }
  241. else
  242. {
  243. if (_config->Exists("Acquire::FTP::Proxy::Passive") == true &&
  244. _config->FindB("Acquire::FTP::Proxy::Passive",true) == true)
  245. TryPassive = true;
  246. else
  247. if (_config->FindB("Acquire::FTP::Passive",true) == true)
  248. TryPassive = true;
  249. }
  250. }
  251. // Binary mode
  252. if (WriteMsg(Tag,Msg,"TYPE I") == false)
  253. return false;
  254. if (Tag >= 400)
  255. return _error->Error("TYPE failed, server said: %s",Msg.c_str());
  256. return true;
  257. }
  258. /*}}}*/
  259. // FTPConn::ReadLine - Read a line from the server /*{{{*/
  260. // ---------------------------------------------------------------------
  261. /* This performs a very simple buffered read. */
  262. bool FTPConn::ReadLine(string &Text)
  263. {
  264. // Suck in a line
  265. while (Len < sizeof(Buffer))
  266. {
  267. // Scan the buffer for a new line
  268. for (unsigned int I = 0; I != Len; I++)
  269. {
  270. // Escape some special chars
  271. if (Buffer[I] == 0)
  272. Buffer[I] = '?';
  273. // End of line?
  274. if (Buffer[I] != '\n')
  275. continue;
  276. I++;
  277. Text = string(Buffer,I);
  278. memmove(Buffer,Buffer+I,Len - I);
  279. Len -= I;
  280. return true;
  281. }
  282. // Wait for some data..
  283. if (WaitFd(ServerFd,false,TimeOut) == false)
  284. return _error->Error("Connection timeout");
  285. // Suck it back
  286. int Res = read(ServerFd,Buffer,sizeof(Buffer) - Len);
  287. if (Res <= 0)
  288. return _error->Errno("read","Read error");
  289. Len += Res;
  290. }
  291. return _error->Error("A response overflowed the buffer.");
  292. }
  293. /*}}}*/
  294. // FTPConn::ReadResp - Read a full response from the server /*{{{*/
  295. // ---------------------------------------------------------------------
  296. /* This reads a reply code from the server, it handles both p */
  297. bool FTPConn::ReadResp(unsigned int &Ret,string &Text)
  298. {
  299. // Grab the first line of the response
  300. string Msg;
  301. if (ReadLine(Msg) == false)
  302. return false;
  303. // Get the ID code
  304. char *End;
  305. Ret = strtol(Msg.c_str(),&End,10);
  306. if (End - Msg.c_str() != 3)
  307. return _error->Error("Protocol corruption");
  308. // All done ?
  309. Text = Msg.c_str()+4;
  310. if (*End == ' ')
  311. {
  312. if (Debug == true)
  313. cout << "<- '" << QuoteString(Text,"") << "'" << endl;
  314. return true;
  315. }
  316. if (*End != '-')
  317. return _error->Error("Protocol corruption");
  318. /* Okay, here we do the continued message trick. This is foolish, but
  319. proftpd follows the protocol as specified and wu-ftpd doesn't, so
  320. we filter. I wonder how many clients break if you use proftpd and
  321. put a '- in the 3rd spot in the message? */
  322. char Leader[4];
  323. strncpy(Leader,Msg.c_str(),3);
  324. Leader[3] = 0;
  325. while (ReadLine(Msg) == true)
  326. {
  327. // Short, it must be using RFC continuation..
  328. if (Msg.length() < 4)
  329. {
  330. Text += Msg;
  331. continue;
  332. }
  333. // Oops, finished
  334. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == ' ')
  335. {
  336. Text += Msg.c_str()+4;
  337. break;
  338. }
  339. // This message has the wu-ftpd style reply code prefixed
  340. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == '-')
  341. {
  342. Text += Msg.c_str()+4;
  343. continue;
  344. }
  345. // Must be RFC style prefixing
  346. Text += Msg;
  347. }
  348. if (Debug == true && _error->PendingError() == false)
  349. cout << "<- '" << QuoteString(Text,"") << "'" << endl;
  350. return !_error->PendingError();
  351. }
  352. /*}}}*/
  353. // FTPConn::WriteMsg - Send a message to the server /*{{{*/
  354. // ---------------------------------------------------------------------
  355. /* Simple printf like function.. */
  356. bool FTPConn::WriteMsg(unsigned int &Ret,string &Text,const char *Fmt,...)
  357. {
  358. va_list args;
  359. va_start(args,Fmt);
  360. // sprintf the description
  361. char S[400];
  362. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  363. strcat(S,"\r\n");
  364. if (Debug == true)
  365. cout << "-> '" << QuoteString(S,"") << "'" << endl;
  366. // Send it off
  367. unsigned long Len = strlen(S);
  368. unsigned long Start = 0;
  369. while (Len != 0)
  370. {
  371. if (WaitFd(ServerFd,true,TimeOut) == false)
  372. return _error->Error("Connection timeout");
  373. int Res = write(ServerFd,S + Start,Len);
  374. if (Res <= 0)
  375. return _error->Errno("write","Write Error");
  376. Len -= Res;
  377. Start += Res;
  378. }
  379. return ReadResp(Ret,Text);
  380. }
  381. /*}}}*/
  382. // FTPConn::GoPasv - Enter Passive mode /*{{{*/
  383. // ---------------------------------------------------------------------
  384. /* Try to enter passive mode, the return code does not indicate if passive
  385. mode could or could not be established, only if there was a fatal error.
  386. Borrowed mostly from lftp. We have to enter passive mode every time
  387. we make a data connection :| */
  388. bool FTPConn::GoPasv()
  389. {
  390. // Try to enable pasv mode
  391. unsigned int Tag;
  392. string Msg;
  393. if (WriteMsg(Tag,Msg,"PASV") == false)
  394. return false;
  395. // Unsupported function
  396. string::size_type Pos = Msg.find('(');
  397. if (Tag >= 400 || Pos == string::npos)
  398. {
  399. memset(&PasvAddr,0,sizeof(PasvAddr));
  400. return true;
  401. }
  402. // Scan it
  403. unsigned a0,a1,a2,a3,p0,p1;
  404. if (sscanf(Msg.c_str() + Pos,"(%u,%u,%u,%u,%u,%u)",&a0,&a1,&a2,&a3,&p0,&p1) != 6)
  405. {
  406. memset(&PasvAddr,0,sizeof(PasvAddr));
  407. return true;
  408. }
  409. // lftp used this horrid byte order manipulation.. Ik.
  410. PasvAddr.sin_family = AF_INET;
  411. unsigned char *a;
  412. unsigned char *p;
  413. a = (unsigned char *)&PasvAddr.sin_addr;
  414. p = (unsigned char *)&PasvAddr.sin_port;
  415. // Some evil servers return 0 to mean their addr
  416. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  417. {
  418. PasvAddr.sin_addr = Peer.sin_addr;
  419. }
  420. else
  421. {
  422. a[0] = a0;
  423. a[1] = a1;
  424. a[2] = a2;
  425. a[3] = a3;
  426. }
  427. p[0] = p0;
  428. p[1] = p1;
  429. return true;
  430. }
  431. /*}}}*/
  432. // FTPConn::Size - Return the size of a file /*{{{*/
  433. // ---------------------------------------------------------------------
  434. /* Grab the file size from the server, 0 means no size or empty file */
  435. unsigned long FTPConn::Size(const char *Path)
  436. {
  437. // Query the size
  438. unsigned int Tag;
  439. string Msg;
  440. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  441. return false;
  442. char *End;
  443. unsigned long Size = strtol(Msg.c_str(),&End,10);
  444. if (Tag >= 400 || End == Msg.c_str())
  445. return 0;
  446. return Size;
  447. }
  448. /*}}}*/
  449. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  450. // ---------------------------------------------------------------------
  451. /* Like Size no error is returned if the command is not supported. If the
  452. command fails then time is set to the current time of day to fool
  453. date checks. */
  454. bool FTPConn::ModTime(const char *Path, time_t &Time)
  455. {
  456. Time = time(&Time);
  457. // Query the mod time
  458. unsigned int Tag;
  459. string Msg;
  460. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  461. return false;
  462. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  463. return true;
  464. // Parse it
  465. struct tm tm;
  466. memset(&tm,0,sizeof(tm));
  467. if (sscanf(Msg.c_str(),"%4d%2d%2d%2d%2d%2d",&tm.tm_year,&tm.tm_mon,
  468. &tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec) != 6)
  469. return true;
  470. tm.tm_year -= 1900;
  471. tm.tm_mon--;
  472. /* We use timegm from the GNU C library, libapt-pkg will provide this
  473. symbol if it does not exist */
  474. Time = timegm(&tm);
  475. return true;
  476. }
  477. /*}}}*/
  478. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  479. // ---------------------------------------------------------------------
  480. /* Create the data connection. Call FinalizeDataFd after this though.. */
  481. bool FTPConn::CreateDataFd()
  482. {
  483. close(DataFd);
  484. DataFd = -1;
  485. // Attempt to enter passive mode.
  486. if (TryPassive == true)
  487. {
  488. if (GoPasv() == false)
  489. return false;
  490. // Oops, didn't work out, don't bother trying again.
  491. if (PasvAddr.sin_port == 0)
  492. TryPassive = false;
  493. }
  494. // Passive mode?
  495. if (PasvAddr.sin_port != 0)
  496. {
  497. // Get a socket
  498. if ((DataFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  499. return _error->Errno("socket","Could not create a socket");
  500. // Connect to the server
  501. SetNonBlock(DataFd,true);
  502. if (connect(DataFd,(sockaddr *)&PasvAddr,sizeof(PasvAddr)) < 0 &&
  503. errno != EINPROGRESS)
  504. return _error->Errno("socket","Could not create a socket");
  505. /* This implements a timeout for connect by opening the connection
  506. nonblocking */
  507. if (WaitFd(ServerFd,true,TimeOut) == false)
  508. return _error->Error("Could not connect data socket, connection timed out");
  509. unsigned int Err;
  510. unsigned int Len = sizeof(Err);
  511. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  512. return _error->Errno("getsockopt","Failed");
  513. if (Err != 0)
  514. return _error->Error("Could not connect.");
  515. return true;
  516. }
  517. // Port mode :<
  518. if (DataListenFd == -1)
  519. {
  520. // Get a socket
  521. if ((DataListenFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  522. return _error->Errno("socket","Could not create a socket");
  523. // Bind and listen
  524. sockaddr_in Addr;
  525. memset(&Addr,0,sizeof(Addr));
  526. if (bind(DataListenFd,(sockaddr *)&Addr,sizeof(Addr)) < 0)
  527. return _error->Errno("bind","Could not bind a socket");
  528. if (listen(DataListenFd,1) < 0)
  529. return _error->Errno("listen","Could not listen on the socket");
  530. SetNonBlock(DataListenFd,true);
  531. }
  532. // Determine the name to send to the remote
  533. sockaddr_in Addr;
  534. sockaddr_in Addr2;
  535. socklen_t Jnk = sizeof(Addr);
  536. if (getsockname(DataListenFd,(sockaddr *)&Addr,&Jnk) < 0)
  537. return _error->Errno("getsockname","Could not determine the socket's name");
  538. Jnk = sizeof(Addr2);
  539. if (getsockname(ServerFd,(sockaddr *)&Addr2,&Jnk) < 0)
  540. return _error->Errno("getsockname","Could not determine the socket's name");
  541. // This bit ripped from qftp
  542. unsigned long badr = ntohl(*(unsigned long *)&Addr2.sin_addr);
  543. unsigned long bp = ntohs(Addr.sin_port);
  544. // Send the port command
  545. unsigned int Tag;
  546. string Msg;
  547. if (WriteMsg(Tag,Msg,"PORT %d,%d,%d,%d,%d,%d",
  548. (int) (badr >> 24) & 0xff, (int) (badr >> 16) & 0xff,
  549. (int) (badr >> 8) & 0xff, (int) badr & 0xff,
  550. (int) (bp >> 8) & 0xff, (int) bp & 0xff) == false)
  551. return false;
  552. if (Tag >= 400)
  553. return _error->Error("Unable to send port command");
  554. return true;
  555. }
  556. /*}}}*/
  557. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  558. // ---------------------------------------------------------------------
  559. /* If the connection is in port mode this waits for the other end to hook
  560. up to us. */
  561. bool FTPConn::Finalize()
  562. {
  563. // Passive mode? Do nothing
  564. if (PasvAddr.sin_port != 0)
  565. return true;
  566. // Close any old socket..
  567. close(DataFd);
  568. DataFd = -1;
  569. // Wait for someone to connect..
  570. if (WaitFd(DataListenFd,false,TimeOut) == false)
  571. return _error->Error("Data socket connect timed out");
  572. // Accept the connection
  573. struct sockaddr_in Addr;
  574. socklen_t Len = sizeof(Addr);
  575. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  576. if (DataFd < 0)
  577. return _error->Errno("accept","Unable to accept connection");
  578. return true;
  579. }
  580. /*}}}*/
  581. // FTPConn::Get - Get a file /*{{{*/
  582. // ---------------------------------------------------------------------
  583. /* This opens a data connection, sends REST and RETR and then
  584. transfers the file over. */
  585. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume)
  586. {
  587. if (CreateDataFd() == false)
  588. return false;
  589. unsigned int Tag;
  590. string Msg;
  591. if (Resume != 0)
  592. {
  593. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  594. return false;
  595. if (Tag >= 400)
  596. Resume = 0;
  597. }
  598. if (To.Truncate(Resume) == false)
  599. return false;
  600. // Send the get command
  601. if (WriteMsg(Tag,Msg,"RETR %s",Path) == false)
  602. return false;
  603. if (Tag >= 400)
  604. return _error->Error("Unable to fetch file, server said '%s'",Msg.c_str());
  605. // Finish off the data connection
  606. if (Finalize() == false)
  607. return false;
  608. // Copy loop
  609. unsigned char Buffer[4096];
  610. while (1)
  611. {
  612. // Wait for some data..
  613. if (WaitFd(DataFd,false,TimeOut) == false)
  614. return _error->Error("Data socket connect timed out");
  615. // Read the data..
  616. int Res = read(DataFd,Buffer,sizeof(Buffer));
  617. if (Res == 0)
  618. break;
  619. if (Res < 0)
  620. {
  621. if (errno == EAGAIN)
  622. continue;
  623. break;
  624. }
  625. if (To.Write(Buffer,Res) == false)
  626. return false;
  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. int main()
  640. {
  641. FTPConn Con(URI("ftp://va.debian.org/debian/README"));
  642. string Msg;
  643. _config->Set("Acquire::FTP::Passive","false");
  644. while (1)
  645. {
  646. if (Con.Open() == false)
  647. break;
  648. cout << "Size: " << Con.Size("/debian/README") << endl;
  649. time_t Time;
  650. Con.ModTime("/debian/README",Time);
  651. cout << "Time: " << TimeRFC1123(Time) << endl;
  652. {
  653. FileFd F("t",FileFd::WriteEmpty);
  654. Con.Get("/debian/README",F);
  655. }
  656. {
  657. FileFd F("t3",FileFd::WriteEmpty);
  658. Con.Get("/debian/README.pgp",F);
  659. }
  660. break;
  661. }
  662. _error->DumpErrors();
  663. return 0;
  664. }