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>
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreServices/CoreServices.h>
53 #include <SystemConfiguration/SystemConfiguration.h>
56 #include "rfc2553emu.h"
62 void CfrsError(CFReadStreamRef rs
) {
63 CFStreamError se
= CFReadStreamGetError(rs
);
65 if (se
.domain
== kCFStreamErrorDomainCustom
) {
66 } else if (se
.domain
== kCFStreamErrorDomainPOSIX
) {
67 _error
->Error("POSIX: %s", strerror(se
.error
));
68 } else if (se
.domain
== kCFStreamErrorDomainMacOSStatus
) {
69 _error
->Error("MacOSStatus: %ld", se
.error
);
70 } else if (se
.domain
== kCFStreamErrorDomainNetDB
) {
71 _error
->Error("NetDB: %s", gai_strerror(se
.error
));
72 } else if (se
.domain
== kCFStreamErrorDomainMach
) {
73 _error
->Error("Mach: %ld", se
.error
);
74 } else if (se
.domain
== kCFStreamErrorDomainHTTP
) {
76 case kCFStreamErrorHTTPParseFailure
:
77 _error
->Error("Parse failure");
80 case kCFStreamErrorHTTPRedirectionLoop
:
81 _error
->Error("Redirection loop");
84 case kCFStreamErrorHTTPBadURL
:
85 _error
->Error("Bad URL");
89 _error
->Error("Unknown HTTP error: %ld", se
.error
);
92 } else if (se
.domain
== kCFStreamErrorDomainSOCKS
) {
93 _error
->Error("SOCKS: %ld", se
.error
);
94 } else if (se
.domain
== kCFStreamErrorDomainSystemConfiguration
) {
95 _error
->Error("SystemConfiguration: %ld", se
.error
);
96 } else if (se
.domain
== kCFStreamErrorDomainSSL
) {
97 _error
->Error("SSL: %ld", se
.error
);
99 _error
->Error("Domain #%d: %ld", se
.domain
, se
.error
);
103 string
HttpMethod::FailFile
;
104 int HttpMethod::FailFd
= -1;
105 time_t HttpMethod::FailTime
= 0;
106 unsigned long PipelineDepth
= 10;
107 unsigned long TimeOut
= 120;
110 unsigned long CircleBuf::BwReadLimit
=0;
111 unsigned long CircleBuf::BwTickReadData
=0;
112 struct timeval
CircleBuf::BwReadTick
={0,0};
113 const unsigned int CircleBuf::BW_HZ
=10;
115 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
116 // ---------------------------------------------------------------------
118 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
120 Buf
= new unsigned char[Size
];
123 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
126 // CircleBuf::Reset - Reset to the default state /*{{{*/
127 // ---------------------------------------------------------------------
129 void CircleBuf::Reset()
134 MaxGet
= (unsigned int)-1;
143 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
144 // ---------------------------------------------------------------------
145 /* This fills up the buffer with as much data as is in the FD, assuming it
147 bool CircleBuf::Read(int Fd
)
149 unsigned long BwReadMax
;
153 // Woops, buffer is full
154 if (InP
- OutP
== Size
)
157 // what's left to read in this tick
158 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
160 if(CircleBuf::BwReadLimit
) {
162 gettimeofday(&now
,0);
164 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
165 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
166 if(d
> 1000000/BW_HZ
) {
167 CircleBuf::BwReadTick
= now
;
168 CircleBuf::BwTickReadData
= 0;
171 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
172 usleep(1000000/BW_HZ
);
177 // Write the buffer segment
179 if(CircleBuf::BwReadLimit
) {
180 Res
= read(Fd
,Buf
+ (InP%Size
),
181 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
183 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
185 if(Res
> 0 && BwReadLimit
> 0)
186 CircleBuf::BwTickReadData
+= Res
;
198 gettimeofday(&Start
,0);
203 // CircleBuf::Read - Put the string into the buffer /*{{{*/
204 // ---------------------------------------------------------------------
205 /* This will hold the string in and fill the buffer with it as it empties */
206 bool CircleBuf::Read(string Data
)
213 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
214 // ---------------------------------------------------------------------
216 void CircleBuf::FillOut()
218 if (OutQueue
.empty() == true)
222 // Woops, buffer is full
223 if (InP
- OutP
== Size
)
226 // Write the buffer segment
227 unsigned long Sz
= LeftRead();
228 if (OutQueue
.length() - StrPos
< Sz
)
229 Sz
= OutQueue
.length() - StrPos
;
230 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
235 if (OutQueue
.length() == StrPos
)
244 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
245 // ---------------------------------------------------------------------
246 /* This empties the buffer into the FD. */
247 bool CircleBuf::Write(int Fd
)
253 // Woops, buffer is empty
260 // Write the buffer segment
262 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
275 Hash
->Add(Buf
+ (OutP%Size
),Res
);
281 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
282 // ---------------------------------------------------------------------
283 /* This copies till the first empty line */
284 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
286 // We cheat and assume it is unneeded to have more than one buffer load
287 for (unsigned long I
= OutP
; I
< InP
; I
++)
289 if (Buf
[I%Size
] != '\n')
295 if (I
< InP
&& Buf
[I%Size
] == '\r')
297 if (I
>= InP
|| Buf
[I%Size
] != '\n')
305 unsigned long Sz
= LeftWrite();
310 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
318 // CircleBuf::Stats - Print out stats information /*{{{*/
319 // ---------------------------------------------------------------------
321 void CircleBuf::Stats()
327 gettimeofday(&Stop
,0);
328 /* float Diff = Stop.tv_sec - Start.tv_sec +
329 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
330 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
334 // ServerState::ServerState - Constructor /*{{{*/
335 // ---------------------------------------------------------------------
337 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
338 In(64*1024), Out(4*1024),
344 // ServerState::Open - Open a connection to the server /*{{{*/
345 // ---------------------------------------------------------------------
346 /* This opens a connection to the server. */
347 bool ServerState::Open()
349 // Use the already open connection if possible.
358 // Determine the proxy setting
359 if (getenv("http_proxy") == 0)
361 string DefProxy
= _config
->Find("Acquire::http::Proxy");
362 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
363 if (SpecificProxy
.empty() == false)
365 if (SpecificProxy
== "DIRECT")
368 Proxy
= SpecificProxy
;
374 Proxy
= getenv("http_proxy");
376 // Parse no_proxy, a , separated list of domains
377 if (getenv("no_proxy") != 0)
379 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
383 // Determine what host and port to use based on the proxy settings
386 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
388 if (ServerName
.Port
!= 0)
389 Port
= ServerName
.Port
;
390 Host
= ServerName
.Host
;
399 // Connect to the remote server
400 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
406 // ServerState::Close - Close a connection to the server /*{{{*/
407 // ---------------------------------------------------------------------
409 bool ServerState::Close()
416 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
417 // ---------------------------------------------------------------------
418 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
419 parse error occured */
420 int ServerState::RunHeaders()
424 Owner
->Status(_("Waiting for headers"));
438 if (In
.WriteTillEl(Data
) == false)
444 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
446 string::const_iterator J
= I
;
447 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
448 if (HeaderLine(string(I
,J
)) == false)
453 // 100 Continue is a Nop...
457 // Tidy up the connection persistance state.
458 if (Encoding
== Closes
&& HaveContent
== true)
463 while (Owner
->Go(false,this) == true);
468 // ServerState::RunData - Transfer the data from the socket /*{{{*/
469 // ---------------------------------------------------------------------
471 bool ServerState::RunData()
475 // Chunked transfer encoding is fun..
476 if (Encoding
== Chunked
)
480 // Grab the block size
486 if (In
.WriteTillEl(Data
,true) == true)
489 while ((Last
= Owner
->Go(false,this)) == true);
494 // See if we are done
495 unsigned long Len
= strtol(Data
.c_str(),0,16);
500 // We have to remove the entity trailer
504 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
507 while ((Last
= Owner
->Go(false,this)) == true);
510 return !_error
->PendingError();
513 // Transfer the block
515 while (Owner
->Go(true,this) == true)
516 if (In
.IsLimit() == true)
520 if (In
.IsLimit() == false)
523 // The server sends an extra new line before the next block specifier..
528 if (In
.WriteTillEl(Data
,true) == true)
531 while ((Last
= Owner
->Go(false,this)) == true);
538 /* Closes encoding is used when the server did not specify a size, the
539 loss of the connection means we are done */
540 if (Encoding
== Closes
)
543 In
.Limit(Size
- StartPos
);
545 // Just transfer the whole block.
548 if (In
.IsLimit() == false)
552 return !_error
->PendingError();
554 while (Owner
->Go(true,this) == true);
557 return Owner
->Flush(this) && !_error
->PendingError();
560 // ServerState::HeaderLine - Process a header line /*{{{*/
561 // ---------------------------------------------------------------------
563 bool ServerState::HeaderLine(string Line
)
565 if (Line
.empty() == true)
568 // The http server might be trying to do something evil.
569 if (Line
.length() >= MAXLEN
)
570 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
572 string::size_type Pos
= Line
.find(' ');
573 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
575 // Blah, some servers use "connection:closes", evil.
576 Pos
= Line
.find(':');
577 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
578 return _error
->Error(_("Bad header line"));
582 // Parse off any trailing spaces between the : and the next word.
583 string::size_type Pos2
= Pos
;
584 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
587 string Tag
= string(Line
,0,Pos
);
588 string Val
= string(Line
,Pos2
);
590 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
592 // Evil servers return no version
595 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
597 return _error
->Error(_("The HTTP server sent an invalid reply header"));
603 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
604 return _error
->Error(_("The HTTP server sent an invalid reply header"));
607 /* Check the HTTP response header to get the default persistance
613 if (Major
== 1 && Minor
<= 0)
622 if (stringcasecmp(Tag
,"Content-Length:") == 0)
624 if (Encoding
== Closes
)
628 // The length is already set from the Content-Range header
632 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
633 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
637 if (stringcasecmp(Tag
,"Content-Type:") == 0)
643 if (stringcasecmp(Tag
,"Content-Range:") == 0)
647 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
648 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
649 if ((unsigned)StartPos
> Size
)
650 return _error
->Error(_("This HTTP server has broken range support"));
654 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
657 if (stringcasecmp(Val
,"chunked") == 0)
662 if (stringcasecmp(Tag
,"Connection:") == 0)
664 if (stringcasecmp(Val
,"close") == 0)
666 if (stringcasecmp(Val
,"keep-alive") == 0)
671 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
673 if (StrToTime(Val
,Date
) == false)
674 return _error
->Error(_("Unknown date format"));
682 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
683 // ---------------------------------------------------------------------
684 /* This places the http request in the outbound buffer */
685 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
689 // The HTTP server expects a hostname with a trailing :port
691 string ProperHost
= Uri
.Host
;
694 sprintf(Buf
,":%u",Uri
.Port
);
699 if (Itm
->Uri
.length() >= sizeof(Buf
))
702 /* Build the request. We include a keep-alive header only for non-proxy
703 requests. This is to tweak old http/1.0 servers that do support keep-alive
704 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
705 will glitch HTTP/1.0 proxies because they do not filter it out and
706 pass it on, HTTP/1.1 says the connection should default to keep alive
707 and we expect the proxy to do this */
708 if (Proxy
.empty() == true || Proxy
.Host
.empty())
709 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
710 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
713 /* Generate a cache control header if necessary. We place a max
714 cache age on index files, optionally set a no-cache directive
715 and a no-store directive for archives. */
716 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
717 Itm
->Uri
.c_str(),ProperHost
.c_str());
718 // only generate a cache control header if we actually want to
720 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
722 if (Itm
->IndexFile
== true)
723 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
724 _config
->FindI("Acquire::http::Max-Age",0));
727 if (_config
->FindB("Acquire::http::No-Store",false) == true)
728 strcat(Buf
,"Cache-Control: no-store\r\n");
732 // generate a no-cache header if needed
733 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
734 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
739 // Check for a partial file
741 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
743 // In this case we send an if-range query with a range header
744 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
745 TimeRFC1123(SBuf
.st_mtime
).c_str());
750 if (Itm
->LastModified
!= 0)
752 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
757 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
758 Req
+= string("Proxy-Authorization: Basic ") +
759 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
761 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
762 Req
+= string("Authorization: Basic ") +
763 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
765 Req
+= "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
773 // HttpMethod::Go - Run a single loop /*{{{*/
774 // ---------------------------------------------------------------------
775 /* This runs the select loop over the server FDs, Output file FDs and
777 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
779 // Server has closed the connection
780 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
788 /* Add the server. We only send more requests if the connection will
790 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
791 && Srv
->Persistent
== true)
792 FD_SET(Srv
->ServerFd
,&wfds
);
793 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
794 FD_SET(Srv
->ServerFd
,&rfds
);
801 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
802 FD_SET(FileFD
,&wfds
);
805 FD_SET(STDIN_FILENO
,&rfds
);
807 // Figure out the max fd
809 if (MaxFd
< Srv
->ServerFd
)
810 MaxFd
= Srv
->ServerFd
;
817 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
821 return _error
->Errno("select",_("Select failed"));
826 _error
->Error(_("Connection timed out"));
827 return ServerDie(Srv
);
831 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
834 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
835 return ServerDie(Srv
);
838 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
841 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
842 return ServerDie(Srv
);
845 // Send data to the file
846 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
848 if (Srv
->In
.Write(FileFD
) == false)
849 return _error
->Errno("write",_("Error writing to output file"));
852 // Handle commands from APT
853 if (FD_ISSET(STDIN_FILENO
,&rfds
))
862 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
863 // ---------------------------------------------------------------------
864 /* This takes the current input buffer from the Server FD and writes it
866 bool HttpMethod::Flush(ServerState
*Srv
)
870 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
872 if (File
->Name() != "/dev/null")
873 SetNonBlock(File
->Fd(),false);
874 if (Srv
->In
.WriteSpace() == false)
877 while (Srv
->In
.WriteSpace() == true)
879 if (Srv
->In
.Write(File
->Fd()) == false)
880 return _error
->Errno("write",_("Error writing to file"));
881 if (Srv
->In
.IsLimit() == true)
885 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
891 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
892 // ---------------------------------------------------------------------
894 bool HttpMethod::ServerDie(ServerState
*Srv
)
896 unsigned int LErrno
= errno
;
898 // Dump the buffer to the file
899 if (Srv
->State
== ServerState::Data
)
901 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
903 if (File
->Name() != "/dev/null")
904 SetNonBlock(File
->Fd(),false);
905 while (Srv
->In
.WriteSpace() == true)
907 if (Srv
->In
.Write(File
->Fd()) == false)
908 return _error
->Errno("write",_("Error writing to the file"));
911 if (Srv
->In
.IsLimit() == true)
916 // See if this is because the server finished the data stream
917 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
918 Srv
->Encoding
!= ServerState::Closes
)
922 return _error
->Error(_("Error reading from server. Remote end closed connection"));
924 return _error
->Errno("read",_("Error reading from server"));
930 // Nothing left in the buffer
931 if (Srv
->In
.WriteSpace() == false)
934 // We may have got multiple responses back in one packet..
942 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
943 // ---------------------------------------------------------------------
944 /* We look at the header data we got back from the server and decide what
948 3 - Unrecoverable error
949 4 - Error with error content page
950 5 - Unrecoverable non-server error (close the connection) */
951 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
954 if (Srv
->Result
== 304)
956 unlink(Queue
->DestFile
.c_str());
958 Res
.LastModified
= Queue
->LastModified
;
962 /* We have a reply we dont handle. This should indicate a perm server
964 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
966 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
967 if (Srv
->HaveContent
== true)
972 // This is some sort of 2xx 'data follows' reply
973 Res
.LastModified
= Srv
->Date
;
974 Res
.Size
= Srv
->Size
;
978 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
979 if (_error
->PendingError() == true)
982 FailFile
= Queue
->DestFile
;
983 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
985 FailTime
= Srv
->Date
;
987 // Set the expected size
988 if (Srv
->StartPos
>= 0)
990 Res
.ResumePoint
= Srv
->StartPos
;
991 ftruncate(File
->Fd(),Srv
->StartPos
);
994 // Set the start point
995 lseek(File
->Fd(),0,SEEK_END
);
998 Srv
->In
.Hash
= new Hashes
;
1000 // Fill the Hash if the file is non-empty (resume)
1001 if (Srv
->StartPos
> 0)
1003 lseek(File
->Fd(),0,SEEK_SET
);
1004 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
1006 _error
->Errno("read",_("Problem hashing file"));
1009 lseek(File
->Fd(),0,SEEK_END
);
1012 SetNonBlock(File
->Fd(),true);
1016 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1017 // ---------------------------------------------------------------------
1018 /* This closes and timestamps the open file. This is neccessary to get
1019 resume behavoir on user abort */
1020 void HttpMethod::SigTerm(int)
1027 struct utimbuf UBuf
;
1028 UBuf
.actime
= FailTime
;
1029 UBuf
.modtime
= FailTime
;
1030 utime(FailFile
.c_str(),&UBuf
);
1035 // HttpMethod::Fetch - Fetch an item /*{{{*/
1036 // ---------------------------------------------------------------------
1037 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1039 bool HttpMethod::Fetch(FetchItem
*)
1044 // Queue the requests
1047 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1048 I
= I
->Next
, Depth
++)
1050 // If pipelining is disabled, we only queue 1 request
1051 if (Server
->Pipeline
== false && Depth
>= 0)
1054 // Make sure we stick with the same server
1055 if (Server
->Comp(I
->Uri
) == false)
1061 QueueBack
= I
->Next
;
1062 SendReq(I
,Server
->Out
);
1070 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1071 // ---------------------------------------------------------------------
1072 /* We stash the desired pipeline depth */
1073 bool HttpMethod::Configuration(string Message
)
1075 if (pkgAcqMethod::Configuration(Message
) == false)
1078 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1079 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1081 Debug
= _config
->FindB("Debug::Acquire::http",false);
1086 // HttpMethod::Loop - Main loop /*{{{*/
1087 // ---------------------------------------------------------------------
1089 int HttpMethod::Loop()
1091 signal(SIGTERM
,SigTerm
);
1092 signal(SIGINT
,SigTerm
);
1096 int FailCounter
= 0;
1099 // We have no commands, wait for some to arrive
1102 if (WaitFd(STDIN_FILENO
) == false)
1106 /* Run messages, we can accept 0 (no message) if we didn't
1107 do a WaitFd above.. Otherwise the FD is closed. */
1108 int Result
= Run(true);
1109 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1115 CFStringEncoding se
= kCFStringEncodingUTF8
;
1117 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Queue
->Uri
.c_str(), se
);
1118 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1120 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1124 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1125 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1126 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1129 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1130 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1132 } else if (Queue
->LastModified
!= 0) {
1133 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1134 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1138 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.98"));
1139 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1142 CFDictionaryRef dr
= SCDynamicStoreCopyProxies(NULL
);
1143 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPProxy
, dr
);
1146 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPShouldAutoredirect
, kCFBooleanTrue
);
1147 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1149 URI uri
= Queue
->Uri
;
1153 uint8_t data
[10240];
1156 Status("Connecting to %s", uri
.Host
.c_str());
1158 if (!CFReadStreamOpen(rs
)) {
1164 CFIndex rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1172 Res
.Filename
= Queue
->DestFile
;
1174 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1175 UInt32 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1177 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1179 size_t ln
= CFStringGetLength(sr
) + 1;
1182 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1189 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1190 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1195 if (offset
> Res
.Size
) {
1196 _error
->Error(_("This HTTP server has broken range support"));
1201 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1203 Res
.Size
= CFStringGetIntValue(sr
);
1208 time(&Res
.LastModified
);
1210 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1212 size_t ln
= CFStringGetLength(sr
) + 1;
1215 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1222 if (!StrToTime(cr
, Res
.LastModified
)) {
1223 _error
->Error(_("Unknown date format"));
1232 unlink(Queue
->DestFile
.c_str());
1234 Res
.LastModified
= Queue
->LastModified
;
1236 } else if (sc
< 200 || sc
>= 300)
1241 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1242 if (_error
->PendingError() == true) {
1249 FailFile
= Queue
->DestFile
;
1250 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1251 FailFd
= File
->Fd();
1252 FailTime
= Res
.LastModified
;
1254 Res
.ResumePoint
= offset
;
1255 ftruncate(File
->Fd(), offset
);
1258 lseek(File
->Fd(), 0, SEEK_SET
);
1259 if (!hash
.AddFD(File
->Fd(), offset
)) {
1260 _error
->Errno("read", _("Problem hashing file"));
1268 lseek(File
->Fd(), 0, SEEK_END
);
1272 read
: if (rd
== -1) {
1275 } else if (rd
== 0) {
1277 Res
.Size
= File
->Size();
1279 struct utimbuf UBuf
;
1281 UBuf
.actime
= Res
.LastModified
;
1282 UBuf
.modtime
= Res
.LastModified
;
1283 utime(Queue
->DestFile
.c_str(), &UBuf
);
1285 Res
.TakeHashes(hash
);
1292 int sz
= write(File
->Fd(), dt
, rd
);
1305 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1314 CFReadStreamClose(rs
);
1327 memset(nl
, 0, sizeof(nl
));
1328 nl
[0].n_un
.n_name
= (char *) "_useMDNSResponder";
1329 nlist("/usr/lib/libc.dylib", nl
);
1330 if (nl
[0].n_type
!= N_UNDF
)
1331 *(int *) nl
[0].n_value
= 0;
1333 setlocale(LC_ALL
, "");