forked from ThomasMertes/seed7
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserv.s7i
More file actions
344 lines (314 loc) · 12.6 KB
/
httpserv.s7i
File metadata and controls
344 lines (314 loc) · 12.6 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
(********************************************************************)
(* *)
(* httpserv.s7i Support for HTTP server and HTTP requests. *)
(* Copyright (C) 2015 Thomas Mertes *)
(* *)
(* This file is part of the Seed7 Runtime Library. *)
(* *)
(* The Seed7 Runtime Library is free software; you can *)
(* redistribute it and/or modify it under the terms of the GNU *)
(* Lesser General Public License as published by the Free Software *)
(* Foundation; either version 2.1 of the License, or (at your *)
(* option) any later version. *)
(* *)
(* The Seed7 Runtime Library is distributed in the hope that it *)
(* will be useful, but WITHOUT ANY WARRANTY; without even the *)
(* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR *)
(* PURPOSE. See the GNU Lesser General Public License for more *)
(* details. *)
(* *)
(* You should have received a copy of the GNU Lesser General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 51 Franklin Street, *)
(* Fifth Floor, Boston, MA 02110-1301, USA. *)
(* *)
(********************************************************************)
include "time.s7i";
include "duration.s7i";
include "listener.s7i";
include "scanstri.s7i";
include "encoding.s7i";
include "unicode.s7i";
include "x509cert.s7i";
include "tls.s7i";
include "cgi.s7i";
const type: propertyType is hash [string] string;
const type: setOfFile is hashset(file);
(**
* Destribes an incoming HTTP request.
* This is formatted to be easily processed by an ''httpServer''.
*)
const type: httpServerRequest is new struct
var file: sock is STD_NULL;
var string: method is "";
var string: path is "";
var string: queryStri is "";
var propertyType: queryParams is propertyType.value;
var propertyType: properties is propertyType.value;
var string: header is "";
var string: body is "";
end struct;
(**
* Destribes an HTTP server connection.
*)
const type: httpServerConnection is new struct
var file: sock is STD_NULL;
var duration: keepAliveTime is 15 . SECONDS;
var time: timeout is time.value;
var string: buffer is "";
var integer: readPos is 1;
var boolean: readingHeader is TRUE;
var integer: contentToRead is 0;
var httpServerRequest: request is httpServerRequest.value;
end struct;
const type: httpConnectionHash is hash [file] httpServerConnection;
(**
* Destribes an HTTP server.
*)
const type: httpServer is new struct
var boolean: useTls is FALSE;
var integer: port is 1080;
var certAndKey: certificate is certAndKey.value;
var listener: httpListener is listener.value;
var setOfFile: newConnections is setOfFile.value;
var httpConnectionHash: sessions is httpConnectionHash.value;
var duration: keepAliveTime is 15 . SECONDS;
end struct;
(**
* Check if the request has a particular expectation.
* In accordance with the specification, this comparison is done case-insensitively.
* @param a previously received HTTP request.
* @return TRUE if the expectation is present; FALSE otherwise.
*)
const func boolean: expecting (in httpServerRequest: request, in string: expectation) is
return "expect" in request.properties and lower(request.properties["expect"]) = lower(expectation);
##
# Reset a request that has been "paused" by an "Expect" header.
# It appears that 100 and 417 responses often result in the continuance
# of a request--meaning the body will be sent next without any headers--
# but since I couldn't find this as an official rule, I've left the decision
# to reset or retain the data up to the user.
#
const proc: resetRequest (inout httpServer: server, inout file: sock) is func
begin
server.sessions[sock].readingHeader := TRUE;
server.sessions[sock].request := httpServerRequest.value;
end func;
##
# Reads a chunk of request data from an open connection.
#
const func httpServerRequest: getHttpRequest (inout httpServerConnection: conn) is func
result
var httpServerRequest: request is httpServerRequest.value;
local
var string: line is "";
var integer: lfPos is 0;
var string: requestPath is "";
var integer: questionMarkPos is 0;
var integer: colonPos is 0;
begin
# writeln("getHttpRequest");
conn.timeout := time(NOW) + conn.keepAliveTime;
conn.buffer := conn.buffer[conn.readPos ..];
conn.readPos := 1;
# The common upper-limit for headers is 16 KB, while body limits can be far larger;
# so--for the body--read in 512 KB chunks to require fewer loops when possible.
conn.buffer &:= gets(conn.sock, conn.readingHeader ? 16384 : 524288);
if conn.readingHeader then
lfPos := pos(conn.buffer, '\n');
while lfPos <> 0 do
conn.request.header &:= conn.buffer[conn.readPos .. lfPos];
if lfPos > 1 and conn.buffer[pred(lfPos)] = '\r' then
line := conn.buffer[conn.readPos .. lfPos - 2];
else
line := conn.buffer[conn.readPos .. pred(lfPos)];
end if;
conn.readPos := succ(lfPos);
# writeln("<- " <& line);
if line = "" then
if "content-length" in conn.request.properties then
block
conn.contentToRead := integer(conn.request.properties["content-length"]);
exception
catch RANGE_ERROR:
noop;
end block;
end if;
conn.readingHeader := FALSE;
lfPos := 0;
elsif conn.request.method = "" then
conn.request.method := getWord(line);
requestPath := getWord(line);
questionMarkPos := pos(requestPath, '?');
if questionMarkPos <> 0 then
conn.request.queryStri := requestPath[succ(questionMarkPos) ..];
requestPath := requestPath[.. pred(questionMarkPos)];
end if;
conn.request.path := replace(fromUrlEncoded(requestPath), "\\", "/");
block
conn.request.path := fromUtf8(conn.request.path);
exception
catch RANGE_ERROR:
noop;
end block;
conn.request.queryParams := getCgiParameters(conn.request.queryStri);
else
colonPos := pos(line, ':');
if colonPos <> 0 then
# Coerce the keys to lowercase for simplicity's sake, as the spec dictates that they are case-insensitive.
conn.request.properties @:= [lower(trim(line[.. pred(colonPos)]))] trim(line[succ(colonPos) ..]);
end if;
end if;
if conn.readingHeader then
lfPos := pos(conn.buffer, '\n', conn.readPos);
end if;
end while;
end if;
if not conn.readingHeader then
(* It can be that a client sends an "Expect: 100-continue" header, indicating that there
is a large amount of data to follow. In this case, store the request without resetting it,
so as to allow the program to check if the request is possible and to respond accordingly.
In the event we respond with a "Status: 100 Continue", then the body will be sent without
any headers. *)
if expecting(conn.request, "100-continue") then
request := conn.request;
request.sock := conn.sock;
excl(conn.request.properties, "expect"); # Now exclude from the connection's side, so as to avoid an eternal loop.
else
if conn.contentToRead <> 0 then
# If the remaining buffer contains the rest of the content, acquire and finish.
if length(conn.buffer) - conn.readPos + 1 >= conn.contentToRead then
# writeln("<- " <& conn.buffer[conn.readPos len conn.contentToRead]);
conn.request.body &:= conn.buffer[conn.readPos len conn.contentToRead];
conn.readPos +:= conn.contentToRead;
conn.contentToRead := 0;
else
# writeln("<- '" <& conn.buffer[conn.readPos ..] <& "'");
conn.request.body &:= conn.buffer[conn.readPos ..];
conn.contentToRead -:= length(conn.buffer) - conn.readPos + 1;
conn.readPos := succ(length(conn.buffer));
end if;
end if;
if conn.contentToRead = 0 then
request := conn.request;
request.sock := conn.sock;
conn.readingHeader := TRUE;
conn.request := httpServerRequest.value;
end if;
end if;
end if;
end func;
const proc: openHttpSession (inout httpServer: server, inout file: sock) is func
local
var file: tlsSock is STD_NULL;
var httpServerConnection: conn is httpServerConnection.value;
begin
# writeln("openHttpSession: " <& ord(sock));
if server.useTls then
conn.sock := openServerTls(sock, server.certificate);
if conn.sock = STD_NULL then
# writeln(" ***** Cannot open TLS connection.");
block
close(sock);
exception
catch FILE_ERROR:
noop;
end block;
sock := STD_NULL;
end if;
else
conn.sock := sock;
end if;
if conn.sock <> STD_NULL then
conn.keepAliveTime := server.keepAliveTime;
conn.timeout := time(NOW) + conn.keepAliveTime;
server.sessions @:= [sock] conn;
end if;
end func;
const proc: closeHttpSession (inout httpServer: server, inout file: sock) is func
begin
# writeln("closeHttpSession: " <& ord(sock));
close(server.sessions[sock].sock);
excl(server.sessions, sock);
end func;
const func httpServerRequest: getHttpRequest (inout httpServer: server, inout file: sock) is func
result
var httpServerRequest: request is httpServerRequest.value;
begin
# writeln("getHttpRequest: " <& ord(sock));
if sock not in server.sessions then
openHttpSession(server, sock);
end if;
if sock in server.sessions then
if eof(sock) then
closeHttpSession(server, sock);
else
block
request := getHttpRequest(server.sessions[sock]);
exception
catch FILE_ERROR:
noop;
end block;
end if;
end if;
end func;
const proc: cleanSessions (inout httpServer: server) is func
local
var file: sock is STD_NULL;
begin
# writeln(length(server.sessions) <& " sessions");
for sock range keys(server.sessions) do
if sock in server.sessions and
time(NOW) > server.sessions[sock].timeout then
closeHttpSession(server, sock);
end if;
end for;
end func;
(**
* Open a HTTP or HTTPS server at the given ''port''.
* @param port Port of the HTTP/HTTPS server.
* @param certificate Server certificate used for HTTPS.
* @param useTls TRUE if an HTTPS server should be opened, or
* FALSE if an HTTP server should be opened.
* @return an open HTTP or HTTPS server.
*)
const func httpServer: openHttpServer (in integer: port,
in certAndKey: certificate, in boolean: useTls) is func
result
var httpServer: server is httpServer.value;
begin
server.useTls := useTls;
server.port := port;
server.certificate := certificate;
server.httpListener := openInetListener(port);
listen(server.httpListener, 10);
end func;
(**
* Get the next HTTP request from the HTTP or HTTPS ''server''.
* If necessary this function waits until a request is received.
* @param server HTTP or HTTPS server that receives the request.
* @return the received HTTP request.
*)
const func httpServerRequest: getHttpRequest (inout httpServer: server) is func
result
var httpServerRequest: request is httpServerRequest.value;
local
var file: existingConnection is STD_NULL;
var file: newConnection is STD_NULL;
begin
repeat
waitForRequest(server.httpListener, existingConnection, newConnection);
if existingConnection <> STD_NULL then
if existingConnection in server.newConnections then
excl(server.newConnections, existingConnection);
openHttpSession(server, existingConnection);
else
request := getHttpRequest(server, existingConnection);
end if;
end if;
if newConnection <> STD_NULL then
incl(server.newConnections, newConnection);
end if;
cleanSessions(server);
until request.method <> "";
end func;