ftp.cc 30 KB

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