1 // -*- mode: cpp; mode: fold -*-
3 /* ######################################################################
5 HTTP and HTTPS share a lot of common code and these classes are
6 exactly the dumping ground for this common code
8 ##################################################################### */
10 // Include Files /*{{{*/
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>
39 string
ServerMethod::FailFile
;
40 int ServerMethod::FailFd
= -1;
41 time_t ServerMethod::FailTime
= 0;
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 */
47 ServerState::RunHeadersResult
ServerState::RunHeaders(FileFd
* const File
,
48 const std::string
&Uri
)
52 Owner
->Status(_("Waiting for headers"));
67 if (ReadHeaderLines(Data
) == false)
70 if (Owner
->Debug
== true)
71 clog
<< "Answer for: " << Uri
<< endl
<< Data
;
73 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); ++I
)
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
;
82 // 100 Continue is a Nop...
86 // Tidy up the connection persistence state.
87 if (Encoding
== Closes
&& HaveContent
== true)
90 return RUN_HEADERS_OK
;
92 while (LoadNextResponse(false, File
) == true);
94 return RUN_HEADERS_IO_ERROR
;
97 // ServerState::HeaderLine - Process a header line /*{{{*/
98 // ---------------------------------------------------------------------
100 bool ServerState::HeaderLine(string Line
)
102 if (Line
.empty() == true)
105 if (Line
.size() > 4 && stringcasecmp(Line
.data(), Line
.data()+4, "HTTP") == 0)
107 // Evil servers return no version
110 int const elements
= sscanf(Line
.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major
,&Minor
,&Result
,Code
);
114 if (Owner
!= NULL
&& Owner
->Debug
== true)
115 clog
<< "HTTP server doesn't give Reason-Phrase for " << std::to_string(Result
) << std::endl
;
117 else if (elements
!= 4)
118 return _error
->Error(_("The HTTP server sent an invalid reply header"));
124 if (sscanf(Line
.c_str(),"HTTP %3u%359[^\n]",&Result
,Code
) != 2)
125 return _error
->Error(_("The HTTP server sent an invalid reply header"));
128 /* Check the HTTP response header to get the default persistence
134 if (Major
== 1 && Minor
== 0)
149 // Blah, some servers use "connection:closes", evil.
150 // and some even send empty header fields…
151 string::size_type Pos
= Line
.find(':');
152 if (Pos
== string::npos
)
153 return _error
->Error(_("Bad header line"));
156 // Parse off any trailing spaces between the : and the next word.
157 string::size_type Pos2
= Pos
;
158 while (Pos2
< Line
.length() && isspace_ascii(Line
[Pos2
]) != 0)
161 string
const Tag(Line
,0,Pos
);
162 string
const Val(Line
,Pos2
);
164 if (stringcasecmp(Tag
,"Content-Length:") == 0)
166 if (Encoding
== Closes
)
170 unsigned long long * DownloadSizePtr
= &DownloadSize
;
172 DownloadSizePtr
= &JunkSize
;
174 *DownloadSizePtr
= strtoull(Val
.c_str(), NULL
, 10);
175 if (*DownloadSizePtr
>= std::numeric_limits
<unsigned long long>::max())
176 return _error
->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
177 else if (*DownloadSizePtr
== 0)
180 // On partial content (206) the Content-Length less than the real
181 // size, so do not set it here but leave that to the Content-Range
183 if(Result
!= 206 && TotalFileSize
== 0)
184 TotalFileSize
= DownloadSize
;
189 if (stringcasecmp(Tag
,"Content-Type:") == 0)
195 if (stringcasecmp(Tag
,"Content-Range:") == 0)
199 // §14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
200 if (Result
== 416 && sscanf(Val
.c_str(), "bytes */%llu",&TotalFileSize
) == 1)
201 ; // we got the expected filesize which is all we wanted
202 else if (sscanf(Val
.c_str(),"bytes %llu-%*u/%llu",&StartPos
,&TotalFileSize
) != 2)
203 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
204 if ((unsigned long long)StartPos
> TotalFileSize
)
205 return _error
->Error(_("This HTTP server has broken range support"));
207 // figure out what we will download
208 DownloadSize
= TotalFileSize
- StartPos
;
212 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
215 if (stringcasecmp(Val
,"chunked") == 0)
220 if (stringcasecmp(Tag
,"Connection:") == 0)
222 if (stringcasecmp(Val
,"close") == 0)
224 if (stringcasecmp(Val
,"keep-alive") == 0)
229 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
231 if (RFC1123StrToTime(Val
.c_str(), Date
) == false)
232 return _error
->Error(_("Unknown date format"));
236 if (stringcasecmp(Tag
,"Location:") == 0)
245 // ServerState::ServerState - Constructor /*{{{*/
246 ServerState::ServerState(URI Srv
, ServerMethod
*Owner
) :
247 DownloadSize(0), ServerName(Srv
), TimeOut(120), Owner(Owner
)
252 bool ServerState::AddPartialFileToHashes(FileFd
&File
) /*{{{*/
254 File
.Truncate(StartPos
);
255 return GetHashes()->AddFD(File
, StartPos
);
259 // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
260 // ---------------------------------------------------------------------
261 /* We look at the header data we got back from the server and decide what
262 to do. Returns DealWithHeadersResult (see http.h for details).
264 ServerMethod::DealWithHeadersResult
265 ServerMethod::DealWithHeaders(FetchResult
&Res
)
268 if (Server
->Result
== 304)
270 RemoveFile("server", Queue
->DestFile
);
272 Res
.LastModified
= Queue
->LastModified
;
278 * Note that it is only OK for us to treat all redirection the same
279 * because we *always* use GET, not other HTTP methods. There are
280 * three redirection codes for which it is not appropriate that we
281 * redirect. Pass on those codes so the error handling kicks in.
284 && (Server
->Result
> 300 && Server
->Result
< 400)
285 && (Server
->Result
!= 300 // Multiple Choices
286 && Server
->Result
!= 304 // Not Modified
287 && Server
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
289 if (Server
->Location
.empty() == true);
290 else if (Server
->Location
[0] == '/' && Queue
->Uri
.empty() == false)
292 URI Uri
= Queue
->Uri
;
293 if (Uri
.Host
.empty() == false)
294 NextURI
= URI::SiteOnly(Uri
);
297 NextURI
.append(DeQuoteString(Server
->Location
));
298 return TRY_AGAIN_OR_REDIRECT
;
302 NextURI
= DeQuoteString(Server
->Location
);
303 URI tmpURI
= NextURI
;
304 URI Uri
= Queue
->Uri
;
305 // same protocol redirects are okay
306 if (tmpURI
.Access
== Uri
.Access
)
307 return TRY_AGAIN_OR_REDIRECT
;
308 // as well as http to https
309 else if (Uri
.Access
== "http" && tmpURI
.Access
== "https")
310 return TRY_AGAIN_OR_REDIRECT
;
312 /* else pass through for error message */
314 // retry after an invalid range response without partial data
315 else if (Server
->Result
== 416)
318 if (stat(Queue
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
320 bool partialHit
= false;
321 if (Queue
->ExpectedHashes
.usable() == true)
323 Hashes
resultHashes(Queue
->ExpectedHashes
);
324 FileFd
file(Queue
->DestFile
, FileFd::ReadOnly
);
325 Server
->TotalFileSize
= file
.FileSize();
326 Server
->Date
= file
.ModificationTime();
327 resultHashes
.AddFD(file
);
328 HashStringList
const hashList
= resultHashes
.GetHashStringList();
329 partialHit
= (Queue
->ExpectedHashes
== hashList
);
331 else if ((unsigned long long)SBuf
.st_size
== Server
->TotalFileSize
)
333 if (partialHit
== true)
335 // the file is completely downloaded, but was not moved
336 if (Server
->HaveContent
== true)
338 // Send to error page to dev/null
339 FileFd
DevNull("/dev/null",FileFd::WriteExists
);
340 Server
->RunData(&DevNull
);
342 Server
->HaveContent
= false;
343 Server
->StartPos
= Server
->TotalFileSize
;
344 Server
->Result
= 200;
346 else if (RemoveFile("server", Queue
->DestFile
))
348 NextURI
= Queue
->Uri
;
349 return TRY_AGAIN_OR_REDIRECT
;
354 /* We have a reply we don't handle. This should indicate a perm server
356 if (Server
->Result
< 200 || Server
->Result
>= 300)
359 strprintf(err
, "HttpError%u", Server
->Result
);
361 _error
->Error("%u %s", Server
->Result
, Server
->Code
);
362 if (Server
->HaveContent
== true)
363 return ERROR_WITH_CONTENT_PAGE
;
364 return ERROR_UNRECOVERABLE
;
367 // This is some sort of 2xx 'data follows' reply
368 Res
.LastModified
= Server
->Date
;
369 Res
.Size
= Server
->TotalFileSize
;
373 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
374 if (_error
->PendingError() == true)
375 return ERROR_NOT_FROM_SERVER
;
377 FailFile
= Queue
->DestFile
;
378 FailFile
.c_str(); // Make sure we don't do a malloc in the signal handler
380 FailTime
= Server
->Date
;
382 if (Server
->InitHashes(Queue
->ExpectedHashes
) == false || Server
->AddPartialFileToHashes(*File
) == false)
384 _error
->Errno("read",_("Problem hashing file"));
385 return ERROR_NOT_FROM_SERVER
;
387 if (Server
->StartPos
> 0)
388 Res
.ResumePoint
= Server
->StartPos
;
390 SetNonBlock(File
->Fd(),true);
394 // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
395 // ---------------------------------------------------------------------
396 /* This closes and timestamps the open file. This is necessary to get
397 resume behavoir on user abort */
398 void ServerMethod::SigTerm(int)
403 struct timeval times
[2];
404 times
[0].tv_sec
= FailTime
;
405 times
[1].tv_sec
= FailTime
;
406 times
[0].tv_usec
= times
[1].tv_usec
= 0;
407 utimes(FailFile
.c_str(), times
);
413 // ServerMethod::Fetch - Fetch an item /*{{{*/
414 // ---------------------------------------------------------------------
415 /* This adds an item to the pipeline. We keep the pipeline at a fixed
417 bool ServerMethod::Fetch(FetchItem
*)
422 // Queue the requests
424 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
425 I
= I
->Next
, Depth
++)
429 // If pipelining is disabled, we only queue 1 request
430 if (Server
->Pipeline
== false)
432 // if we have no hashes, do at most one such request
433 // as we can't fixup pipeling misbehaviors otherwise
434 else if (I
->ExpectedHashes
.usable() == false)
438 // Make sure we stick with the same server
439 if (Server
->Comp(I
->Uri
) == false)
452 // ServerMethod::Loop - Main loop /*{{{*/
453 int ServerMethod::Loop()
455 typedef vector
<string
> StringVector
;
456 typedef vector
<string
>::iterator StringVectorIterator
;
457 map
<string
, StringVector
> Redirected
;
459 signal(SIGTERM
,SigTerm
);
460 signal(SIGINT
,SigTerm
);
467 // We have no commands, wait for some to arrive
470 if (WaitFd(STDIN_FILENO
) == false)
474 /* Run messages, we can accept 0 (no message) if we didn't
475 do a WaitFd above.. Otherwise the FD is closed. */
476 int Result
= Run(true);
477 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
479 if(FailReason
.empty() == false ||
480 _config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
489 // Connect to the server
490 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
491 Server
= CreateServerState(Queue
->Uri
);
493 /* If the server has explicitly said this is the last connection
494 then we pre-emptively shut down the pipeline and tear down
495 the connection. This will speed up HTTP/1.0 servers a tad
496 since we don't have to wait for the close sequence to
498 if (Server
->Persistent
== false)
501 // Reset the pipeline
502 if (Server
->IsOpen() == false)
505 // Connnect to the host
506 if (Server
->Open() == false)
513 // Fill the pipeline.
516 // Fetch the next URL header data from the server.
517 switch (Server
->RunHeaders(File
, Queue
->Uri
))
519 case ServerState::RUN_HEADERS_OK
:
522 // The header data is bad
523 case ServerState::RUN_HEADERS_PARSE_ERROR
:
525 _error
->Error(_("Bad header data"));
532 // The server closed a connection during the header get..
534 case ServerState::RUN_HEADERS_IO_ERROR
:
539 Server
->Pipeline
= false;
540 Server
->PipelineAllowed
= false;
542 if (FailCounter
>= 2)
544 Fail(_("Connection failed"),true);
553 // Decide what to do.
555 Res
.Filename
= Queue
->DestFile
;
556 switch (DealWithHeaders(Res
))
558 // Ok, the file is Open
566 // ensure we don't fetch too much
567 // we could do "Server->MaximumSize = Queue->MaximumSize" here
568 // but that would break the clever pipeline messup detection
569 // so instead we use the size of the biggest item in the queue
570 Server
->MaximumSize
= FindMaximumObjectSizeInQueue();
572 if (Server
->HaveContent
)
573 Result
= Server
->RunData(File
);
575 /* If the server is sending back sizeless responses then fill in
578 Res
.Size
= File
->Size();
580 // Close the file, destroy the FD object and timestamp it
586 struct timeval times
[2];
587 times
[0].tv_sec
= times
[1].tv_sec
= Server
->Date
;
588 times
[0].tv_usec
= times
[1].tv_usec
= 0;
589 utimes(Queue
->DestFile
.c_str(), times
);
591 // Send status to APT
594 Hashes
* const resultHashes
= Server
->GetHashes();
595 HashStringList
const hashList
= resultHashes
->GetHashStringList();
596 if (PipelineDepth
!= 0 && Queue
->ExpectedHashes
.usable() == true && Queue
->ExpectedHashes
!= hashList
)
598 // we did not get the expected hash… mhhh:
599 // could it be that server/proxy messed up pipelining?
600 FetchItem
* BeforeI
= Queue
;
601 for (FetchItem
*I
= Queue
->Next
; I
!= 0 && I
!= QueueBack
; I
= I
->Next
)
603 if (I
->ExpectedHashes
.usable() == true && I
->ExpectedHashes
== hashList
)
605 // yes, he did! Disable pipelining and rewrite queue
606 if (Server
->Pipeline
== true)
608 Warning(_("Automatically disabled %s due to incorrect response from server/proxy. (man 5 apt.conf)"), "Acquire::http::Pipeline-Depth");
609 Server
->Pipeline
= false;
610 Server
->PipelineAllowed
= false;
611 // we keep the PipelineDepth value so that the rest of the queue can be fixed up as well
613 Rename(Res
.Filename
, I
->DestFile
);
614 Res
.Filename
= I
->DestFile
;
615 BeforeI
->Next
= I
->Next
;
623 Res
.TakeHashes(*resultHashes
);
628 if (Server
->IsOpen() == false)
634 if (FailCounter
>= 2)
636 Fail(_("Connection failed"),true);
658 // Hard server error, not found or something
659 case ERROR_UNRECOVERABLE
:
665 // Hard internal error, kill the connection and fail
666 case ERROR_NOT_FROM_SERVER
:
677 // We need to flush the data, the header is like a 404 w/ error text
678 case ERROR_WITH_CONTENT_PAGE
:
682 // Send to content to dev/null
683 File
= new FileFd("/dev/null",FileFd::WriteExists
);
684 Server
->RunData(File
);
690 // Try again with a new URL
691 case TRY_AGAIN_OR_REDIRECT
:
693 // Clear rest of response if there is content
694 if (Server
->HaveContent
)
696 File
= new FileFd("/dev/null",FileFd::WriteExists
);
697 Server
->RunData(File
);
702 /* Detect redirect loops. No more redirects are allowed
703 after the same URI is seen twice in a queue item. */
704 StringVector
&R
= Redirected
[Queue
->DestFile
];
705 bool StopRedirects
= false;
706 if (R
.empty() == true)
707 R
.push_back(Queue
->Uri
);
708 else if (R
[0] == "STOP" || R
.size() > 10)
709 StopRedirects
= true;
712 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); ++I
)
713 if (Queue
->Uri
== *I
)
719 R
.push_back(Queue
->Uri
);
722 if (StopRedirects
== false)
731 Fail(_("Internal error"));
741 unsigned long long ServerMethod::FindMaximumObjectSizeInQueue() const /*{{{*/
743 unsigned long long MaxSizeInQueue
= 0;
744 for (FetchItem
*I
= Queue
; I
!= 0 && I
!= QueueBack
; I
= I
->Next
)
745 MaxSizeInQueue
= std::max(MaxSizeInQueue
, I
->MaximumSize
);
746 return MaxSizeInQueue
;
749 ServerMethod::ServerMethod(char const * const Binary
, char const * const Ver
,unsigned long const Flags
) :/*{{{*/
750 aptMethod(Binary
, Ver
, Flags
), Server(nullptr), File(NULL
), PipelineDepth(10),
751 AllowRedirect(false), Debug(false)