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
)
51 Owner
->Status(_("Waiting for headers"));
65 if (ReadHeaderLines(Data
) == false)
68 if (Owner
->Debug
== true)
71 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); ++I
)
73 string::const_iterator J
= I
;
74 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r'; ++J
);
75 if (HeaderLine(string(I
,J
)) == false)
76 return RUN_HEADERS_PARSE_ERROR
;
80 // 100 Continue is a Nop...
84 // Tidy up the connection persistence state.
85 if (Encoding
== Closes
&& HaveContent
== true)
88 return RUN_HEADERS_OK
;
90 while (LoadNextResponse(false, File
) == true);
92 return RUN_HEADERS_IO_ERROR
;
95 // ServerState::HeaderLine - Process a header line /*{{{*/
96 // ---------------------------------------------------------------------
98 bool ServerState::HeaderLine(string Line
)
100 if (Line
.empty() == true)
103 string::size_type Pos
= Line
.find(' ');
104 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
106 // Blah, some servers use "connection:closes", evil.
107 Pos
= Line
.find(':');
108 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
109 return _error
->Error(_("Bad header line"));
113 // Parse off any trailing spaces between the : and the next word.
114 string::size_type Pos2
= Pos
;
115 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
118 string Tag
= string(Line
,0,Pos
);
119 string Val
= string(Line
,Pos2
);
121 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
123 // Evil servers return no version
126 int const elements
= sscanf(Line
.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major
,&Minor
,&Result
,Code
);
130 if (Owner
->Debug
== true)
131 clog
<< "HTTP server doesn't give Reason-Phrase for " << Result
<< std::endl
;
133 else if (elements
!= 4)
134 return _error
->Error(_("The HTTP server sent an invalid reply header"));
140 if (sscanf(Line
.c_str(),"HTTP %3u%359[^\n]",&Result
,Code
) != 2)
141 return _error
->Error(_("The HTTP server sent an invalid reply header"));
144 /* Check the HTTP response header to get the default persistence
150 if (Major
== 1 && Minor
== 0)
159 if (stringcasecmp(Tag
,"Content-Length:") == 0)
161 if (Encoding
== Closes
)
165 // The length is already set from the Content-Range header
169 Size
= strtoull(Val
.c_str(), NULL
, 10);
170 if (Size
>= std::numeric_limits
<unsigned long long>::max())
171 return _error
->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
177 if (stringcasecmp(Tag
,"Content-Type:") == 0)
183 if (stringcasecmp(Tag
,"Content-Range:") == 0)
187 // ยง14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
188 if (Result
== 416 && sscanf(Val
.c_str(), "bytes */%llu",&Size
) == 1)
190 StartPos
= 1; // ignore Content-Length, it would override Size
193 else if (sscanf(Val
.c_str(),"bytes %llu-%*u/%llu",&StartPos
,&Size
) != 2)
194 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
195 if ((unsigned long long)StartPos
> Size
)
196 return _error
->Error(_("This HTTP server has broken range support"));
200 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
203 if (stringcasecmp(Val
,"chunked") == 0)
208 if (stringcasecmp(Tag
,"Connection:") == 0)
210 if (stringcasecmp(Val
,"close") == 0)
212 if (stringcasecmp(Val
,"keep-alive") == 0)
217 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
219 if (RFC1123StrToTime(Val
.c_str(), Date
) == false)
220 return _error
->Error(_("Unknown date format"));
224 if (stringcasecmp(Tag
,"Location:") == 0)
233 // ServerState::ServerState - Constructor /*{{{*/
234 ServerState::ServerState(URI Srv
, ServerMethod
*Owner
) : ServerName(Srv
), TimeOut(120), Owner(Owner
)
240 bool ServerMethod::Configuration(string Message
) /*{{{*/
242 return pkgAcqMethod::Configuration(Message
);
246 // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
247 // ---------------------------------------------------------------------
248 /* We look at the header data we got back from the server and decide what
249 to do. Returns DealWithHeadersResult (see http.h for details).
251 ServerMethod::DealWithHeadersResult
252 ServerMethod::DealWithHeaders(FetchResult
&Res
)
255 if (Server
->Result
== 304)
257 unlink(Queue
->DestFile
.c_str());
259 Res
.LastModified
= Queue
->LastModified
;
265 * Note that it is only OK for us to treat all redirection the same
266 * because we *always* use GET, not other HTTP methods. There are
267 * three redirection codes for which it is not appropriate that we
268 * redirect. Pass on those codes so the error handling kicks in.
271 && (Server
->Result
> 300 && Server
->Result
< 400)
272 && (Server
->Result
!= 300 // Multiple Choices
273 && Server
->Result
!= 304 // Not Modified
274 && Server
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
276 if (Server
->Location
.empty() == true);
277 else if (Server
->Location
[0] == '/' && Queue
->Uri
.empty() == false)
279 URI Uri
= Queue
->Uri
;
280 if (Uri
.Host
.empty() == false)
281 NextURI
= URI::SiteOnly(Uri
);
284 NextURI
.append(DeQuoteString(Server
->Location
));
285 return TRY_AGAIN_OR_REDIRECT
;
289 NextURI
= DeQuoteString(Server
->Location
);
290 URI tmpURI
= NextURI
;
291 URI Uri
= Queue
->Uri
;
292 // same protocol redirects are okay
293 if (tmpURI
.Access
== Uri
.Access
)
294 return TRY_AGAIN_OR_REDIRECT
;
295 // as well as http to https
296 else if (Uri
.Access
== "http" && tmpURI
.Access
== "https")
297 return TRY_AGAIN_OR_REDIRECT
;
299 /* else pass through for error message */
301 // retry after an invalid range response without partial data
302 else if (Server
->Result
== 416)
305 if (stat(Queue
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
307 if ((unsigned long long)SBuf
.st_size
== Server
->Size
)
309 // the file is completely downloaded, but was not moved
310 Server
->StartPos
= Server
->Size
;
311 Server
->Result
= 200;
312 Server
->HaveContent
= false;
314 else if (unlink(Queue
->DestFile
.c_str()) == 0)
316 NextURI
= Queue
->Uri
;
317 return TRY_AGAIN_OR_REDIRECT
;
322 /* We have a reply we dont handle. This should indicate a perm server
324 if (Server
->Result
< 200 || Server
->Result
>= 300)
327 snprintf(err
,sizeof(err
)-1,"HttpError%i",Server
->Result
);
329 _error
->Error("%u %s",Server
->Result
,Server
->Code
);
330 if (Server
->HaveContent
== true)
331 return ERROR_WITH_CONTENT_PAGE
;
332 return ERROR_UNRECOVERABLE
;
335 // This is some sort of 2xx 'data follows' reply
336 Res
.LastModified
= Server
->Date
;
337 Res
.Size
= Server
->Size
;
341 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
342 if (_error
->PendingError() == true)
343 return ERROR_NOT_FROM_SERVER
;
345 FailFile
= Queue
->DestFile
;
346 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
348 FailTime
= Server
->Date
;
350 if (Server
->InitHashes(*File
) == false)
352 _error
->Errno("read",_("Problem hashing file"));
353 return ERROR_NOT_FROM_SERVER
;
355 if (Server
->StartPos
> 0)
356 Res
.ResumePoint
= Server
->StartPos
;
358 SetNonBlock(File
->Fd(),true);
362 // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
363 // ---------------------------------------------------------------------
364 /* This closes and timestamps the open file. This is necessary to get
365 resume behavoir on user abort */
366 void ServerMethod::SigTerm(int)
371 struct timeval times
[2];
372 times
[0].tv_sec
= FailTime
;
373 times
[1].tv_sec
= FailTime
;
374 times
[0].tv_usec
= times
[1].tv_usec
= 0;
375 utimes(FailFile
.c_str(), times
);
381 // ServerMethod::Fetch - Fetch an item /*{{{*/
382 // ---------------------------------------------------------------------
383 /* This adds an item to the pipeline. We keep the pipeline at a fixed
385 bool ServerMethod::Fetch(FetchItem
*)
390 // Queue the requests
392 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
393 I
= I
->Next
, Depth
++)
395 // If pipelining is disabled, we only queue 1 request
396 if (Server
->Pipeline
== false && Depth
>= 0)
399 // Make sure we stick with the same server
400 if (Server
->Comp(I
->Uri
) == false)
413 // ServerMethod::Loop - Main loop /*{{{*/
414 int ServerMethod::Loop()
416 typedef vector
<string
> StringVector
;
417 typedef vector
<string
>::iterator StringVectorIterator
;
418 map
<string
, StringVector
> Redirected
;
420 signal(SIGTERM
,SigTerm
);
421 signal(SIGINT
,SigTerm
);
428 // We have no commands, wait for some to arrive
431 if (WaitFd(STDIN_FILENO
) == false)
435 /* Run messages, we can accept 0 (no message) if we didn't
436 do a WaitFd above.. Otherwise the FD is closed. */
437 int Result
= Run(true);
438 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
440 if(FailReason
.empty() == false ||
441 _config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
450 // Connect to the server
451 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
454 Server
= CreateServerState(Queue
->Uri
);
456 /* If the server has explicitly said this is the last connection
457 then we pre-emptively shut down the pipeline and tear down
458 the connection. This will speed up HTTP/1.0 servers a tad
459 since we don't have to wait for the close sequence to
461 if (Server
->Persistent
== false)
464 // Reset the pipeline
465 if (Server
->IsOpen() == false)
468 // Connnect to the host
469 if (Server
->Open() == false)
477 // Fill the pipeline.
480 // Fetch the next URL header data from the server.
481 switch (Server
->RunHeaders(File
))
483 case ServerState::RUN_HEADERS_OK
:
486 // The header data is bad
487 case ServerState::RUN_HEADERS_PARSE_ERROR
:
489 _error
->Error(_("Bad header data"));
495 // The server closed a connection during the header get..
497 case ServerState::RUN_HEADERS_IO_ERROR
:
502 Server
->Pipeline
= false;
504 if (FailCounter
>= 2)
506 Fail(_("Connection failed"),true);
515 // Decide what to do.
517 Res
.Filename
= Queue
->DestFile
;
518 switch (DealWithHeaders(Res
))
520 // Ok, the file is Open
527 if (Server
->HaveContent
)
528 Result
= Server
->RunData(File
);
530 /* If the server is sending back sizeless responses then fill in
533 Res
.Size
= File
->Size();
535 // Close the file, destroy the FD object and timestamp it
541 struct timeval times
[2];
542 times
[0].tv_sec
= times
[1].tv_sec
= Server
->Date
;
543 times
[0].tv_usec
= times
[1].tv_usec
= 0;
544 utimes(Queue
->DestFile
.c_str(), times
);
546 // Send status to APT
549 Res
.TakeHashes(*Server
->GetHashes());
554 if (Server
->IsOpen() == false)
560 if (FailCounter
>= 2)
562 Fail(_("Connection failed"),true);
581 // Hard server error, not found or something
582 case ERROR_UNRECOVERABLE
:
588 // Hard internal error, kill the connection and fail
589 case ERROR_NOT_FROM_SERVER
:
600 // We need to flush the data, the header is like a 404 w/ error text
601 case ERROR_WITH_CONTENT_PAGE
:
605 // Send to content to dev/null
606 File
= new FileFd("/dev/null",FileFd::WriteExists
);
607 Server
->RunData(File
);
613 // Try again with a new URL
614 case TRY_AGAIN_OR_REDIRECT
:
616 // Clear rest of response if there is content
617 if (Server
->HaveContent
)
619 File
= new FileFd("/dev/null",FileFd::WriteExists
);
620 Server
->RunData(File
);
625 /* Detect redirect loops. No more redirects are allowed
626 after the same URI is seen twice in a queue item. */
627 StringVector
&R
= Redirected
[Queue
->DestFile
];
628 bool StopRedirects
= false;
629 if (R
.empty() == true)
630 R
.push_back(Queue
->Uri
);
631 else if (R
[0] == "STOP" || R
.size() > 10)
632 StopRedirects
= true;
635 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); ++I
)
636 if (Queue
->Uri
== *I
)
642 R
.push_back(Queue
->Uri
);
645 if (StopRedirects
== false)
654 Fail(_("Internal error"));