Debian Codegraph @

src/files/castledownload_url_http_fphttpclient.inc

raw
1 {%MainUnit castledownload.pas}
2 {
3 Copyright 2013-2023 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 FpHttpClient. }
18 {$ifdef HAS_FP_HTTP_CLIENT}
19
20 {$ifdef read_implementation_uses}
21 SSLSockets, FpHttpClient, SyncObjs,
22 {$endif}
23
24 {$ifdef read_implementation}
25
26 type
27 TFpHttpClientThread = class;
28 TFpHttpClientJob = class;
29
30 { Customized HTTP client. In addition to TFpHttpClient this:
31
32 - Updates ParentJob.DownloadedBytes
33 - Updates ParentJob.TotalBytes
34 - Updates ParentJob.MimeType
35 - Updates ParentJob.FinalUrl
36 - Terminates the client, if ParentThread is terminated
37 (ParentThread can also be = nil, for non-threaded operation)
38
39 This is used only within thread, in TFpHttpClientThread. }
40 TCastleFpHttpClient = class(TFpHttpClient)
41 protected
42 function ReadResponseHeaders: Integer; override;
43 procedure DisconnectFromServer; override;
44 procedure RedirectLog(Sender: TObject; const ASrc: String; var ADest: String);
45 procedure DataReceived(Sender: TObject; const ContentLength, CurrentPos: Int64);
46 public
47 ParentJob: TFpHttpClientJob;
48 ParentThread: TFpHttpClientThread;
49 SynchronizationCS: TCriticalSection;
50 Contents: TMemoryStream;
51 MimeTypeFromUrl: String;
52 constructor Create(AOwner: TComponent); override;
53 destructor Destroy; override;
54 end;
55
56 { Job that downloads using FpHttpClient.
57 Can be put in thread (like TFpHttpClientThread) or used without thread. }
58 TFpHttpClientJob = class
59 public
60 { Set these before Execute }
61 HttpPostData, HttpHeadersKeys, HttpHeadersValues: TStrings;
62 HttpRequestBody: TStream;
63 Url: String;
64 HttpMethod: THttpMethod;
65 SynchronizationCS: TCriticalSection;
66 ParentThread: TFpHttpClientThread; //< leave nil for non-threaded operation
67
68 { Updated even during downloading, but always using SynchronizationCS. }
69 DownloadedBytes, TotalBytes: Int64;
70 MimeType: String;
71
72 { Once we're finished (Running = false) then
73
74 - Success informs about whether we have dsSuccess or dsError.
75 - HttpResponseCode is the HTTP answer.
76 - Contents contain the response (regardless of Success value).
77 If you take it, then set it to @nil, to avoid freeing it here.
78 - When Success = @false, ErrorMessage is the error message.
79 }
80 Success: Boolean;
81 Contents: TMemoryStream;
82 ErrorMessage: String;
83 HttpResponseCode: Integer;
84 HttpResponseHeaders: TStrings;
85 FinalUrl: String;
86
87 { Free SynchronizationCS in destructor. }
88 OwnsSynchronizationCS: Boolean;
89
90 constructor Create;
91 destructor Destroy; override;
92 procedure Execute;
93 end;
94
95 { Thread that downloads using FpHttpClient. }
96 TFpHttpClientThread = class(TThread)
97 Job: TFpHttpClientJob;
98 constructor Create;
99 destructor Destroy; override;
100 procedure Execute; override;
101 end;
102
103 { TUrlAsynchronousReader descendant that implements http(s) downloading. }
104 TFpHttpClientReader = class(TUrlAsynchronousReader)
105 strict private
106 Thread: TFpHttpClientThread;
107 SynchronizationCS: TCriticalSection;
108 { Synchronize one last time from Job, when it finished work in Execute. }
109 procedure SynchronizeFromFinishedJob(const Job: TFpHttpClientJob);
110 public
111 procedure Start; override;
112 destructor Destroy; override;
113 procedure Update; override;
114 end;
115
116 { TCastleFpHttpClient ---------------------------------------------------------- }
117
118 constructor TCastleFpHttpClient.Create(AOwner: TComponent);
119 begin
120 inherited;
121 OnRedirect := @RedirectLog;
122 OnDataReceived := @DataReceived;
123 end;
124
125 procedure TCastleFpHttpClient.RedirectLog(Sender: TObject; const ASrc: String; var ADest: String);
126 begin
127 // TODO: WritelnLog is not safe from thread:
128 WritelnLog('Network', 'Following HTTP redirect to "%s"', [ADest]);
129
130 SynchronizationCS.Acquire;
131 try
132 ParentJob.FinalUrl := ADest;
133 finally SynchronizationCS.Release end;
134 end;
135
136 procedure TCastleFpHttpClient.DataReceived(Sender: TObject; const ContentLength, CurrentPos: Int64);
137 begin
138 SynchronizationCS.Acquire;
139 try
140 ParentJob.DownloadedBytes := Max(Contents.Size, 0);
141
142 if ContentLength = 0 then
143 { FpHttpClient leaves ContentLength as 0 in case of chunked HTTP response.
144 We want to treat it as -1 (unknown) then.
145 Testcase: examples/network/asynchronous_download/ with
146 https://castle-engine.io/modern_pascal_introduction.html (FPC 3.2.0 on Linux/x86_64). }
147 ParentJob.TotalBytes := -1
148 else
149 { Otherwise ContentLength is exactly what we need for TotalBytes.
150 Note: FpHttpClient may set ContentLength to -1 if unknown
151 (not specified in headers), which is exactly what we want. }
152 ParentJob.TotalBytes := ContentLength;
153 finally SynchronizationCS.Release end;
154
155 {$ifndef VER3_0_2}
156 if (ParentThread <> nil) and ParentThread.Terminated then
157 Terminate;
158 {$endif}
159 end;
160
161 function TCastleFpHttpClient.ReadResponseHeaders: Integer;
162 var
163 MimeType: String;
164 begin
165 Result := inherited;
166
167 { Determine ParentJob.MimeType.
168 Do it only for http status = 200, otherwise we would detect MIME type
169 for intermediate content send with redirection. }
170 if Result = 200 then
171 begin
172 ResponseHeaders.NameValueSeparator := ':';
173 MimeType := ContentTypeToMimeType(ResponseHeaders.Values['Content-Type']);
174 if MimeType = '' then
175 MimeType := MimeTypeFromUrl;
176 SynchronizationCS.Acquire;
177 try
178 ParentJob.MimeType := MimeType;
179 finally SynchronizationCS.Release end;
180 end;
181 end;
182
183 procedure TCastleFpHttpClient.DisconnectFromServer;
184 begin
185 inherited;
186 end;
187
188 destructor TCastleFpHttpClient.Destroy;
189 begin
190 inherited;
191 end;
192
193 { TFpHttpClientJob -------------------------------------------------------- }
194
195 constructor TFpHttpClientJob.Create;
196 begin
197 inherited;
198 Contents := TMemoryStream.Create;
199 TotalBytes := -1;
200 end;
201
202 destructor TFpHttpClientJob.Destroy;
203 begin
204 FreeAndNil(Contents);
205 FreeAndNil(HttpResponseHeaders);
206 if OwnsSynchronizationCS then
207 FreeAndNil(SynchronizationCS);
208 inherited;
209 end;
210
211 procedure TFpHttpClientJob.Execute;
212
213 function UseHttpRequestBody: Boolean;
214 begin
215 Result := (HttpRequestBody <> nil) and (HttpRequestBody.Size <> 0);
216 end;
217
218 var
219 Client: TCastleFpHttpClient;
220 I: Integer;
221 MemStream: TMemoryStream;
222 begin
223 MemStream := nil; // to have later FreeAndNil(MemStream) safely
224 try
225 Client := TCastleFpHttpClient.Create(nil);
226 try
227 Client.ParentJob := Self;
228 Client.ParentThread := ParentThread;
229 Client.SynchronizationCS := SynchronizationCS;
230 Client.Contents := Contents;
231 Client.AllowRedirect := true;
232 Client.MimeTypeFromUrl := UriMimeType(Url);
233 // Client is used only once, so KeepConnection not necessary
234 {$ifndef VER3_0_2}
235 Client.KeepConnection := false;
236 {$endif}
237 // add additional headers
238 if HttpHeadersKeys <> nil then
239 begin
240 Assert((HttpHeadersKeys <> nil) = (HttpHeadersValues <> nil));
241 Assert(HttpHeadersKeys.Count = HttpHeadersValues.Count);
242 for I := 0 to HttpHeadersKeys.Count - 1 do
243 Client.AddHeader(HttpHeadersKeys[I], HttpHeadersValues[I]);
244 end;
245
246 // will be updated by Client when redirect occurs
247 FinalUrl := Url;
248
249 try
250 if UseHttpRequestBody then
251 begin
252 Assert(HttpRequestBody <> nil);
253 MemStream := TMemoryStream.Create;
254 MemStream.CopyFrom(HttpRequestBody, 0);
255 MemStream.Seek(0, soFromBeginning); // client does not always rewind the stream before send
256 Client.RequestBody := MemStream; // we own stream, and free it, the client is not touching it
257 end;
258
259 case HttpMethod of
260 hmGet: Client.Get(Url, Contents);
261 hmPost:
262 if (HttpPostData <> nil) and (not UseHttpRequestBody) then
263 Client.FormPost(Url, HttpPostData, Contents)
264 else
265 Client.Post(Url, Contents);
266 hmPut: Client.Put(Url, Contents);
267 hmDelete: Client.Delete(Url, Contents);
268 hmOptions: Client.Options(Url, Contents);
269 hmHead: //Client.Head(Url);
270 Client.HTTPMethod('HEAD', Url, nil, [200]);
271 {$ifndef COMPILER_CASE_ANALYSIS}
272 else raise EInternalError.Create('HttpMethod=?');
273 {$endif}
274 end;
275 finally
276 HttpResponseCode := Client.ResponseStatusCode;
277 HttpResponseHeaders := TStringList.Create;
278 HttpResponseHeaders.NameValueSeparator := ':';
279 HttpResponseHeaders.Assign(Client.ResponseHeaders);
280 end;
281
282 { In case of GET, this is done automatically by FpHttpClient.
283 But for e.g. POST, it accepts any response code as OK (I'm not sure why).
284 So we check it manually here. }
285 if HttpResponseCode <> 200 then
286 raise EHTTPClient.CreateFmt('Unexpected response status code: %d', [HttpResponseCode]);
287 finally
288 FreeAndNil(MemStream);
289 FreeAndNil(Client);
290 end;
291
292 Contents.Position := 0; { rewind for easy reading }
293
294 Success := true;
295 except
296 on E: TObject do
297 begin
298 Success := false;
299 ErrorMessage := Format('Error when downloading "%s": ', [UriDisplay(Url)]) + ExceptMessage(E);
300
301 {$if defined(VER3_2) and defined(DARWIN) and not defined(CASTLE_IOS)}
302 if (E is ESocketError) and (URIProtocol(Url) = 'https') then
303 begin
304 ErrorMessage += NL +
305 'Warning: Https downloading with FPC 3.2.0 on macOS is broken for many hosts.' + NL +
306 'Upgrade to FPC 3.3.1.' + NL +
307 'See https://bugs.freepascal.org/view.php?id=37747 , https://github.com/castle-engine/castle-engine/issues/184 .';
308 end;
309 {$endif}
310 end;
311 end;
312 end;
313
314 { TFpHttpClientThread -------------------------------------------------------- }
315
316 constructor TFpHttpClientThread.Create;
317 begin
318 inherited Create(true); // create suspended
319 Job := TFpHttpClientJob.Create;
320 Job.ParentThread := Self;
321 end;
322
323 destructor TFpHttpClientThread.Destroy;
324 begin
325 FreeAndNil(Job);
326 inherited;
327 end;
328
329 procedure TFpHttpClientThread.Execute;
330 begin
331 Job.Execute;
332 end;
333
334 { TFpHttpClientReader --------------------------------------------------- }
335
336 procedure TFpHttpClientReader.Start;
337
338 procedure InitializeJob(const Job: TFpHttpClientJob);
339 begin
340 Job.Url := Url;
341 Job.SynchronizationCS := SynchronizationCS;
342 Job.HttpMethod := HttpMethod;
343 Job.HttpPostData := HttpPostData;
344 Job.HttpRequestBody := HttpRequestBody;
345 Job.HttpHeadersKeys := HttpHeadersKeys;
346 Job.HttpHeadersValues := HttpHeadersValues;
347 end;
348
349 var
350 SynchronousJob: TFpHttpClientJob;
351 begin
352 inherited;
353 if not CheckNetworkAccess then
354 Exit;
355
356 if URIProtocol(Url) = 'https' then
357 begin
358 {$ifdef VER3_0}
359 { Testcase: FPC 3.0.4, Linux/x86_64:
360 TFPCustomHTTPClient fails with Access Violation on https URLs.
361 TODO: Test on Windows/x86_64. }
362 Status := dsError;
363 ErrorMessage := 'Downloading using "https" protocol does not work when the application is compiled with FPC 3.0.x. Use newer FPC (and add OpenSSLSockets unit to the uses clause).';
364 Exit;
365 {$endif}
366
367 {$ifndef VER3_0} // only for FPC >= 3.2.0
368 { The first download using https initializes OpenSSL library.
369 This is done by TFPCustomHTTPClient accessing TSSLSocketHandler.GetDefaultHandler,
370 and using OpenSSLSockets unit initializes that handler to do MaybeInitSSLInterface
371 at handler creation.
372 However this cannot be done from thread: multiple threads trying to do
373 MaybeInitSSLInterface at the same time, means that only 1 succeeds,
374 others raise "Could not initialize OpenSSL library".
375 Testcase: examples/network/asynchronous_download/ with 3 downloads over https
376 (FPC 3.2.0 on Linux/x86_64).
377
378 Solution is simply to initialize it from main thread here. }
379 TSSLSocketHandler.GetDefaultHandler.Free;
380 {$endif}
381 end;
382
383 CheckFileAccessSafe(Url);
384 WritelnLog('Network', 'Downloading "%s"', [UriDisplay(Url)]);
385
386 SynchronizationCS := TCriticalSection.Create;
387
388 if ForceSynchronous then
389 begin
390 { This is useful when OS doesn't support
391 threads, or they not linked in (e.g. no CThreads on Unix).
392 In this case we can at least download synchronously, which sometimes is enough. }
393 SynchronousJob := TFpHttpClientJob.Create;
394 try
395 InitializeJob(SynchronousJob);
396 SynchronousJob.Execute;
397 SynchronizeFromFinishedJob(SynchronousJob);
398 finally FreeAndNil(SynchronousJob) end;
399 end else
400 begin
401 Thread := TFpHttpClientThread.Create;
402 InitializeJob(Thread.Job);
403 Thread.Start;
404 end;
405 end;
406
407 destructor TFpHttpClientReader.Destroy;
408 begin
409 if Thread <> nil then
410 begin
411 Thread.Terminate;
412
413 {.$define CASTLE_SAFE_DOWNLOAD_INTERRUPTION}
414 {$ifdef CASTLE_SAFE_DOWNLOAD_INTERRUPTION}
415 WritelnLog('Network', 'Interrupting download in-progress of "%s"', [UriDisplay(Url)]);
416 Thread.WaitFor;
417 FreeAndNil(Thread);
418
419 {$else}
420 if not Thread.Finished then
421 begin
422 { TODO: This will leak memory if Running changed from true to false between these 2 lines.
423 Then thread instance will not be freed, as ThreadProc (running Execute,
424 and potentially freeing thread afterwards) has already finished
425 before we set FreeOnTerminate.
426
427 We cannot fix it by doing "Thread.FreeOnTerminate := true" earlier,
428 because then we have a race, and "Thread" reference may no longer be used.
429
430 A potential fix is in CASTLE_SAFE_DOWNLOAD_INTERRUPTION but this
431 could cause short delay when interrupting downloads.
432
433 TODO: This is actually dangerous if the interruption will happen
434 before thread Execute processed HttpPostData and HttpHeadersKeys/Values,
435 as they may become invalid when owning TCastleDownload it freed.
436 }
437 WritelnLog('Network', 'Interrupting download in-progress of "%s"', [UriDisplay(Url)]);
438 Thread.Job.OwnsSynchronizationCS := true;
439 Thread.FreeOnTerminate := true;
440 Thread := nil;
441 SynchronizationCS := nil; // do not free it here, let Thread use it, let Thread.Job free it
442 end else
443 FreeAndNil(Thread);
444 {$endif}
445 end;
446
447 FreeAndNil(SynchronizationCS);
448
449 inherited;
450 end;
451
452 procedure TFpHttpClientReader.SynchronizeFromFinishedJob(const Job: TFpHttpClientJob);
453 begin
454 { Looks like FpHttpClient doesn't call DoDataRead on the final data chunk,
455 and thus Job.DownloadedBytes is a bit less than Job.TotalBytes at the end.
456 The actual stream has correct size, so just use this. }
457 DownloadedBytes := Job.Contents.Size; // Job.DownloadedBytes;
458 TotalBytes := Job.TotalBytes;
459 MimeType := Job.MimeType;
460 Contents := Job.Contents;
461 Job.Contents := nil; // do not free our Contents inside TFpHttpClientJob destructor anymore
462 HttpResponseCode := Job.HttpResponseCode;
463 HttpResponseHeaders := Job.HttpResponseHeaders;
464 Job.HttpResponseHeaders := nil; // do not free HttpResponseHeaders inside TFpHttpClientJob destructor
465 FinalUrl := Job.FinalUrl;
466 if Job.Success then
467 begin
468 Status := dsSuccess;
469 WritelnLog('Network', 'Successfully downloaded "%s", MIME type "%s", HTTP response code %d', [
470 Url,
471 MimeType,
472 HttpResponseCode
473 ]);
474 end else
475 begin
476 Status := dsError;
477 ErrorMessage := Job.ErrorMessage;
478 WritelnLog('Network', 'Failed to download "%s", HTTP response code %d', [
479 Url,
480 HttpResponseCode
481 ]);
482 end;
483 end;
484
485 procedure TFpHttpClientReader.Update;
486 begin
487 inherited;
488
489 if Thread <> nil then // Thread may be nil here if not supported on this platform
490 begin
491 if not Thread.Finished then
492 begin
493 SynchronizationCS.Acquire;
494 try
495 DownloadedBytes := Thread.Job.DownloadedBytes;
496 TotalBytes := Thread.Job.TotalBytes;
497 MimeType := Thread.Job.MimeType;
498 finally SynchronizationCS.Release end;
499 end else
500 begin
501 SynchronizeFromFinishedJob(Thread.Job);
502 end;
503 end;
504 end;
505
506 {$endif}
507
508 {$endif HAS_FP_HTTP_CLIENT}