This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 79
/
HttpServer.cs
175 lines (138 loc) · 5.43 KB
/
HttpServer.cs
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
//
// Author:
// Aaron Bockover <abock@xamarin.com>
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Interactive.Logging;
namespace Xamarin.Interactive.Core
{
abstract class HttpServer : IDisposable
{
const string TAG = nameof (HttpServer);
readonly object mutex = new object ();
CancellationTokenSource cts;
Semaphore semaphore;
ManualResetEventSlim stopEvent;
HttpListener listener;
protected Uri BaseUri { get; private set; }
protected int MaxConnections { get; set; } = 4;
bool IsListening => listener != null;
protected abstract Task PerformHttpAsync (
HttpListenerContext context,
CancellationToken cancellationToken);
public void Dispose ()
{
GC.SuppressFinalize (this);
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing)
Stop ();
}
void StopListener ()
{
listener?.Stop ();
listener = null;
}
protected void Start ()
{
lock (mutex) {
if (IsListening)
return;
var timeout = DateTime.Now.AddSeconds (1);
SocketException exception = null;
while (true) {
if (DateTime.Now >= timeout) {
StopListener ();
throw new Exception (
"unable to bind to a port within an acceptable amount of time",
exception);
}
var port = (ushort)ValidPortRange.GetRandom ();
try {
// Fall back to 127.0.0.1 instead of "localhost" to avoid IPv6/IPv4 ambiguity.
// On Windows < 10, we only have permission to use "localhost".
var osVersion = Environment.OSVersion;
var host = osVersion.Platform == PlatformID.Win32NT && osVersion.Version.Major < 10
? "localhost"
: "127.0.0.1";
BaseUri = new Uri ($"http://{host}:{port}");
listener = new HttpListener ();
listener.Prefixes.Add (BaseUri.AbsoluteUri);
listener.Start ();
cts = new CancellationTokenSource ();
semaphore = new Semaphore (MaxConnections, MaxConnections);
stopEvent = new ManualResetEventSlim (false);
using (var startEvent = new ManualResetEventSlim (false)) {
new Thread (() => {
startEvent.Set ();
AcceptLoop ();
}) { IsBackground = true }.Start ();
startEvent.Wait ();
}
break;
} catch (SocketException e) {
exception = e;
}
}
}
}
protected void Stop ()
{
lock (mutex) {
if (!IsListening)
return;
semaphore.Release ();
cts.Cancel ();
}
stopEvent.Wait ();
Log.Debug (TAG, "Stopped");
}
void AcceptLoop ()
{
Log.Debug (TAG, $"Listening on prefix {BaseUri}");
while (true) {
semaphore.WaitOne ();
CancellationToken cancellationToken;
lock (mutex) {
if (cts == null || cts.Token.IsCancellationRequested) {
Log.Debug (TAG, "AcceptLoop: cancellation requested");
semaphore.Dispose ();
StopListener ();
stopEvent.Set ();
return;
}
cancellationToken = cts.Token;
}
Log.Debug (TAG, "AcceptLoop: AcceptClientConnectionAsync");
// do not await this in order to return control immediately back to
// the loop so we can hit the semaphore wait for the next connection
listener.GetContextAsync ().ContinueWith (async t1 => {
Log.Debug (TAG, "AcceptLoop: AcceptClientConnectionAsync continuation");
semaphore.Release ();
if (t1.Exception != null) {
Log.Error (TAG, "AcceptClientConnectionAsync failed", t1.Exception);
return;
}
var context = t1.Result;
if (context == null)
return;
try {
await PerformHttpAsync (context, cancellationToken)
.ConfigureAwait (false);
context.Response.Close ();
} catch (Exception e) {
Log.Error (TAG, "HandleClientConnectionAsync failed", e);
}
}).ConfigureAwait (false);
}
}
}
}