This repository has been archived by the owner on Jan 26, 2024. It is now read-only.
/
http.c
364 lines (294 loc) · 9.99 KB
/
http.c
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
/*
* BitMeterOS
* http://codebox.org.uk/bitmeterOS
*
* Copyright (c) 2011 Rob Dawson
*
* Licensed under the GNU General Public License
* http://www.gnu.org/licenses/gpl.txt
*
* This file is part of BitMeterOS.
*
* BitMeterOS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BitMeterOS 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BitMeterOS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _WIN32
#define __USE_MINGW_ANSI_STDIO 1
#endif
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "bmws.h"
#include "common.h"
/*
Contains HTTP-related functions, mostly for reading in requests and writing out responses.
*/
static struct HttpResponse HTTP_OK = {200, "OK"};
static struct HttpResponse HTTP_SEE_OTHER = {303, "See Other"};
static struct HttpResponse HTTP_NOT_FOUND = {404, "Not Found"};
static struct HttpResponse HTTP_FORBIDDEN = {403, "Forbidden"};
static struct HttpResponse HTTP_NOT_ALLOWED = {405, "Method not allowed"};
static struct HttpResponse HTTP_SERVER_ERROR = {500, "Bad/missing parameter"};
static void writeHeaders(SOCKET fd, struct HttpResponse response, char* contentType, int endHeaders);
extern struct serverInfo ServerInfo;
// These are the different operations that we can perform on behalf of the client
enum OpType{File, Monitor, Summary, Query, Sync, Config, Alert, Export, RSS, MobileMonitor, MobileSummary, MobileAbout};
void writeHeader(SOCKET fd, char* name, char* value){
// Helper function, writes out a single HTTP header with the appropriate separator and line terminator
char buffer[SMALL_BUFSIZE];
sprintf(buffer, "%s: %s" HTTP_EOL, name, value);
writeText(fd, buffer);
}
static void writeMimeType(SOCKET fd, char* contentType){
writeHeader(fd, HEADER_CONTENT_TYPE, contentType);
}
static void writeResponseCode(SOCKET fd, struct HttpResponse response){
// Writes out the first line of a response, including the HTTP response code and message
char buffer[SMALL_BUFSIZE];
sprintf(buffer,"HTTP/1.0 %d %s" HTTP_EOL, response.code, response.msg);
writeText(fd, buffer);
}
static void writeCommonHeaders(SOCKET fd){
// We send these out on every response
writeHeader(fd, "Server", "BitMeterOS " VERSION " Web Server");
char dateTxt[32];
time_t now = getTime();
strftime(dateTxt, sizeof(dateTxt), "%a, %d %b %Y %H:%M:%S +0000", gmtime(&now));
writeHeader(fd, "Date", dateTxt);
writeHeader(fd, "Connection", "Close");
}
void writeEndOfHeaders(SOCKET fd){
char* buffer = HTTP_EOL;
writeText(fd, buffer);
}
void writeHeadersNotFound(SOCKET fd, char* file){
logMsg(LOG_ERR, "%s: %s", HTTP_NOT_FOUND.msg, file);
writeHeaders(fd, HTTP_NOT_FOUND, NULL, TRUE);
}
void writeHeadersForbidden(SOCKET fd, char* request){
logMsg(LOG_ERR, "%s: %s", HTTP_FORBIDDEN.msg, request);
writeHeaders(fd, HTTP_FORBIDDEN, NULL, TRUE);
}
void writeHeadersNotAllowed(SOCKET fd, char* httpMethod){
logMsg(LOG_ERR, "%s: %s", HTTP_NOT_ALLOWED.msg, httpMethod);
writeHeaders(fd, HTTP_NOT_ALLOWED, NULL, FALSE);
}
void writeHeadersServerError(SOCKET fd, char* msg, ...){
va_list argp;
va_start(argp, msg);
vlogMsg(LOG_ERR, msg, argp);
va_end(argp);
writeHeaders(fd, HTTP_SERVER_ERROR, NULL, TRUE);
}
void writeHeadersOk(SOCKET fd, char* contentType, int endHeaders){
writeHeaders(fd, HTTP_OK, contentType, endHeaders);
}
void writeHeadersSeeOther(SOCKET fd, char* newPath, int endHeaders){
writeHeaders(fd, HTTP_SEE_OTHER, newPath, endHeaders);
}
static void writeHeaders(SOCKET fd, struct HttpResponse response, char* contentType, int endHeaders){
// Writes out a full set of headers including the specified HTTP response and, if appropriate, the MIME type
writeResponseCode(fd, response);
if (response.code == HTTP_OK.code && contentType != NULL){
// Only need this if we are returning some content
writeMimeType(fd, contentType);
}
if (response.code == HTTP_SEE_OTHER.code && contentType != NULL){
char newLocation[SMALL_BUFSIZE];
sprintf(newLocation, "http://%s:%d%s", ServerInfo.hostname, ServerInfo.port, contentType);
writeHeader(fd, "Location", newLocation);
}
writeCommonHeaders(fd);
if (endHeaders){
writeEndOfHeaders(fd);
}
}
void processRequest(SOCKET fd, char* buffer, int allowAdmin){
// Examine the request, and hand it off to the appropriate handler
struct Request* req = parseRequest(buffer);
if (strcmp(req->method, "GET") == 0) {
enum OpType op;
if (strcmp(req->path, "/monitor") == 0){
op = Monitor;
} else if (strcmp(req->path, "/summary") == 0){
op = Summary;
} else if (strcmp(req->path, "/query") == 0){
op = Query;
} else if (strcmp(req->path, "/sync") == 0){
op = Sync;
} else if (strcmp(req->path, "/config") == 0){
op = Config;
} else if (strcmp(req->path, "/export") == 0){
op = Export;
} else if (strcmp(req->path, "/alert") == 0){
op = Alert;
} else if (strcmp(req->path, "/rss.xml") == 0){
op = RSS;
} else if (strcmp(req->path, "/m/monitor") == 0) {
op = MobileMonitor;
} else if (strcmp(req->path, "/m/summary") == 0) {
op = MobileSummary;
} else if (strcmp(req->path, "/m/about") == 0) {
op = MobileAbout;
} else {
op = File;
}
#ifdef _WIN32
waitForMutex();
#endif
int needsDb = ((op != File) || (strcmp(req->path, "/") == 0));
// Special handling if someone only requested the index dir
if (needsDb){
// The client isn't asking for a file, so we will need a database connection to complete the request
openDb();
}
// Call the appropriate request handler
if (op == Monitor){
processMonitorRequest(fd, req);
} else if (op == Summary){
processSummaryRequest(fd, req);
} else if (op == Query){
processQueryRequest(fd, req);
} else if (op == Sync){
processSyncRequest(fd, req);
} else if (op == Config){
processConfigRequest(fd, req, allowAdmin);
} else if (op == Export){
processExportRequest(fd, req);
} else if (op == Alert){
processAlertRequest(fd, req, allowAdmin);
} else if (op == RSS){
processRssRequest(fd, req);
} else if (op == MobileMonitor){
processMobileMonitorRequest(fd, req);
} else if (op == MobileSummary){
processMobileSummaryRequest(fd, req);
} else if (op == MobileAbout){
struct NameValuePair pair = {"version", VERSION, NULL};
processFileRequest(fd, req, &pair);
} else if (op == File){
processFileRequest(fd, req, NULL);
} else {
assert(FALSE);
}
if (needsDb){
// Clean up
closeDb();
}
#ifdef _WIN32
releaseMutex();
#endif
} else {
// Only GET requests are allowed - send an error
writeHeadersNotAllowed(fd, req->method);
writeHeader(fd, "Allow", "GET");
writeEndOfHeaders(fd);
}
freeRequest(req);
}
void writeText(SOCKET fd, char* txt){
// Helper function, computes the length of the text for us
writeData(fd, txt, strlen(txt));
}
void writeData(SOCKET fd, char* data, int len){
#ifdef TESTING
write(fd, data, len);
#ifndef _WIN32
fsync(fd);
#endif
#else
send(fd, data, len, 0);
#endif
}
void writeDataToJson(SOCKET fd, struct Data* data){
// Converts the Data struct into an JSON array and writes it out to the stream
writeText(fd, "[");
int i=0;
while (data != NULL) {
if (i++ > 0){
writeText(fd, ",");
}
writeSingleDataToJson(fd, data);
data = data->next;
}
writeText(fd, "]");
}
void writeSingleDataToJson(SOCKET fd, struct Data* data){
char jsonBuffer[SMALL_BUFSIZE];
writeText(fd, "{");
if (data != NULL){
sprintf(jsonBuffer, "\"dl\": %llu,\"ul\": %llu,\"ts\": %d,\"dr\": %d", data->dl, data->ul, (int)data->ts, data->dr);
writeText(fd, jsonBuffer);
}
writeText(fd, "}");
}
void writeTextArrayToJson(SOCKET fd, char* key, char** values){
if (key != NULL){
writeText(fd, "\"");
writeText(fd, key);
writeText(fd, "\" : ");
}
writeText(fd, "[");
int firstItem = TRUE;
while (*values != NULL){
if (!firstItem) {
writeText(fd, ",");
}
firstItem = FALSE;
writeText(fd, "\"");
writeText(fd, *values);
writeText(fd, "\"");
values++;
}
writeText(fd, "]");
}
void writeTextValueToJson(SOCKET fd, char* key, char* value){
char jsonBuffer[SMALL_BUFSIZE];
if (strlen(key) + strlen(value) + 8 > SMALL_BUFSIZE){
logMsg(LOG_ERR, "Input values too large for buffer, key='%s' value='%s'", key, value);
} else {
sprintf(jsonBuffer, "\"%s\" : \"%s\"", key, value);
writeText(fd, jsonBuffer);
}
}
void writeNumValueToJson(SOCKET fd, char* key, BW_INT value){
char jsonBuffer[SMALL_BUFSIZE];
if (strlen(key) + 40 > SMALL_BUFSIZE) {
logMsg(LOG_ERR, "Input values too large for buffer, key='%s' value=%llu", key, value);
} else {
sprintf(jsonBuffer, "\"%s\" : %llu", key, value);
writeText(fd, jsonBuffer);
}
}
void writeSyncData(SOCKET fd, struct Data* data){
char row[SMALL_BUFSIZE];
sprintf(row, "%d,%d,%llu,%llu,%s" HTTP_EOL, (int)data->ts, data->dr, data->dl, data->ul, data->ad);
writeText(fd, row);
}
#ifdef _WIN32
HANDLE mutex = NULL;
void initMutex(){
assert(mutex == NULL);
mutex = CreateMutex(NULL, FALSE, "Mutex");
}
void waitForMutex(){
assert(mutex != NULL);
WaitForSingleObject(mutex, INFINITE);
}
void releaseMutex(){
assert(mutex != NULL);
ReleaseMutex(mutex);
}
#endif