ftp.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: ftp.cc,v 1.2 1999/03/15 07:20:41 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. TryPassive = false;
  190. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true &&
  191. _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true) == true)
  192. {
  193. TryPassive = true;
  194. }
  195. else
  196. {
  197. if (_config->FindB("Acquire::FTP::Passive",true) == true)
  198. TryPassive = true;
  199. }
  200. }
  201. else
  202. {
  203. // Read the initial response
  204. if (ReadResp(Tag,Msg) == false)
  205. return false;
  206. if (Tag >= 400)
  207. return _error->Error("Server refused our connection and said: %s",Msg.c_str());
  208. // Perform proxy script execution
  209. Configuration::Item const *Opts = _config->Tree("Acquire::ftp::ProxyLogin");
  210. if (Opts == 0 || Opts->Child == 0)
  211. return _error->Error("A proxy server was specified but no login "
  212. "script, Acquire::ftp::ProxyLogin is empty.");
  213. Opts = Opts->Child;
  214. // Iterate over the entire login script
  215. for (; Opts != 0; Opts = Opts->Next)
  216. {
  217. if (Opts->Value.empty() == true)
  218. continue;
  219. // Substitute the variables into the command
  220. char SitePort[20];
  221. if (ServerName.Port != 0)
  222. sprintf(SitePort,"%u",ServerName.Port);
  223. else
  224. strcat("21",SitePort);
  225. string Tmp = Opts->Value;
  226. Tmp = SubstVar(Tmp,"$(PROXY_USER)",Proxy.User);
  227. Tmp = SubstVar(Tmp,"$(PROXY_PASS)",Proxy.Password);
  228. Tmp = SubstVar(Tmp,"$(SITE_USER)",User);
  229. Tmp = SubstVar(Tmp,"$(SITE_PASS)",Pass);
  230. Tmp = SubstVar(Tmp,"$(SITE_PORT)",SitePort);
  231. Tmp = SubstVar(Tmp,"$(SITE)",ServerName.Host);
  232. // Send the command
  233. if (WriteMsg(Tag,Msg,"%s",Tmp.c_str()) == false)
  234. return false;
  235. if (Tag >= 400)
  236. return _error->Error("Login script command '%s' failed, server said: %s",Tmp.c_str(),Msg.c_str());
  237. }
  238. // Enter passive mode
  239. TryPassive = false;
  240. if (_config->Exists("Acquire::FTP::Passive::" + ServerName.Host) == true &&
  241. _config->FindB("Acquire::FTP::Passive::" + ServerName.Host,true) == true)
  242. {
  243. TryPassive = true;
  244. }
  245. else
  246. {
  247. if (_config->Exists("Acquire::FTP::Proxy::Passive") == true &&
  248. _config->FindB("Acquire::FTP::Proxy::Passive",true) == true)
  249. TryPassive = true;
  250. else
  251. if (_config->FindB("Acquire::FTP::Passive",true) == true)
  252. TryPassive = true;
  253. }
  254. }
  255. // Binary mode
  256. if (WriteMsg(Tag,Msg,"TYPE I") == false)
  257. return false;
  258. if (Tag >= 400)
  259. return _error->Error("TYPE failed, server said: %s",Msg.c_str());
  260. return true;
  261. }
  262. /*}}}*/
  263. // FTPConn::ReadLine - Read a line from the server /*{{{*/
  264. // ---------------------------------------------------------------------
  265. /* This performs a very simple buffered read. */
  266. bool FTPConn::ReadLine(string &Text)
  267. {
  268. // Suck in a line
  269. while (Len < sizeof(Buffer))
  270. {
  271. // Scan the buffer for a new line
  272. for (unsigned int I = 0; I != Len; I++)
  273. {
  274. // Escape some special chars
  275. if (Buffer[I] == 0)
  276. Buffer[I] = '?';
  277. // End of line?
  278. if (Buffer[I] != '\n')
  279. continue;
  280. I++;
  281. Text = string(Buffer,I);
  282. memmove(Buffer,Buffer+I,Len - I);
  283. Len -= I;
  284. return true;
  285. }
  286. // Wait for some data..
  287. if (WaitFd(ServerFd,false,TimeOut) == false)
  288. {
  289. Close();
  290. return _error->Error("Connection timeout");
  291. }
  292. // Suck it back
  293. int Res = read(ServerFd,Buffer,sizeof(Buffer) - Len);
  294. if (Res <= 0)
  295. {
  296. Close();
  297. return _error->Errno("read","Read error");
  298. }
  299. Len += Res;
  300. }
  301. return _error->Error("A response overflowed the buffer.");
  302. }
  303. /*}}}*/
  304. // FTPConn::ReadResp - Read a full response from the server /*{{{*/
  305. // ---------------------------------------------------------------------
  306. /* This reads a reply code from the server, it handles both p */
  307. bool FTPConn::ReadResp(unsigned int &Ret,string &Text)
  308. {
  309. // Grab the first line of the response
  310. string Msg;
  311. if (ReadLine(Msg) == false)
  312. return false;
  313. // Get the ID code
  314. char *End;
  315. Ret = strtol(Msg.c_str(),&End,10);
  316. if (End - Msg.c_str() != 3)
  317. return _error->Error("Protocol corruption");
  318. // All done ?
  319. Text = Msg.c_str()+4;
  320. if (*End == ' ')
  321. {
  322. if (Debug == true)
  323. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  324. return true;
  325. }
  326. if (*End != '-')
  327. return _error->Error("Protocol corruption");
  328. /* Okay, here we do the continued message trick. This is foolish, but
  329. proftpd follows the protocol as specified and wu-ftpd doesn't, so
  330. we filter. I wonder how many clients break if you use proftpd and
  331. put a '- in the 3rd spot in the message? */
  332. char Leader[4];
  333. strncpy(Leader,Msg.c_str(),3);
  334. Leader[3] = 0;
  335. while (ReadLine(Msg) == true)
  336. {
  337. // Short, it must be using RFC continuation..
  338. if (Msg.length() < 4)
  339. {
  340. Text += Msg;
  341. continue;
  342. }
  343. // Oops, finished
  344. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == ' ')
  345. {
  346. Text += Msg.c_str()+4;
  347. break;
  348. }
  349. // This message has the wu-ftpd style reply code prefixed
  350. if (strncmp(Msg.c_str(),Leader,3) == 0 && Msg[3] == '-')
  351. {
  352. Text += Msg.c_str()+4;
  353. continue;
  354. }
  355. // Must be RFC style prefixing
  356. Text += Msg;
  357. }
  358. if (Debug == true && _error->PendingError() == false)
  359. cerr << "<- '" << QuoteString(Text,"") << "'" << endl;
  360. return !_error->PendingError();
  361. }
  362. /*}}}*/
  363. // FTPConn::WriteMsg - Send a message to the server /*{{{*/
  364. // ---------------------------------------------------------------------
  365. /* Simple printf like function.. */
  366. bool FTPConn::WriteMsg(unsigned int &Ret,string &Text,const char *Fmt,...)
  367. {
  368. va_list args;
  369. va_start(args,Fmt);
  370. // sprintf the description
  371. char S[400];
  372. vsnprintf(S,sizeof(S) - 4,Fmt,args);
  373. strcat(S,"\r\n");
  374. if (Debug == true)
  375. cerr << "-> '" << QuoteString(S,"") << "'" << endl;
  376. // Send it off
  377. unsigned long Len = strlen(S);
  378. unsigned long Start = 0;
  379. while (Len != 0)
  380. {
  381. if (WaitFd(ServerFd,true,TimeOut) == false)
  382. {
  383. Close();
  384. return _error->Error("Connection timeout");
  385. }
  386. int Res = write(ServerFd,S + Start,Len);
  387. if (Res <= 0)
  388. {
  389. Close();
  390. return _error->Errno("write","Write Error");
  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. Borrowed mostly from lftp. We have to enter passive mode every time
  403. we make a data connection :| */
  404. bool FTPConn::GoPasv()
  405. {
  406. // Try to enable pasv mode
  407. unsigned int Tag;
  408. string Msg;
  409. if (WriteMsg(Tag,Msg,"PASV") == false)
  410. return false;
  411. // Unsupported function
  412. string::size_type Pos = Msg.find('(');
  413. if (Tag >= 400 || Pos == string::npos)
  414. {
  415. memset(&PasvAddr,0,sizeof(PasvAddr));
  416. return true;
  417. }
  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. {
  422. memset(&PasvAddr,0,sizeof(PasvAddr));
  423. return true;
  424. }
  425. // lftp used this horrid byte order manipulation.. Ik.
  426. PasvAddr.sin_family = AF_INET;
  427. unsigned char *a;
  428. unsigned char *p;
  429. a = (unsigned char *)&PasvAddr.sin_addr;
  430. p = (unsigned char *)&PasvAddr.sin_port;
  431. // Some evil servers return 0 to mean their addr
  432. if (a0 == 0 && a1 == 0 && a2 == 0 && a3 == 0)
  433. {
  434. PasvAddr.sin_addr = Peer.sin_addr;
  435. }
  436. else
  437. {
  438. a[0] = a0;
  439. a[1] = a1;
  440. a[2] = a2;
  441. a[3] = a3;
  442. }
  443. p[0] = p0;
  444. p[1] = p1;
  445. return true;
  446. }
  447. /*}}}*/
  448. // FTPConn::Size - Return the size of a file /*{{{*/
  449. // ---------------------------------------------------------------------
  450. /* Grab the file size from the server, 0 means no size or empty file */
  451. bool FTPConn::Size(const char *Path,unsigned long &Size)
  452. {
  453. // Query the size
  454. unsigned int Tag;
  455. string Msg;
  456. Size = 0;
  457. if (WriteMsg(Tag,Msg,"SIZE %s",Path) == false)
  458. return false;
  459. char *End;
  460. Size = strtol(Msg.c_str(),&End,10);
  461. if (Tag >= 400 || End == Msg.c_str())
  462. Size = 0;
  463. return true;
  464. }
  465. /*}}}*/
  466. // FTPConn::ModTime - Return the modification time of the file /*{{{*/
  467. // ---------------------------------------------------------------------
  468. /* Like Size no error is returned if the command is not supported. If the
  469. command fails then time is set to the current time of day to fool
  470. date checks. */
  471. bool FTPConn::ModTime(const char *Path, time_t &Time)
  472. {
  473. Time = time(&Time);
  474. // Query the mod time
  475. unsigned int Tag;
  476. string Msg;
  477. if (WriteMsg(Tag,Msg,"MDTM %s",Path) == false)
  478. return false;
  479. if (Tag >= 400 || Msg.empty() == true || isdigit(Msg[0]) == 0)
  480. return true;
  481. // Parse it
  482. struct tm tm;
  483. memset(&tm,0,sizeof(tm));
  484. if (sscanf(Msg.c_str(),"%4d%2d%2d%2d%2d%2d",&tm.tm_year,&tm.tm_mon,
  485. &tm.tm_mday,&tm.tm_hour,&tm.tm_min,&tm.tm_sec) != 6)
  486. return true;
  487. tm.tm_year -= 1900;
  488. tm.tm_mon--;
  489. /* We use timegm from the GNU C library, libapt-pkg will provide this
  490. symbol if it does not exist */
  491. Time = timegm(&tm);
  492. return true;
  493. }
  494. /*}}}*/
  495. // FTPConn::CreateDataFd - Get a data connection /*{{{*/
  496. // ---------------------------------------------------------------------
  497. /* Create the data connection. Call FinalizeDataFd after this though.. */
  498. bool FTPConn::CreateDataFd()
  499. {
  500. close(DataFd);
  501. DataFd = -1;
  502. // Attempt to enter passive mode.
  503. if (TryPassive == true)
  504. {
  505. if (GoPasv() == false)
  506. return false;
  507. // Oops, didn't work out, don't bother trying again.
  508. if (PasvAddr.sin_port == 0)
  509. TryPassive = false;
  510. }
  511. // Passive mode?
  512. if (PasvAddr.sin_port != 0)
  513. {
  514. // Get a socket
  515. if ((DataFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  516. return _error->Errno("socket","Could not create a socket");
  517. // Connect to the server
  518. SetNonBlock(DataFd,true);
  519. if (connect(DataFd,(sockaddr *)&PasvAddr,sizeof(PasvAddr)) < 0 &&
  520. errno != EINPROGRESS)
  521. return _error->Errno("socket","Could not create a socket");
  522. /* This implements a timeout for connect by opening the connection
  523. nonblocking */
  524. if (WaitFd(ServerFd,true,TimeOut) == false)
  525. return _error->Error("Could not connect data socket, connection timed out");
  526. unsigned int Err;
  527. unsigned int Len = sizeof(Err);
  528. if (getsockopt(ServerFd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  529. return _error->Errno("getsockopt","Failed");
  530. if (Err != 0)
  531. return _error->Error("Could not connect.");
  532. return true;
  533. }
  534. // Port mode :<
  535. if (DataListenFd == -1)
  536. {
  537. // Get a socket
  538. if ((DataListenFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  539. return _error->Errno("socket","Could not create a socket");
  540. // Bind and listen
  541. sockaddr_in Addr;
  542. memset(&Addr,0,sizeof(Addr));
  543. if (bind(DataListenFd,(sockaddr *)&Addr,sizeof(Addr)) < 0)
  544. return _error->Errno("bind","Could not bind a socket");
  545. if (listen(DataListenFd,1) < 0)
  546. return _error->Errno("listen","Could not listen on the socket");
  547. SetNonBlock(DataListenFd,true);
  548. }
  549. // Determine the name to send to the remote
  550. sockaddr_in Addr;
  551. sockaddr_in Addr2;
  552. socklen_t Jnk = sizeof(Addr);
  553. if (getsockname(DataListenFd,(sockaddr *)&Addr,&Jnk) < 0)
  554. return _error->Errno("getsockname","Could not determine the socket's name");
  555. Jnk = sizeof(Addr2);
  556. if (getsockname(ServerFd,(sockaddr *)&Addr2,&Jnk) < 0)
  557. return _error->Errno("getsockname","Could not determine the socket's name");
  558. // This bit ripped from qftp
  559. unsigned long badr = ntohl(*(unsigned long *)&Addr2.sin_addr);
  560. unsigned long bp = ntohs(Addr.sin_port);
  561. // Send the port command
  562. unsigned int Tag;
  563. string Msg;
  564. if (WriteMsg(Tag,Msg,"PORT %d,%d,%d,%d,%d,%d",
  565. (int) (badr >> 24) & 0xff, (int) (badr >> 16) & 0xff,
  566. (int) (badr >> 8) & 0xff, (int) badr & 0xff,
  567. (int) (bp >> 8) & 0xff, (int) bp & 0xff) == false)
  568. return false;
  569. if (Tag >= 400)
  570. return _error->Error("Unable to send port command");
  571. return true;
  572. }
  573. /*}}}*/
  574. // FTPConn::Finalize - Complete the Data connection /*{{{*/
  575. // ---------------------------------------------------------------------
  576. /* If the connection is in port mode this waits for the other end to hook
  577. up to us. */
  578. bool FTPConn::Finalize()
  579. {
  580. // Passive mode? Do nothing
  581. if (PasvAddr.sin_port != 0)
  582. return true;
  583. // Close any old socket..
  584. close(DataFd);
  585. DataFd = -1;
  586. // Wait for someone to connect..
  587. if (WaitFd(DataListenFd,false,TimeOut) == false)
  588. return _error->Error("Data socket connect timed out");
  589. // Accept the connection
  590. struct sockaddr_in Addr;
  591. socklen_t Len = sizeof(Addr);
  592. DataFd = accept(DataListenFd,(struct sockaddr *)&Addr,&Len);
  593. if (DataFd < 0)
  594. return _error->Errno("accept","Unable to accept connection");
  595. return true;
  596. }
  597. /*}}}*/
  598. // FTPConn::Get - Get a file /*{{{*/
  599. // ---------------------------------------------------------------------
  600. /* This opens a data connection, sends REST and RETR and then
  601. transfers the file over. */
  602. bool FTPConn::Get(const char *Path,FileFd &To,unsigned long Resume,
  603. MD5Summation &MD5,bool &Missing)
  604. {
  605. Missing = false;
  606. if (CreateDataFd() == false)
  607. return false;
  608. unsigned int Tag;
  609. string Msg;
  610. if (Resume != 0)
  611. {
  612. if (WriteMsg(Tag,Msg,"REST %u",Resume) == false)
  613. return false;
  614. if (Tag >= 400)
  615. Resume = 0;
  616. }
  617. if (To.Truncate(Resume) == false)
  618. return false;
  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. return _error->Error("Data socket connect timed out");
  638. // Read the data..
  639. int Res = read(DataFd,Buffer,sizeof(Buffer));
  640. if (Res == 0)
  641. break;
  642. if (Res < 0)
  643. {
  644. if (errno == EAGAIN)
  645. continue;
  646. break;
  647. }
  648. if (To.Write(Buffer,Res) == false)
  649. return false;
  650. }
  651. // All done
  652. close(DataFd);
  653. DataFd = -1;
  654. // Read the closing message from the server
  655. if (ReadResp(Tag,Msg) == false)
  656. return false;
  657. if (Tag >= 400)
  658. return _error->Error("Data transfer failed, server said '%s'",Msg.c_str());
  659. return true;
  660. }
  661. /*}}}*/
  662. // FtpMethod::FtpMethod - Constructor /*{{{*/
  663. // ---------------------------------------------------------------------
  664. /* */
  665. FtpMethod::FtpMethod() : pkgAcqMethod("1.0",SendConfig)
  666. {
  667. signal(SIGTERM,SigTerm);
  668. signal(SIGINT,SigTerm);
  669. Server = 0;
  670. FailFd = -1;
  671. }
  672. /*}}}*/
  673. // FtpMethod::SigTerm - Handle a fatal signal /*{{{*/
  674. // ---------------------------------------------------------------------
  675. /* This closes and timestamps the open file. This is neccessary to get
  676. resume behavoir on user abort */
  677. void FtpMethod::SigTerm(int)
  678. {
  679. if (FailFd == -1)
  680. exit(100);
  681. close(FailFd);
  682. // Timestamp
  683. struct utimbuf UBuf;
  684. UBuf.actime = FailTime;
  685. UBuf.modtime = FailTime;
  686. utime(FailFile.c_str(),&UBuf);
  687. exit(100);
  688. }
  689. /*}}}*/
  690. // FtpMethod::Configuration - Handle a configuration message /*{{{*/
  691. // ---------------------------------------------------------------------
  692. /* We stash the desired pipeline depth */
  693. bool FtpMethod::Configuration(string Message)
  694. {
  695. if (pkgAcqMethod::Configuration(Message) == false)
  696. return false;
  697. TimeOut = _config->FindI("Acquire::Ftp::Timeout",TimeOut);
  698. return true;
  699. }
  700. /*}}}*/
  701. // FtpMethod::Fetch - Fetch a file /*{{{*/
  702. // ---------------------------------------------------------------------
  703. /* */
  704. bool FtpMethod::Fetch(FetchItem *Itm)
  705. {
  706. URI Get = Itm->Uri;
  707. const char *File = Get.Path.c_str();
  708. FetchResult Res;
  709. Res.Filename = Itm->DestFile;
  710. Res.IMSHit = false;
  711. // Connect to the server
  712. if (Server == 0 || Server->Comp(Get) == false)
  713. {
  714. delete Server;
  715. Server = new FTPConn(Get);
  716. }
  717. // Could not connect is a transient error..
  718. if (Server->Open(this) == false)
  719. {
  720. Fail(true);
  721. return true;
  722. }
  723. // Get the files information
  724. unsigned long Size;
  725. if (Server->Size(File,Size) == false ||
  726. Server->ModTime(File,FailTime) == false)
  727. {
  728. Fail(true);
  729. return true;
  730. }
  731. Res.Size = Size;
  732. // See if it is an IMS hit
  733. if (Itm->LastModified == FailTime)
  734. {
  735. Res.Size = 0;
  736. Res.IMSHit = true;
  737. URIDone(Res);
  738. return true;
  739. }
  740. // See if the file exists
  741. struct stat Buf;
  742. if (stat(Itm->DestFile.c_str(),&Buf) == 0)
  743. {
  744. if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime)
  745. {
  746. Res.Size = Buf.st_size;
  747. Res.LastModified = Buf.st_mtime;
  748. URIDone(Res);
  749. return true;
  750. }
  751. // Resume?
  752. if (FailTime == Buf.st_mtime && Size < (unsigned)Buf.st_size)
  753. Res.ResumePoint = Buf.st_size;
  754. }
  755. // Open the file
  756. MD5Summation MD5;
  757. {
  758. FileFd Fd(Itm->DestFile,FileFd::WriteAny);
  759. if (_error->PendingError() == true)
  760. return false;
  761. URIStart(Res);
  762. FailFile = Itm->DestFile;
  763. FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
  764. FailFd = Fd.Fd();
  765. bool Missing;
  766. if (Server->Get(File,Fd,Res.ResumePoint,MD5,Missing) == false)
  767. {
  768. // If the file is missing we hard fail otherwise transient fail
  769. if (Missing == true)
  770. return false;
  771. Fail(true);
  772. return true;
  773. }
  774. Res.Size = Fd.Size();
  775. }
  776. Res.LastModified = FailTime;
  777. Res.MD5Sum = MD5.Result();
  778. // Timestamp
  779. struct utimbuf UBuf;
  780. time(&UBuf.actime);
  781. UBuf.actime = FailTime;
  782. UBuf.modtime = FailTime;
  783. utime(Queue->DestFile.c_str(),&UBuf);
  784. FailFd = -1;
  785. URIDone(Res);
  786. return true;
  787. }
  788. /*}}}*/
  789. int main()
  790. {
  791. FtpMethod Mth;
  792. return Mth.Run();
  793. }