]>
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>
49 #include "rfc2553emu.h"
55 string
HttpMethod::FailFile
;
56 int HttpMethod::FailFd
= -1;
57 time_t HttpMethod::FailTime
= 0;
58 unsigned long PipelineDepth
= 10;
59 unsigned long TimeOut
= 120;
63 unsigned long CircleBuf::BwReadLimit
=0;
64 unsigned long CircleBuf::BwTickReadData
=0;
65 struct timeval
CircleBuf::BwReadTick
={0,0};
66 const unsigned int CircleBuf::BW_HZ
=10;
68 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
69 // ---------------------------------------------------------------------
71 CircleBuf::CircleBuf(unsigned long Size
) : Size(Size
), Hash(0)
73 Buf
= new unsigned char[Size
];
76 CircleBuf::BwReadLimit
= _config
->FindI("Acquire::http::Dl-Limit",0)*1024;
79 // CircleBuf::Reset - Reset to the default state /*{{{*/
80 // ---------------------------------------------------------------------
82 void CircleBuf::Reset()
87 MaxGet
= (unsigned int)-1;
96 // CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
97 // ---------------------------------------------------------------------
98 /* This fills up the buffer with as much data as is in the FD, assuming it
100 bool CircleBuf::Read(int Fd
)
102 unsigned long BwReadMax
;
106 // Woops, buffer is full
107 if (InP
- OutP
== Size
)
110 // what's left to read in this tick
111 BwReadMax
= CircleBuf::BwReadLimit
/BW_HZ
;
113 if(CircleBuf::BwReadLimit
) {
115 gettimeofday(&now
,0);
117 unsigned long d
= (now
.tv_sec
-CircleBuf::BwReadTick
.tv_sec
)*1000000 +
118 now
.tv_usec
-CircleBuf::BwReadTick
.tv_usec
;
119 if(d
> 1000000/BW_HZ
) {
120 CircleBuf::BwReadTick
= now
;
121 CircleBuf::BwTickReadData
= 0;
124 if(CircleBuf::BwTickReadData
>= BwReadMax
) {
125 usleep(1000000/BW_HZ
);
130 // Write the buffer segment
132 if(CircleBuf::BwReadLimit
) {
133 Res
= read(Fd
,Buf
+ (InP%Size
),
134 BwReadMax
> LeftRead() ? LeftRead() : BwReadMax
);
136 Res
= read(Fd
,Buf
+ (InP%Size
),LeftRead());
138 if(Res
> 0 && BwReadLimit
> 0)
139 CircleBuf::BwTickReadData
+= Res
;
151 gettimeofday(&Start
,0);
156 // CircleBuf::Read - Put the string into the buffer /*{{{*/
157 // ---------------------------------------------------------------------
158 /* This will hold the string in and fill the buffer with it as it empties */
159 bool CircleBuf::Read(string Data
)
166 // CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
167 // ---------------------------------------------------------------------
169 void CircleBuf::FillOut()
171 if (OutQueue
.empty() == true)
175 // Woops, buffer is full
176 if (InP
- OutP
== Size
)
179 // Write the buffer segment
180 unsigned long Sz
= LeftRead();
181 if (OutQueue
.length() - StrPos
< Sz
)
182 Sz
= OutQueue
.length() - StrPos
;
183 memcpy(Buf
+ (InP%Size
),OutQueue
.c_str() + StrPos
,Sz
);
188 if (OutQueue
.length() == StrPos
)
197 // CircleBuf::Write - Write from the buffer into a FD /*{{{*/
198 // ---------------------------------------------------------------------
199 /* This empties the buffer into the FD. */
200 bool CircleBuf::Write(int Fd
)
206 // Woops, buffer is empty
213 // Write the buffer segment
215 Res
= write(Fd
,Buf
+ (OutP%Size
),LeftWrite());
228 Hash
->Add(Buf
+ (OutP%Size
),Res
);
234 // CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
235 // ---------------------------------------------------------------------
236 /* This copies till the first empty line */
237 bool CircleBuf::WriteTillEl(string
&Data
,bool Single
)
239 // We cheat and assume it is unneeded to have more than one buffer load
240 for (unsigned long I
= OutP
; I
< InP
; I
++)
242 if (Buf
[I%Size
] != '\n')
248 if (I
< InP
&& Buf
[I%Size
] == '\r')
250 if (I
>= InP
|| Buf
[I%Size
] != '\n')
258 unsigned long Sz
= LeftWrite();
263 Data
+= string((char *)(Buf
+ (OutP%Size
)),Sz
);
271 // CircleBuf::Stats - Print out stats information /*{{{*/
272 // ---------------------------------------------------------------------
274 void CircleBuf::Stats()
280 gettimeofday(&Stop
,0);
281 /* float Diff = Stop.tv_sec - Start.tv_sec +
282 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
283 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
287 // ServerState::ServerState - Constructor /*{{{*/
288 // ---------------------------------------------------------------------
290 ServerState::ServerState(URI Srv
,HttpMethod
*Owner
) : Owner(Owner
),
291 In(64*1024), Out(4*1024),
297 // ServerState::Open - Open a connection to the server /*{{{*/
298 // ---------------------------------------------------------------------
299 /* This opens a connection to the server. */
300 bool ServerState::Open()
302 // Use the already open connection if possible.
311 // Determine the proxy setting
312 if (getenv("http_proxy") == 0)
314 string DefProxy
= _config
->Find("Acquire::http::Proxy");
315 string SpecificProxy
= _config
->Find("Acquire::http::Proxy::" + ServerName
.Host
);
316 if (SpecificProxy
.empty() == false)
318 if (SpecificProxy
== "DIRECT")
321 Proxy
= SpecificProxy
;
327 Proxy
= getenv("http_proxy");
329 // Parse no_proxy, a , separated list of domains
330 if (getenv("no_proxy") != 0)
332 if (CheckDomainList(ServerName
.Host
,getenv("no_proxy")) == true)
336 // Determine what host and port to use based on the proxy settings
339 if (Proxy
.empty() == true || Proxy
.Host
.empty() == true)
341 if (ServerName
.Port
!= 0)
342 Port
= ServerName
.Port
;
343 Host
= ServerName
.Host
;
352 // Connect to the remote server
353 if (Connect(Host
,Port
,"http",80,ServerFd
,TimeOut
,Owner
) == false)
359 // ServerState::Close - Close a connection to the server /*{{{*/
360 // ---------------------------------------------------------------------
362 bool ServerState::Close()
369 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
370 // ---------------------------------------------------------------------
371 /* Returns 0 if things are OK, 1 if an IO error occursed and 2 if a header
372 parse error occured */
373 int ServerState::RunHeaders()
377 Owner
->Status(_("Waiting for headers"));
391 if (In
.WriteTillEl(Data
) == false)
397 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); I
++)
399 string::const_iterator J
= I
;
400 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r';J
++);
401 if (HeaderLine(string(I
,J
)) == false)
406 // 100 Continue is a Nop...
410 // Tidy up the connection persistance state.
411 if (Encoding
== Closes
&& HaveContent
== true)
416 while (Owner
->Go(false,this) == true);
421 // ServerState::RunData - Transfer the data from the socket /*{{{*/
422 // ---------------------------------------------------------------------
424 bool ServerState::RunData()
428 // Chunked transfer encoding is fun..
429 if (Encoding
== Chunked
)
433 // Grab the block size
439 if (In
.WriteTillEl(Data
,true) == true)
442 while ((Last
= Owner
->Go(false,this)) == true);
447 // See if we are done
448 unsigned long Len
= strtol(Data
.c_str(),0,16);
453 // We have to remove the entity trailer
457 if (In
.WriteTillEl(Data
,true) == true && Data
.length() <= 2)
460 while ((Last
= Owner
->Go(false,this)) == true);
463 return !_error
->PendingError();
466 // Transfer the block
468 while (Owner
->Go(true,this) == true)
469 if (In
.IsLimit() == true)
473 if (In
.IsLimit() == false)
476 // The server sends an extra new line before the next block specifier..
481 if (In
.WriteTillEl(Data
,true) == true)
484 while ((Last
= Owner
->Go(false,this)) == true);
491 /* Closes encoding is used when the server did not specify a size, the
492 loss of the connection means we are done */
493 if (Encoding
== Closes
)
496 In
.Limit(Size
- StartPos
);
498 // Just transfer the whole block.
501 if (In
.IsLimit() == false)
505 return !_error
->PendingError();
507 while (Owner
->Go(true,this) == true);
510 return Owner
->Flush(this) && !_error
->PendingError();
513 // ServerState::HeaderLine - Process a header line /*{{{*/
514 // ---------------------------------------------------------------------
516 bool ServerState::HeaderLine(string Line
)
518 if (Line
.empty() == true)
521 // The http server might be trying to do something evil.
522 if (Line
.length() >= MAXLEN
)
523 return _error
->Error(_("Got a single header line over %u chars"),MAXLEN
);
525 string::size_type Pos
= Line
.find(' ');
526 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
528 // Blah, some servers use "connection:closes", evil.
529 Pos
= Line
.find(':');
530 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
531 return _error
->Error(_("Bad header line"));
535 // Parse off any trailing spaces between the : and the next word.
536 string::size_type Pos2
= Pos
;
537 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
540 string Tag
= string(Line
,0,Pos
);
541 string Val
= string(Line
,Pos2
);
543 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
545 // Evil servers return no version
548 if (sscanf(Line
.c_str(),"HTTP/%u.%u %u %[^\n]",&Major
,&Minor
,
550 return _error
->Error(_("The HTTP server sent an invalid reply header"));
556 if (sscanf(Line
.c_str(),"HTTP %u %[^\n]",&Result
,Code
) != 2)
557 return _error
->Error(_("The HTTP server sent an invalid reply header"));
560 /* Check the HTTP response header to get the default persistance
566 if (Major
== 1 && Minor
<= 0)
575 if (stringcasecmp(Tag
,"Content-Length:") == 0)
577 if (Encoding
== Closes
)
581 // The length is already set from the Content-Range header
585 if (sscanf(Val
.c_str(),"%lu",&Size
) != 1)
586 return _error
->Error(_("The HTTP server sent an invalid Content-Length header"));
590 if (stringcasecmp(Tag
,"Content-Type:") == 0)
596 if (stringcasecmp(Tag
,"Content-Range:") == 0)
600 if (sscanf(Val
.c_str(),"bytes %lu-%*u/%lu",&StartPos
,&Size
) != 2)
601 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
602 if ((unsigned)StartPos
> Size
)
603 return _error
->Error(_("This HTTP server has broken range support"));
607 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
610 if (stringcasecmp(Val
,"chunked") == 0)
615 if (stringcasecmp(Tag
,"Connection:") == 0)
617 if (stringcasecmp(Val
,"close") == 0)
619 if (stringcasecmp(Val
,"keep-alive") == 0)
624 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
626 if (StrToTime(Val
,Date
) == false)
627 return _error
->Error(_("Unknown date format"));
635 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
636 // ---------------------------------------------------------------------
637 /* This places the http request in the outbound buffer */
638 void HttpMethod::SendReq(FetchItem
*Itm
,CircleBuf
&Out
)
642 // The HTTP server expects a hostname with a trailing :port
644 string ProperHost
= Uri
.Host
;
647 sprintf(Buf
,":%u",Uri
.Port
);
652 if (Itm
->Uri
.length() >= sizeof(Buf
))
655 /* Build the request. We include a keep-alive header only for non-proxy
656 requests. This is to tweak old http/1.0 servers that do support keep-alive
657 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
658 will glitch HTTP/1.0 proxies because they do not filter it out and
659 pass it on, HTTP/1.1 says the connection should default to keep alive
660 and we expect the proxy to do this */
661 if (Proxy
.empty() == true || Proxy
.Host
.empty())
662 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
663 QuoteString(Uri
.Path
,"~").c_str(),ProperHost
.c_str());
666 /* Generate a cache control header if necessary. We place a max
667 cache age on index files, optionally set a no-cache directive
668 and a no-store directive for archives. */
669 sprintf(Buf
,"GET %s HTTP/1.1\r\nHost: %s\r\n",
670 Itm
->Uri
.c_str(),ProperHost
.c_str());
671 // only generate a cache control header if we actually want to
673 if (_config
->FindB("Acquire::http::No-Cache",false) == false)
675 if (Itm
->IndexFile
== true)
676 sprintf(Buf
+strlen(Buf
),"Cache-Control: max-age=%u\r\n",
677 _config
->FindI("Acquire::http::Max-Age",0));
680 if (_config
->FindB("Acquire::http::No-Store",false) == true)
681 strcat(Buf
,"Cache-Control: no-store\r\n");
685 // generate a no-cache header if needed
686 if (_config
->FindB("Acquire::http::No-Cache",false) == true)
687 strcat(Buf
,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
692 // Check for a partial file
694 if (stat(Itm
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
696 // In this case we send an if-range query with a range header
697 sprintf(Buf
,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf
.st_size
- 1,
698 TimeRFC1123(SBuf
.st_mtime
).c_str());
703 if (Itm
->LastModified
!= 0)
705 sprintf(Buf
,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm
->LastModified
).c_str());
710 if (Proxy
.User
.empty() == false || Proxy
.Password
.empty() == false)
711 Req
+= string("Proxy-Authorization: Basic ") +
712 Base64Encode(Proxy
.User
+ ":" + Proxy
.Password
) + "\r\n";
714 if (Uri
.User
.empty() == false || Uri
.Password
.empty() == false)
715 Req
+= string("Authorization: Basic ") +
716 Base64Encode(Uri
.User
+ ":" + Uri
.Password
) + "\r\n";
718 Req
+= "User-Agent: Ubuntu APT-HTTP/1.3 ("VERSION
")\r\n\r\n";
726 // HttpMethod::Go - Run a single loop /*{{{*/
727 // ---------------------------------------------------------------------
728 /* This runs the select loop over the server FDs, Output file FDs and
730 bool HttpMethod::Go(bool ToFile
,ServerState
*Srv
)
732 // Server has closed the connection
733 if (Srv
->ServerFd
== -1 && (Srv
->In
.WriteSpace() == false ||
741 /* Add the server. We only send more requests if the connection will
743 if (Srv
->Out
.WriteSpace() == true && Srv
->ServerFd
!= -1
744 && Srv
->Persistent
== true)
745 FD_SET(Srv
->ServerFd
,&wfds
);
746 if (Srv
->In
.ReadSpace() == true && Srv
->ServerFd
!= -1)
747 FD_SET(Srv
->ServerFd
,&rfds
);
754 if (Srv
->In
.WriteSpace() == true && ToFile
== true && FileFD
!= -1)
755 FD_SET(FileFD
,&wfds
);
758 FD_SET(STDIN_FILENO
,&rfds
);
760 // Figure out the max fd
762 if (MaxFd
< Srv
->ServerFd
)
763 MaxFd
= Srv
->ServerFd
;
770 if ((Res
= select(MaxFd
+1,&rfds
,&wfds
,0,&tv
)) < 0)
774 return _error
->Errno("select",_("Select failed"));
779 _error
->Error(_("Connection timed out"));
780 return ServerDie(Srv
);
784 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&rfds
))
787 if (Srv
->In
.Read(Srv
->ServerFd
) == false)
788 return ServerDie(Srv
);
791 if (Srv
->ServerFd
!= -1 && FD_ISSET(Srv
->ServerFd
,&wfds
))
794 if (Srv
->Out
.Write(Srv
->ServerFd
) == false)
795 return ServerDie(Srv
);
798 // Send data to the file
799 if (FileFD
!= -1 && FD_ISSET(FileFD
,&wfds
))
801 if (Srv
->In
.Write(FileFD
) == false)
802 return _error
->Errno("write",_("Error writing to output file"));
805 // Handle commands from APT
806 if (FD_ISSET(STDIN_FILENO
,&rfds
))
815 // HttpMethod::Flush - Dump the buffer into the file /*{{{*/
816 // ---------------------------------------------------------------------
817 /* This takes the current input buffer from the Server FD and writes it
819 bool HttpMethod::Flush(ServerState
*Srv
)
823 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
825 if (File
->Name() != "/dev/null")
826 SetNonBlock(File
->Fd(),false);
827 if (Srv
->In
.WriteSpace() == false)
830 while (Srv
->In
.WriteSpace() == true)
832 if (Srv
->In
.Write(File
->Fd()) == false)
833 return _error
->Errno("write",_("Error writing to file"));
834 if (Srv
->In
.IsLimit() == true)
838 if (Srv
->In
.IsLimit() == true || Srv
->Encoding
== ServerState::Closes
)
844 // HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
845 // ---------------------------------------------------------------------
847 bool HttpMethod::ServerDie(ServerState
*Srv
)
849 unsigned int LErrno
= errno
;
851 // Dump the buffer to the file
852 if (Srv
->State
== ServerState::Data
)
854 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
856 if (File
->Name() != "/dev/null")
857 SetNonBlock(File
->Fd(),false);
858 while (Srv
->In
.WriteSpace() == true)
860 if (Srv
->In
.Write(File
->Fd()) == false)
861 return _error
->Errno("write",_("Error writing to the file"));
864 if (Srv
->In
.IsLimit() == true)
869 // See if this is because the server finished the data stream
870 if (Srv
->In
.IsLimit() == false && Srv
->State
!= ServerState::Header
&&
871 Srv
->Encoding
!= ServerState::Closes
)
875 return _error
->Error(_("Error reading from server. Remote end closed connection"));
877 return _error
->Errno("read",_("Error reading from server"));
883 // Nothing left in the buffer
884 if (Srv
->In
.WriteSpace() == false)
887 // We may have got multiple responses back in one packet..
895 // HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
896 // ---------------------------------------------------------------------
897 /* We look at the header data we got back from the server and decide what
901 3 - Unrecoverable error
902 4 - Error with error content page
903 5 - Unrecoverable non-server error (close the connection) */
904 int HttpMethod::DealWithHeaders(FetchResult
&Res
,ServerState
*Srv
)
907 if (Srv
->Result
== 304)
909 unlink(Queue
->DestFile
.c_str());
911 Res
.LastModified
= Queue
->LastModified
;
915 /* We have a reply we dont handle. This should indicate a perm server
917 if (Srv
->Result
< 200 || Srv
->Result
>= 300)
919 _error
->Error("%u %s",Srv
->Result
,Srv
->Code
);
920 if (Srv
->HaveContent
== true)
925 // This is some sort of 2xx 'data follows' reply
926 Res
.LastModified
= Srv
->Date
;
927 Res
.Size
= Srv
->Size
;
931 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
932 if (_error
->PendingError() == true)
935 FailFile
= Queue
->DestFile
;
936 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
938 FailTime
= Srv
->Date
;
940 // Set the expected size
941 if (Srv
->StartPos
>= 0)
943 Res
.ResumePoint
= Srv
->StartPos
;
944 ftruncate(File
->Fd(),Srv
->StartPos
);
947 // Set the start point
948 lseek(File
->Fd(),0,SEEK_END
);
951 Srv
->In
.Hash
= new Hashes
;
953 // Fill the Hash if the file is non-empty (resume)
954 if (Srv
->StartPos
> 0)
956 lseek(File
->Fd(),0,SEEK_SET
);
957 if (Srv
->In
.Hash
->AddFD(File
->Fd(),Srv
->StartPos
) == false)
959 _error
->Errno("read",_("Problem hashing file"));
962 lseek(File
->Fd(),0,SEEK_END
);
965 SetNonBlock(File
->Fd(),true);
969 // HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
970 // ---------------------------------------------------------------------
971 /* This closes and timestamps the open file. This is neccessary to get
972 resume behavoir on user abort */
973 void HttpMethod::SigTerm(int)
981 UBuf
.actime
= FailTime
;
982 UBuf
.modtime
= FailTime
;
983 utime(FailFile
.c_str(),&UBuf
);
988 // HttpMethod::Fetch - Fetch an item /*{{{*/
989 // ---------------------------------------------------------------------
990 /* This adds an item to the pipeline. We keep the pipeline at a fixed
992 bool HttpMethod::Fetch(FetchItem
*)
997 // Queue the requests
1000 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
1001 I
= I
->Next
, Depth
++)
1003 // If pipelining is disabled, we only queue 1 request
1004 if (Server
->Pipeline
== false && Depth
>= 0)
1007 // Make sure we stick with the same server
1008 if (Server
->Comp(I
->Uri
) == false)
1014 QueueBack
= I
->Next
;
1015 SendReq(I
,Server
->Out
);
1023 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
1024 // ---------------------------------------------------------------------
1025 /* We stash the desired pipeline depth */
1026 bool HttpMethod::Configuration(string Message
)
1028 if (pkgAcqMethod::Configuration(Message
) == false)
1031 TimeOut
= _config
->FindI("Acquire::http::Timeout",TimeOut
);
1032 PipelineDepth
= _config
->FindI("Acquire::http::Pipeline-Depth",
1034 Debug
= _config
->FindB("Debug::Acquire::http",false);
1039 // HttpMethod::Loop - Main loop /*{{{*/
1040 // ---------------------------------------------------------------------
1042 int HttpMethod::Loop()
1044 signal(SIGTERM
,SigTerm
);
1045 signal(SIGINT
,SigTerm
);
1049 int FailCounter
= 0;
1052 // We have no commands, wait for some to arrive
1055 if (WaitFd(STDIN_FILENO
) == false)
1059 /* Run messages, we can accept 0 (no message) if we didn't
1060 do a WaitFd above.. Otherwise the FD is closed. */
1061 int Result
= Run(true);
1062 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
1068 // Connect to the server
1069 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
1072 Server
= new ServerState(Queue
->Uri
,this);
1075 /* If the server has explicitly said this is the last connection
1076 then we pre-emptively shut down the pipeline and tear down
1077 the connection. This will speed up HTTP/1.0 servers a tad
1078 since we don't have to wait for the close sequence to
1080 if (Server
->Persistent
== false)
1083 // Reset the pipeline
1084 if (Server
->ServerFd
== -1)
1087 // Connnect to the host
1088 if (Server
->Open() == false)
1096 // Fill the pipeline.
1099 // Fetch the next URL header data from the server.
1100 switch (Server
->RunHeaders())
1105 // The header data is bad
1108 _error
->Error(_("Bad header data"));
1114 // The server closed a connection during the header get..
1121 Server
->Pipeline
= false;
1123 if (FailCounter
>= 2)
1125 Fail(_("Connection failed"),true);
1134 // Decide what to do.
1136 Res
.Filename
= Queue
->DestFile
;
1137 switch (DealWithHeaders(Res
,Server
))
1139 // Ok, the file is Open
1145 bool Result
= Server
->RunData();
1147 /* If the server is sending back sizeless responses then fill in
1150 Res
.Size
= File
->Size();
1152 // Close the file, destroy the FD object and timestamp it
1158 struct utimbuf UBuf
;
1160 UBuf
.actime
= Server
->Date
;
1161 UBuf
.modtime
= Server
->Date
;
1162 utime(Queue
->DestFile
.c_str(),&UBuf
);
1164 // Send status to APT
1167 Res
.TakeHashes(*Server
->In
.Hash
);
1183 // Hard server error, not found or something
1190 // Hard internal error, kill the connection and fail
1202 // We need to flush the data, the header is like a 404 w/ error text
1207 // Send to content to dev/null
1208 File
= new FileFd("/dev/null",FileFd::WriteExists
);
1216 Fail(_("Internal error"));
1229 setlocale(LC_ALL
, "");