]> git.saurik.com Git - apt.git/blob - methods/http.cc
merged from david, many thanks
[apt.git] / methods / http.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
5
6 HTTP Acquire Method - This is the HTTP aquire method for APT.
7
8 It uses HTTP/1.1 and many of the fancy options there-in, such as
9 pipelining, range, if-range and so on.
10
11 It is based on a doubly buffered select loop. A groupe of requests are
12 fed into a single output buffer that is constantly fed out the
13 socket. This provides ideal pipelining as in many cases all of the
14 requests will fit into a single packet. The input socket is buffered
15 the same way and fed into the fd for the file (may be a pipe in future).
16
17 This double buffering provides fairly substantial transfer rates,
18 compared to wget the http method is about 4% faster. Most importantly,
19 when HTTP is compared with FTP as a protocol the speed difference is
20 huge. In tests over the internet from two sites to llug (via ATM) this
21 program got 230k/s sustained http transfer rates. FTP on the other
22 hand topped out at 170k/s. That combined with the time to setup the
23 FTP connection makes HTTP a vastly superior protocol.
24
25 ##################################################################### */
26 /*}}}*/
27 // Include Files /*{{{*/
28 #include <apt-pkg/fileutl.h>
29 #include <apt-pkg/acquire-method.h>
30 #include <apt-pkg/error.h>
31 #include <apt-pkg/hashes.h>
32
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <utime.h>
36 #include <unistd.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <errno.h>
40 #include <string.h>
41 #include <iostream>
42 #include <map>
43 #include <apti18n.h>
44
45 // Internet stuff
46 #include <netdb.h>
47
48 #include "config.h"
49 #include "connect.h"
50 #include "rfc2553emu.h"
51 #include "http.h"
52
53 /*}}}*/
54 using namespace std;
55
56 string HttpMethod::FailFile;
57 int HttpMethod::FailFd = -1;
58 time_t HttpMethod::FailTime = 0;
59 unsigned long PipelineDepth = 10;
60 unsigned long TimeOut = 120;
61 bool AllowRedirect = false;
62 bool Debug = false;
63 URI Proxy;
64
65 unsigned long CircleBuf::BwReadLimit=0;
66 unsigned long CircleBuf::BwTickReadData=0;
67 struct timeval CircleBuf::BwReadTick={0,0};
68 const unsigned int CircleBuf::BW_HZ=10;
69
70 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
71 // ---------------------------------------------------------------------
72 /* */
73 CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
74 {
75 Buf = new unsigned char[Size];
76 Reset();
77
78 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
79 }
80 /*}}}*/
81 // CircleBuf::Reset - Reset to the default state /*{{{*/
82 // ---------------------------------------------------------------------
83 /* */
84 void CircleBuf::Reset()
85 {
86 InP = 0;
87 OutP = 0;
88 StrPos = 0;
89 MaxGet = (unsigned int)-1;
90 OutQueue = string();
91 if (Hash != 0)
92 {
93 delete Hash;
94 Hash = new Hashes;
95 }
96 };
97 /*}}}*/
98 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
99 // ---------------------------------------------------------------------
100 /* This fills up the buffer with as much data as is in the FD, assuming it
101 is non-blocking.. */
102 bool CircleBuf::Read(int Fd)
103 {
104 unsigned long BwReadMax;
105
106 while (1)
107 {
108 // Woops, buffer is full
109 if (InP - OutP == Size)
110 return true;
111
112 // what's left to read in this tick
113 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
114
115 if(CircleBuf::BwReadLimit) {
116 struct timeval now;
117 gettimeofday(&now,0);
118
119 unsigned long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
120 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
121 if(d > 1000000/BW_HZ) {
122 CircleBuf::BwReadTick = now;
123 CircleBuf::BwTickReadData = 0;
124 }
125
126 if(CircleBuf::BwTickReadData >= BwReadMax) {
127 usleep(1000000/BW_HZ);
128 return true;
129 }
130 }
131
132 // Write the buffer segment
133 int Res;
134 if(CircleBuf::BwReadLimit) {
135 Res = read(Fd,Buf + (InP%Size),
136 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
137 } else
138 Res = read(Fd,Buf + (InP%Size),LeftRead());
139
140 if(Res > 0 && BwReadLimit > 0)
141 CircleBuf::BwTickReadData += Res;
142
143 if (Res == 0)
144 return false;
145 if (Res < 0)
146 {
147 if (errno == EAGAIN)
148 return true;
149 return false;
150 }
151
152 if (InP == 0)
153 gettimeofday(&Start,0);
154 InP += Res;
155 }
156 }
157 /*}}}*/
158 // CircleBuf::Read - Put the string into the buffer /*{{{*/
159 // ---------------------------------------------------------------------
160 /* This will hold the string in and fill the buffer with it as it empties */
161 bool CircleBuf::Read(string Data)
162 {
163 OutQueue += Data;
164 FillOut();
165 return true;
166 }
167 /*}}}*/
168 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
169 // ---------------------------------------------------------------------
170 /* */
171 void CircleBuf::FillOut()
172 {
173 if (OutQueue.empty() == true)
174 return;
175 while (1)
176 {
177 // Woops, buffer is full
178 if (InP - OutP == Size)
179 return;
180
181 // Write the buffer segment
182 unsigned long Sz = LeftRead();
183 if (OutQueue.length() - StrPos < Sz)
184 Sz = OutQueue.length() - StrPos;
185 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
186
187 // Advance
188 StrPos += Sz;
189 InP += Sz;
190 if (OutQueue.length() == StrPos)
191 {
192 StrPos = 0;
193 OutQueue = "";
194 return;
195 }
196 }
197 }
198 /*}}}*/
199 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
200 // ---------------------------------------------------------------------
201 /* This empties the buffer into the FD. */
202 bool CircleBuf::Write(int Fd)
203 {
204 while (1)
205 {
206 FillOut();
207
208 // Woops, buffer is empty
209 if (OutP == InP)
210 return true;
211
212 if (OutP == MaxGet)
213 return true;
214
215 // Write the buffer segment
216 int Res;
217 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
218
219 if (Res == 0)
220 return false;
221 if (Res < 0)
222 {
223 if (errno == EAGAIN)
224 return true;
225
226 return false;
227 }
228
229 if (Hash != 0)
230 Hash->Add(Buf + (OutP%Size),Res);
231
232 OutP += Res;
233 }
234 }
235 /*}}}*/
236 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
237 // ---------------------------------------------------------------------
238 /* This copies till the first empty line */
239 bool CircleBuf::WriteTillEl(string &Data,bool Single)
240 {
241 // We cheat and assume it is unneeded to have more than one buffer load
242 for (unsigned long I = OutP; I < InP; I++)
243 {
244 if (Buf[I%Size] != '\n')
245 continue;
246 ++I;
247
248 if (Single == false)
249 {
250 if (I < InP && Buf[I%Size] == '\r')
251 ++I;
252 if (I >= InP || Buf[I%Size] != '\n')
253 continue;
254 ++I;
255 }
256
257 Data = "";
258 while (OutP < I)
259 {
260 unsigned long Sz = LeftWrite();
261 if (Sz == 0)
262 return false;
263 if (I - OutP < Sz)
264 Sz = I - OutP;
265 Data += string((char *)(Buf + (OutP%Size)),Sz);
266 OutP += Sz;
267 }
268 return true;
269 }
270 return false;
271 }
272 /*}}}*/
273 // CircleBuf::Stats - Print out stats information /*{{{*/
274 // ---------------------------------------------------------------------
275 /* */
276 void CircleBuf::Stats()
277 {
278 if (InP == 0)
279 return;
280
281 struct timeval Stop;
282 gettimeofday(&Stop,0);
283 /* float Diff = Stop.tv_sec - Start.tv_sec +
284 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
285 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
286 }
287 /*}}}*/
288
289 // ServerState::ServerState - Constructor /*{{{*/
290 // ---------------------------------------------------------------------
291 /* */
292 ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
293 In(64*1024), Out(4*1024),
294 ServerName(Srv)
295 {
296 Reset();
297 }
298 /*}}}*/
299 // ServerState::Open - Open a connection to the server /*{{{*/
300 // ---------------------------------------------------------------------
301 /* This opens a connection to the server. */
302 bool ServerState::Open()
303 {
304 // Use the already open connection if possible.
305 if (ServerFd != -1)
306 return true;
307
308 Close();
309 In.Reset();
310 Out.Reset();
311 Persistent = true;
312
313 // Determine the proxy setting
314 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
315 if (!SpecificProxy.empty())
316 {
317 if (SpecificProxy == "DIRECT")
318 Proxy = "";
319 else
320 Proxy = SpecificProxy;
321 }
322 else
323 {
324 string DefProxy = _config->Find("Acquire::http::Proxy");
325 if (!DefProxy.empty())
326 {
327 Proxy = DefProxy;
328 }
329 else
330 {
331 char* result = getenv("http_proxy");
332 Proxy = result ? result : "";
333 }
334 }
335
336 // Parse no_proxy, a , separated list of domains
337 if (getenv("no_proxy") != 0)
338 {
339 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
340 Proxy = "";
341 }
342
343 // Determine what host and port to use based on the proxy settings
344 int Port = 0;
345 string Host;
346 if (Proxy.empty() == true || Proxy.Host.empty() == true)
347 {
348 if (ServerName.Port != 0)
349 Port = ServerName.Port;
350 Host = ServerName.Host;
351 }
352 else
353 {
354 if (Proxy.Port != 0)
355 Port = Proxy.Port;
356 Host = Proxy.Host;
357 }
358
359 // Connect to the remote server
360 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
361 return false;
362
363 return true;
364 }
365 /*}}}*/
366 // ServerState::Close - Close a connection to the server /*{{{*/
367 // ---------------------------------------------------------------------
368 /* */
369 bool ServerState::Close()
370 {
371 close(ServerFd);
372 ServerFd = -1;
373 return true;
374 }
375 /*}}}*/
376 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
377 // ---------------------------------------------------------------------
378 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
379 parse error occurred */
380 int ServerState::RunHeaders()
381 {
382 State = Header;
383
384 Owner->Status(_("Waiting for headers"));
385
386 Major = 0;
387 Minor = 0;
388 Result = 0;
389 Size = 0;
390 StartPos = 0;
391 Encoding = Closes;
392 HaveContent = false;
393 time(&Date);
394
395 do
396 {
397 string Data;
398 if (In.WriteTillEl(Data) == false)
399 continue;
400
401 if (Debug == true)
402 clog << Data;
403
404 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
405 {
406 string::const_iterator J = I;
407 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
408 if (HeaderLine(string(I,J)) == false)
409 return 2;
410 I = J;
411 }
412
413 // 100 Continue is a Nop...
414 if (Result == 100)
415 continue;
416
417 // Tidy up the connection persistance state.
418 if (Encoding == Closes && HaveContent == true)
419 Persistent = false;
420
421 return 0;
422 }
423 while (Owner->Go(false,this) == true);
424
425 return 1;
426 }
427 /*}}}*/
428 // ServerState::RunData - Transfer the data from the socket /*{{{*/
429 // ---------------------------------------------------------------------
430 /* */
431 bool ServerState::RunData()
432 {
433 State = Data;
434
435 // Chunked transfer encoding is fun..
436 if (Encoding == Chunked)
437 {
438 while (1)
439 {
440 // Grab the block size
441 bool Last = true;
442 string Data;
443 In.Limit(-1);
444 do
445 {
446 if (In.WriteTillEl(Data,true) == true)
447 break;
448 }
449 while ((Last = Owner->Go(false,this)) == true);
450
451 if (Last == false)
452 return false;
453
454 // See if we are done
455 unsigned long Len = strtol(Data.c_str(),0,16);
456 if (Len == 0)
457 {
458 In.Limit(-1);
459
460 // We have to remove the entity trailer
461 Last = true;
462 do
463 {
464 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
465 break;
466 }
467 while ((Last = Owner->Go(false,this)) == true);
468 if (Last == false)
469 return false;
470 return !_error->PendingError();
471 }
472
473 // Transfer the block
474 In.Limit(Len);
475 while (Owner->Go(true,this) == true)
476 if (In.IsLimit() == true)
477 break;
478
479 // Error
480 if (In.IsLimit() == false)
481 return false;
482
483 // The server sends an extra new line before the next block specifier..
484 In.Limit(-1);
485 Last = true;
486 do
487 {
488 if (In.WriteTillEl(Data,true) == true)
489 break;
490 }
491 while ((Last = Owner->Go(false,this)) == true);
492 if (Last == false)
493 return false;
494 }
495 }
496 else
497 {
498 /* Closes encoding is used when the server did not specify a size, the
499 loss of the connection means we are done */
500 if (Encoding == Closes)
501 In.Limit(-1);
502 else
503 In.Limit(Size - StartPos);
504
505 // Just transfer the whole block.
506 do
507 {
508 if (In.IsLimit() == false)
509 continue;
510
511 In.Limit(-1);
512 return !_error->PendingError();
513 }
514 while (Owner->Go(true,this) == true);
515 }
516
517 return Owner->Flush(this) && !_error->PendingError();
518 }
519 /*}}}*/
520 // ServerState::HeaderLine - Process a header line /*{{{*/
521 // ---------------------------------------------------------------------
522 /* */
523 bool ServerState::HeaderLine(string Line)
524 {
525 if (Line.empty() == true)
526 return true;
527
528 // The http server might be trying to do something evil.
529 if (Line.length() >= MAXLEN)
530 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
531
532 string::size_type Pos = Line.find(' ');
533 if (Pos == string::npos || Pos+1 > Line.length())
534 {
535 // Blah, some servers use "connection:closes", evil.
536 Pos = Line.find(':');
537 if (Pos == string::npos || Pos + 2 > Line.length())
538 return _error->Error(_("Bad header line"));
539 Pos++;
540 }
541
542 // Parse off any trailing spaces between the : and the next word.
543 string::size_type Pos2 = Pos;
544 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
545 Pos2++;
546
547 string Tag = string(Line,0,Pos);
548 string Val = string(Line,Pos2);
549
550 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
551 {
552 // Evil servers return no version
553 if (Line[4] == '/')
554 {
555 if (sscanf(Line.c_str(),"HTTP/%u.%u %u%[^\n]",&Major,&Minor,
556 &Result,Code) != 4)
557 return _error->Error(_("The HTTP server sent an invalid reply header"));
558 }
559 else
560 {
561 Major = 0;
562 Minor = 9;
563 if (sscanf(Line.c_str(),"HTTP %u%[^\n]",&Result,Code) != 2)
564 return _error->Error(_("The HTTP server sent an invalid reply header"));
565 }
566
567 /* Check the HTTP response header to get the default persistance
568 state. */
569 if (Major < 1)
570 Persistent = false;
571 else
572 {
573 if (Major == 1 && Minor <= 0)
574 Persistent = false;
575 else
576 Persistent = true;
577 }
578
579 return true;
580 }
581
582 if (stringcasecmp(Tag,"Content-Length:") == 0)
583 {
584 if (Encoding == Closes)
585 Encoding = Stream;
586 HaveContent = true;
587
588 // The length is already set from the Content-Range header
589 if (StartPos != 0)
590 return true;
591
592 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
593 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
594 return true;
595 }
596
597 if (stringcasecmp(Tag,"Content-Type:") == 0)
598 {
599 HaveContent = true;
600 return true;
601 }
602
603 if (stringcasecmp(Tag,"Content-Range:") == 0)
604 {
605 HaveContent = true;
606
607 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
608 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
609 if ((unsigned)StartPos > Size)
610 return _error->Error(_("This HTTP server has broken range support"));
611 return true;
612 }
613
614 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
615 {
616 HaveContent = true;
617 if (stringcasecmp(Val,"chunked") == 0)
618 Encoding = Chunked;
619 return true;
620 }
621
622 if (stringcasecmp(Tag,"Connection:") == 0)
623 {
624 if (stringcasecmp(Val,"close") == 0)
625 Persistent = false;
626 if (stringcasecmp(Val,"keep-alive") == 0)
627 Persistent = true;
628 return true;
629 }
630
631 if (stringcasecmp(Tag,"Last-Modified:") == 0)
632 {
633 if (StrToTime(Val,Date) == false)
634 return _error->Error(_("Unknown date format"));
635 return true;
636 }
637
638 if (stringcasecmp(Tag,"Location:") == 0)
639 {
640 Location = Val;
641 return true;
642 }
643
644 return true;
645 }
646 /*}}}*/
647
648 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
649 // ---------------------------------------------------------------------
650 /* This places the http request in the outbound buffer */
651 void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
652 {
653 URI Uri = Itm->Uri;
654
655 // The HTTP server expects a hostname with a trailing :port
656 char Buf[1000];
657 string ProperHost = Uri.Host;
658 if (Uri.Port != 0)
659 {
660 sprintf(Buf,":%u",Uri.Port);
661 ProperHost += Buf;
662 }
663
664 // Just in case.
665 if (Itm->Uri.length() >= sizeof(Buf))
666 abort();
667
668 /* Build the request. We include a keep-alive header only for non-proxy
669 requests. This is to tweak old http/1.0 servers that do support keep-alive
670 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
671 will glitch HTTP/1.0 proxies because they do not filter it out and
672 pass it on, HTTP/1.1 says the connection should default to keep alive
673 and we expect the proxy to do this */
674 if (Proxy.empty() == true || Proxy.Host.empty())
675 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
676 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
677 else
678 {
679 /* Generate a cache control header if necessary. We place a max
680 cache age on index files, optionally set a no-cache directive
681 and a no-store directive for archives. */
682 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
683 Itm->Uri.c_str(),ProperHost.c_str());
684 // only generate a cache control header if we actually want to
685 // use a cache
686 if (_config->FindB("Acquire::http::No-Cache",false) == false)
687 {
688 if (Itm->IndexFile == true)
689 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
690 _config->FindI("Acquire::http::Max-Age",0));
691 else
692 {
693 if (_config->FindB("Acquire::http::No-Store",false) == true)
694 strcat(Buf,"Cache-Control: no-store\r\n");
695 }
696 }
697 }
698 // generate a no-cache header if needed
699 if (_config->FindB("Acquire::http::No-Cache",false) == true)
700 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
701
702
703 string Req = Buf;
704
705 // Check for a partial file
706 struct stat SBuf;
707 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
708 {
709 // In this case we send an if-range query with a range header
710 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
711 TimeRFC1123(SBuf.st_mtime).c_str());
712 Req += Buf;
713 }
714 else
715 {
716 if (Itm->LastModified != 0)
717 {
718 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
719 Req += Buf;
720 }
721 }
722
723 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
724 Req += string("Proxy-Authorization: Basic ") +
725 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
726
727 if (Uri.User.empty() == false || Uri.Password.empty() == false)
728 Req += string("Authorization: Basic ") +
729 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
730
731 Req += "User-Agent: Debian APT-HTTP/1.3 ("VERSION")\r\n\r\n";
732
733 if (Debug == true)
734 cerr << Req << endl;
735
736 Out.Read(Req);
737 }
738 /*}}}*/
739 // HttpMethod::Go - Run a single loop /*{{{*/
740 // ---------------------------------------------------------------------
741 /* This runs the select loop over the server FDs, Output file FDs and
742 stdin. */
743 bool HttpMethod::Go(bool ToFile,ServerState *Srv)
744 {
745 // Server has closed the connection
746 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
747 ToFile == false))
748 return false;
749
750 fd_set rfds,wfds;
751 FD_ZERO(&rfds);
752 FD_ZERO(&wfds);
753
754 /* Add the server. We only send more requests if the connection will
755 be persisting */
756 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
757 && Srv->Persistent == true)
758 FD_SET(Srv->ServerFd,&wfds);
759 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
760 FD_SET(Srv->ServerFd,&rfds);
761
762 // Add the file
763 int FileFD = -1;
764 if (File != 0)
765 FileFD = File->Fd();
766
767 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
768 FD_SET(FileFD,&wfds);
769
770 // Add stdin
771 FD_SET(STDIN_FILENO,&rfds);
772
773 // Figure out the max fd
774 int MaxFd = FileFD;
775 if (MaxFd < Srv->ServerFd)
776 MaxFd = Srv->ServerFd;
777
778 // Select
779 struct timeval tv;
780 tv.tv_sec = TimeOut;
781 tv.tv_usec = 0;
782 int Res = 0;
783 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
784 {
785 if (errno == EINTR)
786 return true;
787 return _error->Errno("select",_("Select failed"));
788 }
789
790 if (Res == 0)
791 {
792 _error->Error(_("Connection timed out"));
793 return ServerDie(Srv);
794 }
795
796 // Handle server IO
797 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
798 {
799 errno = 0;
800 if (Srv->In.Read(Srv->ServerFd) == false)
801 return ServerDie(Srv);
802 }
803
804 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
805 {
806 errno = 0;
807 if (Srv->Out.Write(Srv->ServerFd) == false)
808 return ServerDie(Srv);
809 }
810
811 // Send data to the file
812 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
813 {
814 if (Srv->In.Write(FileFD) == false)
815 return _error->Errno("write",_("Error writing to output file"));
816 }
817
818 // Handle commands from APT
819 if (FD_ISSET(STDIN_FILENO,&rfds))
820 {
821 if (Run(true) != -1)
822 exit(100);
823 }
824
825 return true;
826 }
827 /*}}}*/
828 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
829 // ---------------------------------------------------------------------
830 /* This takes the current input buffer from the Server FD and writes it
831 into the file */
832 bool HttpMethod::Flush(ServerState *Srv)
833 {
834 if (File != 0)
835 {
836 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
837 // can't be set
838 if (File->Name() != "/dev/null")
839 SetNonBlock(File->Fd(),false);
840 if (Srv->In.WriteSpace() == false)
841 return true;
842
843 while (Srv->In.WriteSpace() == true)
844 {
845 if (Srv->In.Write(File->Fd()) == false)
846 return _error->Errno("write",_("Error writing to file"));
847 if (Srv->In.IsLimit() == true)
848 return true;
849 }
850
851 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
852 return true;
853 }
854 return false;
855 }
856 /*}}}*/
857 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
858 // ---------------------------------------------------------------------
859 /* */
860 bool HttpMethod::ServerDie(ServerState *Srv)
861 {
862 unsigned int LErrno = errno;
863
864 // Dump the buffer to the file
865 if (Srv->State == ServerState::Data)
866 {
867 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
868 // can't be set
869 if (File->Name() != "/dev/null")
870 SetNonBlock(File->Fd(),false);
871 while (Srv->In.WriteSpace() == true)
872 {
873 if (Srv->In.Write(File->Fd()) == false)
874 return _error->Errno("write",_("Error writing to the file"));
875
876 // Done
877 if (Srv->In.IsLimit() == true)
878 return true;
879 }
880 }
881
882 // See if this is because the server finished the data stream
883 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
884 Srv->Encoding != ServerState::Closes)
885 {
886 Srv->Close();
887 if (LErrno == 0)
888 return _error->Error(_("Error reading from server. Remote end closed connection"));
889 errno = LErrno;
890 return _error->Errno("read",_("Error reading from server"));
891 }
892 else
893 {
894 Srv->In.Limit(-1);
895
896 // Nothing left in the buffer
897 if (Srv->In.WriteSpace() == false)
898 return false;
899
900 // We may have got multiple responses back in one packet..
901 Srv->Close();
902 return true;
903 }
904
905 return false;
906 }
907 /*}}}*/
908 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
909 // ---------------------------------------------------------------------
910 /* We look at the header data we got back from the server and decide what
911 to do. Returns
912 0 - File is open,
913 1 - IMS hit
914 3 - Unrecoverable error
915 4 - Error with error content page
916 5 - Unrecoverable non-server error (close the connection)
917 6 - Try again with a new or changed URI
918 */
919 int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
920 {
921 // Not Modified
922 if (Srv->Result == 304)
923 {
924 unlink(Queue->DestFile.c_str());
925 Res.IMSHit = true;
926 Res.LastModified = Queue->LastModified;
927 return 1;
928 }
929
930 /* Redirect
931 *
932 * Note that it is only OK for us to treat all redirection the same
933 * because we *always* use GET, not other HTTP methods. There are
934 * three redirection codes for which it is not appropriate that we
935 * redirect. Pass on those codes so the error handling kicks in.
936 */
937 if (AllowRedirect
938 && (Srv->Result > 300 && Srv->Result < 400)
939 && (Srv->Result != 300 // Multiple Choices
940 && Srv->Result != 304 // Not Modified
941 && Srv->Result != 306)) // (Not part of HTTP/1.1, reserved)
942 {
943 if (!Srv->Location.empty())
944 {
945 NextURI = Srv->Location;
946 return 6;
947 }
948 /* else pass through for error message */
949 }
950
951 /* We have a reply we dont handle. This should indicate a perm server
952 failure */
953 if (Srv->Result < 200 || Srv->Result >= 300)
954 {
955 _error->Error("%u %s",Srv->Result,Srv->Code);
956 if (Srv->HaveContent == true)
957 return 4;
958 return 3;
959 }
960
961 // This is some sort of 2xx 'data follows' reply
962 Res.LastModified = Srv->Date;
963 Res.Size = Srv->Size;
964
965 // Open the file
966 delete File;
967 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
968 if (_error->PendingError() == true)
969 return 5;
970
971 FailFile = Queue->DestFile;
972 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
973 FailFd = File->Fd();
974 FailTime = Srv->Date;
975
976 // Set the expected size
977 if (Srv->StartPos >= 0)
978 {
979 Res.ResumePoint = Srv->StartPos;
980 if (ftruncate(File->Fd(),Srv->StartPos) < 0)
981 _error->Errno("ftruncate", _("Failed to truncate file"));
982 }
983
984 // Set the start point
985 lseek(File->Fd(),0,SEEK_END);
986
987 delete Srv->In.Hash;
988 Srv->In.Hash = new Hashes;
989
990 // Fill the Hash if the file is non-empty (resume)
991 if (Srv->StartPos > 0)
992 {
993 lseek(File->Fd(),0,SEEK_SET);
994 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
995 {
996 _error->Errno("read",_("Problem hashing file"));
997 return 5;
998 }
999 lseek(File->Fd(),0,SEEK_END);
1000 }
1001
1002 SetNonBlock(File->Fd(),true);
1003 return 0;
1004 }
1005 /*}}}*/
1006 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1007 // ---------------------------------------------------------------------
1008 /* This closes and timestamps the open file. This is neccessary to get
1009 resume behavoir on user abort */
1010 void HttpMethod::SigTerm(int)
1011 {
1012 if (FailFd == -1)
1013 _exit(100);
1014 close(FailFd);
1015
1016 // Timestamp
1017 struct utimbuf UBuf;
1018 UBuf.actime = FailTime;
1019 UBuf.modtime = FailTime;
1020 utime(FailFile.c_str(),&UBuf);
1021
1022 _exit(100);
1023 }
1024 /*}}}*/
1025 // HttpMethod::Fetch - Fetch an item /*{{{*/
1026 // ---------------------------------------------------------------------
1027 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1028 depth. */
1029 bool HttpMethod::Fetch(FetchItem *)
1030 {
1031 if (Server == 0)
1032 return true;
1033
1034 // Queue the requests
1035 int Depth = -1;
1036 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1037 I = I->Next, Depth++)
1038 {
1039 // If pipelining is disabled, we only queue 1 request
1040 if (Server->Pipeline == false && Depth >= 0)
1041 break;
1042
1043 // Make sure we stick with the same server
1044 if (Server->Comp(I->Uri) == false)
1045 break;
1046 if (QueueBack == I)
1047 {
1048 QueueBack = I->Next;
1049 SendReq(I,Server->Out);
1050 continue;
1051 }
1052 }
1053
1054 return true;
1055 };
1056 /*}}}*/
1057 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1058 // ---------------------------------------------------------------------
1059 /* We stash the desired pipeline depth */
1060 bool HttpMethod::Configuration(string Message)
1061 {
1062 if (pkgAcqMethod::Configuration(Message) == false)
1063 return false;
1064
1065 AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
1066 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1067 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1068 PipelineDepth);
1069 Debug = _config->FindB("Debug::Acquire::http",false);
1070
1071 return true;
1072 }
1073 /*}}}*/
1074 // HttpMethod::Loop - Main loop /*{{{*/
1075 // ---------------------------------------------------------------------
1076 /* */
1077 int HttpMethod::Loop()
1078 {
1079 typedef vector<string> StringVector;
1080 typedef vector<string>::iterator StringVectorIterator;
1081 map<string, StringVector> Redirected;
1082
1083 signal(SIGTERM,SigTerm);
1084 signal(SIGINT,SigTerm);
1085
1086 Server = 0;
1087
1088 int FailCounter = 0;
1089 while (1)
1090 {
1091 // We have no commands, wait for some to arrive
1092 if (Queue == 0)
1093 {
1094 if (WaitFd(STDIN_FILENO) == false)
1095 return 0;
1096 }
1097
1098 /* Run messages, we can accept 0 (no message) if we didn't
1099 do a WaitFd above.. Otherwise the FD is closed. */
1100 int Result = Run(true);
1101 if (Result != -1 && (Result != 0 || Queue == 0))
1102 return 100;
1103
1104 if (Queue == 0)
1105 continue;
1106
1107 // Connect to the server
1108 if (Server == 0 || Server->Comp(Queue->Uri) == false)
1109 {
1110 delete Server;
1111 Server = new ServerState(Queue->Uri,this);
1112 }
1113 /* If the server has explicitly said this is the last connection
1114 then we pre-emptively shut down the pipeline and tear down
1115 the connection. This will speed up HTTP/1.0 servers a tad
1116 since we don't have to wait for the close sequence to
1117 complete */
1118 if (Server->Persistent == false)
1119 Server->Close();
1120
1121 // Reset the pipeline
1122 if (Server->ServerFd == -1)
1123 QueueBack = Queue;
1124
1125 // Connnect to the host
1126 if (Server->Open() == false)
1127 {
1128 Fail(true);
1129 delete Server;
1130 Server = 0;
1131 continue;
1132 }
1133
1134 // Fill the pipeline.
1135 Fetch(0);
1136
1137 // Fetch the next URL header data from the server.
1138 switch (Server->RunHeaders())
1139 {
1140 case 0:
1141 break;
1142
1143 // The header data is bad
1144 case 2:
1145 {
1146 _error->Error(_("Bad header data"));
1147 Fail(true);
1148 RotateDNS();
1149 continue;
1150 }
1151
1152 // The server closed a connection during the header get..
1153 default:
1154 case 1:
1155 {
1156 FailCounter++;
1157 _error->Discard();
1158 Server->Close();
1159 Server->Pipeline = false;
1160
1161 if (FailCounter >= 2)
1162 {
1163 Fail(_("Connection failed"),true);
1164 FailCounter = 0;
1165 }
1166
1167 RotateDNS();
1168 continue;
1169 }
1170 };
1171
1172 // Decide what to do.
1173 FetchResult Res;
1174 Res.Filename = Queue->DestFile;
1175 switch (DealWithHeaders(Res,Server))
1176 {
1177 // Ok, the file is Open
1178 case 0:
1179 {
1180 URIStart(Res);
1181
1182 // Run the data
1183 bool Result = Server->RunData();
1184
1185 /* If the server is sending back sizeless responses then fill in
1186 the size now */
1187 if (Res.Size == 0)
1188 Res.Size = File->Size();
1189
1190 // Close the file, destroy the FD object and timestamp it
1191 FailFd = -1;
1192 delete File;
1193 File = 0;
1194
1195 // Timestamp
1196 struct utimbuf UBuf;
1197 time(&UBuf.actime);
1198 UBuf.actime = Server->Date;
1199 UBuf.modtime = Server->Date;
1200 utime(Queue->DestFile.c_str(),&UBuf);
1201
1202 // Send status to APT
1203 if (Result == true)
1204 {
1205 Res.TakeHashes(*Server->In.Hash);
1206 URIDone(Res);
1207 }
1208 else
1209 {
1210 if (Server->ServerFd == -1)
1211 {
1212 FailCounter++;
1213 _error->Discard();
1214 Server->Close();
1215
1216 if (FailCounter >= 2)
1217 {
1218 Fail(_("Connection failed"),true);
1219 FailCounter = 0;
1220 }
1221
1222 QueueBack = Queue;
1223 }
1224 else
1225 Fail(true);
1226 }
1227 break;
1228 }
1229
1230 // IMS hit
1231 case 1:
1232 {
1233 URIDone(Res);
1234 break;
1235 }
1236
1237 // Hard server error, not found or something
1238 case 3:
1239 {
1240 Fail();
1241 break;
1242 }
1243
1244 // Hard internal error, kill the connection and fail
1245 case 5:
1246 {
1247 delete File;
1248 File = 0;
1249
1250 Fail();
1251 RotateDNS();
1252 Server->Close();
1253 break;
1254 }
1255
1256 // We need to flush the data, the header is like a 404 w/ error text
1257 case 4:
1258 {
1259 Fail();
1260
1261 // Send to content to dev/null
1262 File = new FileFd("/dev/null",FileFd::WriteExists);
1263 Server->RunData();
1264 delete File;
1265 File = 0;
1266 break;
1267 }
1268
1269 // Try again with a new URL
1270 case 6:
1271 {
1272 // Clear rest of response if there is content
1273 if (Server->HaveContent)
1274 {
1275 File = new FileFd("/dev/null",FileFd::WriteExists);
1276 Server->RunData();
1277 delete File;
1278 File = 0;
1279 }
1280
1281 /* Detect redirect loops. No more redirects are allowed
1282 after the same URI is seen twice in a queue item. */
1283 StringVector &R = Redirected[Queue->DestFile];
1284 bool StopRedirects = false;
1285 if (R.size() == 0)
1286 R.push_back(Queue->Uri);
1287 else if (R[0] == "STOP" || R.size() > 10)
1288 StopRedirects = true;
1289 else
1290 {
1291 for (StringVectorIterator I = R.begin(); I != R.end(); I++)
1292 if (Queue->Uri == *I)
1293 {
1294 R[0] = "STOP";
1295 break;
1296 }
1297
1298 R.push_back(Queue->Uri);
1299 }
1300
1301 if (StopRedirects == false)
1302 Redirect(NextURI);
1303 else
1304 Fail();
1305
1306 break;
1307 }
1308
1309 default:
1310 Fail(_("Internal error"));
1311 break;
1312 }
1313
1314 FailCounter = 0;
1315 }
1316
1317 return 0;
1318 }
1319 /*}}}*/
1320
1321 int main()
1322 {
1323 setlocale(LC_ALL, "");
1324 // ignore SIGPIPE, this can happen on write() if the socket
1325 // closes the connection (this is dealt with via ServerDie())
1326 signal(SIGPIPE, SIG_IGN);
1327
1328 HttpMethod Mth;
1329 return Mth.Loop();
1330 }
1331
1332