ftp.cc 30 KB

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