]>
git.saurik.com Git - apt.git/blob - methods/http.cc
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 acquire 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 /*{{{*/
30 #include <apt-pkg/fileutl.h>
31 #include <apt-pkg/acquire-method.h>
32 #include <apt-pkg/configuration.h>
33 #include <apt-pkg/error.h>
34 #include <apt-pkg/hashes.h>
35 #include <apt-pkg/netrc.h>
36 #include <apt-pkg/strutl.h>
40 #include <sys/select.h>
57 unsigned long long CircleBuf::BwReadLimit
=0;
58 unsigned long long CircleBuf::BwTickReadData
=0;
59 struct timeval
CircleBuf::BwReadTick
={0,0};
60 const unsigned int CircleBuf::BW_HZ
=10;
62 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
63 // ---------------------------------------------------------------------
65 CircleBuf::CircleBuf(unsigned long long Size
) : Size(Size
), Hash(0)
67 Buf
= new unsigned char[Size
];
70 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
73 // CircleBuf::Reset - Reset to the default state /*{{{*/
74 // ---------------------------------------------------------------------
76 void CircleBuf::Reset()
81 MaxGet
= (unsigned long long)-1;
90 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
91 // ---------------------------------------------------------------------
92 /* This fills up the buffer with as much data as is in the FD, assuming it
94 bool CircleBuf::Read(int Fd
)
98 // Woops, buffer is full
99 if (InP
- OutP
== Size
)
102 // what's left to read in this tick
103 unsigned long long const BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
105 if(CircleBuf::BwReadLimit
) {
107 gettimeofday(&now
,0);
109 unsigned long long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
110 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
111 if(d
> 1000000/BW_HZ
) {
112 CircleBuf::BwReadTick
= now
;
113 CircleBuf::BwTickReadData
= 0;
116 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
117 usleep(1000000/BW_HZ
);
122 // Write the buffer segment
124 if(CircleBuf::BwReadLimit
) {
125 Res
= read(Fd
,Buf
+ (InP%Size
),
126 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
128 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
130 if(Res
> 0 && BwReadLimit
> 0)
131 CircleBuf::BwTickReadData
+= Res
;
143 gettimeofday(&Start
,0);
148 // CircleBuf::Read - Put the string into the buffer /*{{{*/
149 // ---------------------------------------------------------------------
150 /* This will hold the string in and fill the buffer with it as it empties */
151 bool CircleBuf::Read(string Data
)
158 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
159 // ---------------------------------------------------------------------
161 void CircleBuf::FillOut()
163 if (OutQueue
.empty() == true)
167 // Woops, buffer is full
168 if (InP
- OutP
== Size
)
171 // Write the buffer segment
172 unsigned long long Sz
= LeftRead();
173 if (OutQueue
.length() - StrPos
< Sz
)
174 Sz
= OutQueue
.length() - StrPos
;
175 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
180 if (OutQueue
.length() == StrPos
)
189 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
190 // ---------------------------------------------------------------------
191 /* This empties the buffer into the FD. */
192 bool CircleBuf::Write(int Fd
)
198 // Woops, buffer is empty
205 // Write the buffer segment
207 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
220 Hash
->Add(Buf
+ (OutP%Size
),Res
);
226 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
227 // ---------------------------------------------------------------------
228 /* This copies till the first empty line */
229 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
231 // We cheat and assume it is unneeded to have more than one buffer load
232 for (unsigned long long I
= OutP
; I
< InP
; I
++)
234 if (Buf
[I%Size
] != '\n')
240 if (I
< InP
&& Buf
[I%Size
] == '\r')
242 if (I
>= InP
|| Buf
[I%Size
] != '\n')
250 unsigned long long Sz
= LeftWrite();
255 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
263 // CircleBuf::Stats - Print out stats information /*{{{*/
264 // ---------------------------------------------------------------------
266 void CircleBuf::Stats()
272 gettimeofday(&Stop
,0);
273 /* float Diff = Stop.tv_sec - Start.tv_sec +
274 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
275 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
278 CircleBuf::~CircleBuf()
284 // HttpServerState::HttpServerState - Constructor /*{{{*/
285 HttpServerState::HttpServerState(URI Srv
,HttpMethod
*Owner
) : ServerState(Srv
, Owner
), In(64*1024), Out(4*1024)
287 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
291 // HttpServerState::Open - Open a connection to the server /*{{{*/
292 // ---------------------------------------------------------------------
293 /* This opens a connection to the server. */
294 bool HttpServerState::Open()
296 // Use the already open connection if possible.
305 // Determine the proxy setting
306 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
307 if (!SpecificProxy
.empty())
309 if (SpecificProxy
== "DIRECT")
312 Proxy
= SpecificProxy
;
316 string DefProxy
= _config
->Find("Acquire::http::Proxy");
317 if (!DefProxy
.empty())
323 char* result
= getenv("http_proxy");
324 Proxy
= result
? result
: "";
328 // Parse no_proxy, a , separated list of domains
329 if (getenv("no_proxy") != 0)
331 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
335 // Determine what host and port to use based on the proxy settings
338 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
340 if (ServerName
.Port
!= 0)
341 Port
= ServerName
.Port
;
342 Host
= ServerName
.Host
;
351 // Connect to the remote server
352 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
358 // HttpServerState::Close - Close a connection to the server /*{{{*/
359 // ---------------------------------------------------------------------
361 bool HttpServerState::Close()
368 // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
369 bool HttpServerState::RunData(FileFd
* const File
)
373 // Chunked transfer encoding is fun..
374 if (Encoding
== Chunked
)
378 // Grab the block size
384 if (In
.WriteTillEl(Data
,true) == true)
387 while ((Last
= Go(false, File
)) == true);
392 // See if we are done
393 unsigned long long Len
= strtoull(Data
.c_str(),0,16);
398 // We have to remove the entity trailer
402 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
405 while ((Last
= Go(false, File
)) == true);
408 return !_error
->PendingError();
411 // Transfer the block
413 while (Go(true, File
) == true)
414 if (In
.IsLimit() == true)
418 if (In
.IsLimit() == false)
421 // The server sends an extra new line before the next block specifier..
426 if (In
.WriteTillEl(Data
,true) == true)
429 while ((Last
= Go(false, File
)) == true);
436 /* Closes encoding is used when the server did not specify a size, the
437 loss of the connection means we are done */
438 if (Encoding
== Closes
)
441 In
.Limit(Size
- StartPos
);
443 // Just transfer the whole block.
446 if (In
.IsLimit() == false)
450 return !_error
->PendingError();
452 while (Go(true, File
) == true);
455 return Owner
->Flush() && !_error
->PendingError();
458 bool HttpServerState::ReadHeaderLines(std::string
&Data
) /*{{{*/
460 return In
.WriteTillEl(Data
);
463 bool HttpServerState::LoadNextResponse(bool const ToFile
, FileFd
* const File
)/*{{{*/
465 return Go(ToFile
, File
);
468 bool HttpServerState::WriteResponse(const std::string
&Data
) /*{{{*/
470 return Out
.Read(Data
);
473 APT_PURE
bool HttpServerState::IsOpen() /*{{{*/
475 return (ServerFd
!= -1);
478 bool HttpServerState::InitHashes(FileFd
&File
) /*{{{*/
481 In
.Hash
= new Hashes
;
483 // Set the expected size and read file for the hashes
484 File
.Truncate(StartPos
);
485 return In
.Hash
->AddFD(File
, StartPos
);
488 APT_PURE Hashes
* HttpServerState::GetHashes() /*{{{*/
493 // HttpServerState::Die - The server has closed the connection. /*{{{*/
494 bool HttpServerState::Die(FileFd
&File
)
496 unsigned int LErrno
= errno
;
498 // Dump the buffer to the file
499 if (State
== ServerState::Data
)
501 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
503 if (File
.Name() != "/dev/null")
504 SetNonBlock(File
.Fd(),false);
505 while (In
.WriteSpace() == true)
507 if (In
.Write(File
.Fd()) == false)
508 return _error
->Errno("write",_("Error writing to the file"));
511 if (In
.IsLimit() == true)
516 // See if this is because the server finished the data stream
517 if (In
.IsLimit() == false && State
!= HttpServerState::Header
&&
518 Encoding
!= HttpServerState::Closes
)
522 return _error
->Error(_("Error reading from server. Remote end closed connection"));
524 return _error
->Errno("read",_("Error reading from server"));
530 // Nothing left in the buffer
531 if (In
.WriteSpace() == false)
534 // We may have got multiple responses back in one packet..
542 // HttpServerState::Flush - Dump the buffer into the file /*{{{*/
543 // ---------------------------------------------------------------------
544 /* This takes the current input buffer from the Server FD and writes it
546 bool HttpServerState::Flush(FileFd
* const File
)
550 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
552 if (File
->Name() != "/dev/null")
553 SetNonBlock(File
->Fd(),false);
554 if (In
.WriteSpace() == false)
557 while (In
.WriteSpace() == true)
559 if (In
.Write(File
->Fd()) == false)
560 return _error
->Errno("write",_("Error writing to file"));
561 if (In
.IsLimit() == true)
565 if (In
.IsLimit() == true || Encoding
== ServerState::Closes
)
571 // HttpServerState::Go - Run a single loop /*{{{*/
572 // ---------------------------------------------------------------------
573 /* This runs the select loop over the server FDs, Output file FDs and
575 bool HttpServerState::Go(bool ToFile
, FileFd
* const File
)
577 // Server has closed the connection
578 if (ServerFd
== -1 && (In
.WriteSpace() == false ||
586 /* Add the server. We only send more requests if the connection will
588 if (Out
.WriteSpace() == true && ServerFd
!= -1
589 && Persistent
== true)
590 FD_SET(ServerFd
,&wfds
);
591 if (In
.ReadSpace() == true && ServerFd
!= -1)
592 FD_SET(ServerFd
,&rfds
);
599 if (In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
600 FD_SET(FileFD
,&wfds
);
603 if (_config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
604 FD_SET(STDIN_FILENO
,&rfds
);
606 // Figure out the max fd
608 if (MaxFd
< ServerFd
)
616 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
620 return _error
->Errno("select",_("Select failed"));
625 _error
->Error(_("Connection timed out"));
630 if (ServerFd
!= -1 && FD_ISSET(ServerFd
,&rfds
))
633 if (In
.Read(ServerFd
) == false)
637 if (ServerFd
!= -1 && FD_ISSET(ServerFd
,&wfds
))
640 if (Out
.Write(ServerFd
) == false)
644 // Send data to the file
645 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
647 if (In
.Write(FileFD
) == false)
648 return _error
->Errno("write",_("Error writing to output file"));
651 // Handle commands from APT
652 if (FD_ISSET(STDIN_FILENO
,&rfds
))
654 if (Owner
->Run(true) != -1)
662 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
663 // ---------------------------------------------------------------------
664 /* This places the http request in the outbound buffer */
665 void HttpMethod::SendReq(FetchItem
*Itm
)
669 // The HTTP server expects a hostname with a trailing :port
673 if (Uri
.Host
.find(':') != string::npos
)
674 ProperHost
= '[' + Uri
.Host
+ ']';
676 ProperHost
= Uri
.Host
;
679 sprintf(Buf
,":%u",Uri
.Port
);
684 if (Itm
->Uri
.length() >= sizeof(Buf
))
687 /* RFC 2616 ยง5.1.2 requires absolute URIs for requests to proxies,
688 but while its a must for all servers to accept absolute URIs,
689 it is assumed clients will sent an absolute path for non-proxies */
690 std::string requesturi
;
691 if (Server
->Proxy
.empty() == true || Server
->Proxy
.Host
.empty())
692 requesturi
= Uri
.Path
;
694 requesturi
= Itm
->Uri
;
696 // The "+" is encoded as a workaround for a amazon S3 bug
697 // see LP bugs #1003633 and #1086997.
698 requesturi
= QuoteString(requesturi
, "+~ ");
700 /* Build the request. No keep-alive is included as it is the default
701 in 1.1, can cause problems with proxies, and we are an HTTP/1.1
703 C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
704 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
705 requesturi
.c_str(),ProperHost
.c_str());
707 // generate a cache control header (if needed)
708 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
710 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
714 if (Itm
->IndexFile
== true)
716 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
717 _config
->FindI("Acquire::http::Max-Age",0));
721 if (_config
->FindB("Acquire::http::No-Store",false) == true)
722 strcat(Buf
,"Cache-Control: no-store\r\n");
726 // If we ask for uncompressed files servers might respond with content-
727 // negotiation which lets us end up with compressed files we do not support,
728 // see 657029, 657560 and co, so if we have no extension on the request
729 // ask for text only. As a sidenote: If there is nothing to negotate servers
730 // seem to be nice and ignore it.
731 if (_config
->FindB("Acquire::http::SendAccept", true) == true)
733 size_t const filepos
= Itm
->Uri
.find_last_of('/');
734 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
735 if (flExtension(file
) == file
)
736 strcat(Buf
,"Accept: text/*\r\n");
741 // Check for a partial file
743 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
745 // In this case we send an if-range query with a range header
746 sprintf(Buf
,"Range: bytes=%lli-\r\nIf-Range: %s\r\n",(long long)SBuf
.st_size
,
747 TimeRFC1123(SBuf
.st_mtime
).c_str());
752 if (Itm
->LastModified
!= 0)
754 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
759 if (Server
->Proxy
.User
.empty() == false || Server
->Proxy
.Password
.empty() == false)
760 Req
+= string("Proxy-Authorization: Basic ") +
761 Base64Encode(Server
->Proxy
.User
+ ":" + Server
->Proxy
.Password
) + "\r\n";
763 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
764 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
766 Req
+= string("Authorization: Basic ") +
767 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
769 Req
+= "User-Agent: " + _config
->Find("Acquire::http::User-Agent",
770 "Debian APT-HTTP/1.3 (" PACKAGE_VERSION
")") + "\r\n\r\n";
775 Server
->WriteResponse(Req
);
778 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
779 // ---------------------------------------------------------------------
780 /* We stash the desired pipeline depth */
781 bool HttpMethod::Configuration(string Message
)
783 if (ServerMethod::Configuration(Message
) == false)
786 AllowRedirect
= _config
->FindB("Acquire::http::AllowRedirect",true);
787 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
789 Debug
= _config
->FindB("Debug::Acquire::http",false);
791 // Get the proxy to use
797 // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
798 // ---------------------------------------------------------------------
800 bool HttpMethod::AutoDetectProxy()
802 // option is "Acquire::http::Proxy-Auto-Detect" but we allow the old
803 // name without the dash ("-")
804 AutoDetectProxyCmd
= _config
->Find("Acquire::http::Proxy-Auto-Detect",
805 _config
->Find("Acquire::http::ProxyAutoDetect"));
807 if (AutoDetectProxyCmd
.empty())
811 clog
<< "Using auto proxy detect command: " << AutoDetectProxyCmd
<< endl
;
813 int Pipes
[2] = {-1,-1};
814 if (pipe(Pipes
) != 0)
815 return _error
->Errno("pipe", "Failed to create Pipe");
817 pid_t Process
= ExecFork();
821 dup2(Pipes
[1],STDOUT_FILENO
);
822 SetCloseExec(STDOUT_FILENO
,false);
825 Args
[0] = AutoDetectProxyCmd
.c_str();
827 execv(Args
[0],(char **)Args
);
828 cerr
<< "Failed to exec method " << Args
[0] << endl
;
834 int res
= read(InFd
, buf
, sizeof(buf
)-1);
835 ExecWait(Process
, "ProxyAutoDetect", true);
838 return _error
->Errno("read", "Failed to read");
840 return _error
->Warning("ProxyAutoDetect returned no data");
846 clog
<< "auto detect command returned: '" << buf
<< "'" << endl
;
848 if (strstr(buf
, "http://") == buf
)
849 _config
->Set("Acquire::http::proxy", _strstrip(buf
));
854 ServerState
* HttpMethod::CreateServerState(URI uri
) /*{{{*/
856 return new HttpServerState(uri
, this);
859 void HttpMethod::RotateDNS() /*{{{*/