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>
48 #include <arpa/inet.h>
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreServices/CoreServices.h>
53 #include <SystemConfiguration/SystemConfiguration.h>
56 #include "rfc2553emu.h"
62 CFStringRef Firmware_;
64 CFStringRef UniqueID_;
66 void CfrsError(const char *name, CFReadStreamRef rs) {
67 CFStreamError se = CFReadStreamGetError(rs);
69 if (se.domain == kCFStreamErrorDomainCustom) {
70 } else if (se.domain == kCFStreamErrorDomainPOSIX) {
71 _error->Error("POSIX: %s", strerror(se.error));
72 } else if (se.domain == kCFStreamErrorDomainMacOSStatus) {
73 _error->Error("MacOSStatus: %ld", se.error);
74 } else if (se.domain == kCFStreamErrorDomainNetDB) {
75 _error->Error("NetDB: %s %s", name, gai_strerror(se.error));
76 } else if (se.domain == kCFStreamErrorDomainMach) {
77 _error->Error("Mach: %ld", se.error);
78 } else if (se.domain == kCFStreamErrorDomainHTTP) {
80 case kCFStreamErrorHTTPParseFailure:
81 _error->Error("Parse failure");
84 case kCFStreamErrorHTTPRedirectionLoop:
85 _error->Error("Redirection loop");
88 case kCFStreamErrorHTTPBadURL:
89 _error->Error("Bad URL");
93 _error->Error("Unknown HTTP error: %ld", se.error);
96 } else if (se.domain == kCFStreamErrorDomainSOCKS) {
97 _error->Error("SOCKS: %ld", se.error);
98 } else if (se.domain == kCFStreamErrorDomainSystemConfiguration) {
99 _error->Error("SystemConfiguration: %ld", se.error);
100 } else if (se.domain == kCFStreamErrorDomainSSL) {
101 _error->Error("SSL: %ld", se.error);
103 _error->Error("Domain #%ld: %ld", se.domain, se.error);
107 string HttpMethod::FailFile;
108 int HttpMethod::FailFd = -1;
109 time_t HttpMethod::FailTime = 0;
110 unsigned long PipelineDepth = 10;
111 unsigned long TimeOut = 120;
114 unsigned long CircleBuf::BwReadLimit=0;
115 unsigned long CircleBuf::BwTickReadData=0;
116 struct timeval CircleBuf::BwReadTick={0,0};
117 const unsigned int CircleBuf::BW_HZ=10;
119 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
120 // ---------------------------------------------------------------------
122 CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
124 Buf = new unsigned char[Size];
127 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
130 // CircleBuf::Reset - Reset to the default state /*{{{*/
131 // ---------------------------------------------------------------------
133 void CircleBuf::Reset()
138 MaxGet = (unsigned int)-1;
147 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
148 // ---------------------------------------------------------------------
149 /* This fills up the buffer with as much data as is in the FD, assuming it
151 bool CircleBuf::Read(int Fd)
153 unsigned long BwReadMax;
157 // Woops, buffer is full
158 if (InP - OutP == Size)
161 // what's left to read in this tick
162 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
164 if(CircleBuf::BwReadLimit) {
166 gettimeofday(&now,0);
168 unsigned long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
169 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
170 if(d > 1000000/BW_HZ) {
171 CircleBuf::BwReadTick = now;
172 CircleBuf::BwTickReadData = 0;
175 if(CircleBuf::BwTickReadData >= BwReadMax) {
176 usleep(1000000/BW_HZ);
181 // Write the buffer segment
183 if(CircleBuf::BwReadLimit) {
184 Res = read(Fd,Buf + (InP%Size),
185 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
187 Res = read(Fd,Buf + (InP%Size),LeftRead());
189 if(Res > 0 && BwReadLimit > 0)
190 CircleBuf::BwTickReadData += Res;
202 gettimeofday(&Start,0);
207 // CircleBuf::Read - Put the string into the buffer /*{{{*/
208 // ---------------------------------------------------------------------
209 /* This will hold the string in and fill the buffer with it as it empties */
210 bool CircleBuf::Read(string Data)
217 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
218 // ---------------------------------------------------------------------
220 void CircleBuf::FillOut()
222 if (OutQueue.empty() == true)
226 // Woops, buffer is full
227 if (InP - OutP == Size)
230 // Write the buffer segment
231 unsigned long Sz = LeftRead();
232 if (OutQueue.length() - StrPos < Sz)
233 Sz = OutQueue.length() - StrPos;
234 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
239 if (OutQueue.length() == StrPos)
248 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
249 // ---------------------------------------------------------------------
250 /* This empties the buffer into the FD. */
251 bool CircleBuf::Write(int Fd)
257 // Woops, buffer is empty
264 // Write the buffer segment
266 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
279 Hash->Add(Buf + (OutP%Size),Res);
285 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
286 // ---------------------------------------------------------------------
287 /* This copies till the first empty line */
288 bool CircleBuf::WriteTillEl(string &Data,bool Single)
290 // We cheat and assume it is unneeded to have more than one buffer load
291 for (unsigned long I = OutP; I < InP; I++)
293 if (Buf[I%Size] != '\n')
299 if (I < InP && Buf[I%Size] == '\r')
301 if (I >= InP || Buf[I%Size] != '\n')
309 unsigned long Sz = LeftWrite();
314 Data += string((char *)(Buf + (OutP%Size)),Sz);
322 // CircleBuf::Stats - Print out stats information /*{{{*/
323 // ---------------------------------------------------------------------
325 void CircleBuf::Stats()
331 gettimeofday(&Stop,0);
332 /* float Diff = Stop.tv_sec - Start.tv_sec +
333 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
334 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
338 // ServerState::ServerState - Constructor /*{{{*/
339 // ---------------------------------------------------------------------
341 ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
342 In(64*1024), Out(4*1024),
348 // ServerState::Open - Open a connection to the server /*{{{*/
349 // ---------------------------------------------------------------------
350 /* This opens a connection to the server. */
351 bool ServerState::Open()
353 // Use the already open connection if possible.
362 // Determine the proxy setting
363 if (getenv("http_proxy") == 0)
365 string DefProxy = _config->Find("Acquire::http::Proxy");
366 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
367 if (SpecificProxy.empty() == false)
369 if (SpecificProxy == "DIRECT")
372 Proxy = SpecificProxy;
378 Proxy = getenv("http_proxy");
380 // Parse no_proxy, a , separated list of domains
381 if (getenv("no_proxy") != 0)
383 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
387 // Determine what host and port to use based on the proxy settings
390 if (Proxy.empty() == true || Proxy.Host.empty() == true)
392 if (ServerName.Port != 0)
393 Port = ServerName.Port;
394 Host = ServerName.Host;
403 // Connect to the remote server
404 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
410 // ServerState::Close - Close a connection to the server /*{{{*/
411 // ---------------------------------------------------------------------
413 bool ServerState::Close()
420 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
421 // ---------------------------------------------------------------------
422 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
423 parse error occured */
424 int ServerState::RunHeaders()
428 Owner->Status(_("Waiting for headers"));
442 if (In.WriteTillEl(Data) == false)
448 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
450 string::const_iterator J = I;
451 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
452 if (HeaderLine(string(I,J)) == false)
457 // 100 Continue is a Nop...
461 // Tidy up the connection persistance state.
462 if (Encoding == Closes && HaveContent == true)
467 while (Owner->Go(false,this) == true);
472 // ServerState::RunData - Transfer the data from the socket /*{{{*/
473 // ---------------------------------------------------------------------
475 bool ServerState::RunData()
479 // Chunked transfer encoding is fun..
480 if (Encoding == Chunked)
484 // Grab the block size
490 if (In.WriteTillEl(Data,true) == true)
493 while ((Last = Owner->Go(false,this)) == true);
498 // See if we are done
499 unsigned long Len = strtol(Data.c_str(),0,16);
504 // We have to remove the entity trailer
508 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
511 while ((Last = Owner->Go(false,this)) == true);
514 return !_error->PendingError();
517 // Transfer the block
519 while (Owner->Go(true,this) == true)
520 if (In.IsLimit() == true)
524 if (In.IsLimit() == false)
527 // The server sends an extra new line before the next block specifier..
532 if (In.WriteTillEl(Data,true) == true)
535 while ((Last = Owner->Go(false,this)) == true);
542 /* Closes encoding is used when the server did not specify a size, the
543 loss of the connection means we are done */
544 if (Encoding == Closes)
547 In.Limit(Size - StartPos);
549 // Just transfer the whole block.
552 if (In.IsLimit() == false)
556 return !_error->PendingError();
558 while (Owner->Go(true,this) == true);
561 return Owner->Flush(this) && !_error->PendingError();
564 // ServerState::HeaderLine - Process a header line /*{{{*/
565 // ---------------------------------------------------------------------
567 bool ServerState::HeaderLine(string Line)
569 if (Line.empty() == true)
572 // The http server might be trying to do something evil.
573 if (Line.length() >= MAXLEN)
574 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
576 string::size_type Pos = Line.find(' ');
577 if (Pos == string::npos || Pos+1 > Line.length())
579 // Blah, some servers use "connection:closes", evil.
580 Pos = Line.find(':');
581 if (Pos == string::npos || Pos + 2 > Line.length())
582 return _error->Error(_("Bad header line"));
586 // Parse off any trailing spaces between the : and the next word.
587 string::size_type Pos2 = Pos;
588 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
591 string Tag = string(Line,0,Pos);
592 string Val = string(Line,Pos2);
594 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
596 // Evil servers return no version
599 if (sscanf(Line.c_str(),"HTTP/%u.%u %u %[^\n]",&Major,&Minor,
601 return _error->Error(_("The HTTP server sent an invalid reply header"));
607 if (sscanf(Line.c_str(),"HTTP %u %[^\n]",&Result,Code) != 2)
608 return _error->Error(_("The HTTP server sent an invalid reply header"));
611 /* Check the HTTP response header to get the default persistance
617 if (Major == 1 && Minor <= 0)
626 if (stringcasecmp(Tag,"Content-Length:") == 0)
628 if (Encoding == Closes)
632 // The length is already set from the Content-Range header
636 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
637 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
641 if (stringcasecmp(Tag,"Content-Type:") == 0)
647 if (stringcasecmp(Tag,"Content-Range:") == 0)
651 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
652 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
653 if ((unsigned)StartPos > Size)
654 return _error->Error(_("This HTTP server has broken range support"));
658 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
661 if (stringcasecmp(Val,"chunked") == 0)
666 if (stringcasecmp(Tag,"Connection:") == 0)
668 if (stringcasecmp(Val,"close") == 0)
670 if (stringcasecmp(Val,"keep-alive") == 0)
675 if (stringcasecmp(Tag,"Last-Modified:") == 0)
677 if (StrToTime(Val,Date) == false)
678 return _error->Error(_("Unknown date format"));
686 static const CFOptionFlags kNetworkEvents =
687 kCFStreamEventOpenCompleted |
688 kCFStreamEventHasBytesAvailable |
689 kCFStreamEventEndEncountered |
690 kCFStreamEventErrorOccurred |
693 static void CFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType event, void *arg) {
695 case kCFStreamEventOpenCompleted:
698 case kCFStreamEventHasBytesAvailable:
699 case kCFStreamEventEndEncountered:
700 *reinterpret_cast<int *>(arg) = 1;
701 CFRunLoopStop(CFRunLoopGetCurrent());
704 case kCFStreamEventErrorOccurred:
705 *reinterpret_cast<int *>(arg) = -1;
706 CFRunLoopStop(CFRunLoopGetCurrent());
711 /* http://lists.apple.com/archives/Macnetworkprog/2006/Apr/msg00014.html */
712 int CFReadStreamOpen(CFReadStreamRef stream, double timeout) {
713 CFStreamClientContext context;
716 memset(&context, 0, sizeof(context));
717 context.info = &value;
719 if (CFReadStreamSetClient(stream, kNetworkEvents, CFReadStreamCallback, &context)) {
720 CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
721 if (CFReadStreamOpen(stream))
722 CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout, false);
725 CFReadStreamSetClient(stream, kCFStreamEventNone, NULL, NULL);
731 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
732 // ---------------------------------------------------------------------
733 /* This places the http request in the outbound buffer */
734 void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
738 // The HTTP server expects a hostname with a trailing :port
740 string ProperHost = Uri.Host;
743 sprintf(Buf,":%u",Uri.Port);
748 if (Itm->Uri.length() >= sizeof(Buf))
751 /* Build the request. We include a keep-alive header only for non-proxy
752 requests. This is to tweak old http/1.0 servers that do support keep-alive
753 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
754 will glitch HTTP/1.0 proxies because they do not filter it out and
755 pass it on, HTTP/1.1 says the connection should default to keep alive
756 and we expect the proxy to do this */
757 if (Proxy.empty() == true || Proxy.Host.empty())
758 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
759 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
762 /* Generate a cache control header if necessary. We place a max
763 cache age on index files, optionally set a no-cache directive
764 and a no-store directive for archives. */
765 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
766 Itm->Uri.c_str(),ProperHost.c_str());
767 // only generate a cache control header if we actually want to
769 if (_config->FindB("Acquire::http::No-Cache",false) == false)
771 if (Itm->IndexFile == true)
772 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
773 _config->FindI("Acquire::http::Max-Age",0));
776 if (_config->FindB("Acquire::http::No-Store",false) == true)
777 strcat(Buf,"Cache-Control: no-store\r\n");
781 // generate a no-cache header if needed
782 if (_config->FindB("Acquire::http::No-Cache",false) == true)
783 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
788 // Check for a partial file
790 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
792 // In this case we send an if-range query with a range header
793 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
794 TimeRFC1123(SBuf.st_mtime).c_str());
799 if (Itm->LastModified != 0)
801 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
806 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
807 Req += string("Proxy-Authorization: Basic ") +
808 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
810 if (Uri.User.empty() == false || Uri.Password.empty() == false)
811 Req += string("Authorization: Basic ") +
812 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
814 Req += "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
822 // HttpMethod::Go - Run a single loop /*{{{*/
823 // ---------------------------------------------------------------------
824 /* This runs the select loop over the server FDs, Output file FDs and
826 bool HttpMethod::Go(bool ToFile,ServerState *Srv)
828 // Server has closed the connection
829 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
837 /* Add the server. We only send more requests if the connection will
839 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
840 && Srv->Persistent == true)
841 FD_SET(Srv->ServerFd,&wfds);
842 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
843 FD_SET(Srv->ServerFd,&rfds);
850 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
851 FD_SET(FileFD,&wfds);
854 FD_SET(STDIN_FILENO,&rfds);
856 // Figure out the max fd
858 if (MaxFd < Srv->ServerFd)
859 MaxFd = Srv->ServerFd;
866 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
870 return _error->Errno("select",_("Select failed"));
875 _error->Error(_("Connection timed out"));
876 return ServerDie(Srv);
880 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
883 if (Srv->In.Read(Srv->ServerFd) == false)
884 return ServerDie(Srv);
887 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
890 if (Srv->Out.Write(Srv->ServerFd) == false)
891 return ServerDie(Srv);
894 // Send data to the file
895 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
897 if (Srv->In.Write(FileFD) == false)
898 return _error->Errno("write",_("Error writing to output file"));
901 // Handle commands from APT
902 if (FD_ISSET(STDIN_FILENO,&rfds))
911 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
912 // ---------------------------------------------------------------------
913 /* This takes the current input buffer from the Server FD and writes it
915 bool HttpMethod::Flush(ServerState *Srv)
919 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
921 if (File->Name() != "/dev/null")
922 SetNonBlock(File->Fd(),false);
923 if (Srv->In.WriteSpace() == false)
926 while (Srv->In.WriteSpace() == true)
928 if (Srv->In.Write(File->Fd()) == false)
929 return _error->Errno("write",_("Error writing to file"));
930 if (Srv->In.IsLimit() == true)
934 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
940 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
941 // ---------------------------------------------------------------------
943 bool HttpMethod::ServerDie(ServerState *Srv)
945 unsigned int LErrno = errno;
947 // Dump the buffer to the file
948 if (Srv->State == ServerState::Data)
950 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
952 if (File->Name() != "/dev/null")
953 SetNonBlock(File->Fd(),false);
954 while (Srv->In.WriteSpace() == true)
956 if (Srv->In.Write(File->Fd()) == false)
957 return _error->Errno("write",_("Error writing to the file"));
960 if (Srv->In.IsLimit() == true)
965 // See if this is because the server finished the data stream
966 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
967 Srv->Encoding != ServerState::Closes)
971 return _error->Error(_("Error reading from server. Remote end closed connection"));
973 return _error->Errno("read",_("Error reading from server"));
979 // Nothing left in the buffer
980 if (Srv->In.WriteSpace() == false)
983 // We may have got multiple responses back in one packet..
991 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
992 // ---------------------------------------------------------------------
993 /* We look at the header data we got back from the server and decide what
997 3 - Unrecoverable error
998 4 - Error with error content page
999 5 - Unrecoverable non-server error (close the connection) */
1000 int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
1003 if (Srv->Result == 304)
1005 unlink(Queue->DestFile.c_str());
1007 Res.LastModified = Queue->LastModified;
1011 /* We have a reply we dont handle. This should indicate a perm server
1013 if (Srv->Result < 200 || Srv->Result >= 300)
1015 _error->Error("%u %s",Srv->Result,Srv->Code);
1016 if (Srv->HaveContent == true)
1021 // This is some sort of 2xx 'data follows' reply
1022 Res.LastModified = Srv->Date;
1023 Res.Size = Srv->Size;
1027 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
1028 if (_error->PendingError() == true)
1031 FailFile = Queue->DestFile;
1032 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
1033 FailFd = File->Fd();
1034 FailTime = Srv->Date;
1036 // Set the expected size
1037 if (Srv->StartPos >= 0)
1039 Res.ResumePoint = Srv->StartPos;
1040 ftruncate(File->Fd(),Srv->StartPos);
1043 // Set the start point
1044 lseek(File->Fd(),0,SEEK_END);
1046 delete Srv->In.Hash;
1047 Srv->In.Hash = new Hashes;
1049 // Fill the Hash if the file is non-empty (resume)
1050 if (Srv->StartPos > 0)
1052 lseek(File->Fd(),0,SEEK_SET);
1053 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
1055 _error->Errno("read",_("Problem hashing file"));
1058 lseek(File->Fd(),0,SEEK_END);
1061 SetNonBlock(File->Fd(),true);
1065 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1066 // ---------------------------------------------------------------------
1067 /* This closes and timestamps the open file. This is neccessary to get
1068 resume behavoir on user abort */
1069 void HttpMethod::SigTerm(int)
1076 struct utimbuf UBuf;
1077 UBuf.actime = FailTime;
1078 UBuf.modtime = FailTime;
1079 utime(FailFile.c_str(),&UBuf);
1084 // HttpMethod::Fetch - Fetch an item /*{{{*/
1085 // ---------------------------------------------------------------------
1086 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1088 bool HttpMethod::Fetch(FetchItem *)
1093 // Queue the requests
1096 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1097 I = I->Next, Depth++)
1099 // If pipelining is disabled, we only queue 1 request
1100 if (Server->Pipeline == false && Depth >= 0)
1103 // Make sure we stick with the same server
1104 if (Server->Comp(I->Uri) == false)
1110 QueueBack = I->Next;
1111 SendReq(I,Server->Out);
1119 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1120 // ---------------------------------------------------------------------
1121 /* We stash the desired pipeline depth */
1122 bool HttpMethod::Configuration(string Message)
1124 if (pkgAcqMethod::Configuration(Message) == false)
1127 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1128 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1130 Debug = _config->FindB("Debug::Acquire::http",false);
1135 // HttpMethod::Loop - Main loop /*{{{*/
1136 // ---------------------------------------------------------------------
1138 int HttpMethod::Loop()
1140 signal(SIGTERM,SigTerm);
1141 signal(SIGINT,SigTerm);
1145 std::set<std::string> cached;
1147 int FailCounter = 0;
1150 // We have no commands, wait for some to arrive
1153 if (WaitFd(STDIN_FILENO) == false)
1157 /* Run messages, we can accept 0 (no message) if we didn't
1158 do a WaitFd above.. Otherwise the FD is closed. */
1159 int Result = Run(true);
1160 if (Result != -1 && (Result != 0 || Queue == 0))
1166 CFStringEncoding se = kCFStringEncodingUTF8;
1168 char *url = strdup(Queue->Uri.c_str());
1170 URI uri = std::string(url);
1171 std::string hs = uri.Host;
1173 if (cached.find(hs) != cached.end()) {
1174 _error->Error("Cached Failure");
1181 std::string urs = uri;
1184 size_t bad = urs.find_first_of("+");
1185 if (bad == std::string::npos)
1188 urs = urs.substr(0, bad) + "%2b" + urs.substr(bad + 1);
1191 CFStringRef sr = CFStringCreateWithCString(kCFAllocatorDefault, urs.c_str(), se);
1192 CFURLRef ur = CFURLCreateWithString(kCFAllocatorDefault, sr, NULL);
1194 CFHTTPMessageRef hm = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), ur, kCFHTTPVersion1_1);
1198 if (stat(Queue->DestFile.c_str(), &SBuf) >= 0 && SBuf.st_size > 0) {
1199 sr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("bytes=%li-"), (long) SBuf.st_size - 1);
1200 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Range"), sr);
1203 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(SBuf.st_mtime).c_str(), se);
1204 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Range"), sr);
1207 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Cache-Control"), CFSTR("no-cache"));
1208 } else if (Queue->LastModified != 0) {
1209 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(Queue->LastModified).c_str(), se);
1210 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Modified-Since"), sr);
1213 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Cache-Control"), CFSTR("no-cache"));
1215 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Cache-Control"), CFSTR("max-age=0"));
1217 if (Firmware_ != NULL)
1218 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Firmware"), Firmware_);
1220 sr = CFStringCreateWithCString(kCFAllocatorDefault, Machine_, se);
1221 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Machine"), sr);
1224 if (UniqueID_ != NULL)
1225 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("X-Unique-ID"), UniqueID_);
1227 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.534"));
1229 CFReadStreamRef rs = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, hm);
1232 #define _kCFStreamPropertyReadTimeout CFSTR("_kCFStreamPropertyReadTimeout")
1233 #define _kCFStreamPropertyWriteTimeout CFSTR("_kCFStreamPropertyWriteTimeout")
1234 #define _kCFStreamPropertySocketImmediateBufferTimeOut CFSTR("_kCFStreamPropertySocketImmediateBufferTimeOut")
1236 /*SInt32 to(TimeOut);
1237 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &to));*/
1239 CFNumberRef nm(CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &to));
1241 CFReadStreamSetProperty(rs, _kCFStreamPropertyReadTimeout, nm);
1242 CFReadStreamSetProperty(rs, _kCFStreamPropertyWriteTimeout, nm);
1243 CFReadStreamSetProperty(rs, _kCFStreamPropertySocketImmediateBufferTimeOut, nm);
1246 CFDictionaryRef dr = SCDynamicStoreCopyProxies(NULL);
1247 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPProxy, dr);
1250 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1251 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
1257 uint8_t data[10240];
1260 Status("Connecting to %s", hs.c_str());
1262 switch (CFReadStreamOpen(rs, to)) {
1264 CfrsError("Open", rs);
1268 _error->Error("Host Unreachable");
1281 rd = CFReadStreamRead(rs, data, sizeof(data));
1284 CfrsError(uri.Host.c_str(), rs);
1290 Res.Filename = Queue->DestFile;
1292 hm = (CFHTTPMessageRef) CFReadStreamCopyProperty(rs, kCFStreamPropertyHTTPResponseHeader);
1293 sc = CFHTTPMessageGetResponseStatusCode(hm);
1295 if (sc == 301 || sc == 302) {
1296 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Location"));
1301 size_t ln = CFStringGetLength(sr) + 1;
1303 url = static_cast<char *>(malloc(ln));
1305 if (!CFStringGetCString(sr, url, ln, se)) {
1315 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Range"));
1317 size_t ln = CFStringGetLength(sr) + 1;
1320 if (!CFStringGetCString(sr, cr, ln, se)) {
1327 if (sscanf(cr, "bytes %lu-%*u/%lu", &offset, &Res.Size) != 2) {
1328 _error->Error(_("The HTTP server sent an invalid Content-Range header"));
1333 if (offset > Res.Size) {
1334 _error->Error(_("This HTTP server has broken range support"));
1339 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Length"));
1341 Res.Size = CFStringGetIntValue(sr);
1346 time(&Res.LastModified);
1348 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Last-Modified"));
1350 size_t ln = CFStringGetLength(sr) + 1;
1353 if (!CFStringGetCString(sr, cr, ln, se)) {
1360 if (!StrToTime(cr, Res.LastModified)) {
1361 _error->Error(_("Unknown date format"));
1367 if (sc < 200 || sc >= 300 && sc != 304) {
1368 sr = CFHTTPMessageCopyResponseStatusLine(hm);
1370 size_t ln = CFStringGetLength(sr) + 1;
1373 if (!CFStringGetCString(sr, cr, ln, se)) {
1380 _error->Error("%s", cr);
1389 unlink(Queue->DestFile.c_str());
1391 Res.LastModified = Queue->LastModified;
1396 File = new FileFd(Queue->DestFile, FileFd::WriteAny);
1397 if (_error->PendingError() == true) {
1404 FailFile = Queue->DestFile;
1405 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
1406 FailFd = File->Fd();
1407 FailTime = Res.LastModified;
1409 Res.ResumePoint = offset;
1410 ftruncate(File->Fd(), offset);
1413 lseek(File->Fd(), 0, SEEK_SET);
1414 if (!hash.AddFD(File->Fd(), offset)) {
1415 _error->Errno("read", _("Problem hashing file"));
1423 lseek(File->Fd(), 0, SEEK_END);
1427 read: if (rd == -1) {
1428 CfrsError("rd", rs);
1430 } else if (rd == 0) {
1432 Res.Size = File->Size();
1434 struct utimbuf UBuf;
1436 UBuf.actime = Res.LastModified;
1437 UBuf.modtime = Res.LastModified;
1438 utime(Queue->DestFile.c_str(), &UBuf);
1440 Res.TakeHashes(hash);
1447 int sz = write(File->Fd(), dt, rd);
1460 rd = CFReadStreamRead(rs, data, sizeof(data));
1469 CFReadStreamClose(rs);
1482 setlocale(LC_ALL, "");
1487 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1488 char *machine = new char[size];
1489 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1492 const char *path = "/System/Library/CoreServices/SystemVersion.plist";
1493 CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (uint8_t *) path, strlen(path), false);
1495 CFPropertyListRef plist; {
1496 CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
1497 CFReadStreamOpen(stream);
1498 plist = CFPropertyListCreateFromStream(kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, NULL);
1499 CFReadStreamClose(stream);
1504 if (plist != NULL) {
1505 Firmware_ = (CFStringRef) CFRetain(CFDictionaryGetValue((CFDictionaryRef) plist, CFSTR("ProductVersion")));
1509 if (void *lockdown = lockdown_connect()) {
1510 UniqueID_ = lockdown_copy_value(lockdown, NULL, kLockdownUniqueDeviceIDKey);
1511 lockdown_disconnect(lockdown);