-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathHttpServer.cs
More file actions
2521 lines (2208 loc) · 81.2 KB
/
HttpServer.cs
File metadata and controls
2521 lines (2208 loc) · 81.2 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.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Networking;
using Windows.Networking.Connectivity;
using Windows.Networking.Sockets;
#else
using System.Security.Authentication;
using System.Net.NetworkInformation;
using System.Security.Cryptography.X509Certificates;
#endif
using Waher.Content;
using Waher.Events;
using Waher.Events.Statistics;
using Waher.Networking.HTTP.HeaderFields;
using Waher.Networking.Sniffers;
using Waher.Networking.HTTP.TransferEncodings;
using Waher.Networking.HTTP.Vanity;
using Waher.Runtime.Cache;
using Waher.Security;
using Waher.Networking.HTTP.HTTP2;
using Waher.Runtime.IO;
using Waher.Networking.HTTP.Interfaces;
namespace Waher.Networking.HTTP
{
/// <summary>
/// Implements an HTTP server.
/// </summary>
public class HttpServer : CommunicationLayer, IDisposableAsync, IResourceMap
#if !WINDOWS_UWP
, ITlsCertificateEndpoint
#endif
{
/// <summary>
/// Default HTTP Port (80).
/// </summary>
public const int DefaultHttpPort = 80;
/// <summary>
/// Default HTTPS port (443).
/// </summary>
public const int DefaultHttpsPort = 443;
/// <summary>
/// Default Connection backlog (10).
/// </summary>
public const int DefaultConnectionBacklog = BinaryTcpServer.DefaultC2SConnectionBacklog;
/// <summary>
/// Default buffer size (16384).
/// </summary>
public const int DefaultBufferSize = 16384;
#if WINDOWS_UWP
private LinkedList<KeyValuePair<StreamSocketListener, Guid>> listeners = new LinkedList<KeyValuePair<StreamSocketListener, Guid>>();
#else
private LinkedList<KeyValuePair<TcpListener, bool>> listeners = new LinkedList<KeyValuePair<TcpListener, bool>>();
private X509Certificate serverCertificate;
private Dictionary<int, KeyValuePair<ClientCertificates, bool>> portSpecificMTlsSettings;
private ClientCertificates clientCertificates = ClientCertificates.NotUsed;
private bool trustClientCertificates = false;
private bool clientCertificateSettingsLocked = false;
#endif
private readonly Dictionary<string, HttpResource> resources = new Dictionary<string, HttpResource>(StringComparer.CurrentCultureIgnoreCase);
private readonly Dictionary<string, HttpReverseProxyResource> domainProxies = new Dictionary<string, HttpReverseProxyResource>(StringComparer.CurrentCultureIgnoreCase);
private TimeSpan sessionTimeout = TimeSpan.FromMinutes(20);
private TimeSpan requestTimeout = TimeSpan.FromMinutes(2);
private Cache<HttpRequest, RequestInfo> currentRequests;
private Cache<string, SessionVariables> sessions;
private string resourceOverride = null;
private Regex resourceOverrideFilter = null;
private readonly object statSynch = new object();
private Dictionary<string, Statistic> callsPerMethod = new Dictionary<string, Statistic>();
private Dictionary<string, Statistic> callsPerUserAgent = new Dictionary<string, Statistic>();
private Dictionary<string, Statistic> callsPerFrom = new Dictionary<string, Statistic>();
private Dictionary<string, Statistic> callsPerResource = new Dictionary<string, Statistic>();
private readonly Dictionary<Guid, HttpClientConnection> connections = new Dictionary<Guid, HttpClientConnection>();
private readonly Dictionary<int, bool> failedPorts = new Dictionary<int, bool>();
private readonly VanityResources vanityResources = new VanityResources();
private ILoginAuditor loginAuditor = null;
private IWebApplicationFirewall webApplicationFirewall = null;
private DateTime lastStat = DateTime.MinValue;
private string eTagSalt = string.Empty;
private string name = typeof(HttpServer).Namespace;
private int[] httpPorts;
private long nrBytesRx = 0;
private long nrBytesTx = 0;
private long nrCalls = 0;
#if !WINDOWS_UWP
private int[] httpsPorts;
private int? upgradePort = null;
#endif
private bool disposed = false;
private bool adaptToNetworkChanges;
private bool hasProxyDomains = false;
// HTTP/2 default settings
private int http2InitialStreamWindowSize = ConnectionSettings.DefaultHttp2InitialConnectionWindowSize;
private int http2InitialConnectionWindowSize = ConnectionSettings.DefaultHttp2InitialConnectionWindowSize;
private int http2MaxFrameSize = ConnectionSettings.DefaultHttp2MaxFrameSize;
private int http2MaxConcurrentStreams = ConnectionSettings.DefaultHttp2MaxConcurrentStreams;
private int http2HeaderTableSize = ConnectionSettings.DefaultHttp2HeaderTableSize;
private bool http2EnablePush = ConnectionSettings.DefaultHttp2EnablePush;
private bool http2Enabled = true;
private bool http2SettingsLocked = false;
private bool http2NoRfc7540Priorities = false;
private bool http2Profiling = false;
#region Constructors
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(params ISniffer[] Sniffers)
#if WINDOWS_UWP
: this(new int[] { DefaultHttpPort }, false, Sniffers)
#else
: this(new int[] { DefaultHttpPort }, null, null, false, Sniffers)
#endif
{
}
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPort">HTTP Port</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int HttpPort, params ISniffer[] Sniffers)
#if WINDOWS_UWP
: this(new int[] { HttpPort }, false, Sniffers)
#else
: this(new int[] { HttpPort }, null, null, false, Sniffers)
#endif
{
}
#if !WINDOWS_UWP
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="ServerCertificate">Server certificate identifying the domain of the server.</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(X509Certificate ServerCertificate, params ISniffer[] Sniffers)
: this(new int[] { DefaultHttpPort }, new int[] { DefaultHttpsPort }, ServerCertificate, false, Sniffers)
{
}
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPort">HTTP Port</param>
/// <param name="HttpsPort">HTTPS Port</param>
/// <param name="ServerCertificate">Server certificate identifying the domain of the server.</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int HttpPort, int HttpsPort, X509Certificate ServerCertificate, params ISniffer[] Sniffers)
: this(new int[] { HttpPort }, new int[] { HttpsPort }, ServerCertificate, false, Sniffers)
{
}
#endif
#if WINDOWS_UWP
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPorts">HTTP Ports</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int[] HttpPorts, params ISniffer[] Sniffers)
: this(HttpPorts, false, Sniffers)
{
}
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPorts">HTTP Ports</param>
/// <param name="AdaptToNetworkChanges">If the server is to adapt to network changes automatically.</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int[] HttpPorts, bool AdaptToNetworkChanges, params ISniffer[] Sniffers)
#else
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPorts">HTTP Ports</param>
/// <param name="Sniffers">Sniffers.</param>
/// <param name="HttpsPorts">HTTPS Ports</param>
/// <param name="ServerCertificate">Server certificate identifying the domain of the server.</param>
public HttpServer(int[] HttpPorts, int[] HttpsPorts, X509Certificate ServerCertificate, params ISniffer[] Sniffers)
: this(HttpPorts, HttpsPorts, ServerCertificate, false, Sniffers)
{
}
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPorts">HTTP Ports</param>
/// <param name="HttpsPorts">HTTPS Ports</param>
/// <param name="ServerCertificate">Server certificate identifying the domain of the server.</param>
/// <param name="AdaptToNetworkChanges">If the server is to adapt to network changes automatically.</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int[] HttpPorts, int[] HttpsPorts, X509Certificate ServerCertificate, bool AdaptToNetworkChanges,
params ISniffer[] Sniffers)
: this(HttpPorts, HttpsPorts, ServerCertificate, AdaptToNetworkChanges, ClientCertificates.NotUsed, false, null, false, Sniffers)
{
}
/// <summary>
/// Implements an HTTPS server.
/// </summary>
/// <param name="HttpPorts">HTTP Ports</param>
/// <param name="HttpsPorts">HTTPS Ports</param>
/// <param name="ServerCertificate">Server certificate identifying the domain of the server.</param>
/// <param name="AdaptToNetworkChanges">If the server is to adapt to network changes automatically.</param>
/// <param name="ClientCertificates">If client certificates are not used, optional or required.</param>
/// <param name="TrustClientCertificates">If client certificates should be trusted, even if they do not validate.</param>
/// <param name="PortSpecificSettings">Port-specific mTLS settings.</param>
/// <param name="LockSettings">If client certificate settings should be locked.</param>
/// <param name="Sniffers">Sniffers.</param>
public HttpServer(int[] HttpPorts, int[] HttpsPorts, X509Certificate ServerCertificate, bool AdaptToNetworkChanges,
ClientCertificates ClientCertificates, bool TrustClientCertificates,
Dictionary<int, KeyValuePair<ClientCertificates, bool>> PortSpecificSettings, bool LockSettings,
params ISniffer[] Sniffers)
#endif
: base(false, Sniffers)
{
#if !WINDOWS_UWP
this.serverCertificate = ServerCertificate;
this.clientCertificates = ClientCertificates;
this.trustClientCertificates = TrustClientCertificates;
this.portSpecificMTlsSettings = PortSpecificSettings;
this.clientCertificateSettingsLocked = LockSettings;
#endif
this.sessions = new Cache<string, SessionVariables>(int.MaxValue, TimeSpan.MaxValue, this.sessionTimeout, true);
this.sessions.Removed += this.Sessions_Removed;
this.currentRequests = new Cache<HttpRequest, RequestInfo>(int.MaxValue, TimeSpan.MaxValue, this.requestTimeout, true);
this.currentRequests.Removed += this.CurrentRequests_Removed;
this.lastStat = DateTime.UtcNow;
this.adaptToNetworkChanges = AdaptToNetworkChanges;
this.httpPorts = Array.Empty<int>();
#if WINDOWS_UWP
Task _ = this.AddHttpPorts(HttpPorts);
if (this.adaptToNetworkChanges)
NetworkInformation.NetworkStatusChanged += this.NetworkChange_NetworkAddressChanged;
#else
this.AddHttpPorts(HttpPorts);
this.httpsPorts = Array.Empty<int>();
this.AddHttpsPorts(HttpsPorts);
if (this.adaptToNetworkChanges)
NetworkChange.NetworkAddressChanged += this.NetworkChange_NetworkAddressChanged;
#endif
}
#if WINDOWS_UWP
private void NetworkChange_NetworkAddressChanged(object sender)
{
Task _ = this.NetworkChanged();
}
/// <summary>
/// Adapts the server to changes in the network. This method can be called automatically by calling the constructor accordingly.
/// </summary>
public async Task NetworkChanged()
#else
private void NetworkChange_NetworkAddressChanged(object Sender, EventArgs e)
{
this.NetworkChanged();
}
/// <summary>
/// Adapts the server to changes in the network. This method can be called automatically by calling the constructor accordingly.
/// </summary>
public async void NetworkChanged()
#endif
{
try
{
int[] HttpPorts = this.httpPorts;
this.httpPorts = Array.Empty<int>();
#if WINDOWS_UWP
LinkedList<KeyValuePair<StreamSocketListener, Guid>> Listeners = this.listeners;
this.listeners = new LinkedList<KeyValuePair<StreamSocketListener, Guid>>();
foreach (KeyValuePair<StreamSocketListener, Guid> P in Listeners)
{
try
{
P.Key.Dispose();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
await this.AddHttpPorts(HttpPorts, Listeners);
#else
int[] HttpsPorts = this.httpsPorts;
this.httpsPorts = Array.Empty<int>();
LinkedList<KeyValuePair<TcpListener, bool>> Listeners = this.listeners;
this.listeners = new LinkedList<KeyValuePair<TcpListener, bool>>();
foreach (KeyValuePair<TcpListener, bool> P in Listeners)
{
try
{
P.Key.Stop();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
this.AddHttpPorts(HttpPorts, Listeners);
this.AddHttpsPorts(HttpsPorts, Listeners);
#endif
await this.OnNetworkChanged.Raise(this, EventArgs.Empty);
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
/// <summary>
/// Event raised when the network has been changed.
/// </summary>
public event EventHandlerAsync OnNetworkChanged = null;
/// <summary>
/// If the server is to adapt to network changes automatically.
/// </summary>
public bool AdaptToNetworkChanges
{
get => this.adaptToNetworkChanges;
set
{
if (value != this.adaptToNetworkChanges)
{
this.adaptToNetworkChanges = value;
if (value)
{
#if WINDOWS_UWP
NetworkInformation.NetworkStatusChanged += this.NetworkChange_NetworkAddressChanged;
#else
NetworkChange.NetworkAddressChanged += this.NetworkChange_NetworkAddressChanged;
#endif
}
else
{
#if WINDOWS_UWP
NetworkInformation.NetworkStatusChanged -= this.NetworkChange_NetworkAddressChanged;
#else
NetworkChange.NetworkAddressChanged -= this.NetworkChange_NetworkAddressChanged;
#endif
}
}
}
}
#if WINDOWS_UWP
/// <summary>
/// Opens additional HTTP ports, if not already open.
/// </summary>
/// <param name="HttpPorts">HTTP ports</param>
public async Task AddHttpPorts(params int[] HttpPorts)
{
await this.AddHttpPorts(HttpPorts, null);
}
#else
/// <summary>
/// Opens additional HTTP ports, if not already open.
/// </summary>
/// <param name="HttpPorts">HTTP ports</param>33
public void AddHttpPorts(params int[] HttpPorts)
{
this.AddHttpPorts(HttpPorts, null);
}
#endif
#if WINDOWS_UWP
private async Task AddHttpPorts(int[] HttpPorts, LinkedList<KeyValuePair<StreamSocketListener, Guid>> Listeners)
#else
private void AddHttpPorts(int[] HttpPorts, LinkedList<KeyValuePair<TcpListener, bool>> Listeners)
#endif
{
if (HttpPorts is null)
return;
try
{
#if WINDOWS_UWP
StreamSocketListener Listener;
foreach (ConnectionProfile Profile in NetworkInformation.GetConnectionProfiles())
{
if (Profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.None)
continue;
foreach (int HttpPort in HttpPorts)
{
if (Array.IndexOf(this.httpPorts, HttpPort) >= 0)
continue;
Listener = null;
LinkedListNode<KeyValuePair<StreamSocketListener, Guid>> Node;
Node = Listeners?.First;
while (!(Node is null))
{
StreamSocketListener L = Node.Value.Key;
Guid AdapterId = Node.Value.Value;
if (AdapterId == Profile.NetworkAdapter.NetworkAdapterId)
{
Listener = L;
Listeners.Remove(Node);
break;
}
Node = Node.Next;
}
if (Listener is null)
{
try
{
Listener = new StreamSocketListener();
await Listener.BindServiceNameAsync(HttpPort.ToString(), SocketProtectionLevel.PlainSocket, Profile.NetworkAdapter);
Listener.ConnectionReceived += this.Listener_ConnectionReceived;
this.listeners.AddLast(new KeyValuePair<StreamSocketListener, Guid>(Listener, Profile.NetworkAdapter.NetworkAdapterId));
}
catch (Exception ex)
{
this.failedPorts[HttpPort] = true;
Log.Exception(ex, Profile.ProfileName);
}
}
else
this.listeners.AddLast(new KeyValuePair<StreamSocketListener, Guid>(Listener, Profile.NetworkAdapter.NetworkAdapterId));
}
}
#else
TcpListener Listener;
foreach (NetworkInterface Interface in NetworkInterface.GetAllNetworkInterfaces())
{
if (Interface.OperationalStatus != OperationalStatus.Up)
continue;
IPInterfaceProperties Properties = Interface.GetIPProperties();
foreach (UnicastIPAddressInformation UnicastAddress in Properties.UnicastAddresses)
{
if ((UnicastAddress.Address.AddressFamily == AddressFamily.InterNetwork && Socket.OSSupportsIPv4) ||
(UnicastAddress.Address.AddressFamily == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6))
{
foreach (int HttpPort in HttpPorts)
{
if (Array.IndexOf(this.httpPorts, HttpPort) >= 0)
continue;
Listener = null;
LinkedListNode<KeyValuePair<TcpListener, bool>> Node;
IPEndPoint DesiredEndpoint = new IPEndPoint(UnicastAddress.Address, HttpPort);
Node = Listeners?.First;
while (!(Node is null))
{
TcpListener L = Node.Value.Key;
bool Tls = Node.Value.Value;
if ((!Tls) && L.LocalEndpoint == DesiredEndpoint)
{
Listener = L;
Listeners.Remove(Node);
break;
}
Node = Node.Next;
}
if (Listener is null)
{
try
{
Listener = new TcpListener(UnicastAddress.Address, HttpPort);
Listener.Start(DefaultConnectionBacklog);
Task T = this.ListenForIncomingConnections(Listener, false, HttpPort, ClientCertificates.NotUsed, false);
this.listeners.AddLast(new KeyValuePair<TcpListener, bool>(Listener, false));
}
catch (SocketException)
{
this.failedPorts[HttpPort] = true;
Log.Error("Unable to open HTTP port for listening.",
new KeyValuePair<string, object>("Address", UnicastAddress.Address.ToString()),
new KeyValuePair<string, object>("Port", HttpPort));
}
catch (Exception ex)
{
this.failedPorts[HttpPort] = true;
Log.Exception(ex, UnicastAddress.Address.ToString() + ":" + HttpPort);
}
}
else
this.listeners.AddLast(new KeyValuePair<TcpListener, bool>(Listener, false));
}
}
}
}
#endif
foreach (int HttpPort in HttpPorts)
{
if (Array.IndexOf(this.httpPorts, HttpPort) < 0)
{
int c = this.httpPorts.Length;
Array.Resize(ref this.httpPorts, c + 1);
this.httpPorts[c] = HttpPort;
}
}
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
#if !WINDOWS_UWP
/// <summary>
/// Opens additional HTTPS ports, if not already open.
/// </summary>
/// <param name="HttpsPorts">HTTP ports</param>
public void AddHttpsPorts(params int[] HttpsPorts)
{
this.AddHttpsPorts(HttpsPorts, null);
}
private void AddHttpsPorts(int[] HttpsPorts, LinkedList<KeyValuePair<TcpListener, bool>> Listeners)
{
if (HttpsPorts is null)
return;
try
{
TcpListener Listener;
foreach (NetworkInterface Interface in NetworkInterface.GetAllNetworkInterfaces())
{
if (Interface.OperationalStatus != OperationalStatus.Up)
continue;
IPInterfaceProperties Properties = Interface.GetIPProperties();
foreach (UnicastIPAddressInformation UnicastAddress in Properties.UnicastAddresses)
{
if ((UnicastAddress.Address.AddressFamily == AddressFamily.InterNetwork && Socket.OSSupportsIPv4) ||
(UnicastAddress.Address.AddressFamily == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6))
{
foreach (int HttpsPort in HttpsPorts)
{
if (Array.IndexOf(this.httpsPorts, HttpsPort) >= 0)
continue;
Listener = null;
LinkedListNode<KeyValuePair<TcpListener, bool>> Node;
IPEndPoint DesiredEndpoint = new IPEndPoint(UnicastAddress.Address, HttpsPort);
Node = Listeners?.First;
while (!(Node is null))
{
TcpListener L = Node.Value.Key;
bool Tls = Node.Value.Value;
if (Tls && L.LocalEndpoint == DesiredEndpoint)
{
Listener = L;
Listeners.Remove(Node);
break;
}
Node = Node.Next;
}
if (Listener is null)
{
try
{
this.GetMTlsSettings(HttpsPort, out ClientCertificates ClientCertificates, out bool TrustCertificates);
Listener = new TcpListener(DesiredEndpoint);
Listener.Start(DefaultConnectionBacklog);
Task T = this.ListenForIncomingConnections(Listener, true, HttpsPort, ClientCertificates, TrustCertificates);
this.listeners.AddLast(new KeyValuePair<TcpListener, bool>(Listener, true));
}
catch (SocketException)
{
this.failedPorts[HttpsPort] = true;
Log.Error("Unable to open HTTPS port for listening.",
new KeyValuePair<string, object>("Address", UnicastAddress.Address.ToString()),
new KeyValuePair<string, object>("Port", HttpsPort));
}
catch (Exception ex)
{
this.failedPorts[HttpsPort] = true;
Log.Exception(ex, UnicastAddress.Address.ToString() + ":" + HttpsPort);
}
}
else
this.listeners.AddLast(new KeyValuePair<TcpListener, bool>(Listener, true));
}
}
}
}
foreach (int HttpsPort in HttpsPorts)
{
if (Array.IndexOf(this.httpsPorts, HttpsPort) < 0)
{
int c = this.httpsPorts.Length;
Array.Resize(ref this.httpsPorts, c + 1);
this.httpsPorts[c] = HttpsPort;
}
}
}
catch (Exception ex)
{
Log.Exception(ex);
}
this.upgradePort = null;
}
#endif
/// <summary>
/// If object has been disposed.
/// </summary>
public bool Disposed => this.disposed;
/// <summary>
/// <see cref="IDisposable.Dispose"/>
/// </summary>
[Obsolete("Use DisposeAsync instead.")]
public void Dispose()
{
this.DisposeAsync().Wait();
}
/// <summary>
/// <see cref="IDisposableAsync.DisposeAsync"/>
/// </summary>
public async Task DisposeAsync()
{
this.disposed = true;
#if WINDOWS_UWP
NetworkInformation.NetworkStatusChanged -= this.NetworkChange_NetworkAddressChanged;
#else
NetworkChange.NetworkAddressChanged -= this.NetworkChange_NetworkAddressChanged;
#endif
if (!(this.listeners is null))
{
#if WINDOWS_UWP
LinkedList<KeyValuePair<StreamSocketListener, Guid>> Listeners = this.listeners;
this.listeners = null;
foreach (KeyValuePair<StreamSocketListener, Guid> Listener in Listeners)
{
try
{
Listener.Key.Dispose();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
#else
LinkedList<KeyValuePair<TcpListener, bool>> Listeners = this.listeners;
this.listeners = null;
foreach (KeyValuePair<TcpListener, bool> Listener in Listeners)
{
try
{
Listener.Key.Stop();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
#endif
}
HttpClientConnection[] Connections = this.GetConnections(true);
foreach (HttpClientConnection Connection in Connections)
{
try
{
await this.Remove(Connection);
}
catch (Exception ex)
{
Log.Exception(ex);
}
try
{
await Connection.DisposeAsync();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
try
{
this.sessions?.Dispose();
this.sessions = null;
}
catch (Exception ex)
{
Log.Exception(ex);
}
try
{
this.currentRequests?.Dispose();
this.currentRequests = null;
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
/// <summary>
/// Ports successfully opened.
/// </summary>
public int[] OpenPorts => this.GetPorts(true, true);
/// <summary>
/// HTTP Ports successfully opened.
/// </summary>
public int[] OpenHttpPorts => this.GetPorts(true, false);
/// <summary>
/// HTTPS Ports successfully opened.
/// </summary>
public int[] OpenHttpsPorts => this.GetPorts(false, true);
/// <summary>
/// IP Addresses receiving requests on.
/// </summary>
public IPAddress[] LocalIpAddresses
{
get
{
Dictionary<IPAddress, bool> Addresses = new Dictionary<IPAddress, bool>();
#if WINDOWS_UWP
foreach (HostName HostName in NetworkInformation.GetHostNames())
{
if ((HostName.Type == HostNameType.Ipv4 || HostName.Type == HostNameType.Ipv6) &&
!(HostName.IPInformation?.NetworkAdapter is null) &&
IPAddress.TryParse(HostName.CanonicalName, out IPAddress Addr))
{
Addresses[Addr] = true;
}
}
#else
if (!(this.listeners is null))
{
foreach (KeyValuePair<TcpListener, bool> P in this.listeners)
{
if (P.Key.LocalEndpoint is IPEndPoint Endpoint)
Addresses[Endpoint.Address] = true;
}
}
#endif
IPAddress[] Result = new IPAddress[Addresses.Count];
Addresses.Keys.CopyTo(Result, 0);
return Result;
}
}
/// <summary>
/// Salt value used when calculating ETag values.
/// </summary>
public string ETagSalt => this.eTagSalt;
/// <summary>
/// Sets a new salt value used when calculating ETag values.
/// </summary>
public async Task SetETagSalt(string NewSalt)
{
if (this.eTagSalt != NewSalt)
{
this.eTagSalt = NewSalt;
await this.ETagSaltChanged.Raise(this, EventArgs.Empty);
}
}
/// <summary>
/// Server name. This string will be shown on the Server header field if nothing else is provided. If it is blank,
/// the server header field will be omitted.
/// </summary>
public string Name
{
get => this.name;
set => this.name = value;
}
/// <summary>
/// Event raised when the <see cref="ETagSalt"/> value has changed.
/// </summary>
public event EventHandlerAsync ETagSaltChanged = null;
/// <summary>
/// Gets open ports
/// </summary>
/// <param name="Http">If HTTP ports should be included.</param>
/// <param name="Https">If HTTPs ports should be included.</param>
/// <returns>Open ports.</returns>
public int[] GetPorts(bool Http, bool Https)
{
SortedDictionary<int, bool> Open = new SortedDictionary<int, bool>();
if (!(this.listeners is null))
{
#if WINDOWS_UWP
foreach (KeyValuePair<StreamSocketListener, Guid> Listener in this.listeners)
{
if (Http)
{
if (int.TryParse(Listener.Key.Information.LocalPort, out int i) && !this.failedPorts.ContainsKey(i))
Open[i] = true;
}
}
#else
IPEndPoint IPEndPoint;
foreach (KeyValuePair<TcpListener, bool> Listener in this.listeners)
{
if ((Listener.Value && Https) || ((!Listener.Value) && Http))
{
IPEndPoint = Listener.Key.LocalEndpoint as IPEndPoint;
if (!(IPEndPoint is null) && !this.failedPorts.ContainsKey(IPEndPoint.Port))
Open[IPEndPoint.Port] = true;
}
}
#endif
}
int[] Result = new int[Open.Count];
Open.Keys.CopyTo(Result, 0);
return Result;
}
#if !WINDOWS_UWP
internal int? UpgradePort
{
get
{
if (this.upgradePort.HasValue)
return this.upgradePort;
if (this.serverCertificate is null)
return null;
int? Result = null;
int Port;
if (!(this.listeners is null))
{
IPEndPoint IPEndPoint;
foreach (KeyValuePair<TcpListener, bool> Listener in this.listeners)
{
if (Listener.Value)
{
IPEndPoint = Listener.Key.LocalEndpoint as IPEndPoint;
if (!(IPEndPoint is null) && !this.failedPorts.ContainsKey(Port = IPEndPoint.Port))
{
if (Port == DefaultHttpsPort || !Result.HasValue)
Result = Port;
}
}
}
}
this.upgradePort = Result;
return Result;
}
}
/// <summary>
/// Updates the server certificate
/// </summary>
/// <param name="ServerCertificate">Server Certificate.</param>
public void UpdateCertificate(X509Certificate ServerCertificate)
{
this.serverCertificate = ServerCertificate;
this.upgradePort = null;
}
/// <summary>
/// Configures Mutual-TLS capabilities of the server. Affects all connections, all resources.
/// </summary>
/// <param name="ClientCertificates">If client certificates are not used, optional or required.</param>
/// <param name="TrustClientCertificates">If client certificates should be trusted, even if they do not validate.</param>
/// <param name="LockSettings">If client certificate settings should be locked.</param>
public void ConfigureMutualTls(ClientCertificates ClientCertificates, bool TrustClientCertificates, bool LockSettings)
{
this.ConfigureMutualTls(ClientCertificates, TrustClientCertificates, null, LockSettings);
}
/// <summary>
/// Configures Mutual-TLS capabilities of the server. Affects all connections, all resources.
/// </summary>
/// <param name="ClientCertificates">If client certificates are not used, optional or required.</param>
/// <param name="TrustClientCertificates">If client certificates should be trusted, even if they do not validate.</param>
/// <param name="PortSpecificSettings">Port-specific mTLS settings.</param>
/// <param name="LockSettings">If client certificate settings should be locked.</param>
public void ConfigureMutualTls(ClientCertificates ClientCertificates, bool TrustClientCertificates,
Dictionary<int, KeyValuePair<ClientCertificates, bool>> PortSpecificSettings, bool LockSettings)
{
if (this.clientCertificateSettingsLocked)
throw new InvalidOperationException("Mutual TLS settings locked.");
this.clientCertificates = ClientCertificates;
this.trustClientCertificates = TrustClientCertificates;
this.portSpecificMTlsSettings = PortSpecificSettings;
this.clientCertificateSettingsLocked = LockSettings;
}
/// <summary>
/// If client certificates are not used by default, optional or required.
/// </summary>
public ClientCertificates ClientCertificates => this.clientCertificates;
/// <summary>
/// If client certificates should be trusted by default, even if they do not validate.
/// </summary>
public bool TrustClientCertificates => this.trustClientCertificates;
/// <summary>
/// Gets mTLS settings for a given port number.
/// </summary>
/// <param name="Port">Port number.</param>
/// <param name="ClientCertificates">How to configure mTLS for the corresponding port number.</param>
/// <param name="TrustClientCertificates">If client certificates are to be trusted by default.</param>
public void GetMTlsSettings(int Port, out ClientCertificates ClientCertificates, out bool TrustClientCertificates)
{
if (!(this.portSpecificMTlsSettings is null) && this.portSpecificMTlsSettings.TryGetValue(Port,
out KeyValuePair<ClientCertificates, bool> P))
{
ClientCertificates = P.Key;
TrustClientCertificates = P.Value;
}
else
{
ClientCertificates = this.clientCertificates;
TrustClientCertificates = this.trustClientCertificates;
}
}
#endif
#endregion
#region HTTP/2 Properties
/// <summary>
/// HTTP/2: Enabled or not.