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