ftp.cc 31 KB

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