-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathHttpServer.cs
More file actions
1720 lines (1551 loc) · 48.3 KB
/
HttpServer.cs
File metadata and controls
1720 lines (1551 loc) · 48.3 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
#region License
/*
* HttpServer.cs
*
* A simple HTTP server that allows to accept WebSocket handshake requests.
*
* The MIT License
*
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a simple HTTP server that allows to accept
/// WebSocket handshake requests.
/// </summary>
/// <remarks>
/// This class can provide multiple WebSocket services.
/// </remarks>
public class HttpServer
{
#region Private Fields
private System.Net.IPAddress _address;
private string _docRootPath;
private string _hostname;
private HttpListener _listener;
private Logger _log;
private int _port;
private Thread _receiveThread;
private bool _secure;
private WebSocketServiceManager _services;
private volatile ServerState _state;
private object _sync;
private bool _autoCloseResponse;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// The new instance listens for incoming requests on
/// <see cref="System.Net.IPAddress.Any"/> and port 80.
/// </remarks>
public HttpServer ()
{
init ("*", System.Net.IPAddress.Any, 80, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for incoming requests on
/// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// It provides secure connections if <paramref name="port"/> is 443.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the number of the port
/// on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public HttpServer (int port)
: this (port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="url"/>.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for incoming requests on the IP address of the
/// host of <paramref name="url"/> and the port of <paramref name="url"/>.
/// </para>
/// <para>
/// Either port 80 or 443 is used if <paramref name="url"/> includes
/// no port. Port 443 is used if the scheme of <paramref name="url"/>
/// is https; otherwise, port 80 is used.
/// </para>
/// <para>
/// The new instance provides secure connections if the scheme of
/// <paramref name="url"/> is https.
/// </para>
/// </remarks>
/// <param name="url">
/// A <see cref="string"/> that represents the HTTP URL of the server.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="url"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="url"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="url"/> is invalid.
/// </para>
/// </exception>
public HttpServer (string url)
{
if (url == null)
throw new ArgumentNullException ("url");
if (url.Length == 0)
throw new ArgumentException ("An empty string.", "url");
Uri uri;
string msg;
if (!tryCreateUri (url, out uri, out msg))
throw new ArgumentException (msg, "url");
var host = uri.GetDnsSafeHost (true);
var addr = host.ToIPAddress ();
if (addr == null) {
msg = "The host part could not be converted to an IP address.";
throw new ArgumentException (msg, "url");
}
if (!addr.IsLocal ()) {
msg = "The IP address of the host is not a local IP address.";
throw new ArgumentException (msg, "url");
}
init (host, addr, uri.Port, uri.Scheme == "https");
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// The new instance listens for incoming requests on
/// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the number of the port
/// on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/>: <c>true</c> if the new instance provides
/// secure connections; otherwise, <c>false</c>.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public HttpServer (int port, bool secure)
{
if (!port.IsPortNumber ()) {
var msg = "Less than 1 or greater than 65535.";
throw new ArgumentOutOfRangeException ("port", msg);
}
init ("*", System.Net.IPAddress.Any, port, secure);
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/> and <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// The new instance listens for incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </para>
/// <para>
/// It provides secure connections if <paramref name="port"/> is 443.
/// </para>
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents
/// the local IP address on which to listen.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the number of the port
/// on which to listen.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> is not a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port)
: this (address, port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with
/// the specified <paramref name="address"/>, <paramref name="port"/>,
/// and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// The new instance listens for incoming requests on
/// <paramref name="address"/> and <paramref name="port"/>.
/// </remarks>
/// <param name="address">
/// A <see cref="System.Net.IPAddress"/> that represents
/// the local IP address on which to listen.
/// </param>
/// <param name="port">
/// An <see cref="int"/> that represents the number of the port
/// on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/>: <c>true</c> if the new instance provides
/// secure connections; otherwise, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="address"/> is not a local IP address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> is less than 1 or greater than 65535.
/// </exception>
public HttpServer (System.Net.IPAddress address, int port, bool secure)
{
if (address == null)
throw new ArgumentNullException ("address");
if (!address.IsLocal ())
throw new ArgumentException ("Not a local IP address.", "address");
if (!port.IsPortNumber ()) {
var msg = "Less than 1 or greater than 65535.";
throw new ArgumentOutOfRangeException ("port", msg);
}
init (address.ToString (true), address, port, secure);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the IP address of the server.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPAddress"/> that represents the local
/// IP address on which to listen for incoming requests.
/// </value>
public System.Net.IPAddress Address {
get {
return _address;
}
}
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </remarks>
/// <value>
/// <para>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/>
/// enum values.
/// </para>
/// <para>
/// It represents the scheme used to authenticate the clients.
/// </para>
/// <para>
/// The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </para>
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _listener.AuthenticationSchemes;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_listener.AuthenticationSchemes = value;
}
}
}
/// <summary>
/// Gets or sets the path to the document folder of the server.
/// </summary>
/// <remarks>
/// <para>
/// '/' or '\' is trimmed from the end of the value if any.
/// </para>
/// <para>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> that represents a path to the folder
/// from which to find the requested file.
/// </para>
/// <para>
/// The default value is "./Public".
/// </para>
/// </value>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// The value specified for a set operation is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The value specified for a set operation is an invalid path string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The value specified for a set operation is an absolute root.
/// </para>
/// </exception>
public string DocumentRootPath {
get {
return _docRootPath;
}
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
value = value.TrimSlashOrBackslashFromEnd ();
string full = null;
try {
full = Path.GetFullPath (value);
}
catch (Exception ex) {
throw new ArgumentException ("An invalid path string.", "value", ex);
}
if (value == "/")
throw new ArgumentException ("An absolute root.", "value");
if (value == "\\")
throw new ArgumentException ("An absolute root.", "value");
if (value.Length == 2 && value[1] == ':')
throw new ArgumentException ("An absolute root.", "value");
if (full == "/")
throw new ArgumentException ("An absolute root.", "value");
full = full.TrimSlashOrBackslashFromEnd ();
if (full.Length == 2 && full[1] == ':')
throw new ArgumentException ("An absolute root.", "value");
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_docRootPath = value;
}
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether secure connections are provided.
/// </summary>
/// <value>
/// <c>true</c> if this instance provides secure connections; otherwise,
/// <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up
/// the inactive sessions periodically.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if the server cleans up the inactive sessions
/// every 60 seconds; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>true</c>.
/// </para>
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging function for the server.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging function.
/// </value>
public Logger Log {
get {
return _log;
}
}
/// <summary>
/// Gets the port of the server.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the port
/// on which to listen for incoming requests.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the realm used for authentication.
/// </summary>
/// <remarks>
/// <para>
/// "SECRET AREA" is used as the realm if the value is
/// <see langword="null"/> or an empty string.
/// </para>
/// <para>
/// The set operation does nothing if the server has
/// already started or it is shutting down.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> or <see langword="null"/> by default.
/// </para>
/// <para>
/// That string represents the name of the realm.
/// </para>
/// </value>
public string Realm {
get {
return _listener.Realm;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_listener.Realm = value;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to
/// be bound to an address that is already in use.
/// </summary>
/// <remarks>
/// <para>
/// You should set this property to <c>true</c> if you would
/// like to resolve to wait for socket in TIME_WAIT state.
/// </para>
/// <para>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if the server is allowed to be bound to an address
/// that is already in use; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool ReuseAddress {
get {
return _listener.ReuseAddress;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_listener.ReuseAddress = value;
}
}
}
/// <summary>
/// Gets the configuration for secure connections.
/// </summary>
/// <remarks>
/// This configuration will be referenced when attempts to start,
/// so it must be configured before the start method is called.
/// </remarks>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents
/// the configuration used to provide secure connections.
/// </value>
/// <exception cref="InvalidOperationException">
/// This instance does not provide secure connections.
/// </exception>
public ServerSslConfiguration SslConfiguration {
get {
if (!_secure) {
var msg = "This instance does not provide secure connections.";
throw new InvalidOperationException (msg);
}
return _listener.SslConfiguration;
}
}
/// <summary>
/// Gets or sets the delegate used to find the credentials
/// for an identity.
/// </summary>
/// <remarks>
/// <para>
/// No credentials are found if the method invoked by
/// the delegate returns <see langword="null"/> or
/// the value is <see langword="null"/>.
/// </para>
/// <para>
/// The set operation does nothing if the server has
/// already started or it is shutting down.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// A <c>Func<<see cref="IIdentity"/>,
/// <see cref="NetworkCredential"/>></c> delegate or
/// <see langword="null"/> if not needed.
/// </para>
/// <para>
/// That delegate invokes the method called for finding
/// the credentials used to authenticate a client.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _listener.UserCredentialsFinder;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_listener.UserCredentialsFinder = value;
}
}
}
/// <summary>
/// Gets or sets the time to wait for the response to the WebSocket Ping or
/// Close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="TimeSpan"/> to wait for the response.
/// </para>
/// <para>
/// The default value is the same as 1 second.
/// </para>
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the management function for the WebSocket services
/// provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages
/// the WebSocket services provided by the server.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
/// <summary>
/// Gets or sets a value indicating whether the responses
/// are synchronously closed after the request event handler
/// has returned. If set to <c>false</c>, it is the responsibility to
/// the event handler delegate to call the <see cref="HttpListenerResponse.Close()"/>
/// method on the response object, otherwise resources may not be properly cleaned.
/// </summary>
/// <remarks>
/// <para>
/// You should set this property to <c>true</c> if you would
/// like to send response after executing an asynchronous task.
/// </para>
/// <para>
/// The set operation does nothing if the server has already
/// started or it is shutting down.
/// </para>
/// </remarks>
/// <value>
/// <para>
/// <c>true</c> if the server synchronously close the response
/// after the handler delegate has returned; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>true</c>.
/// </para>
/// </value>
public bool AutoCloseResponse
{
get
{
return _autoCloseResponse;
}
set
{
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
_autoCloseResponse = value;
}
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the server receives an HTTP CONNECT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnConnect;
/// <summary>
/// Occurs when the server receives an HTTP DELETE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnDelete;
/// <summary>
/// Occurs when the server receives an HTTP GET request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnGet;
/// <summary>
/// Occurs when the server receives an HTTP HEAD request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnHead;
/// <summary>
/// Occurs when the server receives an HTTP OPTIONS request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnOptions;
/// <summary>
/// Occurs when the server receives an HTTP POST request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPost;
/// <summary>
/// Occurs when the server receives an HTTP PUT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPut;
/// <summary>
/// Occurs when the server receives an HTTP TRACE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnTrace;
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (_state != ServerState.Start)
return;
_state = ServerState.ShuttingDown;
}
try {
try {
_services.Stop (1006, String.Empty);
}
finally {
_listener.Abort ();
}
}
catch {
}
_state = ServerState.Stop;
}
private bool canSet (out string message)
{
message = null;
if (_state == ServerState.Start) {
message = "The server has already started.";
return false;
}
if (_state == ServerState.ShuttingDown) {
message = "The server is shutting down.";
return false;
}
return true;
}
private bool checkCertificate (out string message)
{
message = null;
var byUser = _listener.SslConfiguration.ServerCertificate != null;
var path = _listener.CertificateFolderPath;
var withPort = EndPointListener.CertificateExists (_port, path);
var both = byUser && withPort;
if (both) {
_log.Warn ("A server certificate associated with the port is used.");
return true;
}
var either = byUser || withPort;
if (!either) {
message = "There is no server certificate for secure connections.";
return false;
}
return true;
}
private string createFilePath (string childPath)
{
childPath = childPath.TrimStart ('/', '\\');
return new StringBuilder (_docRootPath, 32)
.AppendFormat ("/{0}", childPath)
.ToString ()
.Replace ('\\', '/');
}
private static HttpListener createListener (
string hostname, int port, bool secure
)
{
var lsnr = new HttpListener ();
var schm = secure ? "https" : "http";
var pref = String.Format ("{0}://{1}:{2}/", schm, hostname, port);
lsnr.Prefixes.Add (pref);
return lsnr;
}
private void init (
string hostname, System.Net.IPAddress address, int port, bool secure
)
{
_hostname = hostname;
_address = address;
_port = port;
_secure = secure;
_docRootPath = "./Public";
_listener = createListener (_hostname, _port, _secure);
_log = _listener.Log;
_services = new WebSocketServiceManager (_log);
_sync = new object ();
AutoCloseResponse = true;
}
private void processRequest (HttpListenerContext context)
{
var method = context.Request.HttpMethod;
var evt = method == "GET"
? OnGet
: method == "HEAD"
? OnHead
: method == "POST"
? OnPost
: method == "PUT"
? OnPut
: method == "DELETE"
? OnDelete
: method == "CONNECT"
? OnConnect
: method == "OPTIONS"
? OnOptions
: method == "TRACE"
? OnTrace
: null;
if (evt != null)
evt (this, new HttpRequestEventArgs (context, _docRootPath));
else
{
context.Response.StatusCode = 501; // Not Implemented
context.Response.Close ();
return;
}
if (AutoCloseResponse)
context.Response.Close ();
}
private void processRequest (HttpListenerWebSocketContext context)
{
var uri = context.RequestUri;
if (uri == null) {
context.Close (HttpStatusCode.BadRequest);
return;
}
var path = uri.AbsolutePath;
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (path, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
HttpListenerContext ctx = null;
try {