]>
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>
58 unsigned long long CircleBuf::BwReadLimit
=0;
59 unsigned long long CircleBuf::BwTickReadData
=0;
60 struct timeval
CircleBuf::BwReadTick
={0,0};
61 const unsigned int CircleBuf::BW_HZ
=10;
63 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
64 // ---------------------------------------------------------------------
66 CircleBuf::CircleBuf(unsigned long long Size
) : Size(Size
), Hash(0)
68 Buf
= new unsigned char[Size
];
71 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
74 // CircleBuf::Reset - Reset to the default state /*{{{*/
75 // ---------------------------------------------------------------------
77 void CircleBuf::Reset()
82 MaxGet
= (unsigned long long)-1;
91 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
92 // ---------------------------------------------------------------------
93 /* This fills up the buffer with as much data as is in the FD, assuming it
95 bool CircleBuf::Read(int Fd
)
99 // Woops, buffer is full
100 if (InP
- OutP
== Size
)
103 // what's left to read in this tick
104 unsigned long long const BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
106 if(CircleBuf::BwReadLimit
) {
108 gettimeofday(&now
,0);
110 unsigned long long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
111 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
112 if(d
> 1000000/BW_HZ
) {
113 CircleBuf::BwReadTick
= now
;
114 CircleBuf::BwTickReadData
= 0;
117 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
118 usleep(1000000/BW_HZ
);
123 // Write the buffer segment
125 if(CircleBuf::BwReadLimit
) {
126 Res
= read(Fd
,Buf
+ (InP%Size
),
127 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
129 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
131 if(Res
> 0 && BwReadLimit
> 0)
132 CircleBuf::BwTickReadData
+= Res
;
144 gettimeofday(&Start
,0);
149 // CircleBuf::Read - Put the string into the buffer /*{{{*/
150 // ---------------------------------------------------------------------
151 /* This will hold the string in and fill the buffer with it as it empties */
152 bool CircleBuf::Read(string Data
)
159 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
160 // ---------------------------------------------------------------------
162 void CircleBuf::FillOut()
164 if (OutQueue
.empty() == true)
168 // Woops, buffer is full
169 if (InP
- OutP
== Size
)
172 // Write the buffer segment
173 unsigned long long Sz
= LeftRead();
174 if (OutQueue
.length() - StrPos
< Sz
)
175 Sz
= OutQueue
.length() - StrPos
;
176 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
181 if (OutQueue
.length() == StrPos
)
190 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
191 // ---------------------------------------------------------------------
192 /* This empties the buffer into the FD. */
193 bool CircleBuf::Write(int Fd
)
199 // Woops, buffer is empty
206 // Write the buffer segment
208 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
221 Hash
->Add(Buf
+ (OutP%Size
),Res
);
227 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
228 // ---------------------------------------------------------------------
229 /* This copies till the first empty line */
230 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
232 // We cheat and assume it is unneeded to have more than one buffer load
233 for (unsigned long long I
= OutP
; I
< InP
; I
++)
235 if (Buf
[I%Size
] != '\n')
241 if (I
< InP
&& Buf
[I%Size
] == '\r')
243 if (I
>= InP
|| Buf
[I%Size
] != '\n')
251 unsigned long long Sz
= LeftWrite();
256 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
264 // CircleBuf::Stats - Print out stats information /*{{{*/
265 // ---------------------------------------------------------------------
267 void CircleBuf::Stats()
273 gettimeofday(&Stop
,0);
274 /* float Diff = Stop.tv_sec - Start.tv_sec +
275 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
276 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
279 CircleBuf::~CircleBuf()
285 // HttpServerState::HttpServerState - Constructor /*{{{*/
286 HttpServerState::HttpServerState(URI Srv
,HttpMethod
*Owner
) : ServerState(Srv
, Owner
), In(64*1024), Out(4*1024)
288 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
292 // HttpServerState::Open - Open a connection to the server /*{{{*/
293 // ---------------------------------------------------------------------
294 /* This opens a connection to the server. */
295 bool HttpServerState::Open()
297 // Use the already open connection if possible.
306 // Determine the proxy setting
307 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
308 if (!SpecificProxy
.empty())
310 if (SpecificProxy
== "DIRECT")
313 Proxy
= SpecificProxy
;
317 string DefProxy
= _config
->Find("Acquire::http::Proxy");
318 if (!DefProxy
.empty())
324 char* result
= getenv("http_proxy");
325 Proxy
= result
? result
: "";
329 // Parse no_proxy, a , separated list of domains
330 if (getenv("no_proxy") != 0)
332 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
336 // Determine what host and port to use based on the proxy settings
339 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
341 if (ServerName
.Port
!= 0)
342 Port
= ServerName
.Port
;
343 Host
= ServerName
.Host
;
352 // Connect to the remote server
353 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
359 // HttpServerState::Close - Close a connection to the server /*{{{*/
360 // ---------------------------------------------------------------------
362 bool HttpServerState::Close()
369 // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
370 bool HttpServerState::RunData(FileFd
* const File
)
374 // Chunked transfer encoding is fun..
375 if (Encoding
== Chunked
)
379 // Grab the block size
385 if (In
.WriteTillEl(Data
,true) == true)
388 while ((Last
= Go(false, File
)) == true);
393 // See if we are done
394 unsigned long long Len
= strtoull(Data
.c_str(),0,16);
399 // We have to remove the entity trailer
403 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
406 while ((Last
= Go(false, File
)) == true);
409 return !_error
->PendingError();
412 // Transfer the block
414 while (Go(true, File
) == true)
415 if (In
.IsLimit() == true)
419 if (In
.IsLimit() == false)
422 // The server sends an extra new line before the next block specifier..
427 if (In
.WriteTillEl(Data
,true) == true)
430 while ((Last
= Go(false, File
)) == true);
437 /* Closes encoding is used when the server did not specify a size, the
438 loss of the connection means we are done */
439 if (Encoding
== Closes
)
442 In
.Limit(Size
- StartPos
);
444 // Just transfer the whole block.
447 if (In
.IsLimit() == false)
451 return !_error
->PendingError();
453 while (Go(true, File
) == true);
456 return Owner
->Flush() && !_error
->PendingError();
459 bool HttpServerState::ReadHeaderLines(std::string
&Data
) /*{{{*/
461 return In
.WriteTillEl(Data
);
464 bool HttpServerState::LoadNextResponse(bool const ToFile
, FileFd
* const File
)/*{{{*/
466 return Go(ToFile
, File
);
469 bool HttpServerState::WriteResponse(const std::string
&Data
) /*{{{*/
471 return Out
.Read(Data
);
474 APT_PURE
bool HttpServerState::IsOpen() /*{{{*/
476 return (ServerFd
!= -1);
479 bool HttpServerState::InitHashes(FileFd
&File
) /*{{{*/
482 In
.Hash
= new Hashes
;
484 // Set the expected size and read file for the hashes
485 File
.Truncate(StartPos
);
486 return In
.Hash
->AddFD(File
, StartPos
);
489 APT_PURE Hashes
* HttpServerState::GetHashes() /*{{{*/
494 // HttpServerState::Die - The server has closed the connection. /*{{{*/
495 bool HttpServerState::Die(FileFd
&File
)
497 unsigned int LErrno
= errno
;
499 // Dump the buffer to the file
500 if (State
== ServerState::Data
)
502 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
504 if (File
.Name() != "/dev/null")
505 SetNonBlock(File
.Fd(),false);
506 while (In
.WriteSpace() == true)
508 if (In
.Write(File
.Fd()) == false)
509 return _error
->Errno("write",_("Error writing to the file"));
512 if (In
.IsLimit() == true)
517 // See if this is because the server finished the data stream
518 if (In
.IsLimit() == false && State
!= HttpServerState::Header
&&
519 Encoding
!= HttpServerState::Closes
)
523 return _error
->Error(_("Error reading from server. Remote end closed connection"));
525 return _error
->Errno("read",_("Error reading from server"));
531 // Nothing left in the buffer
532 if (In
.WriteSpace() == false)
535 // We may have got multiple responses back in one packet..
543 // HttpServerState::Flush - Dump the buffer into the file /*{{{*/
544 // ---------------------------------------------------------------------
545 /* This takes the current input buffer from the Server FD and writes it
547 bool HttpServerState::Flush(FileFd
* const File
)
551 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
553 if (File
->Name() != "/dev/null")
554 SetNonBlock(File
->Fd(),false);
555 if (In
.WriteSpace() == false)
558 while (In
.WriteSpace() == true)
560 if (In
.Write(File
->Fd()) == false)
561 return _error
->Errno("write",_("Error writing to file"));
562 if (In
.IsLimit() == true)
566 if (In
.IsLimit() == true || Encoding
== ServerState::Closes
)
572 // HttpServerState::Go - Run a single loop /*{{{*/
573 // ---------------------------------------------------------------------
574 /* This runs the select loop over the server FDs, Output file FDs and
576 bool HttpServerState::Go(bool ToFile
, FileFd
* const File
)
578 // Server has closed the connection
579 if (ServerFd
== -1 && (In
.WriteSpace() == false ||
587 /* Add the server. We only send more requests if the connection will
589 if (Out
.WriteSpace() == true && ServerFd
!= -1
590 && Persistent
== true)
591 FD_SET(ServerFd
,&wfds
);
592 if (In
.ReadSpace() == true && ServerFd
!= -1)
593 FD_SET(ServerFd
,&rfds
);
600 if (In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
601 FD_SET(FileFD
,&wfds
);
604 if (_config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
605 FD_SET(STDIN_FILENO
,&rfds
);
607 // Figure out the max fd
609 if (MaxFd
< ServerFd
)
617 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
621 return _error
->Errno("select",_("Select failed"));
626 _error
->Error(_("Connection timed out"));
631 if (ServerFd
!= -1 && FD_ISSET(ServerFd
,&rfds
))
634 if (In
.Read(ServerFd
) == false)
638 if (ServerFd
!= -1 && FD_ISSET(ServerFd
,&wfds
))
641 if (Out
.Write(ServerFd
) == false)
645 // Send data to the file
646 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
648 if (In
.Write(FileFD
) == false)
649 return _error
->Errno("write",_("Error writing to output file"));
652 // Handle commands from APT
653 if (FD_ISSET(STDIN_FILENO
,&rfds
))
655 if (Owner
->Run(true) != -1)
663 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
664 // ---------------------------------------------------------------------
665 /* This places the http request in the outbound buffer */
666 void HttpMethod::SendReq(FetchItem
*Itm
)
670 // The HTTP server expects a hostname with a trailing :port
671 std::stringstream Req
;
674 if (Uri
.Host
.find(':') != string::npos
)
675 ProperHost
= '[' + Uri
.Host
+ ']';
677 ProperHost
= Uri
.Host
;
679 /* RFC 2616 ยง5.1.2 requires absolute URIs for requests to proxies,
680 but while its a must for all servers to accept absolute URIs,
681 it is assumed clients will sent an absolute path for non-proxies */
682 std::string requesturi
;
683 if (Server
->Proxy
.empty() == true || Server
->Proxy
.Host
.empty())
684 requesturi
= Uri
.Path
;
686 requesturi
= Itm
->Uri
;
688 // The "+" is encoded as a workaround for a amazon S3 bug
689 // see LP bugs #1003633 and #1086997.
690 requesturi
= QuoteString(requesturi
, "+~ ");
692 /* Build the request. No keep-alive is included as it is the default
693 in 1.1, can cause problems with proxies, and we are an HTTP/1.1
695 C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
696 Req
<< "GET " << requesturi
<< " HTTP/1.1\r\n";
698 Req
<< "Host: " << ProperHost
<< ":" << Uri
.Port
<< "\r\n";
700 Req
<< "Host: " << ProperHost
<< "\r\n";
702 // generate a cache control header (if needed)
703 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
704 Req
<< "Cache-Control: no-cache\r\n"
705 << "Pragma: no-cache\r\n";
706 else if (Itm
->IndexFile
== true)
707 Req
<< "Cache-Control: max-age=" << _config
->FindI("Acquire::http::Max-Age",0) << "\r\n";
708 else if (_config
->FindB("Acquire::http::No-Store",false) == true)
709 Req
<< "Cache-Control: no-store\r\n";
711 // If we ask for uncompressed files servers might respond with content-
712 // negotiation which lets us end up with compressed files we do not support,
713 // see 657029, 657560 and co, so if we have no extension on the request
714 // ask for text only. As a sidenote: If there is nothing to negotate servers
715 // seem to be nice and ignore it.
716 if (_config
->FindB("Acquire::http::SendAccept", true) == true)
718 size_t const filepos
= Itm
->Uri
.find_last_of('/');
719 string
const file
= Itm
->Uri
.substr(filepos
+ 1);
720 if (flExtension(file
) == file
)
721 Req
<< "Accept: text/*\r\n";
724 // Check for a partial file and send if-queries accordingly
726 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
727 Req
<< "Range: bytes=" << SBuf
.st_size
<< "-\r\n"
728 << "If-Range: " << TimeRFC1123(SBuf
.st_mtime
) << "\r\n";
729 else if (Itm
->LastModified
!= 0)
730 Req
<< "If-Modified-Since: " << TimeRFC1123(Itm
->LastModified
).c_str() << "\r\n";
732 if (Server
->Proxy
.User
.empty() == false || Server
->Proxy
.Password
.empty() == false)
733 Req
<< "Proxy-Authorization: Basic "
734 << Base64Encode(Server
->Proxy
.User
+ ":" + Server
->Proxy
.Password
) << "\r\n";
736 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
737 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
738 Req
<< "Authorization: Basic "
739 << Base64Encode(Uri
.User
+ ":" + Uri
.Password
) << "\r\n";
741 Req
<< "User-Agent: " << _config
->Find("Acquire::http::User-Agent",
742 "Debian APT-HTTP/1.3 (" PACKAGE_VERSION
")") << "\r\n";
749 Server
->WriteResponse(Req
.str());
752 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
753 // ---------------------------------------------------------------------
754 /* We stash the desired pipeline depth */
755 bool HttpMethod::Configuration(string Message
)
757 if (ServerMethod::Configuration(Message
) == false)
760 AllowRedirect
= _config
->FindB("Acquire::http::AllowRedirect",true);
761 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
763 Debug
= _config
->FindB("Debug::Acquire::http",false);
765 // Get the proxy to use
771 // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
772 // ---------------------------------------------------------------------
774 bool HttpMethod::AutoDetectProxy()
776 // option is "Acquire::http::Proxy-Auto-Detect" but we allow the old
777 // name without the dash ("-")
778 AutoDetectProxyCmd
= _config
->Find("Acquire::http::Proxy-Auto-Detect",
779 _config
->Find("Acquire::http::ProxyAutoDetect"));
781 if (AutoDetectProxyCmd
.empty())
785 clog
<< "Using auto proxy detect command: " << AutoDetectProxyCmd
<< endl
;
787 int Pipes
[2] = {-1,-1};
788 if (pipe(Pipes
) != 0)
789 return _error
->Errno("pipe", "Failed to create Pipe");
791 pid_t Process
= ExecFork();
795 dup2(Pipes
[1],STDOUT_FILENO
);
796 SetCloseExec(STDOUT_FILENO
,false);
799 Args
[0] = AutoDetectProxyCmd
.c_str();
801 execv(Args
[0],(char **)Args
);
802 cerr
<< "Failed to exec method " << Args
[0] << endl
;
808 int res
= read(InFd
, buf
, sizeof(buf
)-1);
809 ExecWait(Process
, "ProxyAutoDetect", true);
812 return _error
->Errno("read", "Failed to read");
814 return _error
->Warning("ProxyAutoDetect returned no data");
820 clog
<< "auto detect command returned: '" << buf
<< "'" << endl
;
822 if (strstr(buf
, "http://") == buf
)
823 _config
->Set("Acquire::http::proxy", _strstrip(buf
));
828 ServerState
* HttpMethod::CreateServerState(URI uri
) /*{{{*/
830 return new HttpServerState(uri
, this);
833 void HttpMethod::RotateDNS() /*{{{*/