7c7949eac8ef531b4224dab3eedeebe61dcfb316
[ntk/apt.git] / methods / http.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Description /*{{{*/
3 // $Id: http.cc,v 1.59 2004/05/08 19:42:35 mdz Exp $
4 /* ######################################################################
5
6 HTTP Acquire Method - This is the HTTP acquire method for APT.
7
8 It uses HTTP/1.1 and many of the fancy options there-in, such as
9 pipelining, range, if-range and so on.
10
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).
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 <config.h>
29
30 #include <apt-pkg/fileutl.h>
31 #include <apt-pkg/acquire-method.h>
32 #include <apt-pkg/configuration.h>
33 #include <apt-pkg/error.h>
34 #include <apt-pkg/hashes.h>
35 #include <apt-pkg/netrc.h>
36 #include <apt-pkg/strutl.h>
37
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <sys/select.h>
41 #include <cstring>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <unistd.h>
45 #include <stdio.h>
46 #include <errno.h>
47 #include <iostream>
48 #include <sstream>
49
50 #include "config.h"
51 #include "connect.h"
52 #include "http.h"
53
54 #include <apti18n.h>
55 /*}}}*/
56 using namespace std;
57
58 unsigned long long CircleBuf::BwReadLimit=0;
59 unsigned long long CircleBuf::BwTickReadData=0;
60 struct timeval CircleBuf::BwReadTick={0,0};
61 const unsigned int CircleBuf::BW_HZ=10;
62
63 // CircleBuf::CircleBuf - Circular input buffer /*{{{*/
64 // ---------------------------------------------------------------------
65 /* */
66 CircleBuf::CircleBuf(unsigned long long Size) : Size(Size), Hash(0)
67 {
68 Buf = new unsigned char[Size];
69 Reset();
70
71 CircleBuf::BwReadLimit = _config->FindI("Acquire::http::Dl-Limit",0)*1024;
72 }
73 /*}}}*/
74 // CircleBuf::Reset - Reset to the default state /*{{{*/
75 // ---------------------------------------------------------------------
76 /* */
77 void CircleBuf::Reset()
78 {
79 InP = 0;
80 OutP = 0;
81 StrPos = 0;
82 MaxGet = (unsigned long long)-1;
83 OutQueue = string();
84 if (Hash != 0)
85 {
86 delete Hash;
87 Hash = new Hashes;
88 }
89 }
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.. */
95 bool CircleBuf::Read(int Fd)
96 {
97 while (1)
98 {
99 // Woops, buffer is full
100 if (InP - OutP == Size)
101 return true;
102
103 // what's left to read in this tick
104 unsigned long long const BwReadMax = CircleBuf::BwReadLimit/BW_HZ;
105
106 if(CircleBuf::BwReadLimit) {
107 struct timeval now;
108 gettimeofday(&now,0);
109
110 unsigned long long d = (now.tv_sec-CircleBuf::BwReadTick.tv_sec)*1000000 +
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
123 // Write the buffer segment
124 ssize_t Res;
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());
130
131 if(Res > 0 && BwReadLimit > 0)
132 CircleBuf::BwTickReadData += Res;
133
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 */
152 bool 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 /* */
162 void 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
173 unsigned long long Sz = LeftRead();
174 if (OutQueue.length() - StrPos < Sz)
175 Sz = OutQueue.length() - StrPos;
176 memcpy(Buf + (InP%Size),OutQueue.c_str() + StrPos,Sz);
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. */
193 bool 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
207 ssize_t Res;
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
220 if (Hash != 0)
221 Hash->Add(Buf + (OutP%Size),Res);
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 */
230 bool CircleBuf::WriteTillEl(string &Data,bool Single)
231 {
232 // We cheat and assume it is unneeded to have more than one buffer load
233 for (unsigned long long I = OutP; I < InP; I++)
234 {
235 if (Buf[I%Size] != '\n')
236 continue;
237 ++I;
238
239 if (Single == false)
240 {
241 if (I < InP && Buf[I%Size] == '\r')
242 ++I;
243 if (I >= InP || Buf[I%Size] != '\n')
244 continue;
245 ++I;
246 }
247
248 Data = "";
249 while (OutP < I)
250 {
251 unsigned long long Sz = LeftWrite();
252 if (Sz == 0)
253 return false;
254 if (I - OutP < Sz)
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 /* */
267 void 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 /*}}}*/
279 CircleBuf::~CircleBuf()
280 {
281 delete [] Buf;
282 delete Hash;
283 }
284
285 // HttpServerState::HttpServerState - Constructor /*{{{*/
286 HttpServerState::HttpServerState(URI Srv,HttpMethod *Owner) : ServerState(Srv, Owner), In(64*1024), Out(4*1024)
287 {
288 TimeOut = _config->FindI("Acquire::http::Timeout",TimeOut);
289 Reset();
290 }
291 /*}}}*/
292 // HttpServerState::Open - Open a connection to the server /*{{{*/
293 // ---------------------------------------------------------------------
294 /* This opens a connection to the server. */
295 bool HttpServerState::Open()
296 {
297 // Use the already open connection if possible.
298 if (ServerFd != -1)
299 return true;
300
301 Close();
302 In.Reset();
303 Out.Reset();
304 Persistent = true;
305
306 // Determine the proxy setting
307 string SpecificProxy = _config->Find("Acquire::http::Proxy::" + ServerName.Host);
308 if (!SpecificProxy.empty())
309 {
310 if (SpecificProxy == "DIRECT")
311 Proxy = "";
312 else
313 Proxy = SpecificProxy;
314 }
315 else
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 }
328
329 // Parse no_proxy, a , separated list of domains
330 if (getenv("no_proxy") != 0)
331 {
332 if (CheckDomainList(ServerName.Host,getenv("no_proxy")) == true)
333 Proxy = "";
334 }
335
336 // Determine what host and port to use based on the proxy settings
337 int Port = 0;
338 string Host;
339 if (Proxy.empty() == true || Proxy.Host.empty() == true)
340 {
341 if (ServerName.Port != 0)
342 Port = ServerName.Port;
343 Host = ServerName.Host;
344 }
345 else
346 {
347 if (Proxy.Port != 0)
348 Port = Proxy.Port;
349 Host = Proxy.Host;
350 }
351
352 // Connect to the remote server
353 if (Connect(Host,Port,"http",80,ServerFd,TimeOut,Owner) == false)
354 return false;
355
356 return true;
357 }
358 /*}}}*/
359 // HttpServerState::Close - Close a connection to the server /*{{{*/
360 // ---------------------------------------------------------------------
361 /* */
362 bool HttpServerState::Close()
363 {
364 close(ServerFd);
365 ServerFd = -1;
366 return true;
367 }
368 /*}}}*/
369 // HttpServerState::RunData - Transfer the data from the socket /*{{{*/
370 bool HttpServerState::RunData(FileFd * const File)
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 }
388 while ((Last = Go(false, File)) == true);
389
390 if (Last == false)
391 return false;
392
393 // See if we are done
394 unsigned long long Len = strtoull(Data.c_str(),0,16);
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 }
406 while ((Last = Go(false, File)) == true);
407 if (Last == false)
408 return false;
409 return !_error->PendingError();
410 }
411
412 // Transfer the block
413 In.Limit(Len);
414 while (Go(true, File) == true)
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 }
430 while ((Last = Go(false, File)) == true);
431 if (Last == false)
432 return false;
433 }
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);
451 return !_error->PendingError();
452 }
453 while (Go(true, File) == true);
454 }
455
456 return Owner->Flush() && !_error->PendingError();
457 }
458 /*}}}*/
459 bool HttpServerState::ReadHeaderLines(std::string &Data) /*{{{*/
460 {
461 return In.WriteTillEl(Data);
462 }
463 /*}}}*/
464 bool HttpServerState::LoadNextResponse(bool const ToFile, FileFd * const File)/*{{{*/
465 {
466 return Go(ToFile, File);
467 }
468 /*}}}*/
469 bool HttpServerState::WriteResponse(const std::string &Data) /*{{{*/
470 {
471 return Out.Read(Data);
472 }
473 /*}}}*/
474 APT_PURE bool HttpServerState::IsOpen() /*{{{*/
475 {
476 return (ServerFd != -1);
477 }
478 /*}}}*/
479 bool HttpServerState::InitHashes(FileFd &File) /*{{{*/
480 {
481 delete In.Hash;
482 In.Hash = new Hashes;
483
484 // Set the expected size and read file for the hashes
485 File.Truncate(StartPos);
486 return In.Hash->AddFD(File, StartPos);
487 }
488 /*}}}*/
489 APT_PURE Hashes * HttpServerState::GetHashes() /*{{{*/
490 {
491 return In.Hash;
492 }
493 /*}}}*/
494 // HttpServerState::Die - The server has closed the connection. /*{{{*/
495 bool HttpServerState::Die(FileFd &File)
496 {
497 unsigned int LErrno = errno;
498
499 // Dump the buffer to the file
500 if (State == ServerState::Data)
501 {
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)
507 {
508 if (In.Write(File.Fd()) == false)
509 return _error->Errno("write",_("Error writing to the file"));
510
511 // Done
512 if (In.IsLimit() == true)
513 return true;
514 }
515 }
516
517 // See if this is because the server finished the data stream
518 if (In.IsLimit() == false && State != HttpServerState::Header &&
519 Encoding != HttpServerState::Closes)
520 {
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"));
526 }
527 else
528 {
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();
537 return true;
538 }
539
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 */
547 bool 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)
559 {
560 if (In.Write(File->Fd()) == false)
561 return _error->Errno("write",_("Error writing to file"));
562 if (In.IsLimit() == true)
563 return true;
564 }
565
566 if (In.IsLimit() == true || Encoding == ServerState::Closes)
567 return true;
568 }
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. */
576 bool 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);
594
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)
618 {
619 if (errno == EINTR)
620 return true;
621 return _error->Errno("select",_("Select failed"));
622 }
623
624 if (Res == 0)
625 {
626 _error->Error(_("Connection timed out"));
627 return Die(*File);
628 }
629
630 // Handle server IO
631 if (ServerFd != -1 && FD_ISSET(ServerFd,&rfds))
632 {
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);
643 }
644
645 // Send data to the file
646 if (FileFD != -1 && FD_ISSET(FileFD,&wfds))
647 {
648 if (In.Write(FileFD) == false)
649 return _error->Errno("write",_("Error writing to output file"));
650 }
651
652 // Handle commands from APT
653 if (FD_ISSET(STDIN_FILENO,&rfds))
654 {
655 if (Owner->Run(true) != -1)
656 exit(100);
657 }
658
659 return true;
660 }
661 /*}}}*/
662
663 // HttpMethod::SendReq - Send the HTTP request /*{{{*/
664 // ---------------------------------------------------------------------
665 /* This places the http request in the outbound buffer */
666 void HttpMethod::SendReq(FetchItem *Itm)
667 {
668 URI Uri = Itm->Uri;
669
670 // The HTTP server expects a hostname with a trailing :port
671 std::stringstream Req;
672 string ProperHost;
673
674 if (Uri.Host.find(':') != string::npos)
675 ProperHost = '[' + Uri.Host + ']';
676 else
677 ProperHost = Uri.Host;
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;
683 if (Server->Proxy.empty() == true || Server->Proxy.Host.empty())
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
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 */
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";
701
702 // generate a cache control header (if needed)
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";
710
711 // If we ask for uncompressed files servers might respond with content-
712 // negotiation which lets us end up with compressed files we do not support,
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)
721 Req << "Accept: text/*\r\n";
722 }
723
724 // Check for a partial file and send if-queries accordingly
725 struct stat SBuf;
726 if (stat(Itm->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
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";
731
732 if (Server->Proxy.User.empty() == false || Server->Proxy.Password.empty() == false)
733 Req << "Proxy-Authorization: Basic "
734 << Base64Encode(Server->Proxy.User + ":" + Server->Proxy.Password) << "\r\n";
735
736 maybe_add_auth (Uri, _config->FindFile("Dir::Etc::netrc"));
737 if (Uri.User.empty() == false || Uri.Password.empty() == false)
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
746 if (Debug == true)
747 cerr << Req.str() << endl;
748
749 Server->WriteResponse(Req.str());
750 }
751 /*}}}*/
752 // HttpMethod::Configuration - Handle a configuration message /*{{{*/
753 // ---------------------------------------------------------------------
754 /* We stash the desired pipeline depth */
755 bool HttpMethod::Configuration(string Message)
756 {
757 if (ServerMethod::Configuration(Message) == false)
758 return false;
759
760 AllowRedirect = _config->FindB("Acquire::http::AllowRedirect",true);
761 PipelineDepth = _config->FindI("Acquire::http::Pipeline-Depth",
762 PipelineDepth);
763 Debug = _config->FindB("Debug::Acquire::http",false);
764
765 // Get the proxy to use
766 AutoDetectProxy();
767
768 return true;
769 }
770 /*}}}*/
771 // HttpMethod::AutoDetectProxy - auto detect proxy /*{{{*/
772 // ---------------------------------------------------------------------
773 /* */
774 bool HttpMethod::AutoDetectProxy()
775 {
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
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 {
794 close(Pipes[0]);
795 dup2(Pipes[1],STDOUT_FILENO);
796 SetCloseExec(STDOUT_FILENO,false);
797
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];
807 close(Pipes[1]);
808 int res = read(InFd, buf, sizeof(buf)-1);
809 ExecWait(Process, "ProxyAutoDetect", true);
810
811 if (res < 0)
812 return _error->Errno("read", "Failed to read");
813 if (res == 0)
814 return _error->Warning("ProxyAutoDetect returned no data");
815
816 // add trailing \0
817 buf[res] = 0;
818
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 /*}}}*/
828 ServerState * HttpMethod::CreateServerState(URI uri) /*{{{*/
829 {
830 return new HttpServerState(uri, this);
831 }
832 /*}}}*/
833 void HttpMethod::RotateDNS() /*{{{*/
834 {
835 ::RotateDNS();
836 }
837 /*}}}*/