ftp.cc 26 KB

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