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