ftp.cc 30 KB

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