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/fileutl.h>
14 #include <apt-pkg/acquire-method.h>
15 #include <apt-pkg/configuration.h>
16 #include <apt-pkg/error.h>
17 #include <apt-pkg/hashes.h>
18 #include <apt-pkg/netrc.h>
37 #include "rfc2553emu.h"
44 string
ServerMethod::FailFile
;
45 int ServerMethod::FailFd
= -1;
46 time_t ServerMethod::FailTime
= 0;
48 // ServerState::RunHeaders - Get the headers before the data /*{{{*/
49 // ---------------------------------------------------------------------
50 /* Returns 0 if things are OK, 1 if an IO error occurred and 2 if a header
51 parse error occurred */
52 ServerState::RunHeadersResult
ServerState::RunHeaders(FileFd
* const File
)
56 Owner
->Status(_("Waiting for headers"));
70 if (ReadHeaderLines(Data
) == false)
73 if (Owner
->Debug
== true)
76 for (string::const_iterator I
= Data
.begin(); I
< Data
.end(); ++I
)
78 string::const_iterator J
= I
;
79 for (; J
!= Data
.end() && *J
!= '\n' && *J
!= '\r'; ++J
);
80 if (HeaderLine(string(I
,J
)) == false)
81 return RUN_HEADERS_PARSE_ERROR
;
85 // 100 Continue is a Nop...
89 // Tidy up the connection persistance state.
90 if (Encoding
== Closes
&& HaveContent
== true)
93 return RUN_HEADERS_OK
;
95 while (LoadNextResponse(false, File
) == true);
97 return RUN_HEADERS_IO_ERROR
;
100 // ServerState::HeaderLine - Process a header line /*{{{*/
101 // ---------------------------------------------------------------------
103 bool ServerState::HeaderLine(string Line
)
105 if (Line
.empty() == true)
108 string::size_type Pos
= Line
.find(' ');
109 if (Pos
== string::npos
|| Pos
+1 > Line
.length())
111 // Blah, some servers use "connection:closes", evil.
112 Pos
= Line
.find(':');
113 if (Pos
== string::npos
|| Pos
+ 2 > Line
.length())
114 return _error
->Error(_("Bad header line"));
118 // Parse off any trailing spaces between the : and the next word.
119 string::size_type Pos2
= Pos
;
120 while (Pos2
< Line
.length() && isspace(Line
[Pos2
]) != 0)
123 string Tag
= string(Line
,0,Pos
);
124 string Val
= string(Line
,Pos2
);
126 if (stringcasecmp(Tag
.c_str(),Tag
.c_str()+4,"HTTP") == 0)
128 // Evil servers return no version
131 int const elements
= sscanf(Line
.c_str(),"HTTP/%3u.%3u %3u%359[^\n]",&Major
,&Minor
,&Result
,Code
);
135 if (Owner
->Debug
== true)
136 clog
<< "HTTP server doesn't give Reason-Phrase for " << Result
<< std::endl
;
138 else if (elements
!= 4)
139 return _error
->Error(_("The HTTP server sent an invalid reply header"));
145 if (sscanf(Line
.c_str(),"HTTP %3u%359[^\n]",&Result
,Code
) != 2)
146 return _error
->Error(_("The HTTP server sent an invalid reply header"));
149 /* Check the HTTP response header to get the default persistance
155 if (Major
== 1 && Minor
== 0)
164 if (stringcasecmp(Tag
,"Content-Length:") == 0)
166 if (Encoding
== Closes
)
170 // The length is already set from the Content-Range header
174 Size
= strtoull(Val
.c_str(), NULL
, 10);
175 if (Size
>= std::numeric_limits
<unsigned long long>::max())
176 return _error
->Errno("HeaderLine", _("The HTTP server sent an invalid Content-Length header"));
182 if (stringcasecmp(Tag
,"Content-Type:") == 0)
188 if (stringcasecmp(Tag
,"Content-Range:") == 0)
192 // ยง14.16 says 'byte-range-resp-spec' should be a '*' in case of 416
193 if (Result
== 416 && sscanf(Val
.c_str(), "bytes */%llu",&Size
) == 1)
195 StartPos
= 1; // ignore Content-Length, it would override Size
198 else if (sscanf(Val
.c_str(),"bytes %llu-%*u/%llu",&StartPos
,&Size
) != 2)
199 return _error
->Error(_("The HTTP server sent an invalid Content-Range header"));
200 if ((unsigned long long)StartPos
> Size
)
201 return _error
->Error(_("This HTTP server has broken range support"));
205 if (stringcasecmp(Tag
,"Transfer-Encoding:") == 0)
208 if (stringcasecmp(Val
,"chunked") == 0)
213 if (stringcasecmp(Tag
,"Connection:") == 0)
215 if (stringcasecmp(Val
,"close") == 0)
217 if (stringcasecmp(Val
,"keep-alive") == 0)
222 if (stringcasecmp(Tag
,"Last-Modified:") == 0)
224 if (RFC1123StrToTime(Val
.c_str(), Date
) == false)
225 return _error
->Error(_("Unknown date format"));
229 if (stringcasecmp(Tag
,"Location:") == 0)
238 // ServerState::ServerState - Constructor /*{{{*/
239 ServerState::ServerState(URI Srv
, ServerMethod
*Owner
) : ServerName(Srv
), TimeOut(120), Owner(Owner
)
245 bool ServerMethod::Configuration(string Message
) /*{{{*/
247 return pkgAcqMethod::Configuration(Message
);
251 // ServerMethod::DealWithHeaders - Handle the retrieved header data /*{{{*/
252 // ---------------------------------------------------------------------
253 /* We look at the header data we got back from the server and decide what
254 to do. Returns DealWithHeadersResult (see http.h for details).
256 ServerMethod::DealWithHeadersResult
257 ServerMethod::DealWithHeaders(FetchResult
&Res
)
260 if (Server
->Result
== 304)
262 unlink(Queue
->DestFile
.c_str());
264 Res
.LastModified
= Queue
->LastModified
;
270 * Note that it is only OK for us to treat all redirection the same
271 * because we *always* use GET, not other HTTP methods. There are
272 * three redirection codes for which it is not appropriate that we
273 * redirect. Pass on those codes so the error handling kicks in.
276 && (Server
->Result
> 300 && Server
->Result
< 400)
277 && (Server
->Result
!= 300 // Multiple Choices
278 && Server
->Result
!= 304 // Not Modified
279 && Server
->Result
!= 306)) // (Not part of HTTP/1.1, reserved)
281 if (Server
->Location
.empty() == true);
282 else if (Server
->Location
[0] == '/' && Queue
->Uri
.empty() == false)
284 URI Uri
= Queue
->Uri
;
285 if (Uri
.Host
.empty() == false)
286 NextURI
= URI::SiteOnly(Uri
);
289 NextURI
.append(DeQuoteString(Server
->Location
));
290 return TRY_AGAIN_OR_REDIRECT
;
294 NextURI
= DeQuoteString(Server
->Location
);
295 URI tmpURI
= NextURI
;
296 // Do not allow a redirection to switch protocol
297 if (tmpURI
.Access
== "http")
298 return TRY_AGAIN_OR_REDIRECT
;
300 /* else pass through for error message */
302 // retry after an invalid range response without partial data
303 else if (Server
->Result
== 416)
306 if (stat(Queue
->DestFile
.c_str(),&SBuf
) >= 0 && SBuf
.st_size
> 0)
308 if ((unsigned long long)SBuf
.st_size
== Server
->Size
)
310 // the file is completely downloaded, but was not moved
311 Server
->StartPos
= Server
->Size
;
312 Server
->Result
= 200;
313 Server
->HaveContent
= false;
315 else if (unlink(Queue
->DestFile
.c_str()) == 0)
317 NextURI
= Queue
->Uri
;
318 return TRY_AGAIN_OR_REDIRECT
;
323 /* We have a reply we dont handle. This should indicate a perm server
325 if (Server
->Result
< 200 || Server
->Result
>= 300)
328 snprintf(err
,sizeof(err
)-1,"HttpError%i",Server
->Result
);
330 _error
->Error("%u %s",Server
->Result
,Server
->Code
);
331 if (Server
->HaveContent
== true)
332 return ERROR_WITH_CONTENT_PAGE
;
333 return ERROR_UNRECOVERABLE
;
336 // This is some sort of 2xx 'data follows' reply
337 Res
.LastModified
= Server
->Date
;
338 Res
.Size
= Server
->Size
;
342 File
= new FileFd(Queue
->DestFile
,FileFd::WriteAny
);
343 if (_error
->PendingError() == true)
344 return ERROR_NOT_FROM_SERVER
;
346 FailFile
= Queue
->DestFile
;
347 FailFile
.c_str(); // Make sure we dont do a malloc in the signal handler
349 FailTime
= Server
->Date
;
351 if (Server
->InitHashes(*File
) == false)
353 _error
->Errno("read",_("Problem hashing file"));
354 return ERROR_NOT_FROM_SERVER
;
356 if (Server
->StartPos
> 0)
357 Res
.ResumePoint
= Server
->StartPos
;
359 SetNonBlock(File
->Fd(),true);
363 // ServerMethod::SigTerm - Handle a fatal signal /*{{{*/
364 // ---------------------------------------------------------------------
365 /* This closes and timestamps the open file. This is neccessary to get
366 resume behavoir on user abort */
367 void ServerMethod::SigTerm(int)
375 UBuf
.actime
= FailTime
;
376 UBuf
.modtime
= FailTime
;
377 utime(FailFile
.c_str(),&UBuf
);
382 // ServerMethod::Fetch - Fetch an item /*{{{*/
383 // ---------------------------------------------------------------------
384 /* This adds an item to the pipeline. We keep the pipeline at a fixed
386 bool ServerMethod::Fetch(FetchItem
*)
391 // Queue the requests
393 for (FetchItem
*I
= Queue
; I
!= 0 && Depth
< (signed)PipelineDepth
;
394 I
= I
->Next
, Depth
++)
396 // If pipelining is disabled, we only queue 1 request
397 if (Server
->Pipeline
== false && Depth
>= 0)
400 // Make sure we stick with the same server
401 if (Server
->Comp(I
->Uri
) == false)
414 // ServerMethod::Loop - Main loop /*{{{*/
415 int ServerMethod::Loop()
417 typedef vector
<string
> StringVector
;
418 typedef vector
<string
>::iterator StringVectorIterator
;
419 map
<string
, StringVector
> Redirected
;
421 signal(SIGTERM
,SigTerm
);
422 signal(SIGINT
,SigTerm
);
429 // We have no commands, wait for some to arrive
432 if (WaitFd(STDIN_FILENO
) == false)
436 /* Run messages, we can accept 0 (no message) if we didn't
437 do a WaitFd above.. Otherwise the FD is closed. */
438 int Result
= Run(true);
439 if (Result
!= -1 && (Result
!= 0 || Queue
== 0))
441 if(FailReason
.empty() == false ||
442 _config
->FindB("Acquire::http::DependOnSTDIN", true) == true)
451 // Connect to the server
452 if (Server
== 0 || Server
->Comp(Queue
->Uri
) == false)
455 Server
= CreateServerState(Queue
->Uri
);
457 /* If the server has explicitly said this is the last connection
458 then we pre-emptively shut down the pipeline and tear down
459 the connection. This will speed up HTTP/1.0 servers a tad
460 since we don't have to wait for the close sequence to
462 if (Server
->Persistent
== false)
465 // Reset the pipeline
466 if (Server
->IsOpen() == false)
469 // Connnect to the host
470 if (Server
->Open() == false)
478 // Fill the pipeline.
481 // Fetch the next URL header data from the server.
482 switch (Server
->RunHeaders(File
))
484 case ServerState::RUN_HEADERS_OK
:
487 // The header data is bad
488 case ServerState::RUN_HEADERS_PARSE_ERROR
:
490 _error
->Error(_("Bad header data"));
496 // The server closed a connection during the header get..
498 case ServerState::RUN_HEADERS_IO_ERROR
:
503 Server
->Pipeline
= false;
505 if (FailCounter
>= 2)
507 Fail(_("Connection failed"),true);
516 // Decide what to do.
518 Res
.Filename
= Queue
->DestFile
;
519 switch (DealWithHeaders(Res
))
521 // Ok, the file is Open
528 if (Server
->HaveContent
)
529 Result
= Server
->RunData(File
);
531 /* If the server is sending back sizeless responses then fill in
534 Res
.Size
= File
->Size();
536 // Close the file, destroy the FD object and timestamp it
544 UBuf
.actime
= Server
->Date
;
545 UBuf
.modtime
= Server
->Date
;
546 utime(Queue
->DestFile
.c_str(),&UBuf
);
548 // Send status to APT
551 Res
.TakeHashes(*Server
->GetHashes());
556 if (Server
->IsOpen() == false)
562 if (FailCounter
>= 2)
564 Fail(_("Connection failed"),true);
583 // Hard server error, not found or something
584 case ERROR_UNRECOVERABLE
:
590 // Hard internal error, kill the connection and fail
591 case ERROR_NOT_FROM_SERVER
:
602 // We need to flush the data, the header is like a 404 w/ error text
603 case ERROR_WITH_CONTENT_PAGE
:
607 // Send to content to dev/null
608 File
= new FileFd("/dev/null",FileFd::WriteExists
);
609 Server
->RunData(File
);
615 // Try again with a new URL
616 case TRY_AGAIN_OR_REDIRECT
:
618 // Clear rest of response if there is content
619 if (Server
->HaveContent
)
621 File
= new FileFd("/dev/null",FileFd::WriteExists
);
622 Server
->RunData(File
);
627 /* Detect redirect loops. No more redirects are allowed
628 after the same URI is seen twice in a queue item. */
629 StringVector
&R
= Redirected
[Queue
->DestFile
];
630 bool StopRedirects
= false;
631 if (R
.empty() == true)
632 R
.push_back(Queue
->Uri
);
633 else if (R
[0] == "STOP" || R
.size() > 10)
634 StopRedirects
= true;
637 for (StringVectorIterator I
= R
.begin(); I
!= R
.end(); ++I
)
638 if (Queue
->Uri
== *I
)
644 R
.push_back(Queue
->Uri
);
647 if (StopRedirects
== false)
656 Fail(_("Internal error"));