ftp.cc 31 KB

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