1 // -*- mode: cpp; mode: fold -*-
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
6 HTTP Acquire Method - This is the HTTP aquire method for APT.
8 It uses HTTP/1.1 and many of the fancy options there-in, such as
9 pipelining, range, if-range and so on.
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).
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.
25 ##################################################################### */
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>
49 #include "rfc2553emu.h"
55 string
HttpMethod::FailFile
;
56 int HttpMethod::FailFd
= -1;
57 time_t HttpMethod::FailTime
= 0;
58 unsigned long PipelineDepth
= 10;
59 unsigned long TimeOut
= 120;
60 bool AllowRedirect
= false;
64 unsigned long CircleBuf::BwReadLimit
=0;
65 unsigned long CircleBuf::BwTickReadData
=0;
66 struct timeval
CircleBuf::BwReadTick
={0,0};
67 const unsigned int CircleBuf::BW_HZ
=10;
69 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
70 // ---------------------------------------------------------------------
72 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
74 Buf
= new unsigned char[Size
];
77 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
80 // CircleBuf::Reset - Reset to the default state /*{{{*/
81 // ---------------------------------------------------------------------
83 void CircleBuf::Reset()
88 MaxGet
= (unsigned int)-1;
97 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
98 // ---------------------------------------------------------------------
99 /* This fills up the buffer with as much data as is in the FD, assuming it
101 bool CircleBuf::Read(int Fd
)
103 unsigned long BwReadMax
;
107 // Woops, buffer is full
108 if (InP
- OutP
== Size
)
111 // what's left to read in this tick
112 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
114 if(CircleBuf::BwReadLimit
) {
116 gettimeofday(&now
,0);
118 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
119 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
120 if(d
> 1000000/BW_HZ
) {
121 CircleBuf::BwReadTick
= now
;
122 CircleBuf::BwTickReadData
= 0;
125 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
126 usleep(1000000/BW_HZ
);
131 // Write the buffer segment
133 if(CircleBuf::BwReadLimit
) {
134 Res
= read(Fd
,Buf
+ (InP%Size
),
135 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
137 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
139 if(Res
> 0 && BwReadLimit
> 0)
140 CircleBuf::BwTickReadData
+= Res
;
152 gettimeofday(&Start
,0);
157 // CircleBuf::Read - Put the string into the buffer /*{{{*/
158 // ---------------------------------------------------------------------
159 /* This will hold the string in and fill the buffer with it as it empties */
160 bool CircleBuf::Read(string Data
)
167 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
168 // ---------------------------------------------------------------------
170 void CircleBuf::FillOut()
172 if (OutQueue
.empty() == true)
176 // Woops, buffer is full
177 if (InP
- OutP
== Size
)
180 // Write the buffer segment
181 unsigned long Sz
= LeftRead();
182 if (OutQueue
.length() - StrPos
< Sz
)
183 Sz
= OutQueue
.length() - StrPos
;
184 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
189 if (OutQueue
.length() == StrPos
)
198 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
199 // ---------------------------------------------------------------------
200 /* This empties the buffer into the FD. */
201 bool CircleBuf::Write(int Fd
)
207 // Woops, buffer is empty
214 // Write the buffer segment
216 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
229 Hash
->Add(Buf
+ (OutP%Size
),Res
);
235 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
236 // ---------------------------------------------------------------------
237 /* This copies till the first empty line */
238 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
240 // We cheat and assume it is unneeded to have more than one buffer load
241 for (unsigned long I
= OutP
; I
< InP
; I
++)
243 if (Buf
[I%Size
] != '\n')
249 if (I
< InP
&& Buf
[I%Size
] == '\r')
251 if (I
>= InP
|| Buf
[I%Size
] != '\n')
259 unsigned long Sz
= LeftWrite();
264 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
272 // CircleBuf::Stats - Print out stats information /*{{{*/
273 // ---------------------------------------------------------------------
275 void CircleBuf::Stats()
281 gettimeofday(&Stop
,0);
282 /* float Diff = Stop.tv_sec - Start.tv_sec +
283 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
284 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
288 // ServerState::ServerState - Constructor /*{{{*/
289 // ---------------------------------------------------------------------
291 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
292 In(64*1024), Out(4*1024),
298 // ServerState::Open - Open a connection to the server /*{{{*/
299 // ---------------------------------------------------------------------
300 /* This opens a connection to the server. */
301 bool ServerState::Open()
303 // Use the already open connection if possible.
312 // Determine the proxy setting
313 if (getenv("http_proxy") == 0)
315 string DefProxy
= _config
->Find("Acquire::http::Proxy");
316 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
317 if (SpecificProxy
.empty() == false)
319 if (SpecificProxy
== "DIRECT")
322 Proxy
= SpecificProxy
;
328 Proxy
= getenv("http_proxy");
330 // Parse no_proxy, a , separated list of domains
331 if (getenv("no_proxy") != 0)
333 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
337 // Determine what host and port to use based on the proxy settings
340 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
342 if (ServerName
.Port
!= 0)
343 Port
= ServerName
.Port
;
344 Host
= ServerName
.Host
;
353 // Connect to the remote server
354 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
360 // ServerState::Close - Close a connection to the server /*{{{*/
361 // ---------------------------------------------------------------------
363 bool ServerState::Close()
370 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
371 // ---------------------------------------------------------------------
372 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
373 parse error occurred */
374 int ServerState::RunHeaders()
378 Owner
->Status(_("Waiting for headers"));
392 if (In
.WriteTillEl(Data
) == false)
398 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
400 string::const_iterator J
= I
;
401 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
402 if (HeaderLine(string(I
,J
)) == false)
407 // 100 Continue is a Nop...
411 // Tidy up the connection persistance state.
412 if (Encoding
== Closes
&& HaveContent
== true)
417 while (Owner
->Go(false,this) == true);
422 // ServerState::RunData - Transfer the data from the socket /*{{{*/
423 // ---------------------------------------------------------------------
425 bool ServerState::RunData()
429 // Chunked transfer encoding is fun..
430 if (Encoding
== Chunked
)
434 // Grab the block size
440 if (In
.WriteTillEl(Data
,true) == true)
443 while ((Last
= Owner
->Go(false,this)) == true);
448 // See if we are done
449 unsigned long Len
= strtol(Data
.c_str(),0,16);
454 // We have to remove the entity trailer
458 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
461 while ((Last
= Owner
->Go(false,this)) == true);
464 return !_error
->PendingError();
467 // Transfer the block
469 while (Owner
->Go(true,this) == true)
470 if (In
.IsLimit() == true)
474 if (In
.IsLimit() == false)
477 // The server sends an extra new line before the next block specifier..
482 if (In
.WriteTillEl(Data
,true) == true)
485 while ((Last
= Owner
->Go(false,this)) == true);
492 /* Closes encoding is used when the server did not specify a size, the
493 loss of the connection means we are done */
494 if (Encoding
== Closes
)
497 In
.Limit(Size
- StartPos
);
499 // Just transfer the whole block.
502 if (In
.IsLimit() == false)
506 return !_error
->PendingError();
508 while (Owner
->Go(true,this) == true);
511 return Owner
->Flush(this) && !_error
->PendingError();
514 // ServerState::HeaderLine - Process a header line /*{{{*/
515 // ---------------------------------------------------------------------
517 bool ServerState::HeaderLine(string Line
)
519 if (Line
.empty() == true)
522 // The http server might be trying to do something evil.
523 if (Line
.length() >= MAXLEN
)
524 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
526 string::size_type Pos
= Line
.find(' ');
527 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
529 // Blah, some servers use "connection:closes", evil.
530 Pos
= Line
.find(':');
531 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
532 return _error
->Error(_("Bad header line"));
536 // Parse off any trailing spaces between the : and the next word.
537 string::size_type Pos2
= Pos
;
538 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
541 string Tag
= string(Line
,0,Pos
);
542 string Val
= string(Line
,Pos2
);
544 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
546 // Evil servers return no version
549 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
551 return _error
->Error(_("The HTTP server sent an invalid reply header"));
557 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
558 return _error
->Error(_("The HTTP server sent an invalid reply header"));
561 /* Check the HTTP response header to get the default persistance
567 if (Major
== 1 && Minor
<= 0)
576 if (stringcasecmp(Tag
,"Content-Length:") == 0)
578 if (Encoding
== Closes
)
582 // The length is already set from the Content-Range header
586 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
587 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
591 if (stringcasecmp(Tag
,"Content-Type:") == 0)
597 if (stringcasecmp(Tag
,"Content-Range:") == 0)
601 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
602 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
603 if ((unsigned)StartPos
> Size
)
604 return _error
->Error(_("This HTTP server has broken range support"));
608 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
611 if (stringcasecmp(Val
,"chunked") == 0)
616 if (stringcasecmp(Tag
,"Connection:") == 0)
618 if (stringcasecmp(Val
,"close") == 0)
620 if (stringcasecmp(Val
,"keep-alive") == 0)
625 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
627 if (StrToTime(Val
,Date
) == false)
628 return _error
->Error(_("Unknown date format"));
632 if (stringcasecmp(Tag
,"Location:") == 0)
642 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
643 // ---------------------------------------------------------------------
644 /* This places the http request in the outbound buffer */
645 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
649 // The HTTP server expects a hostname with a trailing :port
651 string ProperHost
= Uri
.Host
;
654 sprintf(Buf
,":%u",Uri
.Port
);
659 if (Itm
->Uri
.length() >= sizeof(Buf
))
662 /* Build the request. We include a keep-alive header only for non-proxy
663 requests. This is to tweak old http/1.0 servers that do support keep-alive
664 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
665 will glitch HTTP/1.0 proxies because they do not filter it out and
666 pass it on, HTTP/1.1 says the connection should default to keep alive
667 and we expect the proxy to do this */
668 if (Proxy
.empty() == true || Proxy
.Host
.empty())
669 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
670 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
673 /* Generate a cache control header if necessary. We place a max
674 cache age on index files, optionally set a no-cache directive
675 and a no-store directive for archives. */
676 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
677 Itm
->Uri
.c_str(),ProperHost
.c_str());
678 // only generate a cache control header if we actually want to
680 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
682 if (Itm
->IndexFile
== true)
683 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
684 _config
->FindI("Acquire::http::Max-Age",0));
687 if (_config
->FindB("Acquire::http::No-Store",false) == true)
688 strcat(Buf
,"Cache-Control: no-store\r\n");
692 // generate a no-cache header if needed
693 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
694 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
699 // Check for a partial file
701 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
703 // In this case we send an if-range query with a range header
704 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
705 TimeRFC1123(SBuf
.st_mtime
).c_str());
710 if (Itm
->LastModified
!= 0)
712 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
717 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
718 Req
+= string("Proxy-Authorization: Basic ") +
719 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
721 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
722 Req
+= string("Authorization: Basic ") +
723 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
725 Req
+= "User-Agent: Ubuntu APT-HTTP/1.3 ("VERSION
")\r\n\r\n";
733 // HttpMethod::Go - Run a single loop /*{{{*/
734 // ---------------------------------------------------------------------
735 /* This runs the select loop over the server FDs, Output file FDs and
737 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
739 // Server has closed the connection
740 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
748 /* Add the server. We only send more requests if the connection will
750 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
751 && Srv
->Persistent
== true)
752 FD_SET(Srv
->ServerFd
,&wfds
);
753 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
754 FD_SET(Srv
->ServerFd
,&rfds
);
761 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
762 FD_SET(FileFD
,&wfds
);
765 FD_SET(STDIN_FILENO
,&rfds
);
767 // Figure out the max fd
769 if (MaxFd
< Srv
->ServerFd
)
770 MaxFd
= Srv
->ServerFd
;
777 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
781 return _error
->Errno("select",_("Select failed"));
786 _error
->Error(_("Connection timed out"));
787 return ServerDie(Srv
);
791 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
794 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
795 return ServerDie(Srv
);
798 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
801 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
802 return ServerDie(Srv
);
805 // Send data to the file
806 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
808 if (Srv
->In
.Write(FileFD
) == false)
809 return _error
->Errno("write",_("Error writing to output file"));
812 // Handle commands from APT
813 if (FD_ISSET(STDIN_FILENO
,&rfds
))
822 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
823 // ---------------------------------------------------------------------
824 /* This takes the current input buffer from the Server FD and writes it
826 bool HttpMethod::Flush(ServerState
*Srv
)
830 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
832 if (File
->Name() != "/dev/null")
833 SetNonBlock(File
->Fd(),false);
834 if (Srv
->In
.WriteSpace() == false)
837 while (Srv
->In
.WriteSpace() == true)
839 if (Srv
->In
.Write(File
->Fd()) == false)
840 return _error
->Errno("write",_("Error writing to file"));
841 if (Srv
->In
.IsLimit() == true)
845 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
851 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
852 // ---------------------------------------------------------------------
854 bool HttpMethod::ServerDie(ServerState
*Srv
)
856 unsigned int LErrno
= errno
;
858 // Dump the buffer to the file
859 if (Srv
->State
== ServerState::Data
)
861 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
863 if (File
->Name() != "/dev/null")
864 SetNonBlock(File
->Fd(),false);
865 while (Srv
->In
.WriteSpace() == true)
867 if (Srv
->In
.Write(File
->Fd()) == false)
868 return _error
->Errno("write",_("Error writing to the file"));
871 if (Srv
->In
.IsLimit() == true)
876 // See if this is because the server finished the data stream
877 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
878 Srv
->Encoding
!= ServerState::Closes
)
882 return _error
->Error(_("Error reading from server. Remote end closed connection"));
884 return _error
->Errno("read",_("Error reading from server"));
890 // Nothing left in the buffer
891 if (Srv
->In
.WriteSpace() == false)
894 // We may have got multiple responses back in one packet..
902 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
903 // ---------------------------------------------------------------------
904 /* We look at the header data we got back from the server and decide what
908 3 - Unrecoverable error
909 4 - Error with error content page
910 5 - Unrecoverable non-server error (close the connection)
911 6 - Try again with a new or changed URI
913 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
916 if (Srv
->Result
== 304)
918 unlink(Queue
->DestFile
.c_str());
920 Res
.LastModified
= Queue
->LastModified
;
926 * Note that it is only OK for us to treat all redirection the same
927 * because we *always* use GET, not other HTTP methods. There are
928 * three redirection codes for which it is not appropriate that we
929 * redirect. Pass on those codes so the error handling kicks in.
932 && (Srv
->Result
> 300 && Srv
->Result
< 400)
933 && (Srv
->Result
!= 300 // Multiple Choices
934 && Srv
->Result
!= 304 // Not Modified
935 && Srv
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
937 if (!Srv
->Location
.empty())
939 NextURI
= Srv
->Location
;
942 /* else pass through for error message */
945 /* We have a reply we dont handle. This should indicate a perm server
947 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
950 snprintf(err
,sizeof(err
)-1,"HttpError%i",Srv
->Result
);
952 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
953 if (Srv
->HaveContent
== true)
958 // This is some sort of 2xx 'data follows' reply
959 Res
.LastModified
= Srv
->Date
;
960 Res
.Size
= Srv
->Size
;
964 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
965 if (_error
->PendingError() == true)
968 FailFile
= Queue
->DestFile
;
969 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
971 FailTime
= Srv
->Date
;
973 // Set the expected size
974 if (Srv
->StartPos
>= 0)
976 Res
.ResumePoint
= Srv
->StartPos
;
977 if (ftruncate(File
->Fd(),Srv
->StartPos
) < 0)
978 _error
->Errno("ftruncate", _("Failed to truncate file"));
981 // Set the start point
982 lseek(File
->Fd(),0,SEEK_END
);
985 Srv
->In
.Hash
= new Hashes
;
987 // Fill the Hash if the file is non-empty (resume)
988 if (Srv
->StartPos
> 0)
990 lseek(File
->Fd(),0,SEEK_SET
);
991 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
993 _error
->Errno("read",_("Problem hashing file"));
996 lseek(File
->Fd(),0,SEEK_END
);
999 SetNonBlock(File
->Fd(),true);
1003 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1004 // ---------------------------------------------------------------------
1005 /* This closes and timestamps the open file. This is neccessary to get
1006 resume behavoir on user abort */
1007 void HttpMethod::SigTerm(int)
1014 struct utimbuf UBuf
;
1015 UBuf
.actime
= FailTime
;
1016 UBuf
.modtime
= FailTime
;
1017 utime(FailFile
.c_str(),&UBuf
);
1022 // HttpMethod::Fetch - Fetch an item /*{{{*/
1023 // ---------------------------------------------------------------------
1024 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1026 bool HttpMethod::Fetch(FetchItem
*)
1031 // Queue the requests
1033 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1034 I
= I
->Next
, Depth
++)
1036 // If pipelining is disabled, we only queue 1 request
1037 if (Server
->Pipeline
== false && Depth
>= 0)
1040 // Make sure we stick with the same server
1041 if (Server
->Comp(I
->Uri
) == false)
1045 QueueBack
= I
->Next
;
1046 SendReq(I
,Server
->Out
);
1054 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1055 // ---------------------------------------------------------------------
1056 /* We stash the desired pipeline depth */
1057 bool HttpMethod::Configuration(string Message
)
1059 if (pkgAcqMethod::Configuration(Message
) == false)
1062 AllowRedirect
= _config
->FindB("Acquire::http::AllowRedirect",true);
1063 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1064 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1066 Debug
= _config
->FindB("Debug::Acquire::http",false);
1071 // HttpMethod::Loop - Main loop /*{{{*/
1072 // ---------------------------------------------------------------------
1074 int HttpMethod::Loop()
1076 typedef vector
<string
> StringVector
;
1077 typedef vector
<string
>::iterator StringVectorIterator
;
1078 map
<string
, StringVector
> Redirected
;
1080 signal(SIGTERM
,SigTerm
);
1081 signal(SIGINT
,SigTerm
);
1085 int FailCounter
= 0;
1088 // We have no commands, wait for some to arrive
1091 if (WaitFd(STDIN_FILENO
) == false)
1095 /* Run messages, we can accept 0 (no message) if we didn't
1096 do a WaitFd above.. Otherwise the FD is closed. */
1097 int Result
= Run(true);
1098 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1104 // Connect to the server
1105 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
1108 Server
= new ServerState(Queue
->Uri
,this);
1110 /* If the server has explicitly said this is the last connection
1111 then we pre-emptively shut down the pipeline and tear down
1112 the connection. This will speed up HTTP/1.0 servers a tad
1113 since we don't have to wait for the close sequence to
1115 if (Server
->Persistent
== false)
1118 // Reset the pipeline
1119 if (Server
->ServerFd
== -1)
1122 // Connnect to the host
1123 if (Server
->Open() == false)
1131 // Fill the pipeline.
1134 // Fetch the next URL header data from the server.
1135 switch (Server
->RunHeaders())
1140 // The header data is bad
1143 _error
->Error(_("Bad header data"));
1149 // The server closed a connection during the header get..
1156 Server
->Pipeline
= false;
1158 if (FailCounter
>= 2)
1160 Fail(_("Connection failed"),true);
1169 // Decide what to do.
1171 Res
.Filename
= Queue
->DestFile
;
1172 switch (DealWithHeaders(Res
,Server
))
1174 // Ok, the file is Open
1180 bool Result
= Server
->RunData();
1182 /* If the server is sending back sizeless responses then fill in
1185 Res
.Size
= File
->Size();
1187 // Close the file, destroy the FD object and timestamp it
1193 struct utimbuf UBuf
;
1195 UBuf
.actime
= Server
->Date
;
1196 UBuf
.modtime
= Server
->Date
;
1197 utime(Queue
->DestFile
.c_str(),&UBuf
);
1199 // Send status to APT
1202 Res
.TakeHashes(*Server
->In
.Hash
);
1207 if (Server
->ServerFd
== -1)
1213 if (FailCounter
>= 2)
1215 Fail(_("Connection failed"),true);
1234 // Hard server error, not found or something
1241 // Hard internal error, kill the connection and fail
1253 // We need to flush the data, the header is like a 404 w/ error text
1258 // Send to content to dev/null
1259 File
= new FileFd("/dev/null",FileFd::WriteExists
);
1266 // Try again with a new URL
1269 // Clear rest of response if there is content
1270 if (Server
->HaveContent
)
1272 File
= new FileFd("/dev/null",FileFd::WriteExists
);
1278 /* Detect redirect loops. No more redirects are allowed
1279 after the same URI is seen twice in a queue item. */
1280 StringVector
&R
= Redirected
[Queue
->DestFile
];
1281 bool StopRedirects
= false;
1283 R
.push_back(Queue
->Uri
);
1284 else if (R
[0] == "STOP" || R
.size() > 10)
1285 StopRedirects
= true;
1288 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); I
++)
1289 if (Queue
->Uri
== *I
)
1295 R
.push_back(Queue
->Uri
);
1298 if (StopRedirects
== false)
1307 Fail(_("Internal error"));