ftp.cc 30 KB

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