| 1 |
{%MainUnit castledownload.pas} |
| 2 |
{ |
| 3 |
Copyright 2023-2024 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{ Handle http, https URLs using Delphi TNetHTTPClient. |
| 18 |
|
| 19 |
See https://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_an_HTTP_Client . |
| 20 |
See https://github.com/michaliskambi/delphi-http-download for my tests. |
| 21 |
|
| 22 |
Compared to Indy TIdHTTP, TNetHTTPClient : |
| 23 |
|
| 24 |
- Seems more feature-packed: |
| 25 |
TNetHTTPClient can do asynchronous operation, |
| 26 |
doing work in thread, automatically. |
| 27 |
|
| 28 |
- Supports HTTPS out of the box without the need for any additional DLLs on Windows. |
| 29 |
On Windows, it relies on system libraries (winhttp.dll) for HTTPS (and unencrypted HTTP too). |
| 30 |
On Linux, it relies on libcurl (and unencrypted HTTP too). |
| 31 |
Overall, it works on "higher-level", whereas Indy uses sockets directly |
| 32 |
and has more work to implement e.g. HTTPS support. |
| 33 |
|
| 34 |
- See https://stackoverflow.com/questions/43153919/delphi-tidhttp-vs-tnethttpclient |
| 35 |
for more info about the differences between the two. |
| 36 |
|
| 37 |
TODO: |
| 38 |
|
| 39 |
- On Windows: The download using TNetHTTPClient seems to be quite slow. |
| 40 |
Test with large file, like https://castle-engine.io/latest.zip , |
| 41 |
using e.g. asynchronous_download CGE example. |
| 42 |
|
| 43 |
Compare with FPC execution of asynchronous_download, using TFpHttpClient. |
| 44 |
|
| 45 |
The TNetHTTPClient is like 10x slower, very noticeable. |
| 46 |
|
| 47 |
Unknown whether this is also on Linux, due to Linux problems below. |
| 48 |
} |
| 49 |
|
| 50 |
{$if defined(DELPHI) and defined(CASTLE_DELPHI_NET_HTTP_CLIENT)} |
| 51 |
|
| 52 |
{$ifdef read_implementation_uses} |
| 53 |
System.Net.HttpClientComponent, System.Net.HttpClient, |
| 54 |
// for sLocation used when CASTLE_HTTP_MANUAL_REDIRECTS |
| 55 |
System.NetConsts, |
| 56 |
{$endif} |
| 57 |
|
| 58 |
{$ifdef read_implementation} |
| 59 |
|
| 60 |
type |
| 61 |
{ TUrlAsynchronousReader descendant that implements http(s) downloading. } |
| 62 |
TDelphiNetReader = class(TUrlAsynchronousReader) |
| 63 |
strict private |
| 64 |
C: TNetHttpClient; |
| 65 |
ContentsOwned: TMemoryStream; |
| 66 |
Response: IHTTPResponse; |
| 67 |
{ Call C.Get or similar method of C to actually start HTTP request. } |
| 68 |
procedure NetClientStart(const StartUrl: String); |
| 69 |
procedure ReceiveData(const Sender: TObject; |
| 70 |
AContentLength: Int64; AReadCount: Int64; var AAbort: Boolean); |
| 71 |
procedure RequestCompleted(const Sender: TObject; |
| 72 |
const AResponse: IHTTPResponse); |
| 73 |
procedure RequestError(const Sender: TObject; |
| 74 |
const AError: string); |
| 75 |
procedure RequestException(const Sender: TObject; |
| 76 |
const AError: Exception); |
| 77 |
class procedure ReceiveDataAbort(const Sender: TObject; |
| 78 |
AContentLength: Int64; AReadCount: Int64; var AAbort: Boolean); |
| 79 |
public |
| 80 |
procedure Start; override; |
| 81 |
destructor Destroy; override; |
| 82 |
procedure Update; override; |
| 83 |
end; |
| 84 |
|
| 85 |
{ Define TDelphiHttpReader used in castledownload_register.inc. |
| 86 |
It is an alias to a different class, depending on whether |
| 87 |
CASTLE_DELPHI_NET_HTTP_CLIENT was defined. } |
| 88 |
TDelphiHttpReader = TDelphiNetReader; |
| 89 |
|
| 90 |
{ TNetHttpClient on Delphi/Linux fails to handle redirects in some cases, |
| 91 |
testcase: http://castle-engine.io/latest.zip failing with timeout. |
| 92 |
Handling redirects on our side fixes the issue. |
| 93 |
|
| 94 |
Details: |
| 95 |
|
| 96 |
- https://github.com/michaliskambi/delphi-http-download (no CGE code) |
| 97 |
allows to reproduce it too (so it's really unrelated to CGE): |
| 98 |
|
| 99 |
- using the command-line https://github.com/michaliskambi/delphi-http-download/blob/master/test_net_http_client.dpr |
| 100 |
|
| 101 |
- using the FMX (GUI) application in https://github.com/michaliskambi/delphi-http-download/tree/master/fmx |
| 102 |
|
| 103 |
- Tested and reproduced with both Delphi 11.3 and 12. |
| 104 |
|
| 105 |
- It is reproducible regardless of the `Asynchronous` property value -- |
| 106 |
so it fails even in simpler case of synchronous operation. |
| 107 |
|
| 108 |
- Using `curl` from the command-line on the same system works OK, |
| 109 |
i.e. this works OK: |
| 110 |
|
| 111 |
curl -L http://castle-engine.io/latest.zip --output cge.zip |
| 112 |
|
| 113 |
Note that `TNetHttpClient` uses `libcurl` under the hood, |
| 114 |
so it should really work like `curl`. |
| 115 |
} |
| 116 |
{$define CASTLE_HTTP_MANUAL_REDIRECTS} |
| 117 |
|
| 118 |
{ TDelphiNetReader --------------------------------------------------- } |
| 119 |
|
| 120 |
procedure TDelphiNetReader.NetClientStart(const StartUrl: String); |
| 121 |
var |
| 122 |
EmptyPostData: TStringList; |
| 123 |
begin |
| 124 |
case HttpMethod of |
| 125 |
hmGet: Response := C.Get(StartUrl, ContentsOwned); |
| 126 |
hmPost: |
| 127 |
begin |
| 128 |
if HttpPostData = nil then |
| 129 |
begin |
| 130 |
EmptyPostData := TStringList.Create; |
| 131 |
try |
| 132 |
Response := C.Post(StartUrl, EmptyPostData, Contents) |
| 133 |
finally FreeAndNil(EmptyPostData) end; |
| 134 |
end else |
| 135 |
Response := C.Post(StartUrl, HttpPostData, Contents); |
| 136 |
end; |
| 137 |
hmPut: |
| 138 |
// TODO: We should pass Source stream to put, otherwise it is not very useful |
| 139 |
begin |
| 140 |
EmptyPostData := TStringList.Create; |
| 141 |
try |
| 142 |
Response := C.Put(StartUrl, EmptyPostData, Contents); |
| 143 |
finally FreeAndNil(EmptyPostData) end; |
| 144 |
end; |
| 145 |
hmDelete: Response := C.Delete(StartUrl, Contents); |
| 146 |
hmOptions: Response := C.Options(StartUrl, Contents); |
| 147 |
hmHead: Response := C.Head(StartUrl); |
| 148 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 149 |
else raise EInternalError.Create('HttpMethod=?'); |
| 150 |
{$endif} |
| 151 |
end; |
| 152 |
end; |
| 153 |
|
| 154 |
procedure TDelphiNetReader.Start; |
| 155 |
begin |
| 156 |
inherited; |
| 157 |
if not CheckNetworkAccess then |
| 158 |
Exit; |
| 159 |
|
| 160 |
{ TODO: honor |
| 161 |
ForceSynchronous: Boolean; // or nothing more to do? |
| 162 |
HttpHeadersKeys, HttpHeadersValues: TStrings; |
| 163 |
} |
| 164 |
|
| 165 |
{ Using separate ContentsOwned is a hack, to let the client |
| 166 |
leak in some cases. |
| 167 |
See TDelphiNetReader.Destroy comments. } |
| 168 |
ContentsOwned := TMemoryStream.Create; |
| 169 |
|
| 170 |
Contents := TMemoryStream.Create; |
| 171 |
|
| 172 |
C := TNetHttpClient.Create(nil); |
| 173 |
C.Asynchronous := not ForceSynchronous; |
| 174 |
C.OnReceiveData := ReceiveData; |
| 175 |
C.OnRequestCompleted := RequestCompleted; |
| 176 |
C.OnRequestError := RequestError; |
| 177 |
C.OnRequestException := RequestException; |
| 178 |
C.SynchronizeEvents := true; |
| 179 |
|
| 180 |
{$ifdef CASTLE_HTTP_MANUAL_REDIRECTS} |
| 181 |
C.HandleRedirects := false; |
| 182 |
{$endif} |
| 183 |
|
| 184 |
{$ifdef LINUX} |
| 185 |
{ Disable timeouts, otherwise downloading long files |
| 186 |
(like http://castle-engine.io/latest.zip) is always broken at timeout, |
| 187 |
even when things actually go OK (e.g. after downloading over 400 MB). |
| 188 |
This is asynchronous downloader anyway -- outside code can always |
| 189 |
break it, so timeouts hardcoded here should not be necessary. } |
| 190 |
C.ConnectionTimeout := -1; |
| 191 |
C.ResponseTimeout := -1; |
| 192 |
{$endif} |
| 193 |
|
| 194 |
{ TODO: Update FinalUrl during HTTP redirects even when |
| 195 |
CASTLE_HTTP_MANUAL_REDIRECTS not defined. |
| 196 |
For now only CASTLE_HTTP_MANUAL_REDIRECTS will update it. } |
| 197 |
FinalUrl := Url; |
| 198 |
|
| 199 |
NetClientStart(Url); |
| 200 |
end; |
| 201 |
|
| 202 |
destructor TDelphiNetReader.Destroy; |
| 203 |
|
| 204 |
{ TNetHttpClient cannot be freed before it finished the work |
| 205 |
or it will crash with access violation. |
| 206 |
|
| 207 |
We try to cancel it, and this seems to usually work, |
| 208 |
but in case it fails: |
| 209 |
we let the C and ContentsOwned to just leak, |
| 210 |
this still causes some crashes but at least we can ignore them |
| 211 |
(they seem to happen then only in some non-main thread). |
| 212 |
|
| 213 |
We also pass ReceiveDataAbort to at least stop actual transfer |
| 214 |
as soon as feasible. } |
| 215 |
procedure LeakNetHttpClient; |
| 216 |
begin |
| 217 |
C.OnReceiveData := TDelphiNetReader.ReceiveDataAbort; |
| 218 |
C.OnRequestCompleted := nil; |
| 219 |
C.OnRequestError := nil; |
| 220 |
C.OnRequestException := nil; |
| 221 |
|
| 222 |
WritelnWarning('Leaking TNetHttpClient reference. Freeing it before the request has completed leads to crashes'); |
| 223 |
|
| 224 |
ContentsOwned := nil; |
| 225 |
C := nil; |
| 226 |
Response := nil; |
| 227 |
end; |
| 228 |
|
| 229 |
const |
| 230 |
WaitForCancelStep = 10; //< in miliseconds |
| 231 |
WaitForCancelMax = 1000; //< in miliseconds; so we wait max 1 second |
| 232 |
var |
| 233 |
Waited: Cardinal; |
| 234 |
begin |
| 235 |
if (C <> nil) and |
| 236 |
(Status = dsDownloading) and |
| 237 |
(Response <> nil) and |
| 238 |
(not Response.AsyncResult.IsCompleted) then |
| 239 |
begin |
| 240 |
WritelnLog('TNetHttpClient', 'Aborting download in progress of "%s"', [UriDisplay(Url)]); |
| 241 |
|
| 242 |
{ We have to use SynchronizeEvents:=false, otherwise aborting |
| 243 |
TNetHttpClient would cause crashes as it would put in Synchronize() |
| 244 |
calls to our callbacks, so they will run from next |
| 245 |
Application.ProcessMessages, but by then we are already freed. |
| 246 |
|
| 247 |
So we also change callbacks to things that are harmless to run |
| 248 |
from arbitrary thread. |
| 249 |
} |
| 250 |
C.OnReceiveData := TDelphiNetReader.ReceiveDataAbort; |
| 251 |
C.OnRequestCompleted := nil; |
| 252 |
C.OnRequestError := nil; |
| 253 |
C.OnRequestException := nil; |
| 254 |
C.SynchronizeEvents := false; |
| 255 |
|
| 256 |
{ TNetHttpClient causes exceptions if freed without properly closing the connection. |
| 257 |
Testcase: asynchronous_download CGE example, press "Abort Downloads" |
| 258 |
after starting the downloads. |
| 259 |
Luckily, usually it can be cancelled immediately. } |
| 260 |
if Response.AsyncResult.Cancel then |
| 261 |
begin |
| 262 |
Assert(Response.AsyncResult.IsCancelled); |
| 263 |
Waited := 0; |
| 264 |
while |
| 265 |
(not Response.AsyncResult.IsCompleted) and |
| 266 |
(Waited < WaitForCancelMax) do |
| 267 |
begin |
| 268 |
Sleep(WaitForCancelStep); |
| 269 |
Waited := Waited + WaitForCancelStep; |
| 270 |
end; |
| 271 |
// warn when Waited <> 0 |
| 272 |
if Waited <> 0 then |
| 273 |
begin |
| 274 |
if Response.AsyncResult.IsCancelled then |
| 275 |
WritelnWarning('Waited to cancel for %f seconds. At least we cancelled OK, so we can cleanup TNetHttpClient OK. But cancelling this way causes delays in execution of the main loop.', [Waited / 1000]) |
| 276 |
else |
| 277 |
begin |
| 278 |
WritelnWarning('Waited to cancel for %f seconds. And we failed to cancel, to we will just leak TNetHttpClient now. Report a bug with reproduction.', [Waited / 1000]); |
| 279 |
LeakNetHttpClient; |
| 280 |
end; |
| 281 |
end; |
| 282 |
end else |
| 283 |
begin |
| 284 |
WritelnWarning('TNetHttpClient cannot be cancelled; leaking it'); |
| 285 |
LeakNetHttpClient; |
| 286 |
|
| 287 |
// TODO: Calling LeakNetHttpClient, to avoid crashes. |
| 288 |
// Find a case when it can be tested it in practice. |
| 289 |
// When does Cancel return false? Does it imply we can free TNetHttpClient? |
| 290 |
end; |
| 291 |
end; |
| 292 |
|
| 293 |
FreeAndNil(C); |
| 294 |
Response := nil; // release reference count from interface |
| 295 |
FreeAndNil(ContentsOwned); |
| 296 |
|
| 297 |
inherited; |
| 298 |
end; |
| 299 |
|
| 300 |
procedure TDelphiNetReader.ReceiveData(const Sender: TObject; |
| 301 |
AContentLength, AReadCount: Int64; var AAbort: Boolean); |
| 302 |
begin |
| 303 |
DownloadedBytes := AReadCount; |
| 304 |
TotalBytes := AContentLength; |
| 305 |
end; |
| 306 |
|
| 307 |
class procedure TDelphiNetReader.ReceiveDataAbort(const Sender: TObject; |
| 308 |
AContentLength, AReadCount: Int64; var AAbort: Boolean); |
| 309 |
begin |
| 310 |
{ Note: This cannot access any main thread stuff, it may be run |
| 311 |
in arbitrary thread by TNetHttpClient. } |
| 312 |
AAbort := true; |
| 313 |
end; |
| 314 |
|
| 315 |
procedure TDelphiNetReader.RequestCompleted(const Sender: TObject; |
| 316 |
const AResponse: IHTTPResponse); |
| 317 |
|
| 318 |
{$ifdef CASTLE_HTTP_MANUAL_REDIRECTS} |
| 319 |
function ArrayContainsInt(const X: Integer; const A: array of Integer): Boolean; |
| 320 |
var |
| 321 |
I: Integer; |
| 322 |
begin |
| 323 |
for I := 0 to High(A) do |
| 324 |
if A[I] = X then |
| 325 |
Exit(true); |
| 326 |
Result := false; |
| 327 |
end; |
| 328 |
|
| 329 |
{ Detect and handle http redirect, doing new NetClientStart if needed. |
| 330 |
Returns @true if redirect was handled, @false if not. } |
| 331 |
function HandleRedirect: Boolean; |
| 332 |
var |
| 333 |
RedirectToGet: Boolean; |
| 334 |
RedirectUrl: String; |
| 335 |
begin |
| 336 |
Result := false; |
| 337 |
|
| 338 |
if ArrayContainsInt(AResponse.StatusCode, [300, 301, 302, 303, 307, 308]) then |
| 339 |
begin |
| 340 |
RedirectUrl := Trim(AResponse.GetHeaderValue(sLocation)); |
| 341 |
if RedirectUrl <> '' then |
| 342 |
begin |
| 343 |
{ TODO: Preserve fragment (#xxx, it seems https://tools.ietf.org/html/rfc7231#section-7.1.2 ) |
| 344 |
from Url to FinalUrl. It practically doesn't matter for just downloading. } |
| 345 |
FinalUrl := RedirectUrl; |
| 346 |
WritelnLog('Redirecting to "%s"', [UriDisplay(FinalUrl)]); |
| 347 |
|
| 348 |
{ Some redirects should change method to GET. |
| 349 |
Logic matches default value of CHTTPDefRedirectsWithGET in Delphi. } |
| 350 |
RedirectToGet := false; |
| 351 |
case HttpMethod of |
| 352 |
hmPost: RedirectToGet := ArrayContainsInt(AResponse.StatusCode, [301, 302, 303]); |
| 353 |
hmPut: RedirectToGet := ArrayContainsInt(AResponse.StatusCode, [303]); |
| 354 |
hmDelete: RedirectToGet := ArrayContainsInt(Response.StatusCode, [303]); |
| 355 |
end; |
| 356 |
if RedirectToGet and (HttpMethod <> hmGet) then |
| 357 |
begin |
| 358 |
WritelnLog('Redirect changes method to GET'); |
| 359 |
HttpMethod := hmGet; |
| 360 |
end; |
| 361 |
|
| 362 |
// reset ContentsOwned |
| 363 |
ContentsOwned.Size := 0; |
| 364 |
ContentsOwned.Position := 0; |
| 365 |
|
| 366 |
NetClientStart(FinalUrl); |
| 367 |
|
| 368 |
Result := true; |
| 369 |
end; |
| 370 |
end; |
| 371 |
end; |
| 372 |
{$endif} |
| 373 |
|
| 374 |
begin |
| 375 |
{$ifdef CASTLE_HTTP_MANUAL_REDIRECTS} |
| 376 |
if HandleRedirect then |
| 377 |
Exit; |
| 378 |
{$endif} |
| 379 |
|
| 380 |
WritelnLog('Completed request for "%s" with status %d', [ |
| 381 |
UriDisplay(Url), |
| 382 |
AResponse.StatusCode |
| 383 |
]); |
| 384 |
|
| 385 |
HttpResponseCode := AResponse.StatusCode; |
| 386 |
MimeType := ContentTypeToMimeType(AResponse.MimeType); |
| 387 |
|
| 388 |
{ TODO: Set HttpResponseHeaders from AResponse.Headers |
| 389 |
HttpResponseHeaders := TStringList.Create; |
| 390 |
HttpResponseHeaders.NameValueSeparator := ':'; |
| 391 |
// for each pair in AResponse.Headers, add it to HttpResponseHeaders |
| 392 |
} |
| 393 |
|
| 394 |
// finish the Contents stream |
| 395 |
Contents.CopyFrom(ContentsOwned); |
| 396 |
DownloadedBytes := TMemoryStream(Contents).Size; |
| 397 |
TotalBytes := TMemoryStream(Contents).Size; |
| 398 |
Contents.Position := 0; // rewind |
| 399 |
|
| 400 |
if HttpResponseCode <> 200 then |
| 401 |
begin |
| 402 |
Status := dsError; |
| 403 |
ErrorMessage := Format('HTTP request completed with status %d (not 200, so not success)', [ |
| 404 |
HttpResponseCode |
| 405 |
]); |
| 406 |
end else |
| 407 |
begin |
| 408 |
Status := dsSuccess; |
| 409 |
end; |
| 410 |
end; |
| 411 |
|
| 412 |
procedure TDelphiNetReader.RequestError(const Sender: TObject; |
| 413 |
const AError: string); |
| 414 |
begin |
| 415 |
Status := dsError; |
| 416 |
ErrorMessage := AError; |
| 417 |
end; |
| 418 |
|
| 419 |
procedure TDelphiNetReader.RequestException(const Sender: TObject; |
| 420 |
const AError: Exception); |
| 421 |
begin |
| 422 |
Status := dsError; |
| 423 |
ErrorMessage := ExceptMessage(AError); |
| 424 |
end; |
| 425 |
|
| 426 |
procedure TDelphiNetReader.Update; |
| 427 |
begin |
| 428 |
inherited; |
| 429 |
|
| 430 |
{ No need to do anything, our event callbacks are called already. |
| 431 |
|
| 432 |
Even in console application, that doesn't explicitly |
| 433 |
do Application.ProcessMessages. |
| 434 |
On both Windows and Linux. |
| 435 |
See https://github.com/michaliskambi/delphi-http-download test. |
| 436 |
|
| 437 |
TODO: How are the callbacks called, from where, |
| 438 |
since we don't necessarily execute the Delphi VCL / FMX event loop? |
| 439 |
E.g. with TCastleWindow (WinAPI backend) we execute own loop, |
| 440 |
and we don't call VCL / FMX Application.ProcessMessages. |
| 441 |
But the callbacks still happen, even in console application. |
| 442 |
It seems that at least for Windows, with TCastleWindow, |
| 443 |
Delphi somehow hooked to the Windows event loop to make them happen? |
| 444 |
I haven't found how are they done on Linux. |
| 445 |
|
| 446 |
Note: The work of TNetHttpClient is done in a thread, so it makes sense |
| 447 |
that it *does processing (downloads new bytes)* without |
| 448 |
Application.ProcessMessages. |
| 449 |
The above question is how does Delphi Synchronize work in |
| 450 |
Linux console application |
| 451 |
that doesn't call VCL / FMX Application.ProcessMessages? |
| 452 |
} |
| 453 |
end; |
| 454 |
|
| 455 |
{$endif read_implementation} |
| 456 |
|
| 457 |
{$endif defined(DELPHI) and defined(CASTLE_DELPHI_NET_HTTP_CLIENT)} |