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>
32 #include <apt-pkg/netrc.h>
34 #include <sys/sysctl.h>
51 #include <arpa/inet.h>
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <CoreServices/CoreServices.h>
56 #include <SystemConfiguration/SystemConfiguration.h>
60 #include "rfc2553emu.h"
65 CFStringRef Firmware_
;
67 CFStringRef UniqueID_
;
69 void CfrsError(const char *name
, CFReadStreamRef rs
) {
70 CFStreamError se
= CFReadStreamGetError(rs
);
72 if (se
.domain
== kCFStreamErrorDomainCustom
) {
73 } else if (se
.domain
== kCFStreamErrorDomainPOSIX
) {
74 _error
->Error("POSIX: %s", strerror(se
.error
));
75 } else if (se
.domain
== kCFStreamErrorDomainMacOSStatus
) {
76 _error
->Error("MacOSStatus: %ld", se
.error
);
77 } else if (se
.domain
== kCFStreamErrorDomainNetDB
) {
78 _error
->Error("NetDB: %s %s", name
, gai_strerror(se
.error
));
79 } else if (se
.domain
== kCFStreamErrorDomainMach
) {
80 _error
->Error("Mach: %ld", se
.error
);
81 } else if (se
.domain
== kCFStreamErrorDomainHTTP
) {
83 case kCFStreamErrorHTTPParseFailure
:
84 _error
->Error("Parse failure");
87 case kCFStreamErrorHTTPRedirectionLoop
:
88 _error
->Error("Redirection loop");
91 case kCFStreamErrorHTTPBadURL
:
92 _error
->Error("Bad URL");
96 _error
->Error("Unknown HTTP error: %ld", se
.error
);
99 } else if (se
.domain
== kCFStreamErrorDomainSOCKS
) {
100 _error
->Error("SOCKS: %ld", se
.error
);
101 } else if (se
.domain
== kCFStreamErrorDomainSystemConfiguration
) {
102 _error
->Error("SystemConfiguration: %ld", se
.error
);
103 } else if (se
.domain
== kCFStreamErrorDomainSSL
) {
104 _error
->Error("SSL: %ld", se
.error
);
106 _error
->Error("Domain #%ld: %ld", se
.domain
, se
.error
);
110 string
HttpMethod::FailFile
;
111 int HttpMethod::FailFd
= -1;
112 time_t HttpMethod::FailTime
= 0;
113 unsigned long PipelineDepth
= 10;
114 unsigned long TimeOut
= 120;
115 bool AllowRedirect
= false;
119 unsigned long CircleBuf::BwReadLimit
=0;
120 unsigned long CircleBuf::BwTickReadData
=0;
121 struct timeval
CircleBuf::BwReadTick
={0,0};
122 const unsigned int CircleBuf::BW_HZ
=10;
124 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
125 // ---------------------------------------------------------------------
127 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
129 Buf
= new unsigned char[Size
];
132 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
135 // CircleBuf::Reset - Reset to the default state /*{{{*/
136 // ---------------------------------------------------------------------
138 void CircleBuf::Reset()
143 MaxGet
= (unsigned int)-1;
152 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
153 // ---------------------------------------------------------------------
154 /* This fills up the buffer with as much data as is in the FD, assuming it
156 bool CircleBuf::Read(int Fd
)
158 unsigned long BwReadMax
;
162 // Woops, buffer is full
163 if (InP
- OutP
== Size
)
166 // what's left to read in this tick
167 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
169 if(CircleBuf::BwReadLimit
) {
171 gettimeofday(&now
,0);
173 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
174 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
175 if(d
> 1000000/BW_HZ
) {
176 CircleBuf::BwReadTick
= now
;
177 CircleBuf::BwTickReadData
= 0;
180 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
181 usleep(1000000/BW_HZ
);
186 // Write the buffer segment
188 if(CircleBuf::BwReadLimit
) {
189 Res
= read(Fd
,Buf
+ (InP%Size
),
190 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
192 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
194 if(Res
> 0 && BwReadLimit
> 0)
195 CircleBuf::BwTickReadData
+= Res
;
207 gettimeofday(&Start
,0);
212 // CircleBuf::Read - Put the string into the buffer /*{{{*/
213 // ---------------------------------------------------------------------
214 /* This will hold the string in and fill the buffer with it as it empties */
215 bool CircleBuf::Read(string Data
)
222 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
223 // ---------------------------------------------------------------------
225 void CircleBuf::FillOut()
227 if (OutQueue
.empty() == true)
231 // Woops, buffer is full
232 if (InP
- OutP
== Size
)
235 // Write the buffer segment
236 unsigned long Sz
= LeftRead();
237 if (OutQueue
.length() - StrPos
< Sz
)
238 Sz
= OutQueue
.length() - StrPos
;
239 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
244 if (OutQueue
.length() == StrPos
)
253 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
254 // ---------------------------------------------------------------------
255 /* This empties the buffer into the FD. */
256 bool CircleBuf::Write(int Fd
)
262 // Woops, buffer is empty
269 // Write the buffer segment
271 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
284 Hash
->Add(Buf
+ (OutP%Size
),Res
);
290 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
291 // ---------------------------------------------------------------------
292 /* This copies till the first empty line */
293 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
295 // We cheat and assume it is unneeded to have more than one buffer load
296 for (unsigned long I
= OutP
; I
< InP
; I
++)
298 if (Buf
[I%Size
] != '\n')
304 if (I
< InP
&& Buf
[I%Size
] == '\r')
306 if (I
>= InP
|| Buf
[I%Size
] != '\n')
314 unsigned long Sz
= LeftWrite();
319 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
327 // CircleBuf::Stats - Print out stats information /*{{{*/
328 // ---------------------------------------------------------------------
330 void CircleBuf::Stats()
336 gettimeofday(&Stop
,0);
337 /* float Diff = Stop.tv_sec - Start.tv_sec +
338 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
339 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
343 // ServerState::ServerState - Constructor /*{{{*/
344 // ---------------------------------------------------------------------
346 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
347 In(64*1024), Out(4*1024),
353 // ServerState::Open - Open a connection to the server /*{{{*/
354 // ---------------------------------------------------------------------
355 /* This opens a connection to the server. */
356 bool ServerState::Open()
358 // Use the already open connection if possible.
367 // Determine the proxy setting
368 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
369 if (!SpecificProxy
.empty())
371 if (SpecificProxy
== "DIRECT")
374 Proxy
= SpecificProxy
;
378 string DefProxy
= _config
->Find("Acquire::http::Proxy");
379 if (!DefProxy
.empty())
385 char* result
= getenv("http_proxy");
386 Proxy
= result
? result
: "";
390 // Parse no_proxy, a , separated list of domains
391 if (getenv("no_proxy") != 0)
393 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
397 // Determine what host and port to use based on the proxy settings
400 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
402 if (ServerName
.Port
!= 0)
403 Port
= ServerName
.Port
;
404 Host
= ServerName
.Host
;
413 // Connect to the remote server
414 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
420 // ServerState::Close - Close a connection to the server /*{{{*/
421 // ---------------------------------------------------------------------
423 bool ServerState::Close()
430 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
431 // ---------------------------------------------------------------------
432 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
433 parse error occurred */
434 int ServerState::RunHeaders()
438 Owner
->Status(_("Waiting for headers"));
452 if (In
.WriteTillEl(Data
) == false)
458 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
460 string::const_iterator J
= I
;
461 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
462 if (HeaderLine(string(I
,J
)) == false)
467 // 100 Continue is a Nop...
471 // Tidy up the connection persistance state.
472 if (Encoding
== Closes
&& HaveContent
== true)
477 while (Owner
->Go(false,this) == true);
482 // ServerState::RunData - Transfer the data from the socket /*{{{*/
483 // ---------------------------------------------------------------------
485 bool ServerState::RunData()
489 // Chunked transfer encoding is fun..
490 if (Encoding
== Chunked
)
494 // Grab the block size
500 if (In
.WriteTillEl(Data
,true) == true)
503 while ((Last
= Owner
->Go(false,this)) == true);
508 // See if we are done
509 unsigned long Len
= strtol(Data
.c_str(),0,16);
514 // We have to remove the entity trailer
518 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
521 while ((Last
= Owner
->Go(false,this)) == true);
524 return !_error
->PendingError();
527 // Transfer the block
529 while (Owner
->Go(true,this) == true)
530 if (In
.IsLimit() == true)
534 if (In
.IsLimit() == false)
537 // The server sends an extra new line before the next block specifier..
542 if (In
.WriteTillEl(Data
,true) == true)
545 while ((Last
= Owner
->Go(false,this)) == true);
552 /* Closes encoding is used when the server did not specify a size, the
553 loss of the connection means we are done */
554 if (Encoding
== Closes
)
557 In
.Limit(Size
- StartPos
);
559 // Just transfer the whole block.
562 if (In
.IsLimit() == false)
566 return !_error
->PendingError();
568 while (Owner
->Go(true,this) == true);
571 return Owner
->Flush(this) && !_error
->PendingError();
574 // ServerState::HeaderLine - Process a header line /*{{{*/
575 // ---------------------------------------------------------------------
577 bool ServerState::HeaderLine(string Line
)
579 if (Line
.empty() == true)
582 // The http server might be trying to do something evil.
583 if (Line
.length() >= MAXLEN
)
584 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
586 string::size_type Pos
= Line
.find(' ');
587 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
589 // Blah, some servers use "connection:closes", evil.
590 Pos
= Line
.find(':');
591 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
592 return _error
->Error(_("Bad header line"));
596 // Parse off any trailing spaces between the : and the next word.
597 string::size_type Pos2
= Pos
;
598 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
601 string Tag
= string(Line
,0,Pos
);
602 string Val
= string(Line
,Pos2
);
604 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
606 // Evil servers return no version
609 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u%[^\n]",&Major
,&Minor
,
611 return _error
->Error(_("The HTTP server sent an invalid reply header"));
617 if (sscanf(Line
.c_str(),"HTTP %u%[^\n]",&Result
,Code
) != 2)
618 return _error
->Error(_("The HTTP server sent an invalid reply header"));
621 /* Check the HTTP response header to get the default persistance
627 if (Major
== 1 && Minor
<= 0)
636 if (stringcasecmp(Tag
,"Content-Length:") == 0)
638 if (Encoding
== Closes
)
642 // The length is already set from the Content-Range header
646 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
647 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
651 if (stringcasecmp(Tag
,"Content-Type:") == 0)
657 if (stringcasecmp(Tag
,"Content-Range:") == 0)
661 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
662 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
663 if ((unsigned)StartPos
> Size
)
664 return _error
->Error(_("This HTTP server has broken range support"));
668 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
671 if (stringcasecmp(Val
,"chunked") == 0)
676 if (stringcasecmp(Tag
,"Connection:") == 0)
678 if (stringcasecmp(Val
,"close") == 0)
680 if (stringcasecmp(Val
,"keep-alive") == 0)
685 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
687 if (StrToTime(Val
,Date
) == false)
688 return _error
->Error(_("Unknown date format"));
692 if (stringcasecmp(Tag
,"Location:") == 0)
702 static const CFOptionFlags kNetworkEvents
=
703 kCFStreamEventOpenCompleted
|
704 kCFStreamEventHasBytesAvailable
|
705 kCFStreamEventEndEncountered
|
706 kCFStreamEventErrorOccurred
|
709 static void CFReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType event
, void *arg
) {
711 case kCFStreamEventOpenCompleted
:
714 case kCFStreamEventHasBytesAvailable
:
715 case kCFStreamEventEndEncountered
:
716 *reinterpret_cast<int *>(arg
) = 1;
717 CFRunLoopStop(CFRunLoopGetCurrent());
720 case kCFStreamEventErrorOccurred
:
721 *reinterpret_cast<int *>(arg
) = -1;
722 CFRunLoopStop(CFRunLoopGetCurrent());
727 /* http://lists.apple.com/archives/Macnetworkprog/2006/Apr/msg00014.html */
728 int CFReadStreamOpen(CFReadStreamRef stream
, double timeout
) {
729 CFStreamClientContext context
;
732 memset(&context
, 0, sizeof(context
));
733 context
.info
= &value
;
735 if (CFReadStreamSetClient(stream
, kNetworkEvents
, CFReadStreamCallback
, &context
)) {
736 CFReadStreamScheduleWithRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
737 if (CFReadStreamOpen(stream
))
738 CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
, false);
741 CFReadStreamSetClient(stream
, kCFStreamEventNone
, NULL
, NULL
);
747 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
748 // ---------------------------------------------------------------------
749 /* This places the http request in the outbound buffer */
750 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
754 // The HTTP server expects a hostname with a trailing :port
756 string ProperHost
= Uri
.Host
;
759 sprintf(Buf
,":%u",Uri
.Port
);
764 if (Itm
->Uri
.length() >= sizeof(Buf
))
767 /* Build the request. We include a keep-alive header only for non-proxy
768 requests. This is to tweak old http/1.0 servers that do support keep-alive
769 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
770 will glitch HTTP/1.0 proxies because they do not filter it out and
771 pass it on, HTTP/1.1 says the connection should default to keep alive
772 and we expect the proxy to do this */
773 if (Proxy
.empty() == true || Proxy
.Host
.empty())
774 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
775 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
778 /* Generate a cache control header if necessary. We place a max
779 cache age on index files, optionally set a no-cache directive
780 and a no-store directive for archives. */
781 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
782 Itm
->Uri
.c_str(),ProperHost
.c_str());
783 // only generate a cache control header if we actually want to
785 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
787 if (Itm
->IndexFile
== true)
788 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
789 _config
->FindI("Acquire::http::Max-Age",0));
792 if (_config
->FindB("Acquire::http::No-Store",false) == true)
793 strcat(Buf
,"Cache-Control: no-store\r\n");
797 // generate a no-cache header if needed
798 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
799 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
804 // Check for a partial file
806 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
808 // In this case we send an if-range query with a range header
809 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
810 TimeRFC1123(SBuf
.st_mtime
).c_str());
815 if (Itm
->LastModified
!= 0)
817 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
822 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
823 Req
+= string("Proxy-Authorization: Basic ") +
824 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
826 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
827 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
829 Req
+= string("Authorization: Basic ") +
830 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
832 Req
+= "User-Agent: " + _config
->Find("Acquire::http::User-Agent",
833 "Debian APT-HTTP/1.3 ("VERSION
")") + "\r\n\r\n";
841 // HttpMethod::Go - Run a single loop /*{{{*/
842 // ---------------------------------------------------------------------
843 /* This runs the select loop over the server FDs, Output file FDs and
845 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
847 // Server has closed the connection
848 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
856 /* Add the server. We only send more requests if the connection will
858 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
859 && Srv
->Persistent
== true)
860 FD_SET(Srv
->ServerFd
,&wfds
);
861 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
862 FD_SET(Srv
->ServerFd
,&rfds
);
869 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
870 FD_SET(FileFD
,&wfds
);
873 FD_SET(STDIN_FILENO
,&rfds
);
875 // Figure out the max fd
877 if (MaxFd
< Srv
->ServerFd
)
878 MaxFd
= Srv
->ServerFd
;
885 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
889 return _error
->Errno("select",_("Select failed"));
894 _error
->Error(_("Connection timed out"));
895 return ServerDie(Srv
);
899 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
902 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
903 return ServerDie(Srv
);
906 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
909 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
910 return ServerDie(Srv
);
913 // Send data to the file
914 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
916 if (Srv
->In
.Write(FileFD
) == false)
917 return _error
->Errno("write",_("Error writing to output file"));
920 // Handle commands from APT
921 if (FD_ISSET(STDIN_FILENO
,&rfds
))
930 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
931 // ---------------------------------------------------------------------
932 /* This takes the current input buffer from the Server FD and writes it
934 bool HttpMethod::Flush(ServerState
*Srv
)
938 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
940 if (File
->Name() != "/dev/null")
941 SetNonBlock(File
->Fd(),false);
942 if (Srv
->In
.WriteSpace() == false)
945 while (Srv
->In
.WriteSpace() == true)
947 if (Srv
->In
.Write(File
->Fd()) == false)
948 return _error
->Errno("write",_("Error writing to file"));
949 if (Srv
->In
.IsLimit() == true)
953 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
959 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
960 // ---------------------------------------------------------------------
962 bool HttpMethod::ServerDie(ServerState
*Srv
)
964 unsigned int LErrno
= errno
;
966 // Dump the buffer to the file
967 if (Srv
->State
== ServerState::Data
)
969 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
971 if (File
->Name() != "/dev/null")
972 SetNonBlock(File
->Fd(),false);
973 while (Srv
->In
.WriteSpace() == true)
975 if (Srv
->In
.Write(File
->Fd()) == false)
976 return _error
->Errno("write",_("Error writing to the file"));
979 if (Srv
->In
.IsLimit() == true)
984 // See if this is because the server finished the data stream
985 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
986 Srv
->Encoding
!= ServerState::Closes
)
990 return _error
->Error(_("Error reading from server. Remote end closed connection"));
992 return _error
->Errno("read",_("Error reading from server"));
998 // Nothing left in the buffer
999 if (Srv
->In
.WriteSpace() == false)
1002 // We may have got multiple responses back in one packet..
1010 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
1011 // ---------------------------------------------------------------------
1012 /* We look at the header data we got back from the server and decide what
1016 3 - Unrecoverable error
1017 4 - Error with error content page
1018 5 - Unrecoverable non-server error (close the connection)
1019 6 - Try again with a new or changed URI
1021 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
1024 if (Srv
->Result
== 304)
1026 unlink(Queue
->DestFile
.c_str());
1028 Res
.LastModified
= Queue
->LastModified
;
1034 * Note that it is only OK for us to treat all redirection the same
1035 * because we *always* use GET, not other HTTP methods. There are
1036 * three redirection codes for which it is not appropriate that we
1037 * redirect. Pass on those codes so the error handling kicks in.
1040 && (Srv
->Result
> 300 && Srv
->Result
< 400)
1041 && (Srv
->Result
!= 300 // Multiple Choices
1042 && Srv
->Result
!= 304 // Not Modified
1043 && Srv
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
1045 if (!Srv
->Location
.empty())
1047 NextURI
= Srv
->Location
;
1050 /* else pass through for error message */
1053 /* We have a reply we dont handle. This should indicate a perm server
1055 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
1057 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
1058 if (Srv
->HaveContent
== true)
1063 // This is some sort of 2xx 'data follows' reply
1064 Res
.LastModified
= Srv
->Date
;
1065 Res
.Size
= Srv
->Size
;
1069 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
1070 if (_error
->PendingError() == true)
1073 FailFile
= Queue
->DestFile
;
1074 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1075 FailFd
= File
->Fd();
1076 FailTime
= Srv
->Date
;
1078 // Set the expected size
1079 if (Srv
->StartPos
>= 0)
1081 Res
.ResumePoint
= Srv
->StartPos
;
1082 if (ftruncate(File
->Fd(),Srv
->StartPos
) < 0)
1083 _error
->Errno("ftruncate", _("Failed to truncate file"));
1086 // Set the start point
1087 lseek(File
->Fd(),0,SEEK_END
);
1089 delete Srv
->In
.Hash
;
1090 Srv
->In
.Hash
= new Hashes
;
1092 // Fill the Hash if the file is non-empty (resume)
1093 if (Srv
->StartPos
> 0)
1095 lseek(File
->Fd(),0,SEEK_SET
);
1096 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1098 _error
->Errno("read",_("Problem hashing file"));
1101 lseek(File
->Fd(),0,SEEK_END
);
1104 SetNonBlock(File
->Fd(),true);
1108 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1109 // ---------------------------------------------------------------------
1110 /* This closes and timestamps the open file. This is neccessary to get
1111 resume behavoir on user abort */
1112 void HttpMethod::SigTerm(int)
1119 struct utimbuf UBuf
;
1120 UBuf
.actime
= FailTime
;
1121 UBuf
.modtime
= FailTime
;
1122 utime(FailFile
.c_str(),&UBuf
);
1127 // HttpMethod::Fetch - Fetch an item /*{{{*/
1128 // ---------------------------------------------------------------------
1129 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1131 bool HttpMethod::Fetch(FetchItem
*)
1136 // Queue the requests
1138 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1139 I
= I
->Next
, Depth
++)
1141 // If pipelining is disabled, we only queue 1 request
1142 if (Server
->Pipeline
== false && Depth
>= 0)
1145 // Make sure we stick with the same server
1146 if (Server
->Comp(I
->Uri
) == false)
1150 QueueBack
= I
->Next
;
1151 SendReq(I
,Server
->Out
);
1159 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1160 // ---------------------------------------------------------------------
1161 /* We stash the desired pipeline depth */
1162 bool HttpMethod::Configuration(string Message
)
1164 if (pkgAcqMethod::Configuration(Message
) == false)
1167 AllowRedirect
= _config
->FindB("Acquire::http::AllowRedirect",true);
1168 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1169 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1171 Debug
= _config
->FindB("Debug::Acquire::http",false);
1176 // HttpMethod::Loop - Main loop /*{{{*/
1177 // ---------------------------------------------------------------------
1179 int HttpMethod::Loop()
1181 typedef vector
<string
> StringVector
;
1182 typedef vector
<string
>::iterator StringVectorIterator
;
1183 map
<string
, StringVector
> Redirected
;
1185 signal(SIGTERM
,SigTerm
);
1186 signal(SIGINT
,SigTerm
);
1190 std::set
<std::string
> cached
;
1192 int FailCounter
= 0;
1195 // We have no commands, wait for some to arrive
1198 if (WaitFd(STDIN_FILENO
) == false)
1202 /* Run messages, we can accept 0 (no message) if we didn't
1203 do a WaitFd above.. Otherwise the FD is closed. */
1204 int Result
= Run(true);
1205 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1211 CFStringEncoding se
= kCFStringEncodingUTF8
;
1213 char *url
= strdup(Queue
->Uri
.c_str());
1215 URI uri
= std::string(url
);
1216 std::string hs
= uri
.Host
;
1218 if (cached
.find(hs
) != cached
.end()) {
1219 _error
->Error("Cached Failure");
1226 std::string urs
= uri
;
1229 size_t bad
= urs
.find_first_of("+");
1230 if (bad
== std::string::npos
)
1233 urs
= urs
.substr(0, bad
) + "%2b" + urs
.substr(bad
+ 1);
1236 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, urs
.c_str(), se
);
1237 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1239 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1243 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1244 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1245 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1248 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1249 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1252 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1253 } else if (Queue
->LastModified
!= 0) {
1254 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(Queue
->LastModified
).c_str(), se
);
1255 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1258 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1260 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("max-age=0"));
1262 if (Firmware_
!= NULL
)
1263 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Firmware"), Firmware_
);
1265 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Machine_
, se
);
1266 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Machine"), sr
);
1269 if (UniqueID_
!= NULL
)
1270 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Unique-ID"), UniqueID_
);
1272 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.592"));
1274 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1277 #define _kCFStreamPropertyReadTimeout CFSTR("_kCFStreamPropertyReadTimeout")
1278 #define _kCFStreamPropertyWriteTimeout CFSTR("_kCFStreamPropertyWriteTimeout")
1279 #define _kCFStreamPropertySocketImmediateBufferTimeOut CFSTR("_kCFStreamPropertySocketImmediateBufferTimeOut")
1281 /*SInt32 to(TimeOut);
1282 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &to));*/
1284 CFNumberRef
nm(CFNumberCreate(kCFAllocatorDefault
, kCFNumberDoubleType
, &to
));
1286 CFReadStreamSetProperty(rs
, _kCFStreamPropertyReadTimeout
, nm
);
1287 CFReadStreamSetProperty(rs
, _kCFStreamPropertyWriteTimeout
, nm
);
1288 CFReadStreamSetProperty(rs
, _kCFStreamPropertySocketImmediateBufferTimeOut
, nm
);
1291 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1292 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1295 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1296 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1302 uint8_t data
[10240];
1305 Status("Connecting to %s", hs
.c_str());
1307 switch (CFReadStreamOpen(rs
, to
)) {
1309 CfrsError("Open", rs
);
1313 _error
->Error("Host Unreachable");
1326 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1329 CfrsError(uri
.Host
.c_str(), rs
);
1335 Res
.Filename
= Queue
->DestFile
;
1337 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1338 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1340 if (sc
== 301 || sc
== 302) {
1341 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Location"));
1346 size_t ln
= CFStringGetLength(sr
) + 1;
1348 url
= static_cast<char *>(malloc(ln
));
1350 if (!CFStringGetCString(sr
, url
, ln
, se
)) {
1360 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1362 size_t ln
= CFStringGetLength(sr
) + 1;
1365 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1372 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1373 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1378 if (offset
> Res
.Size
) {
1379 _error
->Error(_("This HTTP server has broken range support"));
1384 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1386 Res
.Size
= CFStringGetIntValue(sr
);
1391 time(&Res
.LastModified
);
1393 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1395 size_t ln
= CFStringGetLength(sr
) + 1;
1398 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1405 if (!StrToTime(cr
, Res
.LastModified
)) {
1406 _error
->Error(_("Unknown date format"));
1412 if (sc
< 200 || sc
>= 300 && sc
!= 304) {
1413 sr
= CFHTTPMessageCopyResponseStatusLine(hm
);
1415 size_t ln
= CFStringGetLength(sr
) + 1;
1418 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1425 _error
->Error("%s", cr
);
1434 unlink(Queue
->DestFile
.c_str());
1436 Res
.LastModified
= Queue
->LastModified
;
1441 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1442 if (_error
->PendingError() == true) {
1449 FailFile
= Queue
->DestFile
;
1450 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1451 FailFd
= File
->Fd();
1452 FailTime
= Res
.LastModified
;
1454 Res
.ResumePoint
= offset
;
1455 ftruncate(File
->Fd(), offset
);
1458 lseek(File
->Fd(), 0, SEEK_SET
);
1459 if (!hash
.AddFD(File
->Fd(), offset
)) {
1460 _error
->Errno("read", _("Problem hashing file"));
1468 lseek(File
->Fd(), 0, SEEK_END
);
1472 read
: if (rd
== -1) {
1473 CfrsError("rd", rs
);
1475 } else if (rd
== 0) {
1477 Res
.Size
= File
->Size();
1479 struct utimbuf UBuf
;
1481 UBuf
.actime
= Res
.LastModified
;
1482 UBuf
.modtime
= Res
.LastModified
;
1483 utime(Queue
->DestFile
.c_str(), &UBuf
);
1485 Res
.TakeHashes(hash
);
1492 int sz
= write(File
->Fd(), dt
, rd
);
1505 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1514 CFReadStreamClose(rs
);
1527 setlocale(LC_ALL
, "");
1528 // ignore SIGPIPE, this can happen on write() if the socket
1529 // closes the connection (this is dealt with via ServerDie())
1530 signal(SIGPIPE
, SIG_IGN
);
1535 sysctlbyname("hw.machine", NULL
, &size
, NULL
, 0);
1536 char *machine
= new char[size
];
1537 sysctlbyname("hw.machine", machine
, &size
, NULL
, 0);
1540 const char *path
= "/System/Library/CoreServices/SystemVersion.plist";
1541 CFURLRef url
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (uint8_t *) path
, strlen(path
), false);
1543 CFPropertyListRef plist
; {
1544 CFReadStreamRef stream
= CFReadStreamCreateWithFile(kCFAllocatorDefault
, url
);
1545 CFReadStreamOpen(stream
);
1546 plist
= CFPropertyListCreateFromStream(kCFAllocatorDefault
, stream
, 0, kCFPropertyListImmutable
, NULL
, NULL
);
1547 CFReadStreamClose(stream
);
1552 if (plist
!= NULL
) {
1553 Firmware_
= (CFStringRef
) CFRetain(CFDictionaryGetValue((CFDictionaryRef
) plist
, CFSTR("ProductVersion")));
1557 if (void *lockdown
= lockdown_connect()) {
1558 UniqueID_
= lockdown_copy_value(lockdown
, NULL
, kLockdownUniqueDeviceIDKey
);
1559 lockdown_disconnect(lockdown
);