]> git.saurik.com Git - apt.git/blame - methods/http.cc
Make apt proxy options have the highest priority, unified proxy determining code.
[apt.git] / methods / http.cc
CommitLineData
be4401bf
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
2cbcabd8 3// $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
be4401bf
AL
4/* ######################################################################
5
ae58a985 6 HTTP Acquire Method - This is the HTTP aquire method for APT.
be4401bf
AL
7
8 It uses HTTP/1.1 and many of the fancy options there-in, such as
e836f356
AL
9 pipelining, range, if-range and so on.
10
11 It is based on a doubly buffered select loop. A groupe of requests are
be4401bf
AL
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
e836f356 15 the same way and fed into the fd for the file (may be a pipe in future).
be4401bf
AL
16
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.
24
25 ##################################################################### */
26 /*}}}*/
27// Include Files /*{{{*/
28#include <apt-pkg/fileutl.h>
29#include <apt-pkg/acquire-method.h>
30#include <apt-pkg/error.h>
63b1700f 31#include <apt-pkg/hashes.h>
be4401bf
AL
32
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <utime.h>
36#include <unistd.h>
492f957a 37#include <signal.h>
be4401bf 38#include <stdio.h>
65a1e968 39#include <errno.h>
42195eb2
AL
40#include <string.h>
41#include <iostream>
d77559ac 42#include <apti18n.h>
be4401bf
AL
43
44// Internet stuff
0837bd25 45#include <netdb.h>
be4401bf 46
59b46c41 47#include "config.h"
0837bd25 48#include "connect.h"
934b6582 49#include "rfc2553emu.h"
be4401bf 50#include "http.h"
934b6582 51
be4401bf 52 /*}}}*/
42195eb2 53using namespace std;
be4401bf 54
492f957a
AL
55string HttpMethod::FailFile;
56int HttpMethod::FailFd = -1;
57time_t HttpMethod::FailTime = 0;
c37030c2 58unsigned long PipelineDepth = 10;
3000ccea 59unsigned long TimeOut = 120;
c98b1307 60bool Debug = false;
c37030c2 61URI Proxy;
492f957a 62
7c6e2dc7
MV
63unsigned long CircleBuf::BwReadLimit=0;
64unsigned long CircleBuf::BwTickReadData=0;
65struct timeval CircleBuf::BwReadTick={0,0};
66const unsigned int CircleBuf::BW_HZ=10;
67
be4401bf
AL
68// CircleBuf::CircleBuf - Circular input buffer /*{{{*/
69// ---------------------------------------------------------------------
70/* */
63b1700f 71CircleBuf::CircleBuf(unsigned long Size) : Size(Size), Hash(0)
be4401bf
AL
72{
73 Buf = new unsigned char[Size];
74 Reset();
7c6e2dc7
MV
75
76 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
be4401bf
AL
77}
78 /*}}}*/
79// CircleBuf::Reset - Reset to the default state /*{{{*/
80// ---------------------------------------------------------------------
81/* */
82void CircleBuf::Reset()
83{
84 InP = 0;
85 OutP = 0;
86 StrPos = 0;
87 MaxGet = (unsigned int)-1;
88 OutQueue = string();
63b1700f 89 if (Hash != 0)
be4401bf 90 {
63b1700f
AL
91 delete Hash;
92 Hash = new Hashes;
be4401bf
AL
93 }
94};
95 /*}}}*/
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
99 is non-blocking.. */
100bool CircleBuf::Read(int Fd)
101{
7c6e2dc7
MV
102 unsigned long BwReadMax;
103
be4401bf
AL
104 while (1)
105 {
106 // Woops, buffer is full
107 if (InP - OutP == Size)
108 return true;
7c6e2dc7
MV
109
110 // what's left to read in this tick
111 BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
112
113 if(CircleBuf::BwReadLimit) {
114 struct timeval now;
115 gettimeofday(&now,0);
116
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;
122 }
123
124 if(CircleBuf::BwTickReadData >= BwReadMax) {
125 usleep(1000000/BW_HZ);
126 return true;
127 }
128 }
129
be4401bf
AL
130 // Write the buffer segment
131 int Res;
7c6e2dc7
MV
132 if(CircleBuf::BwReadLimit) {
133 Res = read(Fd,Buf + (InP%Size),
134 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
135 } else
136 Res = read(Fd,Buf + (InP%Size),LeftRead());
be4401bf 137
7c6e2dc7
MV
138 if(Res > 0 && BwReadLimit > 0)
139 CircleBuf::BwTickReadData += Res;
140
be4401bf
AL
141 if (Res == 0)
142 return false;
143 if (Res < 0)
144 {
145 if (errno == EAGAIN)
146 return true;
147 return false;
148 }
149
150 if (InP == 0)
151 gettimeofday(&Start,0);
152 InP += Res;
153 }
154}
155 /*}}}*/
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 */
159bool CircleBuf::Read(string Data)
160{
161 OutQueue += Data;
162 FillOut();
163 return true;
164}
165 /*}}}*/
166// CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
167// ---------------------------------------------------------------------
168/* */
169void CircleBuf::FillOut()
170{
171 if (OutQueue.empty() == true)
172 return;
173 while (1)
174 {
175 // Woops, buffer is full
176 if (InP - OutP == Size)
177 return;
178
179 // Write the buffer segment
180 unsigned long Sz = LeftRead();
181 if (OutQueue.length() - StrPos < Sz)
182 Sz = OutQueue.length() - StrPos;
42195eb2 183 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
be4401bf
AL
184
185 // Advance
186 StrPos += Sz;
187 InP += Sz;
188 if (OutQueue.length() == StrPos)
189 {
190 StrPos = 0;
191 OutQueue = "";
192 return;
193 }
194 }
195}
196 /*}}}*/
197// CircleBuf::Write - Write from the buffer into a FD /*{{{*/
198// ---------------------------------------------------------------------
199/* This empties the buffer into the FD. */
200bool CircleBuf::Write(int Fd)
201{
202 while (1)
203 {
204 FillOut();
205
206 // Woops, buffer is empty
207 if (OutP == InP)
208 return true;
209
210 if (OutP == MaxGet)
211 return true;
212
213 // Write the buffer segment
214 int Res;
215 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
216
217 if (Res == 0)
218 return false;
219 if (Res < 0)
220 {
221 if (errno == EAGAIN)
222 return true;
223
224 return false;
225 }
226
63b1700f
AL
227 if (Hash != 0)
228 Hash->Add(Buf + (OutP%Size),Res);
be4401bf
AL
229
230 OutP += Res;
231 }
232}
233 /*}}}*/
234// CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
235// ---------------------------------------------------------------------
236/* This copies till the first empty line */
237bool CircleBuf::WriteTillEl(string &Data,bool Single)
238{
239 // We cheat and assume it is unneeded to have more than one buffer load
240 for (unsigned long I = OutP; I < InP; I++)
241 {
242 if (Buf[I%Size] != '\n')
243 continue;
2cbcabd8 244 ++I;
be4401bf
AL
245
246 if (Single == false)
247 {
2cbcabd8
AL
248 if (I < InP && Buf[I%Size] == '\r')
249 ++I;
927c393f
MV
250 if (I >= InP || Buf[I%Size] != '\n')
251 continue;
252 ++I;
be4401bf
AL
253 }
254
be4401bf
AL
255 Data = "";
256 while (OutP < I)
257 {
258 unsigned long Sz = LeftWrite();
259 if (Sz == 0)
260 return false;
927c393f 261 if (I - OutP < Sz)
be4401bf
AL
262 Sz = I - OutP;
263 Data += string((char *)(Buf + (OutP%Size)),Sz);
264 OutP += Sz;
265 }
266 return true;
267 }
268 return false;
269}
270 /*}}}*/
271// CircleBuf::Stats - Print out stats information /*{{{*/
272// ---------------------------------------------------------------------
273/* */
274void CircleBuf::Stats()
275{
276 if (InP == 0)
277 return;
278
279 struct timeval Stop;
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;*/
284}
285 /*}}}*/
286
287// ServerState::ServerState - Constructor /*{{{*/
288// ---------------------------------------------------------------------
289/* */
290ServerState::ServerState(URI Srv,HttpMethod *Owner) : Owner(Owner),
3000ccea 291 In(64*1024), Out(4*1024),
be4401bf
AL
292 ServerName(Srv)
293{
294 Reset();
295}
296 /*}}}*/
297// ServerState::Open - Open a connection to the server /*{{{*/
298// ---------------------------------------------------------------------
299/* This opens a connection to the server. */
be4401bf
AL
300bool ServerState::Open()
301{
92e889c8
AL
302 // Use the already open connection if possible.
303 if (ServerFd != -1)
304 return true;
305
be4401bf 306 Close();
492f957a
AL
307 In.Reset();
308 Out.Reset();
e836f356
AL
309 Persistent = true;
310
492f957a 311 // Determine the proxy setting
788a8f42
EL
312 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
313 if (!SpecificProxy.empty())
492f957a 314 {
788a8f42
EL
315 if (SpecificProxy == "DIRECT")
316 Proxy = "";
317 else
318 Proxy = SpecificProxy;
352c2768 319 }
492f957a 320 else
788a8f42
EL
321 {
322 string DefProxy = _config->Find("Acquire::http::Proxy");
323 if (!DefProxy.empty())
324 {
325 Proxy = DefProxy;
326 }
327 else
328 {
329 char* result = getenv("http_proxy");
330 Proxy = result ? result : "";
331 }
332 }
352c2768 333
f8081133 334 // Parse no_proxy, a , separated list of domains
9e2a06ff
AL
335 if (getenv("no_proxy") != 0)
336 {
f8081133
AL
337 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
338 Proxy = "";
339 }
340
492f957a 341 // Determine what host and port to use based on the proxy settings
934b6582 342 int Port = 0;
492f957a 343 string Host;
dd1fd92b 344 if (Proxy.empty() == true || Proxy.Host.empty() == true)
be4401bf 345 {
92e889c8
AL
346 if (ServerName.Port != 0)
347 Port = ServerName.Port;
be4401bf
AL
348 Host = ServerName.Host;
349 }
350 else
351 {
92e889c8
AL
352 if (Proxy.Port != 0)
353 Port = Proxy.Port;
be4401bf
AL
354 Host = Proxy.Host;
355 }
356
0837bd25 357 // Connect to the remote server
9505213b 358 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
0837bd25 359 return false;
3000ccea 360
be4401bf
AL
361 return true;
362}
363 /*}}}*/
364// ServerState::Close - Close a connection to the server /*{{{*/
365// ---------------------------------------------------------------------
366/* */
367bool ServerState::Close()
368{
369 close(ServerFd);
370 ServerFd = -1;
be4401bf
AL
371 return true;
372}
373 /*}}}*/
374// ServerState::RunHeaders - Get the headers before the data /*{{{*/
375// ---------------------------------------------------------------------
38965a34
MV
376/* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
377 parse error occurred */
92e889c8 378int ServerState::RunHeaders()
be4401bf
AL
379{
380 State = Header;
381
519c5591 382 Owner->Status(_("Waiting for headers"));
be4401bf
AL
383
384 Major = 0;
385 Minor = 0;
386 Result = 0;
387 Size = 0;
388 StartPos = 0;
92e889c8
AL
389 Encoding = Closes;
390 HaveContent = false;
be4401bf
AL
391 time(&Date);
392
393 do
394 {
395 string Data;
396 if (In.WriteTillEl(Data) == false)
397 continue;
9d95e726
AL
398
399 if (Debug == true)
400 clog << Data;
be4401bf
AL
401
402 for (string::const_iterator I = Data.begin(); I < Data.end(); I++)
403 {
404 string::const_iterator J = I;
405 for (; J != Data.end() && *J != '\n' && *J != '\r';J++);
42195eb2 406 if (HeaderLine(string(I,J)) == false)
92e889c8 407 return 2;
be4401bf
AL
408 I = J;
409 }
e836f356 410
b2e465d6
AL
411 // 100 Continue is a Nop...
412 if (Result == 100)
413 continue;
414
e836f356
AL
415 // Tidy up the connection persistance state.
416 if (Encoding == Closes && HaveContent == true)
417 Persistent = false;
418
92e889c8 419 return 0;
be4401bf
AL
420 }
421 while (Owner->Go(false,this) == true);
e836f356 422
92e889c8 423 return 1;
be4401bf
AL
424}
425 /*}}}*/
426// ServerState::RunData - Transfer the data from the socket /*{{{*/
427// ---------------------------------------------------------------------
428/* */
429bool ServerState::RunData()
430{
431 State = Data;
432
433 // Chunked transfer encoding is fun..
434 if (Encoding == Chunked)
435 {
436 while (1)
437 {
438 // Grab the block size
439 bool Last = true;
440 string Data;
441 In.Limit(-1);
442 do
443 {
444 if (In.WriteTillEl(Data,true) == true)
445 break;
446 }
447 while ((Last = Owner->Go(false,this)) == true);
448
449 if (Last == false)
450 return false;
451
452 // See if we are done
453 unsigned long Len = strtol(Data.c_str(),0,16);
454 if (Len == 0)
455 {
456 In.Limit(-1);
457
458 // We have to remove the entity trailer
459 Last = true;
460 do
461 {
462 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
463 break;
464 }
465 while ((Last = Owner->Go(false,this)) == true);
466 if (Last == false)
467 return false;
e1b96638 468 return !_error->PendingError();
be4401bf
AL
469 }
470
471 // Transfer the block
472 In.Limit(Len);
473 while (Owner->Go(true,this) == true)
474 if (In.IsLimit() == true)
475 break;
476
477 // Error
478 if (In.IsLimit() == false)
479 return false;
480
481 // The server sends an extra new line before the next block specifier..
482 In.Limit(-1);
483 Last = true;
484 do
485 {
486 if (In.WriteTillEl(Data,true) == true)
487 break;
488 }
489 while ((Last = Owner->Go(false,this)) == true);
490 if (Last == false)
491 return false;
92e889c8 492 }
be4401bf
AL
493 }
494 else
495 {
496 /* Closes encoding is used when the server did not specify a size, the
497 loss of the connection means we are done */
498 if (Encoding == Closes)
499 In.Limit(-1);
500 else
501 In.Limit(Size - StartPos);
502
503 // Just transfer the whole block.
504 do
505 {
506 if (In.IsLimit() == false)
507 continue;
508
509 In.Limit(-1);
e1b96638 510 return !_error->PendingError();
be4401bf
AL
511 }
512 while (Owner->Go(true,this) == true);
513 }
514
e1b96638 515 return Owner->Flush(this) && !_error->PendingError();
be4401bf
AL
516}
517 /*}}}*/
518// ServerState::HeaderLine - Process a header line /*{{{*/
519// ---------------------------------------------------------------------
520/* */
521bool ServerState::HeaderLine(string Line)
522{
523 if (Line.empty() == true)
524 return true;
30456e14 525
be4401bf
AL
526 // The http server might be trying to do something evil.
527 if (Line.length() >= MAXLEN)
dc738e7a 528 return _error->Error(_("Got a single header line over %u chars"),MAXLEN);
be4401bf
AL
529
530 string::size_type Pos = Line.find(' ');
531 if (Pos == string::npos || Pos+1 > Line.length())
c901051d
AL
532 {
533 // Blah, some servers use "connection:closes", evil.
534 Pos = Line.find(':');
535 if (Pos == string::npos || Pos + 2 > Line.length())
dc738e7a 536 return _error->Error(_("Bad header line"));
c901051d
AL
537 Pos++;
538 }
be4401bf 539
c901051d
AL
540 // Parse off any trailing spaces between the : and the next word.
541 string::size_type Pos2 = Pos;
542 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
543 Pos2++;
544
545 string Tag = string(Line,0,Pos);
546 string Val = string(Line,Pos2);
547
42195eb2 548 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
be4401bf
AL
549 {
550 // Evil servers return no version
551 if (Line[4] == '/')
552 {
553 if (sscanf(Line.c_str(),"HTTP/%u.%u %u %[^\n]",&Major,&Minor,
554 &Result,Code) != 4)
db0db9fe 555 return _error->Error(_("The HTTP server sent an invalid reply header"));
be4401bf
AL
556 }
557 else
558 {
559 Major = 0;
560 Minor = 9;
561 if (sscanf(Line.c_str(),"HTTP %u %[^\n]",&Result,Code) != 2)
db0db9fe 562 return _error->Error(_("The HTTP server sent an invalid reply header"));
be4401bf 563 }
e836f356
AL
564
565 /* Check the HTTP response header to get the default persistance
566 state. */
567 if (Major < 1)
568 Persistent = false;
569 else
570 {
571 if (Major == 1 && Minor <= 0)
572 Persistent = false;
573 else
574 Persistent = true;
575 }
b2e465d6 576
be4401bf
AL
577 return true;
578 }
579
92e889c8 580 if (stringcasecmp(Tag,"Content-Length:") == 0)
be4401bf
AL
581 {
582 if (Encoding == Closes)
583 Encoding = Stream;
92e889c8 584 HaveContent = true;
be4401bf
AL
585
586 // The length is already set from the Content-Range header
587 if (StartPos != 0)
588 return true;
589
590 if (sscanf(Val.c_str(),"%lu",&Size) != 1)
db0db9fe 591 return _error->Error(_("The HTTP server sent an invalid Content-Length header"));
be4401bf
AL
592 return true;
593 }
594
92e889c8
AL
595 if (stringcasecmp(Tag,"Content-Type:") == 0)
596 {
597 HaveContent = true;
598 return true;
599 }
600
601 if (stringcasecmp(Tag,"Content-Range:") == 0)
be4401bf 602 {
92e889c8
AL
603 HaveContent = true;
604
be4401bf 605 if (sscanf(Val.c_str(),"bytes %lu-%*u/%lu",&StartPos,&Size) != 2)
db0db9fe 606 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
be4401bf 607 if ((unsigned)StartPos > Size)
db0db9fe 608 return _error->Error(_("This HTTP server has broken range support"));
be4401bf
AL
609 return true;
610 }
611
92e889c8 612 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
be4401bf 613 {
92e889c8
AL
614 HaveContent = true;
615 if (stringcasecmp(Val,"chunked") == 0)
e836f356 616 Encoding = Chunked;
be4401bf
AL
617 return true;
618 }
619
e836f356
AL
620 if (stringcasecmp(Tag,"Connection:") == 0)
621 {
622 if (stringcasecmp(Val,"close") == 0)
623 Persistent = false;
624 if (stringcasecmp(Val,"keep-alive") == 0)
625 Persistent = true;
626 return true;
627 }
628
92e889c8 629 if (stringcasecmp(Tag,"Last-Modified:") == 0)
be4401bf
AL
630 {
631 if (StrToTime(Val,Date) == false)
dc738e7a 632 return _error->Error(_("Unknown date format"));
be4401bf
AL
633 return true;
634 }
635
636 return true;
637}
638 /*}}}*/
639
640// HttpMethod::SendReq - Send the HTTP request /*{{{*/
641// ---------------------------------------------------------------------
642/* This places the http request in the outbound buffer */
643void HttpMethod::SendReq(FetchItem *Itm,CircleBuf &Out)
644{
645 URI Uri = Itm->Uri;
c1a22377 646
be4401bf 647 // The HTTP server expects a hostname with a trailing :port
c1a22377 648 char Buf[1000];
be4401bf
AL
649 string ProperHost = Uri.Host;
650 if (Uri.Port != 0)
651 {
652 sprintf(Buf,":%u",Uri.Port);
653 ProperHost += Buf;
654 }
655
c1a22377
AL
656 // Just in case.
657 if (Itm->Uri.length() >= sizeof(Buf))
658 abort();
659
492f957a
AL
660 /* Build the request. We include a keep-alive header only for non-proxy
661 requests. This is to tweak old http/1.0 servers that do support keep-alive
662 but not HTTP/1.1 automatic keep-alive. Doing this with a proxy server
663 will glitch HTTP/1.0 proxies because they do not filter it out and
664 pass it on, HTTP/1.1 says the connection should default to keep alive
665 and we expect the proxy to do this */
02b7ddb1 666 if (Proxy.empty() == true || Proxy.Host.empty())
be4401bf 667 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n",
a4edf53b 668 QuoteString(Uri.Path,"~").c_str(),ProperHost.c_str());
be4401bf 669 else
c1a22377
AL
670 {
671 /* Generate a cache control header if necessary. We place a max
672 cache age on index files, optionally set a no-cache directive
673 and a no-store directive for archives. */
be4401bf
AL
674 sprintf(Buf,"GET %s HTTP/1.1\r\nHost: %s\r\n",
675 Itm->Uri.c_str(),ProperHost.c_str());
106e6740
MV
676 // only generate a cache control header if we actually want to
677 // use a cache
678 if (_config->FindB("Acquire::http::No-Cache",false) == false)
c1a22377
AL
679 {
680 if (Itm->IndexFile == true)
681 sprintf(Buf+strlen(Buf),"Cache-Control: max-age=%u\r\n",
bcbe61ae 682 _config->FindI("Acquire::http::Max-Age",0));
c1a22377
AL
683 else
684 {
685 if (_config->FindB("Acquire::http::No-Store",false) == true)
686 strcat(Buf,"Cache-Control: no-store\r\n");
687 }
688 }
689 }
106e6740
MV
690 // generate a no-cache header if needed
691 if (_config->FindB("Acquire::http::No-Cache",false) == true)
692 strcat(Buf,"Cache-Control: no-cache\r\nPragma: no-cache\r\n");
693
c1a22377 694
be4401bf 695 string Req = Buf;
492f957a 696
be4401bf
AL
697 // Check for a partial file
698 struct stat SBuf;
699 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
700 {
701 // In this case we send an if-range query with a range header
1ae93c94 702 sprintf(Buf,"Range: bytes=%li-\r\nIf-Range: %s\r\n",(long)SBuf.st_size - 1,
be4401bf
AL
703 TimeRFC1123(SBuf.st_mtime).c_str());
704 Req += Buf;
705 }
706 else
707 {
708 if (Itm->LastModified != 0)
709 {
710 sprintf(Buf,"If-Modified-Since: %s\r\n",TimeRFC1123(Itm->LastModified).c_str());
711 Req += Buf;
712 }
713 }
714
8d64c395
AL
715 if (Proxy.User.empty() == false || Proxy.Password.empty() == false)
716 Req += string("Proxy-Authorization: Basic ") +
717 Base64Encode(Proxy.User + ":" + Proxy.Password) + "\r\n";
be4401bf 718
b2e465d6
AL
719 if (Uri.User.empty() == false || Uri.Password.empty() == false)
720 Req += string("Authorization: Basic ") +
721 Base64Encode(Uri.User + ":" + Uri.Password) + "\r\n";
722
59b46c41 723 Req += "User-Agent: Debian APT-HTTP/1.3 ("VERSION")\r\n\r\n";
c98b1307
AL
724
725 if (Debug == true)
726 cerr << Req << endl;
c1a22377 727
be4401bf
AL
728 Out.Read(Req);
729}
730 /*}}}*/
731// HttpMethod::Go - Run a single loop /*{{{*/
732// ---------------------------------------------------------------------
733/* This runs the select loop over the server FDs, Output file FDs and
734 stdin. */
735bool HttpMethod::Go(bool ToFile,ServerState *Srv)
736{
737 // Server has closed the connection
8195ae46
AL
738 if (Srv->ServerFd == -1 && (Srv->In.WriteSpace() == false ||
739 ToFile == false))
be4401bf
AL
740 return false;
741
d955fe80 742 fd_set rfds,wfds;
be4401bf
AL
743 FD_ZERO(&rfds);
744 FD_ZERO(&wfds);
be4401bf 745
e836f356
AL
746 /* Add the server. We only send more requests if the connection will
747 be persisting */
748 if (Srv->Out.WriteSpace() == true && Srv->ServerFd != -1
749 && Srv->Persistent == true)
be4401bf 750 FD_SET(Srv->ServerFd,&wfds);
e836f356 751 if (Srv->In.ReadSpace() == true && Srv->ServerFd != -1)
be4401bf
AL
752 FD_SET(Srv->ServerFd,&rfds);
753
754 // Add the file
755 int FileFD = -1;
756 if (File != 0)
757 FileFD = File->Fd();
758
759 if (Srv->In.WriteSpace() == true && ToFile == true && FileFD != -1)
760 FD_SET(FileFD,&wfds);
761
762 // Add stdin
763 FD_SET(STDIN_FILENO,&rfds);
764
be4401bf
AL
765 // Figure out the max fd
766 int MaxFd = FileFD;
767 if (MaxFd < Srv->ServerFd)
768 MaxFd = Srv->ServerFd;
8195ae46 769
be4401bf
AL
770 // Select
771 struct timeval tv;
3000ccea 772 tv.tv_sec = TimeOut;
be4401bf
AL
773 tv.tv_usec = 0;
774 int Res = 0;
d955fe80 775 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
c37b9502
AL
776 {
777 if (errno == EINTR)
778 return true;
dc738e7a 779 return _error->Errno("select",_("Select failed"));
c37b9502 780 }
be4401bf
AL
781
782 if (Res == 0)
783 {
dc738e7a 784 _error->Error(_("Connection timed out"));
be4401bf
AL
785 return ServerDie(Srv);
786 }
787
be4401bf
AL
788 // Handle server IO
789 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&rfds))
790 {
791 errno = 0;
792 if (Srv->In.Read(Srv->ServerFd) == false)
793 return ServerDie(Srv);
794 }
795
796 if (Srv->ServerFd != -1 && FD_ISSET(Srv->ServerFd,&wfds))
797 {
798 errno = 0;
799 if (Srv->Out.Write(Srv->ServerFd) == false)
800 return ServerDie(Srv);
801 }
802
803 // Send data to the file
804 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
805 {
806 if (Srv->In.Write(FileFD) == false)
dc738e7a 807 return _error->Errno("write",_("Error writing to output file"));
be4401bf
AL
808 }
809
810 // Handle commands from APT
811 if (FD_ISSET(STDIN_FILENO,&rfds))
812 {
6920216d 813 if (Run(true) != -1)
be4401bf
AL
814 exit(100);
815 }
816
817 return true;
818}
819 /*}}}*/
820// HttpMethod::Flush - Dump the buffer into the file /*{{{*/
821// ---------------------------------------------------------------------
822/* This takes the current input buffer from the Server FD and writes it
823 into the file */
824bool HttpMethod::Flush(ServerState *Srv)
825{
826 if (File != 0)
827 {
b57c8bb4
MV
828 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
829 // can't be set
830 if (File->Name() != "/dev/null")
831 SetNonBlock(File->Fd(),false);
be4401bf
AL
832 if (Srv->In.WriteSpace() == false)
833 return true;
834
835 while (Srv->In.WriteSpace() == true)
836 {
837 if (Srv->In.Write(File->Fd()) == false)
dc738e7a 838 return _error->Errno("write",_("Error writing to file"));
92e889c8
AL
839 if (Srv->In.IsLimit() == true)
840 return true;
be4401bf
AL
841 }
842
843 if (Srv->In.IsLimit() == true || Srv->Encoding == ServerState::Closes)
844 return true;
845 }
846 return false;
847}
848 /*}}}*/
849// HttpMethod::ServerDie - The server has closed the connection. /*{{{*/
850// ---------------------------------------------------------------------
851/* */
852bool HttpMethod::ServerDie(ServerState *Srv)
853{
2b154e53
AL
854 unsigned int LErrno = errno;
855
be4401bf
AL
856 // Dump the buffer to the file
857 if (Srv->State == ServerState::Data)
858 {
b57c8bb4
MV
859 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
860 // can't be set
861 if (File->Name() != "/dev/null")
862 SetNonBlock(File->Fd(),false);
be4401bf
AL
863 while (Srv->In.WriteSpace() == true)
864 {
865 if (Srv->In.Write(File->Fd()) == false)
dc738e7a 866 return _error->Errno("write",_("Error writing to the file"));
92e889c8
AL
867
868 // Done
869 if (Srv->In.IsLimit() == true)
870 return true;
be4401bf
AL
871 }
872 }
873
874 // See if this is because the server finished the data stream
875 if (Srv->In.IsLimit() == false && Srv->State != ServerState::Header &&
876 Srv->Encoding != ServerState::Closes)
877 {
3d615484 878 Srv->Close();
2b154e53 879 if (LErrno == 0)
db0db9fe 880 return _error->Error(_("Error reading from server. Remote end closed connection"));
2b154e53 881 errno = LErrno;
dc738e7a 882 return _error->Errno("read",_("Error reading from server"));
be4401bf
AL
883 }
884 else
885 {
886 Srv->In.Limit(-1);
887
888 // Nothing left in the buffer
889 if (Srv->In.WriteSpace() == false)
890 return false;
891
892 // We may have got multiple responses back in one packet..
893 Srv->Close();
894 return true;
895 }
896
897 return false;
898}
899 /*}}}*/
900// HttpMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
901// ---------------------------------------------------------------------
902/* We look at the header data we got back from the server and decide what
903 to do. Returns
904 0 - File is open,
905 1 - IMS hit
92e889c8 906 3 - Unrecoverable error
94235cfb
AL
907 4 - Error with error content page
908 5 - Unrecoverable non-server error (close the connection) */
be4401bf
AL
909int HttpMethod::DealWithHeaders(FetchResult &Res,ServerState *Srv)
910{
911 // Not Modified
912 if (Srv->Result == 304)
913 {
914 unlink(Queue->DestFile.c_str());
915 Res.IMSHit = true;
916 Res.LastModified = Queue->LastModified;
917 return 1;
918 }
919
920 /* We have a reply we dont handle. This should indicate a perm server
921 failure */
922 if (Srv->Result < 200 || Srv->Result >= 300)
923 {
924 _error->Error("%u %s",Srv->Result,Srv->Code);
92e889c8
AL
925 if (Srv->HaveContent == true)
926 return 4;
be4401bf
AL
927 return 3;
928 }
929
930 // This is some sort of 2xx 'data follows' reply
931 Res.LastModified = Srv->Date;
932 Res.Size = Srv->Size;
933
934 // Open the file
935 delete File;
936 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
937 if (_error->PendingError() == true)
94235cfb 938 return 5;
492f957a
AL
939
940 FailFile = Queue->DestFile;
30b30ec1 941 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
492f957a
AL
942 FailFd = File->Fd();
943 FailTime = Srv->Date;
944
be4401bf
AL
945 // Set the expected size
946 if (Srv->StartPos >= 0)
947 {
948 Res.ResumePoint = Srv->StartPos;
3c8cda8b
MV
949 if (ftruncate(File->Fd(),Srv->StartPos) < 0)
950 _error->Errno("ftruncate", _("Failed to truncate file"));
be4401bf
AL
951 }
952
953 // Set the start point
954 lseek(File->Fd(),0,SEEK_END);
955
63b1700f
AL
956 delete Srv->In.Hash;
957 Srv->In.Hash = new Hashes;
be4401bf 958
63b1700f 959 // Fill the Hash if the file is non-empty (resume)
be4401bf
AL
960 if (Srv->StartPos > 0)
961 {
962 lseek(File->Fd(),0,SEEK_SET);
63b1700f 963 if (Srv->In.Hash->AddFD(File->Fd(),Srv->StartPos) == false)
be4401bf 964 {
dc738e7a 965 _error->Errno("read",_("Problem hashing file"));
94235cfb 966 return 5;
be4401bf
AL
967 }
968 lseek(File->Fd(),0,SEEK_END);
969 }
970
971 SetNonBlock(File->Fd(),true);
972 return 0;
973}
974 /*}}}*/
492f957a
AL
975// HttpMethod::SigTerm - Handle a fatal signal /*{{{*/
976// ---------------------------------------------------------------------
977/* This closes and timestamps the open file. This is neccessary to get
978 resume behavoir on user abort */
979void HttpMethod::SigTerm(int)
980{
981 if (FailFd == -1)
ffe9323a 982 _exit(100);
492f957a
AL
983 close(FailFd);
984
985 // Timestamp
986 struct utimbuf UBuf;
492f957a
AL
987 UBuf.actime = FailTime;
988 UBuf.modtime = FailTime;
989 utime(FailFile.c_str(),&UBuf);
990
ffe9323a 991 _exit(100);
492f957a
AL
992}
993 /*}}}*/
5cb5d8dc
AL
994// HttpMethod::Fetch - Fetch an item /*{{{*/
995// ---------------------------------------------------------------------
996/* This adds an item to the pipeline. We keep the pipeline at a fixed
997 depth. */
998bool HttpMethod::Fetch(FetchItem *)
999{
1000 if (Server == 0)
1001 return true;
3000ccea 1002
5cb5d8dc
AL
1003 // Queue the requests
1004 int Depth = -1;
f93d1355
AL
1005 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
1006 I = I->Next, Depth++)
5cb5d8dc 1007 {
f93d1355
AL
1008 // If pipelining is disabled, we only queue 1 request
1009 if (Server->Pipeline == false && Depth >= 0)
1010 break;
1011
5cb5d8dc
AL
1012 // Make sure we stick with the same server
1013 if (Server->Comp(I->Uri) == false)
1014 break;
5cb5d8dc 1015 if (QueueBack == I)
5cb5d8dc 1016 {
5cb5d8dc
AL
1017 QueueBack = I->Next;
1018 SendReq(I,Server->Out);
1019 continue;
f93d1355 1020 }
5cb5d8dc
AL
1021 }
1022
1023 return true;
1024};
1025 /*}}}*/
85f72a56
AL
1026// HttpMethod::Configuration - Handle a configuration message /*{{{*/
1027// ---------------------------------------------------------------------
1028/* We stash the desired pipeline depth */
1029bool HttpMethod::Configuration(string Message)
1030{
1031 if (pkgAcqMethod::Configuration(Message) == false)
1032 return false;
1033
30456e14
AL
1034 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
1035 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
1036 PipelineDepth);
c98b1307 1037 Debug = _config->FindB("Debug::Acquire::http",false);
3000ccea 1038
85f72a56
AL
1039 return true;
1040}
1041 /*}}}*/
492f957a 1042// HttpMethod::Loop - Main loop /*{{{*/
be4401bf
AL
1043// ---------------------------------------------------------------------
1044/* */
1045int HttpMethod::Loop()
1046{
492f957a
AL
1047 signal(SIGTERM,SigTerm);
1048 signal(SIGINT,SigTerm);
1049
5cb5d8dc 1050 Server = 0;
be4401bf 1051
92e889c8 1052 int FailCounter = 0;
be4401bf 1053 while (1)
2b154e53 1054 {
be4401bf
AL
1055 // We have no commands, wait for some to arrive
1056 if (Queue == 0)
1057 {
1058 if (WaitFd(STDIN_FILENO) == false)
1059 return 0;
1060 }
1061
6920216d
AL
1062 /* Run messages, we can accept 0 (no message) if we didn't
1063 do a WaitFd above.. Otherwise the FD is closed. */
1064 int Result = Run(true);
1065 if (Result != -1 && (Result != 0 || Queue == 0))
be4401bf
AL
1066 return 100;
1067
1068 if (Queue == 0)
1069 continue;
1070
1071 // Connect to the server
1072 if (Server == 0 || Server->Comp(Queue->Uri) == false)
1073 {
1074 delete Server;
1075 Server = new ServerState(Queue->Uri,this);
1076 }
e836f356
AL
1077 /* If the server has explicitly said this is the last connection
1078 then we pre-emptively shut down the pipeline and tear down
1079 the connection. This will speed up HTTP/1.0 servers a tad
1080 since we don't have to wait for the close sequence to
1081 complete */
1082 if (Server->Persistent == false)
1083 Server->Close();
1084
a7fb252c
AL
1085 // Reset the pipeline
1086 if (Server->ServerFd == -1)
1087 QueueBack = Queue;
1088
be4401bf
AL
1089 // Connnect to the host
1090 if (Server->Open() == false)
1091 {
43252d15 1092 Fail(true);
a1459f52
AL
1093 delete Server;
1094 Server = 0;
be4401bf
AL
1095 continue;
1096 }
be4401bf 1097
5cb5d8dc
AL
1098 // Fill the pipeline.
1099 Fetch(0);
1100
92e889c8
AL
1101 // Fetch the next URL header data from the server.
1102 switch (Server->RunHeaders())
be4401bf 1103 {
92e889c8
AL
1104 case 0:
1105 break;
1106
1107 // The header data is bad
1108 case 2:
1109 {
db0db9fe 1110 _error->Error(_("Bad header data"));
43252d15 1111 Fail(true);
b2e465d6 1112 RotateDNS();
92e889c8
AL
1113 continue;
1114 }
1115
1116 // The server closed a connection during the header get..
1117 default:
1118 case 1:
1119 {
1120 FailCounter++;
3d615484 1121 _error->Discard();
92e889c8 1122 Server->Close();
f93d1355
AL
1123 Server->Pipeline = false;
1124
2b154e53
AL
1125 if (FailCounter >= 2)
1126 {
dc738e7a 1127 Fail(_("Connection failed"),true);
2b154e53
AL
1128 FailCounter = 0;
1129 }
1130
b2e465d6 1131 RotateDNS();
92e889c8
AL
1132 continue;
1133 }
1134 };
5cb5d8dc 1135
be4401bf
AL
1136 // Decide what to do.
1137 FetchResult Res;
bfd22fc0 1138 Res.Filename = Queue->DestFile;
be4401bf
AL
1139 switch (DealWithHeaders(Res,Server))
1140 {
1141 // Ok, the file is Open
1142 case 0:
1143 {
1144 URIStart(Res);
1145
1146 // Run the data
492f957a
AL
1147 bool Result = Server->RunData();
1148
b2e465d6
AL
1149 /* If the server is sending back sizeless responses then fill in
1150 the size now */
1151 if (Res.Size == 0)
1152 Res.Size = File->Size();
1153
492f957a
AL
1154 // Close the file, destroy the FD object and timestamp it
1155 FailFd = -1;
1156 delete File;
1157 File = 0;
1158
1159 // Timestamp
1160 struct utimbuf UBuf;
1161 time(&UBuf.actime);
1162 UBuf.actime = Server->Date;
1163 UBuf.modtime = Server->Date;
1164 utime(Queue->DestFile.c_str(),&UBuf);
1165
1166 // Send status to APT
1167 if (Result == true)
92e889c8 1168 {
a7c835af 1169 Res.TakeHashes(*Server->In.Hash);
92e889c8
AL
1170 URIDone(Res);
1171 }
492f957a 1172 else
82d0afc2
MV
1173 {
1174 if (Server->ServerFd == -1)
1175 {
1176 FailCounter++;
1177 _error->Discard();
1178 Server->Close();
1179
1180 if (FailCounter >= 2)
9a52beaa 1181 {
82d0afc2
MV
1182 Fail(_("Connection failed"),true);
1183 FailCounter = 0;
9a52beaa 1184 }
82d0afc2
MV
1185
1186 QueueBack = Queue;
1187 }
1188 else
1189 Fail(true);
1190 }
be4401bf
AL
1191 break;
1192 }
1193
1194 // IMS hit
1195 case 1:
1196 {
1197 URIDone(Res);
1198 break;
1199 }
1200
1201 // Hard server error, not found or something
1202 case 3:
1203 {
1204 Fail();
1205 break;
1206 }
94235cfb
AL
1207
1208 // Hard internal error, kill the connection and fail
1209 case 5:
1210 {
a305f593
AL
1211 delete File;
1212 File = 0;
1213
94235cfb 1214 Fail();
b2e465d6 1215 RotateDNS();
94235cfb
AL
1216 Server->Close();
1217 break;
1218 }
92e889c8
AL
1219
1220 // We need to flush the data, the header is like a 404 w/ error text
1221 case 4:
1222 {
1223 Fail();
1224
1225 // Send to content to dev/null
1226 File = new FileFd("/dev/null",FileFd::WriteExists);
1227 Server->RunData();
1228 delete File;
1229 File = 0;
1230 break;
1231 }
be4401bf
AL
1232
1233 default:
dc738e7a 1234 Fail(_("Internal error"));
be4401bf 1235 break;
92e889c8
AL
1236 }
1237
1238 FailCounter = 0;
be4401bf
AL
1239 }
1240
1241 return 0;
1242}
1243 /*}}}*/
1244
1245int main()
1246{
049c0171 1247 setlocale(LC_ALL, "");
049c0171 1248
be4401bf
AL
1249 HttpMethod Mth;
1250
1251 return Mth.Loop();
1252}
a305f593
AL
1253
1254