-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.fs
More file actions
301 lines (236 loc) · 10.4 KB
/
HttpServer.fs
File metadata and controls
301 lines (236 loc) · 10.4 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
module HttpServer
open System
open System.IO
open System.Net
open System.Net.Sockets
open System.Text
open System.Threading
open HttpHeaders
open HttpStreamReader
open HttpData
open HttpLogger
open Utils
open Fiber
exception HttpResponseExnException of HttpResponse
let HttpResponseExnWithCode =
fun code -> HttpResponseExnException(http_response_of_code code)
type HttpClientHandler(server: HttpServer, peer: TcpClient) =
let mutable rawstream: NetworkStream = null
let mutable stream: Stream = null
let mutable reader: HttpStreamReader = Unchecked.defaultof<HttpStreamReader>
let mutable handlers = []
interface IDisposable with
member _.Dispose() =
if not (isNull stream) then
noexn (fun () -> rawstream.Dispose())
if not (isNull rawstream) then
noexn (fun () -> rawstream.Dispose())
rawstream <- null
stream <- null
reader <- Unchecked.defaultof<HttpStreamReader>
noexn (fun () -> peer.Close())
member private _.SendLine(line: string) =
let bytes = Encoding.ASCII.GetBytes(line + "\r\n")
stream.WriteAsync(bytes, 0, bytes.Length) |> ignore
member private self.SendStatus version code =
self.SendLine(
String.Format(
"HTTP/{0} {1} {2}",
(string_of_httpversion version),
(HttpCode.code code),
(HttpCode.http_status code)
)
)
member private self.SendHeaders(headers: seq<string * string>) =
headers
|> Seq.iter (fun (h, v) -> self.SendLine(String.Format("{0}: {1}", h, v)))
member private self.SendResponseWithBody version code headers (body: byte[]) =
self.SendStatus version code
self.SendHeaders headers
self.SendLine ""
if body.Length <> 0 then
stream.WriteAsync(body, 0, body.Length).GetAwaiter().GetResult()
member private self.SendResponse version code =
self.SendResponseWithBody
version
code
[ ("Content-Type", "text/plain"); ("Connection", "close") ]
(Encoding.ASCII.GetBytes((HttpCode.http_message code) + "\r\n"))
member private _.ResponseOfStream (fi: FileInfo) (stream: Stream) =
let ctype =
match server.Config.mimesmap.Lookup(Path.GetExtension(fi.FullName)) with
| Some ctype -> ctype
| None -> "text/plain" in
{ code = HttpCode.HTTP_200
headers = HttpHeaders.OfList [ (CONTENT_TYPE, ctype) ]
body = HB_Stream(stream, fi.Length) }
member private self.ServeStatic(request: HttpRequest) =
let path = HttpServer.CanonicalPath request.path in
let path = if path.Equals("") then "index.html" else path
let path = Path.Combine(server.Config.docroot, path) in
if request.mthod <> "GET" then
begin raise (HttpResponseExnWithCode HttpCode.HTTP_400) end
try
let infos = FileInfo(path) in
if not infos.Exists then
begin raise (HttpResponseExnWithCode HttpCode.HTTP_404) end
let input =
try
infos.Open(FileMode.Open, FileAccess.Read, FileShare.Read)
with :? IOException ->
raise (HttpResponseExnWithCode HttpCode.HTTP_500)
self.ResponseOfStream infos input
with
| :? UnauthorizedAccessException -> raise (HttpResponseExnWithCode HttpCode.HTTP_403)
| :? PathTooLongException
| :? NotSupportedException
| :? ArgumentException -> raise (HttpResponseExnWithCode HttpCode.HTTP_404)
member private self.ReadAndServeRequest() =
try
let request = reader.ReadRequest() in
match List.tryPick (fun handler -> handler request) handlers with
| Some status -> status
| None ->
let close =
match request.version with
| HTTPV_10 ->
match request.headers.Get "Connection" with
| Some v when v.Equals("keep-alive", StringComparison.OrdinalIgnoreCase) -> false
| _ -> true
| _ ->
match request.headers.Get "Connection" with
| Some v when v.Equals("close", StringComparison.OrdinalIgnoreCase) -> true
| _ -> false
let response =
try
self.ServeStatic request
with
| :? IOException as e -> raise e
| HttpResponseExnException response -> response
| _ -> http_response_of_code HttpCode.HTTP_500 in
if close then
begin response.headers.Set "Connection" "close" end
response.headers.Set "Content-Length" (String.Format("{0}", (http_body_length response.body)))
begin
match response.body with
| HB_Raw bytes ->
self.SendResponseWithBody request.version response.code (response.headers.ToSeq()) bytes
| HB_Stream(f, flen) ->
self.SendStatus request.version response.code
self.SendHeaders(response.headers.ToSeq())
self.SendLine ""
try
let fa = Fiber.atom (fun () -> f)
Fiber.swap fa (fun f ->
if f().CopyTo(stream, flen) < flen then
failwith "ReadAndServeRequest: short-read"
f // Return the result if needed, or modify as appropriate
)
|> fun _ -> noexn (fun () -> f.Close()) // Ignore the return, focus on side effects
finally
noexn (fun () -> stream.Flush())
end
//stream.Flush()
not close
with NoHttpRequest as e ->
if e <> NoHttpRequest then
begin
self.SendResponse HTTPV_10 HttpCode.HTTP_400
stream.Flush()
end
false (* no keep-alive *)
member self.Start() =
try
try
(*HttpLogger.Info
(String.Format("new connection from [{0}]",peer.Client.RemoteEndPoint))*)
peer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true)
peer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true)
rawstream <- peer.GetStream()
(*HttpLogger.Info "Plaintext connection"*)
stream <- rawstream
reader <- new HttpStreamReader(stream)
while self.ReadAndServeRequest() do ()
with e ->
Console.WriteLine(e.Message)
finally
(*HttpLogger.Info "closing connection";*)
noexn (fun () -> peer.Close())
and HttpServer(localaddr: IPEndPoint, config: HttpServerConfig) =
let config: HttpServerConfig = config
let mutable socket: TcpListener = null
interface IDisposable with
member _.Dispose() =
if not (isNull socket) then
noexn (fun () -> socket.Stop())
member self.Config = config
static member CanonicalPath(path: string) =
let path =
path.Split('/')
|> Array.fold
(fun canon segment ->
match canon, segment with
| _, "" -> canon
| _, "." -> canon
| _ :: ctail, ".." -> ctail
| [], ".." -> []
| _, segment -> segment :: canon)
[] in
String.Join("/", Array.ofList (List.rev path))
member private self.ClientHandler (peer: TcpClient) : Async<unit> =
async {
peer.NoDelay <- true
use handler = new HttpClientHandler(self, peer)
do! Async.SwitchToThreadPool()
handler.Start()
}
member private self.AcceptAndServe() =
let rec acceptLoop () =
async {
// Accept a client
let! client =
Async.FromBeginEnd(socket.BeginAcceptTcpClient, socket.EndAcceptTcpClient)
|> Async.Catch
match client with
| Choice1Of2 client ->
let! peer = async { do! self.ClientHandler client } |> Async.Catch
match peer with
| Choice1Of2 _ -> ()
| Choice2Of2 ex -> printfn "Error handling client: %A" ex
| Choice2Of2 ex ->
// Handle any exceptions from accepting client
printfn "Error accepting client: %A" ex
// Recursive call
return! acceptLoop ()
}
// Start the acceptLoop
let cts = new System.Threading.CancellationTokenSource()
Async.Start(
async {
try
do! acceptLoop ()
with ex ->
printfn "AcceptLoop terminated with exception: %A" ex
},
cts.Token
)
// Keep the program running
printfn "Server is running on port 2443. Press any key to stop."
Console.ReadKey() |> ignore
// Cancel the accept loop when a key is pressed
cts.Cancel()
member self.Start() =
if not (isNull socket) then
raise (InvalidOperationException())
//HttpLogger.Info (sprintf "Starting HTTP server on port %d" localaddr.Port)
socket <- new TcpListener(localaddr)
try
socket.Start()
self.AcceptAndServe()
finally
noexn (fun () -> socket.Stop())
socket <- null
let run =
fun config ->
use http = new HttpServer(config.localaddr, config)
http.Start()