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.
 
 
 
 
 
 

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