2 #include <mach-o/nlist.h>
5 // -*- mode: cpp; mode: fold -*-
7 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
8 /* ######################################################################
10 HTTP Aquire Method - This is the HTTP aquire method for APT.
12 It uses HTTP/1.1 and many of the fancy options there-in, such as
13 pipelining, range, if-range and so on.
15 It is based on a doubly buffered select loop. A groupe of requests are
16 fed into a single output buffer that is constantly fed out the
17 socket. This provides ideal pipelining as in many cases all of the
18 requests will fit into a single packet. The input socket is buffered
19 the same way and fed into the fd for the file (may be a pipe in future).
21 This double buffering provides fairly substantial transfer rates,
22 compared to wget the http method is about 4% faster. Most importantly,
23 when HTTP is compared with FTP as a protocol the speed difference is
24 huge. In tests over the internet from two sites to llug (via ATM) this
25 program got 230k/s sustained http transfer rates. FTP on the other
26 hand topped out at 170k/s. That combined with the time to setup the
27 FTP connection makes HTTP a vastly superior protocol.
29 ##################################################################### */
31 // Include Files /*{{{*/
32 #include <apt-pkg/fileutl.h>
33 #include <apt-pkg/acquire-method.h>
34 #include <apt-pkg/error.h>
35 #include <apt-pkg/hashes.h>
37 #include <sys/sysctl.h>
52 #include <arpa/inet.h>
55 #include <CoreFoundation/CoreFoundation.h>
56 #include <CoreServices/CoreServices.h>
57 #include <SystemConfiguration/SystemConfiguration.h>
60 #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;
118 unsigned long CircleBuf::BwReadLimit
=0;
119 unsigned long CircleBuf::BwTickReadData
=0;
120 struct timeval
CircleBuf::BwReadTick
={0,0};
121 const unsigned int CircleBuf::BW_HZ
=10;
123 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
124 // ---------------------------------------------------------------------
126 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
128 Buf
= new unsigned char[Size
];
131 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
134 // CircleBuf::Reset - Reset to the default state /*{{{*/
135 // ---------------------------------------------------------------------
137 void CircleBuf::Reset()
142 MaxGet
= (unsigned int)-1;
151 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
152 // ---------------------------------------------------------------------
153 /* This fills up the buffer with as much data as is in the FD, assuming it
155 bool CircleBuf::Read(int Fd
)
157 unsigned long BwReadMax
;
161 // Woops, buffer is full
162 if (InP
- OutP
== Size
)
165 // what's left to read in this tick
166 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
168 if(CircleBuf::BwReadLimit
) {
170 gettimeofday(&now
,0);
172 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
173 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
174 if(d
> 1000000/BW_HZ
) {
175 CircleBuf::BwReadTick
= now
;
176 CircleBuf::BwTickReadData
= 0;
179 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
180 usleep(1000000/BW_HZ
);
185 // Write the buffer segment
187 if(CircleBuf::BwReadLimit
) {
188 Res
= read(Fd
,Buf
+ (InP%Size
),
189 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
191 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
193 if(Res
> 0 && BwReadLimit
> 0)
194 CircleBuf::BwTickReadData
+= Res
;
206 gettimeofday(&Start
,0);
211 // CircleBuf::Read - Put the string into the buffer /*{{{*/
212 // ---------------------------------------------------------------------
213 /* This will hold the string in and fill the buffer with it as it empties */
214 bool CircleBuf::Read(string Data
)
221 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
222 // ---------------------------------------------------------------------
224 void CircleBuf::FillOut()
226 if (OutQueue
.empty() == true)
230 // Woops, buffer is full
231 if (InP
- OutP
== Size
)
234 // Write the buffer segment
235 unsigned long Sz
= LeftRead();
236 if (OutQueue
.length() - StrPos
< Sz
)
237 Sz
= OutQueue
.length() - StrPos
;
238 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
243 if (OutQueue
.length() == StrPos
)
252 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
253 // ---------------------------------------------------------------------
254 /* This empties the buffer into the FD. */
255 bool CircleBuf::Write(int Fd
)
261 // Woops, buffer is empty
268 // Write the buffer segment
270 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
283 Hash
->Add(Buf
+ (OutP%Size
),Res
);
289 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
290 // ---------------------------------------------------------------------
291 /* This copies till the first empty line */
292 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
294 // We cheat and assume it is unneeded to have more than one buffer load
295 for (unsigned long I
= OutP
; I
< InP
; I
++)
297 if (Buf
[I%Size
] != '\n')
303 if (I
< InP
&& Buf
[I%Size
] == '\r')
305 if (I
>= InP
|| Buf
[I%Size
] != '\n')
313 unsigned long Sz
= LeftWrite();
318 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
326 // CircleBuf::Stats - Print out stats information /*{{{*/
327 // ---------------------------------------------------------------------
329 void CircleBuf::Stats()
335 gettimeofday(&Stop
,0);
336 /* float Diff = Stop.tv_sec - Start.tv_sec +
337 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
338 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
342 // ServerState::ServerState - Constructor /*{{{*/
343 // ---------------------------------------------------------------------
345 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
346 In(64*1024), Out(4*1024),
352 // ServerState::Open - Open a connection to the server /*{{{*/
353 // ---------------------------------------------------------------------
354 /* This opens a connection to the server. */
355 bool ServerState::Open()
357 // Use the already open connection if possible.
366 // Determine the proxy setting
367 if (getenv("http_proxy") == 0)
369 string DefProxy
= _config
->Find("Acquire::http::Proxy");
370 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
371 if (SpecificProxy
.empty() == false)
373 if (SpecificProxy
== "DIRECT")
376 Proxy
= SpecificProxy
;
382 Proxy
= getenv("http_proxy");
384 // Parse no_proxy, a , separated list of domains
385 if (getenv("no_proxy") != 0)
387 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
391 // Determine what host and port to use based on the proxy settings
394 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
396 if (ServerName
.Port
!= 0)
397 Port
= ServerName
.Port
;
398 Host
= ServerName
.Host
;
407 // Connect to the remote server
408 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
414 // ServerState::Close - Close a connection to the server /*{{{*/
415 // ---------------------------------------------------------------------
417 bool ServerState::Close()
424 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
425 // ---------------------------------------------------------------------
426 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
427 parse error occured */
428 int ServerState::RunHeaders()
432 Owner
->Status(_("Waiting for headers"));
446 if (In
.WriteTillEl(Data
) == false)
452 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
454 string::const_iterator J
= I
;
455 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
456 if (HeaderLine(string(I
,J
)) == false)
461 // 100 Continue is a Nop...
465 // Tidy up the connection persistance state.
466 if (Encoding
== Closes
&& HaveContent
== true)
471 while (Owner
->Go(false,this) == true);
476 // ServerState::RunData - Transfer the data from the socket /*{{{*/
477 // ---------------------------------------------------------------------
479 bool ServerState::RunData()
483 // Chunked transfer encoding is fun..
484 if (Encoding
== Chunked
)
488 // Grab the block size
494 if (In
.WriteTillEl(Data
,true) == true)
497 while ((Last
= Owner
->Go(false,this)) == true);
502 // See if we are done
503 unsigned long Len
= strtol(Data
.c_str(),0,16);
508 // We have to remove the entity trailer
512 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
515 while ((Last
= Owner
->Go(false,this)) == true);
518 return !_error
->PendingError();
521 // Transfer the block
523 while (Owner
->Go(true,this) == true)
524 if (In
.IsLimit() == true)
528 if (In
.IsLimit() == false)
531 // The server sends an extra new line before the next block specifier..
536 if (In
.WriteTillEl(Data
,true) == true)
539 while ((Last
= Owner
->Go(false,this)) == true);
546 /* Closes encoding is used when the server did not specify a size, the
547 loss of the connection means we are done */
548 if (Encoding
== Closes
)
551 In
.Limit(Size
- StartPos
);
553 // Just transfer the whole block.
556 if (In
.IsLimit() == false)
560 return !_error
->PendingError();
562 while (Owner
->Go(true,this) == true);
565 return Owner
->Flush(this) && !_error
->PendingError();
568 // ServerState::HeaderLine - Process a header line /*{{{*/
569 // ---------------------------------------------------------------------
571 bool ServerState::HeaderLine(string Line
)
573 if (Line
.empty() == true)
576 // The http server might be trying to do something evil.
577 if (Line
.length() >= MAXLEN
)
578 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
580 string::size_type Pos
= Line
.find(' ');
581 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
583 // Blah, some servers use "connection:closes", evil.
584 Pos
= Line
.find(':');
585 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
586 return _error
->Error(_("Bad header line"));
590 // Parse off any trailing spaces between the : and the next word.
591 string::size_type Pos2
= Pos
;
592 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
595 string Tag
= string(Line
,0,Pos
);
596 string Val
= string(Line
,Pos2
);
598 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
600 // Evil servers return no version
603 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
605 return _error
->Error(_("The HTTP server sent an invalid reply header"));
611 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
612 return _error
->Error(_("The HTTP server sent an invalid reply header"));
615 /* Check the HTTP response header to get the default persistance
621 if (Major
== 1 && Minor
<= 0)
630 if (stringcasecmp(Tag
,"Content-Length:") == 0)
632 if (Encoding
== Closes
)
636 // The length is already set from the Content-Range header
640 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
641 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
645 if (stringcasecmp(Tag
,"Content-Type:") == 0)
651 if (stringcasecmp(Tag
,"Content-Range:") == 0)
655 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
656 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
657 if ((unsigned)StartPos
> Size
)
658 return _error
->Error(_("This HTTP server has broken range support"));
662 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
665 if (stringcasecmp(Val
,"chunked") == 0)
670 if (stringcasecmp(Tag
,"Connection:") == 0)
672 if (stringcasecmp(Val
,"close") == 0)
674 if (stringcasecmp(Val
,"keep-alive") == 0)
679 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
681 if (StrToTime(Val
,Date
) == false)
682 return _error
->Error(_("Unknown date format"));
690 static const CFOptionFlags kNetworkEvents
=
691 kCFStreamEventOpenCompleted
|
692 kCFStreamEventHasBytesAvailable
|
693 kCFStreamEventEndEncountered
|
694 kCFStreamEventErrorOccurred
|
697 static void CFReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType event
, void *arg
) {
699 case kCFStreamEventOpenCompleted
:
702 case kCFStreamEventHasBytesAvailable
:
703 case kCFStreamEventEndEncountered
:
704 *reinterpret_cast<int *>(arg
) = 1;
705 CFRunLoopStop(CFRunLoopGetCurrent());
708 case kCFStreamEventErrorOccurred
:
709 *reinterpret_cast<int *>(arg
) = -1;
710 CFRunLoopStop(CFRunLoopGetCurrent());
715 /* http://lists.apple.com/archives/Macnetworkprog/2006/Apr/msg00014.html */
716 int CFReadStreamOpen(CFReadStreamRef stream
, double timeout
) {
717 CFStreamClientContext context
;
720 memset(&context
, 0, sizeof(context
));
721 context
.info
= &value
;
723 if (CFReadStreamSetClient(stream
, kNetworkEvents
, CFReadStreamCallback
, &context
)) {
724 CFReadStreamScheduleWithRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
725 if (CFReadStreamOpen(stream
))
726 CFRunLoopRunInMode(kCFRunLoopDefaultMode
, timeout
, false);
729 CFReadStreamSetClient(stream
, kCFStreamEventNone
, NULL
, NULL
);
735 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
736 // ---------------------------------------------------------------------
737 /* This places the http request in the outbound buffer */
738 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
742 // The HTTP server expects a hostname with a trailing :port
744 string ProperHost
= Uri
.Host
;
747 sprintf(Buf
,":%u",Uri
.Port
);
752 if (Itm
->Uri
.length() >= sizeof(Buf
))
755 /* Build the request. We include a keep-alive header only for non-proxy
756 requests. This is to tweak old http/1.0 servers that do support keep-alive
757 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
758 will glitch HTTP/1.0 proxies because they do not filter it out and
759 pass it on, HTTP/1.1 says the connection should default to keep alive
760 and we expect the proxy to do this */
761 if (Proxy
.empty() == true || Proxy
.Host
.empty())
762 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
763 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
766 /* Generate a cache control header if necessary. We place a max
767 cache age on index files, optionally set a no-cache directive
768 and a no-store directive for archives. */
769 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
770 Itm
->Uri
.c_str(),ProperHost
.c_str());
771 // only generate a cache control header if we actually want to
773 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
775 if (Itm
->IndexFile
== true)
776 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
777 _config
->FindI("Acquire::http::Max-Age",0));
780 if (_config
->FindB("Acquire::http::No-Store",false) == true)
781 strcat(Buf
,"Cache-Control: no-store\r\n");
785 // generate a no-cache header if needed
786 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
787 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
792 // Check for a partial file
794 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
796 // In this case we send an if-range query with a range header
797 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
798 TimeRFC1123(SBuf
.st_mtime
).c_str());
803 if (Itm
->LastModified
!= 0)
805 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
810 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
811 Req
+= string("Proxy-Authorization: Basic ") +
812 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
814 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
815 Req
+= string("Authorization: Basic ") +
816 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
818 Req
+= "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
826 // HttpMethod::Go - Run a single loop /*{{{*/
827 // ---------------------------------------------------------------------
828 /* This runs the select loop over the server FDs, Output file FDs and
830 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
832 // Server has closed the connection
833 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
841 /* Add the server. We only send more requests if the connection will
843 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
844 && Srv
->Persistent
== true)
845 FD_SET(Srv
->ServerFd
,&wfds
);
846 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
847 FD_SET(Srv
->ServerFd
,&rfds
);
854 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
855 FD_SET(FileFD
,&wfds
);
858 FD_SET(STDIN_FILENO
,&rfds
);
860 // Figure out the max fd
862 if (MaxFd
< Srv
->ServerFd
)
863 MaxFd
= Srv
->ServerFd
;
870 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
874 return _error
->Errno("select",_("Select failed"));
879 _error
->Error(_("Connection timed out"));
880 return ServerDie(Srv
);
884 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
887 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
888 return ServerDie(Srv
);
891 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
894 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
895 return ServerDie(Srv
);
898 // Send data to the file
899 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
901 if (Srv
->In
.Write(FileFD
) == false)
902 return _error
->Errno("write",_("Error writing to output file"));
905 // Handle commands from APT
906 if (FD_ISSET(STDIN_FILENO
,&rfds
))
915 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
916 // ---------------------------------------------------------------------
917 /* This takes the current input buffer from the Server FD and writes it
919 bool HttpMethod::Flush(ServerState
*Srv
)
923 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
925 if (File
->Name() != "/dev/null")
926 SetNonBlock(File
->Fd(),false);
927 if (Srv
->In
.WriteSpace() == false)
930 while (Srv
->In
.WriteSpace() == true)
932 if (Srv
->In
.Write(File
->Fd()) == false)
933 return _error
->Errno("write",_("Error writing to file"));
934 if (Srv
->In
.IsLimit() == true)
938 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
944 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
945 // ---------------------------------------------------------------------
947 bool HttpMethod::ServerDie(ServerState
*Srv
)
949 unsigned int LErrno
= errno
;
951 // Dump the buffer to the file
952 if (Srv
->State
== ServerState::Data
)
954 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
956 if (File
->Name() != "/dev/null")
957 SetNonBlock(File
->Fd(),false);
958 while (Srv
->In
.WriteSpace() == true)
960 if (Srv
->In
.Write(File
->Fd()) == false)
961 return _error
->Errno("write",_("Error writing to the file"));
964 if (Srv
->In
.IsLimit() == true)
969 // See if this is because the server finished the data stream
970 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
971 Srv
->Encoding
!= ServerState::Closes
)
975 return _error
->Error(_("Error reading from server. Remote end closed connection"));
977 return _error
->Errno("read",_("Error reading from server"));
983 // Nothing left in the buffer
984 if (Srv
->In
.WriteSpace() == false)
987 // We may have got multiple responses back in one packet..
995 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
996 // ---------------------------------------------------------------------
997 /* We look at the header data we got back from the server and decide what
1001 3 - Unrecoverable error
1002 4 - Error with error content page
1003 5 - Unrecoverable non-server error (close the connection) */
1004 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
1007 if (Srv
->Result
== 304)
1009 unlink(Queue
->DestFile
.c_str());
1011 Res
.LastModified
= Queue
->LastModified
;
1015 /* We have a reply we dont handle. This should indicate a perm server
1017 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
1019 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
1020 if (Srv
->HaveContent
== true)
1025 // This is some sort of 2xx 'data follows' reply
1026 Res
.LastModified
= Srv
->Date
;
1027 Res
.Size
= Srv
->Size
;
1031 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
1032 if (_error
->PendingError() == true)
1035 FailFile
= Queue
->DestFile
;
1036 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1037 FailFd
= File
->Fd();
1038 FailTime
= Srv
->Date
;
1040 // Set the expected size
1041 if (Srv
->StartPos
>= 0)
1043 Res
.ResumePoint
= Srv
->StartPos
;
1044 ftruncate(File
->Fd(),Srv
->StartPos
);
1047 // Set the start point
1048 lseek(File
->Fd(),0,SEEK_END
);
1050 delete Srv
->In
.Hash
;
1051 Srv
->In
.Hash
= new Hashes
;
1053 // Fill the Hash if the file is non-empty (resume)
1054 if (Srv
->StartPos
> 0)
1056 lseek(File
->Fd(),0,SEEK_SET
);
1057 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1059 _error
->Errno("read",_("Problem hashing file"));
1062 lseek(File
->Fd(),0,SEEK_END
);
1065 SetNonBlock(File
->Fd(),true);
1069 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1070 // ---------------------------------------------------------------------
1071 /* This closes and timestamps the open file. This is neccessary to get
1072 resume behavoir on user abort */
1073 void HttpMethod::SigTerm(int)
1080 struct utimbuf UBuf
;
1081 UBuf
.actime
= FailTime
;
1082 UBuf
.modtime
= FailTime
;
1083 utime(FailFile
.c_str(),&UBuf
);
1088 // HttpMethod::Fetch - Fetch an item /*{{{*/
1089 // ---------------------------------------------------------------------
1090 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1092 bool HttpMethod::Fetch(FetchItem
*)
1097 // Queue the requests
1100 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1101 I
= I
->Next
, Depth
++)
1103 // If pipelining is disabled, we only queue 1 request
1104 if (Server
->Pipeline
== false && Depth
>= 0)
1107 // Make sure we stick with the same server
1108 if (Server
->Comp(I
->Uri
) == false)
1114 QueueBack
= I
->Next
;
1115 SendReq(I
,Server
->Out
);
1123 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1124 // ---------------------------------------------------------------------
1125 /* We stash the desired pipeline depth */
1126 bool HttpMethod::Configuration(string Message
)
1128 if (pkgAcqMethod::Configuration(Message
) == false)
1131 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1132 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1134 Debug
= _config
->FindB("Debug::Acquire::http",false);
1139 // HttpMethod::Loop - Main loop /*{{{*/
1140 // ---------------------------------------------------------------------
1142 int HttpMethod::Loop()
1144 signal(SIGTERM
,SigTerm
);
1145 signal(SIGINT
,SigTerm
);
1149 std::set
<std::string
> cached
;
1151 int FailCounter
= 0;
1154 // We have no commands, wait for some to arrive
1157 if (WaitFd(STDIN_FILENO
) == false)
1161 /* Run messages, we can accept 0 (no message) if we didn't
1162 do a WaitFd above.. Otherwise the FD is closed. */
1163 int Result
= Run(true);
1164 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1170 CFStringEncoding se
= kCFStringEncodingUTF8
;
1172 char *url
= strdup(Queue
->Uri
.c_str());
1174 URI uri
= std::string(url
);
1175 std::string hs
= uri
.Host
;
1177 if (cached
.find(hs
) != cached
.end()) {
1178 _error
->Error("Cached Failure");
1185 std::string urs
= uri
;
1188 size_t bad
= urs
.find_first_of("+");
1189 if (bad
== std::string::npos
)
1192 urs
= urs
.substr(0, bad
) + "%2b" + urs
.substr(bad
+ 1);
1195 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, urs
.c_str(), se
);
1196 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1198 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1202 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1203 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1204 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1207 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1208 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1211 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1212 } else if (Queue
->LastModified
!= 0) {
1213 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(Queue
->LastModified
).c_str(), se
);
1214 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1217 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("no-cache"));
1219 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Cache-Control"), CFSTR("max-age=0"));
1221 if (Firmware_
!= NULL
)
1222 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Firmware"), Firmware_
);
1224 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Machine_
, se
);
1225 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Machine"), sr
);
1228 if (UniqueID_
!= NULL
)
1229 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Unique-ID"), UniqueID_
);
1231 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.534"));
1233 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1236 #define _kCFStreamPropertyReadTimeout CFSTR("_kCFStreamPropertyReadTimeout")
1237 #define _kCFStreamPropertyWriteTimeout CFSTR("_kCFStreamPropertyWriteTimeout")
1238 #define _kCFStreamPropertySocketImmediateBufferTimeOut CFSTR("_kCFStreamPropertySocketImmediateBufferTimeOut")
1240 /*SInt32 to(TimeOut);
1241 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &to));*/
1243 CFNumberRef
nm(CFNumberCreate(kCFAllocatorDefault
, kCFNumberDoubleType
, &to
));
1245 CFReadStreamSetProperty(rs
, _kCFStreamPropertyReadTimeout
, nm
);
1246 CFReadStreamSetProperty(rs
, _kCFStreamPropertyWriteTimeout
, nm
);
1247 CFReadStreamSetProperty(rs
, _kCFStreamPropertySocketImmediateBufferTimeOut
, nm
);
1250 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1251 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1254 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1255 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1261 uint8_t data
[10240];
1264 Status("Connecting to %s", hs
.c_str());
1266 switch (CFReadStreamOpen(rs
, to
)) {
1268 CfrsError("Open", rs
);
1272 _error
->Error("Host Unreachable");
1285 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1288 CfrsError(uri
.Host
.c_str(), rs
);
1294 Res
.Filename
= Queue
->DestFile
;
1296 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1297 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1299 if (sc
== 301 || sc
== 302) {
1300 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Location"));
1305 size_t ln
= CFStringGetLength(sr
) + 1;
1307 url
= static_cast<char *>(malloc(ln
));
1309 if (!CFStringGetCString(sr
, url
, ln
, se
)) {
1319 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1321 size_t ln
= CFStringGetLength(sr
) + 1;
1324 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1331 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1332 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1337 if (offset
> Res
.Size
) {
1338 _error
->Error(_("This HTTP server has broken range support"));
1343 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1345 Res
.Size
= CFStringGetIntValue(sr
);
1350 time(&Res
.LastModified
);
1352 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1354 size_t ln
= CFStringGetLength(sr
) + 1;
1357 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1364 if (!StrToTime(cr
, Res
.LastModified
)) {
1365 _error
->Error(_("Unknown date format"));
1371 if (sc
< 200 || sc
>= 300 && sc
!= 304) {
1372 sr
= CFHTTPMessageCopyResponseStatusLine(hm
);
1374 size_t ln
= CFStringGetLength(sr
) + 1;
1377 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1384 _error
->Error("%s", cr
);
1393 unlink(Queue
->DestFile
.c_str());
1395 Res
.LastModified
= Queue
->LastModified
;
1400 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1401 if (_error
->PendingError() == true) {
1408 FailFile
= Queue
->DestFile
;
1409 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1410 FailFd
= File
->Fd();
1411 FailTime
= Res
.LastModified
;
1413 Res
.ResumePoint
= offset
;
1414 ftruncate(File
->Fd(), offset
);
1417 lseek(File
->Fd(), 0, SEEK_SET
);
1418 if (!hash
.AddFD(File
->Fd(), offset
)) {
1419 _error
->Errno("read", _("Problem hashing file"));
1427 lseek(File
->Fd(), 0, SEEK_END
);
1431 read
: if (rd
== -1) {
1432 CfrsError("rd", rs
);
1434 } else if (rd
== 0) {
1436 Res
.Size
= File
->Size();
1438 struct utimbuf UBuf
;
1440 UBuf
.actime
= Res
.LastModified
;
1441 UBuf
.modtime
= Res
.LastModified
;
1442 utime(Queue
->DestFile
.c_str(), &UBuf
);
1444 Res
.TakeHashes(hash
);
1451 int sz
= write(File
->Fd(), dt
, rd
);
1464 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1473 CFReadStreamClose(rs
);
1486 #if !defined(__ENVIRONMENT_ASPEN_VERSION_MIN_REQUIRED__) || __ENVIRONMENT_ASPEN_VERSION_MIN_REQUIRED__ < 10200
1488 memset(nl
, 0, sizeof(nl
));
1489 nl
[0].n_un
.n_name
= (char *) "_useMDNSResponder";
1490 nlist("/usr/lib/libc.dylib", nl
);
1491 if (nl
[0].n_type
!= N_UNDF
)
1492 *(int *) nl
[0].n_value
= 0;
1495 setlocale(LC_ALL
, "");
1500 sysctlbyname("hw.machine", NULL
, &size
, NULL
, 0);
1501 char *machine
= new char[size
];
1502 sysctlbyname("hw.machine", machine
, &size
, NULL
, 0);
1505 const char *path
= "/System/Library/CoreServices/SystemVersion.plist";
1506 CFURLRef url
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
, (uint8_t *) path
, strlen(path
), false);
1508 CFPropertyListRef plist
; {
1509 CFReadStreamRef stream
= CFReadStreamCreateWithFile(kCFAllocatorDefault
, url
);
1510 CFReadStreamOpen(stream
);
1511 plist
= CFPropertyListCreateFromStream(kCFAllocatorDefault
, stream
, 0, kCFPropertyListImmutable
, NULL
, NULL
);
1512 CFReadStreamClose(stream
);
1517 if (plist
!= NULL
) {
1518 Firmware_
= (CFStringRef
) CFRetain(CFDictionaryGetValue((CFDictionaryRef
) plist
, CFSTR("ProductVersion")));
1522 if (void *lockdown
= lockdown_connect()) {
1523 UniqueID_
= lockdown_copy_value(lockdown
, NULL
, kLockdownUniqueDeviceIDKey
);
1524 lockdown_disconnect(lockdown
);