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>
55 #include "rfc2553emu.h"
61 string
HttpMethod::FailFile
;
62 int HttpMethod::FailFd
= -1;
63 time_t HttpMethod::FailTime
= 0;
64 unsigned long PipelineDepth
= 10;
65 unsigned long TimeOut
= 120;
68 unsigned long CircleBuf::BwReadLimit
=0;
69 unsigned long CircleBuf::BwTickReadData
=0;
70 struct timeval
CircleBuf::BwReadTick
={0,0};
71 const unsigned int CircleBuf::BW_HZ
=10;
73 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
74 // ---------------------------------------------------------------------
76 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
78 Buf
= new unsigned char[Size
];
81 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
84 // CircleBuf::Reset - Reset to the default state /*{{{*/
85 // ---------------------------------------------------------------------
87 void CircleBuf::Reset()
92 MaxGet
= (unsigned int)-1;
101 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
102 // ---------------------------------------------------------------------
103 /* This fills up the buffer with as much data as is in the FD, assuming it
105 bool CircleBuf::Read(int Fd
)
107 unsigned long BwReadMax
;
111 // Woops, buffer is full
112 if (InP
- OutP
== Size
)
115 // what's left to read in this tick
116 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
118 if(CircleBuf::BwReadLimit
) {
120 gettimeofday(&now
,0);
122 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
123 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
124 if(d
> 1000000/BW_HZ
) {
125 CircleBuf::BwReadTick
= now
;
126 CircleBuf::BwTickReadData
= 0;
129 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
130 usleep(1000000/BW_HZ
);
135 // Write the buffer segment
137 if(CircleBuf::BwReadLimit
) {
138 Res
= read(Fd
,Buf
+ (InP%Size
),
139 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
141 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
143 if(Res
> 0 && BwReadLimit
> 0)
144 CircleBuf::BwTickReadData
+= Res
;
156 gettimeofday(&Start
,0);
161 // CircleBuf::Read - Put the string into the buffer /*{{{*/
162 // ---------------------------------------------------------------------
163 /* This will hold the string in and fill the buffer with it as it empties */
164 bool CircleBuf::Read(string Data
)
171 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
172 // ---------------------------------------------------------------------
174 void CircleBuf::FillOut()
176 if (OutQueue
.empty() == true)
180 // Woops, buffer is full
181 if (InP
- OutP
== Size
)
184 // Write the buffer segment
185 unsigned long Sz
= LeftRead();
186 if (OutQueue
.length() - StrPos
< Sz
)
187 Sz
= OutQueue
.length() - StrPos
;
188 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
193 if (OutQueue
.length() == StrPos
)
202 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
203 // ---------------------------------------------------------------------
204 /* This empties the buffer into the FD. */
205 bool CircleBuf::Write(int Fd
)
211 // Woops, buffer is empty
218 // Write the buffer segment
220 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
233 Hash
->Add(Buf
+ (OutP%Size
),Res
);
239 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
240 // ---------------------------------------------------------------------
241 /* This copies till the first empty line */
242 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
244 // We cheat and assume it is unneeded to have more than one buffer load
245 for (unsigned long I
= OutP
; I
< InP
; I
++)
247 if (Buf
[I%Size
] != '\n')
253 if (I
< InP
&& Buf
[I%Size
] == '\r')
255 if (I
>= InP
|| Buf
[I%Size
] != '\n')
263 unsigned long Sz
= LeftWrite();
268 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
276 // CircleBuf::Stats - Print out stats information /*{{{*/
277 // ---------------------------------------------------------------------
279 void CircleBuf::Stats()
285 gettimeofday(&Stop
,0);
286 /* float Diff = Stop.tv_sec - Start.tv_sec +
287 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
288 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
292 // ServerState::ServerState - Constructor /*{{{*/
293 // ---------------------------------------------------------------------
295 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
296 In(64*1024), Out(4*1024),
302 // ServerState::Open - Open a connection to the server /*{{{*/
303 // ---------------------------------------------------------------------
304 /* This opens a connection to the server. */
305 bool ServerState::Open()
307 // Use the already open connection if possible.
316 // Determine the proxy setting
317 if (getenv("http_proxy") == 0)
319 string DefProxy
= _config
->Find("Acquire::http::Proxy");
320 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
321 if (SpecificProxy
.empty() == false)
323 if (SpecificProxy
== "DIRECT")
326 Proxy
= SpecificProxy
;
332 Proxy
= getenv("http_proxy");
334 // Parse no_proxy, a , separated list of domains
335 if (getenv("no_proxy") != 0)
337 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
341 // Determine what host and port to use based on the proxy settings
344 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
346 if (ServerName
.Port
!= 0)
347 Port
= ServerName
.Port
;
348 Host
= ServerName
.Host
;
357 // Connect to the remote server
358 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
364 // ServerState::Close - Close a connection to the server /*{{{*/
365 // ---------------------------------------------------------------------
367 bool ServerState::Close()
374 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
375 // ---------------------------------------------------------------------
376 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
377 parse error occured */
378 int ServerState::RunHeaders()
382 Owner
->Status(_("Waiting for headers"));
396 if (In
.WriteTillEl(Data
) == false)
402 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
404 string::const_iterator J
= I
;
405 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
406 if (HeaderLine(string(I
,J
)) == false)
411 // 100 Continue is a Nop...
415 // Tidy up the connection persistance state.
416 if (Encoding
== Closes
&& HaveContent
== true)
421 while (Owner
->Go(false,this) == true);
426 // ServerState::RunData - Transfer the data from the socket /*{{{*/
427 // ---------------------------------------------------------------------
429 bool ServerState::RunData()
433 // Chunked transfer encoding is fun..
434 if (Encoding
== Chunked
)
438 // Grab the block size
444 if (In
.WriteTillEl(Data
,true) == true)
447 while ((Last
= Owner
->Go(false,this)) == true);
452 // See if we are done
453 unsigned long Len
= strtol(Data
.c_str(),0,16);
458 // We have to remove the entity trailer
462 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
465 while ((Last
= Owner
->Go(false,this)) == true);
468 return !_error
->PendingError();
471 // Transfer the block
473 while (Owner
->Go(true,this) == true)
474 if (In
.IsLimit() == true)
478 if (In
.IsLimit() == false)
481 // The server sends an extra new line before the next block specifier..
486 if (In
.WriteTillEl(Data
,true) == true)
489 while ((Last
= Owner
->Go(false,this)) == true);
496 /* Closes encoding is used when the server did not specify a size, the
497 loss of the connection means we are done */
498 if (Encoding
== Closes
)
501 In
.Limit(Size
- StartPos
);
503 // Just transfer the whole block.
506 if (In
.IsLimit() == false)
510 return !_error
->PendingError();
512 while (Owner
->Go(true,this) == true);
515 return Owner
->Flush(this) && !_error
->PendingError();
518 // ServerState::HeaderLine - Process a header line /*{{{*/
519 // ---------------------------------------------------------------------
521 bool ServerState::HeaderLine(string Line
)
523 if (Line
.empty() == true)
526 // The http server might be trying to do something evil.
527 if (Line
.length() >= MAXLEN
)
528 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
530 string::size_type Pos
= Line
.find(' ');
531 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
533 // Blah, some servers use "connection:closes", evil.
534 Pos
= Line
.find(':');
535 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
536 return _error
->Error(_("Bad header line"));
540 // Parse off any trailing spaces between the : and the next word.
541 string::size_type Pos2
= Pos
;
542 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
545 string Tag
= string(Line
,0,Pos
);
546 string Val
= string(Line
,Pos2
);
548 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
550 // Evil servers return no version
553 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
555 return _error
->Error(_("The HTTP server sent an invalid reply header"));
561 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
562 return _error
->Error(_("The HTTP server sent an invalid reply header"));
565 /* Check the HTTP response header to get the default persistance
571 if (Major
== 1 && Minor
<= 0)
580 if (stringcasecmp(Tag
,"Content-Length:") == 0)
582 if (Encoding
== Closes
)
586 // The length is already set from the Content-Range header
590 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
591 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
595 if (stringcasecmp(Tag
,"Content-Type:") == 0)
601 if (stringcasecmp(Tag
,"Content-Range:") == 0)
605 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
606 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
607 if ((unsigned)StartPos
> Size
)
608 return _error
->Error(_("This HTTP server has broken range support"));
612 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
615 if (stringcasecmp(Val
,"chunked") == 0)
620 if (stringcasecmp(Tag
,"Connection:") == 0)
622 if (stringcasecmp(Val
,"close") == 0)
624 if (stringcasecmp(Val
,"keep-alive") == 0)
629 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
631 if (StrToTime(Val
,Date
) == false)
632 return _error
->Error(_("Unknown date format"));
640 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
641 // ---------------------------------------------------------------------
642 /* This places the http request in the outbound buffer */
643 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
647 // The HTTP server expects a hostname with a trailing :port
649 string ProperHost
= Uri
.Host
;
652 sprintf(Buf
,":%u",Uri
.Port
);
657 if (Itm
->Uri
.length() >= sizeof(Buf
))
660 /* Build the request. We include a keep-alive header only for non-proxy
661 requests. This is to tweak old http/1.0 servers that do support keep-alive
662 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
663 will glitch HTTP/1.0 proxies because they do not filter it out and
664 pass it on, HTTP/1.1 says the connection should default to keep alive
665 and we expect the proxy to do this */
666 if (Proxy
.empty() == true || Proxy
.Host
.empty())
667 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
668 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
671 /* Generate a cache control header if necessary. We place a max
672 cache age on index files, optionally set a no-cache directive
673 and a no-store directive for archives. */
674 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
675 Itm
->Uri
.c_str(),ProperHost
.c_str());
676 // only generate a cache control header if we actually want to
678 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
680 if (Itm
->IndexFile
== true)
681 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
682 _config
->FindI("Acquire::http::Max-Age",0));
685 if (_config
->FindB("Acquire::http::No-Store",false) == true)
686 strcat(Buf
,"Cache-Control: no-store\r\n");
690 // generate a no-cache header if needed
691 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
692 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
697 // Check for a partial file
699 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
701 // In this case we send an if-range query with a range header
702 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
703 TimeRFC1123(SBuf
.st_mtime
).c_str());
708 if (Itm
->LastModified
!= 0)
710 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
715 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
716 Req
+= string("Proxy-Authorization: Basic ") +
717 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
719 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
720 Req
+= string("Authorization: Basic ") +
721 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
723 Req
+= "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
731 // HttpMethod::Go - Run a single loop /*{{{*/
732 // ---------------------------------------------------------------------
733 /* This runs the select loop over the server FDs, Output file FDs and
735 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
737 // Server has closed the connection
738 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
746 /* Add the server. We only send more requests if the connection will
748 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
749 && Srv
->Persistent
== true)
750 FD_SET(Srv
->ServerFd
,&wfds
);
751 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
752 FD_SET(Srv
->ServerFd
,&rfds
);
759 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
760 FD_SET(FileFD
,&wfds
);
763 FD_SET(STDIN_FILENO
,&rfds
);
765 // Figure out the max fd
767 if (MaxFd
< Srv
->ServerFd
)
768 MaxFd
= Srv
->ServerFd
;
775 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
779 return _error
->Errno("select",_("Select failed"));
784 _error
->Error(_("Connection timed out"));
785 return ServerDie(Srv
);
789 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
792 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
793 return ServerDie(Srv
);
796 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
799 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
800 return ServerDie(Srv
);
803 // Send data to the file
804 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
806 if (Srv
->In
.Write(FileFD
) == false)
807 return _error
->Errno("write",_("Error writing to output file"));
810 // Handle commands from APT
811 if (FD_ISSET(STDIN_FILENO
,&rfds
))
820 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
821 // ---------------------------------------------------------------------
822 /* This takes the current input buffer from the Server FD and writes it
824 bool HttpMethod::Flush(ServerState
*Srv
)
828 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
830 if (File
->Name() != "/dev/null")
831 SetNonBlock(File
->Fd(),false);
832 if (Srv
->In
.WriteSpace() == false)
835 while (Srv
->In
.WriteSpace() == true)
837 if (Srv
->In
.Write(File
->Fd()) == false)
838 return _error
->Errno("write",_("Error writing to file"));
839 if (Srv
->In
.IsLimit() == true)
843 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
849 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
850 // ---------------------------------------------------------------------
852 bool HttpMethod::ServerDie(ServerState
*Srv
)
854 unsigned int LErrno
= errno
;
856 // Dump the buffer to the file
857 if (Srv
->State
== ServerState::Data
)
859 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
861 if (File
->Name() != "/dev/null")
862 SetNonBlock(File
->Fd(),false);
863 while (Srv
->In
.WriteSpace() == true)
865 if (Srv
->In
.Write(File
->Fd()) == false)
866 return _error
->Errno("write",_("Error writing to the file"));
869 if (Srv
->In
.IsLimit() == true)
874 // See if this is because the server finished the data stream
875 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
876 Srv
->Encoding
!= ServerState::Closes
)
880 return _error
->Error(_("Error reading from server. Remote end closed connection"));
882 return _error
->Errno("read",_("Error reading from server"));
888 // Nothing left in the buffer
889 if (Srv
->In
.WriteSpace() == false)
892 // We may have got multiple responses back in one packet..
900 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
901 // ---------------------------------------------------------------------
902 /* We look at the header data we got back from the server and decide what
906 3 - Unrecoverable error
907 4 - Error with error content page
908 5 - Unrecoverable non-server error (close the connection) */
909 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
912 if (Srv
->Result
== 304)
914 unlink(Queue
->DestFile
.c_str());
916 Res
.LastModified
= Queue
->LastModified
;
920 /* We have a reply we dont handle. This should indicate a perm server
922 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
924 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
925 if (Srv
->HaveContent
== true)
930 // This is some sort of 2xx 'data follows' reply
931 Res
.LastModified
= Srv
->Date
;
932 Res
.Size
= Srv
->Size
;
936 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
937 if (_error
->PendingError() == true)
940 FailFile
= Queue
->DestFile
;
941 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
943 FailTime
= Srv
->Date
;
945 // Set the expected size
946 if (Srv
->StartPos
>= 0)
948 Res
.ResumePoint
= Srv
->StartPos
;
949 ftruncate(File
->Fd(),Srv
->StartPos
);
952 // Set the start point
953 lseek(File
->Fd(),0,SEEK_END
);
956 Srv
->In
.Hash
= new Hashes
;
958 // Fill the Hash if the file is non-empty (resume)
959 if (Srv
->StartPos
> 0)
961 lseek(File
->Fd(),0,SEEK_SET
);
962 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
964 _error
->Errno("read",_("Problem hashing file"));
967 lseek(File
->Fd(),0,SEEK_END
);
970 SetNonBlock(File
->Fd(),true);
974 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
975 // ---------------------------------------------------------------------
976 /* This closes and timestamps the open file. This is neccessary to get
977 resume behavoir on user abort */
978 void HttpMethod::SigTerm(int)
986 UBuf
.actime
= FailTime
;
987 UBuf
.modtime
= FailTime
;
988 utime(FailFile
.c_str(),&UBuf
);
993 // HttpMethod::Fetch - Fetch an item /*{{{*/
994 // ---------------------------------------------------------------------
995 /* This adds an item to the pipeline. We keep the pipeline at a fixed
997 bool HttpMethod::Fetch(FetchItem
*)
1002 // Queue the requests
1005 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1006 I
= I
->Next
, Depth
++)
1008 // If pipelining is disabled, we only queue 1 request
1009 if (Server
->Pipeline
== false && Depth
>= 0)
1012 // Make sure we stick with the same server
1013 if (Server
->Comp(I
->Uri
) == false)
1019 QueueBack
= I
->Next
;
1020 SendReq(I
,Server
->Out
);
1028 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1029 // ---------------------------------------------------------------------
1030 /* We stash the desired pipeline depth */
1031 bool HttpMethod::Configuration(string Message
)
1033 if (pkgAcqMethod::Configuration(Message
) == false)
1036 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1037 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1039 Debug
= _config
->FindB("Debug::Acquire::http",false);
1044 // HttpMethod::Loop - Main loop /*{{{*/
1045 // ---------------------------------------------------------------------
1047 int HttpMethod::Loop()
1049 signal(SIGTERM
,SigTerm
);
1050 signal(SIGINT
,SigTerm
);
1054 int FailCounter
= 0;
1057 // We have no commands, wait for some to arrive
1060 if (WaitFd(STDIN_FILENO
) == false)
1064 /* Run messages, we can accept 0 (no message) if we didn't
1065 do a WaitFd above.. Otherwise the FD is closed. */
1066 int Result
= Run(true);
1067 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1073 CFStringEncoding se
= kCFStringEncodingUTF8
;
1075 CFStringRef sr
= CFStringCreateWithCString(kCFAllocatorDefault
, Queue
->Uri
.c_str(), se
);
1076 CFURLRef ur
= CFURLCreateWithString(kCFAllocatorDefault
, sr
, NULL
);
1078 CFHTTPMessageRef hm
= CFHTTPMessageCreateRequest(kCFAllocatorDefault
, CFSTR("GET"), ur
, kCFHTTPVersion1_1
);
1082 if (stat(Queue
->DestFile
.c_str(), &SBuf
) >= 0 && SBuf
.st_size
> 0) {
1083 sr
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("bytes=%li-"), (long) SBuf
.st_size
- 1);
1084 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("Range"), sr
);
1087 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1088 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Range"), sr
);
1090 } else if (Queue
->LastModified
!= 0) {
1091 sr
= CFStringCreateWithCString(kCFAllocatorDefault
, TimeRFC1123(SBuf
.st_mtime
).c_str(), se
);
1092 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("If-Modified-Since"), sr
);
1096 CFHTTPMessageSetHeaderFieldValue(hm
, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.98"));
1097 CFReadStreamRef rs
= CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault
, hm
);
1100 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPShouldAutoredirect
, kCFBooleanTrue
);
1101 CFReadStreamSetProperty(rs
, kCFStreamPropertyHTTPAttemptPersistentConnection
, kCFBooleanTrue
);
1103 URI uri
= Queue
->Uri
;
1107 uint8_t data
[10240];
1110 Status("Connecting to %s", uri
.Host
.c_str());
1112 if (!CFReadStreamOpen(rs
)) {
1113 _error
->Error("Unable to open stream");
1118 CFIndex rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1121 _error
->Error("Stream read failure");
1126 Res
.Filename
= Queue
->DestFile
;
1128 hm
= (CFHTTPMessageRef
) CFReadStreamCopyProperty(rs
, kCFStreamPropertyHTTPResponseHeader
);
1129 UInt32 sc
= CFHTTPMessageGetResponseStatusCode(hm
);
1131 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Range"));
1133 size_t ln
= CFStringGetLength(sr
) + 1;
1136 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1143 if (sscanf(cr
, "bytes %lu-%*u/%lu", &offset
, &Res
.Size
) != 2) {
1144 _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
1149 if (offset
> Res
.Size
) {
1150 _error
->Error(_("This HTTP server has broken range support"));
1155 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Content-Length"));
1157 Res
.Size
= CFStringGetIntValue(sr
);
1162 time(&Res
.LastModified
);
1164 sr
= CFHTTPMessageCopyHeaderFieldValue(hm
, CFSTR("Last-Modified"));
1166 size_t ln
= CFStringGetLength(sr
) + 1;
1169 if (!CFStringGetCString(sr
, cr
, ln
, se
)) {
1176 if (!StrToTime(cr
, Res
.LastModified
)) {
1177 _error
->Error(_("Unknown date format"));
1186 unlink(Queue
->DestFile
.c_str());
1188 Res
.LastModified
= Queue
->LastModified
;
1190 } else if (sc
< 200 || sc
>= 300)
1195 File
= new FileFd(Queue
->DestFile
, FileFd::WriteAny
);
1196 if (_error
->PendingError() == true) {
1203 FailFile
= Queue
->DestFile
;
1204 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
1205 FailFd
= File
->Fd();
1206 FailTime
= Res
.LastModified
;
1208 Res
.ResumePoint
= offset
;
1209 ftruncate(File
->Fd(), offset
);
1212 lseek(File
->Fd(), 0, SEEK_SET
);
1213 if (!hash
.AddFD(File
->Fd(), offset
)) {
1214 _error
->Errno("read", _("Problem hashing file"));
1222 lseek(File
->Fd(), 0, SEEK_END
);
1226 read
: if (rd
== -1) {
1227 _error
->Error("Stream read failure");
1229 } else if (rd
== 0) {
1231 Res
.Size
= File
->Size();
1233 struct utimbuf UBuf
;
1235 UBuf
.actime
= Res
.LastModified
;
1236 UBuf
.modtime
= Res
.LastModified
;
1237 utime(Queue
->DestFile
.c_str(), &UBuf
);
1239 Res
.TakeHashes(hash
);
1246 int sz
= write(File
->Fd(), dt
, rd
);
1259 rd
= CFReadStreamRead(rs
, data
, sizeof(data
));
1277 memset(nl
, 0, sizeof(nl
));
1278 nl
[0].n_un
.n_name
= "_useMDNSResponder";
1279 nlist("/usr/lib/libc.dylib", nl
);
1280 if (nl
[0].n_type
!= N_UNDF
)
1281 *(int *) nl
[0].n_value
= 0;
1283 setlocale(LC_ALL
, "");