merged from the mvo branch
[ntk/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: Ubuntu 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 char err[255];
956 snprintf(err,sizeof(err)-1,"HttpError%i",Srv->Result);
957 SetFailReason(err);
958 _error->Error("%u %s",Srv->Result,Srv->Code);
959 if (Srv->HaveContent == true)
960 return 4;
961 return 3;
962 }
963
964 // This is some sort of 2xx 'data follows' reply
965 Res.LastModified = Srv->Date;
966 Res.Size = Srv->Size;
967
968 // Open the file
969 delete File;
970 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
971 if (_error->PendingError() == true)
972 return 5;
973
974 FailFile = Queue->DestFile;
975 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
976 FailFd = File->Fd();
977 FailTime = Srv->Date;
978
979 // Set the expected size
980 if (Srv->StartPos >= 0)
981 {
982 Res.ResumePoint = Srv->StartPos;
983 if (ftruncate(File->Fd(),Srv->StartPos) < 0)
984 _error->Errno("ftruncate", _("Failed to truncate file"));
985 }
986
987 // Set the start point
988 lseek(File->Fd(),0,SEEK_END);
989
990 delete Srv->In.Hash;
991 Srv->In.Hash = new Hashes;
992
993 // Fill the Hash if the file is non-empty (resume)
994 if (Srv->StartPos > 0)
995 {
996 lseek(File->Fd(),0,SEEK_SET);
997 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
998 {
999 _error->Errno("read",_("Problem hashing file"));
1000 return 5;
1001 }
1002 lseek(File->Fd(),0,SEEK_END);
1003 }
1004
1005 SetNonBlock(File->Fd(),true);
1006 return 0;
1007 }
1008 /*}}}*/
1009 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1010 // ---------------------------------------------------------------------
1011 /* This closes and timestamps the open file. This is neccessary to get
1012 resume behavoir on user abort */
1013 void HttpMethod::SigTerm(int)
1014 {
1015 if (FailFd == -1)
1016 _exit(100);
1017 close(FailFd);
1018
1019 // Timestamp
1020 struct utimbuf UBuf;
1021 UBuf.actime = FailTime;
1022 UBuf.modtime = FailTime;
1023 utime(FailFile.c_str(),&UBuf);
1024
1025 _exit(100);
1026 }
1027 /*}}}*/
1028 // HttpMethod::Fetch - Fetch an item /*{{{*/
1029 // ---------------------------------------------------------------------
1030 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1031 depth. */
1032 bool HttpMethod::Fetch(FetchItem *)
1033 {
1034 if (Server == 0)
1035 return true;
1036
1037 // Queue the requests
1038 int Depth = -1;
1039 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1040 I = I->Next, Depth++)
1041 {
1042 // If pipelining is disabled, we only queue 1 request
1043 if (Server->Pipeline == false && Depth >= 0)
1044 break;
1045
1046 // Make sure we stick with the same server
1047 if (Server->Comp(I->Uri) == false)
1048 break;
1049 if (QueueBack == I)
1050 {
1051 QueueBack = I->Next;
1052 SendReq(I,Server->Out);
1053 continue;
1054 }
1055 }
1056
1057 return true;
1058 };
1059 /*}}}*/
1060 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1061 // ---------------------------------------------------------------------
1062 /* We stash the desired pipeline depth */
1063 bool HttpMethod::Configuration(string Message)
1064 {
1065 if (pkgAcqMethod::Configuration(Message) == false)
1066 return false;
1067
1068 AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
1069 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1070 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1071 PipelineDepth);
1072 Debug = _config->FindB("Debug::Acquire::http",false);
1073
1074 return true;
1075 }
1076 /*}}}*/
1077 // HttpMethod::Loop - Main loop /*{{{*/
1078 // ---------------------------------------------------------------------
1079 /* */
1080 int HttpMethod::Loop()
1081 {
1082 typedef vector<string> StringVector;
1083 typedef vector<string>::iterator StringVectorIterator;
1084 map<string, StringVector> Redirected;
1085
1086 signal(SIGTERM,SigTerm);
1087 signal(SIGINT,SigTerm);
1088
1089 Server = 0;
1090
1091 int FailCounter = 0;
1092 while (1)
1093 {
1094 // We have no commands, wait for some to arrive
1095 if (Queue == 0)
1096 {
1097 if (WaitFd(STDIN_FILENO) == false)
1098 return 0;
1099 }
1100
1101 /* Run messages, we can accept 0 (no message) if we didn't
1102 do a WaitFd above.. Otherwise the FD is closed. */
1103 int Result = Run(true);
1104 if (Result != -1 && (Result != 0 || Queue == 0))
1105 return 100;
1106
1107 if (Queue == 0)
1108 continue;
1109
1110 // Connect to the server
1111 if (Server == 0 || Server->Comp(Queue->Uri) == false)
1112 {
1113 delete Server;
1114 Server = new ServerState(Queue->Uri,this);
1115 }
1116 /* If the server has explicitly said this is the last connection
1117 then we pre-emptively shut down the pipeline and tear down
1118 the connection. This will speed up HTTP/1.0 servers a tad
1119 since we don't have to wait for the close sequence to
1120 complete */
1121 if (Server->Persistent == false)
1122 Server->Close();
1123
1124 // Reset the pipeline
1125 if (Server->ServerFd == -1)
1126 QueueBack = Queue;
1127
1128 // Connnect to the host
1129 if (Server->Open() == false)
1130 {
1131 Fail(true);
1132 delete Server;
1133 Server = 0;
1134 continue;
1135 }
1136
1137 // Fill the pipeline.
1138 Fetch(0);
1139
1140 // Fetch the next URL header data from the server.
1141 switch (Server->RunHeaders())
1142 {
1143 case 0:
1144 break;
1145
1146 // The header data is bad
1147 case 2:
1148 {
1149 _error->Error(_("Bad header data"));
1150 Fail(true);
1151 RotateDNS();
1152 continue;
1153 }
1154
1155 // The server closed a connection during the header get..
1156 default:
1157 case 1:
1158 {
1159 FailCounter++;
1160 _error->Discard();
1161 Server->Close();
1162 Server->Pipeline = false;
1163
1164 if (FailCounter >= 2)
1165 {
1166 Fail(_("Connection failed"),true);
1167 FailCounter = 0;
1168 }
1169
1170 RotateDNS();
1171 continue;
1172 }
1173 };
1174
1175 // Decide what to do.
1176 FetchResult Res;
1177 Res.Filename = Queue->DestFile;
1178 switch (DealWithHeaders(Res,Server))
1179 {
1180 // Ok, the file is Open
1181 case 0:
1182 {
1183 URIStart(Res);
1184
1185 // Run the data
1186 bool Result = Server->RunData();
1187
1188 /* If the server is sending back sizeless responses then fill in
1189 the size now */
1190 if (Res.Size == 0)
1191 Res.Size = File->Size();
1192
1193 // Close the file, destroy the FD object and timestamp it
1194 FailFd = -1;
1195 delete File;
1196 File = 0;
1197
1198 // Timestamp
1199 struct utimbuf UBuf;
1200 time(&UBuf.actime);
1201 UBuf.actime = Server->Date;
1202 UBuf.modtime = Server->Date;
1203 utime(Queue->DestFile.c_str(),&UBuf);
1204
1205 // Send status to APT
1206 if (Result == true)
1207 {
1208 Res.TakeHashes(*Server->In.Hash);
1209 URIDone(Res);
1210 }
1211 else
1212 {
1213 if (Server->ServerFd == -1)
1214 {
1215 FailCounter++;
1216 _error->Discard();
1217 Server->Close();
1218
1219 if (FailCounter >= 2)
1220 {
1221 Fail(_("Connection failed"),true);
1222 FailCounter = 0;
1223 }
1224
1225 QueueBack = Queue;
1226 }
1227 else
1228 Fail(true);
1229 }
1230 break;
1231 }
1232
1233 // IMS hit
1234 case 1:
1235 {
1236 URIDone(Res);
1237 break;
1238 }
1239
1240 // Hard server error, not found or something
1241 case 3:
1242 {
1243 Fail();
1244 break;
1245 }
1246
1247 // Hard internal error, kill the connection and fail
1248 case 5:
1249 {
1250 delete File;
1251 File = 0;
1252
1253 Fail();
1254 RotateDNS();
1255 Server->Close();
1256 break;
1257 }
1258
1259 // We need to flush the data, the header is like a 404 w/ error text
1260 case 4:
1261 {
1262 Fail();
1263
1264 // Send to content to dev/null
1265 File = new FileFd("/dev/null",FileFd::WriteExists);
1266 Server->RunData();
1267 delete File;
1268 File = 0;
1269 break;
1270 }
1271
1272 // Try again with a new URL
1273 case 6:
1274 {
1275 // Clear rest of response if there is content
1276 if (Server->HaveContent)
1277 {
1278 File = new FileFd("/dev/null",FileFd::WriteExists);
1279 Server->RunData();
1280 delete File;
1281 File = 0;
1282 }
1283
1284 /* Detect redirect loops. No more redirects are allowed
1285 after the same URI is seen twice in a queue item. */
1286 StringVector &R = Redirected[Queue->DestFile];
1287 bool StopRedirects = false;
1288 if (R.size() == 0)
1289 R.push_back(Queue->Uri);
1290 else if (R[0] == "STOP" || R.size() > 10)
1291 StopRedirects = true;
1292 else
1293 {
1294 for (StringVectorIterator I = R.begin(); I != R.end(); I++)
1295 if (Queue->Uri == *I)
1296 {
1297 R[0] = "STOP";
1298 break;
1299 }
1300
1301 R.push_back(Queue->Uri);
1302 }
1303
1304 if (StopRedirects == false)
1305 Redirect(NextURI);
1306 else
1307 Fail();
1308
1309 break;
1310 }
1311
1312 default:
1313 Fail(_("Internal error"));
1314 break;
1315 }
1316
1317 FailCounter = 0;
1318 }
1319
1320 return 0;
1321 }
1322 /*}}}*/
1323
1324