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>
55 #include <CoreFoundation/CoreFoundation.h>
56 #include <CFNetwork/CFNetwork.h>
57 #include <SystemConfiguration/SystemConfiguration.h>
61 #include "rfc2553emu.h"
66 CFStringRef Firmware_
;
68 CFStringRef UniqueID_
;
70 void CfrsError(const char *name
, CFReadStreamRef rs
) {
71 CFStreamError se
= CFReadStreamGetError(rs
);
73 if (se
.domain
== kCFStreamErrorDomainCustom
) {
74 } else if (se
.domain
== kCFStreamErrorDomainPOSIX
) {
75 _error
->Error("POSIX: %s", strerror(se
.error
));
76 } else if (se
.domain
== kCFStreamErrorDomainMacOSStatus
) {
77 _error
->Error("MacOSStatus: %ld", se
.error
);
78 } else if (se
.domain
== kCFStreamErrorDomainNetDB
) {
79 _error
->Error("NetDB: %s %s", name
, gai_strerror(se
.error
));
80 } else if (se
.domain
== kCFStreamErrorDomainMach
) {
81 _error
->Error("Mach: %ld", se
.error
);
82 } else if (se
.domain
== kCFStreamErrorDomainHTTP
) {
84 case kCFStreamErrorHTTPParseFailure
:
85 _error
->Error("Parse failure");
88 case kCFStreamErrorHTTPRedirectionLoop
:
89 _error
->Error("Redirection loop");
92 case kCFStreamErrorHTTPBadURL
:
93 _error
->Error("Bad URL");
97 _error
->Error("Unknown HTTP error: %ld", se
.error
);
100 } else if (se
.domain
== kCFStreamErrorDomainSOCKS
) {
101 _error
->Error("SOCKS: %ld", se
.error
);
102 } else if (se
.domain
== kCFStreamErrorDomainSystemConfiguration
) {
103 _error
->Error("SystemConfiguration: %ld", se
.error
);
104 } else if (se
.domain
== kCFStreamErrorDomainSSL
) {
105 _error
->Error("SSL: %ld", se
.error
);
107 _error
->Error("Domain #%ld: %ld", se
.domain
, se
.error
);
111 string
HttpMethod::FailFile
;
112 int HttpMethod::FailFd
= -1;
113 time_t HttpMethod::FailTime
= 0;
114 unsigned long PipelineDepth
= 10;
115 unsigned long TimeOut
= 120;
116 bool AllowRedirect
= false;
120 unsigned long CircleBuf::BwReadLimit
=0;
121 unsigned long CircleBuf::BwTickReadData
=0;
122 struct timeval
CircleBuf::BwReadTick
={0,0};
123 const unsigned int CircleBuf::BW_HZ
=10;
125 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
126 // ---------------------------------------------------------------------
128 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
130 Buf
= new unsigned char[Size
];
133 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
136 // CircleBuf::Reset - Reset to the default state /*{{{*/
137 // ---------------------------------------------------------------------
139 void CircleBuf::Reset()
144 MaxGet
= (unsigned int)-1;
153 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
154 // ---------------------------------------------------------------------
155 /* This fills up the buffer with as much data as is in the FD, assuming it
157 bool CircleBuf::Read(int Fd
)
159 unsigned long BwReadMax
;
163 // Woops, buffer is full
164 if (InP
- OutP
== Size
)
167 // what's left to read in this tick
168 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
170 if(CircleBuf::BwReadLimit
) {
172 gettimeofday(&now
,0);
174 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
175 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
176 if(d
> 1000000/BW_HZ
) {
177 CircleBuf::BwReadTick
= now
;
178 CircleBuf::BwTickReadData
= 0;
181 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
182 usleep(1000000/BW_HZ
);
187 // Write the buffer segment
189 if(CircleBuf::BwReadLimit
) {
190 Res
= read(Fd
,Buf
+ (InP%Size
),
191 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
193 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
195 if(Res
> 0 && BwReadLimit
> 0)
196 CircleBuf::BwTickReadData
+= Res
;
208 gettimeofday(&Start
,0);
213 // CircleBuf::Read - Put the string into the buffer /*{{{*/
214 // ---------------------------------------------------------------------
215 /* This will hold the string in and fill the buffer with it as it empties */
216 bool CircleBuf::Read(string Data
)
223 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
224 // ---------------------------------------------------------------------
226 void CircleBuf::FillOut()
228 if (OutQueue
.empty() == true)
232 // Woops, buffer is full
233 if (InP
- OutP
== Size
)
236 // Write the buffer segment
237 unsigned long Sz
= LeftRead();
238 if (OutQueue
.length() - StrPos
< Sz
)
239 Sz
= OutQueue
.length() - StrPos
;
240 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
245 if (OutQueue
.length() == StrPos
)
254 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
255 // ---------------------------------------------------------------------
256 /* This empties the buffer into the FD. */
257 bool CircleBuf::Write(int Fd
)
263 // Woops, buffer is empty
270 // Write the buffer segment
272 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
285 Hash
->Add(Buf
+ (OutP%Size
),Res
);
291 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
292 // ---------------------------------------------------------------------
293 /* This copies till the first empty line */
294 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
296 // We cheat and assume it is unneeded to have more than one buffer load
297 for (unsigned long I
= OutP
; I
< InP
; I
++)
299 if (Buf
[I%Size
] != '\n')
305 if (I
< InP
&& Buf
[I%Size
] == '\r')
307 if (I
>= InP
|| Buf
[I%Size
] != '\n')
315 unsigned long Sz
= LeftWrite();
320 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
328 // CircleBuf::Stats - Print out stats information /*{{{*/
329 // ---------------------------------------------------------------------
331 void CircleBuf::Stats()
337 gettimeofday(&Stop
,0);
338 /* float Diff = Stop.tv_sec - Start.tv_sec +
339 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
340 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
344 // ServerState::ServerState - Constructor /*{{{*/
345 // ---------------------------------------------------------------------
347 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
348 In(64*1024), Out(4*1024),
354 // ServerState::Open - Open a connection to the server /*{{{*/
355 // ---------------------------------------------------------------------
356 /* This opens a connection to the server. */
357 bool ServerState::Open()
359 // Use the already open connection if possible.
368 // Determine the proxy setting
369 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
370 if (!SpecificProxy
.empty())
372 if (SpecificProxy
== "DIRECT")
375 Proxy
= SpecificProxy
;
379 string DefProxy
= _config
->Find("Acquire::http::Proxy");
380 if (!DefProxy
.empty())
386 char* result
= getenv("http_proxy");
387 Proxy
= result
? result
: "";
391 // Parse no_proxy, a , separated list of domains
392 if (getenv("no_proxy") != 0)
394 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
398 // Determine what host and port to use based on the proxy settings
401 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
403 if (ServerName
.Port
!= 0)
404 Port
= ServerName
.Port
;
405 Host
= ServerName
.Host
;
414 // Connect to the remote server
415 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
421 // ServerState::Close - Close a connection to the server /*{{{*/
422 // ---------------------------------------------------------------------
424 bool ServerState::Close()
431 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
432 // ---------------------------------------------------------------------
433 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
434 parse error occurred */
435 int ServerState::RunHeaders()
439 Owner
->Status(_("Waiting for headers"));
453 if (In
.WriteTillEl(Data
) == false)
459 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
461 string::const_iterator J
= I
;
462 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
463 if (HeaderLine(string(I
,J
)) == false)
468 // 100 Continue is a Nop...
472 // Tidy up the connection persistance state.
473 if (Encoding
== Closes
&& HaveContent
== true)
478 while (Owner
->Go(false,this) == true);
483 // ServerState::RunData - Transfer the data from the socket /*{{{*/
484 // ---------------------------------------------------------------------
486 bool ServerState::RunData()
490 // Chunked transfer encoding is fun..
491 if (Encoding
== Chunked
)
495 // Grab the block size
501 if (In
.WriteTillEl(Data
,true) == true)
504 while ((Last
= Owner
->Go(false,this)) == true);
509 // See if we are done
510 unsigned long Len
= strtol(Data
.c_str(),0,16);
515 // We have to remove the entity trailer
519 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
522 while ((Last
= Owner
->Go(false,this)) == true);
525 return !_error
->PendingError();
528 // Transfer the block
530 while (Owner
->Go(true,this) == true)
531 if (In
.IsLimit() == true)
535 if (In
.IsLimit() == false)
538 // The server sends an extra new line before the next block specifier..
543 if (In
.WriteTillEl(Data
,true) == true)
546 while ((Last
= Owner
->Go(false,this)) == true);
553 /* Closes encoding is used when the server did not specify a size, the
554 loss of the connection means we are done */
555 if (Encoding
== Closes
)
558 In
.Limit(Size
- StartPos
);
560 // Just transfer the whole block.
563 if (In
.IsLimit() == false)
567 return !_error
->PendingError();
569 while (Owner
->Go(true,this) == true);
572 return Owner
->Flush(this) && !_error
->PendingError();
575 // ServerState::HeaderLine - Process a header line /*{{{*/
576 // ---------------------------------------------------------------------
578 bool ServerState::HeaderLine(string Line
)
580 if (Line
.empty() == true)
583 // The http server might be trying to do something evil.
584 if (Line
.length() >= MAXLEN
)
585 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
587 string::size_type Pos
= Line
.find(' ');
588 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
590 // Blah, some servers use "connection:closes", evil.
591 Pos
= Line
.find(':');
592 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
593 return _error
->Error(_("Bad header line"));
597 // Parse off any trailing spaces between the : and the next word.
598 string::size_type Pos2
= Pos
;
599 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
602 string Tag
= string(Line
,0,Pos
);
603 string Val
= string(Line
,Pos2
);
605 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
607 // Evil servers return no version
610 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u%[^\n]",&Major
,&Minor
,
612 return _error
->Error(_("The HTTP server sent an invalid reply header"));
618 if (sscanf(Line
.c_str(),"HTTP %u%[^\n]",&Result
,Code
) != 2)
619 return _error
->Error(_("The HTTP server sent an invalid reply header"));
622 /* Check the HTTP response header to get the default persistance
628 if (Major
== 1 && Minor
<= 0)
637 if (stringcasecmp(Tag
,"Content-Length:") == 0)
639 if (Encoding
== Closes
)
643 // The length is already set from the Content-Range header
647 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
648 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
652 if (stringcasecmp(Tag
,"Content-Type:") == 0)
658 if (stringcasecmp(Tag
,"Content-Range:") == 0)
662 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
663 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
664 if ((unsigned)StartPos
> Size
)
665 return _error
->Error(_("This HTTP server has broken range support"));
669 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
672 if (stringcasecmp(Val
,"chunked") == 0)
677 if (stringcasecmp(Tag
,"Connection:") == 0)
679 if (stringcasecmp(Val
,"close") == 0)
681 if (stringcasecmp(Val
,"keep-alive") == 0)
686 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
688 if (StrToTime(Val
,Date
) == false)
689 return _error
->Error(_("Unknown date format"));
693 if (stringcasecmp(Tag
,"Location:") == 0)
703 static const CFOptionFlags kNetworkEvents
=
704 kCFStreamEventOpenCompleted
|
705 kCFStreamEventHasBytesAvailable
|
706 kCFStreamEventEndEncountered
|
707 kCFStreamEventErrorOccurred
|
710 static void CFReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType event
, void *arg
) {
712 case kCFStreamEventOpenCompleted
:
715 case kCFStreamEventHasBytesAvailable
:
716 case kCFStreamEventEndEncountered
:
717 *reinterpret_cast<int *>(arg
) = 1;
718 CFRunLoopStop(CFRunLoopGetCurrent());
721 case kCFStreamEventErrorOccurred
:
722 *reinterpret_cast<int *>(arg
) = -1;
723 CFRunLoopStop(CFRunLoopGetCurrent());
728 /* http://lists.apple.com/archives/Macnetworkprog/2006/Apr/msg00014.html */
729 int CFReadStreamOpen(CFReadStreamRef stream
, double timeout
) {
730 CFStreamClientContext context
;
733 memset(&context
, 0, sizeof(context
));
734 context
.info
= &value
;
736 if (CFReadStreamSetClient(stream
, kNetworkEvents
, CFReadStreamCallback
, &context
)) {
737 CFReadStreamScheduleWithRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
738 if (CFReadStreamOpen(stream
))
739 CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
, false);
742 CFReadStreamSetClient(stream
, kCFStreamEventNone
, NULL
, NULL
);
748 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
749 // ---------------------------------------------------------------------
750 /* This places the http request in the outbound buffer */
751 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
755 // The HTTP server expects a hostname with a trailing :port
757 string ProperHost
= Uri
.Host
;
760 sprintf(Buf
,":%u",Uri
.Port
);
765 if (Itm
->Uri
.length() >= sizeof(Buf
))
768 /* Build the request. We include a keep-alive header only for non-proxy
769 requests. This is to tweak old http/1.0 servers that do support keep-alive
770 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
771 will glitch HTTP/1.0 proxies because they do not filter it out and
772 pass it on, HTTP/1.1 says the connection should default to keep alive
773 and we expect the proxy to do this */
774 if (Proxy
.empty() == true || Proxy
.Host
.empty())
775 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
776 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
779 /* Generate a cache control header if necessary. We place a max
780 cache age on index files, optionally set a no-cache directive
781 and a no-store directive for archives. */
782 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
783 Itm
->Uri
.c_str(),ProperHost
.c_str());
784 // only generate a cache control header if we actually want to
786 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
788 if (Itm
->IndexFile
== true)
789 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
790 _config
->FindI("Acquire::http::Max-Age",0));
793 if (_config
->FindB("Acquire::http::No-Store",false) == true)
794 strcat(Buf
,"Cache-Control: no-store\r\n");
798 // generate a no-cache header if needed
799 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
800 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
805 // Check for a partial file
807 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
809 // In this case we send an if-range query with a range header
810 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
811 TimeRFC1123(SBuf
.st_mtime
).c_str());
816 if (Itm
->LastModified
!= 0)
818 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
823 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
824 Req
+= string("Proxy-Authorization: Basic ") +
825 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
827 maybe_add_auth (Uri
, _config
->FindFile("Dir::Etc::netrc"));
828 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
830 Req
+= string("Authorization: Basic ") +
831 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
833 Req
+= "User-Agent: " + _config
->Find("Acquire::http::User-Agent",
834 "Debian APT-HTTP/1.3 ("VERSION
")") + "\r\n\r\n";
842 // HttpMethod::Go - Run a single loop /*{{{*/
843 // ---------------------------------------------------------------------
844 /* This runs the select loop over the server FDs, Output file FDs and
846 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
848 // Server has closed the connection
849 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
857 /* Add the server. We only send more requests if the connection will
859 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
860 && Srv
->Persistent
== true)
861 FD_SET(Srv
->ServerFd
,&wfds
);
862 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
863 FD_SET(Srv
->ServerFd
,&rfds
);
870 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
871 FD_SET(FileFD
,&wfds
);
874 FD_SET(STDIN_FILENO
,&rfds
);
876 // Figure out the max fd
878 if (MaxFd
< Srv
->ServerFd
)
879 MaxFd
= Srv
->ServerFd
;
886 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
890 return _error
->Errno("select",_("Select failed"));
895 _error
->Error(_("Connection timed out"));
896 return ServerDie(Srv
);
900 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
903 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
904 return ServerDie(Srv
);
907 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
910 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
911 return ServerDie(Srv
);
914 // Send data to the file
915 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
917 if (Srv
->In
.Write(FileFD
) == false)
918 return _error
->Errno("write",_("Error writing to output file"));
921 // Handle commands from APT
922 if (FD_ISSET(STDIN_FILENO
,&rfds
))
931 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
932 // ---------------------------------------------------------------------
933 /* This takes the current input buffer from the Server FD and writes it
935 bool HttpMethod::Flush(ServerState
*Srv
)
939 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
941 if (File
->Name() != "/dev/null")
942 SetNonBlock(File
->Fd(),false);
943 if (Srv
->In
.WriteSpace() == false)
946 while (Srv
->In
.WriteSpace() == true)
948 if (Srv
->In
.Write(File
->Fd()) == false)
949 return _error
->Errno("write",_("Error writing to file"));
950 if (Srv
->In
.IsLimit() == true)
954 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
960 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
961 // ---------------------------------------------------------------------
963 bool HttpMethod::ServerDie(ServerState
*Srv
)
965 unsigned int LErrno
= errno
;
967 // Dump the buffer to the file
968 if (Srv
->State
== ServerState::Data
)
970 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
972 if (File
->Name() != "/dev/null")
973 SetNonBlock(File
->Fd(),false);
974 while (Srv
->In
.WriteSpace() == true)
976 if (Srv
->In
.Write(File
->Fd()) == false)
977 return _error
->Errno("write",_("Error writing to the file"));
980 if (Srv
->In
.IsLimit() == true)
985 // See if this is because the server finished the data stream
986 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
987 Srv
->Encoding
!= ServerState::Closes
)
991 return _error
->Error(_("Error reading from server. Remote end closed connection"));
993 return _error
->Errno("read",_("Error reading from server"));
999 // Nothing left in the buffer
1000 if (Srv
->In
.WriteSpace() == false)
1003 // We may have got multiple responses back in one packet..
1011 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
1012 // ---------------------------------------------------------------------
1013 /* We look at the header data we got back from the server and decide what
1017 3 - Unrecoverable error
1018 4 - Error with error content page
1019 5 - Unrecoverable non-server error (close the connection)
1020 6 - Try again with a new or changed URI
1022 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
1025 if (Srv
->Result
== 304)
1027 unlink(Queue
->DestFile
.c_str());
1029 Res
.LastModified
= Queue
->LastModified
;
1035 * Note that it is only OK for us to treat all redirection the same
1036 * because we *always* use GET, not other HTTP methods. There are
1037 * three redirection codes for which it is not appropriate that we
1038 * redirect. Pass on those codes so the error handling kicks in.
1041 && (Srv
->Result
> 300 && Srv
->Result
< 400)
1042 && (Srv
->Result
!= 300 // Multiple Choices
1043 && Srv
->Result
!= 304 // Not Modified
1044 && Srv
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
1046 if (!Srv
->Location
.empty())
1048 NextURI
= Srv
->Location
;
1051 /* else pass through for error message */
1054 /* We have a reply we dont handle. This should indicate a perm server
1056 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
1058 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
1059 if (Srv
->HaveContent
== true)
1064 // This is some sort of 2xx 'data follows' reply
1065 Res
.LastModified
= Srv
->Date
;
1066 Res
.Size
= Srv
->Size
;
1070 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
1071 if (_error
->PendingError() == true)
1074 FailFile
= Queue
->DestFile
;
1075 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1076 FailFd
= File
->Fd();
1077 FailTime
= Srv
->Date
;
1079 // Set the expected size
1080 if (Srv
->StartPos
>= 0)
1082 Res
.ResumePoint
= Srv
->StartPos
;
1083 if (ftruncate(File
->Fd(),Srv
->StartPos
) < 0)
1084 _error
->Errno("ftruncate", _("Failed to truncate file"));
1087 // Set the start point
1088 lseek(File
->Fd(),0,SEEK_END
);
1090 delete Srv
->In
.Hash
;
1091 Srv
->In
.Hash
= new Hashes
;
1093 // Fill the Hash if the file is non-empty (resume)
1094 if (Srv
->StartPos
> 0)
1096 lseek(File
->Fd(),0,SEEK_SET
);
1097 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1099 _error
->Errno("read",_("Problem hashing file"));
1102 lseek(File
->Fd(),0,SEEK_END
);
1105 SetNonBlock(File
->Fd(),true);
1109 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1110 // ---------------------------------------------------------------------
1111 /* This closes and timestamps the open file. This is neccessary to get
1112 resume behavoir on user abort */
1113 void HttpMethod::SigTerm(int)
1120 struct utimbuf UBuf
;
1121 UBuf
.actime
= FailTime
;
1122 UBuf
.modtime
= FailTime
;
1123 utime(FailFile
.c_str(),&UBuf
);
1128 // HttpMethod::Fetch - Fetch an item /*{{{*/
1129 // ---------------------------------------------------------------------
1130 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1132 bool HttpMethod::Fetch(FetchItem
*)
1137 // Queue the requests
1139 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1140 I
= I
->Next
, Depth
++)
1142 // If pipelining is disabled, we only queue 1 request
1143 if (Server
->Pipeline
== false && Depth
>= 0)
1146 // Make sure we stick with the same server
1147 if (Server
->Comp(I
->Uri
) == false)
1151 QueueBack
= I
->Next
;
1152 SendReq(I
,Server
->Out
);
1160 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1161 // ---------------------------------------------------------------------
1162 /* We stash the desired pipeline depth */
1163 bool HttpMethod::Configuration(string Message
)
1165 if (pkgAcqMethod::Configuration(Message
) == false)
1168 AllowRedirect
= _config
->FindB("Acquire::http::AllowRedirect",true);
1169 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1170 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1172 Debug
= _config
->FindB("Debug::Acquire::http",false);
1177 // HttpMethod::Loop - Main loop /*{{{*/
1178 // ---------------------------------------------------------------------
1180 int HttpMethod::Loop()
1182 typedef vector
<string
> StringVector
;
1183 typedef vector
<string
>::iterator StringVectorIterator
;
1184 map
<string
, StringVector
> Redirected
;
1186 signal(SIGTERM
,SigTerm
);
1187 signal(SIGINT
,SigTerm
);
1191 std::set
<std::string
> cached
;
1193 int FailCounter
= 0;
1196 // We have no commands, wait for some to arrive
1199 if (WaitFd(STDIN_FILENO
) == false)
1203 /* Run messages, we can accept 0 (no message) if we didn't
1204 do a WaitFd above.. Otherwise the FD is closed. */
1205 int Result
= Run(true);
1206 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1212 CFStringEncoding se
= kCFStringEncodingUTF8
;
1214 char *url
= strdup(Queue
->Uri
.c_str());
1216 URI uri
= std::string(url
);
1217 std::string hs
= uri
.Host
;
1219 if (cached
.find(hs
) != cached
.end()) {
1220 _error
->Error("Cached Failure");
1227 std::string urs
= uri
;
1230 size_t bad
= urs
.find_first_of("+");
1231 if (bad
== std::string::npos
)
1234 urs
= urs
.substr(0, bad
) + "%2b" + urs
.substr(bad
+ 1);
1237 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, urs
.c_str(), se
);
1238 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1240 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1244 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1245 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1246 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1249 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1250 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1253 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1254 } else if (Queue
->LastModified
!= 0) {
1255 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(Queue
->LastModified
).c_str(), se
);
1256 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1259 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1261 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("max-age=0"));
1263 if (Firmware_
!= NULL
)
1264 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Firmware"), Firmware_
);
1266 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Machine_
, se
);
1267 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Machine"), sr
);
1270 if (UniqueID_
!= NULL
)
1271 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Unique-ID"), UniqueID_
);
1273 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.592"));
1275 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1278 #define _kCFStreamPropertyReadTimeout CFSTR("_kCFStreamPropertyReadTimeout")
1279 #define _kCFStreamPropertyWriteTimeout CFSTR("_kCFStreamPropertyWriteTimeout")
1280 #define _kCFStreamPropertySocketImmediateBufferTimeOut CFSTR("_kCFStreamPropertySocketImmediateBufferTimeOut")
1282 /*SInt32 to(TimeOut);
1283 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &to));*/
1285 CFNumberRef
nm(CFNumberCreate(kCFAllocatorDefault
, kCFNumberDoubleType
, &to
));
1287 CFReadStreamSetProperty(rs
, _kCFStreamPropertyReadTimeout
, nm
);
1288 CFReadStreamSetProperty(rs
, _kCFStreamPropertyWriteTimeout
, nm
);
1289 CFReadStreamSetProperty(rs
, _kCFStreamPropertySocketImmediateBufferTimeOut
, nm
);
1292 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1293 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1296 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1297 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1303 uint8_t data
[10240];
1306 Status("Connecting to %s", hs
.c_str());
1308 switch (CFReadStreamOpen(rs
, to
)) {
1310 CfrsError("Open", rs
);
1314 _error
->Error("Host Unreachable");
1327 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1330 CfrsError(uri
.Host
.c_str(), rs
);
1336 Res
.Filename
= Queue
->DestFile
;
1338 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1339 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1341 if (sc
== 301 || sc
== 302) {
1342 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Location"));
1347 size_t ln
= CFStringGetLength(sr
) + 1;
1349 url
= static_cast<char *>(malloc(ln
));
1351 if (!CFStringGetCString(sr
, url
, ln
, se
)) {
1361 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1363 size_t ln
= CFStringGetLength(sr
) + 1;
1366 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1373 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1374 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1379 if (offset
> Res
.Size
) {
1380 _error
->Error(_("This HTTP server has broken range support"));
1385 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1387 Res
.Size
= CFStringGetIntValue(sr
);
1392 time(&Res
.LastModified
);
1394 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1396 size_t ln
= CFStringGetLength(sr
) + 1;
1399 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1406 if (!StrToTime(cr
, Res
.LastModified
)) {
1407 _error
->Error(_("Unknown date format"));
1413 if (sc
< 200 || sc
>= 300 && sc
!= 304) {
1414 sr
= CFHTTPMessageCopyResponseStatusLine(hm
);
1416 size_t ln
= CFStringGetLength(sr
) + 1;
1419 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1426 _error
->Error("%s", cr
);
1435 unlink(Queue
->DestFile
.c_str());
1437 Res
.LastModified
= Queue
->LastModified
;
1442 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1443 if (_error
->PendingError() == true) {
1450 FailFile
= Queue
->DestFile
;
1451 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1452 FailFd
= File
->Fd();
1453 FailTime
= Res
.LastModified
;
1455 Res
.ResumePoint
= offset
;
1456 ftruncate(File
->Fd(), offset
);
1459 lseek(File
->Fd(), 0, SEEK_SET
);
1460 if (!hash
.AddFD(File
->Fd(), offset
)) {
1461 _error
->Errno("read", _("Problem hashing file"));
1469 lseek(File
->Fd(), 0, SEEK_END
);
1473 read
: if (rd
== -1) {
1474 CfrsError("rd", rs
);
1476 } else if (rd
== 0) {
1478 Res
.Size
= File
->Size();
1480 struct utimbuf UBuf
;
1482 UBuf
.actime
= Res
.LastModified
;
1483 UBuf
.modtime
= Res
.LastModified
;
1484 utime(Queue
->DestFile
.c_str(), &UBuf
);
1486 Res
.TakeHashes(hash
);
1493 int sz
= write(File
->Fd(), dt
, rd
);
1506 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1515 CFReadStreamClose(rs
);
1528 setlocale(LC_ALL
, "");
1529 // ignore SIGPIPE, this can happen on write() if the socket
1530 // closes the connection (this is dealt with via ServerDie())
1531 signal(SIGPIPE
, SIG_IGN
);
1536 sysctlbyname("hw.machine", NULL
, &size
, NULL
, 0);
1537 char *machine
= new char[size
];
1538 sysctlbyname("hw.machine", machine
, &size
, NULL
, 0);
1541 const char *path
= "/System/Library/CoreServices/SystemVersion.plist";
1542 CFURLRef url
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (uint8_t *) path
, strlen(path
), false);
1544 CFPropertyListRef plist
; {
1545 CFReadStreamRef stream
= CFReadStreamCreateWithFile(kCFAllocatorDefault
, url
);
1546 CFReadStreamOpen(stream
);
1547 plist
= CFPropertyListCreateFromStream(kCFAllocatorDefault
, stream
, 0, kCFPropertyListImmutable
, NULL
, NULL
);
1548 CFReadStreamClose(stream
);
1553 if (plist
!= NULL
) {
1554 Firmware_
= (CFStringRef
) CFRetain(CFDictionaryGetValue((CFDictionaryRef
) plist
, CFSTR("ProductVersion")));
1558 if (UniqueID_
== NULL
)
1559 if (void *libMobileGestalt
= dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL
| RTLD_LAZY
))
1560 if (CFStringRef (*$MGCopyAnswer
)(CFStringRef
) = (CFStringRef (*)(CFStringRef
)) dlsym(libMobileGestalt
, "MGCopyAnswer"))
1561 UniqueID_
= $
MGCopyAnswer(CFSTR("UniqueDeviceID"));
1563 if (UniqueID_
== NULL
)
1564 if (void *lockdown
= lockdown_connect()) {
1565 UniqueID_
= lockdown_copy_value(lockdown
, NULL
, kLockdownUniqueDeviceIDKey
);
1566 lockdown_disconnect(lockdown
);