]>
git.saurik.com Git - apt.git/blob - methods/http.cc
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>
48 #include "rfc2553emu.h"
54 string
HttpMethod::FailFile
;
55 int HttpMethod::FailFd
= -1;
56 time_t HttpMethod::FailTime
= 0;
57 unsigned long PipelineDepth
= 10;
58 unsigned long TimeOut
= 120;
62 unsigned long CircleBuf::BwReadLimit
=0;
63 unsigned long CircleBuf::BwTickReadData
=0;
64 struct timeval
CircleBuf::BwReadTick
={0,0};
65 const unsigned int CircleBuf::BW_HZ
=10;
67 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
68 // ---------------------------------------------------------------------
70 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
72 Buf
= new unsigned char[Size
];
75 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
78 // CircleBuf::Reset - Reset to the default state /*{{{*/
79 // ---------------------------------------------------------------------
81 void CircleBuf::Reset()
86 MaxGet
= (unsigned int)-1;
95 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
96 // ---------------------------------------------------------------------
97 /* This fills up the buffer with as much data as is in the FD, assuming it
99 bool CircleBuf::Read(int Fd
)
101 unsigned long BwReadMax
;
105 // Woops, buffer is full
106 if (InP
- OutP
== Size
)
109 // what's left to read in this tick
110 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
112 if(CircleBuf::BwReadLimit
) {
114 gettimeofday(&now
,0);
116 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
117 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
118 if(d
> 1000000/BW_HZ
) {
119 CircleBuf::BwReadTick
= now
;
120 CircleBuf::BwTickReadData
= 0;
123 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
124 usleep(1000000/BW_HZ
);
129 // Write the buffer segment
131 if(CircleBuf::BwReadLimit
) {
132 Res
= read(Fd
,Buf
+ (InP%Size
),
133 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
135 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
137 if(Res
> 0 && BwReadLimit
> 0)
138 CircleBuf::BwTickReadData
+= Res
;
150 gettimeofday(&Start
,0);
155 // CircleBuf::Read - Put the string into the buffer /*{{{*/
156 // ---------------------------------------------------------------------
157 /* This will hold the string in and fill the buffer with it as it empties */
158 bool CircleBuf::Read(string Data
)
165 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
166 // ---------------------------------------------------------------------
168 void CircleBuf::FillOut()
170 if (OutQueue
.empty() == true)
174 // Woops, buffer is full
175 if (InP
- OutP
== Size
)
178 // Write the buffer segment
179 unsigned long Sz
= LeftRead();
180 if (OutQueue
.length() - StrPos
< Sz
)
181 Sz
= OutQueue
.length() - StrPos
;
182 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
187 if (OutQueue
.length() == StrPos
)
196 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
197 // ---------------------------------------------------------------------
198 /* This empties the buffer into the FD. */
199 bool CircleBuf::Write(int Fd
)
205 // Woops, buffer is empty
212 // Write the buffer segment
214 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
227 Hash
->Add(Buf
+ (OutP%Size
),Res
);
233 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
234 // ---------------------------------------------------------------------
235 /* This copies till the first empty line */
236 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
238 // We cheat and assume it is unneeded to have more than one buffer load
239 for (unsigned long I
= OutP
; I
< InP
; I
++)
241 if (Buf
[I%Size
] != '\n')
247 if (I
< InP
&& Buf
[I%Size
] == '\r')
249 if (I
>= InP
|| Buf
[I%Size
] != '\n')
257 unsigned long Sz
= LeftWrite();
262 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
270 // CircleBuf::Stats - Print out stats information /*{{{*/
271 // ---------------------------------------------------------------------
273 void CircleBuf::Stats()
279 gettimeofday(&Stop
,0);
280 /* float Diff = Stop.tv_sec - Start.tv_sec +
281 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
282 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
286 // ServerState::ServerState - Constructor /*{{{*/
287 // ---------------------------------------------------------------------
289 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
290 In(64*1024), Out(4*1024),
296 // ServerState::Open - Open a connection to the server /*{{{*/
297 // ---------------------------------------------------------------------
298 /* This opens a connection to the server. */
299 bool ServerState::Open()
301 // Use the already open connection if possible.
310 // Determine the proxy setting
311 if (getenv("http_proxy") == 0)
313 string DefProxy
= _config
->Find("Acquire::http::Proxy");
314 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
315 if (SpecificProxy
.empty() == false)
317 if (SpecificProxy
== "DIRECT")
320 Proxy
= SpecificProxy
;
326 Proxy
= getenv("http_proxy");
328 // Parse no_proxy, a , separated list of domains
329 if (getenv("no_proxy") != 0)
331 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
335 // Determine what host and port to use based on the proxy settings
338 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
340 if (ServerName
.Port
!= 0)
341 Port
= ServerName
.Port
;
342 Host
= ServerName
.Host
;
351 // Connect to the remote server
352 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
358 // ServerState::Close - Close a connection to the server /*{{{*/
359 // ---------------------------------------------------------------------
361 bool ServerState::Close()
368 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
369 // ---------------------------------------------------------------------
370 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
371 parse error occured */
372 int ServerState::RunHeaders()
376 Owner
->Status(_("Waiting for headers"));
390 if (In
.WriteTillEl(Data
) == false)
396 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
398 string::const_iterator J
= I
;
399 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
400 if (HeaderLine(string(I
,J
)) == false)
405 // 100 Continue is a Nop...
409 // Tidy up the connection persistance state.
410 if (Encoding
== Closes
&& HaveContent
== true)
415 while (Owner
->Go(false,this) == true);
420 // ServerState::RunData - Transfer the data from the socket /*{{{*/
421 // ---------------------------------------------------------------------
423 bool ServerState::RunData()
427 // Chunked transfer encoding is fun..
428 if (Encoding
== Chunked
)
432 // Grab the block size
438 if (In
.WriteTillEl(Data
,true) == true)
441 while ((Last
= Owner
->Go(false,this)) == true);
446 // See if we are done
447 unsigned long Len
= strtol(Data
.c_str(),0,16);
452 // We have to remove the entity trailer
456 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
459 while ((Last
= Owner
->Go(false,this)) == true);
462 return !_error
->PendingError();
465 // Transfer the block
467 while (Owner
->Go(true,this) == true)
468 if (In
.IsLimit() == true)
472 if (In
.IsLimit() == false)
475 // The server sends an extra new line before the next block specifier..
480 if (In
.WriteTillEl(Data
,true) == true)
483 while ((Last
= Owner
->Go(false,this)) == true);
490 /* Closes encoding is used when the server did not specify a size, the
491 loss of the connection means we are done */
492 if (Encoding
== Closes
)
495 In
.Limit(Size
- StartPos
);
497 // Just transfer the whole block.
500 if (In
.IsLimit() == false)
504 return !_error
->PendingError();
506 while (Owner
->Go(true,this) == true);
509 return Owner
->Flush(this) && !_error
->PendingError();
512 // ServerState::HeaderLine - Process a header line /*{{{*/
513 // ---------------------------------------------------------------------
515 bool ServerState::HeaderLine(string Line
)
517 if (Line
.empty() == true)
520 // The http server might be trying to do something evil.
521 if (Line
.length() >= MAXLEN
)
522 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
524 string::size_type Pos
= Line
.find(' ');
525 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
527 // Blah, some servers use "connection:closes", evil.
528 Pos
= Line
.find(':');
529 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
530 return _error
->Error(_("Bad header line"));
534 // Parse off any trailing spaces between the : and the next word.
535 string::size_type Pos2
= Pos
;
536 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
539 string Tag
= string(Line
,0,Pos
);
540 string Val
= string(Line
,Pos2
);
542 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
544 // Evil servers return no version
547 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
549 return _error
->Error(_("The HTTP server sent an invalid reply header"));
555 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
556 return _error
->Error(_("The HTTP server sent an invalid reply header"));
559 /* Check the HTTP response header to get the default persistance
565 if (Major
== 1 && Minor
<= 0)
574 if (stringcasecmp(Tag
,"Content-Length:") == 0)
576 if (Encoding
== Closes
)
580 // The length is already set from the Content-Range header
584 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
585 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
589 if (stringcasecmp(Tag
,"Content-Type:") == 0)
595 if (stringcasecmp(Tag
,"Content-Range:") == 0)
599 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
600 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
601 if ((unsigned)StartPos
> Size
)
602 return _error
->Error(_("This HTTP server has broken range support"));
606 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
609 if (stringcasecmp(Val
,"chunked") == 0)
614 if (stringcasecmp(Tag
,"Connection:") == 0)
616 if (stringcasecmp(Val
,"close") == 0)
618 if (stringcasecmp(Val
,"keep-alive") == 0)
623 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
625 if (StrToTime(Val
,Date
) == false)
626 return _error
->Error(_("Unknown date format"));
634 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
635 // ---------------------------------------------------------------------
636 /* This places the http request in the outbound buffer */
637 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
641 // The HTTP server expects a hostname with a trailing :port
643 string ProperHost
= Uri
.Host
;
646 sprintf(Buf
,":%u",Uri
.Port
);
651 if (Itm
->Uri
.length() >= sizeof(Buf
))
654 /* Build the request. We include a keep-alive header only for non-proxy
655 requests. This is to tweak old http/1.0 servers that do support keep-alive
656 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
657 will glitch HTTP/1.0 proxies because they do not filter it out and
658 pass it on, HTTP/1.1 says the connection should default to keep alive
659 and we expect the proxy to do this */
660 if (Proxy
.empty() == true || Proxy
.Host
.empty())
661 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
662 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
665 /* Generate a cache control header if necessary. We place a max
666 cache age on index files, optionally set a no-cache directive
667 and a no-store directive for archives. */
668 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
669 Itm
->Uri
.c_str(),ProperHost
.c_str());
670 // only generate a cache control header if we actually want to
672 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
674 if (Itm
->IndexFile
== true)
675 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
676 _config
->FindI("Acquire::http::Max-Age",0));
679 if (_config
->FindB("Acquire::http::No-Store",false) == true)
680 strcat(Buf
,"Cache-Control: no-store\r\n");
684 // generate a no-cache header if needed
685 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
686 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
691 // Check for a partial file
693 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
695 // In this case we send an if-range query with a range header
696 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
697 TimeRFC1123(SBuf
.st_mtime
).c_str());
702 if (Itm
->LastModified
!= 0)
704 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
709 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
710 Req
+= string("Proxy-Authorization: Basic ") +
711 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
713 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
714 Req
+= string("Authorization: Basic ") +
715 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
717 Req
+= "User-Agent: Ubuntu APT-HTTP/1.3\r\n\r\n";
725 // HttpMethod::Go - Run a single loop /*{{{*/
726 // ---------------------------------------------------------------------
727 /* This runs the select loop over the server FDs, Output file FDs and
729 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
731 // Server has closed the connection
732 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
740 /* Add the server. We only send more requests if the connection will
742 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
743 && Srv
->Persistent
== true)
744 FD_SET(Srv
->ServerFd
,&wfds
);
745 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
746 FD_SET(Srv
->ServerFd
,&rfds
);
753 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
754 FD_SET(FileFD
,&wfds
);
757 FD_SET(STDIN_FILENO
,&rfds
);
759 // Figure out the max fd
761 if (MaxFd
< Srv
->ServerFd
)
762 MaxFd
= Srv
->ServerFd
;
769 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
773 return _error
->Errno("select",_("Select failed"));
778 _error
->Error(_("Connection timed out"));
779 return ServerDie(Srv
);
783 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
786 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
787 return ServerDie(Srv
);
790 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
793 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
794 return ServerDie(Srv
);
797 // Send data to the file
798 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
800 if (Srv
->In
.Write(FileFD
) == false)
801 return _error
->Errno("write",_("Error writing to output file"));
804 // Handle commands from APT
805 if (FD_ISSET(STDIN_FILENO
,&rfds
))
814 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
815 // ---------------------------------------------------------------------
816 /* This takes the current input buffer from the Server FD and writes it
818 bool HttpMethod::Flush(ServerState
*Srv
)
822 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
824 if (File
->Name() != "/dev/null")
825 SetNonBlock(File
->Fd(),false);
826 if (Srv
->In
.WriteSpace() == false)
829 while (Srv
->In
.WriteSpace() == true)
831 if (Srv
->In
.Write(File
->Fd()) == false)
832 return _error
->Errno("write",_("Error writing to file"));
833 if (Srv
->In
.IsLimit() == true)
837 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
843 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
844 // ---------------------------------------------------------------------
846 bool HttpMethod::ServerDie(ServerState
*Srv
)
848 unsigned int LErrno
= errno
;
850 // Dump the buffer to the file
851 if (Srv
->State
== ServerState::Data
)
853 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
855 if (File
->Name() != "/dev/null")
856 SetNonBlock(File
->Fd(),false);
857 while (Srv
->In
.WriteSpace() == true)
859 if (Srv
->In
.Write(File
->Fd()) == false)
860 return _error
->Errno("write",_("Error writing to the file"));
863 if (Srv
->In
.IsLimit() == true)
868 // See if this is because the server finished the data stream
869 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
870 Srv
->Encoding
!= ServerState::Closes
)
874 return _error
->Error(_("Error reading from server. Remote end closed connection"));
876 return _error
->Errno("read",_("Error reading from server"));
882 // Nothing left in the buffer
883 if (Srv
->In
.WriteSpace() == false)
886 // We may have got multiple responses back in one packet..
894 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
895 // ---------------------------------------------------------------------
896 /* We look at the header data we got back from the server and decide what
900 3 - Unrecoverable error
901 4 - Error with error content page
902 5 - Unrecoverable non-server error (close the connection) */
903 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
906 if (Srv
->Result
== 304)
908 unlink(Queue
->DestFile
.c_str());
910 Res
.LastModified
= Queue
->LastModified
;
914 /* We have a reply we dont handle. This should indicate a perm server
916 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
918 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
919 if (Srv
->HaveContent
== true)
924 // This is some sort of 2xx 'data follows' reply
925 Res
.LastModified
= Srv
->Date
;
926 Res
.Size
= Srv
->Size
;
930 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
931 if (_error
->PendingError() == true)
934 FailFile
= Queue
->DestFile
;
935 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
937 FailTime
= Srv
->Date
;
939 // Set the expected size
940 if (Srv
->StartPos
>= 0)
942 Res
.ResumePoint
= Srv
->StartPos
;
943 ftruncate(File
->Fd(),Srv
->StartPos
);
946 // Set the start point
947 lseek(File
->Fd(),0,SEEK_END
);
950 Srv
->In
.Hash
= new Hashes
;
952 // Fill the Hash if the file is non-empty (resume)
953 if (Srv
->StartPos
> 0)
955 lseek(File
->Fd(),0,SEEK_SET
);
956 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
958 _error
->Errno("read",_("Problem hashing file"));
961 lseek(File
->Fd(),0,SEEK_END
);
964 SetNonBlock(File
->Fd(),true);
968 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
969 // ---------------------------------------------------------------------
970 /* This closes and timestamps the open file. This is neccessary to get
971 resume behavoir on user abort */
972 void HttpMethod::SigTerm(int)
980 UBuf
.actime
= FailTime
;
981 UBuf
.modtime
= FailTime
;
982 utime(FailFile
.c_str(),&UBuf
);
987 // HttpMethod::Fetch - Fetch an item /*{{{*/
988 // ---------------------------------------------------------------------
989 /* This adds an item to the pipeline. We keep the pipeline at a fixed
991 bool HttpMethod::Fetch(FetchItem
*)
996 // Queue the requests
999 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1000 I
= I
->Next
, Depth
++)
1002 // If pipelining is disabled, we only queue 1 request
1003 if (Server
->Pipeline
== false && Depth
>= 0)
1006 // Make sure we stick with the same server
1007 if (Server
->Comp(I
->Uri
) == false)
1013 QueueBack
= I
->Next
;
1014 SendReq(I
,Server
->Out
);
1022 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1023 // ---------------------------------------------------------------------
1024 /* We stash the desired pipeline depth */
1025 bool HttpMethod::Configuration(string Message
)
1027 if (pkgAcqMethod::Configuration(Message
) == false)
1030 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1031 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1033 Debug
= _config
->FindB("Debug::Acquire::http",false);
1038 // HttpMethod::Loop - Main loop /*{{{*/
1039 // ---------------------------------------------------------------------
1041 int HttpMethod::Loop()
1043 signal(SIGTERM
,SigTerm
);
1044 signal(SIGINT
,SigTerm
);
1048 int FailCounter
= 0;
1051 // We have no commands, wait for some to arrive
1054 if (WaitFd(STDIN_FILENO
) == false)
1058 /* Run messages, we can accept 0 (no message) if we didn't
1059 do a WaitFd above.. Otherwise the FD is closed. */
1060 int Result
= Run(true);
1061 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1067 // Connect to the server
1068 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
1071 Server
= new ServerState(Queue
->Uri
,this);
1074 /* If the server has explicitly said this is the last connection
1075 then we pre-emptively shut down the pipeline and tear down
1076 the connection. This will speed up HTTP/1.0 servers a tad
1077 since we don't have to wait for the close sequence to
1079 if (Server
->Persistent
== false)
1082 // Reset the pipeline
1083 if (Server
->ServerFd
== -1)
1086 // Connnect to the host
1087 if (Server
->Open() == false)
1095 // Fill the pipeline.
1098 // Fetch the next URL header data from the server.
1099 switch (Server
->RunHeaders())
1104 // The header data is bad
1107 _error
->Error(_("Bad header data"));
1113 // The server closed a connection during the header get..
1120 Server
->Pipeline
= false;
1122 if (FailCounter
>= 2)
1124 Fail(_("Connection failed"),true);
1133 // Decide what to do.
1135 Res
.Filename
= Queue
->DestFile
;
1136 switch (DealWithHeaders(Res
,Server
))
1138 // Ok, the file is Open
1144 bool Result
= Server
->RunData();
1146 /* If the server is sending back sizeless responses then fill in
1149 Res
.Size
= File
->Size();
1151 // Close the file, destroy the FD object and timestamp it
1157 struct utimbuf UBuf
;
1159 UBuf
.actime
= Server
->Date
;
1160 UBuf
.modtime
= Server
->Date
;
1161 utime(Queue
->DestFile
.c_str(),&UBuf
);
1163 // Send status to APT
1166 Res
.TakeHashes(*Server
->In
.Hash
);
1182 // Hard server error, not found or something
1189 // Hard internal error, kill the connection and fail
1201 // We need to flush the data, the header is like a 404 w/ error text
1206 // Send to content to dev/null
1207 File
= new FileFd("/dev/null",FileFd::WriteExists
);
1215 Fail(_("Internal error"));
1228 setlocale(LC_ALL
, "");