Debian Codegraph @

src/files/castledownload_url_http_indy.inc

raw
1 {%MainUnit castledownload.pas}
2 {
3 Copyright 2023-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 {$if defined(DELPHI) and not defined(CASTLE_DELPHI_NET_HTTP_CLIENT)}
18
19 { Handle downloading http, https URLs using TIdHttp (Indy component).
20
21 See https://docwiki.embarcadero.com/CodeExamples/Sydney/en/HTTP_Get_(Delphi) .
22 See https://github.com/michaliskambi/delphi-http-download for my tests.
23
24 We use this only with Delphi now, though in principle we could make it work
25 with FPC too, as it has Indy too. But we don't need it for FPC, where we use
26 FpHttpClient.
27
28 Since Delphi includes Indy, we don't need to distribute Indy with CGE,
29 and users don't need to worry about getting Indy.
30
31 Most things work:
32
33 - Asynchronous operation (TCastleDownload connecting and downloading doesn't
34 block the main thread),
35 - various HTTP methods (GET, POST with post data...),
36 - getting MIME type from server response,
37 - updating progress (total bytes, downloaded bytes),
38 - aborting download in the middle is smooth.
39
40 - Both http and https work smothly on Windows.
41
42 For https, note that you have to use OpenSSL DLLs.
43 You can get the 2 necessary DLLs from
44
45 - win64: https://github.com/castle-engine/castle-engine/tree/master/tools/build-tool/data/external_libraries/x86_64-win64/openssl
46
47 - win32: https://github.com/castle-engine/castle-engine/tree/master/tools/build-tool/data/external_libraries/i386-win32/openssl
48
49 We advise to compile at least once using CGE editor that will place
50 the DLLs automatically alongside your EXE.
51
52 - The code also work on Delphi/Linux.
53
54 http downloading works (test e.g. http://neverssl.com/ ).
55
56 https unfortunately doesn't work, i.e. it will answer "SSL library not found".
57 It seems Indy requires really old OpenSSL library version (1.0 ?),
58 not available in latest Ubuntu. And it's not even 1.1,
59 so https://gist.github.com/joulgs/c8a85bb462f48ffc2044dd878ecaa786 will not help.
60 The PR to support newer OpenSSL was never merged https://github.com/IndySockets/Indy/pull/299 .
61
62 TODOs:
63
64 - How to have https download working from Delphi/Linux?
65
66 - Support HttpHeadersKeys, HttpHeadersValues, HttpResponseHeaders
67 }
68
69 {$ifdef read_implementation_uses}
70 SyncObjs,
71 IdHttp, IdSSL, IdSSLOpenSSL, IdSSLOpenSSLHeaders, IdCTypes,
72 IdHeaderList, IdTCPConnection, IdComponent,
73 {$endif}
74
75 {$ifdef read_implementation}
76
77 type
78 { Thread that downloads using TIdHttp. }
79 TIndyReaderThread = class(TThread)
80 strict private
81 IdHttp: TIdHttp;
82 MyIOHandler: TIdSSLIOHandlerSocketOpenSSL;
83 { Use with special IO handler to do SSL_set_tlsext_host_name,
84 otherwise accessing sites behind Cloudflare will fail,
85 see https://stackoverflow.com/questions/29875664/eidosslunderlyingcryptoerror-exception }
86 procedure StatusInfoEx(ASender: TObject; const AsslSocket: PSSL;
87 const AWhere, Aret: TIdC_INT; const AType, AMsg: String);
88 procedure Redirect(Sender: TObject;
89 var Dest: string; var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
90 procedure HeadersAvailable(Sender: TObject;
91 AHeaders: TIdHeaderList; var VContinue: Boolean);
92 procedure Work(ASender: TObject;
93 AWorkMode: TWorkMode; AWorkCount: Int64);
94 public
95 { Set these before Execute }
96 HttpPostData, HttpHeadersKeys, HttpHeadersValues: TStrings; //< TODO HttpHeadersKeys, HttpHeadersValues
97 Url: String;
98 HttpMethod: THttpMethod;
99 SynchronizationCS: TCriticalSection;
100
101 { Updated even during downloading, but always using SynchronizationCS. }
102 DownloadedBytes, TotalBytes: Int64;
103 MimeType: String;
104 FinalUrl: String;
105
106 { Once we're finished (Running = false) then
107
108 - Success informs about whether we have dsSuccess or dsError.
109 - HttpResponseCode is the HTTP answer.
110 - Contents contain the response (regardless of Success value).
111 If you take it, then set it to @nil, to avoid freeing it here.
112 - When Success = @false, ErrorMessage is the error message.
113 }
114 Success: Boolean;
115 Contents: TMemoryStream;
116 ErrorMessage: String;
117 HttpResponseCode: Integer;
118 //HttpResponseHeaders: TStrings; //< TODO handle
119
120 constructor Create;
121 destructor Destroy; override;
122 procedure Execute; override;
123 end;
124
125 { TUrlAsynchronousReader descendant that implements http(s) downloading. }
126 TIndyReader = class(TUrlAsynchronousReader)
127 strict private
128 Thread: TIndyReaderThread;
129 SynchronizationCS: TCriticalSection;
130 public
131 procedure Start; override;
132 destructor Destroy; override;
133 procedure Update; override;
134 end;
135
136 { Define TDelphiHttpReader used in castledownload_register.inc.
137 It is an alias to a different class, depending on whether
138 CASTLE_DELPHI_NET_HTTP_CLIENT was defined. }
139 TDelphiHttpReader = TIndyReader;
140
141 { TIndyReaderThread --------------------------------------------------- }
142
143 constructor TIndyReaderThread.Create;
144 begin
145 inherited Create(true); // create suspended
146 Contents := TMemoryStream.Create;
147 TotalBytes := -1;
148 end;
149
150 procedure TIndyReaderThread.Execute;
151 begin
152 IdHttp := TIdHTTP.Create(nil);
153 try
154 IdHttp.HandleRedirects := true;
155
156 { We need to pass User-Agent to avoid Cloudflare answering with 403 Forbidden.
157 See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
158 about User-Agent. }
159 IdHttp.Request.UserAgent := 'Mozilla/5.0 (compatible; CastleGameEngine/1.0; https://castle-engine.io/manual_network.php)';
160
161 { Use SSL with proper options in case of https protocol.
162 Note that using TIdSSLIOHandlerSocketOpenSSL to unencrypted http
163 also works, but then we rely on OpenSSL library (DDL, SO) being present
164 unnecessarily. }
165 if URIProtocol(Url) = 'https' then
166 begin
167 { Set special IO handler to do SSL_set_tlsext_host_name,
168 otherwise accessing sites behind Cloudflare will fail,
169 see https://stackoverflow.com/questions/29875664/eidosslunderlyingcryptoerror-exception }
170 MyIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHttp);
171 MyIOHandler.OnStatusInfoEx := StatusInfoEx;
172 MyIOHandler.SSLOptions.Method := sslvSSLv23;
173 MyIOHandler.SSLOptions.SSLVersions := [sslvTLSv1_2, sslvTLSv1_1, sslvTLSv1];
174 IdHttp.IOHandler := MyIOHandler;
175 end;
176
177 IdHttp.OnRedirect := Redirect;
178 IdHttp.OnHeadersAvailable := HeadersAvailable;
179 IdHttp.OnWork := Work;
180
181 case HttpMethod of
182 hmGet: IdHttp.Get(Url, Contents);
183 { Note that HttpPostData may be nil, that's OK,
184 TIdCustomHTTP.Post is ready for this case. }
185 hmPost: IdHttp.Post(Url, HttpPostData, Contents);
186 // TODO: We should pass Source stream to put
187 hmPut: IdHttp.Put(Url, nil, Contents);
188 hmDelete: IdHttp.Delete(Url, Contents);
189 hmOptions: IdHttp.Options(Url, Contents);
190 hmHead: IdHttp.Head(Url);
191 {$ifndef COMPILER_CASE_ANALYSIS}
192 else raise EInternalError.Create('HttpMethod=?');
193 {$endif}
194 end;
195
196 HttpResponseCode := IdHttp.ResponseCode;
197
198 Contents.Position := 0; { rewind for easy reading }
199 if HttpResponseCode <> 200 then
200 begin
201 Success := false;
202 ErrorMessage := Format('HTTP request completed with status %d (not 200, so not success)', [
203 HttpResponseCode
204 ]);
205 end else
206 begin
207 Success := true;
208 end;
209 except
210 on E: TObject do
211 begin
212 Success := false;
213 ErrorMessage := Format('Exception when downloading "%s": ', [UriDisplay(Url)]) + ExceptMessage(E);
214 end;
215 end;
216 end;
217
218 destructor TIndyReaderThread.Destroy;
219 begin
220 // We have to free MyIOHandler early, to avoid later exceptions
221 FreeAndNil(MyIOHandler);
222 FreeAndNil(IdHttp);
223 FreeAndNil(Contents);
224 inherited;
225 end;
226
227 procedure TIndyReaderThread.StatusInfoEx(ASender: TObject; const AsslSocket: PSSL;
228 const AWhere, Aret: TIdC_INT; const AType, AMsg: String);
229 begin
230 SSL_set_tlsext_host_name(AsslSocket, IdHttp.Request.Host);
231 end;
232
233 procedure TIndyReaderThread.Redirect(Sender: TObject;
234 var Dest: string; var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
235 begin
236 // TODO: WritelnLog is not safe from thread:
237 WritelnLog('Network', 'Following HTTP redirect to "%s"', [Dest]);
238
239 SynchronizationCS.Acquire;
240 try
241 FinalUrl := Dest;
242 finally SynchronizationCS.Release end;
243 end;
244
245 procedure TIndyReaderThread.HeadersAvailable(Sender: TObject;
246 AHeaders: TIdHeaderList; var VContinue: Boolean);
247 var
248 ContentType, ContentLength: String;
249 ContentLengthInt: Int64;
250 begin
251 ContentType := AHeaders.Values['Content-Type'];
252 if ContentType <> '' then
253 begin
254 SynchronizationCS.Acquire;
255 try
256 MimeType := ContentTypeToMimeType(ContentType);
257 finally SynchronizationCS.Release end;
258 end;
259
260 ContentLength := AHeaders.Values['Content-Length'];
261 if TryStrToInt64(ContentLength, ContentLengthInt) then
262 begin
263 SynchronizationCS.Acquire;
264 try
265 TotalBytes :=ContentLengthInt;
266 finally SynchronizationCS.Release end;
267 end;
268 end;
269
270 procedure TIndyReaderThread.Work(ASender: TObject;
271 AWorkMode: TWorkMode; AWorkCount: Int64);
272 begin
273 SynchronizationCS.Acquire;
274 try
275 DownloadedBytes := AWorkCount;
276 finally SynchronizationCS.Release end;
277
278 // honor thread Terminate call
279 if Terminated then
280 Abort;
281 end;
282
283 { TIndyReader --------------------------------------------------- }
284
285 procedure TIndyReader.Start;
286
287 procedure InitializeThread(const Thread: TIndyReaderThread);
288 begin
289 Thread.Url := Url;
290 Thread.SynchronizationCS := SynchronizationCS;
291 Thread.HttpMethod := HttpMethod;
292 Thread.HttpPostData := HttpPostData;
293 Thread.HttpHeadersKeys := HttpHeadersKeys;
294 Thread.HttpHeadersValues := HttpHeadersValues;
295
296 // set initial values, thread may update them later
297 Thread.FinalUrl := Url; // will be updated on each redirect
298 Thread.MimeType := UriMimeType(Url); // will be updated from HTTP headers
299 end;
300
301 begin
302 inherited;
303 if not CheckNetworkAccess then
304 Exit;
305
306 WritelnLog('Network', 'Downloading "%s"', [UriDisplay(Url)]);
307 SynchronizationCS := TCriticalSection.Create;
308 Thread := TIndyReaderThread.Create;
309 InitializeThread(Thread);
310 Thread.Start;
311 end;
312
313 destructor TIndyReader.Destroy;
314 begin
315 if Thread <> nil then
316 begin
317 Thread.Terminate;
318
319 { Check Thread.Finished only to avoid writing unnecessarily alarming
320 "interrupting download in-progress ..." message,
321 testcase: examples/network/remote_logging/ . }
322 if not Thread.Finished then
323 begin
324 WritelnLog('Network', 'Interrupting download in-progress of "%s"', [UriDisplay(Url)]);
325 Thread.WaitFor;
326 end;
327 FreeAndNil(Thread);
328
329 { Note: Thread.WaitFor can cause short delay when interrupting download.
330 Seems unnoticeable for now, so let it be.
331 See castledownload_url_http_fphttpclient.inc for working but hacky
332 way to avoid this. }
333 end;
334
335 FreeAndNil(SynchronizationCS);
336
337 inherited;
338 end;
339
340 procedure TIndyReader.Update;
341
342 procedure SynchronizeFromFinishedThread;
343 begin
344 DownloadedBytes := Thread.Contents.Size;
345 TotalBytes := Thread.Contents.Size;
346 MimeType := Thread.MimeType;
347 Contents := Thread.Contents;
348 Thread.Contents := nil; // do not free our Contents inside TIndyReaderThread destructor anymore
349 HttpResponseCode := Thread.HttpResponseCode;
350 // TODO
351 //HttpResponseHeaders := Thread.HttpResponseHeaders;
352 //Thread.HttpResponseHeaders := nil; // do not free HttpResponseHeaders inside TIndyReaderThread destructor
353 FinalUrl := Thread.FinalUrl;
354 if Thread.Success then
355 begin
356 Status := dsSuccess;
357 WritelnLog('Network', 'Successfully downloaded "%s", MIME type "%s", HTTP response code %d', [
358 Url,
359 MimeType,
360 HttpResponseCode
361 ]);
362 end else
363 begin
364 Status := dsError;
365 ErrorMessage := Thread.ErrorMessage;
366 WritelnLog('Network', 'Failed to download "%s", HTTP response code %d', [
367 Url,
368 HttpResponseCode
369 ]);
370 end;
371 end;
372
373 begin
374 inherited;
375
376 if not Thread.Finished then
377 begin
378 SynchronizationCS.Acquire;
379 try
380 DownloadedBytes := Thread.DownloadedBytes;
381 TotalBytes := Thread.TotalBytes;
382 MimeType := Thread.MimeType;
383 finally SynchronizationCS.Release end;
384 end else
385 begin
386 SynchronizeFromFinishedThread;
387 end;
388 end;
389
390 {$endif read_implementation}
391
392 {$endif defined(DELPHI) and not defined(CASTLE_DELPHI_NET_HTTP_CLIENT)}