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>
33 #include <sys/sysctl.h>
48 #include <arpa/inet.h>
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreServices/CoreServices.h>
53 #include <SystemConfiguration/SystemConfiguration.h>
57 #include "rfc2553emu.h"
63 CFStringRef Firmware_
;
65 CFStringRef UniqueID_
;
67 void CfrsError(const char *name
, CFReadStreamRef rs
) {
68 CFStreamError se
= CFReadStreamGetError(rs
);
70 if (se
.domain
== kCFStreamErrorDomainCustom
) {
71 } else if (se
.domain
== kCFStreamErrorDomainPOSIX
) {
72 _error
->Error("POSIX: %s", strerror(se
.error
));
73 } else if (se
.domain
== kCFStreamErrorDomainMacOSStatus
) {
74 _error
->Error("MacOSStatus: %ld", se
.error
);
75 } else if (se
.domain
== kCFStreamErrorDomainNetDB
) {
76 _error
->Error("NetDB: %s %s", name
, gai_strerror(se
.error
));
77 } else if (se
.domain
== kCFStreamErrorDomainMach
) {
78 _error
->Error("Mach: %ld", se
.error
);
79 } else if (se
.domain
== kCFStreamErrorDomainHTTP
) {
81 case kCFStreamErrorHTTPParseFailure
:
82 _error
->Error("Parse failure");
85 case kCFStreamErrorHTTPRedirectionLoop
:
86 _error
->Error("Redirection loop");
89 case kCFStreamErrorHTTPBadURL
:
90 _error
->Error("Bad URL");
94 _error
->Error("Unknown HTTP error: %ld", se
.error
);
97 } else if (se
.domain
== kCFStreamErrorDomainSOCKS
) {
98 _error
->Error("SOCKS: %ld", se
.error
);
99 } else if (se
.domain
== kCFStreamErrorDomainSystemConfiguration
) {
100 _error
->Error("SystemConfiguration: %ld", se
.error
);
101 } else if (se
.domain
== kCFStreamErrorDomainSSL
) {
102 _error
->Error("SSL: %ld", se
.error
);
104 _error
->Error("Domain #%ld: %ld", se
.domain
, se
.error
);
108 string
HttpMethod::FailFile
;
109 int HttpMethod::FailFd
= -1;
110 time_t HttpMethod::FailTime
= 0;
111 unsigned long PipelineDepth
= 10;
112 unsigned long TimeOut
= 120;
116 unsigned long CircleBuf::BwReadLimit
=0;
117 unsigned long CircleBuf::BwTickReadData
=0;
118 struct timeval
CircleBuf::BwReadTick
={0,0};
119 const unsigned int CircleBuf::BW_HZ
=10;
121 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
122 // ---------------------------------------------------------------------
124 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
126 Buf
= new unsigned char[Size
];
129 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
132 // CircleBuf::Reset - Reset to the default state /*{{{*/
133 // ---------------------------------------------------------------------
135 void CircleBuf::Reset()
140 MaxGet
= (unsigned int)-1;
149 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
150 // ---------------------------------------------------------------------
151 /* This fills up the buffer with as much data as is in the FD, assuming it
153 bool CircleBuf::Read(int Fd
)
155 unsigned long BwReadMax
;
159 // Woops, buffer is full
160 if (InP
- OutP
== Size
)
163 // what's left to read in this tick
164 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
166 if(CircleBuf::BwReadLimit
) {
168 gettimeofday(&now
,0);
170 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
171 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
172 if(d
> 1000000/BW_HZ
) {
173 CircleBuf::BwReadTick
= now
;
174 CircleBuf::BwTickReadData
= 0;
177 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
178 usleep(1000000/BW_HZ
);
183 // Write the buffer segment
185 if(CircleBuf::BwReadLimit
) {
186 Res
= read(Fd
,Buf
+ (InP%Size
),
187 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
189 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
191 if(Res
> 0 && BwReadLimit
> 0)
192 CircleBuf::BwTickReadData
+= Res
;
204 gettimeofday(&Start
,0);
209 // CircleBuf::Read - Put the string into the buffer /*{{{*/
210 // ---------------------------------------------------------------------
211 /* This will hold the string in and fill the buffer with it as it empties */
212 bool CircleBuf::Read(string Data
)
219 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
220 // ---------------------------------------------------------------------
222 void CircleBuf::FillOut()
224 if (OutQueue
.empty() == true)
228 // Woops, buffer is full
229 if (InP
- OutP
== Size
)
232 // Write the buffer segment
233 unsigned long Sz
= LeftRead();
234 if (OutQueue
.length() - StrPos
< Sz
)
235 Sz
= OutQueue
.length() - StrPos
;
236 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
241 if (OutQueue
.length() == StrPos
)
250 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
251 // ---------------------------------------------------------------------
252 /* This empties the buffer into the FD. */
253 bool CircleBuf::Write(int Fd
)
259 // Woops, buffer is empty
266 // Write the buffer segment
268 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
281 Hash
->Add(Buf
+ (OutP%Size
),Res
);
287 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
288 // ---------------------------------------------------------------------
289 /* This copies till the first empty line */
290 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
292 // We cheat and assume it is unneeded to have more than one buffer load
293 for (unsigned long I
= OutP
; I
< InP
; I
++)
295 if (Buf
[I%Size
] != '\n')
301 if (I
< InP
&& Buf
[I%Size
] == '\r')
303 if (I
>= InP
|| Buf
[I%Size
] != '\n')
311 unsigned long Sz
= LeftWrite();
316 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
324 // CircleBuf::Stats - Print out stats information /*{{{*/
325 // ---------------------------------------------------------------------
327 void CircleBuf::Stats()
333 gettimeofday(&Stop
,0);
334 /* float Diff = Stop.tv_sec - Start.tv_sec +
335 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
336 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
340 // ServerState::ServerState - Constructor /*{{{*/
341 // ---------------------------------------------------------------------
343 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
344 In(64*1024), Out(4*1024),
350 // ServerState::Open - Open a connection to the server /*{{{*/
351 // ---------------------------------------------------------------------
352 /* This opens a connection to the server. */
353 bool ServerState::Open()
355 // Use the already open connection if possible.
364 // Determine the proxy setting
365 if (getenv("http_proxy") == 0)
367 string DefProxy
= _config
->Find("Acquire::http::Proxy");
368 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
369 if (SpecificProxy
.empty() == false)
371 if (SpecificProxy
== "DIRECT")
374 Proxy
= SpecificProxy
;
380 Proxy
= getenv("http_proxy");
382 // Parse no_proxy, a , separated list of domains
383 if (getenv("no_proxy") != 0)
385 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
389 // Determine what host and port to use based on the proxy settings
392 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
394 if (ServerName
.Port
!= 0)
395 Port
= ServerName
.Port
;
396 Host
= ServerName
.Host
;
405 // Connect to the remote server
406 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
412 // ServerState::Close - Close a connection to the server /*{{{*/
413 // ---------------------------------------------------------------------
415 bool ServerState::Close()
422 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
423 // ---------------------------------------------------------------------
424 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
425 parse error occurred */
426 int ServerState::RunHeaders()
430 Owner
->Status(_("Waiting for headers"));
444 if (In
.WriteTillEl(Data
) == false)
450 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
452 string::const_iterator J
= I
;
453 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
454 if (HeaderLine(string(I
,J
)) == false)
459 // 100 Continue is a Nop...
463 // Tidy up the connection persistance state.
464 if (Encoding
== Closes
&& HaveContent
== true)
469 while (Owner
->Go(false,this) == true);
474 // ServerState::RunData - Transfer the data from the socket /*{{{*/
475 // ---------------------------------------------------------------------
477 bool ServerState::RunData()
481 // Chunked transfer encoding is fun..
482 if (Encoding
== Chunked
)
486 // Grab the block size
492 if (In
.WriteTillEl(Data
,true) == true)
495 while ((Last
= Owner
->Go(false,this)) == true);
500 // See if we are done
501 unsigned long Len
= strtol(Data
.c_str(),0,16);
506 // We have to remove the entity trailer
510 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
513 while ((Last
= Owner
->Go(false,this)) == true);
516 return !_error
->PendingError();
519 // Transfer the block
521 while (Owner
->Go(true,this) == true)
522 if (In
.IsLimit() == true)
526 if (In
.IsLimit() == false)
529 // The server sends an extra new line before the next block specifier..
534 if (In
.WriteTillEl(Data
,true) == true)
537 while ((Last
= Owner
->Go(false,this)) == true);
544 /* Closes encoding is used when the server did not specify a size, the
545 loss of the connection means we are done */
546 if (Encoding
== Closes
)
549 In
.Limit(Size
- StartPos
);
551 // Just transfer the whole block.
554 if (In
.IsLimit() == false)
558 return !_error
->PendingError();
560 while (Owner
->Go(true,this) == true);
563 return Owner
->Flush(this) && !_error
->PendingError();
566 // ServerState::HeaderLine - Process a header line /*{{{*/
567 // ---------------------------------------------------------------------
569 bool ServerState::HeaderLine(string Line
)
571 if (Line
.empty() == true)
574 // The http server might be trying to do something evil.
575 if (Line
.length() >= MAXLEN
)
576 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
578 string::size_type Pos
= Line
.find(' ');
579 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
581 // Blah, some servers use "connection:closes", evil.
582 Pos
= Line
.find(':');
583 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
584 return _error
->Error(_("Bad header line"));
588 // Parse off any trailing spaces between the : and the next word.
589 string::size_type Pos2
= Pos
;
590 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
593 string Tag
= string(Line
,0,Pos
);
594 string Val
= string(Line
,Pos2
);
596 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
598 // Evil servers return no version
601 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
603 return _error
->Error(_("The HTTP server sent an invalid reply header"));
609 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
610 return _error
->Error(_("The HTTP server sent an invalid reply header"));
613 /* Check the HTTP response header to get the default persistance
619 if (Major
== 1 && Minor
<= 0)
628 if (stringcasecmp(Tag
,"Content-Length:") == 0)
630 if (Encoding
== Closes
)
634 // The length is already set from the Content-Range header
638 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
639 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
643 if (stringcasecmp(Tag
,"Content-Type:") == 0)
649 if (stringcasecmp(Tag
,"Content-Range:") == 0)
653 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
654 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
655 if ((unsigned)StartPos
> Size
)
656 return _error
->Error(_("This HTTP server has broken range support"));
660 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
663 if (stringcasecmp(Val
,"chunked") == 0)
668 if (stringcasecmp(Tag
,"Connection:") == 0)
670 if (stringcasecmp(Val
,"close") == 0)
672 if (stringcasecmp(Val
,"keep-alive") == 0)
677 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
679 if (StrToTime(Val
,Date
) == false)
680 return _error
->Error(_("Unknown date format"));
688 static const CFOptionFlags kNetworkEvents
=
689 kCFStreamEventOpenCompleted
|
690 kCFStreamEventHasBytesAvailable
|
691 kCFStreamEventEndEncountered
|
692 kCFStreamEventErrorOccurred
|
695 static void CFReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType event
, void *arg
) {
697 case kCFStreamEventOpenCompleted
:
700 case kCFStreamEventHasBytesAvailable
:
701 case kCFStreamEventEndEncountered
:
702 *reinterpret_cast<int *>(arg
) = 1;
703 CFRunLoopStop(CFRunLoopGetCurrent());
706 case kCFStreamEventErrorOccurred
:
707 *reinterpret_cast<int *>(arg
) = -1;
708 CFRunLoopStop(CFRunLoopGetCurrent());
713 /* http://lists.apple.com/archives/Macnetworkprog/2006/Apr/msg00014.html */
714 int CFReadStreamOpen(CFReadStreamRef stream
, double timeout
) {
715 CFStreamClientContext context
;
718 memset(&context
, 0, sizeof(context
));
719 context
.info
= &value
;
721 if (CFReadStreamSetClient(stream
, kNetworkEvents
, CFReadStreamCallback
, &context
)) {
722 CFReadStreamScheduleWithRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
723 if (CFReadStreamOpen(stream
))
724 CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
, false);
727 CFReadStreamSetClient(stream
, kCFStreamEventNone
, NULL
, NULL
);
733 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
734 // ---------------------------------------------------------------------
735 /* This places the http request in the outbound buffer */
736 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
740 // The HTTP server expects a hostname with a trailing :port
742 string ProperHost
= Uri
.Host
;
745 sprintf(Buf
,":%u",Uri
.Port
);
750 if (Itm
->Uri
.length() >= sizeof(Buf
))
753 /* Build the request. We include a keep-alive header only for non-proxy
754 requests. This is to tweak old http/1.0 servers that do support keep-alive
755 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
756 will glitch HTTP/1.0 proxies because they do not filter it out and
757 pass it on, HTTP/1.1 says the connection should default to keep alive
758 and we expect the proxy to do this */
759 if (Proxy
.empty() == true || Proxy
.Host
.empty())
760 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
761 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
764 /* Generate a cache control header if necessary. We place a max
765 cache age on index files, optionally set a no-cache directive
766 and a no-store directive for archives. */
767 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
768 Itm
->Uri
.c_str(),ProperHost
.c_str());
769 // only generate a cache control header if we actually want to
771 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
773 if (Itm
->IndexFile
== true)
774 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
775 _config
->FindI("Acquire::http::Max-Age",0));
778 if (_config
->FindB("Acquire::http::No-Store",false) == true)
779 strcat(Buf
,"Cache-Control: no-store\r\n");
783 // generate a no-cache header if needed
784 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
785 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
790 // Check for a partial file
792 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
794 // In this case we send an if-range query with a range header
795 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
796 TimeRFC1123(SBuf
.st_mtime
).c_str());
801 if (Itm
->LastModified
!= 0)
803 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
808 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
809 Req
+= string("Proxy-Authorization: Basic ") +
810 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
812 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
813 Req
+= string("Authorization: Basic ") +
814 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
816 Req
+= "User-Agent: Debian APT-HTTP/1.3 ("VERSION
")\r\n\r\n";
824 // HttpMethod::Go - Run a single loop /*{{{*/
825 // ---------------------------------------------------------------------
826 /* This runs the select loop over the server FDs, Output file FDs and
828 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
830 // Server has closed the connection
831 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
839 /* Add the server. We only send more requests if the connection will
841 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
842 && Srv
->Persistent
== true)
843 FD_SET(Srv
->ServerFd
,&wfds
);
844 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
845 FD_SET(Srv
->ServerFd
,&rfds
);
852 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
853 FD_SET(FileFD
,&wfds
);
856 FD_SET(STDIN_FILENO
,&rfds
);
858 // Figure out the max fd
860 if (MaxFd
< Srv
->ServerFd
)
861 MaxFd
= Srv
->ServerFd
;
868 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
872 return _error
->Errno("select",_("Select failed"));
877 _error
->Error(_("Connection timed out"));
878 return ServerDie(Srv
);
882 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
885 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
886 return ServerDie(Srv
);
889 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
892 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
893 return ServerDie(Srv
);
896 // Send data to the file
897 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
899 if (Srv
->In
.Write(FileFD
) == false)
900 return _error
->Errno("write",_("Error writing to output file"));
903 // Handle commands from APT
904 if (FD_ISSET(STDIN_FILENO
,&rfds
))
913 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
914 // ---------------------------------------------------------------------
915 /* This takes the current input buffer from the Server FD and writes it
917 bool HttpMethod::Flush(ServerState
*Srv
)
921 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
923 if (File
->Name() != "/dev/null")
924 SetNonBlock(File
->Fd(),false);
925 if (Srv
->In
.WriteSpace() == false)
928 while (Srv
->In
.WriteSpace() == true)
930 if (Srv
->In
.Write(File
->Fd()) == false)
931 return _error
->Errno("write",_("Error writing to file"));
932 if (Srv
->In
.IsLimit() == true)
936 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
942 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
943 // ---------------------------------------------------------------------
945 bool HttpMethod::ServerDie(ServerState
*Srv
)
947 unsigned int LErrno
= errno
;
949 // Dump the buffer to the file
950 if (Srv
->State
== ServerState::Data
)
952 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
954 if (File
->Name() != "/dev/null")
955 SetNonBlock(File
->Fd(),false);
956 while (Srv
->In
.WriteSpace() == true)
958 if (Srv
->In
.Write(File
->Fd()) == false)
959 return _error
->Errno("write",_("Error writing to the file"));
962 if (Srv
->In
.IsLimit() == true)
967 // See if this is because the server finished the data stream
968 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
969 Srv
->Encoding
!= ServerState::Closes
)
973 return _error
->Error(_("Error reading from server. Remote end closed connection"));
975 return _error
->Errno("read",_("Error reading from server"));
981 // Nothing left in the buffer
982 if (Srv
->In
.WriteSpace() == false)
985 // We may have got multiple responses back in one packet..
993 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
994 // ---------------------------------------------------------------------
995 /* We look at the header data we got back from the server and decide what
999 3 - Unrecoverable error
1000 4 - Error with error content page
1001 5 - Unrecoverable non-server error (close the connection) */
1002 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
1005 if (Srv
->Result
== 304)
1007 unlink(Queue
->DestFile
.c_str());
1009 Res
.LastModified
= Queue
->LastModified
;
1013 /* We have a reply we dont handle. This should indicate a perm server
1015 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
1017 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
1018 if (Srv
->HaveContent
== true)
1023 // This is some sort of 2xx 'data follows' reply
1024 Res
.LastModified
= Srv
->Date
;
1025 Res
.Size
= Srv
->Size
;
1029 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
1030 if (_error
->PendingError() == true)
1033 FailFile
= Queue
->DestFile
;
1034 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1035 FailFd
= File
->Fd();
1036 FailTime
= Srv
->Date
;
1038 // Set the expected size
1039 if (Srv
->StartPos
>= 0)
1041 Res
.ResumePoint
= Srv
->StartPos
;
1042 if (ftruncate(File
->Fd(),Srv
->StartPos
) < 0)
1043 _error
->Errno("ftruncate", _("Failed to truncate file"));
1046 // Set the start point
1047 lseek(File
->Fd(),0,SEEK_END
);
1049 delete Srv
->In
.Hash
;
1050 Srv
->In
.Hash
= new Hashes
;
1052 // Fill the Hash if the file is non-empty (resume)
1053 if (Srv
->StartPos
> 0)
1055 lseek(File
->Fd(),0,SEEK_SET
);
1056 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1058 _error
->Errno("read",_("Problem hashing file"));
1061 lseek(File
->Fd(),0,SEEK_END
);
1064 SetNonBlock(File
->Fd(),true);
1068 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1069 // ---------------------------------------------------------------------
1070 /* This closes and timestamps the open file. This is neccessary to get
1071 resume behavoir on user abort */
1072 void HttpMethod::SigTerm(int)
1079 struct utimbuf UBuf
;
1080 UBuf
.actime
= FailTime
;
1081 UBuf
.modtime
= FailTime
;
1082 utime(FailFile
.c_str(),&UBuf
);
1087 // HttpMethod::Fetch - Fetch an item /*{{{*/
1088 // ---------------------------------------------------------------------
1089 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1091 bool HttpMethod::Fetch(FetchItem
*)
1096 // Queue the requests
1098 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1099 I
= I
->Next
, Depth
++)
1101 // If pipelining is disabled, we only queue 1 request
1102 if (Server
->Pipeline
== false && Depth
>= 0)
1105 // Make sure we stick with the same server
1106 if (Server
->Comp(I
->Uri
) == false)
1110 QueueBack
= I
->Next
;
1111 SendReq(I
,Server
->Out
);
1119 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1120 // ---------------------------------------------------------------------
1121 /* We stash the desired pipeline depth */
1122 bool HttpMethod::Configuration(string Message
)
1124 if (pkgAcqMethod::Configuration(Message
) == false)
1127 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1128 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1130 Debug
= _config
->FindB("Debug::Acquire::http",false);
1135 // HttpMethod::Loop - Main loop /*{{{*/
1136 // ---------------------------------------------------------------------
1138 int HttpMethod::Loop()
1140 signal(SIGTERM
,SigTerm
);
1141 signal(SIGINT
,SigTerm
);
1145 std::set
<std::string
> cached
;
1147 int FailCounter
= 0;
1150 // We have no commands, wait for some to arrive
1153 if (WaitFd(STDIN_FILENO
) == false)
1157 /* Run messages, we can accept 0 (no message) if we didn't
1158 do a WaitFd above.. Otherwise the FD is closed. */
1159 int Result
= Run(true);
1160 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1166 CFStringEncoding se
= kCFStringEncodingUTF8
;
1168 char *url
= strdup(Queue
->Uri
.c_str());
1170 URI uri
= std::string(url
);
1171 std::string hs
= uri
.Host
;
1173 if (cached
.find(hs
) != cached
.end()) {
1174 _error
->Error("Cached Failure");
1181 std::string urs
= uri
;
1184 size_t bad
= urs
.find_first_of("+");
1185 if (bad
== std::string::npos
)
1188 urs
= urs
.substr(0, bad
) + "%2b" + urs
.substr(bad
+ 1);
1191 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, urs
.c_str(), se
);
1192 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1194 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1198 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1199 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1200 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1203 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1204 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1207 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1208 } else if (Queue
->LastModified
!= 0) {
1209 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(Queue
->LastModified
).c_str(), se
);
1210 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1213 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1215 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("max-age=0"));
1217 if (Firmware_
!= NULL
)
1218 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Firmware"), Firmware_
);
1220 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Machine_
, se
);
1221 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Machine"), sr
);
1224 if (UniqueID_
!= NULL
)
1225 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Unique-ID"), UniqueID_
);
1227 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.592"));
1229 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1232 #define _kCFStreamPropertyReadTimeout CFSTR("_kCFStreamPropertyReadTimeout")
1233 #define _kCFStreamPropertyWriteTimeout CFSTR("_kCFStreamPropertyWriteTimeout")
1234 #define _kCFStreamPropertySocketImmediateBufferTimeOut CFSTR("_kCFStreamPropertySocketImmediateBufferTimeOut")
1236 /*SInt32 to(TimeOut);
1237 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &to));*/
1239 CFNumberRef
nm(CFNumberCreate(kCFAllocatorDefault
, kCFNumberDoubleType
, &to
));
1241 CFReadStreamSetProperty(rs
, _kCFStreamPropertyReadTimeout
, nm
);
1242 CFReadStreamSetProperty(rs
, _kCFStreamPropertyWriteTimeout
, nm
);
1243 CFReadStreamSetProperty(rs
, _kCFStreamPropertySocketImmediateBufferTimeOut
, nm
);
1246 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1247 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1250 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1251 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1257 uint8_t data
[10240];
1260 Status("Connecting to %s", hs
.c_str());
1262 switch (CFReadStreamOpen(rs
, to
)) {
1264 CfrsError("Open", rs
);
1268 _error
->Error("Host Unreachable");
1281 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1284 CfrsError(uri
.Host
.c_str(), rs
);
1290 Res
.Filename
= Queue
->DestFile
;
1292 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1293 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1295 if (sc
== 301 || sc
== 302) {
1296 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Location"));
1301 size_t ln
= CFStringGetLength(sr
) + 1;
1303 url
= static_cast<char *>(malloc(ln
));
1305 if (!CFStringGetCString(sr
, url
, ln
, se
)) {
1315 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1317 size_t ln
= CFStringGetLength(sr
) + 1;
1320 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1327 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1328 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1333 if (offset
> Res
.Size
) {
1334 _error
->Error(_("This HTTP server has broken range support"));
1339 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1341 Res
.Size
= CFStringGetIntValue(sr
);
1346 time(&Res
.LastModified
);
1348 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1350 size_t ln
= CFStringGetLength(sr
) + 1;
1353 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1360 if (!StrToTime(cr
, Res
.LastModified
)) {
1361 _error
->Error(_("Unknown date format"));
1367 if (sc
< 200 || sc
>= 300 && sc
!= 304) {
1368 sr
= CFHTTPMessageCopyResponseStatusLine(hm
);
1370 size_t ln
= CFStringGetLength(sr
) + 1;
1373 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1380 _error
->Error("%s", cr
);
1389 unlink(Queue
->DestFile
.c_str());
1391 Res
.LastModified
= Queue
->LastModified
;
1396 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1397 if (_error
->PendingError() == true) {
1404 FailFile
= Queue
->DestFile
;
1405 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1406 FailFd
= File
->Fd();
1407 FailTime
= Res
.LastModified
;
1409 Res
.ResumePoint
= offset
;
1410 ftruncate(File
->Fd(), offset
);
1413 lseek(File
->Fd(), 0, SEEK_SET
);
1414 if (!hash
.AddFD(File
->Fd(), offset
)) {
1415 _error
->Errno("read", _("Problem hashing file"));
1423 lseek(File
->Fd(), 0, SEEK_END
);
1427 read
: if (rd
== -1) {
1428 CfrsError("rd", rs
);
1430 } else if (rd
== 0) {
1432 Res
.Size
= File
->Size();
1434 struct utimbuf UBuf
;
1436 UBuf
.actime
= Res
.LastModified
;
1437 UBuf
.modtime
= Res
.LastModified
;
1438 utime(Queue
->DestFile
.c_str(), &UBuf
);
1440 Res
.TakeHashes(hash
);
1447 int sz
= write(File
->Fd(), dt
, rd
);
1460 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1469 CFReadStreamClose(rs
);
1482 setlocale(LC_ALL
, "");
1487 sysctlbyname("hw.machine", NULL
, &size
, NULL
, 0);
1488 char *machine
= new char[size
];
1489 sysctlbyname("hw.machine", machine
, &size
, NULL
, 0);
1492 const char *path
= "/System/Library/CoreServices/SystemVersion.plist";
1493 CFURLRef url
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (uint8_t *) path
, strlen(path
), false);
1495 CFPropertyListRef plist
; {
1496 CFReadStreamRef stream
= CFReadStreamCreateWithFile(kCFAllocatorDefault
, url
);
1497 CFReadStreamOpen(stream
);
1498 plist
= CFPropertyListCreateFromStream(kCFAllocatorDefault
, stream
, 0, kCFPropertyListImmutable
, NULL
, NULL
);
1499 CFReadStreamClose(stream
);
1504 if (plist
!= NULL
) {
1505 Firmware_
= (CFStringRef
) CFRetain(CFDictionaryGetValue((CFDictionaryRef
) plist
, CFSTR("ProductVersion")));
1509 if (void *lockdown
= lockdown_connect()) {
1510 UniqueID_
= lockdown_copy_value(lockdown
, NULL
, kLockdownUniqueDeviceIDKey
);
1511 lockdown_disconnect(lockdown
);