]> git.saurik.com Git - apt.git/blame - methods/server.cc
Italian program translation update
[apt.git] / methods / server.cc
CommitLineData
7330f4df
DK
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
3/* ######################################################################
4
5 HTTP and HTTPS share a lot of common code and these classes are
6 exactly the dumping ground for this common code
7
8 ##################################################################### */
9 /*}}}*/
10// Include Files /*{{{*/
11#include <config.h>
12
7330f4df
DK
13#include <apt-pkg/acquire-method.h>
14#include <apt-pkg/configuration.h>
15#include <apt-pkg/error.h>
453b82a3
DK
16#include <apt-pkg/fileutl.h>
17#include <apt-pkg/strutl.h>
7330f4df 18
453b82a3
DK
19#include <ctype.h>
20#include <signal.h>
21#include <stdio.h>
22#include <stdlib.h>
7330f4df
DK
23#include <sys/stat.h>
24#include <sys/time.h>
453b82a3 25#include <time.h>
7330f4df 26#include <unistd.h>
7330f4df 27#include <iostream>
453b82a3 28#include <limits>
7330f4df 29#include <map>
453b82a3
DK
30#include <string>
31#include <vector>
7330f4df 32
453b82a3 33#include "server.h"
7330f4df
DK
34
35#include <apti18n.h>
36 /*}}}*/
37using namespace std;
38
39string ServerMethod::FailFile;
40int ServerMethod::FailFd = -1;
41time_t ServerMethod::FailTime = 0;
42
43// ServerState::RunHeaders - Get the headers before the data /*{{{*/
44// ---------------------------------------------------------------------
45/* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
46 parse error occurred */
9622b211
MV
47ServerState::RunHeadersResult ServerState::RunHeaders(FileFd * const File,
48 const std::string &Uri)
7330f4df
DK
49{
50 State = Header;
51
52 Owner->Status(_("Waiting for headers"));
53
54 Major = 0;
55 Minor = 0;
56 Result = 0;
57 Size = 0;
ed793a19 58 JunkSize = 0;
7330f4df
DK
59 StartPos = 0;
60 Encoding = Closes;
61 HaveContent = false;
62 time(&Date);
63
64 do
65 {
66 string Data;
67 if (ReadHeaderLines(Data) == false)
68 continue;
69
70 if (Owner->Debug == true)
9622b211 71 clog << "Answer for: " << Uri << endl << Data;
7330f4df
DK
72
73 for (string::const_iterator I = Data.begin(); I < Data.end(); ++I)
74 {
75 string::const_iterator J = I;
76 for (; J != Data.end() && *J != '\n' && *J != '\r'; ++J);
77 if (HeaderLine(string(I,J)) == false)
78 return RUN_HEADERS_PARSE_ERROR;
79 I = J;
80 }
81
82 // 100 Continue is a Nop...
83 if (Result == 100)
84 continue;
85
1e3f4083 86 // Tidy up the connection persistence state.
7330f4df
DK
87 if (Encoding == Closes && HaveContent == true)
88 Persistent = false;
89
90 return RUN_HEADERS_OK;
91 }
92 while (LoadNextResponse(false, File) == true);
93
94 return RUN_HEADERS_IO_ERROR;
95}
96 /*}}}*/
97// ServerState::HeaderLine - Process a header line /*{{{*/
98// ---------------------------------------------------------------------
99/* */
100bool ServerState::HeaderLine(string Line)
101{
102 if (Line.empty() == true)
103 return true;
104
105 string::size_type Pos = Line.find(' ');
106 if (Pos == string::npos || Pos+1 > Line.length())
107 {
108 // Blah, some servers use "connection:closes", evil.
109 Pos = Line.find(':');
110 if (Pos == string::npos || Pos + 2 > Line.length())
111 return _error->Error(_("Bad header line"));
112 Pos++;
113 }
114
115 // Parse off any trailing spaces between the : and the next word.
116 string::size_type Pos2 = Pos;
117 while (Pos2 < Line.length() && isspace(Line[Pos2]) != 0)
118 Pos2++;
d3e8fbb3 119
7330f4df
DK
120 string Tag = string(Line,0,Pos);
121 string Val = string(Line,Pos2);
d3e8fbb3 122
7330f4df
DK
123 if (stringcasecmp(Tag.c_str(),Tag.c_str()+4,"HTTP") == 0)
124 {
125 // Evil servers return no version
126 if (Line[4] == '/')
127 {
128 int const elements = sscanf(Line.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major,&Minor,&Result,Code);
129 if (elements == 3)
130 {
131 Code[0] = '\0';
0c2dc43d 132 if (Owner != NULL && Owner->Debug == true)
7330f4df
DK
133 clog << "HTTP server doesn't give Reason-Phrase for " << Result << std::endl;
134 }
135 else if (elements != 4)
136 return _error->Error(_("The HTTP server sent an invalid reply header"));
137 }
138 else
139 {
140 Major = 0;
141 Minor = 9;
142 if (sscanf(Line.c_str(),"HTTP %3u%359[^\n]",&Result,Code) != 2)
143 return _error->Error(_("The HTTP server sent an invalid reply header"));
144 }
145
1e3f4083 146 /* Check the HTTP response header to get the default persistence
7330f4df
DK
147 state. */
148 if (Major < 1)
149 Persistent = false;
150 else
151 {
152 if (Major == 1 && Minor == 0)
153 Persistent = false;
154 else
155 Persistent = true;
156 }
157
158 return true;
d3e8fbb3
DK
159 }
160
7330f4df
DK
161 if (stringcasecmp(Tag,"Content-Length:") == 0)
162 {
163 if (Encoding == Closes)
164 Encoding = Stream;
165 HaveContent = true;
d3e8fbb3 166
ed793a19
DK
167 unsigned long long * SizePtr = &Size;
168 if (Result == 416)
169 SizePtr = &JunkSize;
7330f4df 170
ed793a19
DK
171 *SizePtr = strtoull(Val.c_str(), NULL, 10);
172 if (*SizePtr >= std::numeric_limits<unsigned long long>::max())
7330f4df 173 return _error->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
ed793a19 174 else if (*SizePtr == 0)
7330f4df
DK
175 HaveContent = false;
176 return true;
177 }
178
179 if (stringcasecmp(Tag,"Content-Type:") == 0)
180 {
181 HaveContent = true;
182 return true;
183 }
d3e8fbb3 184
7330f4df
DK
185 if (stringcasecmp(Tag,"Content-Range:") == 0)
186 {
187 HaveContent = true;
188
189 // §14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
190 if (Result == 416 && sscanf(Val.c_str(), "bytes */%llu",&Size) == 1)
ed793a19 191 ; // we got the expected filesize which is all we wanted
7330f4df
DK
192 else if (sscanf(Val.c_str(),"bytes %llu-%*u/%llu",&StartPos,&Size) != 2)
193 return _error->Error(_("The HTTP server sent an invalid Content-Range header"));
194 if ((unsigned long long)StartPos > Size)
195 return _error->Error(_("This HTTP server has broken range support"));
196 return true;
197 }
d3e8fbb3 198
7330f4df
DK
199 if (stringcasecmp(Tag,"Transfer-Encoding:") == 0)
200 {
201 HaveContent = true;
202 if (stringcasecmp(Val,"chunked") == 0)
d3e8fbb3 203 Encoding = Chunked;
7330f4df
DK
204 return true;
205 }
206
207 if (stringcasecmp(Tag,"Connection:") == 0)
208 {
209 if (stringcasecmp(Val,"close") == 0)
210 Persistent = false;
211 if (stringcasecmp(Val,"keep-alive") == 0)
212 Persistent = true;
213 return true;
214 }
d3e8fbb3 215
7330f4df
DK
216 if (stringcasecmp(Tag,"Last-Modified:") == 0)
217 {
218 if (RFC1123StrToTime(Val.c_str(), Date) == false)
219 return _error->Error(_("Unknown date format"));
220 return true;
221 }
222
223 if (stringcasecmp(Tag,"Location:") == 0)
224 {
225 Location = Val;
226 return true;
227 }
228
229 return true;
230}
231 /*}}}*/
232// ServerState::ServerState - Constructor /*{{{*/
233ServerState::ServerState(URI Srv, ServerMethod *Owner) : ServerName(Srv), TimeOut(120), Owner(Owner)
234{
235 Reset();
236}
237 /*}}}*/
238
239bool ServerMethod::Configuration(string Message) /*{{{*/
240{
905fba60
DK
241 if (pkgAcqMethod::Configuration(Message) == false)
242 return false;
243
244 DropPrivsOrDie();
245
246 return true;
7330f4df
DK
247}
248 /*}}}*/
249
250// ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
251// ---------------------------------------------------------------------
252/* We look at the header data we got back from the server and decide what
253 to do. Returns DealWithHeadersResult (see http.h for details).
254 */
255ServerMethod::DealWithHeadersResult
256ServerMethod::DealWithHeaders(FetchResult &Res)
257{
258 // Not Modified
259 if (Server->Result == 304)
260 {
261 unlink(Queue->DestFile.c_str());
262 Res.IMSHit = true;
263 Res.LastModified = Queue->LastModified;
264 return IMS_HIT;
265 }
266
267 /* Redirect
268 *
269 * Note that it is only OK for us to treat all redirection the same
270 * because we *always* use GET, not other HTTP methods. There are
271 * three redirection codes for which it is not appropriate that we
272 * redirect. Pass on those codes so the error handling kicks in.
273 */
274 if (AllowRedirect
275 && (Server->Result > 300 && Server->Result < 400)
276 && (Server->Result != 300 // Multiple Choices
277 && Server->Result != 304 // Not Modified
278 && Server->Result != 306)) // (Not part of HTTP/1.1, reserved)
279 {
280 if (Server->Location.empty() == true);
281 else if (Server->Location[0] == '/' && Queue->Uri.empty() == false)
282 {
283 URI Uri = Queue->Uri;
284 if (Uri.Host.empty() == false)
285 NextURI = URI::SiteOnly(Uri);
286 else
287 NextURI.clear();
288 NextURI.append(DeQuoteString(Server->Location));
289 return TRY_AGAIN_OR_REDIRECT;
290 }
291 else
292 {
9082a1fc
DK
293 NextURI = DeQuoteString(Server->Location);
294 URI tmpURI = NextURI;
295 URI Uri = Queue->Uri;
296 // same protocol redirects are okay
297 if (tmpURI.Access == Uri.Access)
298 return TRY_AGAIN_OR_REDIRECT;
299 // as well as http to https
300 else if (Uri.Access == "http" && tmpURI.Access == "https")
301 return TRY_AGAIN_OR_REDIRECT;
7330f4df
DK
302 }
303 /* else pass through for error message */
304 }
305 // retry after an invalid range response without partial data
306 else if (Server->Result == 416)
307 {
308 struct stat SBuf;
309 if (stat(Queue->DestFile.c_str(),&SBuf) >= 0 && SBuf.st_size > 0)
310 {
311 if ((unsigned long long)SBuf.st_size == Server->Size)
312 {
313 // the file is completely downloaded, but was not moved
ed793a19
DK
314 if (Server->HaveContent == true)
315 {
316 // Send to error page to dev/null
317 FileFd DevNull("/dev/null",FileFd::WriteExists);
318 Server->RunData(&DevNull);
319 }
320 Server->HaveContent = false;
7330f4df
DK
321 Server->StartPos = Server->Size;
322 Server->Result = 200;
7330f4df
DK
323 }
324 else if (unlink(Queue->DestFile.c_str()) == 0)
325 {
326 NextURI = Queue->Uri;
327 return TRY_AGAIN_OR_REDIRECT;
328 }
329 }
330 }
331
332 /* We have a reply we dont handle. This should indicate a perm server
333 failure */
334 if (Server->Result < 200 || Server->Result >= 300)
335 {
84361def
DK
336 std::string err;
337 strprintf(err, "HttpError%u", Server->Result);
7330f4df 338 SetFailReason(err);
84361def 339 _error->Error("%u %s", Server->Result, Server->Code);
7330f4df
DK
340 if (Server->HaveContent == true)
341 return ERROR_WITH_CONTENT_PAGE;
342 return ERROR_UNRECOVERABLE;
343 }
344
345 // This is some sort of 2xx 'data follows' reply
346 Res.LastModified = Server->Date;
347 Res.Size = Server->Size;
348
349 // Open the file
350 delete File;
351 File = new FileFd(Queue->DestFile,FileFd::WriteAny);
352 if (_error->PendingError() == true)
353 return ERROR_NOT_FROM_SERVER;
354
355 FailFile = Queue->DestFile;
356 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
357 FailFd = File->Fd();
358 FailTime = Server->Date;
359
9224ce3d 360 if (Server->InitHashes(*File, Queue->ExpectedHashes) == false)
7330f4df
DK
361 {
362 _error->Errno("read",_("Problem hashing file"));
363 return ERROR_NOT_FROM_SERVER;
364 }
365 if (Server->StartPos > 0)
366 Res.ResumePoint = Server->StartPos;
367
368 SetNonBlock(File->Fd(),true);
369 return FILE_IS_OPEN;
370}
371 /*}}}*/
372// ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
373// ---------------------------------------------------------------------
1e3f4083 374/* This closes and timestamps the open file. This is necessary to get
7330f4df
DK
375 resume behavoir on user abort */
376void ServerMethod::SigTerm(int)
377{
378 if (FailFd == -1)
379 _exit(100);
9ce3cfc9 380
246bbb61 381 struct timeval times[2];
9ce3cfc9
DK
382 times[0].tv_sec = FailTime;
383 times[1].tv_sec = FailTime;
246bbb61
DK
384 times[0].tv_usec = times[1].tv_usec = 0;
385 utimes(FailFile.c_str(), times);
7330f4df 386 close(FailFd);
9ce3cfc9 387
7330f4df
DK
388 _exit(100);
389}
390 /*}}}*/
391// ServerMethod::Fetch - Fetch an item /*{{{*/
392// ---------------------------------------------------------------------
393/* This adds an item to the pipeline. We keep the pipeline at a fixed
394 depth. */
395bool ServerMethod::Fetch(FetchItem *)
396{
397 if (Server == 0)
398 return true;
399
400 // Queue the requests
401 int Depth = -1;
402 for (FetchItem *I = Queue; I != 0 && Depth < (signed)PipelineDepth;
403 I = I->Next, Depth++)
404 {
895417ef
DK
405 if (Depth >= 0)
406 {
407 // If pipelining is disabled, we only queue 1 request
408 if (Server->Pipeline == false)
409 break;
410 // if we have no hashes, do at most one such request
411 // as we can't fixup pipeling misbehaviors otherwise
412 else if (I->ExpectedHashes.usable() == false)
413 break;
414 }
7330f4df
DK
415
416 // Make sure we stick with the same server
417 if (Server->Comp(I->Uri) == false)
418 break;
419 if (QueueBack == I)
420 {
421 QueueBack = I->Next;
422 SendReq(I);
423 continue;
424 }
425 }
426
427 return true;
d3e8fbb3 428}
7330f4df
DK
429 /*}}}*/
430// ServerMethod::Loop - Main loop /*{{{*/
431int ServerMethod::Loop()
432{
433 typedef vector<string> StringVector;
434 typedef vector<string>::iterator StringVectorIterator;
435 map<string, StringVector> Redirected;
436
437 signal(SIGTERM,SigTerm);
438 signal(SIGINT,SigTerm);
439
440 Server = 0;
441
442 int FailCounter = 0;
443 while (1)
444 {
445 // We have no commands, wait for some to arrive
446 if (Queue == 0)
447 {
448 if (WaitFd(STDIN_FILENO) == false)
449 return 0;
450 }
451
452 /* Run messages, we can accept 0 (no message) if we didn't
453 do a WaitFd above.. Otherwise the FD is closed. */
454 int Result = Run(true);
455 if (Result != -1 && (Result != 0 || Queue == 0))
456 {
457 if(FailReason.empty() == false ||
458 _config->FindB("Acquire::http::DependOnSTDIN", true) == true)
459 return 100;
460 else
461 return 0;
462 }
463
464 if (Queue == 0)
465 continue;
466
467 // Connect to the server
468 if (Server == 0 || Server->Comp(Queue->Uri) == false)
469 {
470 delete Server;
471 Server = CreateServerState(Queue->Uri);
472 }
473 /* If the server has explicitly said this is the last connection
474 then we pre-emptively shut down the pipeline and tear down
475 the connection. This will speed up HTTP/1.0 servers a tad
476 since we don't have to wait for the close sequence to
477 complete */
478 if (Server->Persistent == false)
479 Server->Close();
480
481 // Reset the pipeline
482 if (Server->IsOpen() == false)
483 QueueBack = Queue;
484
485 // Connnect to the host
486 if (Server->Open() == false)
487 {
488 Fail(true);
489 delete Server;
490 Server = 0;
491 continue;
492 }
493
494 // Fill the pipeline.
495 Fetch(0);
496
497 // Fetch the next URL header data from the server.
9622b211 498 switch (Server->RunHeaders(File, Queue->Uri))
7330f4df
DK
499 {
500 case ServerState::RUN_HEADERS_OK:
501 break;
502
503 // The header data is bad
504 case ServerState::RUN_HEADERS_PARSE_ERROR:
505 {
506 _error->Error(_("Bad header data"));
507 Fail(true);
508 RotateDNS();
509 continue;
510 }
511
512 // The server closed a connection during the header get..
513 default:
514 case ServerState::RUN_HEADERS_IO_ERROR:
515 {
516 FailCounter++;
517 _error->Discard();
518 Server->Close();
519 Server->Pipeline = false;
520
521 if (FailCounter >= 2)
522 {
523 Fail(_("Connection failed"),true);
524 FailCounter = 0;
525 }
526
527 RotateDNS();
528 continue;
529 }
530 };
531
532 // Decide what to do.
533 FetchResult Res;
534 Res.Filename = Queue->DestFile;
535 switch (DealWithHeaders(Res))
536 {
537 // Ok, the file is Open
538 case FILE_IS_OPEN:
539 {
540 URIStart(Res);
541
542 // Run the data
543 bool Result = true;
dcd5856b
MV
544
545 // ensure we don't fetch too much
f2b47ba2
MV
546 // we could do "Server->MaximumSize = Queue->MaximumSize" here
547 // but that would break the clever pipeline messup detection
548 // so instead we use the size of the biggest item in the queue
549 Server->MaximumSize = FindMaximumObjectSizeInQueue();
dcd5856b 550
7330f4df
DK
551 if (Server->HaveContent)
552 Result = Server->RunData(File);
553
554 /* If the server is sending back sizeless responses then fill in
555 the size now */
556 if (Res.Size == 0)
557 Res.Size = File->Size();
558
559 // Close the file, destroy the FD object and timestamp it
560 FailFd = -1;
561 delete File;
562 File = 0;
563
564 // Timestamp
246bbb61 565 struct timeval times[2];
9ce3cfc9 566 times[0].tv_sec = times[1].tv_sec = Server->Date;
246bbb61
DK
567 times[0].tv_usec = times[1].tv_usec = 0;
568 utimes(Queue->DestFile.c_str(), times);
7330f4df
DK
569
570 // Send status to APT
571 if (Result == true)
572 {
895417ef
DK
573 Hashes * const resultHashes = Server->GetHashes();
574 HashStringList const hashList = resultHashes->GetHashStringList();
575 if (PipelineDepth != 0 && Queue->ExpectedHashes.usable() == true && Queue->ExpectedHashes != hashList)
576 {
577 // we did not get the expected hash… mhhh:
578 // could it be that server/proxy messed up pipelining?
579 FetchItem * BeforeI = Queue;
580 for (FetchItem *I = Queue->Next; I != 0 && I != QueueBack; I = I->Next)
581 {
582 if (I->ExpectedHashes.usable() == true && I->ExpectedHashes == hashList)
583 {
584 // yes, he did! Disable pipelining and rewrite queue
585 if (Server->Pipeline == true)
586 {
587 // FIXME: fake a warning message as we have no proper way of communicating here
588 std::string out;
589 strprintf(out, _("Automatically disabled %s due to incorrect response from server/proxy. (man 5 apt.conf)"), "Acquire::http::PipelineDepth");
590 std::cerr << "W: " << out << std::endl;
591 Server->Pipeline = false;
592 // we keep the PipelineDepth value so that the rest of the queue can be fixed up as well
593 }
594 Rename(Res.Filename, I->DestFile);
595 Res.Filename = I->DestFile;
596 BeforeI->Next = I->Next;
597 I->Next = Queue;
598 Queue = I;
599 break;
600 }
601 BeforeI = I;
602 }
603 }
604 Res.TakeHashes(*resultHashes);
7330f4df
DK
605 URIDone(Res);
606 }
607 else
608 {
609 if (Server->IsOpen() == false)
610 {
611 FailCounter++;
612 _error->Discard();
613 Server->Close();
614
615 if (FailCounter >= 2)
616 {
617 Fail(_("Connection failed"),true);
618 FailCounter = 0;
619 }
620
621 QueueBack = Queue;
622 }
623 else
a2d40703
MV
624 {
625 Server->Close();
7330f4df 626 Fail(true);
a2d40703 627 }
7330f4df
DK
628 }
629 break;
630 }
631
632 // IMS hit
633 case IMS_HIT:
634 {
635 URIDone(Res);
636 break;
637 }
638
639 // Hard server error, not found or something
640 case ERROR_UNRECOVERABLE:
641 {
642 Fail();
643 break;
644 }
645
646 // Hard internal error, kill the connection and fail
647 case ERROR_NOT_FROM_SERVER:
648 {
649 delete File;
650 File = 0;
651
652 Fail();
653 RotateDNS();
654 Server->Close();
655 break;
656 }
657
658 // We need to flush the data, the header is like a 404 w/ error text
659 case ERROR_WITH_CONTENT_PAGE:
660 {
661 Fail();
662
663 // Send to content to dev/null
664 File = new FileFd("/dev/null",FileFd::WriteExists);
665 Server->RunData(File);
666 delete File;
667 File = 0;
668 break;
669 }
670
671 // Try again with a new URL
672 case TRY_AGAIN_OR_REDIRECT:
673 {
674 // Clear rest of response if there is content
675 if (Server->HaveContent)
676 {
677 File = new FileFd("/dev/null",FileFd::WriteExists);
678 Server->RunData(File);
679 delete File;
680 File = 0;
681 }
682
683 /* Detect redirect loops. No more redirects are allowed
684 after the same URI is seen twice in a queue item. */
685 StringVector &R = Redirected[Queue->DestFile];
686 bool StopRedirects = false;
687 if (R.empty() == true)
688 R.push_back(Queue->Uri);
689 else if (R[0] == "STOP" || R.size() > 10)
690 StopRedirects = true;
691 else
692 {
693 for (StringVectorIterator I = R.begin(); I != R.end(); ++I)
694 if (Queue->Uri == *I)
695 {
696 R[0] = "STOP";
697 break;
698 }
699
700 R.push_back(Queue->Uri);
701 }
702
703 if (StopRedirects == false)
704 Redirect(NextURI);
705 else
706 Fail();
707
708 break;
709 }
710
711 default:
712 Fail(_("Internal error"));
713 break;
714 }
715
716 FailCounter = 0;
717 }
718
719 return 0;
f2b47ba2
MV
720}
721 /*}}}*/
722 /*{{{*/
723unsigned long long
724ServerMethod::FindMaximumObjectSizeInQueue() const
725{
726 unsigned long long MaxSizeInQueue = 0;
8bb043fc 727 for (FetchItem *I = Queue; I != 0 && I != QueueBack; I = I->Next)
f2b47ba2
MV
728 MaxSizeInQueue = std::max(MaxSizeInQueue, I->MaximumSize);
729 return MaxSizeInQueue;
7330f4df
DK
730}
731 /*}}}*/