ftp.cc 26 KB

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