ftp.cc 25 KB

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