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.
 
 
 
 
 
 

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