]> git.saurik.com Git - apt.git/blame - methods/http.cc
Fix more warnings from clang
[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
1e3f4083 6 HTTP Acquire Method - This is the HTTP acquire 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 /*{{{*/
ea542140
DK
28#include <config.h>
29
be4401bf
AL
30#include <apt-pkg/fileutl.h>
31#include <apt-pkg/acquire-method.h>
472ff00e 32#include <apt-pkg/configuration.h>
be4401bf 33#include <apt-pkg/error.h>
63b1700f 34#include <apt-pkg/hashes.h>
592b7800 35#include <apt-pkg/netrc.h>
453b82a3 36#include <apt-pkg/strutl.h>
be4401bf 37
453b82a3
DK
38#include <stddef.h>
39#include <stdlib.h>
40#include <sys/select.h>
41#include <cstring>
be4401bf
AL
42#include <sys/stat.h>
43#include <sys/time.h>
be4401bf
AL
44#include <unistd.h>
45#include <stdio.h>
65a1e968 46#include <errno.h>
42195eb2 47#include <iostream>
b123b0ba 48#include <sstream>
be4401bf 49
59b46c41 50#include "config.h"
0837bd25 51#include "connect.h"
be4401bf 52#include "http.h"
ea542140
DK
53
54#include <apti18n.h>
be4401bf 55 /*}}}*/
42195eb2 56using namespace std;
be4401bf 57
650faab0
DK
58unsigned long long CircleBuf::BwReadLimit=0;
59unsigned long long CircleBuf::BwTickReadData=0;
7c6e2dc7
MV
60struct timeval CircleBuf::BwReadTick={0,0};
61const unsigned int CircleBuf::BW_HZ=10;
d3e8fbb3 62
be4401bf
AL
63// CircleBuf::CircleBuf - Circular input buffer /*{{{*/
64// ---------------------------------------------------------------------
65/* */
650faab0 66CircleBuf::CircleBuf(unsigned long long Size) : Size(Size), Hash(0)
be4401bf
AL
67{
68 Buf = new unsigned char[Size];
69 Reset();
7c6e2dc7
MV
70
71 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
be4401bf
AL
72}
73 /*}}}*/
74// CircleBuf::Reset - Reset to the default state /*{{{*/
75// ---------------------------------------------------------------------
76/* */
77void CircleBuf::Reset()
78{
79 InP = 0;
80 OutP = 0;
81 StrPos = 0;
650faab0 82 MaxGet = (unsigned long long)-1;
be4401bf 83 OutQueue = string();
63b1700f 84 if (Hash != 0)
be4401bf 85 {
63b1700f
AL
86 delete Hash;
87 Hash = new Hashes;
d3e8fbb3
DK
88 }
89}
be4401bf
AL
90 /*}}}*/
91// CircleBuf::Read - Read from a FD into the circular buffer /*{{{*/
92// ---------------------------------------------------------------------
93/* This fills up the buffer with as much data as is in the FD, assuming it
94 is non-blocking.. */
95bool CircleBuf::Read(int Fd)
96{
97 while (1)
98 {
99 // Woops, buffer is full
100 if (InP - OutP == Size)
101 return true;
7c6e2dc7
MV
102
103 // what's left to read in this tick
9ce3cfc9 104 unsigned long long const BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
7c6e2dc7
MV
105
106 if(CircleBuf::BwReadLimit) {
107 struct timeval now;
108 gettimeofday(&now,0);
109
650faab0 110 unsigned long long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
7c6e2dc7
MV
111 now.tv_usec-CircleBuf::BwReadTick.tv_usec;
112 if(d > 1000000/BW_HZ) {
113 CircleBuf::BwReadTick = now;
114 CircleBuf::BwTickReadData = 0;
115 }
116
117 if(CircleBuf::BwTickReadData >= BwReadMax) {
118 usleep(1000000/BW_HZ);
119 return true;
120 }
121 }
122
be4401bf 123 // Write the buffer segment
650faab0 124 ssize_t Res;
7c6e2dc7
MV
125 if(CircleBuf::BwReadLimit) {
126 Res = read(Fd,Buf + (InP%Size),
127 BwReadMax > LeftRead() ? LeftRead() : BwReadMax);
128 } else
129 Res = read(Fd,Buf + (InP%Size),LeftRead());
be4401bf 130
7c6e2dc7
MV
131 if(Res > 0 && BwReadLimit > 0)
132 CircleBuf::BwTickReadData += Res;
133
be4401bf
AL
134 if (Res == 0)
135 return false;
136 if (Res < 0)
137 {
138 if (errno == EAGAIN)
139 return true;
140 return false;
141 }
142
143 if (InP == 0)
144 gettimeofday(&Start,0);
145 InP += Res;
146 }
147}
148 /*}}}*/
149// CircleBuf::Read - Put the string into the buffer /*{{{*/
150// ---------------------------------------------------------------------
151/* This will hold the string in and fill the buffer with it as it empties */
152bool CircleBuf::Read(string Data)
153{
154 OutQueue += Data;
155 FillOut();
156 return true;
157}
158 /*}}}*/
159// CircleBuf::FillOut - Fill the buffer from the output queue /*{{{*/
160// ---------------------------------------------------------------------
161/* */
162void CircleBuf::FillOut()
163{
164 if (OutQueue.empty() == true)
165 return;
166 while (1)
167 {
168 // Woops, buffer is full
169 if (InP - OutP == Size)
170 return;
171
172 // Write the buffer segment
650faab0 173 unsigned long long Sz = LeftRead();
be4401bf
AL
174 if (OutQueue.length() - StrPos < Sz)
175 Sz = OutQueue.length() - StrPos;
42195eb2 176 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
be4401bf
AL
177
178 // Advance
179 StrPos += Sz;
180 InP += Sz;
181 if (OutQueue.length() == StrPos)
182 {
183 StrPos = 0;
184 OutQueue = "";
185 return;
186 }
187 }
188}
189 /*}}}*/
190// CircleBuf::Write - Write from the buffer into a FD /*{{{*/
191// ---------------------------------------------------------------------
192/* This empties the buffer into the FD. */
193bool CircleBuf::Write(int Fd)
194{
195 while (1)
196 {
197 FillOut();
198
199 // Woops, buffer is empty
200 if (OutP == InP)
201 return true;
202
203 if (OutP == MaxGet)
204 return true;
205
206 // Write the buffer segment
650faab0 207 ssize_t Res;
be4401bf
AL
208 Res = write(Fd,Buf + (OutP%Size),LeftWrite());
209
210 if (Res == 0)
211 return false;
212 if (Res < 0)
213 {
214 if (errno == EAGAIN)
215 return true;
216
217 return false;
218 }
219
63b1700f
AL
220 if (Hash != 0)
221 Hash->Add(Buf + (OutP%Size),Res);
be4401bf
AL
222
223 OutP += Res;
224 }
225}
226 /*}}}*/
227// CircleBuf::WriteTillEl - Write from the buffer to a string /*{{{*/
228// ---------------------------------------------------------------------
229/* This copies till the first empty line */
230bool CircleBuf::WriteTillEl(string &Data,bool Single)
231{
232 // We cheat and assume it is unneeded to have more than one buffer load
650faab0 233 for (unsigned long long I = OutP; I < InP; I++)
be4401bf
AL
234 {
235 if (Buf[I%Size] != '\n')
236 continue;
2cbcabd8 237 ++I;
be4401bf
AL
238
239 if (Single == false)
240 {
2cbcabd8
AL
241 if (I < InP && Buf[I%Size] == '\r')
242 ++I;
927c393f
MV
243 if (I >= InP || Buf[I%Size] != '\n')
244 continue;
245 ++I;
be4401bf
AL
246 }
247
be4401bf
AL
248 Data = "";
249 while (OutP < I)
250 {
650faab0 251 unsigned long long Sz = LeftWrite();
be4401bf
AL
252 if (Sz == 0)
253 return false;
927c393f 254 if (I - OutP < Sz)
be4401bf
AL
255 Sz = I - OutP;
256 Data += string((char *)(Buf + (OutP%Size)),Sz);
257 OutP += Sz;
258 }
259 return true;
260 }
261 return false;
262}
263 /*}}}*/
264// CircleBuf::Stats - Print out stats information /*{{{*/
265// ---------------------------------------------------------------------
266/* */
267void CircleBuf::Stats()
268{
269 if (InP == 0)
270 return;
271
272 struct timeval Stop;
273 gettimeofday(&Stop,0);
274/* float Diff = Stop.tv_sec - Start.tv_sec +
275 (float)(Stop.tv_usec - Start.tv_usec)/1000000;
276 clog << "Got " << InP << " in " << Diff << " at " << InP/Diff << endl;*/
277}
278 /*}}}*/
472ff00e
DK
279CircleBuf::~CircleBuf()
280{
281 delete [] Buf;
282 delete Hash;
283}
be4401bf 284
7330f4df
DK
285// HttpServerState::HttpServerState - Constructor /*{{{*/
286HttpServerState::HttpServerState(URI Srv,HttpMethod *Owner) : ServerState(Srv, Owner), In(64*1024), Out(4*1024)
be4401bf 287{
7330f4df 288 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
be4401bf
AL
289 Reset();
290}
291 /*}}}*/
7330f4df 292// HttpServerState::Open - Open a connection to the server /*{{{*/
be4401bf
AL
293// ---------------------------------------------------------------------
294/* This opens a connection to the server. */
7330f4df 295bool HttpServerState::Open()
be4401bf 296{
92e889c8
AL
297 // Use the already open connection if possible.
298 if (ServerFd != -1)
299 return true;
300
be4401bf 301 Close();
492f957a
AL
302 In.Reset();
303 Out.Reset();
e836f356
AL
304 Persistent = true;
305
492f957a 306 // Determine the proxy setting
788a8f42
EL
307 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
308 if (!SpecificProxy.empty())
492f957a 309 {
788a8f42
EL
310 if (SpecificProxy == "DIRECT")
311 Proxy = "";
312 else
313 Proxy = SpecificProxy;
352c2768 314 }
492f957a 315 else
788a8f42
EL
316 {
317 string DefProxy = _config->Find("Acquire::http::Proxy");
318 if (!DefProxy.empty())
319 {
320 Proxy = DefProxy;
321 }
322 else
323 {
324 char* result = getenv("http_proxy");
325 Proxy = result ? result : "";
326 }
327 }
352c2768 328
f8081133 329 // Parse no_proxy, a , separated list of domains
9e2a06ff
AL
330 if (getenv("no_proxy") != 0)
331 {
f8081133
AL
332 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
333 Proxy = "";
334 }
335
492f957a 336 // Determine what host and port to use based on the proxy settings
934b6582 337 int Port = 0;
492f957a 338 string Host;
dd1fd92b 339 if (Proxy.empty() == true || Proxy.Host.empty() == true)
be4401bf 340 {
92e889c8
AL
341 if (ServerName.Port != 0)
342 Port = ServerName.Port;
be4401bf
AL
343 Host = ServerName.Host;
344 }
345 else
346 {
92e889c8
AL
347 if (Proxy.Port != 0)
348 Port = Proxy.Port;
be4401bf
AL
349 Host = Proxy.Host;
350 }
351
0837bd25 352 // Connect to the remote server
9505213b 353 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
0837bd25 354 return false;
3000ccea 355
be4401bf
AL
356 return true;
357}
358 /*}}}*/
7330f4df 359// HttpServerState::Close - Close a connection to the server /*{{{*/
be4401bf
AL
360// ---------------------------------------------------------------------
361/* */
7330f4df 362bool HttpServerState::Close()
be4401bf
AL
363{
364 close(ServerFd);
365 ServerFd = -1;
be4401bf
AL
366 return true;
367}
368 /*}}}*/
7330f4df
DK
369// HttpServerState::RunData - Transfer the data from the socket /*{{{*/
370bool HttpServerState::RunData(FileFd * const File)
be4401bf
AL
371{
372 State = Data;
373
374 // Chunked transfer encoding is fun..
375 if (Encoding == Chunked)
376 {
377 while (1)
378 {
379 // Grab the block size
380 bool Last = true;
381 string Data;
382 In.Limit(-1);
383 do
384 {
385 if (In.WriteTillEl(Data,true) == true)
386 break;
387 }
7330f4df 388 while ((Last = Go(false, File)) == true);
be4401bf
AL
389
390 if (Last == false)
391 return false;
392
393 // See if we are done
650faab0 394 unsigned long long Len = strtoull(Data.c_str(),0,16);
be4401bf
AL
395 if (Len == 0)
396 {
397 In.Limit(-1);
398
399 // We have to remove the entity trailer
400 Last = true;
401 do
402 {
403 if (In.WriteTillEl(Data,true) == true && Data.length() <= 2)
404 break;
405 }
7330f4df 406 while ((Last = Go(false, File)) == true);
be4401bf
AL
407 if (Last == false)
408 return false;
e1b96638 409 return !_error->PendingError();
be4401bf
AL
410 }
411
412 // Transfer the block
413 In.Limit(Len);
7330f4df 414 while (Go(true, File) == true)
be4401bf
AL
415 if (In.IsLimit() == true)
416 break;
417
418 // Error
419 if (In.IsLimit() == false)
420 return false;
421
422 // The server sends an extra new line before the next block specifier..
423 In.Limit(-1);
424 Last = true;
425 do
426 {
427 if (In.WriteTillEl(Data,true) == true)
428 break;
429 }
7330f4df 430 while ((Last = Go(false, File)) == true);
be4401bf
AL
431 if (Last == false)
432 return false;
92e889c8 433 }
be4401bf
AL
434 }
435 else
436 {
437 /* Closes encoding is used when the server did not specify a size, the
438 loss of the connection means we are done */
439 if (Encoding == Closes)
440 In.Limit(-1);
441 else
442 In.Limit(Size - StartPos);
443
444 // Just transfer the whole block.
445 do
446 {
447 if (In.IsLimit() == false)
448 continue;
449
450 In.Limit(-1);
e1b96638 451 return !_error->PendingError();
be4401bf 452 }
7330f4df 453 while (Go(true, File) == true);
be4401bf
AL
454 }
455
7330f4df 456 return Owner->Flush() && !_error->PendingError();
be4401bf
AL
457}
458 /*}}}*/
7330f4df 459bool HttpServerState::ReadHeaderLines(std::string &Data) /*{{{*/
be4401bf 460{
7330f4df
DK
461 return In.WriteTillEl(Data);
462}
463 /*}}}*/
464bool HttpServerState::LoadNextResponse(bool const ToFile, FileFd * const File)/*{{{*/
465{
466 return Go(ToFile, File);
467}
468 /*}}}*/
469bool HttpServerState::WriteResponse(const std::string &Data) /*{{{*/
470{
471 return Out.Read(Data);
472}
473 /*}}}*/
a02db58f 474APT_PURE bool HttpServerState::IsOpen() /*{{{*/
7330f4df
DK
475{
476 return (ServerFd != -1);
477}
478 /*}}}*/
479bool HttpServerState::InitHashes(FileFd &File) /*{{{*/
480{
481 delete In.Hash;
482 In.Hash = new Hashes;
30456e14 483
7330f4df 484 // Set the expected size and read file for the hashes
3de8f956
DK
485 File.Truncate(StartPos);
486 return In.Hash->AddFD(File, StartPos);
7330f4df
DK
487}
488 /*}}}*/
a02db58f 489APT_PURE Hashes * HttpServerState::GetHashes() /*{{{*/
7330f4df
DK
490{
491 return In.Hash;
492}
493 /*}}}*/
494// HttpServerState::Die - The server has closed the connection. /*{{{*/
495bool HttpServerState::Die(FileFd &File)
496{
497 unsigned int LErrno = errno;
be4401bf 498
7330f4df
DK
499 // Dump the buffer to the file
500 if (State == ServerState::Data)
be4401bf 501 {
7330f4df
DK
502 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
503 // can't be set
504 if (File.Name() != "/dev/null")
505 SetNonBlock(File.Fd(),false);
506 while (In.WriteSpace() == true)
be4401bf 507 {
7330f4df
DK
508 if (In.Write(File.Fd()) == false)
509 return _error->Errno("write",_("Error writing to the file"));
e836f356 510
7330f4df
DK
511 // Done
512 if (In.IsLimit() == true)
513 return true;
e836f356 514 }
7330f4df 515 }
b2e465d6 516
7330f4df
DK
517 // See if this is because the server finished the data stream
518 if (In.IsLimit() == false && State != HttpServerState::Header &&
519 Encoding != HttpServerState::Closes)
be4401bf 520 {
7330f4df
DK
521 Close();
522 if (LErrno == 0)
523 return _error->Error(_("Error reading from server. Remote end closed connection"));
524 errno = LErrno;
525 return _error->Errno("read",_("Error reading from server"));
be4401bf 526 }
7330f4df 527 else
92e889c8 528 {
7330f4df
DK
529 In.Limit(-1);
530
531 // Nothing left in the buffer
532 if (In.WriteSpace() == false)
533 return false;
534
535 // We may have got multiple responses back in one packet..
536 Close();
92e889c8
AL
537 return true;
538 }
331e8396 539
7330f4df
DK
540 return false;
541}
542 /*}}}*/
543// HttpServerState::Flush - Dump the buffer into the file /*{{{*/
544// ---------------------------------------------------------------------
545/* This takes the current input buffer from the Server FD and writes it
546 into the file */
547bool HttpServerState::Flush(FileFd * const File)
548{
549 if (File != NULL)
550 {
551 // on GNU/kFreeBSD, apt dies on /dev/null because non-blocking
552 // can't be set
553 if (File->Name() != "/dev/null")
554 SetNonBlock(File->Fd(),false);
555 if (In.WriteSpace() == false)
556 return true;
557
558 while (In.WriteSpace() == true)
331e8396 559 {
7330f4df
DK
560 if (In.Write(File->Fd()) == false)
561 return _error->Errno("write",_("Error writing to file"));
562 if (In.IsLimit() == true)
563 return true;
331e8396 564 }
7330f4df
DK
565
566 if (In.IsLimit() == true || Encoding == ServerState::Closes)
567 return true;
be4401bf 568 }
7330f4df
DK
569 return false;
570}
571 /*}}}*/
572// HttpServerState::Go - Run a single loop /*{{{*/
573// ---------------------------------------------------------------------
574/* This runs the select loop over the server FDs, Output file FDs and
575 stdin. */
576bool HttpServerState::Go(bool ToFile, FileFd * const File)
577{
578 // Server has closed the connection
579 if (ServerFd == -1 && (In.WriteSpace() == false ||
580 ToFile == false))
581 return false;
582
583 fd_set rfds,wfds;
584 FD_ZERO(&rfds);
585 FD_ZERO(&wfds);
586
587 /* Add the server. We only send more requests if the connection will
588 be persisting */
589 if (Out.WriteSpace() == true && ServerFd != -1
590 && Persistent == true)
591 FD_SET(ServerFd,&wfds);
592 if (In.ReadSpace() == true && ServerFd != -1)
593 FD_SET(ServerFd,&rfds);
be4401bf 594
7330f4df
DK
595 // Add the file
596 int FileFD = -1;
597 if (File != NULL)
598 FileFD = File->Fd();
599
600 if (In.WriteSpace() == true && ToFile == true && FileFD != -1)
601 FD_SET(FileFD,&wfds);
602
603 // Add stdin
604 if (_config->FindB("Acquire::http::DependOnSTDIN", true) == true)
605 FD_SET(STDIN_FILENO,&rfds);
606
607 // Figure out the max fd
608 int MaxFd = FileFD;
609 if (MaxFd < ServerFd)
610 MaxFd = ServerFd;
611
612 // Select
613 struct timeval tv;
614 tv.tv_sec = TimeOut;
615 tv.tv_usec = 0;
616 int Res = 0;
617 if ((Res = select(MaxFd+1,&rfds,&wfds,0,&tv)) < 0)
be4401bf 618 {
7330f4df
DK
619 if (errno == EINTR)
620 return true;
621 return _error->Errno("select",_("Select failed"));
be4401bf 622 }
7330f4df
DK
623
624 if (Res == 0)
e836f356 625 {
7330f4df
DK
626 _error->Error(_("Connection timed out"));
627 return Die(*File);
e836f356
AL
628 }
629
7330f4df
DK
630 // Handle server IO
631 if (ServerFd != -1 && FD_ISSET(ServerFd,&rfds))
be4401bf 632 {
7330f4df
DK
633 errno = 0;
634 if (In.Read(ServerFd) == false)
635 return Die(*File);
636 }
637
638 if (ServerFd != -1 && FD_ISSET(ServerFd,&wfds))
639 {
640 errno = 0;
641 if (Out.Write(ServerFd) == false)
642 return Die(*File);
be4401bf
AL
643 }
644
7330f4df
DK
645 // Send data to the file
646 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
15d7e515 647 {
7330f4df
DK
648 if (In.Write(FileFD) == false)
649 return _error->Errno("write",_("Error writing to output file"));
15d7e515
MV
650 }
651
7330f4df
DK
652 // Handle commands from APT
653 if (FD_ISSET(STDIN_FILENO,&rfds))
654 {
655 if (Owner->Run(true) != -1)
656 exit(100);
657 }
658
be4401bf
AL
659 return true;
660}
661 /*}}}*/
662
663// HttpMethod::SendReq - Send the HTTP request /*{{{*/
664// ---------------------------------------------------------------------
665/* This places the http request in the outbound buffer */
7330f4df 666void HttpMethod::SendReq(FetchItem *Itm)
be4401bf
AL
667{
668 URI Uri = Itm->Uri;
c1a22377 669
be4401bf 670 // The HTTP server expects a hostname with a trailing :port
b123b0ba 671 std::stringstream Req;
5b63d2a9
MV
672 string ProperHost;
673
674 if (Uri.Host.find(':') != string::npos)
675 ProperHost = '[' + Uri.Host + ']';
676 else
677 ProperHost = Uri.Host;
f2380a78
DK
678
679 /* RFC 2616 ยง5.1.2 requires absolute URIs for requests to proxies,
680 but while its a must for all servers to accept absolute URIs,
681 it is assumed clients will sent an absolute path for non-proxies */
682 std::string requesturi;
7330f4df 683 if (Server->Proxy.empty() == true || Server->Proxy.Host.empty())
f2380a78
DK
684 requesturi = Uri.Path;
685 else
686 requesturi = Itm->Uri;
687
688 // The "+" is encoded as a workaround for a amazon S3 bug
689 // see LP bugs #1003633 and #1086997.
690 requesturi = QuoteString(requesturi, "+~ ");
691
2b9c9b7f
RG
692 /* Build the request. No keep-alive is included as it is the default
693 in 1.1, can cause problems with proxies, and we are an HTTP/1.1
694 client anyway.
695 C.f. https://tools.ietf.org/wg/httpbis/trac/ticket/158 */
b123b0ba
DK
696 Req << "GET " << requesturi << " HTTP/1.1\r\n";
697 if (Uri.Port != 0)
698 Req << "Host: " << ProperHost << ":" << Uri.Port << "\r\n";
699 else
700 Req << "Host: " << ProperHost << "\r\n";
f2380a78 701
c9cd3b70 702 // generate a cache control header (if needed)
b123b0ba
DK
703 if (_config->FindB("Acquire::http::No-Cache",false) == true)
704 Req << "Cache-Control: no-cache\r\n"
705 << "Pragma: no-cache\r\n";
706 else if (Itm->IndexFile == true)
707 Req << "Cache-Control: max-age=" << _config->FindI("Acquire::http::Max-Age",0) << "\r\n";
708 else if (_config->FindB("Acquire::http::No-Store",false) == true)
709 Req << "Cache-Control: no-store\r\n";
106e6740 710
6f4501f9 711 // If we ask for uncompressed files servers might respond with content-
1e3f4083 712 // negotiation which lets us end up with compressed files we do not support,
6f4501f9
DK
713 // see 657029, 657560 and co, so if we have no extension on the request
714 // ask for text only. As a sidenote: If there is nothing to negotate servers
715 // seem to be nice and ignore it.
716 if (_config->FindB("Acquire::http::SendAccept", true) == true)
717 {
718 size_t const filepos = Itm->Uri.find_last_of('/');
719 string const file = Itm->Uri.substr(filepos + 1);
720 if (flExtension(file) == file)
b123b0ba 721 Req << "Accept: text/*\r\n";
6f4501f9
DK
722 }
723
b123b0ba 724 // Check for a partial file and send if-queries accordingly
be4401bf
AL
725 struct stat SBuf;
726 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
b123b0ba
DK
727 Req << "Range: bytes=" << SBuf.st_size << "-\r\n"
728 << "If-Range: " << TimeRFC1123(SBuf.st_mtime) << "\r\n";
729 else if (Itm->LastModified != 0)
730 Req << "If-Modified-Since: " << TimeRFC1123(Itm->LastModified).c_str() << "\r\n";
be4401bf 731
7330f4df 732 if (Server->Proxy.User.empty() == false || Server->Proxy.Password.empty() == false)
b123b0ba
DK
733 Req << "Proxy-Authorization: Basic "
734 << Base64Encode(Server->Proxy.User + ":" + Server->Proxy.Password) << "\r\n";
be4401bf 735
1de1f703 736 maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
b2e465d6 737 if (Uri.User.empty() == false || Uri.Password.empty() == false)
b123b0ba
DK
738 Req << "Authorization: Basic "
739 << Base64Encode(Uri.User + ":" + Uri.Password) << "\r\n";
740
741 Req << "User-Agent: " << _config->Find("Acquire::http::User-Agent",
742 "Debian APT-HTTP/1.3 (" PACKAGE_VERSION ")") << "\r\n";
743
744 Req << "\r\n";
745
c98b1307
AL
746 if (Debug == true)
747 cerr << Req << endl;
c1a22377 748
b123b0ba 749 Server->WriteResponse(Req.str());
be4401bf
AL
750}
751 /*}}}*/
85f72a56
AL
752// HttpMethod::Configuration - Handle a configuration message /*{{{*/
753// ---------------------------------------------------------------------
754/* We stash the desired pipeline depth */
755bool HttpMethod::Configuration(string Message)
756{
7330f4df 757 if (ServerMethod::Configuration(Message) == false)
85f72a56 758 return false;
7330f4df 759
15d7e515 760 AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
30456e14
AL
761 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
762 PipelineDepth);
c98b1307 763 Debug = _config->FindB("Debug::Acquire::http",false);
bd49b02c
MV
764
765 // Get the proxy to use
766 AutoDetectProxy();
767
85f72a56
AL
768 return true;
769}
770 /*}}}*/
bd49b02c
MV
771// HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
772// ---------------------------------------------------------------------
773/* */
774bool HttpMethod::AutoDetectProxy()
775{
c08cf1dc
MV
776 // option is "Acquire::http::Proxy-Auto-Detect" but we allow the old
777 // name without the dash ("-")
778 AutoDetectProxyCmd = _config->Find("Acquire::http::Proxy-Auto-Detect",
779 _config->Find("Acquire::http::ProxyAutoDetect"));
780
bd49b02c
MV
781 if (AutoDetectProxyCmd.empty())
782 return true;
783
784 if (Debug)
785 clog << "Using auto proxy detect command: " << AutoDetectProxyCmd << endl;
786
787 int Pipes[2] = {-1,-1};
788 if (pipe(Pipes) != 0)
789 return _error->Errno("pipe", "Failed to create Pipe");
790
791 pid_t Process = ExecFork();
792 if (Process == 0)
793 {
08ded4d6 794 close(Pipes[0]);
bd49b02c
MV
795 dup2(Pipes[1],STDOUT_FILENO);
796 SetCloseExec(STDOUT_FILENO,false);
08ded4d6 797
bd49b02c
MV
798 const char *Args[2];
799 Args[0] = AutoDetectProxyCmd.c_str();
800 Args[1] = 0;
801 execv(Args[0],(char **)Args);
802 cerr << "Failed to exec method " << Args[0] << endl;
803 _exit(100);
804 }
805 char buf[512];
806 int InFd = Pipes[0];
08ded4d6 807 close(Pipes[1]);
c1042000 808 int res = read(InFd, buf, sizeof(buf)-1);
08ded4d6
MV
809 ExecWait(Process, "ProxyAutoDetect", true);
810
811 if (res < 0)
bd49b02c 812 return _error->Errno("read", "Failed to read");
08ded4d6
MV
813 if (res == 0)
814 return _error->Warning("ProxyAutoDetect returned no data");
815
816 // add trailing \0
817 buf[res] = 0;
818
bd49b02c
MV
819 if (Debug)
820 clog << "auto detect command returned: '" << buf << "'" << endl;
821
822 if (strstr(buf, "http://") == buf)
823 _config->Set("Acquire::http::proxy", _strstrip(buf));
824
825 return true;
826}
827 /*}}}*/
7330f4df
DK
828ServerState * HttpMethod::CreateServerState(URI uri) /*{{{*/
829{
830 return new HttpServerState(uri, this);
831}
832 /*}}}*/
fd46d305
DK
833void HttpMethod::RotateDNS() /*{{{*/
834{
835 ::RotateDNS();
836}
837 /*}}}*/