1 // -*- mode: cpp; mode: fold -*-
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
6 HTTP Aquire Method - This is the HTTP aquire method for APT.
8 It uses HTTP/1.1 and many of the fancy options there-in, such as
9 pipelining, range, if-range and so on.
11 It is based on a doubly buffered select loop. A groupe of requests are
12 fed into a single output buffer that is constantly fed out the
13 socket. This provides ideal pipelining as in many cases all of the
14 requests will fit into a single packet. The input socket is buffered
15 the same way and fed into the fd for the file (may be a pipe in future).
17 This double buffering provides fairly substantial transfer rates,
18 compared to wget the http method is about 4% faster. Most importantly,
19 when HTTP is compared with FTP as a protocol the speed difference is
20 huge. In tests over the internet from two sites to llug (via ATM) this
21 program got 230k/s sustained http transfer rates. FTP on the other
22 hand topped out at 170k/s. That combined with the time to setup the
23 FTP connection makes HTTP a vastly superior protocol.
25 ##################################################################### */
27 // Include Files /*{{{*/
28 #include <apt-pkg/fileutl.h>
29 #include <apt-pkg/acquire-method.h>
30 #include <apt-pkg/error.h>
31 #include <apt-pkg/hashes.h>
33 #include <sys/sysctl.h>
47 #include <arpa/inet.h>
49 #include <CoreFoundation/CoreFoundation.h>
50 #include <CoreServices/CoreServices.h>
51 #include <SystemConfiguration/SystemConfiguration.h>
54 #include "rfc2553emu.h"
60 CFStringRef Firmware_;
62 const char *SerialNumber_;
64 void CfrsError(const char *name, CFReadStreamRef rs) {
65 CFStreamError se = CFReadStreamGetError(rs);
67 if (se.domain == kCFStreamErrorDomainCustom) {
68 } else if (se.domain == kCFStreamErrorDomainPOSIX) {
69 _error->Error("POSIX: %s", strerror(se.error));
70 } else if (se.domain == kCFStreamErrorDomainMacOSStatus) {
71 _error->Error("MacOSStatus: %ld", se.error);
72 } else if (se.domain == kCFStreamErrorDomainNetDB) {
73 _error->Error("NetDB: %s %s", name, gai_strerror(se.error));
74 } else if (se.domain == kCFStreamErrorDomainMach) {
75 _error->Error("Mach: %ld", se.error);
76 } else if (se.domain == kCFStreamErrorDomainHTTP) {
78 case kCFStreamErrorHTTPParseFailure:
79 _error->Error("Parse failure");
82 case kCFStreamErrorHTTPRedirectionLoop:
83 _error->Error("Redirection loop");
86 case kCFStreamErrorHTTPBadURL:
87 _error->Error("Bad URL");
91 _error->Error("Unknown HTTP error: %ld", se.error);
94 } else if (se.domain == kCFStreamErrorDomainSOCKS) {
95 _error->Error("SOCKS: %ld", se.error);
96 } else if (se.domain == kCFStreamErrorDomainSystemConfiguration) {
97 _error->Error("SystemConfiguration: %ld", se.error);
98 } else if (se.domain == kCFStreamErrorDomainSSL) {
99 _error->Error("SSL: %ld", se.error);
101 _error->Error("Domain #%ld: %ld", se.domain, se.error);
105 string HttpMethod::FailFile;
106 int HttpMethod::FailFd = -1;
107 time_t HttpMethod::FailTime = 0;
108 unsigned long PipelineDepth = 10;
109 unsigned long TimeOut = 120;
112 unsigned long CircleBuf::BwReadLimit=0;
113 unsigned long CircleBuf::BwTickReadData=0;
114 struct timeval CircleBuf::BwReadTick={0,0};
115 const unsigned int CircleBuf::BW_HZ=10;
117 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
118 // ---------------------------------------------------------------------
120 CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
122 Buf = new unsigned char[Size];
125 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
128 // CircleBuf::Reset - Reset to the default state /*{{{*/
129 // ---------------------------------------------------------------------
131 void CircleBuf::Reset()
136 MaxGet = (unsigned int)-1;
145 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
146 // ---------------------------------------------------------------------
147 /* This fills up the buffer with as much data as is in the FD, assuming it
149 bool CircleBuf::Read(int Fd)
151 unsigned long BwReadMax;
155 // Woops, buffer is full
156 if (InP - OutP == Size)
159 // what's left to read in this tick
160 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
162 if(CircleBuf::BwReadLimit) {
164 gettimeofday(&now,0);
166 unsigned long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
167 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
168 if(d > 1000000/BW_HZ) {
169 CircleBuf::BwReadTick = now;
170 CircleBuf::BwTickReadData = 0;
173 if(CircleBuf::BwTickReadData >= BwReadMax) {
174 usleep(1000000/BW_HZ);
179 // Write the buffer segment
181 if(CircleBuf::BwReadLimit) {
182 Res = read(Fd,Buf + (InP%Size),
183 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
185 Res = read(Fd,Buf + (InP%Size),LeftRead());
187 if(Res > 0 && BwReadLimit > 0)
188 CircleBuf::BwTickReadData += Res;
200 gettimeofday(&Start,0);
205 // CircleBuf::Read - Put the string into the buffer /*{{{*/
206 // ---------------------------------------------------------------------
207 /* This will hold the string in and fill the buffer with it as it empties */
208 bool CircleBuf::Read(string Data)
215 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
216 // ---------------------------------------------------------------------
218 void CircleBuf::FillOut()
220 if (OutQueue.empty() == true)
224 // Woops, buffer is full
225 if (InP - OutP == Size)
228 // Write the buffer segment
229 unsigned long Sz = LeftRead();
230 if (OutQueue.length() - StrPos < Sz)
231 Sz = OutQueue.length() - StrPos;
232 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
237 if (OutQueue.length() == StrPos)
246 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
247 // ---------------------------------------------------------------------
248 /* This empties the buffer into the FD. */
249 bool CircleBuf::Write(int Fd)
255 // Woops, buffer is empty
262 // Write the buffer segment
264 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
277 Hash->Add(Buf + (OutP%Size),Res);
283 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
284 // ---------------------------------------------------------------------
285 /* This copies till the first empty line */
286 bool CircleBuf::WriteTillEl(string &Data,bool Single)
288 // We cheat and assume it is unneeded to have more than one buffer load
289 for (unsigned long I = OutP; I < InP; I++)
291 if (Buf[I%Size] != '\n')
297 if (I < InP && Buf[I%Size] == '\r')
299 if (I >= InP || Buf[I%Size] != '\n')
307 unsigned long Sz = LeftWrite();
312 Data += string((char *)(Buf + (OutP%Size)),Sz);
320 // CircleBuf::Stats - Print out stats information /*{{{*/
321 // ---------------------------------------------------------------------
323 void CircleBuf::Stats()
329 gettimeofday(&Stop,0);
330 /* float Diff = Stop.tv_sec - Start.tv_sec +
331 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
332 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
336 // ServerState::ServerState - Constructor /*{{{*/
337 // ---------------------------------------------------------------------
339 ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
340 In(64*1024), Out(4*1024),
346 // ServerState::Open - Open a connection to the server /*{{{*/
347 // ---------------------------------------------------------------------
348 /* This opens a connection to the server. */
349 bool ServerState::Open()
351 // Use the already open connection if possible.
360 // Determine the proxy setting
361 if (getenv("http_proxy") == 0)
363 string DefProxy = _config->Find("Acquire::http::Proxy");
364 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
365 if (SpecificProxy.empty() == false)
367 if (SpecificProxy == "DIRECT")
370 Proxy = SpecificProxy;
376 Proxy = getenv("http_proxy");
378 // Parse no_proxy, a , separated list of domains
379 if (getenv("no_proxy") != 0)
381 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
385 // Determine what host and port to use based on the proxy settings
388 if (Proxy.empty() == true || Proxy.Host.empty() == true)
390 if (ServerName.Port != 0)
391 Port = ServerName.Port;
392 Host = ServerName.Host;
401 // Connect to the remote server
402 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
408 // ServerState::Close - Close a connection to the server /*{{{*/
409 // ---------------------------------------------------------------------
411 bool ServerState::Close()
418 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
419 // ---------------------------------------------------------------------
420 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
421 parse error occured */
422 int ServerState::RunHeaders()
426 Owner->Status(_("Waiting for headers"));
440 if (In.WriteTillEl(Data) == false)
446 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
448 string::const_iterator J = I;
449 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
450 if (HeaderLine(string(I,J)) == false)
455 // 100 Continue is a Nop...
459 // Tidy up the connection persistance state.
460 if (Encoding == Closes && HaveContent == true)
465 while (Owner->Go(false,this) == true);
470 // ServerState::RunData - Transfer the data from the socket /*{{{*/
471 // ---------------------------------------------------------------------
473 bool ServerState::RunData()
477 // Chunked transfer encoding is fun..
478 if (Encoding == Chunked)
482 // Grab the block size
488 if (In.WriteTillEl(Data,true) == true)
491 while ((Last = Owner->Go(false,this)) == true);
496 // See if we are done
497 unsigned long Len = strtol(Data.c_str(),0,16);
502 // We have to remove the entity trailer
506 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
509 while ((Last = Owner->Go(false,this)) == true);
512 return !_error->PendingError();
515 // Transfer the block
517 while (Owner->Go(true,this) == true)
518 if (In.IsLimit() == true)
522 if (In.IsLimit() == false)
525 // The server sends an extra new line before the next block specifier..
530 if (In.WriteTillEl(Data,true) == true)
533 while ((Last = Owner->Go(false,this)) == true);
540 /* Closes encoding is used when the server did not specify a size, the
541 loss of the connection means we are done */
542 if (Encoding == Closes)
545 In.Limit(Size - StartPos);
547 // Just transfer the whole block.
550 if (In.IsLimit() == false)
554 return !_error->PendingError();
556 while (Owner->Go(true,this) == true);
559 return Owner->Flush(this) && !_error->PendingError();
562 // ServerState::HeaderLine - Process a header line /*{{{*/
563 // ---------------------------------------------------------------------
565 bool ServerState::HeaderLine(string Line)
567 if (Line.empty() == true)
570 // The http server might be trying to do something evil.
571 if (Line.length() >= MAXLEN)
572 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
574 string::size_type Pos = Line.find(' ');
575 if (Pos == string::npos || Pos+1 > Line.length())
577 // Blah, some servers use "connection:closes", evil.
578 Pos = Line.find(':');
579 if (Pos == string::npos || Pos + 2 > Line.length())
580 return _error->Error(_("Bad header line"));
584 // Parse off any trailing spaces between the : and the next word.
585 string::size_type Pos2 = Pos;
586 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
589 string Tag = string(Line,0,Pos);
590 string Val = string(Line,Pos2);
592 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
594 // Evil servers return no version
597 if (sscanf(Line.c_str(),"HTTP/%u.%u %u %[^\n]",&Major,&Minor,
599 return _error->Error(_("The HTTP server sent an invalid reply header"));
605 if (sscanf(Line.c_str(),"HTTP %u %[^\n]",&Result,Code) != 2)
606 return _error->Error(_("The HTTP server sent an invalid reply header"));
609 /* Check the HTTP response header to get the default persistance
615 if (Major == 1 && Minor <= 0)
624 if (stringcasecmp(Tag,"Content-Length:") == 0)
626 if (Encoding == Closes)
630 // The length is already set from the Content-Range header
634 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
635 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
639 if (stringcasecmp(Tag,"Content-Type:") == 0)
645 if (stringcasecmp(Tag,"Content-Range:") == 0)
649 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
650 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
651 if ((unsigned)StartPos > Size)
652 return _error->Error(_("This HTTP server has broken range support"));
656 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
659 if (stringcasecmp(Val,"chunked") == 0)
664 if (stringcasecmp(Tag,"Connection:") == 0)
666 if (stringcasecmp(Val,"close") == 0)
668 if (stringcasecmp(Val,"keep-alive") == 0)
673 if (stringcasecmp(Tag,"Last-Modified:") == 0)
675 if (StrToTime(Val,Date) == false)
676 return _error->Error(_("Unknown date format"));
684 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
685 // ---------------------------------------------------------------------
686 /* This places the http request in the outbound buffer */
687 void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
691 // The HTTP server expects a hostname with a trailing :port
693 string ProperHost = Uri.Host;
696 sprintf(Buf,":%u",Uri.Port);
701 if (Itm->Uri.length() >= sizeof(Buf))
704 /* Build the request. We include a keep-alive header only for non-proxy
705 requests. This is to tweak old http/1.0 servers that do support keep-alive
706 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
707 will glitch HTTP/1.0 proxies because they do not filter it out and
708 pass it on, HTTP/1.1 says the connection should default to keep alive
709 and we expect the proxy to do this */
710 if (Proxy.empty() == true || Proxy.Host.empty())
711 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
712 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
715 /* Generate a cache control header if necessary. We place a max
716 cache age on index files, optionally set a no-cache directive
717 and a no-store directive for archives. */
718 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
719 Itm->Uri.c_str(),ProperHost.c_str());
720 // only generate a cache control header if we actually want to
722 if (_config->FindB("Acquire::http::No-Cache",false) == false)
724 if (Itm->IndexFile == true)
725 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
726 _config->FindI("Acquire::http::Max-Age",0));
729 if (_config->FindB("Acquire::http::No-Store",false) == true)
730 strcat(Buf,"Cache-Control: no-store\r\n");
734 // generate a no-cache header if needed
735 if (_config->FindB("Acquire::http::No-Cache",false) == true)
736 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
741 // Check for a partial file
743 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
745 // In this case we send an if-range query with a range header
746 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
747 TimeRFC1123(SBuf.st_mtime).c_str());
752 if (Itm->LastModified != 0)
754 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
759 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
760 Req += string("Proxy-Authorization: Basic ") +
761 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
763 if (Uri.User.empty() == false || Uri.Password.empty() == false)
764 Req += string("Authorization: Basic ") +
765 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
767 Req += "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
775 // HttpMethod::Go - Run a single loop /*{{{*/
776 // ---------------------------------------------------------------------
777 /* This runs the select loop over the server FDs, Output file FDs and
779 bool HttpMethod::Go(bool ToFile,ServerState *Srv)
781 // Server has closed the connection
782 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
790 /* Add the server. We only send more requests if the connection will
792 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
793 && Srv->Persistent == true)
794 FD_SET(Srv->ServerFd,&wfds);
795 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
796 FD_SET(Srv->ServerFd,&rfds);
803 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
804 FD_SET(FileFD,&wfds);
807 FD_SET(STDIN_FILENO,&rfds);
809 // Figure out the max fd
811 if (MaxFd < Srv->ServerFd)
812 MaxFd = Srv->ServerFd;
819 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
823 return _error->Errno("select",_("Select failed"));
828 _error->Error(_("Connection timed out"));
829 return ServerDie(Srv);
833 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
836 if (Srv->In.Read(Srv->ServerFd) == false)
837 return ServerDie(Srv);
840 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
843 if (Srv->Out.Write(Srv->ServerFd) == false)
844 return ServerDie(Srv);
847 // Send data to the file
848 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
850 if (Srv->In.Write(FileFD) == false)
851 return _error->Errno("write",_("Error writing to output file"));
854 // Handle commands from APT
855 if (FD_ISSET(STDIN_FILENO,&rfds))
864 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
865 // ---------------------------------------------------------------------
866 /* This takes the current input buffer from the Server FD and writes it
868 bool HttpMethod::Flush(ServerState *Srv)
872 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
874 if (File->Name() != "/dev/null")
875 SetNonBlock(File->Fd(),false);
876 if (Srv->In.WriteSpace() == false)
879 while (Srv->In.WriteSpace() == true)
881 if (Srv->In.Write(File->Fd()) == false)
882 return _error->Errno("write",_("Error writing to file"));
883 if (Srv->In.IsLimit() == true)
887 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
893 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
894 // ---------------------------------------------------------------------
896 bool HttpMethod::ServerDie(ServerState *Srv)
898 unsigned int LErrno = errno;
900 // Dump the buffer to the file
901 if (Srv->State == ServerState::Data)
903 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
905 if (File->Name() != "/dev/null")
906 SetNonBlock(File->Fd(),false);
907 while (Srv->In.WriteSpace() == true)
909 if (Srv->In.Write(File->Fd()) == false)
910 return _error->Errno("write",_("Error writing to the file"));
913 if (Srv->In.IsLimit() == true)
918 // See if this is because the server finished the data stream
919 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
920 Srv->Encoding != ServerState::Closes)
924 return _error->Error(_("Error reading from server. Remote end closed connection"));
926 return _error->Errno("read",_("Error reading from server"));
932 // Nothing left in the buffer
933 if (Srv->In.WriteSpace() == false)
936 // We may have got multiple responses back in one packet..
944 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
945 // ---------------------------------------------------------------------
946 /* We look at the header data we got back from the server and decide what
950 3 - Unrecoverable error
951 4 - Error with error content page
952 5 - Unrecoverable non-server error (close the connection) */
953 int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
956 if (Srv->Result == 304)
958 unlink(Queue->DestFile.c_str());
960 Res.LastModified = Queue->LastModified;
964 /* We have a reply we dont handle. This should indicate a perm server
966 if (Srv->Result < 200 || Srv->Result >= 300)
968 _error->Error("%u %s",Srv->Result,Srv->Code);
969 if (Srv->HaveContent == true)
974 // This is some sort of 2xx 'data follows' reply
975 Res.LastModified = Srv->Date;
976 Res.Size = Srv->Size;
980 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
981 if (_error->PendingError() == true)
984 FailFile = Queue->DestFile;
985 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
987 FailTime = Srv->Date;
989 // Set the expected size
990 if (Srv->StartPos >= 0)
992 Res.ResumePoint = Srv->StartPos;
993 ftruncate(File->Fd(),Srv->StartPos);
996 // Set the start point
997 lseek(File->Fd(),0,SEEK_END);
1000 Srv->In.Hash = new Hashes;
1002 // Fill the Hash if the file is non-empty (resume)
1003 if (Srv->StartPos > 0)
1005 lseek(File->Fd(),0,SEEK_SET);
1006 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
1008 _error->Errno("read",_("Problem hashing file"));
1011 lseek(File->Fd(),0,SEEK_END);
1014 SetNonBlock(File->Fd(),true);
1018 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1019 // ---------------------------------------------------------------------
1020 /* This closes and timestamps the open file. This is neccessary to get
1021 resume behavoir on user abort */
1022 void HttpMethod::SigTerm(int)
1029 struct utimbuf UBuf;
1030 UBuf.actime = FailTime;
1031 UBuf.modtime = FailTime;
1032 utime(FailFile.c_str(),&UBuf);
1037 // HttpMethod::Fetch - Fetch an item /*{{{*/
1038 // ---------------------------------------------------------------------
1039 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1041 bool HttpMethod::Fetch(FetchItem *)
1046 // Queue the requests
1049 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1050 I = I->Next, Depth++)
1052 // If pipelining is disabled, we only queue 1 request
1053 if (Server->Pipeline == false && Depth >= 0)
1056 // Make sure we stick with the same server
1057 if (Server->Comp(I->Uri) == false)
1063 QueueBack = I->Next;
1064 SendReq(I,Server->Out);
1072 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1073 // ---------------------------------------------------------------------
1074 /* We stash the desired pipeline depth */
1075 bool HttpMethod::Configuration(string Message)
1077 if (pkgAcqMethod::Configuration(Message) == false)
1080 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1081 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1083 Debug = _config->FindB("Debug::Acquire::http",false);
1088 // HttpMethod::Loop - Main loop /*{{{*/
1089 // ---------------------------------------------------------------------
1091 int HttpMethod::Loop()
1093 signal(SIGTERM,SigTerm);
1094 signal(SIGINT,SigTerm);
1098 int FailCounter = 0;
1101 // We have no commands, wait for some to arrive
1104 if (WaitFd(STDIN_FILENO) == false)
1108 /* Run messages, we can accept 0 (no message) if we didn't
1109 do a WaitFd above.. Otherwise the FD is closed. */
1110 int Result = Run(true);
1111 if (Result != -1 && (Result != 0 || Queue == 0))
1117 CFStringEncoding se = kCFStringEncodingUTF8;
1119 char *url = strdup(Queue->Uri.c_str());
1121 URI uri = std::string(url);
1122 std::string hs = uri.Host;
1124 std::string urs = uri;
1126 CFStringRef sr = CFStringCreateWithCString(kCFAllocatorDefault, urs.c_str(), se);
1127 CFURLRef ur = CFURLCreateWithString(kCFAllocatorDefault, sr, NULL);
1129 CFHTTPMessageRef hm = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), ur, kCFHTTPVersion1_1);
1133 if (stat(Queue->DestFile.c_str(), &SBuf) >= 0 && SBuf.st_size > 0) {
1134 sr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("bytes=%li-"), (long) SBuf.st_size - 1);
1135 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Range"), sr);
1138 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(SBuf.st_mtime).c_str(), se);
1139 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Range"), sr);
1141 } else if (Queue->LastModified != 0) {
1142 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(SBuf.st_mtime).c_str(), se);
1143 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Modified-Since"), sr);
1147 if (Firmware_ != NULL)
1148 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Firmware"), Firmware_);
1150 sr = CFStringCreateWithCString(kCFAllocatorDefault, Machine_, se);
1151 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Machine"), sr);
1154 sr = CFStringCreateWithCString(kCFAllocatorDefault, SerialNumber_, se);
1155 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Serial-Number"), sr);
1158 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.98"));
1160 CFReadStreamRef rs = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, hm);
1163 CFDictionaryRef dr = SCDynamicStoreCopyProxies(NULL);
1164 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPProxy, dr);
1167 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1168 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
1174 uint8_t data[10240];
1177 Status("Connecting to %s", hs.c_str());
1179 if (!CFReadStreamOpen(rs)) {
1180 CfrsError("Open", rs);
1185 rd = CFReadStreamRead(rs, data, sizeof(data));
1188 CfrsError(uri.Host.c_str(), rs);
1193 Res.Filename = Queue->DestFile;
1195 hm = (CFHTTPMessageRef) CFReadStreamCopyProperty(rs, kCFStreamPropertyHTTPResponseHeader);
1196 sc = CFHTTPMessageGetResponseStatusCode(hm);
1198 if (sc == 301 || sc == 302) {
1199 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Location"));
1204 size_t ln = CFStringGetLength(sr) + 1;
1206 url = static_cast<char *>(malloc(ln));
1208 if (!CFStringGetCString(sr, url, ln, se)) {
1218 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Range"));
1220 size_t ln = CFStringGetLength(sr) + 1;
1223 if (!CFStringGetCString(sr, cr, ln, se)) {
1230 if (sscanf(cr, "bytes %lu-%*u/%lu", &offset, &Res.Size) != 2) {
1231 _error->Error(_("The HTTP server sent an invalid Content-Range header"));
1236 if (offset > Res.Size) {
1237 _error->Error(_("This HTTP server has broken range support"));
1242 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Length"));
1244 Res.Size = CFStringGetIntValue(sr);
1249 time(&Res.LastModified);
1251 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Last-Modified"));
1253 size_t ln = CFStringGetLength(sr) + 1;
1256 if (!CFStringGetCString(sr, cr, ln, se)) {
1263 if (!StrToTime(cr, Res.LastModified)) {
1264 _error->Error(_("Unknown date format"));
1273 unlink(Queue->DestFile.c_str());
1275 Res.LastModified = Queue->LastModified;
1277 } else if (sc < 200 || sc >= 300)
1282 File = new FileFd(Queue->DestFile, FileFd::WriteAny);
1283 if (_error->PendingError() == true) {
1290 FailFile = Queue->DestFile;
1291 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
1292 FailFd = File->Fd();
1293 FailTime = Res.LastModified;
1295 Res.ResumePoint = offset;
1296 ftruncate(File->Fd(), offset);
1299 lseek(File->Fd(), 0, SEEK_SET);
1300 if (!hash.AddFD(File->Fd(), offset)) {
1301 _error->Errno("read", _("Problem hashing file"));
1309 lseek(File->Fd(), 0, SEEK_END);
1313 read: if (rd == -1) {
1314 CfrsError("rd", rs);
1316 } else if (rd == 0) {
1318 Res.Size = File->Size();
1320 struct utimbuf UBuf;
1322 UBuf.actime = Res.LastModified;
1323 UBuf.modtime = Res.LastModified;
1324 utime(Queue->DestFile.c_str(), &UBuf);
1326 Res.TakeHashes(hash);
1333 int sz = write(File->Fd(), dt, rd);
1346 rd = CFReadStreamRead(rs, data, sizeof(data));
1355 CFReadStreamClose(rs);
1368 setlocale(LC_ALL, "");
1373 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1374 char *machine = new char[size];
1375 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1378 const char *path = "/System/Library/CoreServices/SystemVersion.plist";
1379 CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (uint8_t *) path, strlen(path), false);
1381 CFPropertyListRef plist; {
1382 CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
1383 CFReadStreamOpen(stream);
1384 plist = CFPropertyListCreateFromStream(kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, NULL);
1385 CFReadStreamClose(stream);
1390 if (plist != NULL) {
1391 Firmware_ = (CFStringRef) CFRetain(CFDictionaryGetValue((CFDictionaryRef) plist, CFSTR("ProductVersion")));
1395 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice"))
1396 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
1397 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
1398 SerialNumber_ = strdup(CFStringGetCStringPtr((CFStringRef) serial, CFStringGetSystemEncoding()));
1402 IOObjectRelease(service);