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 * DownloadSizePtr
= &DownloadSize
;
169 DownloadSizePtr
= &JunkSize
;
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)
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
180 if(Result
!= 206 && TotalFileSize
== 0)
181 TotalFileSize
= DownloadSize
;
186 if (stringcasecmp(Tag
,"Content-Type:") == 0)
192 if (stringcasecmp(Tag
,"Content-Range:") == 0)
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"));
204 // figure out what we will download
205 DownloadSize
= TotalFileSize
- StartPos
;
209 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
212 if (stringcasecmp(Val
,"chunked") == 0)
217 if (stringcasecmp(Tag
,"Connection:") == 0)
219 if (stringcasecmp(Val
,"close") == 0)
221 if (stringcasecmp(Val
,"keep-alive") == 0)
226 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
228 if (RFC1123StrToTime(Val
.c_str(), Date
) == false)
229 return _error
->Error(_("Unknown date format"));
233 if (stringcasecmp(Tag
,"Location:") == 0)
242 // ServerState::ServerState - Constructor /*{{{*/
243 ServerState::ServerState(URI Srv
, ServerMethod
*Owner
) : ServerName(Srv
), TimeOut(120), Owner(Owner
)
249 bool ServerMethod::Configuration(string Message
) /*{{{*/
251 return pkgAcqMethod::Configuration(Message
);
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).
260 ServerMethod::DealWithHeadersResult
261 ServerMethod::DealWithHeaders(FetchResult
&Res
)
264 if (Server
->Result
== 304)
266 unlink(Queue
->DestFile
.c_str());
268 Res
.LastModified
= Queue
->LastModified
;
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.
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)
285 if (Server
->Location
.empty() == true);
286 else if (Server
->Location
[0] == '/' && Queue
->Uri
.empty() == false)
288 URI Uri
= Queue
->Uri
;
289 if (Uri
.Host
.empty() == false)
290 NextURI
= URI::SiteOnly(Uri
);
293 NextURI
.append(DeQuoteString(Server
->Location
));
294 return TRY_AGAIN_OR_REDIRECT
;
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
;
308 /* else pass through for error message */
310 // retry after an invalid range response without partial data
311 else if (Server
->Result
== 416)
314 if (stat(Queue
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
316 if ((unsigned long long)SBuf
.st_size
== Server
->TotalFileSize
)
318 // the file is completely downloaded, but was not moved
319 if (Server
->HaveContent
== true)
321 // Send to error page to dev/null
322 FileFd
DevNull("/dev/null",FileFd::WriteExists
);
323 Server
->RunData(&DevNull
);
325 Server
->HaveContent
= false;
326 Server
->StartPos
= Server
->TotalFileSize
;
327 Server
->Result
= 200;
329 else if (unlink(Queue
->DestFile
.c_str()) == 0)
331 NextURI
= Queue
->Uri
;
332 return TRY_AGAIN_OR_REDIRECT
;
337 /* We have a reply we dont handle. This should indicate a perm server
339 if (Server
->Result
< 200 || Server
->Result
>= 300)
342 snprintf(err
,sizeof(err
)-1,"HttpError%i",Server
->Result
);
344 _error
->Error("%u %s",Server
->Result
,Server
->Code
);
345 if (Server
->HaveContent
== true)
346 return ERROR_WITH_CONTENT_PAGE
;
347 return ERROR_UNRECOVERABLE
;
350 // This is some sort of 2xx 'data follows' reply
351 Res
.LastModified
= Server
->Date
;
352 Res
.Size
= Server
->TotalFileSize
;
356 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
357 if (_error
->PendingError() == true)
358 return ERROR_NOT_FROM_SERVER
;
360 FailFile
= Queue
->DestFile
;
361 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
363 FailTime
= Server
->Date
;
365 if (Server
->InitHashes(*File
) == false)
367 _error
->Errno("read",_("Problem hashing file"));
368 return ERROR_NOT_FROM_SERVER
;
370 if (Server
->StartPos
> 0)
371 Res
.ResumePoint
= Server
->StartPos
;
373 SetNonBlock(File
->Fd(),true);
377 // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
378 // ---------------------------------------------------------------------
379 /* This closes and timestamps the open file. This is necessary to get
380 resume behavoir on user abort */
381 void ServerMethod::SigTerm(int)
386 struct timeval times
[2];
387 times
[0].tv_sec
= FailTime
;
388 times
[1].tv_sec
= FailTime
;
389 times
[0].tv_usec
= times
[1].tv_usec
= 0;
390 utimes(FailFile
.c_str(), times
);
396 // ServerMethod::Fetch - Fetch an item /*{{{*/
397 // ---------------------------------------------------------------------
398 /* This adds an item to the pipeline. We keep the pipeline at a fixed
400 bool ServerMethod::Fetch(FetchItem
*)
405 // Queue the requests
407 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
408 I
= I
->Next
, Depth
++)
410 // If pipelining is disabled, we only queue 1 request
411 if (Server
->Pipeline
== false && Depth
>= 0)
414 // Make sure we stick with the same server
415 if (Server
->Comp(I
->Uri
) == false)
428 // ServerMethod::Loop - Main loop /*{{{*/
429 int ServerMethod::Loop()
431 typedef vector
<string
> StringVector
;
432 typedef vector
<string
>::iterator StringVectorIterator
;
433 map
<string
, StringVector
> Redirected
;
435 signal(SIGTERM
,SigTerm
);
436 signal(SIGINT
,SigTerm
);
443 // We have no commands, wait for some to arrive
446 if (WaitFd(STDIN_FILENO
) == false)
450 /* Run messages, we can accept 0 (no message) if we didn't
451 do a WaitFd above.. Otherwise the FD is closed. */
452 int Result
= Run(true);
453 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
455 if(FailReason
.empty() == false ||
456 _config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
465 // Connect to the server
466 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
469 Server
= CreateServerState(Queue
->Uri
);
471 /* If the server has explicitly said this is the last connection
472 then we pre-emptively shut down the pipeline and tear down
473 the connection. This will speed up HTTP/1.0 servers a tad
474 since we don't have to wait for the close sequence to
476 if (Server
->Persistent
== false)
479 // Reset the pipeline
480 if (Server
->IsOpen() == false)
483 // Connnect to the host
484 if (Server
->Open() == false)
492 // Fill the pipeline.
495 // Fetch the next URL header data from the server.
496 switch (Server
->RunHeaders(File
, Queue
->Uri
))
498 case ServerState::RUN_HEADERS_OK
:
501 // The header data is bad
502 case ServerState::RUN_HEADERS_PARSE_ERROR
:
504 _error
->Error(_("Bad header data"));
510 // The server closed a connection during the header get..
512 case ServerState::RUN_HEADERS_IO_ERROR
:
517 Server
->Pipeline
= false;
519 if (FailCounter
>= 2)
521 Fail(_("Connection failed"),true);
530 // Decide what to do.
532 Res
.Filename
= Queue
->DestFile
;
533 switch (DealWithHeaders(Res
))
535 // Ok, the file is Open
542 if (Server
->HaveContent
)
543 Result
= Server
->RunData(File
);
545 /* If the server is sending back sizeless responses then fill in
548 Res
.Size
= File
->Size();
550 // Close the file, destroy the FD object and timestamp it
556 struct timeval times
[2];
557 times
[0].tv_sec
= times
[1].tv_sec
= Server
->Date
;
558 times
[0].tv_usec
= times
[1].tv_usec
= 0;
559 utimes(Queue
->DestFile
.c_str(), times
);
561 // Send status to APT
564 Res
.TakeHashes(*Server
->GetHashes());
569 if (Server
->IsOpen() == false)
575 if (FailCounter
>= 2)
577 Fail(_("Connection failed"),true);
596 // Hard server error, not found or something
597 case ERROR_UNRECOVERABLE
:
603 // Hard internal error, kill the connection and fail
604 case ERROR_NOT_FROM_SERVER
:
615 // We need to flush the data, the header is like a 404 w/ error text
616 case ERROR_WITH_CONTENT_PAGE
:
620 // Send to content to dev/null
621 File
= new FileFd("/dev/null",FileFd::WriteExists
);
622 Server
->RunData(File
);
628 // Try again with a new URL
629 case TRY_AGAIN_OR_REDIRECT
:
631 // Clear rest of response if there is content
632 if (Server
->HaveContent
)
634 File
= new FileFd("/dev/null",FileFd::WriteExists
);
635 Server
->RunData(File
);
640 /* Detect redirect loops. No more redirects are allowed
641 after the same URI is seen twice in a queue item. */
642 StringVector
&R
= Redirected
[Queue
->DestFile
];
643 bool StopRedirects
= false;
644 if (R
.empty() == true)
645 R
.push_back(Queue
->Uri
);
646 else if (R
[0] == "STOP" || R
.size() > 10)
647 StopRedirects
= true;
650 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); ++I
)
651 if (Queue
->Uri
== *I
)
657 R
.push_back(Queue
->Uri
);
660 if (StopRedirects
== false)
669 Fail(_("Internal error"));