ftp.cc 31 KB

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