http.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: http.cc,v 1.1 1998/11/01 05:30:47 jgg Exp $
  4. /* ######################################################################
  5. HTTP Aquire Method - This is the HTTP aquire method for APT.
  6. It uses HTTP/1.1 and many of the fancy options there-in, such as
  7. pipelining, range, if-range and so on. It accepts on the command line
  8. a list of url destination pairs and writes to stdout the status of the
  9. operation as defined in the APT method spec.
  10. It is based on a doubly buffered select loop. All the requests are
  11. fed into a single output buffer that is constantly fed out the
  12. socket. This provides ideal pipelining as in many cases all of the
  13. requests will fit into a single packet. The input socket is buffered
  14. the same way and fed into the fd for the file.
  15. This double buffering provides fairly substantial transfer rates,
  16. compared to wget the http method is about 4% faster. Most importantly,
  17. when HTTP is compared with FTP as a protocol the speed difference is
  18. huge. In tests over the internet from two sites to llug (via ATM) this
  19. program got 230k/s sustained http transfer rates. FTP on the other
  20. hand topped out at 170k/s. That combined with the time to setup the
  21. FTP connection makes HTTP a vastly superior protocol.
  22. ##################################################################### */
  23. /*}}}*/
  24. // Include Files /*{{{*/
  25. #include <apt-pkg/fileutl.h>
  26. #include <apt-pkg/acquire-method.h>
  27. #include <apt-pkg/error.h>
  28. #include <apt-pkg/md5.h>
  29. #include <sys/stat.h>
  30. #include <sys/time.h>
  31. #include <utime.h>
  32. #include <unistd.h>
  33. #include <stdio.h>
  34. // Internet stuff
  35. #include <netinet/in.h>
  36. #include <sys/socket.h>
  37. #include <arpa/inet.h>
  38. #include <netdb.h>
  39. #include "http.h"
  40. /*}}}*/
  41. // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
  42. // ---------------------------------------------------------------------
  43. /* */
  44. CircleBuf::CircleBuf(unsigned long Size) : Size(Size), MD5(0)
  45. {
  46. Buf = new unsigned char[Size];
  47. Reset();
  48. }
  49. /*}}}*/
  50. // CircleBuf::Reset - Reset to the default state /*{{{*/
  51. // ---------------------------------------------------------------------
  52. /* */
  53. void CircleBuf::Reset()
  54. {
  55. InP = 0;
  56. OutP = 0;
  57. StrPos = 0;
  58. MaxGet = (unsigned int)-1;
  59. OutQueue = string();
  60. if (MD5 != 0)
  61. {
  62. delete MD5;
  63. MD5 = new MD5Summation;
  64. }
  65. };
  66. /*}}}*/
  67. // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
  68. // ---------------------------------------------------------------------
  69. /* This fills up the buffer with as much data as is in the FD, assuming it
  70. is non-blocking.. */
  71. bool CircleBuf::Read(int Fd)
  72. {
  73. while (1)
  74. {
  75. // Woops, buffer is full
  76. if (InP - OutP == Size)
  77. return true;
  78. // Write the buffer segment
  79. int Res;
  80. Res = read(Fd,Buf + (InP%Size),LeftRead());
  81. if (Res == 0)
  82. return false;
  83. if (Res < 0)
  84. {
  85. if (errno == EAGAIN)
  86. return true;
  87. return false;
  88. }
  89. if (InP == 0)
  90. gettimeofday(&Start,0);
  91. InP += Res;
  92. }
  93. }
  94. /*}}}*/
  95. // CircleBuf::Read - Put the string into the buffer /*{{{*/
  96. // ---------------------------------------------------------------------
  97. /* This will hold the string in and fill the buffer with it as it empties */
  98. bool CircleBuf::Read(string Data)
  99. {
  100. OutQueue += Data;
  101. FillOut();
  102. return true;
  103. }
  104. /*}}}*/
  105. // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
  106. // ---------------------------------------------------------------------
  107. /* */
  108. void CircleBuf::FillOut()
  109. {
  110. if (OutQueue.empty() == true)
  111. return;
  112. while (1)
  113. {
  114. // Woops, buffer is full
  115. if (InP - OutP == Size)
  116. return;
  117. // Write the buffer segment
  118. unsigned long Sz = LeftRead();
  119. if (OutQueue.length() - StrPos < Sz)
  120. Sz = OutQueue.length() - StrPos;
  121. memcpy(Buf + (InP%Size),OutQueue.begin() + StrPos,Sz);
  122. // Advance
  123. StrPos += Sz;
  124. InP += Sz;
  125. if (OutQueue.length() == StrPos)
  126. {
  127. StrPos = 0;
  128. OutQueue = "";
  129. return;
  130. }
  131. }
  132. }
  133. /*}}}*/
  134. // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
  135. // ---------------------------------------------------------------------
  136. /* This empties the buffer into the FD. */
  137. bool CircleBuf::Write(int Fd)
  138. {
  139. while (1)
  140. {
  141. FillOut();
  142. // Woops, buffer is empty
  143. if (OutP == InP)
  144. return true;
  145. if (OutP == MaxGet)
  146. return true;
  147. // Write the buffer segment
  148. int Res;
  149. Res = write(Fd,Buf + (OutP%Size),LeftWrite());
  150. if (Res == 0)
  151. return false;
  152. if (Res < 0)
  153. {
  154. if (errno == EAGAIN)
  155. return true;
  156. return false;
  157. }
  158. if (MD5 != 0)
  159. MD5->Add(Buf + (OutP%Size),Res);
  160. OutP += Res;
  161. }
  162. }
  163. /*}}}*/
  164. // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
  165. // ---------------------------------------------------------------------
  166. /* This copies till the first empty line */
  167. bool CircleBuf::WriteTillEl(string &Data,bool Single)
  168. {
  169. // We cheat and assume it is unneeded to have more than one buffer load
  170. for (unsigned long I = OutP; I < InP; I++)
  171. {
  172. if (Buf[I%Size] != '\n')
  173. continue;
  174. for (I++; I < InP && Buf[I%Size] == '\r'; I++);
  175. if (Single == false)
  176. {
  177. if (Buf[I%Size] != '\n')
  178. continue;
  179. for (I++; I < InP && Buf[I%Size] == '\r'; I++);
  180. }
  181. if (I > InP)
  182. I = InP;
  183. Data = "";
  184. while (OutP < I)
  185. {
  186. unsigned long Sz = LeftWrite();
  187. if (Sz == 0)
  188. return false;
  189. if (I - OutP < LeftWrite())
  190. Sz = I - OutP;
  191. Data += string((char *)(Buf + (OutP%Size)),Sz);
  192. OutP += Sz;
  193. }
  194. return true;
  195. }
  196. return false;
  197. }
  198. /*}}}*/
  199. // CircleBuf::Stats - Print out stats information /*{{{*/
  200. // ---------------------------------------------------------------------
  201. /* */
  202. void CircleBuf::Stats()
  203. {
  204. if (InP == 0)
  205. return;
  206. struct timeval Stop;
  207. gettimeofday(&Stop,0);
  208. /* float Diff = Stop.tv_sec - Start.tv_sec +
  209. (float)(Stop.tv_usec - Start.tv_usec)/1000000;
  210. clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
  211. }
  212. /*}}}*/
  213. // ServerState::ServerState - Constructor /*{{{*/
  214. // ---------------------------------------------------------------------
  215. /* */
  216. ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
  217. In(64*1024), Out(1*1024),
  218. ServerName(Srv)
  219. {
  220. Reset();
  221. }
  222. /*}}}*/
  223. // ServerState::Open - Open a connection to the server /*{{{*/
  224. // ---------------------------------------------------------------------
  225. /* This opens a connection to the server. */
  226. string LastHost;
  227. in_addr LastHostA;
  228. bool ServerState::Open()
  229. {
  230. Close();
  231. int Port;
  232. string Host;
  233. if (Proxy.empty() == false)
  234. {
  235. Port = ServerName.Port;
  236. Host = ServerName.Host;
  237. }
  238. else
  239. {
  240. Port = Proxy.Port;
  241. Host = Proxy.Host;
  242. }
  243. if (LastHost != Host)
  244. {
  245. Owner->Status("Connecting to %s",Host.c_str());
  246. // Lookup the host
  247. hostent *Addr = gethostbyname(Host.c_str());
  248. if (Addr == 0)
  249. return _error->Errno("gethostbyname","Could not lookup host %s",Host.c_str());
  250. LastHost = Host;
  251. LastHostA = *(in_addr *)(Addr->h_addr_list[0]);
  252. }
  253. Owner->Status("Connecting to %s (%s)",Host.c_str(),inet_ntoa(LastHostA));
  254. // Get a socket
  255. if ((ServerFd = socket(AF_INET,SOCK_STREAM,0)) < 0)
  256. return _error->Errno("socket","Could not create a socket");
  257. // Connect to the server
  258. struct sockaddr_in server;
  259. server.sin_family = AF_INET;
  260. server.sin_port = htons(Port);
  261. server.sin_addr = LastHostA;
  262. if (connect(ServerFd,(sockaddr *)&server,sizeof(server)) < 0)
  263. return _error->Errno("socket","Could not create a socket");
  264. SetNonBlock(ServerFd,true);
  265. return true;
  266. }
  267. /*}}}*/
  268. // ServerState::Close - Close a connection to the server /*{{{*/
  269. // ---------------------------------------------------------------------
  270. /* */
  271. bool ServerState::Close()
  272. {
  273. close(ServerFd);
  274. ServerFd = -1;
  275. In.Reset();
  276. Out.Reset();
  277. return true;
  278. }
  279. /*}}}*/
  280. // ServerState::RunHeaders - Get the headers before the data /*{{{*/
  281. // ---------------------------------------------------------------------
  282. /* */
  283. bool ServerState::RunHeaders()
  284. {
  285. State = Header;
  286. Owner->Status("Waiting for file");
  287. Major = 0;
  288. Minor = 0;
  289. Result = 0;
  290. Size = 0;
  291. StartPos = 0;
  292. Encoding = Closes;
  293. time(&Date);
  294. do
  295. {
  296. string Data;
  297. if (In.WriteTillEl(Data) == false)
  298. continue;
  299. for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
  300. {
  301. string::const_iterator J = I;
  302. for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
  303. if (HeaderLine(string(I,J-I)) == false)
  304. return false;
  305. I = J;
  306. }
  307. return true;
  308. }
  309. while (Owner->Go(false,this) == true);
  310. return false;
  311. }
  312. /*}}}*/
  313. // ServerState::RunData - Transfer the data from the socket /*{{{*/
  314. // ---------------------------------------------------------------------
  315. /* */
  316. bool ServerState::RunData()
  317. {
  318. State = Data;
  319. // Chunked transfer encoding is fun..
  320. if (Encoding == Chunked)
  321. {
  322. while (1)
  323. {
  324. // Grab the block size
  325. bool Last = true;
  326. string Data;
  327. In.Limit(-1);
  328. do
  329. {
  330. if (In.WriteTillEl(Data,true) == true)
  331. break;
  332. }
  333. while ((Last = Owner->Go(false,this)) == true);
  334. if (Last == false)
  335. return false;
  336. // See if we are done
  337. unsigned long Len = strtol(Data.c_str(),0,16);
  338. if (Len == 0)
  339. {
  340. In.Limit(-1);
  341. // We have to remove the entity trailer
  342. Last = true;
  343. do
  344. {
  345. if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
  346. break;
  347. }
  348. while ((Last = Owner->Go(false,this)) == true);
  349. if (Last == false)
  350. return false;
  351. return true;
  352. }
  353. // Transfer the block
  354. In.Limit(Len);
  355. while (Owner->Go(true,this) == true)
  356. if (In.IsLimit() == true)
  357. break;
  358. // Error
  359. if (In.IsLimit() == false)
  360. return false;
  361. // The server sends an extra new line before the next block specifier..
  362. In.Limit(-1);
  363. Last = true;
  364. do
  365. {
  366. if (In.WriteTillEl(Data,true) == true)
  367. break;
  368. }
  369. while ((Last = Owner->Go(false,this)) == true);
  370. if (Last == false)
  371. return false;
  372. }
  373. }
  374. else
  375. {
  376. /* Closes encoding is used when the server did not specify a size, the
  377. loss of the connection means we are done */
  378. if (Encoding == Closes)
  379. In.Limit(-1);
  380. else
  381. In.Limit(Size - StartPos);
  382. // Just transfer the whole block.
  383. do
  384. {
  385. if (In.IsLimit() == false)
  386. continue;
  387. In.Limit(-1);
  388. return true;
  389. }
  390. while (Owner->Go(true,this) == true);
  391. }
  392. return Owner->Flush(this);
  393. }
  394. /*}}}*/
  395. // ServerState::HeaderLine - Process a header line /*{{{*/
  396. // ---------------------------------------------------------------------
  397. /* */
  398. bool ServerState::HeaderLine(string Line)
  399. {
  400. if (Line.empty() == true)
  401. return true;
  402. // The http server might be trying to do something evil.
  403. if (Line.length() >= MAXLEN)
  404. return _error->Error("Got a single header line over %u chars",MAXLEN);
  405. string::size_type Pos = Line.find(' ');
  406. if (Pos == string::npos || Pos+1 > Line.length())
  407. return _error->Error("Bad header line");
  408. string Tag = string(Line,0,Pos);
  409. string Val = string(Line,Pos+1);
  410. if (stringcasecmp(Tag,"HTTP") == 0)
  411. {
  412. // Evil servers return no version
  413. if (Line[4] == '/')
  414. {
  415. if (sscanf(Line.c_str(),"HTTP/%u.%u %u %[^\n]",&Major,&Minor,
  416. &Result,Code) != 4)
  417. return _error->Error("The http server sent an invalid reply header");
  418. }
  419. else
  420. {
  421. Major = 0;
  422. Minor = 9;
  423. if (sscanf(Line.c_str(),"HTTP %u %[^\n]",&Result,Code) != 2)
  424. return _error->Error("The http server sent an invalid reply header");
  425. }
  426. return true;
  427. }
  428. if (stringcasecmp(Tag,"Content-Length:"))
  429. {
  430. if (Encoding == Closes)
  431. Encoding = Stream;
  432. // The length is already set from the Content-Range header
  433. if (StartPos != 0)
  434. return true;
  435. if (sscanf(Val.c_str(),"%lu",&Size) != 1)
  436. return _error->Error("The http server sent an invalid Content-Length header");
  437. return true;
  438. }
  439. if (stringcasecmp(Tag,"Content-Range:"))
  440. {
  441. if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
  442. return _error->Error("The http server sent an invalid Content-Range header");
  443. if ((unsigned)StartPos > Size)
  444. return _error->Error("This http server has broken range support");
  445. return true;
  446. }
  447. if (stringcasecmp(Tag,"Transfer-Encoding:"))
  448. {
  449. if (stringcasecmp(Val,"chunked"))
  450. Encoding = Chunked;
  451. return true;
  452. }
  453. if (stringcasecmp(Tag,"Last-Modified:"))
  454. {
  455. if (StrToTime(Val,Date) == false)
  456. return _error->Error("Unknown date format");
  457. return true;
  458. }
  459. return true;
  460. }
  461. /*}}}*/
  462. // HttpMethod::SendReq - Send the HTTP request /*{{{*/
  463. // ---------------------------------------------------------------------
  464. /* This places the http request in the outbound buffer */
  465. void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
  466. {
  467. URI Uri = Itm->Uri;
  468. // The HTTP server expects a hostname with a trailing :port
  469. char Buf[300];
  470. string ProperHost = Uri.Host;
  471. if (Uri.Port != 0)
  472. {
  473. sprintf(Buf,":%u",Uri.Port);
  474. ProperHost += Buf;
  475. }
  476. // Build the request
  477. if (Proxy.empty() == true)
  478. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
  479. Uri.Path.c_str(),ProperHost.c_str());
  480. else
  481. sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
  482. Itm->Uri.c_str(),ProperHost.c_str());
  483. string Req = Buf;
  484. // Check for a partial file
  485. struct stat SBuf;
  486. if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
  487. {
  488. // In this case we send an if-range query with a range header
  489. sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",SBuf.st_size - 1,
  490. TimeRFC1123(SBuf.st_mtime).c_str());
  491. Req += Buf;
  492. }
  493. else
  494. {
  495. if (Itm->LastModified != 0)
  496. {
  497. sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
  498. Req += Buf;
  499. }
  500. }
  501. /* if (ProxyAuth.empty() == false)
  502. Req += string("Proxy-Authorization: Basic ") + Base64Encode(ProxyAuth) + "\r\n";*/
  503. Req += "User-Agent: Debian APT-HTTP/1.2\r\n\r\n";
  504. Out.Read(Req);
  505. }
  506. /*}}}*/
  507. // HttpMethod::Go - Run a single loop /*{{{*/
  508. // ---------------------------------------------------------------------
  509. /* This runs the select loop over the server FDs, Output file FDs and
  510. stdin. */
  511. bool HttpMethod::Go(bool ToFile,ServerState *Srv)
  512. {
  513. // Server has closed the connection
  514. if (Srv->ServerFd == -1 && Srv->In.WriteSpace() == false)
  515. return false;
  516. fd_set rfds,wfds,efds;
  517. FD_ZERO(&rfds);
  518. FD_ZERO(&wfds);
  519. FD_ZERO(&efds);
  520. // Add the server
  521. if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1)
  522. FD_SET(Srv->ServerFd,&wfds);
  523. if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
  524. FD_SET(Srv->ServerFd,&rfds);
  525. // Add the file
  526. int FileFD = -1;
  527. if (File != 0)
  528. FileFD = File->Fd();
  529. if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
  530. FD_SET(FileFD,&wfds);
  531. // Add stdin
  532. FD_SET(STDIN_FILENO,&rfds);
  533. // Error Set
  534. if (FileFD != -1)
  535. FD_SET(FileFD,&efds);
  536. if (Srv->ServerFd != -1)
  537. FD_SET(Srv->ServerFd,&efds);
  538. // Figure out the max fd
  539. int MaxFd = FileFD;
  540. if (MaxFd < Srv->ServerFd)
  541. MaxFd = Srv->ServerFd;
  542. // Select
  543. struct timeval tv;
  544. tv.tv_sec = 120;
  545. tv.tv_usec = 0;
  546. int Res = 0;
  547. if ((Res = select(MaxFd+1,&rfds,&wfds,&efds,&tv)) < 0)
  548. return _error->Errno("select","Select failed");
  549. if (Res == 0)
  550. {
  551. _error->Error("Connection timed out");
  552. return ServerDie(Srv);
  553. }
  554. // Some kind of exception (error) on the sockets, die
  555. if ((FileFD != -1 && FD_ISSET(FileFD,&efds)) ||
  556. (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&efds)))
  557. return _error->Error("Socket Exception");
  558. // Handle server IO
  559. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
  560. {
  561. errno = 0;
  562. if (Srv->In.Read(Srv->ServerFd) == false)
  563. return ServerDie(Srv);
  564. }
  565. if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
  566. {
  567. errno = 0;
  568. if (Srv->Out.Write(Srv->ServerFd) == false)
  569. return ServerDie(Srv);
  570. }
  571. // Send data to the file
  572. if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
  573. {
  574. if (Srv->In.Write(FileFD) == false)
  575. return _error->Errno("write","Error writing to output file");
  576. }
  577. // Handle commands from APT
  578. if (FD_ISSET(STDIN_FILENO,&rfds))
  579. {
  580. if (Run(true) != 0)
  581. exit(100);
  582. }
  583. return true;
  584. }
  585. /*}}}*/
  586. // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
  587. // ---------------------------------------------------------------------
  588. /* This takes the current input buffer from the Server FD and writes it
  589. into the file */
  590. bool HttpMethod::Flush(ServerState *Srv)
  591. {
  592. if (File != 0)
  593. {
  594. SetNonBlock(File->Fd(),false);
  595. if (Srv->In.WriteSpace() == false)
  596. return true;
  597. while (Srv->In.WriteSpace() == true)
  598. {
  599. if (Srv->In.Write(File->Fd()) == false)
  600. return _error->Errno("write","Error writing to file");
  601. }
  602. if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
  603. return true;
  604. }
  605. return false;
  606. }
  607. /*}}}*/
  608. // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
  609. // ---------------------------------------------------------------------
  610. /* */
  611. bool HttpMethod::ServerDie(ServerState *Srv)
  612. {
  613. // Dump the buffer to the file
  614. if (Srv->State == ServerState::Data)
  615. {
  616. SetNonBlock(File->Fd(),false);
  617. while (Srv->In.WriteSpace() == true)
  618. {
  619. if (Srv->In.Write(File->Fd()) == false)
  620. return _error->Errno("write","Error writing to the file");
  621. }
  622. }
  623. // See if this is because the server finished the data stream
  624. if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
  625. Srv->Encoding != ServerState::Closes)
  626. {
  627. if (errno == 0)
  628. return _error->Error("Error reading from server Remote end closed connection");
  629. return _error->Errno("read","Error reading from server");
  630. }
  631. else
  632. {
  633. Srv->In.Limit(-1);
  634. // Nothing left in the buffer
  635. if (Srv->In.WriteSpace() == false)
  636. return false;
  637. // We may have got multiple responses back in one packet..
  638. Srv->Close();
  639. return true;
  640. }
  641. return false;
  642. }
  643. /*}}}*/
  644. // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
  645. // ---------------------------------------------------------------------
  646. /* We look at the header data we got back from the server and decide what
  647. to do. Returns
  648. 0 - File is open,
  649. 1 - IMS hit
  650. 3 - Unrecoverable error */
  651. int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
  652. {
  653. // Not Modified
  654. if (Srv->Result == 304)
  655. {
  656. unlink(Queue->DestFile.c_str());
  657. Res.IMSHit = true;
  658. Res.LastModified = Queue->LastModified;
  659. return 1;
  660. }
  661. /* We have a reply we dont handle. This should indicate a perm server
  662. failure */
  663. if (Srv->Result < 200 || Srv->Result >= 300)
  664. {
  665. _error->Error("%u %s",Srv->Result,Srv->Code);
  666. return 3;
  667. }
  668. // This is some sort of 2xx 'data follows' reply
  669. Res.LastModified = Srv->Date;
  670. Res.Size = Srv->Size;
  671. // Open the file
  672. delete File;
  673. File = new FileFd(Queue->DestFile,FileFd::WriteAny);
  674. if (_error->PendingError() == true)
  675. return 3;
  676. // Set the expected size
  677. if (Srv->StartPos >= 0)
  678. {
  679. Res.ResumePoint = Srv->StartPos;
  680. ftruncate(File->Fd(),Srv->StartPos);
  681. }
  682. // Set the start point
  683. lseek(File->Fd(),0,SEEK_END);
  684. delete Srv->In.MD5;
  685. Srv->In.MD5 = new MD5Summation;
  686. // Fill the MD5 Hash if the file is non-empty (resume)
  687. if (Srv->StartPos > 0)
  688. {
  689. lseek(File->Fd(),0,SEEK_SET);
  690. if (Srv->In.MD5->AddFD(File->Fd(),Srv->StartPos) == false)
  691. {
  692. _error->Errno("read","Problem hashing file");
  693. return 3;
  694. }
  695. lseek(File->Fd(),0,SEEK_END);
  696. }
  697. SetNonBlock(File->Fd(),true);
  698. return 0;
  699. }
  700. /*}}}*/
  701. // HttpMethod::Loop /*{{{*/
  702. // ---------------------------------------------------------------------
  703. /* */
  704. int HttpMethod::Loop()
  705. {
  706. ServerState *Server = 0;
  707. while (1)
  708. {
  709. // We have no commands, wait for some to arrive
  710. if (Queue == 0)
  711. {
  712. if (WaitFd(STDIN_FILENO) == false)
  713. return 0;
  714. }
  715. // Run messages
  716. if (Run(true) != 0)
  717. return 100;
  718. if (Queue == 0)
  719. continue;
  720. // Connect to the server
  721. if (Server == 0 || Server->Comp(Queue->Uri) == false)
  722. {
  723. delete Server;
  724. Server = new ServerState(Queue->Uri,this);
  725. }
  726. // Connnect to the host
  727. if (Server->Open() == false)
  728. {
  729. Fail();
  730. continue;
  731. }
  732. // Queue the request
  733. SendReq(Queue,Server->In);
  734. // Handle the header data
  735. if (Server->RunHeaders() == false)
  736. {
  737. Fail();
  738. continue;
  739. }
  740. // Decide what to do.
  741. FetchResult Res;
  742. switch (DealWithHeaders(Res,Server))
  743. {
  744. // Ok, the file is Open
  745. case 0:
  746. {
  747. URIStart(Res);
  748. // Run the data
  749. if (Server->RunData() == false)
  750. Fail();
  751. Res.MD5Sum = Srv->In.MD5->Result();
  752. delete File;
  753. File = 0;
  754. break;
  755. }
  756. // IMS hit
  757. case 1:
  758. {
  759. URIDone(Res);
  760. break;
  761. }
  762. // Hard server error, not found or something
  763. case 3:
  764. {
  765. Fail();
  766. break;
  767. }
  768. default:
  769. Fail("Internal error");
  770. break;
  771. }
  772. }
  773. return 0;
  774. }
  775. /*}}}*/
  776. int main()
  777. {
  778. HttpMethod Mth;
  779. return Mth.Loop();
  780. }