ftp.cc 31 KB

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