ftp.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.7 1999/04/17 23:18:11 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. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/acquire-method.h>
  15. #include <apt-pkg/error.h>
  16. #include <apt-pkg/md5.h>
  17. #include <sys/stat.h>
  18. #include <sys/time.h>
  19. #include <utime.h>
  20. #include <unistd.h>
  21. #include <signal.h>
  22. #include <stdio.h>
  23. #include <errno.h>
  24. #include <stdarg.h>
  25. // Internet stuff
  26. #include <netinet/in.h>
  27. #include <sys/socket.h>
  28. #include <arpa/inet.h>
  29. #include <netdb.h>
  30. #include "ftp.h"
  31. /*}}}*/
  32. unsigned long TimeOut = 120;
  33. URI Proxy;
  34. string FtpMethod::FailFile;
  35. int FtpMethod::FailFd = -1;
  36. time_t FtpMethod::FailTime = 0;
  37. // FTPConn::FTPConn - Constructor /*{{{*/
  38. // ---------------------------------------------------------------------
  39. /* */
  40. FTPConn::FTPConn(URI Srv) : Len(0), ServerFd(-1), DataFd(-1),
  41. DataListenFd(-1), ServerName(Srv)
  42. {
  43. Debug = _config->FindB("Debug::Acquire::Ftp",false);
  44. memset(&PasvAddr,0,sizeof(PasvAddr));
  45. }
  46. /*}}}*/
  47. // FTPConn::~FTPConn - Destructor /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* */
  50. FTPConn::~FTPConn()
  51. {
  52. Close();
  53. }
  54. /*}}}*/
  55. // FTPConn::Close - Close down the connection /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* Just tear down the socket and data socket */
  58. void FTPConn::Close()
  59. {
  60. close(ServerFd);
  61. ServerFd = -1;
  62. close(DataFd);
  63. DataFd = -1;
  64. close(DataListenFd);
  65. DataListenFd = -1;
  66. memset(&PasvAddr,0,sizeof(PasvAddr));
  67. }
  68. /*}}}*/
  69. // FTPConn::Open - Open a new connection /*{{{*/
  70. // ---------------------------------------------------------------------
  71. /* Connect to the server using a non-blocking connection and perform a
  72. login. */
  73. string LastHost;
  74. in_addr LastHostA;
  75. bool FTPConn::Open(pkgAcqMethod *Owner)
  76. {
  77. // Use the already open connection if possible.
  78. if (ServerFd != -1)
  79. return true;
  80. Close();
  81. // Determine the proxy setting
  82. if (getenv("ftp_proxy") == 0)
  83. {
  84. string DefProxy = _config->Find("Acquire::ftp::Proxy");
  85. string SpecificProxy = _config->Find("Acquire::ftp::Proxy::" + ServerName.Host);
  86. if (SpecificProxy.empty() == false)
  87. {
  88. if (SpecificProxy == "DIRECT")
  89. Proxy = "";
  90. else
  91. Proxy = SpecificProxy;
  92. }
  93. else
  94. Proxy = DefProxy;
  95. }
  96. else
  97. Proxy = getenv("ftp_proxy");
  98. // Determine what host and port to use based on the proxy settings
  99. int Port = 21;
  100. string Host;
  101. if (Proxy.empty() == true)
  102. {
  103. if (ServerName.Port != 0)
  104. Port = ServerName.Port;
  105. Host = ServerName.Host;
  106. }
  107. else
  108. {
  109. if (Proxy.Port != 0)
  110. Port = Proxy.Port;
  111. Host = Proxy.Host;
  112. }
  113. /* We used a cached address record.. Yes this is against the spec but
  114. the way we have setup our rotating dns suggests that this is more
  115. sensible */
  116. if (LastHost != Host)
  117. {
  118. Owner->Status("Connecting to %s",Host.c_str());
  119. // Lookup the host
  120. hostent *Addr = gethostbyname(Host.c_str());
  121. if (Addr == 0 || Addr->h_addr_list[0] == 0)
  122. return _error->Error("Could not resolve '%s'",Host.c_str());
  123. LastHost = Host;
  124. LastHostA = *(in_addr *)(Addr->h_addr_list[0]);
  125. }
  126. Owner->Status("Connecting to %s (%s)",Host.c_str(),inet_ntoa(LastHostA));
  127. // Get a socket
  128. if ((ServerFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  129. return _error->Errno("socket","Could not create a socket");
  130. // Connect to the server
  131. struct sockaddr_in server;
  132. server.sin_family = AF_INET;
  133. server.sin_port = htons(Port);
  134. server.sin_addr = LastHostA;
  135. SetNonBlock(ServerFd,true);
  136. if (connect(ServerFd,(sockaddr *)&server,sizeof(server)) < 0 &&
  137. errno != EINPROGRESS)
  138. return _error->Errno("socket","Could not create a socket");
  139. Peer = server;
  140. /* This implements a timeout for connect by opening the connection
  141. nonblocking */
  142. if (WaitFd(ServerFd,true,TimeOut) == false)
  143. return _error->Error("Could not connect, connection timed out");
  144. unsigned int Err;
  145. unsigned int Len = sizeof(Err);
  146. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  147. return _error->Errno("getsockopt","Failed");
  148. if (Err != 0)
  149. return _error->Error("Could not connect.");
  150. Owner->Status("Logging in");
  151. return Login();
  152. }
  153. /*}}}*/
  154. // FTPConn::Login - Login to the remote server /*{{{*/
  155. // ---------------------------------------------------------------------
  156. /* This performs both normal login and proxy login using a simples script
  157. stored in the config file. */
  158. bool FTPConn::Login()
  159. {
  160. unsigned int Tag;
  161. string Msg;
  162. // Setup the variables needed for authentication
  163. string User = "anonymous";
  164. string Pass = "apt_get_ftp_2.0@debian.linux.user";
  165. // Fill in the user/pass
  166. if (ServerName.User.empty() == false)
  167. User = ServerName.User;
  168. if (ServerName.Password.empty() == false)
  169. Pass = ServerName.Password;
  170. // Perform simple login
  171. if (Proxy.empty() == true)
  172. {
  173. // Read the initial response
  174. if (ReadResp(Tag,Msg) == false)
  175. return false;
  176. if (Tag >= 400)
  177. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  178. // Send the user
  179. if (WriteMsg(Tag,Msg,"USER %s",User.c_str()) == false)
  180. return false;
  181. if (Tag >= 400)
  182. return _error->Error("USER failed, server said: %s",Msg.c_str());
  183. // Send the Password
  184. if (WriteMsg(Tag,Msg,"PASS %s",Pass.c_str()) == false)
  185. return false;
  186. if (Tag >= 400)
  187. return _error->Error("PASS failed, server said: %s",Msg.c_str());
  188. // Enter passive mode
  189. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  190. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  191. else
  192. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  193. }
  194. else
  195. {
  196. // Read the initial response
  197. if (ReadResp(Tag,Msg) == false)
  198. return false;
  199. if (Tag >= 400)
  200. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  201. // Perform proxy script execution
  202. Configuration::Item const *Opts = _config->Tree("Acquire::ftp::ProxyLogin");
  203. if (Opts == 0 || Opts->Child == 0)
  204. return _error->Error("A proxy server was specified but no login "
  205. "script, Acquire::ftp::ProxyLogin is empty.");
  206. Opts = Opts->Child;
  207. // Iterate over the entire login script
  208. for (; Opts != 0; Opts = Opts->Next)
  209. {
  210. if (Opts->Value.empty() == true)
  211. continue;
  212. // Substitute the variables into the command
  213. char SitePort[20];
  214. if (ServerName.Port != 0)
  215. sprintf(SitePort,"%u",ServerName.Port);
  216. else
  217. strcpy(SitePort,"21");
  218. string Tmp = Opts->Value;
  219. Tmp = SubstVar(Tmp,"$(PROXY_USER)",Proxy.User);
  220. Tmp = SubstVar(Tmp,"$(PROXY_PASS)",Proxy.Password);
  221. Tmp = SubstVar(Tmp,"$(SITE_USER)",User);
  222. Tmp = SubstVar(Tmp,"$(SITE_PASS)",Pass);
  223. Tmp = SubstVar(Tmp,"$(SITE_PORT)",SitePort);
  224. Tmp = SubstVar(Tmp,"$(SITE)",ServerName.Host);
  225. // Send the command
  226. if (WriteMsg(Tag,Msg,"%s",Tmp.c_str()) == false)
  227. return false;
  228. if (Tag >= 400)
  229. return _error->Error("Login script command '%s' failed, server said: %s",Tmp.c_str(),Msg.c_str());
  230. }
  231. // Enter passive mode
  232. TryPassive = false;
  233. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true)
  234. TryPassive = _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true);
  235. else
  236. {
  237. if (_config->Exists("Acquire::FTP::Proxy::Passive") == true)
  238. TryPassive = _config->FindB("Acquire::FTP::Proxy::Passive",true);
  239. else
  240. TryPassive = _config->FindB("Acquire::FTP::Passive",true);
  241. }
  242. }
  243. // Binary mode
  244. if (WriteMsg(Tag,Msg,"TYPE I") == false)
  245. return false;
  246. if (Tag >= 400)
  247. return _error->Error("TYPE failed, server said: %s",Msg.c_str());
  248. return true;
  249. }
  250. /*}}}*/
  251. // FTPConn::ReadLine - Read a line from the server /*{{{*/
  252. // ---------------------------------------------------------------------
  253. /* This performs a very simple buffered read. */
  254. bool FTPConn::ReadLine(string &Text)
  255. {
  256. if (ServerFd == -1)
  257. return false;
  258. // Suck in a line
  259. while (Len < sizeof(Buffer))
  260. {
  261. // Scan the buffer for a new line
  262. for (unsigned int I = 0; I != Len; I++)
  263. {
  264. // Escape some special chars
  265. if (Buffer[I] == 0)
  266. Buffer[I] = '?';
  267. // End of line?
  268. if (Buffer[I] != '\n')
  269. continue;
  270. I++;
  271. Text = string(Buffer,I);
  272. memmove(Buffer,Buffer+I,Len - I);
  273. Len -= I;
  274. return true;
  275. }
  276. // Wait for some data..
  277. if (WaitFd(ServerFd,false,TimeOut) == false)
  278. {
  279. Close();
  280. return _error->Error("Connection timeout");
  281. }
  282. // Suck it back
  283. int Res = read(ServerFd,Buffer + Len,sizeof(Buffer) - Len);
  284. if (Res <= 0)
  285. {
  286. Close();
  287. return _error->Errno("read","Read error");
  288. }
  289. Len += Res;
  290. }
  291. return _error->Error("A response overflowed the buffer.");
  292. }
  293. /*}}}*/
  294. // FTPConn::ReadResp - Read a full response from the server /*{{{*/
  295. // ---------------------------------------------------------------------
  296. /* This reads a reply code from the server, it handles both p */
  297. bool FTPConn::ReadResp(unsigned int &Ret,string &Text)
  298. {
  299. // Grab the first line of the response
  300. string Msg;
  301. if (ReadLine(Msg) == false)
  302. return false;
  303. // Get the ID code
  304. char *End;
  305. Ret = strtol(Msg.c_str(),&End,10);
  306. if (End - Msg.c_str() != 3)
  307. return _error->Error("Protocol corruption");
  308. // All done ?
  309. Text = Msg.c_str()+4;
  310. if (*End == ' ')
  311. {
  312. if (Debug == true)
  313. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  314. return true;
  315. }
  316. if (*End != '-')
  317. return _error->Error("Protocol corruption");
  318. /* Okay, here we do the continued message trick. This is foolish, but
  319. proftpd follows the protocol as specified and wu-ftpd doesn't, so
  320. we filter. I wonder how many clients break if you use proftpd and
  321. put a '- in the 3rd spot in the message? */
  322. char Leader[4];
  323. strncpy(Leader,Msg.c_str(),3);
  324. Leader[3] = 0;
  325. while (ReadLine(Msg) == true)
  326. {
  327. // Short, it must be using RFC continuation..
  328. if (Msg.length() < 4)
  329. {
  330. Text += Msg;
  331. continue;
  332. }
  333. // Oops, finished
  334. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == ' ')
  335. {
  336. Text += Msg.c_str()+4;
  337. break;
  338. }
  339. // This message has the wu-ftpd style reply code prefixed
  340. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == '-')
  341. {
  342. Text += Msg.c_str()+4;
  343. continue;
  344. }
  345. // Must be RFC style prefixing
  346. Text += Msg;
  347. }
  348. if (Debug == true && _error->PendingError() == false)
  349. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  350. return !_error->PendingError();
  351. }
  352. /*}}}*/
  353. // FTPConn::WriteMsg - Send a message to the server /*{{{*/
  354. // ---------------------------------------------------------------------
  355. /* Simple printf like function.. */
  356. bool FTPConn::WriteMsg(unsigned int &Ret,string &Text,const char *Fmt,...)
  357. {
  358. va_list args;
  359. va_start(args,Fmt);
  360. // sprintf the description
  361. char S[400];
  362. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  363. strcat(S,"\r\n");
  364. if (Debug == true)
  365. cerr << "-> '" << QuoteString(S,"") << "'" << endl;
  366. // Send it off
  367. unsigned long Len = strlen(S);
  368. unsigned long Start = 0;
  369. while (Len != 0)
  370. {
  371. if (WaitFd(ServerFd,true,TimeOut) == false)
  372. {
  373. Close();
  374. return _error->Error("Connection timeout");
  375. }
  376. int Res = write(ServerFd,S + Start,Len);
  377. if (Res <= 0)
  378. {
  379. Close();
  380. return _error->Errno("write","Write Error");
  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. Borrowed mostly from lftp. We have to enter passive mode every time
  393. we make a data connection :| */
  394. bool FTPConn::GoPasv()
  395. {
  396. // Try to enable pasv mode
  397. unsigned int Tag;
  398. string Msg;
  399. if (WriteMsg(Tag,Msg,"PASV") == false)
  400. return false;
  401. // Unsupported function
  402. string::size_type Pos = Msg.find('(');
  403. if (Tag >= 400 || Pos == string::npos)
  404. {
  405. memset(&PasvAddr,0,sizeof(PasvAddr));
  406. return true;
  407. }
  408. // Scan it
  409. unsigned a0,a1,a2,a3,p0,p1;
  410. if (sscanf(Msg.c_str() + Pos,"(%u,%u,%u,%u,%u,%u)",&a0,&a1,&a2,&a3,&p0,&p1) != 6)
  411. {
  412. memset(&PasvAddr,0,sizeof(PasvAddr));
  413. return true;
  414. }
  415. // lftp used this horrid byte order manipulation.. Ik.
  416. PasvAddr.sin_family = AF_INET;
  417. unsigned char *a;
  418. unsigned char *p;
  419. a = (unsigned char *)&PasvAddr.sin_addr;
  420. p = (unsigned char *)&PasvAddr.sin_port;
  421. // Some evil servers return 0 to mean their addr
  422. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  423. {
  424. PasvAddr.sin_addr = Peer.sin_addr;
  425. }
  426. else
  427. {
  428. a[0] = a0;
  429. a[1] = a1;
  430. a[2] = a2;
  431. a[3] = a3;
  432. }
  433. p[0] = p0;
  434. p[1] = p1;
  435. return true;
  436. }
  437. /*}}}*/
  438. // FTPConn::Size - Return the size of a file /*{{{*/
  439. // ---------------------------------------------------------------------
  440. /* Grab the file size from the server, 0 means no size or empty file */
  441. bool FTPConn::Size(const char *Path,unsigned long &Size)
  442. {
  443. // Query the size
  444. unsigned int Tag;
  445. string Msg;
  446. Size = 0;
  447. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  448. return false;
  449. char *End;
  450. Size = strtol(Msg.c_str(),&End,10);
  451. if (Tag >= 400 || End == Msg.c_str())
  452. Size = 0;
  453. return true;
  454. }
  455. /*}}}*/
  456. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  457. // ---------------------------------------------------------------------
  458. /* Like Size no error is returned if the command is not supported. If the
  459. command fails then time is set to the current time of day to fool
  460. date checks. */
  461. bool FTPConn::ModTime(const char *Path, time_t &Time)
  462. {
  463. Time = time(&Time);
  464. // Query the mod time
  465. unsigned int Tag;
  466. string Msg;
  467. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  468. return false;
  469. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  470. return true;
  471. // Parse it
  472. struct tm tm;
  473. memset(&tm,0,sizeof(tm));
  474. if (sscanf(Msg.c_str(),"%4d%2d%2d%2d%2d%2d",&tm.tm_year,&tm.tm_mon,
  475. &tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec) != 6)
  476. return true;
  477. tm.tm_year -= 1900;
  478. tm.tm_mon--;
  479. /* We use timegm from the GNU C library, libapt-pkg will provide this
  480. symbol if it does not exist */
  481. Time = timegm(&tm);
  482. return true;
  483. }
  484. /*}}}*/
  485. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  486. // ---------------------------------------------------------------------
  487. /* Create the data connection. Call FinalizeDataFd after this though.. */
  488. bool FTPConn::CreateDataFd()
  489. {
  490. close(DataFd);
  491. DataFd = -1;
  492. // Attempt to enter passive mode.
  493. if (TryPassive == true)
  494. {
  495. if (GoPasv() == false)
  496. return false;
  497. // Oops, didn't work out, don't bother trying again.
  498. if (PasvAddr.sin_port == 0)
  499. TryPassive = false;
  500. }
  501. // Passive mode?
  502. if (PasvAddr.sin_port != 0)
  503. {
  504. // Get a socket
  505. if ((DataFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  506. return _error->Errno("socket","Could not create a socket");
  507. // Connect to the server
  508. SetNonBlock(DataFd,true);
  509. if (connect(DataFd,(sockaddr *)&PasvAddr,sizeof(PasvAddr)) < 0 &&
  510. errno != EINPROGRESS)
  511. return _error->Errno("socket","Could not create a socket");
  512. /* This implements a timeout for connect by opening the connection
  513. nonblocking */
  514. if (WaitFd(ServerFd,true,TimeOut) == false)
  515. return _error->Error("Could not connect data socket, connection timed out");
  516. unsigned int Err;
  517. unsigned int Len = sizeof(Err);
  518. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  519. return _error->Errno("getsockopt","Failed");
  520. if (Err != 0)
  521. return _error->Error("Could not connect.");
  522. return true;
  523. }
  524. // Port mode :<
  525. close(DataListenFd);
  526. DataListenFd = -1;
  527. // Get a socket
  528. if ((DataListenFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  529. return _error->Errno("socket","Could not create a socket");
  530. // Bind and listen
  531. sockaddr_in Addr;
  532. memset(&Addr,0,sizeof(Addr));
  533. if (bind(DataListenFd,(sockaddr *)&Addr,sizeof(Addr)) < 0)
  534. return _error->Errno("bind","Could not bind a socket");
  535. if (listen(DataListenFd,1) < 0)
  536. return _error->Errno("listen","Could not listen on the socket");
  537. SetNonBlock(DataListenFd,true);
  538. // Determine the name to send to the remote
  539. sockaddr_in Addr2;
  540. socklen_t Jnk = sizeof(Addr);
  541. if (getsockname(DataListenFd,(sockaddr *)&Addr,&Jnk) < 0)
  542. return _error->Errno("getsockname","Could not determine the socket's name");
  543. Jnk = sizeof(Addr2);
  544. if (getsockname(ServerFd,(sockaddr *)&Addr2,&Jnk) < 0)
  545. return _error->Errno("getsockname","Could not determine the socket's name");
  546. // This bit ripped from qftp
  547. unsigned long badr = ntohl(*(unsigned long *)&Addr2.sin_addr);
  548. unsigned long bp = ntohs(Addr.sin_port);
  549. // Send the port command
  550. unsigned int Tag;
  551. string Msg;
  552. if (WriteMsg(Tag,Msg,"PORT %d,%d,%d,%d,%d,%d",
  553. (int) (badr >> 24) & 0xff, (int) (badr >> 16) & 0xff,
  554. (int) (badr >> 8) & 0xff, (int) badr & 0xff,
  555. (int) (bp >> 8) & 0xff, (int) bp & 0xff) == false)
  556. return false;
  557. if (Tag >= 400)
  558. return _error->Error("Unable to send port command");
  559. return true;
  560. }
  561. /*}}}*/
  562. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  563. // ---------------------------------------------------------------------
  564. /* If the connection is in port mode this waits for the other end to hook
  565. up to us. */
  566. bool FTPConn::Finalize()
  567. {
  568. // Passive mode? Do nothing
  569. if (PasvAddr.sin_port != 0)
  570. return true;
  571. // Close any old socket..
  572. close(DataFd);
  573. DataFd = -1;
  574. // Wait for someone to connect..
  575. if (WaitFd(DataListenFd,false,TimeOut) == false)
  576. return _error->Error("Data socket connect timed out");
  577. // Accept the connection
  578. struct sockaddr_in Addr;
  579. socklen_t Len = sizeof(Addr);
  580. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  581. if (DataFd < 0)
  582. return _error->Errno("accept","Unable to accept connection");
  583. close(DataListenFd);
  584. DataListenFd = -1;
  585. return true;
  586. }
  587. /*}}}*/
  588. // FTPConn::Get - Get a file /*{{{*/
  589. // ---------------------------------------------------------------------
  590. /* This opens a data connection, sends REST and RETR and then
  591. transfers the file over. */
  592. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume,
  593. MD5Summation &MD5,bool &Missing)
  594. {
  595. Missing = false;
  596. if (CreateDataFd() == false)
  597. return false;
  598. unsigned int Tag;
  599. string Msg;
  600. if (Resume != 0)
  601. {
  602. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  603. return false;
  604. if (Tag >= 400)
  605. Resume = 0;
  606. }
  607. if (To.Truncate(Resume) == false)
  608. return false;
  609. if (To.Seek(0) == false)
  610. return false;
  611. if (Resume != 0)
  612. {
  613. if (MD5.AddFD(To.Fd(),Resume) == false)
  614. {
  615. _error->Errno("read","Problem hashing file");
  616. return false;
  617. }
  618. }
  619. // Send the get command
  620. if (WriteMsg(Tag,Msg,"RETR %s",Path) == false)
  621. return false;
  622. if (Tag >= 400)
  623. {
  624. if (Tag == 550)
  625. Missing = true;
  626. return _error->Error("Unable to fetch file, server said '%s'",Msg.c_str());
  627. }
  628. // Finish off the data connection
  629. if (Finalize() == false)
  630. return false;
  631. // Copy loop
  632. unsigned char Buffer[4096];
  633. while (1)
  634. {
  635. // Wait for some data..
  636. if (WaitFd(DataFd,false,TimeOut) == false)
  637. {
  638. Close();
  639. return _error->Error("Data socket timed out");
  640. }
  641. // Read the data..
  642. int Res = read(DataFd,Buffer,sizeof(Buffer));
  643. if (Res == 0)
  644. break;
  645. if (Res < 0)
  646. {
  647. if (errno == EAGAIN)
  648. continue;
  649. break;
  650. }
  651. MD5.Add(Buffer,Res);
  652. if (To.Write(Buffer,Res) == false)
  653. {
  654. Close();
  655. return false;
  656. }
  657. }
  658. // All done
  659. close(DataFd);
  660. DataFd = -1;
  661. // Read the closing message from the server
  662. if (ReadResp(Tag,Msg) == false)
  663. return false;
  664. if (Tag >= 400)
  665. return _error->Error("Data transfer failed, server said '%s'",Msg.c_str());
  666. return true;
  667. }
  668. /*}}}*/
  669. // FtpMethod::FtpMethod - Constructor /*{{{*/
  670. // ---------------------------------------------------------------------
  671. /* */
  672. FtpMethod::FtpMethod() : pkgAcqMethod("1.0",SendConfig)
  673. {
  674. signal(SIGTERM,SigTerm);
  675. signal(SIGINT,SigTerm);
  676. Server = 0;
  677. FailFd = -1;
  678. }
  679. /*}}}*/
  680. // FtpMethod::SigTerm - Handle a fatal signal /*{{{*/
  681. // ---------------------------------------------------------------------
  682. /* This closes and timestamps the open file. This is neccessary to get
  683. resume behavoir on user abort */
  684. void FtpMethod::SigTerm(int)
  685. {
  686. if (FailFd == -1)
  687. exit(100);
  688. close(FailFd);
  689. // Timestamp
  690. struct utimbuf UBuf;
  691. UBuf.actime = FailTime;
  692. UBuf.modtime = FailTime;
  693. utime(FailFile.c_str(),&UBuf);
  694. exit(100);
  695. }
  696. /*}}}*/
  697. // FtpMethod::Configuration - Handle a configuration message /*{{{*/
  698. // ---------------------------------------------------------------------
  699. /* We stash the desired pipeline depth */
  700. bool FtpMethod::Configuration(string Message)
  701. {
  702. if (pkgAcqMethod::Configuration(Message) == false)
  703. return false;
  704. TimeOut = _config->FindI("Acquire::Ftp::Timeout",TimeOut);
  705. return true;
  706. }
  707. /*}}}*/
  708. // FtpMethod::Fetch - Fetch a file /*{{{*/
  709. // ---------------------------------------------------------------------
  710. /* Fetch a single file, called by the base class.. */
  711. bool FtpMethod::Fetch(FetchItem *Itm)
  712. {
  713. URI Get = Itm->Uri;
  714. const char *File = Get.Path.c_str();
  715. FetchResult Res;
  716. Res.Filename = Itm->DestFile;
  717. Res.IMSHit = false;
  718. // Connect to the server
  719. if (Server == 0 || Server->Comp(Get) == false)
  720. {
  721. delete Server;
  722. Server = new FTPConn(Get);
  723. }
  724. // Could not connect is a transient error..
  725. if (Server->Open(this) == false)
  726. {
  727. Fail(true);
  728. return true;
  729. }
  730. // Get the files information
  731. Status("Query");
  732. unsigned long Size;
  733. if (Server->Size(File,Size) == false ||
  734. Server->ModTime(File,FailTime) == false)
  735. {
  736. Fail(true);
  737. return true;
  738. }
  739. Res.Size = Size;
  740. // See if it is an IMS hit
  741. if (Itm->LastModified == FailTime)
  742. {
  743. Res.Size = 0;
  744. Res.IMSHit = true;
  745. URIDone(Res);
  746. return true;
  747. }
  748. // See if the file exists
  749. struct stat Buf;
  750. if (stat(Itm->DestFile.c_str(),&Buf) == 0)
  751. {
  752. if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime)
  753. {
  754. Res.Size = Buf.st_size;
  755. Res.LastModified = Buf.st_mtime;
  756. URIDone(Res);
  757. return true;
  758. }
  759. // Resume?
  760. if (FailTime == Buf.st_mtime && Size > (unsigned)Buf.st_size)
  761. Res.ResumePoint = Buf.st_size;
  762. }
  763. // Open the file
  764. MD5Summation MD5;
  765. {
  766. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  767. if (_error->PendingError() == true)
  768. return false;
  769. URIStart(Res);
  770. FailFile = Itm->DestFile;
  771. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  772. FailFd = Fd.Fd();
  773. bool Missing;
  774. if (Server->Get(File,Fd,Res.ResumePoint,MD5,Missing) == false)
  775. {
  776. // If the file is missing we hard fail otherwise transient fail
  777. if (Missing == true)
  778. return false;
  779. Fail(true);
  780. return true;
  781. }
  782. Res.Size = Fd.Size();
  783. }
  784. Res.LastModified = FailTime;
  785. Res.MD5Sum = MD5.Result();
  786. // Timestamp
  787. struct utimbuf UBuf;
  788. time(&UBuf.actime);
  789. UBuf.actime = FailTime;
  790. UBuf.modtime = FailTime;
  791. utime(Queue->DestFile.c_str(),&UBuf);
  792. FailFd = -1;
  793. URIDone(Res);
  794. return true;
  795. }
  796. /*}}}*/
  797. int main()
  798. {
  799. FtpMethod Mth;
  800. return Mth.Run();
  801. }