You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1125 lines
30 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.31.2.1 2004/01/16 18:58:50 mdz Exp $
  4. /* ######################################################################
  5. FTP 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/hashes.h>
  18. #include <apt-pkg/netrc.h>
  19. #include <sys/stat.h>
  20. #include <sys/time.h>
  21. #include <utime.h>
  22. #include <unistd.h>
  23. #include <signal.h>
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include <stdarg.h>
  27. #include <iostream>
  28. #include <apti18n.h>
  29. // Internet stuff
  30. #include <netinet/in.h>
  31. #include <sys/socket.h>
  32. #include <arpa/inet.h>
  33. #include <netdb.h>
  34. #include "rfc2553emu.h"
  35. #include "connect.h"
  36. #include "ftp.h"
  37. /*}}}*/
  38. using namespace std;
  39. /* This table is for the EPRT and EPSV commands, it maps the OS address
  40. family to the IETF address families */
  41. struct AFMap
  42. {
  43. unsigned long Family;
  44. unsigned long IETFFamily;
  45. };
  46. #ifndef AF_INET6
  47. struct AFMap AFMap[] = {{AF_INET,1},{}};
  48. #else
  49. struct AFMap AFMap[] = {{AF_INET,1},{AF_INET6,2},{}};
  50. #endif
  51. unsigned long TimeOut = 120;
  52. URI Proxy;
  53. string FtpMethod::FailFile;
  54. int FtpMethod::FailFd = -1;
  55. time_t FtpMethod::FailTime = 0;
  56. // FTPConn::FTPConn - Constructor /*{{{*/
  57. // ---------------------------------------------------------------------
  58. /* */
  59. FTPConn::FTPConn(URI Srv) : Len(0), ServerFd(-1), DataFd(-1),
  60. DataListenFd(-1), ServerName(Srv)
  61. {
  62. Debug = _config->FindB("Debug::Acquire::Ftp",false);
  63. PasvAddr = 0;
  64. }
  65. /*}}}*/
  66. // FTPConn::~FTPConn - Destructor /*{{{*/
  67. // ---------------------------------------------------------------------
  68. /* */
  69. FTPConn::~FTPConn()
  70. {
  71. Close();
  72. }
  73. /*}}}*/
  74. // FTPConn::Close - Close down the connection /*{{{*/
  75. // ---------------------------------------------------------------------
  76. /* Just tear down the socket and data socket */
  77. void FTPConn::Close()
  78. {
  79. close(ServerFd);
  80. ServerFd = -1;
  81. close(DataFd);
  82. DataFd = -1;
  83. close(DataListenFd);
  84. DataListenFd = -1;
  85. if (PasvAddr != 0)
  86. freeaddrinfo(PasvAddr);
  87. PasvAddr = 0;
  88. }
  89. /*}}}*/
  90. // FTPConn::Open - Open a new connection /*{{{*/
  91. // ---------------------------------------------------------------------
  92. /* Connect to the server using a non-blocking connection and perform a
  93. login. */
  94. bool FTPConn::Open(pkgAcqMethod *Owner)
  95. {
  96. // Use the already open connection if possible.
  97. if (ServerFd != -1)
  98. return true;
  99. Close();
  100. // Determine the proxy setting
  101. string SpecificProxy = _config->Find("Acquire::ftp::Proxy::" + ServerName.Host);
  102. if (!SpecificProxy.empty())
  103. {
  104. if (SpecificProxy == "DIRECT")
  105. Proxy = "";
  106. else
  107. Proxy = SpecificProxy;
  108. }
  109. else
  110. {
  111. string DefProxy = _config->Find("Acquire::ftp::Proxy");
  112. if (!DefProxy.empty())
  113. {
  114. Proxy = DefProxy;
  115. }
  116. else
  117. {
  118. char* result = getenv("ftp_proxy");
  119. Proxy = result ? result : "";
  120. }
  121. }
  122. // Parse no_proxy, a , separated list of domains
  123. if (getenv("no_proxy") != 0)
  124. {
  125. if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
  126. Proxy = "";
  127. }
  128. // Determine what host and port to use based on the proxy settings
  129. int Port = 0;
  130. string Host;
  131. if (Proxy.empty() == true)
  132. {
  133. if (ServerName.Port != 0)
  134. Port = ServerName.Port;
  135. Host = ServerName.Host;
  136. }
  137. else
  138. {
  139. if (Proxy.Port != 0)
  140. Port = Proxy.Port;
  141. Host = Proxy.Host;
  142. }
  143. /* Connect to the remote server. Since FTP is connection oriented we
  144. want to make sure we get a new server every time we reconnect */
  145. RotateDNS();
  146. if (Connect(Host,Port,"ftp",21,ServerFd,TimeOut,Owner) == false)
  147. return false;
  148. // Login must be before getpeername otherwise dante won't work.
  149. Owner->Status(_("Logging in"));
  150. bool Res = Login();
  151. // Get the remote server's address
  152. PeerAddrLen = sizeof(PeerAddr);
  153. if (getpeername(ServerFd,(sockaddr *)&PeerAddr,&PeerAddrLen) != 0)
  154. return _error->Errno("getpeername",_("Unable to determine the peer name"));
  155. // Get the local machine's address
  156. ServerAddrLen = sizeof(ServerAddr);
  157. if (getsockname(ServerFd,(sockaddr *)&ServerAddr,&ServerAddrLen) != 0)
  158. return _error->Errno("getsockname",_("Unable to determine the local name"));
  159. return Res;
  160. }
  161. /*}}}*/
  162. // FTPConn::Login - Login to the remote server /*{{{*/
  163. // ---------------------------------------------------------------------
  164. /* This performs both normal login and proxy login using a simples script
  165. stored in the config file. */
  166. bool FTPConn::Login()
  167. {
  168. unsigned int Tag;
  169. string Msg;
  170. // Setup the variables needed for authentication
  171. string User = "anonymous";
  172. string Pass = "apt_get_ftp_2.1@debian.linux.user";
  173. // Fill in the user/pass
  174. if (ServerName.User.empty() == false)
  175. User = ServerName.User;
  176. if (ServerName.Password.empty() == false)
  177. Pass = ServerName.Password;
  178. // Perform simple login
  179. if (Proxy.empty() == true)
  180. {
  181. // Read the initial response
  182. if (ReadResp(Tag,Msg) == false)
  183. return false;
  184. if (Tag >= 400)
  185. return _error->Error(_("The server refused the connection and said: %s"),Msg.c_str());
  186. // Send the user
  187. if (WriteMsg(Tag,Msg,"USER %s",User.c_str()) == false)
  188. return false;
  189. if (Tag >= 400)
  190. return _error->Error(_("USER failed, server said: %s"),Msg.c_str());
  191. if (Tag == 331) { // 331 User name okay, need password.
  192. // Send the Password
  193. if (WriteMsg(Tag,Msg,"PASS %s",Pass.c_str()) == false)
  194. return false;
  195. if (Tag >= 400)
  196. return _error->Error(_("PASS failed, server said: %s"),Msg.c_str());
  197. }
  198. // Enter passive mode
  199. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  200. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  201. else
  202. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  203. }
  204. else
  205. {
  206. // Read the initial response
  207. if (ReadResp(Tag,Msg) == false)
  208. return false;
  209. if (Tag >= 400)
  210. return _error->Error(_("The server refused the connection and said: %s"),Msg.c_str());
  211. // Perform proxy script execution
  212. Configuration::Item const *Opts = _config->Tree("Acquire::ftp::ProxyLogin");
  213. if (Opts == 0 || Opts->Child == 0)
  214. return _error->Error(_("A proxy server was specified but no login "
  215. "script, Acquire::ftp::ProxyLogin is empty."));
  216. Opts = Opts->Child;
  217. // Iterate over the entire login script
  218. for (; Opts != 0; Opts = Opts->Next)
  219. {
  220. if (Opts->Value.empty() == true)
  221. continue;
  222. // Substitute the variables into the command
  223. char SitePort[20];
  224. if (ServerName.Port != 0)
  225. sprintf(SitePort,"%u",ServerName.Port);
  226. else
  227. strcpy(SitePort,"21");
  228. string Tmp = Opts->Value;
  229. Tmp = SubstVar(Tmp,"$(PROXY_USER)",Proxy.User);
  230. Tmp = SubstVar(Tmp,"$(PROXY_PASS)",Proxy.Password);
  231. Tmp = SubstVar(Tmp,"$(SITE_USER)",User);
  232. Tmp = SubstVar(Tmp,"$(SITE_PASS)",Pass);
  233. Tmp = SubstVar(Tmp,"$(SITE_PORT)",SitePort);
  234. Tmp = SubstVar(Tmp,"$(SITE)",ServerName.Host);
  235. // Send the command
  236. if (WriteMsg(Tag,Msg,"%s",Tmp.c_str()) == false)
  237. return false;
  238. if (Tag >= 400)
  239. return _error->Error(_("Login script command '%s' failed, server said: %s"),Tmp.c_str(),Msg.c_str());
  240. }
  241. // Enter passive mode
  242. TryPassive = false;
  243. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  244. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  245. else
  246. {
  247. if (_config->Exists("Acquire::FTP::Proxy::Passive") == true)
  248. TryPassive = _config->FindB("Acquire::FTP::Proxy::Passive",true);
  249. else
  250. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  251. }
  252. }
  253. // Force the use of extended commands
  254. if (_config->Exists("Acquire::FTP::ForceExtended::" + ServerName.Host) == true)
  255. ForceExtended = _config->FindB("Acquire::FTP::ForceExtended::" + ServerName.Host,true);
  256. else
  257. ForceExtended = _config->FindB("Acquire::FTP::ForceExtended",false);
  258. // Binary mode
  259. if (WriteMsg(Tag,Msg,"TYPE I") == false)
  260. return false;
  261. if (Tag >= 400)
  262. return _error->Error(_("TYPE failed, server said: %s"),Msg.c_str());
  263. return true;
  264. }
  265. /*}}}*/
  266. // FTPConn::ReadLine - Read a line from the server /*{{{*/
  267. // ---------------------------------------------------------------------
  268. /* This performs a very simple buffered read. */
  269. bool FTPConn::ReadLine(string &Text)
  270. {
  271. if (ServerFd == -1)
  272. return false;
  273. // Suck in a line
  274. while (Len < sizeof(Buffer))
  275. {
  276. // Scan the buffer for a new line
  277. for (unsigned int I = 0; I != Len; I++)
  278. {
  279. // Escape some special chars
  280. if (Buffer[I] == 0)
  281. Buffer[I] = '?';
  282. // End of line?
  283. if (Buffer[I] != '\n')
  284. continue;
  285. I++;
  286. Text = string(Buffer,I);
  287. memmove(Buffer,Buffer+I,Len - I);
  288. Len -= I;
  289. return true;
  290. }
  291. // Wait for some data..
  292. if (WaitFd(ServerFd,false,TimeOut) == false)
  293. {
  294. Close();
  295. return _error->Error(_("Connection timeout"));
  296. }
  297. // Suck it back
  298. int Res = read(ServerFd,Buffer + Len,sizeof(Buffer) - Len);
  299. if (Res == 0)
  300. _error->Error(_("Server closed the connection"));
  301. if (Res <= 0)
  302. {
  303. _error->Errno("read",_("Read error"));
  304. Close();
  305. return false;
  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. _error->Errno("write",_("Write error"));
  398. Close();
  399. return false;
  400. }
  401. Len -= Res;
  402. Start += Res;
  403. }
  404. return ReadResp(Ret,Text);
  405. }
  406. /*}}}*/
  407. // FTPConn::GoPasv - Enter Passive mode /*{{{*/
  408. // ---------------------------------------------------------------------
  409. /* Try to enter passive mode, the return code does not indicate if passive
  410. mode could or could not be established, only if there was a fatal error.
  411. We have to enter passive mode every time we make a data connection :| */
  412. bool FTPConn::GoPasv()
  413. {
  414. /* The PASV command only works on IPv4 sockets, even though it could
  415. in theory suppory IPv6 via an all zeros reply */
  416. if (((struct sockaddr *)&PeerAddr)->sa_family != AF_INET ||
  417. ForceExtended == true)
  418. return ExtGoPasv();
  419. if (PasvAddr != 0)
  420. freeaddrinfo(PasvAddr);
  421. PasvAddr = 0;
  422. // Try to enable pasv mode
  423. unsigned int Tag;
  424. string Msg;
  425. if (WriteMsg(Tag,Msg,"PASV") == false)
  426. return false;
  427. // Unsupported function
  428. string::size_type Pos = Msg.find('(');
  429. if (Tag >= 400 || Pos == string::npos)
  430. return true;
  431. // Scan it
  432. unsigned a0,a1,a2,a3,p0,p1;
  433. if (sscanf(Msg.c_str() + Pos,"(%u,%u,%u,%u,%u,%u)",&a0,&a1,&a2,&a3,&p0,&p1) != 6)
  434. return true;
  435. /* Some evil servers return 0 to mean their addr. We can actually speak
  436. to these servers natively using IPv6 */
  437. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  438. {
  439. // Get the IP in text form
  440. char Name[NI_MAXHOST];
  441. char Service[NI_MAXSERV];
  442. getnameinfo((struct sockaddr *)&PeerAddr,PeerAddrLen,
  443. Name,sizeof(Name),Service,sizeof(Service),
  444. NI_NUMERICHOST|NI_NUMERICSERV);
  445. struct addrinfo Hints;
  446. memset(&Hints,0,sizeof(Hints));
  447. Hints.ai_socktype = SOCK_STREAM;
  448. Hints.ai_family = ((struct sockaddr *)&PeerAddr)->sa_family;
  449. Hints.ai_flags |= AI_NUMERICHOST;
  450. // Get a new passive address.
  451. char Port[100];
  452. snprintf(Port,sizeof(Port),"%u",(p0 << 8) + p1);
  453. if (getaddrinfo(Name,Port,&Hints,&PasvAddr) != 0)
  454. return true;
  455. return true;
  456. }
  457. struct addrinfo Hints;
  458. memset(&Hints,0,sizeof(Hints));
  459. Hints.ai_socktype = SOCK_STREAM;
  460. Hints.ai_family = AF_INET;
  461. Hints.ai_flags |= AI_NUMERICHOST;
  462. // Get a new passive address.
  463. char Port[100];
  464. snprintf(Port,sizeof(Port),"%u",(p0 << 8) + p1);
  465. char Name[100];
  466. snprintf(Name,sizeof(Name),"%u.%u.%u.%u",a0,a1,a2,a3);
  467. if (getaddrinfo(Name,Port,&Hints,&PasvAddr) != 0)
  468. return true;
  469. return true;
  470. }
  471. /*}}}*/
  472. // FTPConn::ExtGoPasv - Enter Extended Passive mode /*{{{*/
  473. // ---------------------------------------------------------------------
  474. /* Try to enter extended passive mode. See GoPasv above and RFC 2428 */
  475. bool FTPConn::ExtGoPasv()
  476. {
  477. if (PasvAddr != 0)
  478. freeaddrinfo(PasvAddr);
  479. PasvAddr = 0;
  480. // Try to enable pasv mode
  481. unsigned int Tag;
  482. string Msg;
  483. if (WriteMsg(Tag,Msg,"EPSV") == false)
  484. return false;
  485. // Unsupported function
  486. string::size_type Pos = Msg.find('(');
  487. if (Tag >= 400 || Pos == string::npos)
  488. return true;
  489. // Scan it
  490. string::const_iterator List[4];
  491. unsigned Count = 0;
  492. Pos++;
  493. for (string::const_iterator I = Msg.begin() + Pos; I < Msg.end(); I++)
  494. {
  495. if (*I != Msg[Pos])
  496. continue;
  497. if (Count >= 4)
  498. return true;
  499. List[Count++] = I;
  500. }
  501. if (Count != 4)
  502. return true;
  503. // Break it up ..
  504. unsigned long Proto = 0;
  505. unsigned long Port = 0;
  506. string IP;
  507. IP = string(List[1]+1,List[2]);
  508. Port = atoi(string(List[2]+1,List[3]).c_str());
  509. if (IP.empty() == false)
  510. Proto = atoi(string(List[0]+1,List[1]).c_str());
  511. if (Port == 0)
  512. return false;
  513. // String version of the port
  514. char PStr[100];
  515. snprintf(PStr,sizeof(PStr),"%lu",Port);
  516. // Get the IP in text form
  517. struct addrinfo Hints;
  518. memset(&Hints,0,sizeof(Hints));
  519. Hints.ai_socktype = SOCK_STREAM;
  520. Hints.ai_flags |= AI_NUMERICHOST;
  521. /* The RFC defined case, connect to the old IP/protocol using the
  522. new port. */
  523. if (IP.empty() == true)
  524. {
  525. // Get the IP in text form
  526. char Name[NI_MAXHOST];
  527. char Service[NI_MAXSERV];
  528. getnameinfo((struct sockaddr *)&PeerAddr,PeerAddrLen,
  529. Name,sizeof(Name),Service,sizeof(Service),
  530. NI_NUMERICHOST|NI_NUMERICSERV);
  531. IP = Name;
  532. Hints.ai_family = ((struct sockaddr *)&PeerAddr)->sa_family;
  533. }
  534. else
  535. {
  536. // Get the family..
  537. Hints.ai_family = 0;
  538. for (unsigned J = 0; AFMap[J].Family != 0; J++)
  539. if (AFMap[J].IETFFamily == Proto)
  540. Hints.ai_family = AFMap[J].Family;
  541. if (Hints.ai_family == 0)
  542. return true;
  543. }
  544. // Get a new passive address.
  545. int Res;
  546. if ((Res = getaddrinfo(IP.c_str(),PStr,&Hints,&PasvAddr)) != 0)
  547. return true;
  548. return true;
  549. }
  550. /*}}}*/
  551. // FTPConn::Size - Return the size of a file /*{{{*/
  552. // ---------------------------------------------------------------------
  553. /* Grab the file size from the server, 0 means no size or empty file */
  554. bool FTPConn::Size(const char *Path,unsigned long &Size)
  555. {
  556. // Query the size
  557. unsigned int Tag;
  558. string Msg;
  559. Size = 0;
  560. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  561. return false;
  562. char *End;
  563. Size = strtol(Msg.c_str(),&End,10);
  564. if (Tag >= 400 || End == Msg.c_str())
  565. Size = 0;
  566. return true;
  567. }
  568. /*}}}*/
  569. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  570. // ---------------------------------------------------------------------
  571. /* Like Size no error is returned if the command is not supported. If the
  572. command fails then time is set to the current time of day to fool
  573. date checks. */
  574. bool FTPConn::ModTime(const char *Path, time_t &Time)
  575. {
  576. Time = time(&Time);
  577. // Query the mod time
  578. unsigned int Tag;
  579. string Msg;
  580. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  581. return false;
  582. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  583. return true;
  584. // Parse it
  585. return FTPMDTMStrToTime(Msg.c_str(), Time);
  586. }
  587. /*}}}*/
  588. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* Create the data connection. Call FinalizeDataFd after this though.. */
  591. bool FTPConn::CreateDataFd()
  592. {
  593. close(DataFd);
  594. DataFd = -1;
  595. // Attempt to enter passive mode.
  596. if (TryPassive == true)
  597. {
  598. if (GoPasv() == false)
  599. return false;
  600. // Oops, didn't work out, don't bother trying again.
  601. if (PasvAddr == 0)
  602. TryPassive = false;
  603. }
  604. // Passive mode?
  605. if (PasvAddr != 0)
  606. {
  607. // Get a socket
  608. if ((DataFd = socket(PasvAddr->ai_family,PasvAddr->ai_socktype,
  609. PasvAddr->ai_protocol)) < 0)
  610. return _error->Errno("socket",_("Could not create a socket"));
  611. // Connect to the server
  612. SetNonBlock(DataFd,true);
  613. if (connect(DataFd,PasvAddr->ai_addr,PasvAddr->ai_addrlen) < 0 &&
  614. errno != EINPROGRESS)
  615. return _error->Errno("socket",_("Could not create a socket"));
  616. /* This implements a timeout for connect by opening the connection
  617. nonblocking */
  618. if (WaitFd(DataFd,true,TimeOut) == false)
  619. return _error->Error(_("Could not connect data socket, connection timed out"));
  620. unsigned int Err;
  621. unsigned int Len = sizeof(Err);
  622. if (getsockopt(DataFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  623. return _error->Errno("getsockopt",_("Failed"));
  624. if (Err != 0)
  625. return _error->Error(_("Could not connect passive socket."));
  626. return true;
  627. }
  628. // Port mode :<
  629. close(DataListenFd);
  630. DataListenFd = -1;
  631. // Get the information for a listening socket.
  632. struct addrinfo *BindAddr = 0;
  633. struct addrinfo Hints;
  634. memset(&Hints,0,sizeof(Hints));
  635. Hints.ai_socktype = SOCK_STREAM;
  636. Hints.ai_flags |= AI_PASSIVE;
  637. Hints.ai_family = ((struct sockaddr *)&ServerAddr)->sa_family;
  638. int Res;
  639. if ((Res = getaddrinfo(0,"0",&Hints,&BindAddr)) != 0)
  640. return _error->Error(_("getaddrinfo was unable to get a listening socket"));
  641. // Construct the socket
  642. if ((DataListenFd = socket(BindAddr->ai_family,BindAddr->ai_socktype,
  643. BindAddr->ai_protocol)) < 0)
  644. {
  645. freeaddrinfo(BindAddr);
  646. return _error->Errno("socket",_("Could not create a socket"));
  647. }
  648. // Bind and listen
  649. if (bind(DataListenFd,BindAddr->ai_addr,BindAddr->ai_addrlen) < 0)
  650. {
  651. freeaddrinfo(BindAddr);
  652. return _error->Errno("bind",_("Could not bind a socket"));
  653. }
  654. freeaddrinfo(BindAddr);
  655. if (listen(DataListenFd,1) < 0)
  656. return _error->Errno("listen",_("Could not listen on the socket"));
  657. SetNonBlock(DataListenFd,true);
  658. // Determine the name to send to the remote
  659. struct sockaddr_storage Addr;
  660. socklen_t AddrLen = sizeof(Addr);
  661. if (getsockname(DataListenFd,(sockaddr *)&Addr,&AddrLen) < 0)
  662. return _error->Errno("getsockname",_("Could not determine the socket's name"));
  663. // Reverse the address. We need the server address and the data port.
  664. char Name[NI_MAXHOST];
  665. char Service[NI_MAXSERV];
  666. char Service2[NI_MAXSERV];
  667. getnameinfo((struct sockaddr *)&Addr,AddrLen,
  668. Name,sizeof(Name),Service,sizeof(Service),
  669. NI_NUMERICHOST|NI_NUMERICSERV);
  670. getnameinfo((struct sockaddr *)&ServerAddr,ServerAddrLen,
  671. Name,sizeof(Name),Service2,sizeof(Service2),
  672. NI_NUMERICHOST|NI_NUMERICSERV);
  673. // Send off an IPv4 address in the old port format
  674. if (((struct sockaddr *)&Addr)->sa_family == AF_INET &&
  675. ForceExtended == false)
  676. {
  677. // Convert the dots in the quad into commas
  678. for (char *I = Name; *I != 0; I++)
  679. if (*I == '.')
  680. *I = ',';
  681. unsigned long Port = atoi(Service);
  682. // Send the port command
  683. unsigned int Tag;
  684. string Msg;
  685. if (WriteMsg(Tag,Msg,"PORT %s,%d,%d",
  686. Name,
  687. (int)(Port >> 8) & 0xff, (int)(Port & 0xff)) == false)
  688. return false;
  689. if (Tag >= 400)
  690. return _error->Error(_("Unable to send PORT command"));
  691. return true;
  692. }
  693. // Construct an EPRT command
  694. unsigned Proto = 0;
  695. for (unsigned J = 0; AFMap[J].Family != 0; J++)
  696. if (AFMap[J].Family == ((struct sockaddr *)&Addr)->sa_family)
  697. Proto = AFMap[J].IETFFamily;
  698. if (Proto == 0)
  699. return _error->Error(_("Unknown address family %u (AF_*)"),
  700. ((struct sockaddr *)&Addr)->sa_family);
  701. // Send the EPRT command
  702. unsigned int Tag;
  703. string Msg;
  704. if (WriteMsg(Tag,Msg,"EPRT |%u|%s|%s|",Proto,Name,Service) == false)
  705. return false;
  706. if (Tag >= 400)
  707. return _error->Error(_("EPRT failed, server said: %s"),Msg.c_str());
  708. return true;
  709. }
  710. /*}}}*/
  711. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  712. // ---------------------------------------------------------------------
  713. /* If the connection is in port mode this waits for the other end to hook
  714. up to us. */
  715. bool FTPConn::Finalize()
  716. {
  717. // Passive mode? Do nothing
  718. if (PasvAddr != 0)
  719. return true;
  720. // Close any old socket..
  721. close(DataFd);
  722. DataFd = -1;
  723. // Wait for someone to connect..
  724. if (WaitFd(DataListenFd,false,TimeOut) == false)
  725. return _error->Error(_("Data socket connect timed out"));
  726. // Accept the connection
  727. struct sockaddr_in Addr;
  728. socklen_t Len = sizeof(Addr);
  729. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  730. if (DataFd < 0)
  731. return _error->Errno("accept",_("Unable to accept connection"));
  732. close(DataListenFd);
  733. DataListenFd = -1;
  734. return true;
  735. }
  736. /*}}}*/
  737. // FTPConn::Get - Get a file /*{{{*/
  738. // ---------------------------------------------------------------------
  739. /* This opens a data connection, sends REST and RETR and then
  740. transfers the file over. */
  741. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume,
  742. Hashes &Hash,bool &Missing)
  743. {
  744. Missing = false;
  745. if (CreateDataFd() == false)
  746. return false;
  747. unsigned int Tag;
  748. string Msg;
  749. if (Resume != 0)
  750. {
  751. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  752. return false;
  753. if (Tag >= 400)
  754. Resume = 0;
  755. }
  756. if (To.Truncate(Resume) == false)
  757. return false;
  758. if (To.Seek(0) == false)
  759. return false;
  760. if (Resume != 0)
  761. {
  762. if (Hash.AddFD(To.Fd(),Resume) == false)
  763. {
  764. _error->Errno("read",_("Problem hashing file"));
  765. return false;
  766. }
  767. }
  768. // Send the get command
  769. if (WriteMsg(Tag,Msg,"RETR %s",Path) == false)
  770. return false;
  771. if (Tag >= 400)
  772. {
  773. if (Tag == 550)
  774. Missing = true;
  775. return _error->Error(_("Unable to fetch file, server said '%s'"),Msg.c_str());
  776. }
  777. // Finish off the data connection
  778. if (Finalize() == false)
  779. return false;
  780. // Copy loop
  781. unsigned char Buffer[4096];
  782. while (1)
  783. {
  784. // Wait for some data..
  785. if (WaitFd(DataFd,false,TimeOut) == false)
  786. {
  787. Close();
  788. return _error->Error(_("Data socket timed out"));
  789. }
  790. // Read the data..
  791. int Res = read(DataFd,Buffer,sizeof(Buffer));
  792. if (Res == 0)
  793. break;
  794. if (Res < 0)
  795. {
  796. if (errno == EAGAIN)
  797. continue;
  798. break;
  799. }
  800. Hash.Add(Buffer,Res);
  801. if (To.Write(Buffer,Res) == false)
  802. {
  803. Close();
  804. return false;
  805. }
  806. }
  807. // All done
  808. close(DataFd);
  809. DataFd = -1;
  810. // Read the closing message from the server
  811. if (ReadResp(Tag,Msg) == false)
  812. return false;
  813. if (Tag >= 400)
  814. return _error->Error(_("Data transfer failed, server said '%s'"),Msg.c_str());
  815. return true;
  816. }
  817. /*}}}*/
  818. // FtpMethod::FtpMethod - Constructor /*{{{*/
  819. // ---------------------------------------------------------------------
  820. /* */
  821. FtpMethod::FtpMethod() : pkgAcqMethod("1.0",SendConfig)
  822. {
  823. signal(SIGTERM,SigTerm);
  824. signal(SIGINT,SigTerm);
  825. Server = 0;
  826. FailFd = -1;
  827. }
  828. /*}}}*/
  829. // FtpMethod::SigTerm - Handle a fatal signal /*{{{*/
  830. // ---------------------------------------------------------------------
  831. /* This closes and timestamps the open file. This is neccessary to get
  832. resume behavoir on user abort */
  833. void FtpMethod::SigTerm(int)
  834. {
  835. if (FailFd == -1)
  836. _exit(100);
  837. close(FailFd);
  838. // Timestamp
  839. struct utimbuf UBuf;
  840. UBuf.actime = FailTime;
  841. UBuf.modtime = FailTime;
  842. utime(FailFile.c_str(),&UBuf);
  843. _exit(100);
  844. }
  845. /*}}}*/
  846. // FtpMethod::Configuration - Handle a configuration message /*{{{*/
  847. // ---------------------------------------------------------------------
  848. /* We stash the desired pipeline depth */
  849. bool FtpMethod::Configuration(string Message)
  850. {
  851. if (pkgAcqMethod::Configuration(Message) == false)
  852. return false;
  853. TimeOut = _config->FindI("Acquire::Ftp::Timeout",TimeOut);
  854. return true;
  855. }
  856. /*}}}*/
  857. // FtpMethod::Fetch - Fetch a file /*{{{*/
  858. // ---------------------------------------------------------------------
  859. /* Fetch a single file, called by the base class.. */
  860. bool FtpMethod::Fetch(FetchItem *Itm)
  861. {
  862. URI Get = Itm->Uri;
  863. const char *File = Get.Path.c_str();
  864. FetchResult Res;
  865. Res.Filename = Itm->DestFile;
  866. Res.IMSHit = false;
  867. maybe_add_auth (Get, _config->FindFile("Dir::Etc::netrc"));
  868. // Connect to the server
  869. if (Server == 0 || Server->Comp(Get) == false)
  870. {
  871. delete Server;
  872. Server = new FTPConn(Get);
  873. }
  874. // Could not connect is a transient error..
  875. if (Server->Open(this) == false)
  876. {
  877. Server->Close();
  878. Fail(true);
  879. return true;
  880. }
  881. // Get the files information
  882. Status(_("Query"));
  883. unsigned long Size;
  884. if (Server->Size(File,Size) == false ||
  885. Server->ModTime(File,FailTime) == false)
  886. {
  887. Fail(true);
  888. return true;
  889. }
  890. Res.Size = Size;
  891. // See if it is an IMS hit
  892. if (Itm->LastModified == FailTime)
  893. {
  894. Res.Size = 0;
  895. Res.IMSHit = true;
  896. URIDone(Res);
  897. return true;
  898. }
  899. // See if the file exists
  900. struct stat Buf;
  901. if (stat(Itm->DestFile.c_str(),&Buf) == 0)
  902. {
  903. if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime)
  904. {
  905. Res.Size = Buf.st_size;
  906. Res.LastModified = Buf.st_mtime;
  907. Res.ResumePoint = Buf.st_size;
  908. URIDone(Res);
  909. return true;
  910. }
  911. // Resume?
  912. if (FailTime == Buf.st_mtime && Size > (unsigned)Buf.st_size)
  913. Res.ResumePoint = Buf.st_size;
  914. }
  915. // Open the file
  916. Hashes Hash;
  917. {
  918. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  919. if (_error->PendingError() == true)
  920. return false;
  921. URIStart(Res);
  922. FailFile = Itm->DestFile;
  923. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  924. FailFd = Fd.Fd();
  925. bool Missing;
  926. if (Server->Get(File,Fd,Res.ResumePoint,Hash,Missing) == false)
  927. {
  928. Fd.Close();
  929. // Timestamp
  930. struct utimbuf UBuf;
  931. UBuf.actime = FailTime;
  932. UBuf.modtime = FailTime;
  933. utime(FailFile.c_str(),&UBuf);
  934. // If the file is missing we hard fail and delete the destfile
  935. // otherwise transient fail
  936. if (Missing == true) {
  937. unlink(FailFile.c_str());
  938. return false;
  939. }
  940. Fail(true);
  941. return true;
  942. }
  943. Res.Size = Fd.Size();
  944. }
  945. Res.LastModified = FailTime;
  946. Res.TakeHashes(Hash);
  947. // Timestamp
  948. struct utimbuf UBuf;
  949. UBuf.actime = FailTime;
  950. UBuf.modtime = FailTime;
  951. utime(Queue->DestFile.c_str(),&UBuf);
  952. FailFd = -1;
  953. URIDone(Res);
  954. return true;
  955. }
  956. /*}}}*/
  957. int main(int argc,const char *argv[])
  958. {
  959. setlocale(LC_ALL, "");
  960. /* See if we should be come the http client - we do this for http
  961. proxy urls */
  962. if (getenv("ftp_proxy") != 0)
  963. {
  964. URI Proxy = string(getenv("ftp_proxy"));
  965. // Run the HTTP method
  966. if (Proxy.Access == "http")
  967. {
  968. // Copy over the environment setting
  969. char S[300];
  970. snprintf(S,sizeof(S),"http_proxy=%s",getenv("ftp_proxy"));
  971. putenv(S);
  972. putenv((char *)"no_proxy=");
  973. // Run the http method
  974. string Path = flNotFile(argv[0]) + "http";
  975. execl(Path.c_str(),Path.c_str(),(char *)NULL);
  976. cerr << _("Unable to invoke ") << Path << endl;
  977. exit(100);
  978. }
  979. }
  980. FtpMethod Mth;
  981. return Mth.Run();
  982. }