-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebServer.cpp
398 lines (326 loc) · 13 KB
/
WebServer.cpp
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
#include "Arduino.h"
#include "WebServer.h"
#include "Regexp.h"
#include "WiFiNINA.h"
// ==== WebServer ====
//create WebServer with default port
WebServer::WebServer() : _server(WS_DEFAULT_PORT) { };
//create WebServer with custom port
WebServer::WebServer(byte port) : _server(port) { };
// begin listening to requests
void WebServer::listen() {
_server.begin();
};
// process next incoming request, updating provided WebRequest object.
int WebServer::processIncomingRequest(WebRequest& req) {
// get incoming client requests
WiFiClient client = _server.available();
// reset _lineMode
_lineMode = LINE_MODE_REQUEST;
if(client) { // ensure a client is connected
Serial.println("WebServer - processing new request: ");
int i = 0;
int headerIndex = 0;
int contentLength = 0;
while(client.connected() && i < 50) { // ensure connection still open
if(client.available()) { // ensure client stream is available
// parse request line
if(_lineMode == LINE_MODE_REQUEST) {
//read a new line into the buffer
readLine(client);
Serial.println("Processing request line...");
char method[REQ_METHOD_SIZE];
char path[REQ_PATH_SIZE];
char httpVersion[REQ_VERSION_SIZE];
char params[REQ_PARAMS_STR_SIZE];
// process request line
byte res = parseLineRequest(method, path, params, httpVersion);
if(res == PARSE_SUCCESS) {
//print results
Serial.println("Success!!!");
Serial.print("Method: "); Serial.println(method);
Serial.print("Path: "); Serial.println(path);
Serial.print("Params string: "); Serial.println(params);
Serial.print("Version: "); Serial.println(httpVersion);
//assign values on request
req.method = method;
req.path = path;
req.httpVersion = httpVersion;
parseQueryParams(params, req.params);
} else {
Serial.println("FAILED");
}
//set line mode to headers for next iteration
_lineMode = LINE_MODE_HEADER;
// parse header line
} else if (_lineMode == LINE_MODE_HEADER) {
//read a new line into the buffer
readLine(client);
Serial.println("Processing header line...");
char headerKey[REQ_HEADER_NAME_SIZE];
char headerValue[REQ_HEADER_VALUE_SIZE];
// if blank line, switch to body mode and continue loop
if(_lineBuffer[0] == '\r') {
Serial.println("Empty line, switching to body mode");
_lineMode = LINE_MODE_BODY;
continue;
}
//parse line
parseLineHeader(headerKey, headerValue);
//add header to request
HttpHeader h;
h.key = headerKey;
h.value = headerValue;
req.headers[headerIndex] = h;
headerIndex++;
// check for content length header and update local var
if(strcmp(headerKey, "Content-Length") == 0) {
contentLength = h.value.toInt();
Serial.print("Found Content-Length header: ");
Serial.println(contentLength);
}
//print parsed value
Serial.print("Added header - "); Serial.print(h.key); Serial.print(": "); Serial.println(h.value);
//parse body line
} else if (_lineMode == LINE_MODE_BODY) {
Serial.println("Processing body...");
char body[REQ_BODY_SIZE];
memset(body, 0, REQ_BODY_SIZE); // clear body buffer
client.readBytes(body, contentLength);
req.body = String(body);
Serial.println(req.body);
// return the parsed request object, for external handling, make sure to add client first
req.client = client;
return 1;
} // end if (_lineMode == ...)
} //end if (client.available())
i++;
Serial.print("End loop - i = "); Serial.println(i);
} //end while(client.connected())
} //end if (client)
return -1; // return fail if no incoming requests
};
// clear line buffer and read next line
void WebServer::readLine(WiFiClient client) {
memset(_lineBuffer, 0, WS_LINE_BUFFER_SIZE);
client.readBytesUntil(WS_LINE_TERMINATOR, _lineBuffer, WS_LINE_BUFFER_SIZE);
}
// parse the HTTP method, path, and query param strings from the current line in _lineBuffer
byte WebServer::parseLineRequest(char* method, char* path, char* params, char* version) {
// check matches
MatchState ms;
char* regexParams = "^(%u-) (%S-)%?(%S-) (HTTP.*)";
char* regexNoParams = "^(%u-) (%S-) (HTTP.*)";
int res;
int expectedMatches;
ms.Target(_lineBuffer);
if(String(_lineBuffer).indexOf('?') > 0){
res = ms.Match(regexParams);
expectedMatches = 4;
} else {
res = ms.Match(regexNoParams);
expectedMatches = 3;
}
// process results
switch(res) {
case REGEXP_MATCHED: //match
{ // enclosing scope for variables created in this branch of the switch
int matchCount = ms.level;
if(matchCount != expectedMatches) { // unexpected number of matches
Serial.print("Unexpected number of matches when parsing request line: expected = 4, actual = ");
Serial.println(matchCount);
break;
}
//get captured groups
if(expectedMatches == 4) {
ms.GetCapture(method, 0);
ms.GetCapture(path, 1);
ms.GetCapture(params, 2);
ms.GetCapture(version, 3);
} else {
ms.GetCapture(method, 0);
ms.GetCapture(path, 1);
ms.GetCapture(version, 2);
}
return PARSE_SUCCESS;
}
break;
case REGEXP_NOMATCH: //no match
Serial.print("No matches found...");
break;
default: //some sort of error
Serial.print("Error trying to match...");
}
// if we exit the switch statement before returning, that means there was a problem parsing.
return PARSE_FAIL;
};
// Parse query params from string 'paramStr' into the QueryParam array 'dest'
void WebServer::parseQueryParams(char* paramStr, QueryParam* dest) {
bool inKey = true;
char keyBuffer[REQ_PARAMS_STR_SIZE];
char valueBuffer[REQ_PARAMS_STR_SIZE];
QueryParam paramBuffer;
int bufferIndex = 0;
int paramIndex = 0;
//make sure buffers are empty to start
memset(keyBuffer, 0, REQ_PARAMS_STR_SIZE);
memset(valueBuffer, 0, REQ_PARAMS_STR_SIZE);
Serial.println("Parsing query params");
for(int i = 0; i < REQ_PARAMS_STR_SIZE; i++) {
char c = paramStr[i];
Serial.print("Current char: "); Serial.print(c);
//return if reached end of string
if(c == 0x00) {
Serial.println("..end");
//add last from buffer and return
dest[paramIndex] = QueryParam { String(keyBuffer), String(valueBuffer) };
return;
}
if(inKey) { // processing a key
Serial.print("..in key");
if(c == '=') {
Serial.println("..end of key");
// end of key
inKey = false;
bufferIndex = 0;
} else {
Serial.println("..add to buffer");
//add char to keyBuffer, and increment bufferIndex
keyBuffer[bufferIndex] = c;
bufferIndex++;
}
} else { // processing a value
Serial.print("..in value");
if(c == '&') {
Serial.println("..end of value");
// end of value
inKey = true;
//add QueryParam object
dest[paramIndex] = QueryParam { String(keyBuffer), String(valueBuffer) };
//clear buffers
memset(keyBuffer, 0x00, REQ_PARAMS_STR_SIZE);
memset(valueBuffer, 0x00, REQ_PARAMS_STR_SIZE);
//update indices
paramIndex++;
bufferIndex = 0;
} else {
Serial.println("..add to buffer");
//add char to valueBuffer and increment bufferIndex
valueBuffer[bufferIndex] = c;
bufferIndex++;
}
}
}
};
// parse an HTTP header from the current line in _lineBuffer
byte WebServer::parseLineHeader(char* key, char* value) {
MatchState ms;
ms.Target(_lineBuffer);
char res = ms.Match("^(.-): (.*)");
switch(res) {
case REGEXP_MATCHED:
{
int matchCount = ms.level;
if(matchCount != 2) {
Serial.print("Unexpected number of matches when parsing header line: expected = 2, actual = ");
Serial.println(matchCount);
break;
}
//get captured groups
ms.GetCapture(key, 0);
ms.GetCapture(value, 1);
}
break;
case REGEXP_NOMATCH:
Serial.println("No matches found...");
break;
default: //some sort of error
Serial.print("Error trying to match...");
}
// if we exit the switch statement before returning, that means there was a problem parsing.
return PARSE_FAIL;
};
// ==== WebRequest ====
//return a WebResponse object that can be used to reply to the incoming request
WebResponse WebRequest::getResponse() {
//create new response object
WebResponse res;
res.client = client;
res.httpVersion="HTTP/1.1";
//set up default status
res.status = HTTP_OK;
//set up default headers
res.addHeader("Content-Type", "text/plain");
res.addHeader("Server", "Arduino NANO 33 IoT - Snake Tank Controller");
res.addHeader("Connection", "close");
return res;
};
// Update 'dest' with header specified by 'name'
bool WebRequest::getHeader(String name, HttpHeader& dest) {
for(int i = 0; i < REQ_HEADER_COUNT; i++) {
HttpHeader curr = headers[i];
if(curr.key == name) {
dest = curr;
return true;
}
}
return false;
}
// ==== WebResponse ====
// Add new header with floating point value
int WebResponse::addHeader(const char* key, const float value) {
HttpHeader h { key, String(value, 10) };
return addHeader(h);
};
// Add new header with integer value
int WebResponse::addHeader(const char* key, const long value) {
String(value, 10);
char valueStr[32];
itoa(value, valueStr, 10);
HttpHeader h { key, valueStr };
return addHeader(h);
};
// Add a new header to the header list. Returns 1 for success, returns -1 if error.
int WebResponse::addHeader(const char* key, const char* value) {
HttpHeader h { key, value };
return addHeader(h);
};
// Add a new header to the header list. Returns 1 for success, returns -1 if error.
int WebResponse::addHeader(HttpHeader h) {
//make sure we have room
if(_currentHeaderIndex >= REQ_HEADER_COUNT) {
return -1; //return fail
}
//add header
headers[_currentHeaderIndex] = h;
_currentHeaderIndex += 1;
return 1; // return success
};
// Attempt to send the response to the requesting client. Returns -1 for fail, 1 for success.
int WebResponse::send() {
if(client.connected()) {
//send version and status line.
client.println(httpVersion + " " + status);
// calculate content-length header and add
int bodyLen = body.length();
if(bodyLen > 0) {
char bls[5];
itoa(bodyLen, bls, 10);
addHeader("Content-Length", bls);
} else {
addHeader("Content-Length", "0");
}
//send headers
for (int i = 0; i < _currentHeaderIndex; i++) {
HttpHeader h = headers[i];
client.println(h.key + ": " + h.value);
}
client.println(); // empty line to signify end of headers
client.print(body);// send body
delay(20); // wait for client to receive all data
// close connection and return success
client.stop();
return 1;
}
return -1; // client not connected.
}