* merge lp:~mvo/apt/netrc branch, this adds support for a
[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 #include <apt-pkg/netrc.h>
33
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <utime.h>
37 #include <unistd.h>
38 #include <signal.h>
39 #include <stdio.h>
40 #include <errno.h>
41 #include <string.h>
42 #include <iostream>
43 #include <map>
44 #include <apti18n.h>
45
46
47 // Internet stuff
48 #include <netdb.h>
49
50 #include "config.h"
51 #include "connect.h"
52 #include "rfc2553emu.h"
53 #include "http.h"
54 /*}}}*/
55 using namespace std;
56
57 string HttpMethod::FailFile;
58 int HttpMethod::FailFd = -1;
59 time_t HttpMethod::FailTime = 0;
60 unsigned long PipelineDepth = 10;
61 unsigned long TimeOut = 120;
62 bool AllowRedirect = false;
63 bool Debug = false;
64 URI Proxy;
65
66 unsigned long CircleBuf::BwReadLimit=0;
67 unsigned long CircleBuf::BwTickReadData=0;
68 struct timeval CircleBuf::BwReadTick={0,0};
69 const unsigned int CircleBuf::BW_HZ=10;
70
71 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
72 // ---------------------------------------------------------------------
73 /* */
74 CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
75 {
76 Buf = new unsigned char[Size];
77 Reset();
78
79 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
80 }
81 /*}}}*/
82 // CircleBuf::Reset - Reset to the default state /*{{{*/
83 // ---------------------------------------------------------------------
84 /* */
85 void CircleBuf::Reset()
86 {
87 InP = 0;
88 OutP = 0;
89 StrPos = 0;
90 MaxGet = (unsigned int)-1;
91 OutQueue = string();
92 if (Hash != 0)
93 {
94 delete Hash;
95 Hash = new Hashes;
96 }
97 };
98 /*}}}*/
99 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
100 // ---------------------------------------------------------------------
101 /* This fills up the buffer with as much data as is in the FD, assuming it
102 is non-blocking.. */
103 bool CircleBuf::Read(int Fd)
104 {
105 unsigned long BwReadMax;
106
107 while (1)
108 {
109 // Woops, buffer is full
110 if (InP - OutP == Size)
111 return true;
112
113 // what's left to read in this tick
114 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
115
116 if(CircleBuf::BwReadLimit) {
117 struct timeval now;
118 gettimeofday(&now,0);
119
120 unsigned long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
121 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
122 if(d > 1000000/BW_HZ) {
123 CircleBuf::BwReadTick = now;
124 CircleBuf::BwTickReadData = 0;
125 }
126
127 if(CircleBuf::BwTickReadData >= BwReadMax) {
128 usleep(1000000/BW_HZ);
129 return true;
130 }
131 }
132
133 // Write the buffer segment
134 int Res;
135 if(CircleBuf::BwReadLimit) {
136 Res = read(Fd,Buf + (InP%Size),
137 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
138 } else
139 Res = read(Fd,Buf + (InP%Size),LeftRead());
140
141 if(Res > 0 && BwReadLimit > 0)
142 CircleBuf::BwTickReadData += Res;
143
144 if (Res == 0)
145 return false;
146 if (Res < 0)
147 {
148 if (errno == EAGAIN)
149 return true;
150 return false;
151 }
152
153 if (InP == 0)
154 gettimeofday(&Start,0);
155 InP += Res;
156 }
157 }
158 /*}}}*/
159 // CircleBuf::Read - Put the string into the buffer /*{{{*/
160 // ---------------------------------------------------------------------
161 /* This will hold the string in and fill the buffer with it as it empties */
162 bool CircleBuf::Read(string Data)
163 {
164 OutQueue += Data;
165 FillOut();
166 return true;
167 }
168 /*}}}*/
169 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
170 // ---------------------------------------------------------------------
171 /* */
172 void CircleBuf::FillOut()
173 {
174 if (OutQueue.empty() == true)
175 return;
176 while (1)
177 {
178 // Woops, buffer is full
179 if (InP - OutP == Size)
180 return;
181
182 // Write the buffer segment
183 unsigned long Sz = LeftRead();
184 if (OutQueue.length() - StrPos < Sz)
185 Sz = OutQueue.length() - StrPos;
186 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
187
188 // Advance
189 StrPos += Sz;
190 InP += Sz;
191 if (OutQueue.length() == StrPos)
192 {
193 StrPos = 0;
194 OutQueue = "";
195 return;
196 }
197 }
198 }
199 /*}}}*/
200 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
201 // ---------------------------------------------------------------------
202 /* This empties the buffer into the FD. */
203 bool CircleBuf::Write(int Fd)
204 {
205 while (1)
206 {
207 FillOut();
208
209 // Woops, buffer is empty
210 if (OutP == InP)
211 return true;
212
213 if (OutP == MaxGet)
214 return true;
215
216 // Write the buffer segment
217 int Res;
218 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
219
220 if (Res == 0)
221 return false;
222 if (Res < 0)
223 {
224 if (errno == EAGAIN)
225 return true;
226
227 return false;
228 }
229
230 if (Hash != 0)
231 Hash->Add(Buf + (OutP%Size),Res);
232
233 OutP += Res;
234 }
235 }
236 /*}}}*/
237 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
238 // ---------------------------------------------------------------------
239 /* This copies till the first empty line */
240 bool CircleBuf::WriteTillEl(string &Data,bool Single)
241 {
242 // We cheat and assume it is unneeded to have more than one buffer load
243 for (unsigned long I = OutP; I < InP; I++)
244 {
245 if (Buf[I%Size] != '\n')
246 continue;
247 ++I;
248
249 if (Single == false)
250 {
251 if (I < InP && Buf[I%Size] == '\r')
252 ++I;
253 if (I >= InP || Buf[I%Size] != '\n')
254 continue;
255 ++I;
256 }
257
258 Data = "";
259 while (OutP < I)
260 {
261 unsigned long Sz = LeftWrite();
262 if (Sz == 0)
263 return false;
264 if (I - OutP < Sz)
265 Sz = I - OutP;
266 Data += string((char *)(Buf + (OutP%Size)),Sz);
267 OutP += Sz;
268 }
269 return true;
270 }
271 return false;
272 }
273 /*}}}*/
274 // CircleBuf::Stats - Print out stats information /*{{{*/
275 // ---------------------------------------------------------------------
276 /* */
277 void CircleBuf::Stats()
278 {
279 if (InP == 0)
280 return;
281
282 struct timeval Stop;
283 gettimeofday(&Stop,0);
284 /* float Diff = Stop.tv_sec - Start.tv_sec +
285 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
286 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
287 }
288 /*}}}*/
289
290 // ServerState::ServerState - Constructor /*{{{*/
291 // ---------------------------------------------------------------------
292 /* */
293 ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
294 In(64*1024), Out(4*1024),
295 ServerName(Srv)
296 {
297 Reset();
298 }
299 /*}}}*/
300 // ServerState::Open - Open a connection to the server /*{{{*/
301 // ---------------------------------------------------------------------
302 /* This opens a connection to the server. */
303 bool ServerState::Open()
304 {
305 // Use the already open connection if possible.
306 if (ServerFd != -1)
307 return true;
308
309 Close();
310 In.Reset();
311 Out.Reset();
312 Persistent = true;
313
314 // Determine the proxy setting
315 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
316 if (!SpecificProxy.empty())
317 {
318 if (SpecificProxy == "DIRECT")
319 Proxy = "";
320 else
321 Proxy = SpecificProxy;
322 }
323 else
324 {
325 string DefProxy = _config->Find("Acquire::http::Proxy");
326 if (!DefProxy.empty())
327 {
328 Proxy = DefProxy;
329 }
330 else
331 {
332 char* result = getenv("http_proxy");
333 Proxy = result ? result : "";
334 }
335 }
336
337 // Parse no_proxy, a , separated list of domains
338 if (getenv("no_proxy") != 0)
339 {
340 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
341 Proxy = "";
342 }
343
344 // Determine what host and port to use based on the proxy settings
345 int Port = 0;
346 string Host;
347 if (Proxy.empty() == true || Proxy.Host.empty() == true)
348 {
349 if (ServerName.Port != 0)
350 Port = ServerName.Port;
351 Host = ServerName.Host;
352 }
353 else
354 {
355 if (Proxy.Port != 0)
356 Port = Proxy.Port;
357 Host = Proxy.Host;
358 }
359
360 // Connect to the remote server
361 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
362 return false;
363
364 return true;
365 }
366 /*}}}*/
367 // ServerState::Close - Close a connection to the server /*{{{*/
368 // ---------------------------------------------------------------------
369 /* */
370 bool ServerState::Close()
371 {
372 close(ServerFd);
373 ServerFd = -1;
374 return true;
375 }
376 /*}}}*/
377 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
378 // ---------------------------------------------------------------------
379 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
380 parse error occurred */
381 int ServerState::RunHeaders()
382 {
383 State = Header;
384
385 Owner->Status(_("Waiting for headers"));
386
387 Major = 0;
388 Minor = 0;
389 Result = 0;
390 Size = 0;
391 StartPos = 0;
392 Encoding = Closes;
393 HaveContent = false;
394 time(&Date);
395
396 do
397 {
398 string Data;
399 if (In.WriteTillEl(Data) == false)
400 continue;
401
402 if (Debug == true)
403 clog << Data;
404
405 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
406 {
407 string::const_iterator J = I;
408 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
409 if (HeaderLine(string(I,J)) == false)
410 return 2;
411 I = J;
412 }
413
414 // 100 Continue is a Nop...
415 if (Result == 100)
416 continue;
417
418 // Tidy up the connection persistance state.
419 if (Encoding == Closes && HaveContent == true)
420 Persistent = false;
421
422 return 0;
423 }
424 while (Owner->Go(false,this) == true);
425
426 return 1;
427 }
428 /*}}}*/
429 // ServerState::RunData - Transfer the data from the socket /*{{{*/
430 // ---------------------------------------------------------------------
431 /* */
432 bool ServerState::RunData()
433 {
434 State = Data;
435
436 // Chunked transfer encoding is fun..
437 if (Encoding == Chunked)
438 {
439 while (1)
440 {
441 // Grab the block size
442 bool Last = true;
443 string Data;
444 In.Limit(-1);
445 do
446 {
447 if (In.WriteTillEl(Data,true) == true)
448 break;
449 }
450 while ((Last = Owner->Go(false,this)) == true);
451
452 if (Last == false)
453 return false;
454
455 // See if we are done
456 unsigned long Len = strtol(Data.c_str(),0,16);
457 if (Len == 0)
458 {
459 In.Limit(-1);
460
461 // We have to remove the entity trailer
462 Last = true;
463 do
464 {
465 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
466 break;
467 }
468 while ((Last = Owner->Go(false,this)) == true);
469 if (Last == false)
470 return false;
471 return !_error->PendingError();
472 }
473
474 // Transfer the block
475 In.Limit(Len);
476 while (Owner->Go(true,this) == true)
477 if (In.IsLimit() == true)
478 break;
479
480 // Error
481 if (In.IsLimit() == false)
482 return false;
483
484 // The server sends an extra new line before the next block specifier..
485 In.Limit(-1);
486 Last = true;
487 do
488 {
489 if (In.WriteTillEl(Data,true) == true)
490 break;
491 }
492 while ((Last = Owner->Go(false,this)) == true);
493 if (Last == false)
494 return false;
495 }
496 }
497 else
498 {
499 /* Closes encoding is used when the server did not specify a size, the
500 loss of the connection means we are done */
501 if (Encoding == Closes)
502 In.Limit(-1);
503 else
504 In.Limit(Size - StartPos);
505
506 // Just transfer the whole block.
507 do
508 {
509 if (In.IsLimit() == false)
510 continue;
511
512 In.Limit(-1);
513 return !_error->PendingError();
514 }
515 while (Owner->Go(true,this) == true);
516 }
517
518 return Owner->Flush(this) && !_error->PendingError();
519 }
520 /*}}}*/
521 // ServerState::HeaderLine - Process a header line /*{{{*/
522 // ---------------------------------------------------------------------
523 /* */
524 bool ServerState::HeaderLine(string Line)
525 {
526 if (Line.empty() == true)
527 return true;
528
529 // The http server might be trying to do something evil.
530 if (Line.length() >= MAXLEN)
531 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
532
533 string::size_type Pos = Line.find(' ');
534 if (Pos == string::npos || Pos+1 > Line.length())
535 {
536 // Blah, some servers use "connection:closes", evil.
537 Pos = Line.find(':');
538 if (Pos == string::npos || Pos + 2 > Line.length())
539 return _error->Error(_("Bad header line"));
540 Pos++;
541 }
542
543 // Parse off any trailing spaces between the : and the next word.
544 string::size_type Pos2 = Pos;
545 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
546 Pos2++;
547
548 string Tag = string(Line,0,Pos);
549 string Val = string(Line,Pos2);
550
551 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
552 {
553 // Evil servers return no version
554 if (Line[4] == '/')
555 {
556 if (sscanf(Line.c_str(),"HTTP/%u.%u %u%[^\n]",&Major,&Minor,
557 &Result,Code) != 4)
558 return _error->Error(_("The HTTP server sent an invalid reply header"));
559 }
560 else
561 {
562 Major = 0;
563 Minor = 9;
564 if (sscanf(Line.c_str(),"HTTP %u%[^\n]",&Result,Code) != 2)
565 return _error->Error(_("The HTTP server sent an invalid reply header"));
566 }
567
568 /* Check the HTTP response header to get the default persistance
569 state. */
570 if (Major < 1)
571 Persistent = false;
572 else
573 {
574 if (Major == 1 && Minor <= 0)
575 Persistent = false;
576 else
577 Persistent = true;
578 }
579
580 return true;
581 }
582
583 if (stringcasecmp(Tag,"Content-Length:") == 0)
584 {
585 if (Encoding == Closes)
586 Encoding = Stream;
587 HaveContent = true;
588
589 // The length is already set from the Content-Range header
590 if (StartPos != 0)
591 return true;
592
593 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
594 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
595 return true;
596 }
597
598 if (stringcasecmp(Tag,"Content-Type:") == 0)
599 {
600 HaveContent = true;
601 return true;
602 }
603
604 if (stringcasecmp(Tag,"Content-Range:") == 0)
605 {
606 HaveContent = true;
607
608 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
609 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
610 if ((unsigned)StartPos > Size)
611 return _error->Error(_("This HTTP server has broken range support"));
612 return true;
613 }
614
615 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
616 {
617 HaveContent = true;
618 if (stringcasecmp(Val,"chunked") == 0)
619 Encoding = Chunked;
620 return true;
621 }
622
623 if (stringcasecmp(Tag,"Connection:") == 0)
624 {
625 if (stringcasecmp(Val,"close") == 0)
626 Persistent = false;
627 if (stringcasecmp(Val,"keep-alive") == 0)
628 Persistent = true;
629 return true;
630 }
631
632 if (stringcasecmp(Tag,"Last-Modified:") == 0)
633 {
634 if (StrToTime(Val,Date) == false)
635 return _error->Error(_("Unknown date format"));
636 return true;
637 }
638
639 if (stringcasecmp(Tag,"Location:") == 0)
640 {
641 Location = Val;
642 return true;
643 }
644
645 return true;
646 }
647 /*}}}*/
648
649 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
650 // ---------------------------------------------------------------------
651 /* This places the http request in the outbound buffer */
652 void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
653 {
654 URI Uri = Itm->Uri;
655
656 // The HTTP server expects a hostname with a trailing :port
657 char Buf[1000];
658 string ProperHost = Uri.Host;
659 if (Uri.Port != 0)
660 {
661 sprintf(Buf,":%u",Uri.Port);
662 ProperHost += Buf;
663 }
664
665 // Just in case.
666 if (Itm->Uri.length() >= sizeof(Buf))
667 abort();
668
669 /* Build the request. We include a keep-alive header only for non-proxy
670 requests. This is to tweak old http/1.0 servers that do support keep-alive
671 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
672 will glitch HTTP/1.0 proxies because they do not filter it out and
673 pass it on, HTTP/1.1 says the connection should default to keep alive
674 and we expect the proxy to do this */
675 if (Proxy.empty() == true || Proxy.Host.empty())
676 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
677 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
678 else
679 {
680 /* Generate a cache control header if necessary. We place a max
681 cache age on index files, optionally set a no-cache directive
682 and a no-store directive for archives. */
683 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
684 Itm->Uri.c_str(),ProperHost.c_str());
685 // only generate a cache control header if we actually want to
686 // use a cache
687 if (_config->FindB("Acquire::http::No-Cache",false) == false)
688 {
689 if (Itm->IndexFile == true)
690 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
691 _config->FindI("Acquire::http::Max-Age",0));
692 else
693 {
694 if (_config->FindB("Acquire::http::No-Store",false) == true)
695 strcat(Buf,"Cache-Control: no-store\r\n");
696 }
697 }
698 }
699 // generate a no-cache header if needed
700 if (_config->FindB("Acquire::http::No-Cache",false) == true)
701 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
702
703
704 string Req = Buf;
705
706 // Check for a partial file
707 struct stat SBuf;
708 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
709 {
710 // In this case we send an if-range query with a range header
711 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
712 TimeRFC1123(SBuf.st_mtime).c_str());
713 Req += Buf;
714 }
715 else
716 {
717 if (Itm->LastModified != 0)
718 {
719 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
720 Req += Buf;
721 }
722 }
723
724 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
725 Req += string("Proxy-Authorization: Basic ") +
726 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
727
728 maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
729 if (Uri.User.empty() == false || Uri.Password.empty() == false)
730 {
731 Req += string("Authorization: Basic ") +
732 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
733 }
734 Req += "User-Agent: Debian APT-HTTP/1.3 ("VERSION")\r\n\r\n";
735
736 if (Debug == true)
737 cerr << Req << endl;
738
739 Out.Read(Req);
740 }
741 /*}}}*/
742 // HttpMethod::Go - Run a single loop /*{{{*/
743 // ---------------------------------------------------------------------
744 /* This runs the select loop over the server FDs, Output file FDs and
745 stdin. */
746 bool HttpMethod::Go(bool ToFile,ServerState *Srv)
747 {
748 // Server has closed the connection
749 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
750 ToFile == false))
751 return false;
752
753 fd_set rfds,wfds;
754 FD_ZERO(&rfds);
755 FD_ZERO(&wfds);
756
757 /* Add the server. We only send more requests if the connection will
758 be persisting */
759 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
760 && Srv->Persistent == true)
761 FD_SET(Srv->ServerFd,&wfds);
762 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
763 FD_SET(Srv->ServerFd,&rfds);
764
765 // Add the file
766 int FileFD = -1;
767 if (File != 0)
768 FileFD = File->Fd();
769
770 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
771 FD_SET(FileFD,&wfds);
772
773 // Add stdin
774 FD_SET(STDIN_FILENO,&rfds);
775
776 // Figure out the max fd
777 int MaxFd = FileFD;
778 if (MaxFd < Srv->ServerFd)
779 MaxFd = Srv->ServerFd;
780
781 // Select
782 struct timeval tv;
783 tv.tv_sec = TimeOut;
784 tv.tv_usec = 0;
785 int Res = 0;
786 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
787 {
788 if (errno == EINTR)
789 return true;
790 return _error->Errno("select",_("Select failed"));
791 }
792
793 if (Res == 0)
794 {
795 _error->Error(_("Connection timed out"));
796 return ServerDie(Srv);
797 }
798
799 // Handle server IO
800 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
801 {
802 errno = 0;
803 if (Srv->In.Read(Srv->ServerFd) == false)
804 return ServerDie(Srv);
805 }
806
807 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
808 {
809 errno = 0;
810 if (Srv->Out.Write(Srv->ServerFd) == false)
811 return ServerDie(Srv);
812 }
813
814 // Send data to the file
815 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
816 {
817 if (Srv->In.Write(FileFD) == false)
818 return _error->Errno("write",_("Error writing to output file"));
819 }
820
821 // Handle commands from APT
822 if (FD_ISSET(STDIN_FILENO,&rfds))
823 {
824 if (Run(true) != -1)
825 exit(100);
826 }
827
828 return true;
829 }
830 /*}}}*/
831 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
832 // ---------------------------------------------------------------------
833 /* This takes the current input buffer from the Server FD and writes it
834 into the file */
835 bool HttpMethod::Flush(ServerState *Srv)
836 {
837 if (File != 0)
838 {
839 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
840 // can't be set
841 if (File->Name() != "/dev/null")
842 SetNonBlock(File->Fd(),false);
843 if (Srv->In.WriteSpace() == false)
844 return true;
845
846 while (Srv->In.WriteSpace() == true)
847 {
848 if (Srv->In.Write(File->Fd()) == false)
849 return _error->Errno("write",_("Error writing to file"));
850 if (Srv->In.IsLimit() == true)
851 return true;
852 }
853
854 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
855 return true;
856 }
857 return false;
858 }
859 /*}}}*/
860 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
861 // ---------------------------------------------------------------------
862 /* */
863 bool HttpMethod::ServerDie(ServerState *Srv)
864 {
865 unsigned int LErrno = errno;
866
867 // Dump the buffer to the file
868 if (Srv->State == ServerState::Data)
869 {
870 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
871 // can't be set
872 if (File->Name() != "/dev/null")
873 SetNonBlock(File->Fd(),false);
874 while (Srv->In.WriteSpace() == true)
875 {
876 if (Srv->In.Write(File->Fd()) == false)
877 return _error->Errno("write",_("Error writing to the file"));
878
879 // Done
880 if (Srv->In.IsLimit() == true)
881 return true;
882 }
883 }
884
885 // See if this is because the server finished the data stream
886 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
887 Srv->Encoding != ServerState::Closes)
888 {
889 Srv->Close();
890 if (LErrno == 0)
891 return _error->Error(_("Error reading from server. Remote end closed connection"));
892 errno = LErrno;
893 return _error->Errno("read",_("Error reading from server"));
894 }
895 else
896 {
897 Srv->In.Limit(-1);
898
899 // Nothing left in the buffer
900 if (Srv->In.WriteSpace() == false)
901 return false;
902
903 // We may have got multiple responses back in one packet..
904 Srv->Close();
905 return true;
906 }
907
908 return false;
909 }
910 /*}}}*/
911 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
912 // ---------------------------------------------------------------------
913 /* We look at the header data we got back from the server and decide what
914 to do. Returns
915 0 - File is open,
916 1 - IMS hit
917 3 - Unrecoverable error
918 4 - Error with error content page
919 5 - Unrecoverable non-server error (close the connection)
920 6 - Try again with a new or changed URI
921 */
922 int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
923 {
924 // Not Modified
925 if (Srv->Result == 304)
926 {
927 unlink(Queue->DestFile.c_str());
928 Res.IMSHit = true;
929 Res.LastModified = Queue->LastModified;
930 return 1;
931 }
932
933 /* Redirect
934 *
935 * Note that it is only OK for us to treat all redirection the same
936 * because we *always* use GET, not other HTTP methods. There are
937 * three redirection codes for which it is not appropriate that we
938 * redirect. Pass on those codes so the error handling kicks in.
939 */
940 if (AllowRedirect
941 && (Srv->Result > 300 && Srv->Result < 400)
942 && (Srv->Result != 300 // Multiple Choices
943 && Srv->Result != 304 // Not Modified
944 && Srv->Result != 306)) // (Not part of HTTP/1.1, reserved)
945 {
946 if (!Srv->Location.empty())
947 {
948 NextURI = Srv->Location;
949 return 6;
950 }
951 /* else pass through for error message */
952 }
953
954 /* We have a reply we dont handle. This should indicate a perm server
955 failure */
956 if (Srv->Result < 200 || Srv->Result >= 300)
957 {
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 int main()
1325 {
1326 setlocale(LC_ALL, "");
1327 // ignore SIGPIPE, this can happen on write() if the socket
1328 // closes the connection (this is dealt with via ServerDie())
1329 signal(SIGPIPE, SIG_IGN);
1330
1331 HttpMethod Mth;
1332 return Mth.Loop();
1333 }
1334
1335