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>
47 #include <CoreFoundation/CoreFoundation.h>
48 #include <CoreServices/CoreServices.h>
49 #include <SystemConfiguration/SystemConfiguration.h>
52 #include "rfc2553emu.h"
58 void CfrsError(CFReadStreamRef rs) {
59 CFStreamError se = CFReadStreamGetError(rs);
61 if (se.domain == kCFStreamErrorDomainCustom) {
62 } else if (se.domain == kCFStreamErrorDomainPOSIX) {
63 _error->Error("POSIX: %s", strerror(se.error));
64 } else if (se.domain == kCFStreamErrorDomainMacOSStatus) {
65 _error->Error("MacOSStatus: %ld", se.error);
66 } else if (se.domain == kCFStreamErrorDomainNetDB) {
67 _error->Error("NetDB: %s", gai_strerror(se.error));
68 } else if (se.domain == kCFStreamErrorDomainMach) {
69 _error->Error("Mach: %ld", se.error);
70 } else if (se.domain == kCFStreamErrorDomainHTTP) {
72 case kCFStreamErrorHTTPParseFailure:
73 _error->Error("Parse failure");
76 case kCFStreamErrorHTTPRedirectionLoop:
77 _error->Error("Redirection loop");
80 case kCFStreamErrorHTTPBadURL:
81 _error->Error("Bad URL");
85 _error->Error("Unknown HTTP error: %ld", se.error);
88 } else if (se.domain == kCFStreamErrorDomainSOCKS) {
89 _error->Error("SOCKS: %ld", se.error);
90 } else if (se.domain == kCFStreamErrorDomainSystemConfiguration) {
91 _error->Error("SystemConfiguration: %ld", se.error);
92 } else if (se.domain == kCFStreamErrorDomainSSL) {
93 _error->Error("SSL: %ld", se.error);
95 _error->Error("Domain #%ld: %ld", se.domain, se.error);
99 string HttpMethod::FailFile;
100 int HttpMethod::FailFd = -1;
101 time_t HttpMethod::FailTime = 0;
102 unsigned long PipelineDepth = 10;
103 unsigned long TimeOut = 120;
106 unsigned long CircleBuf::BwReadLimit=0;
107 unsigned long CircleBuf::BwTickReadData=0;
108 struct timeval CircleBuf::BwReadTick={0,0};
109 const unsigned int CircleBuf::BW_HZ=10;
111 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
112 // ---------------------------------------------------------------------
114 CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
116 Buf = new unsigned char[Size];
119 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
122 // CircleBuf::Reset - Reset to the default state /*{{{*/
123 // ---------------------------------------------------------------------
125 void CircleBuf::Reset()
130 MaxGet = (unsigned int)-1;
139 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
140 // ---------------------------------------------------------------------
141 /* This fills up the buffer with as much data as is in the FD, assuming it
143 bool CircleBuf::Read(int Fd)
145 unsigned long BwReadMax;
149 // Woops, buffer is full
150 if (InP - OutP == Size)
153 // what's left to read in this tick
154 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
156 if(CircleBuf::BwReadLimit) {
158 gettimeofday(&now,0);
160 unsigned long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
161 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
162 if(d > 1000000/BW_HZ) {
163 CircleBuf::BwReadTick = now;
164 CircleBuf::BwTickReadData = 0;
167 if(CircleBuf::BwTickReadData >= BwReadMax) {
168 usleep(1000000/BW_HZ);
173 // Write the buffer segment
175 if(CircleBuf::BwReadLimit) {
176 Res = read(Fd,Buf + (InP%Size),
177 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
179 Res = read(Fd,Buf + (InP%Size),LeftRead());
181 if(Res > 0 && BwReadLimit > 0)
182 CircleBuf::BwTickReadData += Res;
194 gettimeofday(&Start,0);
199 // CircleBuf::Read - Put the string into the buffer /*{{{*/
200 // ---------------------------------------------------------------------
201 /* This will hold the string in and fill the buffer with it as it empties */
202 bool CircleBuf::Read(string Data)
209 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
210 // ---------------------------------------------------------------------
212 void CircleBuf::FillOut()
214 if (OutQueue.empty() == true)
218 // Woops, buffer is full
219 if (InP - OutP == Size)
222 // Write the buffer segment
223 unsigned long Sz = LeftRead();
224 if (OutQueue.length() - StrPos < Sz)
225 Sz = OutQueue.length() - StrPos;
226 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
231 if (OutQueue.length() == StrPos)
240 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
241 // ---------------------------------------------------------------------
242 /* This empties the buffer into the FD. */
243 bool CircleBuf::Write(int Fd)
249 // Woops, buffer is empty
256 // Write the buffer segment
258 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
271 Hash->Add(Buf + (OutP%Size),Res);
277 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
278 // ---------------------------------------------------------------------
279 /* This copies till the first empty line */
280 bool CircleBuf::WriteTillEl(string &Data,bool Single)
282 // We cheat and assume it is unneeded to have more than one buffer load
283 for (unsigned long I = OutP; I < InP; I++)
285 if (Buf[I%Size] != '\n')
291 if (I < InP && Buf[I%Size] == '\r')
293 if (I >= InP || Buf[I%Size] != '\n')
301 unsigned long Sz = LeftWrite();
306 Data += string((char *)(Buf + (OutP%Size)),Sz);
314 // CircleBuf::Stats - Print out stats information /*{{{*/
315 // ---------------------------------------------------------------------
317 void CircleBuf::Stats()
323 gettimeofday(&Stop,0);
324 /* float Diff = Stop.tv_sec - Start.tv_sec +
325 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
326 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
330 // ServerState::ServerState - Constructor /*{{{*/
331 // ---------------------------------------------------------------------
333 ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
334 In(64*1024), Out(4*1024),
340 // ServerState::Open - Open a connection to the server /*{{{*/
341 // ---------------------------------------------------------------------
342 /* This opens a connection to the server. */
343 bool ServerState::Open()
345 // Use the already open connection if possible.
354 // Determine the proxy setting
355 if (getenv("http_proxy") == 0)
357 string DefProxy = _config->Find("Acquire::http::Proxy");
358 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
359 if (SpecificProxy.empty() == false)
361 if (SpecificProxy == "DIRECT")
364 Proxy = SpecificProxy;
370 Proxy = getenv("http_proxy");
372 // Parse no_proxy, a , separated list of domains
373 if (getenv("no_proxy") != 0)
375 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
379 // Determine what host and port to use based on the proxy settings
382 if (Proxy.empty() == true || Proxy.Host.empty() == true)
384 if (ServerName.Port != 0)
385 Port = ServerName.Port;
386 Host = ServerName.Host;
395 // Connect to the remote server
396 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
402 // ServerState::Close - Close a connection to the server /*{{{*/
403 // ---------------------------------------------------------------------
405 bool ServerState::Close()
412 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
413 // ---------------------------------------------------------------------
414 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
415 parse error occured */
416 int ServerState::RunHeaders()
420 Owner->Status(_("Waiting for headers"));
434 if (In.WriteTillEl(Data) == false)
440 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
442 string::const_iterator J = I;
443 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
444 if (HeaderLine(string(I,J)) == false)
449 // 100 Continue is a Nop...
453 // Tidy up the connection persistance state.
454 if (Encoding == Closes && HaveContent == true)
459 while (Owner->Go(false,this) == true);
464 // ServerState::RunData - Transfer the data from the socket /*{{{*/
465 // ---------------------------------------------------------------------
467 bool ServerState::RunData()
471 // Chunked transfer encoding is fun..
472 if (Encoding == Chunked)
476 // Grab the block size
482 if (In.WriteTillEl(Data,true) == true)
485 while ((Last = Owner->Go(false,this)) == true);
490 // See if we are done
491 unsigned long Len = strtol(Data.c_str(),0,16);
496 // We have to remove the entity trailer
500 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
503 while ((Last = Owner->Go(false,this)) == true);
506 return !_error->PendingError();
509 // Transfer the block
511 while (Owner->Go(true,this) == true)
512 if (In.IsLimit() == true)
516 if (In.IsLimit() == false)
519 // The server sends an extra new line before the next block specifier..
524 if (In.WriteTillEl(Data,true) == true)
527 while ((Last = Owner->Go(false,this)) == true);
534 /* Closes encoding is used when the server did not specify a size, the
535 loss of the connection means we are done */
536 if (Encoding == Closes)
539 In.Limit(Size - StartPos);
541 // Just transfer the whole block.
544 if (In.IsLimit() == false)
548 return !_error->PendingError();
550 while (Owner->Go(true,this) == true);
553 return Owner->Flush(this) && !_error->PendingError();
556 // ServerState::HeaderLine - Process a header line /*{{{*/
557 // ---------------------------------------------------------------------
559 bool ServerState::HeaderLine(string Line)
561 if (Line.empty() == true)
564 // The http server might be trying to do something evil.
565 if (Line.length() >= MAXLEN)
566 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
568 string::size_type Pos = Line.find(' ');
569 if (Pos == string::npos || Pos+1 > Line.length())
571 // Blah, some servers use "connection:closes", evil.
572 Pos = Line.find(':');
573 if (Pos == string::npos || Pos + 2 > Line.length())
574 return _error->Error(_("Bad header line"));
578 // Parse off any trailing spaces between the : and the next word.
579 string::size_type Pos2 = Pos;
580 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
583 string Tag = string(Line,0,Pos);
584 string Val = string(Line,Pos2);
586 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
588 // Evil servers return no version
591 if (sscanf(Line.c_str(),"HTTP/%u.%u %u %[^\n]",&Major,&Minor,
593 return _error->Error(_("The HTTP server sent an invalid reply header"));
599 if (sscanf(Line.c_str(),"HTTP %u %[^\n]",&Result,Code) != 2)
600 return _error->Error(_("The HTTP server sent an invalid reply header"));
603 /* Check the HTTP response header to get the default persistance
609 if (Major == 1 && Minor <= 0)
618 if (stringcasecmp(Tag,"Content-Length:") == 0)
620 if (Encoding == Closes)
624 // The length is already set from the Content-Range header
628 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
629 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
633 if (stringcasecmp(Tag,"Content-Type:") == 0)
639 if (stringcasecmp(Tag,"Content-Range:") == 0)
643 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
644 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
645 if ((unsigned)StartPos > Size)
646 return _error->Error(_("This HTTP server has broken range support"));
650 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
653 if (stringcasecmp(Val,"chunked") == 0)
658 if (stringcasecmp(Tag,"Connection:") == 0)
660 if (stringcasecmp(Val,"close") == 0)
662 if (stringcasecmp(Val,"keep-alive") == 0)
667 if (stringcasecmp(Tag,"Last-Modified:") == 0)
669 if (StrToTime(Val,Date) == false)
670 return _error->Error(_("Unknown date format"));
678 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
679 // ---------------------------------------------------------------------
680 /* This places the http request in the outbound buffer */
681 void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
685 // The HTTP server expects a hostname with a trailing :port
687 string ProperHost = Uri.Host;
690 sprintf(Buf,":%u",Uri.Port);
695 if (Itm->Uri.length() >= sizeof(Buf))
698 /* Build the request. We include a keep-alive header only for non-proxy
699 requests. This is to tweak old http/1.0 servers that do support keep-alive
700 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
701 will glitch HTTP/1.0 proxies because they do not filter it out and
702 pass it on, HTTP/1.1 says the connection should default to keep alive
703 and we expect the proxy to do this */
704 if (Proxy.empty() == true || Proxy.Host.empty())
705 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
706 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
709 /* Generate a cache control header if necessary. We place a max
710 cache age on index files, optionally set a no-cache directive
711 and a no-store directive for archives. */
712 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
713 Itm->Uri.c_str(),ProperHost.c_str());
714 // only generate a cache control header if we actually want to
716 if (_config->FindB("Acquire::http::No-Cache",false) == false)
718 if (Itm->IndexFile == true)
719 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
720 _config->FindI("Acquire::http::Max-Age",0));
723 if (_config->FindB("Acquire::http::No-Store",false) == true)
724 strcat(Buf,"Cache-Control: no-store\r\n");
728 // generate a no-cache header if needed
729 if (_config->FindB("Acquire::http::No-Cache",false) == true)
730 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
735 // Check for a partial file
737 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
739 // In this case we send an if-range query with a range header
740 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
741 TimeRFC1123(SBuf.st_mtime).c_str());
746 if (Itm->LastModified != 0)
748 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
753 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
754 Req += string("Proxy-Authorization: Basic ") +
755 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
757 if (Uri.User.empty() == false || Uri.Password.empty() == false)
758 Req += string("Authorization: Basic ") +
759 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
761 Req += "User-Agent: Debian APT-HTTP/1.3\r\n\r\n";
769 // HttpMethod::Go - Run a single loop /*{{{*/
770 // ---------------------------------------------------------------------
771 /* This runs the select loop over the server FDs, Output file FDs and
773 bool HttpMethod::Go(bool ToFile,ServerState *Srv)
775 // Server has closed the connection
776 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
784 /* Add the server. We only send more requests if the connection will
786 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
787 && Srv->Persistent == true)
788 FD_SET(Srv->ServerFd,&wfds);
789 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
790 FD_SET(Srv->ServerFd,&rfds);
797 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
798 FD_SET(FileFD,&wfds);
801 FD_SET(STDIN_FILENO,&rfds);
803 // Figure out the max fd
805 if (MaxFd < Srv->ServerFd)
806 MaxFd = Srv->ServerFd;
813 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
817 return _error->Errno("select",_("Select failed"));
822 _error->Error(_("Connection timed out"));
823 return ServerDie(Srv);
827 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
830 if (Srv->In.Read(Srv->ServerFd) == false)
831 return ServerDie(Srv);
834 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
837 if (Srv->Out.Write(Srv->ServerFd) == false)
838 return ServerDie(Srv);
841 // Send data to the file
842 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
844 if (Srv->In.Write(FileFD) == false)
845 return _error->Errno("write",_("Error writing to output file"));
848 // Handle commands from APT
849 if (FD_ISSET(STDIN_FILENO,&rfds))
858 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
859 // ---------------------------------------------------------------------
860 /* This takes the current input buffer from the Server FD and writes it
862 bool HttpMethod::Flush(ServerState *Srv)
866 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
868 if (File->Name() != "/dev/null")
869 SetNonBlock(File->Fd(),false);
870 if (Srv->In.WriteSpace() == false)
873 while (Srv->In.WriteSpace() == true)
875 if (Srv->In.Write(File->Fd()) == false)
876 return _error->Errno("write",_("Error writing to file"));
877 if (Srv->In.IsLimit() == true)
881 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
887 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
888 // ---------------------------------------------------------------------
890 bool HttpMethod::ServerDie(ServerState *Srv)
892 unsigned int LErrno = errno;
894 // Dump the buffer to the file
895 if (Srv->State == ServerState::Data)
897 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
899 if (File->Name() != "/dev/null")
900 SetNonBlock(File->Fd(),false);
901 while (Srv->In.WriteSpace() == true)
903 if (Srv->In.Write(File->Fd()) == false)
904 return _error->Errno("write",_("Error writing to the file"));
907 if (Srv->In.IsLimit() == true)
912 // See if this is because the server finished the data stream
913 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
914 Srv->Encoding != ServerState::Closes)
918 return _error->Error(_("Error reading from server. Remote end closed connection"));
920 return _error->Errno("read",_("Error reading from server"));
926 // Nothing left in the buffer
927 if (Srv->In.WriteSpace() == false)
930 // We may have got multiple responses back in one packet..
938 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
939 // ---------------------------------------------------------------------
940 /* We look at the header data we got back from the server and decide what
944 3 - Unrecoverable error
945 4 - Error with error content page
946 5 - Unrecoverable non-server error (close the connection) */
947 int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
950 if (Srv->Result == 304)
952 unlink(Queue->DestFile.c_str());
954 Res.LastModified = Queue->LastModified;
958 /* We have a reply we dont handle. This should indicate a perm server
960 if (Srv->Result < 200 || Srv->Result >= 300)
962 _error->Error("%u %s",Srv->Result,Srv->Code);
963 if (Srv->HaveContent == true)
968 // This is some sort of 2xx 'data follows' reply
969 Res.LastModified = Srv->Date;
970 Res.Size = Srv->Size;
974 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
975 if (_error->PendingError() == true)
978 FailFile = Queue->DestFile;
979 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
981 FailTime = Srv->Date;
983 // Set the expected size
984 if (Srv->StartPos >= 0)
986 Res.ResumePoint = Srv->StartPos;
987 ftruncate(File->Fd(),Srv->StartPos);
990 // Set the start point
991 lseek(File->Fd(),0,SEEK_END);
994 Srv->In.Hash = new Hashes;
996 // Fill the Hash if the file is non-empty (resume)
997 if (Srv->StartPos > 0)
999 lseek(File->Fd(),0,SEEK_SET);
1000 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
1002 _error->Errno("read",_("Problem hashing file"));
1005 lseek(File->Fd(),0,SEEK_END);
1008 SetNonBlock(File->Fd(),true);
1012 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
1013 // ---------------------------------------------------------------------
1014 /* This closes and timestamps the open file. This is neccessary to get
1015 resume behavoir on user abort */
1016 void HttpMethod::SigTerm(int)
1023 struct utimbuf UBuf;
1024 UBuf.actime = FailTime;
1025 UBuf.modtime = FailTime;
1026 utime(FailFile.c_str(),&UBuf);
1031 // HttpMethod::Fetch - Fetch an item /*{{{*/
1032 // ---------------------------------------------------------------------
1033 /* This adds an item to the pipeline. We keep the pipeline at a fixed
1035 bool HttpMethod::Fetch(FetchItem *)
1040 // Queue the requests
1043 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1044 I = I->Next, Depth++)
1046 // If pipelining is disabled, we only queue 1 request
1047 if (Server->Pipeline == false && Depth >= 0)
1050 // Make sure we stick with the same server
1051 if (Server->Comp(I->Uri) == false)
1057 QueueBack = I->Next;
1058 SendReq(I,Server->Out);
1066 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1067 // ---------------------------------------------------------------------
1068 /* We stash the desired pipeline depth */
1069 bool HttpMethod::Configuration(string Message)
1071 if (pkgAcqMethod::Configuration(Message) == false)
1074 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1075 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1077 Debug = _config->FindB("Debug::Acquire::http",false);
1082 // HttpMethod::Loop - Main loop /*{{{*/
1083 // ---------------------------------------------------------------------
1085 int HttpMethod::Loop()
1087 signal(SIGTERM,SigTerm);
1088 signal(SIGINT,SigTerm);
1092 int FailCounter = 0;
1095 // We have no commands, wait for some to arrive
1098 if (WaitFd(STDIN_FILENO) == false)
1102 /* Run messages, we can accept 0 (no message) if we didn't
1103 do a WaitFd above.. Otherwise the FD is closed. */
1104 int Result = Run(true);
1105 if (Result != -1 && (Result != 0 || Queue == 0))
1111 CFStringEncoding se = kCFStringEncodingUTF8;
1113 char *url = strdup(Queue->Uri.c_str());
1115 CFStringRef sr = CFStringCreateWithCString(kCFAllocatorDefault, url, se);
1116 CFURLRef ur = CFURLCreateWithString(kCFAllocatorDefault, sr, NULL);
1118 CFHTTPMessageRef hm = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), ur, kCFHTTPVersion1_1);
1122 if (stat(Queue->DestFile.c_str(), &SBuf) >= 0 && SBuf.st_size > 0) {
1123 sr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("bytes=%li-"), (long) SBuf.st_size - 1);
1124 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("Range"), sr);
1127 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(SBuf.st_mtime).c_str(), se);
1128 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Range"), sr);
1130 } else if (Queue->LastModified != 0) {
1131 sr = CFStringCreateWithCString(kCFAllocatorDefault, TimeRFC1123(SBuf.st_mtime).c_str(), se);
1132 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("If-Modified-Since"), sr);
1136 CFHTTPMessageSetHeaderFieldValue(hm, CFSTR("User-Agent"), CFSTR("Telesphoreo APT-HTTP/1.0.98"));
1137 CFReadStreamRef rs = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, hm);
1140 CFDictionaryRef dr = SCDynamicStoreCopyProxies(NULL);
1141 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPProxy, dr);
1144 //CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
1145 CFReadStreamSetProperty(rs, kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
1147 URI uri = Queue->Uri;
1153 uint8_t data[10240];
1156 Status("Connecting to %s", uri.Host.c_str());
1158 if (!CFReadStreamOpen(rs)) {
1164 rd = CFReadStreamRead(rs, data, sizeof(data));
1172 Res.Filename = Queue->DestFile;
1174 hm = (CFHTTPMessageRef) CFReadStreamCopyProperty(rs, kCFStreamPropertyHTTPResponseHeader);
1175 sc = CFHTTPMessageGetResponseStatusCode(hm);
1178 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Location"));
1183 size_t ln = CFStringGetLength(sr) + 1;
1185 url = static_cast<char *>(malloc(ln));
1187 if (!CFStringGetCString(sr, url, ln, se)) {
1197 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Range"));
1199 size_t ln = CFStringGetLength(sr) + 1;
1202 if (!CFStringGetCString(sr, cr, ln, se)) {
1209 if (sscanf(cr, "bytes %lu-%*u/%lu", &offset, &Res.Size) != 2) {
1210 _error->Error(_("The HTTP server sent an invalid Content-Range header"));
1215 if (offset > Res.Size) {
1216 _error->Error(_("This HTTP server has broken range support"));
1221 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Content-Length"));
1223 Res.Size = CFStringGetIntValue(sr);
1228 time(&Res.LastModified);
1230 sr = CFHTTPMessageCopyHeaderFieldValue(hm, CFSTR("Last-Modified"));
1232 size_t ln = CFStringGetLength(sr) + 1;
1235 if (!CFStringGetCString(sr, cr, ln, se)) {
1242 if (!StrToTime(cr, Res.LastModified)) {
1243 _error->Error(_("Unknown date format"));
1252 unlink(Queue->DestFile.c_str());
1254 Res.LastModified = Queue->LastModified;
1256 } else if (sc < 200 || sc >= 300)
1261 File = new FileFd(Queue->DestFile, FileFd::WriteAny);
1262 if (_error->PendingError() == true) {
1269 FailFile = Queue->DestFile;
1270 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
1271 FailFd = File->Fd();
1272 FailTime = Res.LastModified;
1274 Res.ResumePoint = offset;
1275 ftruncate(File->Fd(), offset);
1278 lseek(File->Fd(), 0, SEEK_SET);
1279 if (!hash.AddFD(File->Fd(), offset)) {
1280 _error->Errno("read", _("Problem hashing file"));
1288 lseek(File->Fd(), 0, SEEK_END);
1292 read: if (rd == -1) {
1295 } else if (rd == 0) {
1297 Res.Size = File->Size();
1299 struct utimbuf UBuf;
1301 UBuf.actime = Res.LastModified;
1302 UBuf.modtime = Res.LastModified;
1303 utime(Queue->DestFile.c_str(), &UBuf);
1305 Res.TakeHashes(hash);
1312 int sz = write(File->Fd(), dt, rd);
1325 rd = CFReadStreamRead(rs, data, sizeof(data));
1334 CFReadStreamClose(rs);
1347 setlocale(LC_ALL, "");