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>
51 #include <arpa/inet.h>
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreServices/CoreServices.h>
55 #include <SystemConfiguration/SystemConfiguration.h>
58 #include "rfc2553emu.h"
65 const char *SerialNumber_
;
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;
115 unsigned long CircleBuf::BwReadLimit
=0;
116 unsigned long CircleBuf::BwTickReadData
=0;
117 struct timeval
CircleBuf::BwReadTick
={0,0};
118 const unsigned int CircleBuf::BW_HZ
=10;
120 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
121 // ---------------------------------------------------------------------
123 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
125 Buf
= new unsigned char[Size
];
128 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
131 // CircleBuf::Reset - Reset to the default state /*{{{*/
132 // ---------------------------------------------------------------------
134 void CircleBuf::Reset()
139 MaxGet
= (unsigned int)-1;
148 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
149 // ---------------------------------------------------------------------
150 /* This fills up the buffer with as much data as is in the FD, assuming it
152 bool CircleBuf::Read(int Fd
)
154 unsigned long BwReadMax
;
158 // Woops, buffer is full
159 if (InP
- OutP
== Size
)
162 // what's left to read in this tick
163 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
165 if(CircleBuf::BwReadLimit
) {
167 gettimeofday(&now
,0);
169 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
170 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
171 if(d
> 1000000/BW_HZ
) {
172 CircleBuf::BwReadTick
= now
;
173 CircleBuf::BwTickReadData
= 0;
176 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
177 usleep(1000000/BW_HZ
);
182 // Write the buffer segment
184 if(CircleBuf::BwReadLimit
) {
185 Res
= read(Fd
,Buf
+ (InP%Size
),
186 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
188 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
190 if(Res
> 0 && BwReadLimit
> 0)
191 CircleBuf::BwTickReadData
+= Res
;
203 gettimeofday(&Start
,0);
208 // CircleBuf::Read - Put the string into the buffer /*{{{*/
209 // ---------------------------------------------------------------------
210 /* This will hold the string in and fill the buffer with it as it empties */
211 bool CircleBuf::Read(string Data
)
218 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
219 // ---------------------------------------------------------------------
221 void CircleBuf::FillOut()
223 if (OutQueue
.empty() == true)
227 // Woops, buffer is full
228 if (InP
- OutP
== Size
)
231 // Write the buffer segment
232 unsigned long Sz
= LeftRead();
233 if (OutQueue
.length() - StrPos
< Sz
)
234 Sz
= OutQueue
.length() - StrPos
;
235 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
240 if (OutQueue
.length() == StrPos
)
249 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
250 // ---------------------------------------------------------------------
251 /* This empties the buffer into the FD. */
252 bool CircleBuf::Write(int Fd
)
258 // Woops, buffer is empty
265 // Write the buffer segment
267 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
280 Hash
->Add(Buf
+ (OutP%Size
),Res
);
286 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
287 // ---------------------------------------------------------------------
288 /* This copies till the first empty line */
289 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
291 // We cheat and assume it is unneeded to have more than one buffer load
292 for (unsigned long I
= OutP
; I
< InP
; I
++)
294 if (Buf
[I%Size
] != '\n')
300 if (I
< InP
&& Buf
[I%Size
] == '\r')
302 if (I
>= InP
|| Buf
[I%Size
] != '\n')
310 unsigned long Sz
= LeftWrite();
315 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
323 // CircleBuf::Stats - Print out stats information /*{{{*/
324 // ---------------------------------------------------------------------
326 void CircleBuf::Stats()
332 gettimeofday(&Stop
,0);
333 /* float Diff = Stop.tv_sec - Start.tv_sec +
334 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
335 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
339 // ServerState::ServerState - Constructor /*{{{*/
340 // ---------------------------------------------------------------------
342 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
343 In(64*1024), Out(4*1024),
349 // ServerState::Open - Open a connection to the server /*{{{*/
350 // ---------------------------------------------------------------------
351 /* This opens a connection to the server. */
352 bool ServerState::Open()
354 // Use the already open connection if possible.
363 // Determine the proxy setting
364 if (getenv("http_proxy") == 0)
366 string DefProxy
= _config
->Find("Acquire::http::Proxy");
367 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
368 if (SpecificProxy
.empty() == false)
370 if (SpecificProxy
== "DIRECT")
373 Proxy
= SpecificProxy
;
379 Proxy
= getenv("http_proxy");
381 // Parse no_proxy, a , separated list of domains
382 if (getenv("no_proxy") != 0)
384 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
388 // Determine what host and port to use based on the proxy settings
391 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
393 if (ServerName
.Port
!= 0)
394 Port
= ServerName
.Port
;
395 Host
= ServerName
.Host
;
404 // Connect to the remote server
405 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
411 // ServerState::Close - Close a connection to the server /*{{{*/
412 // ---------------------------------------------------------------------
414 bool ServerState::Close()
421 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
422 // ---------------------------------------------------------------------
423 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
424 parse error occured */
425 int ServerState::RunHeaders()
429 Owner
->Status(_("Waiting for headers"));
443 if (In
.WriteTillEl(Data
) == false)
449 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
451 string::const_iterator J
= I
;
452 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
453 if (HeaderLine(string(I
,J
)) == false)
458 // 100 Continue is a Nop...
462 // Tidy up the connection persistance state.
463 if (Encoding
== Closes
&& HaveContent
== true)
468 while (Owner
->Go(false,this) == true);
473 // ServerState::RunData - Transfer the data from the socket /*{{{*/
474 // ---------------------------------------------------------------------
476 bool ServerState::RunData()
480 // Chunked transfer encoding is fun..
481 if (Encoding
== Chunked
)
485 // Grab the block size
491 if (In
.WriteTillEl(Data
,true) == true)
494 while ((Last
= Owner
->Go(false,this)) == true);
499 // See if we are done
500 unsigned long Len
= strtol(Data
.c_str(),0,16);
505 // We have to remove the entity trailer
509 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
512 while ((Last
= Owner
->Go(false,this)) == true);
515 return !_error
->PendingError();
518 // Transfer the block
520 while (Owner
->Go(true,this) == true)
521 if (In
.IsLimit() == true)
525 if (In
.IsLimit() == false)
528 // The server sends an extra new line before the next block specifier..
533 if (In
.WriteTillEl(Data
,true) == true)
536 while ((Last
= Owner
->Go(false,this)) == true);
543 /* Closes encoding is used when the server did not specify a size, the
544 loss of the connection means we are done */
545 if (Encoding
== Closes
)
548 In
.Limit(Size
- StartPos
);
550 // Just transfer the whole block.
553 if (In
.IsLimit() == false)
557 return !_error
->PendingError();
559 while (Owner
->Go(true,this) == true);
562 return Owner
->Flush(this) && !_error
->PendingError();
565 // ServerState::HeaderLine - Process a header line /*{{{*/
566 // ---------------------------------------------------------------------
568 bool ServerState::HeaderLine(string Line
)
570 if (Line
.empty() == true)
573 // The http server might be trying to do something evil.
574 if (Line
.length() >= MAXLEN
)
575 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
577 string::size_type Pos
= Line
.find(' ');
578 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
580 // Blah, some servers use "connection:closes", evil.
581 Pos
= Line
.find(':');
582 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
583 return _error
->Error(_("Bad header line"));
587 // Parse off any trailing spaces between the : and the next word.
588 string::size_type Pos2
= Pos
;
589 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
592 string Tag
= string(Line
,0,Pos
);
593 string Val
= string(Line
,Pos2
);
595 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
597 // Evil servers return no version
600 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
602 return _error
->Error(_("The HTTP server sent an invalid reply header"));
608 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
609 return _error
->Error(_("The HTTP server sent an invalid reply header"));
612 /* Check the HTTP response header to get the default persistance
618 if (Major
== 1 && Minor
<= 0)
627 if (stringcasecmp(Tag
,"Content-Length:") == 0)
629 if (Encoding
== Closes
)
633 // The length is already set from the Content-Range header
637 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
638 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
642 if (stringcasecmp(Tag
,"Content-Type:") == 0)
648 if (stringcasecmp(Tag
,"Content-Range:") == 0)
652 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
653 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
654 if ((unsigned)StartPos
> Size
)
655 return _error
->Error(_("This HTTP server has broken range support"));
659 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
662 if (stringcasecmp(Val
,"chunked") == 0)
667 if (stringcasecmp(Tag
,"Connection:") == 0)
669 if (stringcasecmp(Val
,"close") == 0)
671 if (stringcasecmp(Val
,"keep-alive") == 0)
676 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
678 if (StrToTime(Val
,Date
) == false)
679 return _error
->Error(_("Unknown date format"));
687 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
688 // ---------------------------------------------------------------------
689 /* This places the http request in the outbound buffer */
690 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
694 // The HTTP server expects a hostname with a trailing :port
696 string ProperHost
= Uri
.Host
;
699 sprintf(Buf
,":%u",Uri
.Port
);
704 if (Itm
->Uri
.length() >= sizeof(Buf
))
707 /* Build the request. We include a keep-alive header only for non-proxy
708 requests. This is to tweak old http/1.0 servers that do support keep-alive
709 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
710 will glitch HTTP/1.0 proxies because they do not filter it out and
711 pass it on, HTTP/1.1 says the connection should default to keep alive
712 and we expect the proxy to do this */
713 if (Proxy
.empty() == true || Proxy
.Host
.empty())
714 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
715 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
718 /* Generate a cache control header if necessary. We place a max
719 cache age on index files, optionally set a no-cache directive
720 and a no-store directive for archives. */
721 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
722 Itm
->Uri
.c_str(),ProperHost
.c_str());
723 // only generate a cache control header if we actually want to
725 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
727 if (Itm
->IndexFile
== true)
728 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
729 _config
->FindI("Acquire::http::Max-Age",0));
732 if (_config
->FindB("Acquire::http::No-Store",false) == true)
733 strcat(Buf
,"Cache-Control: no-store\r\n");
737 // generate a no-cache header if needed
738 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
739 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
744 // Check for a partial file
746 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
748 // In this case we send an if-range query with a range header
749 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
750 TimeRFC1123(SBuf
.st_mtime
).c_str());
755 if (Itm
->LastModified
!= 0)
757 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
762 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
763 Req
+= string("Proxy-Authorization: Basic ") +
764 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
766 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
767 Req
+= string("Authorization: Basic ") +
768 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
770 Req
+= "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
778 // HttpMethod::Go - Run a single loop /*{{{*/
779 // ---------------------------------------------------------------------
780 /* This runs the select loop over the server FDs, Output file FDs and
782 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
784 // Server has closed the connection
785 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
793 /* Add the server. We only send more requests if the connection will
795 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
796 && Srv
->Persistent
== true)
797 FD_SET(Srv
->ServerFd
,&wfds
);
798 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
799 FD_SET(Srv
->ServerFd
,&rfds
);
806 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
807 FD_SET(FileFD
,&wfds
);
810 FD_SET(STDIN_FILENO
,&rfds
);
812 // Figure out the max fd
814 if (MaxFd
< Srv
->ServerFd
)
815 MaxFd
= Srv
->ServerFd
;
822 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
826 return _error
->Errno("select",_("Select failed"));
831 _error
->Error(_("Connection timed out"));
832 return ServerDie(Srv
);
836 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
839 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
840 return ServerDie(Srv
);
843 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
846 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
847 return ServerDie(Srv
);
850 // Send data to the file
851 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
853 if (Srv
->In
.Write(FileFD
) == false)
854 return _error
->Errno("write",_("Error writing to output file"));
857 // Handle commands from APT
858 if (FD_ISSET(STDIN_FILENO
,&rfds
))
867 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
868 // ---------------------------------------------------------------------
869 /* This takes the current input buffer from the Server FD and writes it
871 bool HttpMethod::Flush(ServerState
*Srv
)
875 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
877 if (File
->Name() != "/dev/null")
878 SetNonBlock(File
->Fd(),false);
879 if (Srv
->In
.WriteSpace() == false)
882 while (Srv
->In
.WriteSpace() == true)
884 if (Srv
->In
.Write(File
->Fd()) == false)
885 return _error
->Errno("write",_("Error writing to file"));
886 if (Srv
->In
.IsLimit() == true)
890 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
896 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
897 // ---------------------------------------------------------------------
899 bool HttpMethod::ServerDie(ServerState
*Srv
)
901 unsigned int LErrno
= errno
;
903 // Dump the buffer to the file
904 if (Srv
->State
== ServerState::Data
)
906 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
908 if (File
->Name() != "/dev/null")
909 SetNonBlock(File
->Fd(),false);
910 while (Srv
->In
.WriteSpace() == true)
912 if (Srv
->In
.Write(File
->Fd()) == false)
913 return _error
->Errno("write",_("Error writing to the file"));
916 if (Srv
->In
.IsLimit() == true)
921 // See if this is because the server finished the data stream
922 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
923 Srv
->Encoding
!= ServerState::Closes
)
927 return _error
->Error(_("Error reading from server. Remote end closed connection"));
929 return _error
->Errno("read",_("Error reading from server"));
935 // Nothing left in the buffer
936 if (Srv
->In
.WriteSpace() == false)
939 // We may have got multiple responses back in one packet..
947 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
948 // ---------------------------------------------------------------------
949 /* We look at the header data we got back from the server and decide what
953 3 - Unrecoverable error
954 4 - Error with error content page
955 5 - Unrecoverable non-server error (close the connection) */
956 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
959 if (Srv
->Result
== 304)
961 unlink(Queue
->DestFile
.c_str());
963 Res
.LastModified
= Queue
->LastModified
;
967 /* We have a reply we dont handle. This should indicate a perm server
969 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
971 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
972 if (Srv
->HaveContent
== true)
977 // This is some sort of 2xx 'data follows' reply
978 Res
.LastModified
= Srv
->Date
;
979 Res
.Size
= Srv
->Size
;
983 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
984 if (_error
->PendingError() == true)
987 FailFile
= Queue
->DestFile
;
988 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
990 FailTime
= Srv
->Date
;
992 // Set the expected size
993 if (Srv
->StartPos
>= 0)
995 Res
.ResumePoint
= Srv
->StartPos
;
996 ftruncate(File
->Fd(),Srv
->StartPos
);
999 // Set the start point
1000 lseek(File
->Fd(),0,SEEK_END
);
1002 delete Srv
->In
.Hash
;
1003 Srv
->In
.Hash
= new Hashes
;
1005 // Fill the Hash if the file is non-empty (resume)
1006 if (Srv
->StartPos
> 0)
1008 lseek(File
->Fd(),0,SEEK_SET
);
1009 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1011 _error
->Errno("read",_("Problem hashing file"));
1014 lseek(File
->Fd(),0,SEEK_END
);
1017 SetNonBlock(File
->Fd(),true);
1021 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1022 // ---------------------------------------------------------------------
1023 /* This closes and timestamps the open file. This is neccessary to get
1024 resume behavoir on user abort */
1025 void HttpMethod::SigTerm(int)
1032 struct utimbuf UBuf
;
1033 UBuf
.actime
= FailTime
;
1034 UBuf
.modtime
= FailTime
;
1035 utime(FailFile
.c_str(),&UBuf
);
1040 // HttpMethod::Fetch - Fetch an item /*{{{*/
1041 // ---------------------------------------------------------------------
1042 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1044 bool HttpMethod::Fetch(FetchItem
*)
1049 // Queue the requests
1052 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1053 I
= I
->Next
, Depth
++)
1055 // If pipelining is disabled, we only queue 1 request
1056 if (Server
->Pipeline
== false && Depth
>= 0)
1059 // Make sure we stick with the same server
1060 if (Server
->Comp(I
->Uri
) == false)
1066 QueueBack
= I
->Next
;
1067 SendReq(I
,Server
->Out
);
1075 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1076 // ---------------------------------------------------------------------
1077 /* We stash the desired pipeline depth */
1078 bool HttpMethod::Configuration(string Message
)
1080 if (pkgAcqMethod::Configuration(Message
) == false)
1083 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1084 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1086 Debug
= _config
->FindB("Debug::Acquire::http",false);
1091 // HttpMethod::Loop - Main loop /*{{{*/
1092 // ---------------------------------------------------------------------
1094 int HttpMethod::Loop()
1096 signal(SIGTERM
,SigTerm
);
1097 signal(SIGINT
,SigTerm
);
1101 int FailCounter
= 0;
1104 // We have no commands, wait for some to arrive
1107 if (WaitFd(STDIN_FILENO
) == false)
1111 /* Run messages, we can accept 0 (no message) if we didn't
1112 do a WaitFd above.. Otherwise the FD is closed. */
1113 int Result
= Run(true);
1114 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1120 CFStringEncoding se
= kCFStringEncodingUTF8
;
1122 char *url
= strdup(Queue
->Uri
.c_str());
1124 URI uri
= std::string(url
);
1125 std::string hs
= uri
.Host
;
1127 struct hostent
*he
= gethostbyname(hs
.c_str());
1128 if (he
== NULL
|| he
->h_addr_list
[0] == NULL
) {
1129 _error
->Error(hstrerror(h_errno
));
1134 uri
.Host
= inet_ntoa(* (struct in_addr
*) he
->h_addr_list
[0]);
1136 std::string urs
= uri
;
1138 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, urs
.c_str(), se
);
1139 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1141 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1145 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1146 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1147 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1150 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1151 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1153 } else if (Queue
->LastModified
!= 0) {
1154 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1155 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1159 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Machine_
, se
);
1160 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Machine"), sr
);
1163 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, SerialNumber_
, se
);
1164 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("X-Serial-Number"), sr
);
1167 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.98"));
1169 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, hs
.c_str(), se
);
1170 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Host"), sr
);
1173 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1176 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1177 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1180 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1181 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1187 uint8_t data
[10240];
1190 Status("Connecting to %s", hs
.c_str());
1192 if (!CFReadStreamOpen(rs
)) {
1193 CfrsError("Open", rs
);
1198 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1201 CfrsError(uri
.Host
.c_str(), rs
);
1206 Res
.Filename
= Queue
->DestFile
;
1208 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1209 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1211 if (sc
== 301 || sc
== 302) {
1212 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Location"));
1217 size_t ln
= CFStringGetLength(sr
) + 1;
1219 url
= static_cast<char *>(malloc(ln
));
1221 if (!CFStringGetCString(sr
, url
, ln
, se
)) {
1231 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1233 size_t ln
= CFStringGetLength(sr
) + 1;
1236 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1243 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1244 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1249 if (offset
> Res
.Size
) {
1250 _error
->Error(_("This HTTP server has broken range support"));
1255 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1257 Res
.Size
= CFStringGetIntValue(sr
);
1262 time(&Res
.LastModified
);
1264 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1266 size_t ln
= CFStringGetLength(sr
) + 1;
1269 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1276 if (!StrToTime(cr
, Res
.LastModified
)) {
1277 _error
->Error(_("Unknown date format"));
1286 unlink(Queue
->DestFile
.c_str());
1288 Res
.LastModified
= Queue
->LastModified
;
1290 } else if (sc
< 200 || sc
>= 300)
1295 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1296 if (_error
->PendingError() == true) {
1303 FailFile
= Queue
->DestFile
;
1304 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1305 FailFd
= File
->Fd();
1306 FailTime
= Res
.LastModified
;
1308 Res
.ResumePoint
= offset
;
1309 ftruncate(File
->Fd(), offset
);
1312 lseek(File
->Fd(), 0, SEEK_SET
);
1313 if (!hash
.AddFD(File
->Fd(), offset
)) {
1314 _error
->Errno("read", _("Problem hashing file"));
1322 lseek(File
->Fd(), 0, SEEK_END
);
1326 read
: if (rd
== -1) {
1327 CfrsError("rd", rs
);
1329 } else if (rd
== 0) {
1331 Res
.Size
= File
->Size();
1333 struct utimbuf UBuf
;
1335 UBuf
.actime
= Res
.LastModified
;
1336 UBuf
.modtime
= Res
.LastModified
;
1337 utime(Queue
->DestFile
.c_str(), &UBuf
);
1339 Res
.TakeHashes(hash
);
1346 int sz
= write(File
->Fd(), dt
, rd
);
1359 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1368 CFReadStreamClose(rs
);
1381 #if !defined(__ENVIRONMENT_ASPEN_VERSION_MIN_REQUIRED__) || __ENVIRONMENT_ASPEN_VERSION_MIN_REQUIRED__ < 10200
1383 memset(nl
, 0, sizeof(nl
));
1384 nl
[0].n_un
.n_name
= (char *) "_useMDNSResponder";
1385 nlist("/usr/lib/libc.dylib", nl
);
1386 if (nl
[0].n_type
!= N_UNDF
)
1387 *(int *) nl
[0].n_value
= 0;
1390 setlocale(LC_ALL
, "");
1395 sysctlbyname("hw.machine", NULL
, &size
, NULL
, 0);
1396 char *machine
= new char[size
];
1397 sysctlbyname("hw.machine", machine
, &size
, NULL
, 0);
1400 if (CFMutableDictionaryRef dict
= IOServiceMatching("IOPlatformExpertDevice"))
1401 if (io_service_t service
= IOServiceGetMatchingService(kIOMasterPortDefault
, dict
)) {
1402 if (CFTypeRef serial
= IORegistryEntryCreateCFProperty(service
, CFSTR(kIOPlatformSerialNumberKey
), kCFAllocatorDefault
, 0)) {
1403 SerialNumber_
= strdup(CFStringGetCStringPtr((CFStringRef
) serial
, CFStringGetSystemEncoding()));
1407 IOObjectRelease(service
);