-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathHttpFolderResource.cs
More file actions
1602 lines (1381 loc) · 47.7 KB
/
HttpFolderResource.cs
File metadata and controls
1602 lines (1381 loc) · 47.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Net;
using Waher.Content;
using Waher.Events;
using Waher.Networking.HTTP.HeaderFields;
using Waher.Runtime.Temporary;
using Waher.Script;
using Waher.Runtime.IO;
using Waher.Networking.HTTP.Interfaces;
namespace Waher.Networking.HTTP
{
/// <summary>
/// Options on how to handle domain names provided in the Host header.
/// </summary>
public enum HostDomainOptions
{
/// <summary>
/// Only provide access to files for specified domains.
/// </summary>
OnlySpecifiedDomains,
/// <summary>
/// All specified domains receive the same files.
/// </summary>
SameForAllDomains,
/// <summary>
/// If a subfolder exist for a specified host domain name, that subfolder will be used for the request.
/// </summary>
UseDomainSubfolders
}
/// <summary>
/// Publishes a folder with all its files and subfolders through HTTP GET, with optional support for PUT, PATCH and DELETE.
/// If PUT, PATCH and DELETE are allowed, users (if authenticated) can update the contents of the folder.
/// </summary>
public class HttpFolderResource : HttpAsynchronousResource, IHttpGetMethod,
IHttpGetRangesMethod, IHttpPutMethod, IHttpPutRangesMethod, IHttpPatchMethod,
IHttpPatchRangesMethod, IHttpDeleteMethod, IHttpPostMethod, IFolderResource
{
private const int BufferSize = 32768;
private readonly static Dictionary<string, bool> protectedContentTypes = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, CacheRec> cacheInfo = new Dictionary<string, CacheRec>();
private readonly Dictionary<string, bool> definedDomains = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, string> folders = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
private LinkedList<KeyValuePair<string, string>> defaultResponseHeaders = null;
private Dictionary<string, bool> allowTypeConversionFrom = null;
private readonly HttpAuthenticationScheme[] authenticationSchemes;
private readonly HostDomainOptions domainOptions;
private readonly bool allowPutPatch;
private readonly bool allowDelete;
private readonly bool anonymousGET;
private readonly bool userSessions;
private string folderPath;
/// <summary>
/// Publishes a folder with all its files and subfolders through HTTP GET, with optional support for PUT, PATCH and DELETE.
/// If PUT, PATCH and DELETE are allowed, users (if authenticated) can update the contents of the folder.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="FolderPath">Full path to folder to publish.</param>
/// <param name="AllowPutPatch">If the PUT and PATCH methods should be allowed.</param>
/// <param name="AllowDelete">If the DELETE method should be allowed.</param>
/// <param name="AnonymousGET">If Anonymous GET access is allowed.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpFolderResource(string ResourceName, string FolderPath, bool AllowPutPatch, bool AllowDelete, bool AnonymousGET,
bool UserSessions, params HttpAuthenticationScheme[] AuthenticationSchemes)
: this(ResourceName, FolderPath, AllowPutPatch, AllowDelete, AnonymousGET, UserSessions,
HostDomainOptions.SameForAllDomains, AuthenticationSchemes)
{
}
/// <summary>
/// Publishes a folder with all its files and subfolders through HTTP GET, with optional support for PUT, PATCH and DELETE.
/// If PUT, PATCH and DELETE are allowed, users (if authenticated) can update the contents of the folder.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="FolderPath">Full path to folder to publish.</param>
/// <param name="AllowPutPatch">If the PUT and PATCH methods should be allowed.</param>
/// <param name="AllowDelete">If the DELETE method should be allowed.</param>
/// <param name="AnonymousGET">If Anonymous GET access is allowed.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="DomainOptions">Options on how to handle the Host header.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpFolderResource(string ResourceName, string FolderPath, bool AllowPutPatch, bool AllowDelete, bool AnonymousGET,
bool UserSessions, HostDomainOptions DomainOptions, params HttpAuthenticationScheme[] AuthenticationSchemes)
: this(ResourceName, FolderPath, AllowPutPatch, AllowDelete, AnonymousGET, UserSessions,
DomainOptions, Array.Empty<string>(), AuthenticationSchemes)
{
}
/// <summary>
/// Publishes a folder with all its files and subfolders through HTTP GET, with optional support for PUT, PATCH and DELETE.
/// If PUT, PATCH and DELETE are allowed, users (if authenticated) can update the contents of the folder.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="FolderPath">Full path to folder to publish.</param>
/// <param name="AllowPutPatch">If the PUT and PATCH methods should be allowed.</param>
/// <param name="AllowDelete">If the DELETE method should be allowed.</param>
/// <param name="AnonymousGET">If Anonymous GET access is allowed.</param>
/// <param name="UserSessions">If the resource uses user sessions.</param>
/// <param name="DomainOptions">Options on how to handle the Host header.</param>
/// <param name="DomainNames">Pre-defined host names.</param>
/// <param name="AuthenticationSchemes">Any authentication schemes used to authenticate users before access is granted.</param>
public HttpFolderResource(string ResourceName, string FolderPath, bool AllowPutPatch, bool AllowDelete, bool AnonymousGET,
bool UserSessions, HostDomainOptions DomainOptions, string[] DomainNames, params HttpAuthenticationScheme[] AuthenticationSchemes)
: base(ResourceName)
{
this.authenticationSchemes = AuthenticationSchemes;
this.allowPutPatch = AllowPutPatch;
this.allowDelete = AllowDelete;
this.anonymousGET = AnonymousGET;
this.userSessions = UserSessions;
this.domainOptions = DomainOptions;
foreach (string DomainName in DomainNames)
this.definedDomains[DomainName] = true;
this.FolderPath = FolderPath;
}
/// <summary>
/// Protects a content type, so that it cannot be retrieved in raw format by external parties through any folder resources.
/// </summary>
/// <param name="ContentType">Content type to protect.</param>
public static void ProtectContentType(string ContentType)
{
lock (protectedContentTypes)
{
protectedContentTypes[ContentType] = true;
}
}
/// <summary>
/// Checks if a Content-Type is protected.
/// </summary>
/// <param name="ContentType">Content-Type to check.</param>
/// <returns>if the content type is protected.</returns>
public static bool IsProtected(string ContentType)
{
lock (protectedContentTypes)
{
return protectedContentTypes.TryGetValue(ContentType, out bool Protected) && Protected;
}
}
/// <summary>
/// Adds a default HTTP Response header that will be returned in responses for resources in the folder.
/// </summary>
/// <param name="Key">Header key.</param>
/// <param name="Value">Header value.</param>
public void AddDefaultResponseHeader(string Key, string Value)
{
if (this.defaultResponseHeaders is null)
this.defaultResponseHeaders = new LinkedList<KeyValuePair<string, string>>();
this.defaultResponseHeaders.AddLast(new KeyValuePair<string, string>(Key, Value));
}
/// <summary>
/// Folder path.
/// </summary>
public string FolderPath
{
get => this.folderPath;
set
{
string s = value;
int c = s.Length;
if (c > 0 && (s[c - 1] == Path.DirectorySeparatorChar || s[c - 1] == '/' || s[c - 1] == '\\'))
s = s.Substring(0, c - 1);
this.folderPath = s;
}
}
/// <summary>
/// If the resource handles sub-paths.
/// </summary>
public override bool HandlesSubPaths => true;
/// <summary>
/// If the resource uses user sessions.
/// </summary>
public override bool UserSessions => this.userSessions;
/// <summary>
/// If the GET method is allowed.
/// </summary>
public bool AllowsGET => true;
/// <summary>
/// If the PUT method is allowed.
/// </summary>
public bool AllowsPUT => this.allowPutPatch;
/// <summary>
/// If the PATCH method is allowed.
/// </summary>
public bool AllowsPATCH => this.allowPutPatch;
/// <summary>
/// If the DELETE method is allowed.
/// </summary>
public bool AllowsDELETE => this.allowDelete;
/// <summary>
/// If the POST method is allowed.
/// </summary>
public bool AllowsPOST => this.userSessions;
/// <summary>
/// Any authentication schemes used to authenticate users before access is granted to the corresponding resource.
/// </summary>
/// <param name="Request">Current request</param>
public override HttpAuthenticationScheme[] GetAuthenticationSchemes(HttpRequest Request)
{
string s;
if (this.anonymousGET && ((s = Request.Header.Method) == "GET" || s == "HEAD" || s == "OPTIONS"))
return null;
else
return this.authenticationSchemes;
}
/// <summary>
/// Executes the OPTIONS method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public override Task OPTIONS(HttpRequest Request, HttpResponse Response)
{
this.SetDefaultResponseHeaders(Response);
return base.OPTIONS(Request, Response);
}
/// <summary>
/// Validates the request itself. This method is called prior to processing the request, to see if it is valid in the context of the resource
/// or not. If not, corresponding HTTP Exceptions should be thrown. Implementing validation checks in this method, instead of the corresponding
/// execution method, allows the resource to respond correctly to requests using the "Expect: 100-continue" header.
/// </summary>
/// <param name="Request">Request to validate.</param>
public override void Validate(HttpRequest Request)
{
base.Validate(Request);
HttpRequestHeader Header = Request.Header;
DateTimeOffset? Limit;
if (Header.IfMatch is null && !(Header.IfUnmodifiedSince is null) && (Limit = Header.IfUnmodifiedSince.Timestamp).HasValue)
{
string FullPath = this.GetFullPath(Request, true, true, out bool Exists);
if (Exists)
{
DateTime LastModified = File.GetLastWriteTimeUtc(FullPath);
if (GreaterOrEqual(LastModified, Limit.Value.ToUniversalTime()))
throw new NotModifiedException();
}
}
switch (Request.Header.Method)
{
case "PUT":
case "PATCH":
if (!this.allowPutPatch)
throw new MethodNotAllowedException(this.AllowedMethods, Request);
break;
case "DELETE":
if (!this.allowDelete)
throw new MethodNotAllowedException(this.AllowedMethods, Request);
break;
}
}
/// <summary>
/// Checks a string to see if it contains invalid file characters.
/// </summary>
/// <param name="s">String to check.</param>
/// <param name="PermitFolderSeparator">If folder separator characters are permitted.</param>
/// <param name="PermitIpAddress">If IP Addresses are permitted.</param>
/// <returns>If invalid characters are found in the string.</returns>
public static bool ContainsInvalidFileCharacters(string s, bool PermitFolderSeparator, bool PermitIpAddress)
{
if (string.IsNullOrEmpty(s))
return false;
bool PrevPeriod = false;
foreach (char ch in s)
{
switch (ch)
{
case '/':
case '\\':
if (!PermitFolderSeparator)
return true;
PrevPeriod = false;
break;
case ':':
if (!PermitIpAddress || !IPAddress.TryParse(s, out _))
return true;
PrevPeriod = false;
break;
case '|':
case '<':
case '>':
case '?':
case '"':
case '*':
case '\x00':
case '\x01':
case '\x02':
case '\x03':
case '\x04':
case '\x05':
case '\x06':
case '\x07':
case '\x08':
case '\x09':
case '\x0a':
case '\x0b':
case '\x0c':
case '\x0d':
case '\x0e':
case '\x0f':
case '\x10':
case '\x11':
case '\x12':
case '\x13':
case '\x14':
case '\x15':
case '\x16':
case '\x17':
case '\x18':
case '\x19':
case '\x1a':
case '\x1b':
case '\x1c':
case '\x1d':
case '\x1e':
case '\x1f':
return true;
case '.':
if (PrevPeriod)
return true;
PrevPeriod = true;
break;
default:
PrevPeriod = false;
break;
}
}
return false;
}
/// <summary>
/// Gets the full path of a resource in the folder.
/// </summary>
/// <param name="Request">HTTP Request object.</param>
/// <param name="ForbiddenExceptions">If forbidden exceptions can be thrown, if irregularities are found.</param>
/// <param name="MustExist">If file must exist.</param>
/// <param name="Found">If file name is found.</param>
/// <returns>Full path, if found.</returns>
internal string GetFullPath(HttpRequest Request, bool ForbiddenExceptions, bool MustExist, out bool Found)
{
string SubPath = Request.SubPath;
HttpRequestHeader Header = Request?.Header;
string s = WebUtility.UrlDecode(SubPath).Replace('/', Path.DirectorySeparatorChar);
string s2, s3;
string ContentType;
int i;
if (ContainsInvalidFileCharacters(s, true, false))
{
if (ForbiddenExceptions)
throw new ForbiddenException(Request, "Path control characters not permitted in resource name.");
else
{
Found = false;
return null;
}
}
if (this.domainOptions != HostDomainOptions.SameForAllDomains)
{
string Host = Header?.Host?.Value;
string Folder;
if (Host is null)
Host = string.Empty;
else
{
Host = Host.RemovePortNumber();
if (ContainsInvalidFileCharacters(Host, false, true))
{
if (ForbiddenExceptions)
throw new ForbiddenException(Request, "Path control characters not permitted in Host header.");
else
{
Found = false;
return null;
}
}
}
if (this.domainOptions == HostDomainOptions.OnlySpecifiedDomains)
{
lock (this.definedDomains)
{
if (!this.definedDomains.ContainsKey(Host))
{
if (ForbiddenExceptions)
throw new ForbiddenException(Request, "Access to this folder is not permitted on this domain.");
else
{
Found = false;
return null;
}
}
}
Folder = this.folderPath;
}
else
Folder = this.GetRootHostFolder(Host);
if (Folder.EndsWith(Path.DirectorySeparatorChar) && s.StartsWith(Path.DirectorySeparatorChar))
s2 = Folder + s.Substring(1);
else
s2 = Folder + s;
if (Found = File.Exists(s2))
return s2;
i = s2.LastIndexOf('.');
if (i > 0 &&
File.Exists(s3 = s2.Substring(0, i)) &&
InternetContent.TryGetContentType(s2.Substring(i + 1), out ContentType) &&
(Header?.Accept?.IsAcceptable(ContentType) ?? true))
{
if (!(Header is null))
Header.Accept = new HttpFieldAccept("Accept", ContentType);
Found = true;
return s3;
}
}
s2 = this.folderPath + s;
Found = !MustExist || File.Exists(s2);
if (Found)
return s2;
i = s2.LastIndexOf('.');
if (i > 0 &&
File.Exists(s3 = s2.Substring(0, i)) &&
InternetContent.TryGetContentType(s2.Substring(i + 1), out ContentType) &&
(Header?.Accept?.IsAcceptable(ContentType) ?? true))
{
if (!(Header is null))
Header.Accept = new HttpFieldAccept("Accept", ContentType);
Found = true;
return s3;
}
return s2;
}
private string GetRootHostFolder(string Host)
{
lock (this.folders)
{
if (this.folders.TryGetValue(Host, out string Folder))
return Folder;
Folder = this.folderPath + Path.DirectorySeparatorChar + Host;
if (Directory.Exists(Folder))
{
this.folders[Host] = Folder;
return Folder;
}
if (Host.StartsWith("www.", StringComparison.CurrentCultureIgnoreCase))
{
Folder = this.folderPath + Path.DirectorySeparatorChar + Host.Substring(4);
if (Directory.Exists(Folder))
{
this.folders[Host] = Folder;
return Folder;
}
}
int i = Host.IndexOf('.');
if (i > 0)
{
Folder = this.folderPath + Path.DirectorySeparatorChar + Host.Substring(0, i);
if (Directory.Exists(Folder))
{
this.folders[Host] = Folder;
return Folder;
}
}
Folder = this.folderPath;
this.folders[Host] = Folder;
return Folder;
}
}
private class CacheRec
{
public DateTime LastModified;
public string ETag;
public bool IsDynamic;
}
/// <summary>
/// Executes the GET method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public async Task GET(HttpRequest Request, HttpResponse Response)
{
string FullPath = this.GetFullPath(Request, true, true, out bool Exists);
if (Exists)
{
DateTime LastModified = File.GetLastWriteTimeUtc(FullPath);
CacheRec Rec;
Rec = this.CheckCacheHeaders(FullPath, LastModified, Request);
if (Rec is null)
{
await Response.SendResponse(new NotModifiedException());
return;
}
string ContentType = InternetContent.GetContentType(Path.GetExtension(FullPath));
AcceptableResponse AcceptableResponse = await this.CheckAcceptable(Request, Response,
ContentType, FullPath, Request.Header.Resource, LastModified);
if (AcceptableResponse is null || Response.ResponseSent)
return;
Rec.IsDynamic = AcceptableResponse.Dynamic;
await SendResponse(AcceptableResponse.Stream, FullPath,
AcceptableResponse.ContentType, Rec.IsDynamic, Rec.ETag,
AcceptableResponse.LastModified, AcceptableResponse.LastModifiedUpdated,
Response, Request, this.defaultResponseHeaders);
}
else
await this.RaiseFileNotFound(FullPath, Request, Response);
}
private async Task RaiseFileNotFound(string FullPath, HttpRequest Request, HttpResponse Response)
{
NotFoundException ex = new NotFoundException("File not found: " + Request.SubPath);
FileNotFoundEventArgs e = new FileNotFoundEventArgs(ex, FullPath, Request, Response);
await this.FileNotFound.Raise(this, e, false);
ex = e.Exception;
if (ex is null)
return; // Sent asynchronously from event handler.
Log.Warning("File not found.", FullPath, Request.RemoteEndPoint, "FileNotFound");
await Response.SendResponse(ex);
await Response.DisposeAsync();
}
/// <summary>
/// Event raised when a file was requested that could not be found.
/// </summary>
public event EventHandlerAsync<FileNotFoundEventArgs> FileNotFound = null;
/// <summary>
/// Sends a file-based response back to the client.
/// </summary>
/// <param name="FullPath">Full path of file.</param>
/// <param name="ContentType">Content Type.</param>
/// <param name="ETag">ETag of resource.</param>
/// <param name="LastModified">When resource was last modified.</param>
/// <param name="LastModifiedUpdated">If <paramref name="LastModified"/> has
/// been updated during the processing of the resource.</param>
/// <param name="Response">HTTP response object.</param>
public static Task SendResponse(string FullPath, string ContentType, string ETag,
DateTime LastModified, bool LastModifiedUpdated, HttpResponse Response)
{
return SendResponse(null, FullPath, ContentType, false, ETag, LastModified,
LastModifiedUpdated, Response, null, null);
}
/// <summary>
/// Sends a file-based response back to the client.
/// </summary>
/// <param name="FullPath">Full path of file.</param>
/// <param name="ContentType">Content Type.</param>
/// <param name="ETag">ETag of resource.</param>
/// <param name="LastModified">When resource was last modified.</param>
/// <param name="LastModifiedUpdated">If <paramref name="LastModified"/> has
/// been updated during the processing of the resource.</param>
/// <param name="Response">HTTP response object.</param>
/// <param name="Request">HTTP request object.</param>
public static Task SendResponse(string FullPath, string ContentType, string ETag,
DateTime LastModified, bool LastModifiedUpdated, HttpResponse Response,
HttpRequest Request)
{
return SendResponse(null, FullPath, ContentType, false, ETag, LastModified,
LastModifiedUpdated, Response, Request, null);
}
/// <summary>
/// Sets any default response headers registered on the file folder object, to a HTTP Response object.
/// </summary>
/// <param name="Response">HTTP Response.</param>
public void SetDefaultResponseHeaders(HttpResponse Response)
{
SetDefaultResponseHeaders(Response, this.defaultResponseHeaders);
}
private static void SetDefaultResponseHeaders(HttpResponse Response, IEnumerable<KeyValuePair<string, string>> DefaultResponseHeaders)
{
if (!(DefaultResponseHeaders is null))
{
foreach (KeyValuePair<string, string> P in DefaultResponseHeaders)
Response.SetHeader(P.Key, P.Value);
}
}
private static async Task SendResponse(Stream f, string FullPath, string ContentType,
bool IsDynamic, string ETag, DateTime LastModified, bool LastModifiedUpdated,
HttpResponse Response, HttpRequest Request, LinkedList<KeyValuePair<string, string>> DefaultResponseHeaders)
{
ReadProgress Progress = new ReadProgress()
{
Response = Response,
Request = Request,
f = f ?? File.Open(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
Next = null,
Boundary = null,
ContentType = null,
FullPath = FullPath,
SetLastModified = LastModifiedUpdated ? (DateTime?)LastModified : null
};
Progress.BytesLeft = Progress.TotalLength = Progress.f.Length;
Progress.BlockSize = (int)Math.Min(BufferSize, Progress.BytesLeft);
Progress.Buffer = new byte[Progress.BlockSize];
SetDefaultResponseHeaders(Response, DefaultResponseHeaders);
Response.ContentType = ContentType;
Response.ContentLength = Progress.TotalLength;
if (!IsDynamic)
{
Response.SetHeader("ETag", ETag);
Response.SetHeader("Last-Modified", CommonTypes.EncodeRfc822(LastModified));
}
if (Response.OnlyHeader || Progress.TotalLength == 0)
{
await Response.SendResponse();
await Progress.Dispose();
}
else
{
Task _ = Progress.BeginRead();
}
}
private CacheRec CheckCacheHeaders(string FullPath, DateTime LastModified, HttpRequest Request)
{
string CacheKey = FullPath.ToLower();
HttpRequestHeader Header = Request.Header;
CacheRec Rec;
DateTimeOffset? Limit;
lock (this.cacheInfo)
{
if (this.cacheInfo.TryGetValue(CacheKey, out Rec))
{
if (Rec.LastModified != LastModified)
{
this.cacheInfo.Remove(CacheKey);
Rec = null;
}
}
}
if (Rec is null)
{
Rec = new CacheRec()
{
LastModified = LastModified,
IsDynamic = false
};
using (FileStream fs = File.Open(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Rec.ETag = this.ComputeETag(fs);
}
lock (this.cacheInfo)
{
this.cacheInfo[CacheKey] = Rec;
}
}
if (!Rec.IsDynamic)
{
if (!(Header.IfNoneMatch is null))
{
if (Header.IfNoneMatch.Value == Rec.ETag)
return null;
}
else if (!(Header.IfModifiedSince is null))
{
if ((Limit = Header.IfModifiedSince.Timestamp).HasValue &&
LessOrEqual(LastModified, Limit.Value.ToUniversalTime()))
{
return null;
}
}
}
return Rec;
}
/// <summary>
/// Computes <paramref name="LastModified"/><=<paramref name="Limit"/>. The normal <= operator behaved strangely, and
/// did not get the equality part of the operation correct, perhaps due to round-off errors. This method only compares
/// properties own to second level, and assumes all time-zones to be GMT, and avoids comparing time zones.
/// </summary>
/// <param name="LastModified">DateTime value.</param>
/// <param name="Limit">DateTimeOffset value.</param>
/// <returns>If <paramref name="LastModified"/><=<paramref name="Limit"/>.</returns>
public static bool LessOrEqual(DateTime LastModified, DateTimeOffset Limit)
{
int i;
i = LastModified.Year - Limit.Year;
if (i != 0)
return i < 0;
i = LastModified.Month - Limit.Month;
if (i != 0)
return i < 0;
i = LastModified.Day - Limit.Day;
if (i != 0)
return i < 0;
i = LastModified.Hour - Limit.Hour;
if (i != 0)
return i < 0;
i = LastModified.Minute - Limit.Minute;
if (i != 0)
return i < 0;
i = LastModified.Second - Limit.Second;
return i <= 0;
}
/// <summary>
/// Computes <paramref name="LastModified"/>>=<paramref name="Limit"/>. The normal >= operator behaved strangely, and
/// did not get the equality part of the operation correct, perhaps due to round-off errors. This method only compares
/// properties own to second level, and assumes all time-zones to be GMT, and avoids comparing time zones.
/// </summary>
/// <param name="LastModified">DateTime value.</param>
/// <param name="Limit">DateTimeOffset value.</param>
/// <returns>If <paramref name="LastModified"/>>=<paramref name="Limit"/>.</returns>
public static bool GreaterOrEqual(DateTime LastModified, DateTimeOffset Limit)
{
int i;
i = LastModified.Year - Limit.Year;
if (i != 0)
return i > 0;
i = LastModified.Month - Limit.Month;
if (i != 0)
return i > 0;
i = LastModified.Day - Limit.Day;
if (i != 0)
return i > 0;
i = LastModified.Hour - Limit.Hour;
if (i != 0)
return i > 0;
i = LastModified.Minute - Limit.Minute;
if (i != 0)
return i > 0;
i = LastModified.Second - Limit.Second;
return i >= 0;
}
private class AcceptableResponse : ICodecProgress
{
public ICodecProgress Progress;
public DateTime LastModified;
public Stream Stream;
public string ContentType;
public bool Dynamic;
public bool LastModifiedUpdated = false;
public Task EarlyHint(string Resource, string Relation, params KeyValuePair<string, string>[] AdditionalParameters)
=> this.Progress?.EarlyHint(Resource, Relation, AdditionalParameters) ?? Task.CompletedTask;
public Task HeaderProcessed() => this.Progress?.HeaderProcessed() ?? Task.CompletedTask;
public Task BodyProcessed() => this.Progress?.BodyProcessed() ?? Task.CompletedTask;
public void DependencyTimestamp(DateTime Timestamp)
{
DateTime TP = Timestamp.ToUniversalTime();
if (TP > this.LastModified)
{
this.LastModified = TP;
this.LastModifiedUpdated = true;
}
this.Progress?.DependencyTimestamp(Timestamp);
}
}
private static readonly HttpFieldAccept acceptEverything = new HttpFieldAccept("Accept", "*/*");
private async Task<AcceptableResponse> CheckAcceptable(HttpRequest Request, HttpResponse Response,
string ContentType, string FullPath, string ResourceName, DateTime LastModified)
{
HttpRequestHeader Header = Request.Header;
AcceptableResponse Result = new AcceptableResponse()
{
Progress = Response.Progress,
LastModified = LastModified,
ContentType = ContentType,
Dynamic = false
};
HttpFieldAccept Accept = Header.Accept;
AcceptanceLevel TypeAcceptance;
double Quality;
bool Acceptable;
bool CheckConversion;
if (Accept is null)
{
Accept = acceptEverything;
Acceptable = true;
CheckConversion = IsProtected(ContentType);
Quality = 1;
TypeAcceptance = AcceptanceLevel.Wildcard;
}
else
{
Acceptable = Accept.IsAcceptable(ContentType, out Quality, out TypeAcceptance, null);
CheckConversion = !Acceptable ||
(TypeAcceptance == AcceptanceLevel.Wildcard && IsProtected(ContentType));
}
if (!(this.allowTypeConversionFrom is null) &&
(!this.allowTypeConversionFrom.TryGetValue(ContentType, out bool Allowed) ||
!Allowed))
{
CheckConversion = false;
}
if (CheckConversion)
{
IContentConverter Converter = null;
string NewContentType = null;
foreach (AcceptRecord AcceptRecord in Accept.Records)
{
NewContentType = AcceptRecord.Item;
if (NewContentType.EndsWith("/*"))
{
NewContentType = null;
continue;
}
if (InternetContent.CanConvert(ContentType, NewContentType, out Converter))
{
Acceptable = true;
break;
}
}
if (Converter is null)
{
IContentConverter[] Converters = InternetContent.GetConverters(ContentType);
if (!(Converters is null))
{
string BestContentType = null;
double BestQuality = 0;
IContentConverter Best = null;
bool Found;
foreach (IContentConverter Converter2 in Converters)
{
Found = false;
foreach (string FromContentType in Converter2.FromContentTypes)
{
if (ContentType == FromContentType)
{
Found = true;
break;
}
}
if (!Found)
continue;
foreach (string ToContentType in Converter2.ToContentTypes)
{
if (Accept.IsAcceptable(ToContentType, out double Quality2) && Quality > BestQuality)
{
BestContentType = ToContentType;
BestQuality = Quality;
Best = Converter2;
}
else if (BestQuality == 0 && ToContentType == "*")
{
BestContentType = ContentType;
BestQuality = double.Epsilon;
Best = Converter2;
}
}
}
if (!(Best is null) && (!Acceptable || BestQuality >= Quality))
{
Acceptable = true;
Converter = Best;
NewContentType = BestContentType;
}
}
}
if (Acceptable && !(Converter is null))
{
Stream f2 = null;
Stream f = File.Open(FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
bool Ok = false;
try
{
f2 = f.Length < HttpClientConnection.MaxInmemoryMessageSize ? (Stream)new MemoryStream() : new TemporaryFile();
List<string> Alternatives = null;
string[] Range = Converter.ToContentTypes;
bool All = Range.Length == 1 && Range[0] == "*";
foreach (AcceptRecord AcceptRecord in Accept.Records)
{
if (AcceptRecord.Item.EndsWith("/*") || AcceptRecord.Item == NewContentType)
continue;
if (All || Array.IndexOf(Range, AcceptRecord.Item) >= 0)
{
if (Alternatives is null)
Alternatives = new List<string>();
Alternatives.Add(AcceptRecord.Item);
}
}
ConversionState State = new ConversionState(ContentType, f, FullPath, ResourceName,
Request.Header.GetURL(false, false), NewContentType, f2, Request.Session, Result,
Request.Server, Request.TryGetLocalResourceFileName, Alternatives?.ToArray());
if (await Converter.ConvertAsync(State))
{