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 string::size_type Pos
= Line
.find(' ');
106 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
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"));
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)
120 string Tag
= string(Line
,0,Pos
);
121 string Val
= string(Line
,Pos2
);
123 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
125 // Evil servers return no version
128 int const elements
= sscanf(Line
.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major
,&Minor
,&Result
,Code
);
132 if (Owner
!= NULL
&& Owner
->Debug
== true)
133 clog
<< "HTTP server doesn't give Reason-Phrase for " << Result
<< std::endl
;
135 else if (elements
!= 4)
136 return _error
->Error(_("The HTTP server sent an invalid reply header"));
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"));
146 /* Check the HTTP response header to get the default persistence
152 if (Major
== 1 && Minor
== 0)
161 if (stringcasecmp(Tag
,"Content-Length:") == 0)
163 if (Encoding
== Closes
)
167 unsigned long long * SizePtr
= &Size
;
171 *SizePtr
= strtoull(Val
.c_str(), NULL
, 10);
172 if (*SizePtr
>= std::numeric_limits
<unsigned long long>::max())
173 return _error
->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
174 else if (*SizePtr
== 0)
179 if (stringcasecmp(Tag
,"Content-Type:") == 0)
185 if (stringcasecmp(Tag
,"Content-Range:") == 0)
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)
191 ; // we got the expected filesize which is all we wanted
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"));
199 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
202 if (stringcasecmp(Val
,"chunked") == 0)
207 if (stringcasecmp(Tag
,"Connection:") == 0)
209 if (stringcasecmp(Val
,"close") == 0)
211 if (stringcasecmp(Val
,"keep-alive") == 0)
216 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
218 if (RFC1123StrToTime(Val
.c_str(), Date
) == false)
219 return _error
->Error(_("Unknown date format"));
223 if (stringcasecmp(Tag
,"Location:") == 0)
232 // ServerState::ServerState - Constructor /*{{{*/
233 ServerState::ServerState(URI Srv
, ServerMethod
*Owner
) : ServerName(Srv
), TimeOut(120), Owner(Owner
)
238 bool ServerState::AddPartialFileToHashes(FileFd
&File
) /*{{{*/
240 File
.Truncate(StartPos
);
241 return GetHashes()->AddFD(File
, StartPos
);
245 bool ServerMethod::Configuration(string Message
) /*{{{*/
247 if (pkgAcqMethod::Configuration(Message
) == false)
256 // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
257 // ---------------------------------------------------------------------
258 /* We look at the header data we got back from the server and decide what
259 to do. Returns DealWithHeadersResult (see http.h for details).
261 ServerMethod::DealWithHeadersResult
262 ServerMethod::DealWithHeaders(FetchResult
&Res
)
265 if (Server
->Result
== 304)
267 unlink(Queue
->DestFile
.c_str());
269 Res
.LastModified
= Queue
->LastModified
;
275 * Note that it is only OK for us to treat all redirection the same
276 * because we *always* use GET, not other HTTP methods. There are
277 * three redirection codes for which it is not appropriate that we
278 * redirect. Pass on those codes so the error handling kicks in.
281 && (Server
->Result
> 300 && Server
->Result
< 400)
282 && (Server
->Result
!= 300 // Multiple Choices
283 && Server
->Result
!= 304 // Not Modified
284 && Server
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
286 if (Server
->Location
.empty() == true);
287 else if (Server
->Location
[0] == '/' && Queue
->Uri
.empty() == false)
289 URI Uri
= Queue
->Uri
;
290 if (Uri
.Host
.empty() == false)
291 NextURI
= URI::SiteOnly(Uri
);
294 NextURI
.append(DeQuoteString(Server
->Location
));
295 return TRY_AGAIN_OR_REDIRECT
;
299 NextURI
= DeQuoteString(Server
->Location
);
300 URI tmpURI
= NextURI
;
301 URI Uri
= Queue
->Uri
;
302 // same protocol redirects are okay
303 if (tmpURI
.Access
== Uri
.Access
)
304 return TRY_AGAIN_OR_REDIRECT
;
305 // as well as http to https
306 else if (Uri
.Access
== "http" && tmpURI
.Access
== "https")
307 return TRY_AGAIN_OR_REDIRECT
;
309 /* else pass through for error message */
311 // retry after an invalid range response without partial data
312 else if (Server
->Result
== 416)
315 if (stat(Queue
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
317 if ((unsigned long long)SBuf
.st_size
== Server
->Size
)
319 // the file is completely downloaded, but was not moved
320 if (Server
->HaveContent
== true)
322 // Send to error page to dev/null
323 FileFd
DevNull("/dev/null",FileFd::WriteExists
);
324 Server
->RunData(&DevNull
);
326 Server
->HaveContent
= false;
327 Server
->StartPos
= Server
->Size
;
328 Server
->Result
= 200;
330 else if (unlink(Queue
->DestFile
.c_str()) == 0)
332 NextURI
= Queue
->Uri
;
333 return TRY_AGAIN_OR_REDIRECT
;
338 /* We have a reply we dont handle. This should indicate a perm server
340 if (Server
->Result
< 200 || Server
->Result
>= 300)
343 strprintf(err
, "HttpError%u", Server
->Result
);
345 _error
->Error("%u %s", Server
->Result
, Server
->Code
);
346 if (Server
->HaveContent
== true)
347 return ERROR_WITH_CONTENT_PAGE
;
348 return ERROR_UNRECOVERABLE
;
351 // This is some sort of 2xx 'data follows' reply
352 Res
.LastModified
= Server
->Date
;
353 Res
.Size
= Server
->Size
;
357 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
358 if (_error
->PendingError() == true)
359 return ERROR_NOT_FROM_SERVER
;
361 FailFile
= Queue
->DestFile
;
362 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
364 FailTime
= Server
->Date
;
366 if (Server
->InitHashes(Queue
->ExpectedHashes
) == false || Server
->AddPartialFileToHashes(*File
) == false)
368 _error
->Errno("read",_("Problem hashing file"));
369 return ERROR_NOT_FROM_SERVER
;
371 if (Server
->StartPos
> 0)
372 Res
.ResumePoint
= Server
->StartPos
;
374 SetNonBlock(File
->Fd(),true);
378 // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
379 // ---------------------------------------------------------------------
380 /* This closes and timestamps the open file. This is necessary to get
381 resume behavoir on user abort */
382 void ServerMethod::SigTerm(int)
387 struct timeval times
[2];
388 times
[0].tv_sec
= FailTime
;
389 times
[1].tv_sec
= FailTime
;
390 times
[0].tv_usec
= times
[1].tv_usec
= 0;
391 utimes(FailFile
.c_str(), times
);
397 // ServerMethod::Fetch - Fetch an item /*{{{*/
398 // ---------------------------------------------------------------------
399 /* This adds an item to the pipeline. We keep the pipeline at a fixed
401 bool ServerMethod::Fetch(FetchItem
*)
406 // Queue the requests
408 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
409 I
= I
->Next
, Depth
++)
413 // If pipelining is disabled, we only queue 1 request
414 if (Server
->Pipeline
== false)
416 // if we have no hashes, do at most one such request
417 // as we can't fixup pipeling misbehaviors otherwise
418 else if (I
->ExpectedHashes
.usable() == false)
422 // Make sure we stick with the same server
423 if (Server
->Comp(I
->Uri
) == false)
436 // ServerMethod::Loop - Main loop /*{{{*/
437 int ServerMethod::Loop()
439 typedef vector
<string
> StringVector
;
440 typedef vector
<string
>::iterator StringVectorIterator
;
441 map
<string
, StringVector
> Redirected
;
443 signal(SIGTERM
,SigTerm
);
444 signal(SIGINT
,SigTerm
);
451 // We have no commands, wait for some to arrive
454 if (WaitFd(STDIN_FILENO
) == false)
458 /* Run messages, we can accept 0 (no message) if we didn't
459 do a WaitFd above.. Otherwise the FD is closed. */
460 int Result
= Run(true);
461 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
463 if(FailReason
.empty() == false ||
464 _config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
473 // Connect to the server
474 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
477 Server
= CreateServerState(Queue
->Uri
);
479 /* If the server has explicitly said this is the last connection
480 then we pre-emptively shut down the pipeline and tear down
481 the connection. This will speed up HTTP/1.0 servers a tad
482 since we don't have to wait for the close sequence to
484 if (Server
->Persistent
== false)
487 // Reset the pipeline
488 if (Server
->IsOpen() == false)
491 // Connnect to the host
492 if (Server
->Open() == false)
500 // Fill the pipeline.
503 // Fetch the next URL header data from the server.
504 switch (Server
->RunHeaders(File
, Queue
->Uri
))
506 case ServerState::RUN_HEADERS_OK
:
509 // The header data is bad
510 case ServerState::RUN_HEADERS_PARSE_ERROR
:
512 _error
->Error(_("Bad header data"));
518 // The server closed a connection during the header get..
520 case ServerState::RUN_HEADERS_IO_ERROR
:
525 Server
->Pipeline
= false;
527 if (FailCounter
>= 2)
529 Fail(_("Connection failed"),true);
538 // Decide what to do.
540 Res
.Filename
= Queue
->DestFile
;
541 switch (DealWithHeaders(Res
))
543 // Ok, the file is Open
551 // ensure we don't fetch too much
552 // we could do "Server->MaximumSize = Queue->MaximumSize" here
553 // but that would break the clever pipeline messup detection
554 // so instead we use the size of the biggest item in the queue
555 Server
->MaximumSize
= FindMaximumObjectSizeInQueue();
557 if (Server
->HaveContent
)
558 Result
= Server
->RunData(File
);
560 /* If the server is sending back sizeless responses then fill in
563 Res
.Size
= File
->Size();
565 // Close the file, destroy the FD object and timestamp it
571 struct timeval times
[2];
572 times
[0].tv_sec
= times
[1].tv_sec
= Server
->Date
;
573 times
[0].tv_usec
= times
[1].tv_usec
= 0;
574 utimes(Queue
->DestFile
.c_str(), times
);
576 // Send status to APT
579 Hashes
* const resultHashes
= Server
->GetHashes();
580 HashStringList
const hashList
= resultHashes
->GetHashStringList();
581 if (PipelineDepth
!= 0 && Queue
->ExpectedHashes
.usable() == true && Queue
->ExpectedHashes
!= hashList
)
583 // we did not get the expected hash… mhhh:
584 // could it be that server/proxy messed up pipelining?
585 FetchItem
* BeforeI
= Queue
;
586 for (FetchItem
*I
= Queue
->Next
; I
!= 0 && I
!= QueueBack
; I
= I
->Next
)
588 if (I
->ExpectedHashes
.usable() == true && I
->ExpectedHashes
== hashList
)
590 // yes, he did! Disable pipelining and rewrite queue
591 if (Server
->Pipeline
== true)
593 // FIXME: fake a warning message as we have no proper way of communicating here
595 strprintf(out
, _("Automatically disabled %s due to incorrect response from server/proxy. (man 5 apt.conf)"), "Acquire::http::PipelineDepth");
596 std::cerr
<< "W: " << out
<< std::endl
;
597 Server
->Pipeline
= false;
598 // we keep the PipelineDepth value so that the rest of the queue can be fixed up as well
600 Rename(Res
.Filename
, I
->DestFile
);
601 Res
.Filename
= I
->DestFile
;
602 BeforeI
->Next
= I
->Next
;
610 Res
.TakeHashes(*resultHashes
);
615 if (Server
->IsOpen() == false)
621 if (FailCounter
>= 2)
623 Fail(_("Connection failed"),true);
645 // Hard server error, not found or something
646 case ERROR_UNRECOVERABLE
:
652 // Hard internal error, kill the connection and fail
653 case ERROR_NOT_FROM_SERVER
:
664 // We need to flush the data, the header is like a 404 w/ error text
665 case ERROR_WITH_CONTENT_PAGE
:
669 // Send to content to dev/null
670 File
= new FileFd("/dev/null",FileFd::WriteExists
);
671 Server
->RunData(File
);
677 // Try again with a new URL
678 case TRY_AGAIN_OR_REDIRECT
:
680 // Clear rest of response if there is content
681 if (Server
->HaveContent
)
683 File
= new FileFd("/dev/null",FileFd::WriteExists
);
684 Server
->RunData(File
);
689 /* Detect redirect loops. No more redirects are allowed
690 after the same URI is seen twice in a queue item. */
691 StringVector
&R
= Redirected
[Queue
->DestFile
];
692 bool StopRedirects
= false;
693 if (R
.empty() == true)
694 R
.push_back(Queue
->Uri
);
695 else if (R
[0] == "STOP" || R
.size() > 10)
696 StopRedirects
= true;
699 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); ++I
)
700 if (Queue
->Uri
== *I
)
706 R
.push_back(Queue
->Uri
);
709 if (StopRedirects
== false)
718 Fail(_("Internal error"));
730 ServerMethod::FindMaximumObjectSizeInQueue() const
732 unsigned long long MaxSizeInQueue
= 0;
733 for (FetchItem
*I
= Queue
; I
!= 0 && I
!= QueueBack
; I
= I
->Next
)
734 MaxSizeInQueue
= std::max(MaxSizeInQueue
, I
->MaximumSize
);
735 return MaxSizeInQueue
;