Merge branch 'master' of github:szmoore/MCTX3420
[matches/MCTX3420.git] / server / fastcgi.c
1 /**
2  * @file fastcgi.c
3  * @brief Runs the FCGI request loop to handle web interface requests.
4  *
5  * fcgi_stdio.h must be included before all else so the stdio function
6  * redirection works ok.
7  */
8
9 #include <fcgi_stdio.h>
10 #include <openssl/sha.h>
11 #include <stdarg.h>
12
13 #include "common.h"
14 #include "sensor.h"
15 #include "actuator.h"
16 #include "control.h"
17 #include "options.h"
18
19 /**The time period (in seconds) before the control key expires @ */
20 #define CONTROL_TIMEOUT 180
21
22 /**Contextual information related to FCGI requests*/
23 struct FCGIContext {
24         /**The time of last valid user access possessing the control key*/
25         time_t control_timestamp;
26         char control_key[41];
27         char control_ip[16];
28         /**The name of the current module**/
29         const char *current_module;
30         /**For debugging purposes?**/
31         int response_number;
32 };
33
34 /**
35  * Identifies build information and the current API version to the user.
36  * Also useful for testing that the API is running and identifying the 
37  * sensors and actuators present.
38  * @param context The context to work in
39  * @param params User specified paramters: [actuators, sensors]
40  */ 
41 static void IdentifyHandler(FCGIContext *context, char *params) {
42         bool ident_sensors = false, ident_actuators = false;
43         //const char *key, *value;
44
45         int i;
46
47         FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
48                                          {"actuators", &ident_actuators, FCGI_BOOL_T}};
49
50         if (!FCGI_ParseRequest(context, params, values, 2))
51                 return;
52
53         /*while ((params = FCGI_KeyPair(params, &key, &value))) {
54                 if (!strcmp(key, "sensors")) {
55                         ident_sensors = !ident_sensors;
56                 } else if (!strcmp(key, "actuators")) {
57                         ident_actuators = !ident_actuators;
58                 }
59         }*/
60
61         FCGI_BeginJSON(context, STATUS_OK);
62         FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
63         FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
64         FCGI_JSONLong("api_version", API_VERSION);
65
66         //Sensor and actuator information
67         if (ident_sensors) {
68                 FCGI_JSONKey("sensors");
69                 FCGI_JSONValue("{\n\t\t");
70                 for (i = 0; i < NUMSENSORS; i++) {
71                         if (i > 0) {
72                                 FCGI_JSONValue(",\n\t\t");
73                         }
74                         FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]); 
75                 }
76                 FCGI_JSONValue("\n\t}");
77         }
78         if (ident_actuators) {
79                 FCGI_JSONKey("actuators");
80                 FCGI_JSONValue("{\n\t\t");
81                 for (i = 0; i < NUMACTUATORS; i++) {
82                         if (i > 0) {
83                                 FCGI_JSONValue(",\n\t\t");
84                         }
85                         FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]); 
86                 }
87                 FCGI_JSONValue("\n\t}");
88         }
89         FCGI_EndJSON();
90 }
91
92 /**
93  * Gives the user a key that determines who has control over
94  * the system at any one time. The key can be forcibly generated, revoking
95  * any previous control keys. To be used in conjunction with HTTP 
96  * basic authentication.
97  * This function will generate a JSON response that indicates success/failure.
98  * @param context The context to work in
99  * @param force Whether to force key generation or not.
100  */ 
101 void FCGI_BeginControl(FCGIContext *context, bool force) {
102         time_t now = time(NULL);
103         bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
104         
105         if (force || !*(context->control_key) || expired) {
106                 SHA_CTX sha1ctx;
107                 unsigned char sha1[20];
108                 int i = rand();
109
110                 SHA1_Init(&sha1ctx);
111                 SHA1_Update(&sha1ctx, &now, sizeof(now));
112                 SHA1_Update(&sha1ctx, &i, sizeof(i));
113                 SHA1_Final(sha1, &sha1ctx);
114
115                 context->control_timestamp = now;
116                 for (i = 0; i < 20; i++)
117                         sprintf(context->control_key + i * 2, "%02x", sha1[i]);
118                 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
119                 FCGI_BeginJSON(context, STATUS_OK);
120                 FCGI_JSONPair("key", context->control_key);
121                 FCGI_EndJSON();         
122         } else {
123                 char buf[128];
124                 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
125                         localtime(&(context->control_timestamp))); 
126                 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
127                 FCGI_JSONPair("description", "Another user already has control");
128                 FCGI_JSONPair("current_user", context->control_ip); 
129                 FCGI_JSONPair("when", buf);
130                 FCGI_EndJSON();
131         }
132 }
133
134 /**
135  * Given an FCGIContext, determines if the current user (as specified by
136  * the key) has control or not. If validated, the context control_timestamp is
137  * updated.
138  * @param context The context to work in
139  * @param key The control key to be validated.
140  * @return TRUE if authorized, FALSE if not.
141  */
142 bool FCGI_HasControl(FCGIContext *context, const char *key) {
143         time_t now = time(NULL);
144         int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
145                                  key != NULL && !strcmp(context->control_key, key);
146         if (result) {
147                 context->control_timestamp = now; //Update the control_timestamp
148         }
149         return result;
150 }
151
152
153 /**
154  * Revokes the current control key, if present.
155  * @param context The context to work in
156  */
157 void FCGI_EndControl(FCGIContext *context) {
158         *(context->control_key) = 0;
159         FCGI_BeginJSON(context, STATUS_OK);
160         FCGI_EndJSON();
161         return;
162 }
163
164 /**
165  * Extracts a key/value pair from a request string.
166  * Note that the input is modified by this function.
167  * @param in The string from which to extract the pair
168  * @param key A pointer to a variable to hold the key string
169  * @param value A pointer to a variable to hold the value string
170  * @return A pointer to the start of the next search location, or NULL if
171  *         the EOL is reached.
172  */
173 char *FCGI_KeyPair(char *in, const char **key, const char **value)
174 {
175         char *ptr;
176         if (!in || !*in) { //Invalid input or string is EOL
177                 return NULL;
178         }
179
180         *key = in;
181         //Find either = or &, whichever comes first
182         if ((ptr = strpbrk(in, "=&"))) {
183                 if (*ptr == '&') { //No value specified
184                         *value = ptr;
185                         *ptr++ = 0;
186                 } else {
187                         //Stopped at an '=' sign
188                         *ptr++ = 0;
189                         *value = ptr;
190                         if ((ptr = strchr(ptr,'&'))) {
191                                 *ptr++ = 0;
192                         } else {
193                                 ptr = "";
194                         }
195                 }
196         } else { //No value specified and no other pair
197                 ptr = "";
198                 *value = ptr;
199         }
200         return ptr;
201 }
202
203 /**
204  * Aids in parsing request parameters. Expected keys along with their type
205  * and whether or not they're required are provided. This function will then
206  * parse the parameter string to find these keys.
207  * @param context The context to work in
208  * @param params The parameter string to be parsed
209  * @param values An array of FCGIValue's that specify expected keys
210  * @param count The number of elements in 'values'.
211  * @return true If the parameter string was parsed successfully, false otherwise.
212  *         Modes of failure include: Invalid a parsing error on the value,
213  *                                   an unknown key is specified,
214  *                                   a key/value pair is specified more than once, or
215  *                                   not all required keys were present.
216  *         If this function returns false, it is guaranteed that FCGI_RejectJSON
217  *         has already been called with the appropriate description message.
218  */
219 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
220 {
221         const char *key, *value;
222         char buf[BUFSIZ], *ptr;
223         size_t i;
224         
225         while ((params = FCGI_KeyPair(params, &key, &value))) {
226                 for (i = 0; i < count; i++) {
227                         if (!strcmp(key, values[i].key)) {
228                                 FCGIValue *val = &values[i];
229
230                                 if (FCGI_RECEIVED(val->flags)) {
231                                         snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
232                                         FCGI_RejectJSON(context, buf);
233                                         return false;
234                                 }
235                                 val->flags |= FCGI_PARAM_RECEIVED;
236
237                                 switch(FCGI_TYPE(val->flags)) {
238                                         case FCGI_BOOL_T:
239                                                 *((bool*) val->value) = true;
240                                                 break;
241                                         case FCGI_INT_T: case FCGI_LONG_T: {
242                                                 long parsed = strtol(value, &ptr, 10);
243                                                 if (!*value || *ptr) {
244                                                         snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
245                                                         FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
246                                                         return false;
247                                                 }
248
249                                                 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
250                                                         *((int*) val->value) = parsed;
251                                                 else
252                                                         *((long*) val->value) = parsed;
253                                         }       break;
254                                         case FCGI_DOUBLE_T:
255                                                 *((double*) val->value) = strtod(value, &ptr);
256                                                 if (!*value || *ptr) {
257                                                         snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
258                                                         FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
259                                                         return false;
260                                                 }
261                                                 break;
262                                         case FCGI_STRING_T:
263                                                 *((const char**) val->value) = value;
264                                                 break;
265                                         default:
266                                                 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
267                                 }
268                                 break; //No need to search any more
269                         }
270                 } //End for loop
271                 if (i == count) {
272                         snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
273                         FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
274                         return false;
275                 }
276         }
277
278         //Check that required parameters are received
279         for (i = 0; i < count; i++) {
280                 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
281                         snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
282                         FCGI_RejectJSON(context, buf);
283                         return false;
284                 }
285         }
286         return true;
287 }
288
289 /**
290  * Begins a response to the client in JSON format.
291  * @param context The context to work in.
292  * @param status_code The status code to be returned.
293  */
294 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
295 {
296         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
297         printf("{\r\n");
298         printf("\t\"module\" : \"%s\"", context->current_module);
299         FCGI_JSONLong("status", status_code);
300         //Time and running statistics
301         struct timeval now;
302         gettimeofday(&now, NULL);
303         FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
304         FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
305         FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
306 }
307
308 /**
309  * Adds a key/value pair to a JSON response. The response must have already
310  * been initiated by FCGI_BeginJSON. Special characters are not escaped.
311  * @param key The key of the JSON entry
312  * @param value The value associated with the key.
313  */
314 void FCGI_JSONPair(const char *key, const char *value)
315 {
316         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
317 }
318
319 /**
320  * Similar to FCGI_JSONPair except for signed integer values.
321  * @param key The key of the JSON entry
322  * @param value The value associated with the key
323  */
324 void FCGI_JSONLong(const char *key, long value)
325 {
326         printf(",\r\n\t\"%s\" : %ld", key, value);
327 }
328
329 /**
330  * Similar to FCGI_JsonPair except for floating point values.
331  * @param key The key of the JSON entry
332  * @param value The value associated with the key
333  */
334 void FCGI_JSONDouble(const char *key, double value)
335 {
336         printf(",\r\n\t\"%s\" : %f", key, value);
337 }
338
339 /**
340  * Similar to FCGI_JsonPair except for boolean values.
341  * @param key The key of the JSON entry
342  * @param value The value associated with the key
343  */
344 void FCGI_JSONBool(const char *key, bool value)
345 {
346         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
347 }
348
349 /**
350  * Begins a JSON entry by writing the key. To be used in conjunction
351  * with FCGI_JsonValue.
352  * @param key The key of the JSON entry
353  */
354 void FCGI_JSONKey(const char *key)
355 {
356         printf(",\r\n\t\"%s\" : ", key);
357 }
358
359 /**
360  * Ends a JSON response that was initiated by FCGI_BeginJSON.
361  */
362 void FCGI_EndJSON() 
363 {
364         printf("\r\n}\r\n");
365 }
366
367 /**
368  * Escapes a string so it can be used as a JSON string value.
369  * Does not support unicode specifiers in the form of \uXXXX.
370  * @param buf The string to be escaped
371  * @return The escaped string (return value == buf)
372  */
373 char *FCGI_EscapeJSON(char *buf)
374 {
375         int length, i;
376         length = strlen(buf);
377         
378         //Escape special characters. Must count down to escape properly
379         for (i = length - 1; i >= 0; i--) {
380                 if (buf[i] < 0x20) { //Control characters
381                         buf[i] = ' ';
382                 } else if (buf[i] == '"') {
383                         if (i-1 >= 0 && buf[i-1] == '\\') 
384                                 i--;
385                         else
386                                 buf[i] = '\'';
387                 } else if (buf[i] == '\\') {
388                         if (i-1 >= 0 && buf[i-1] == '\'')
389                                 i--;
390                         else
391                                 buf[i] = ' ';
392                 }
393         }
394         return buf;
395 }
396
397 /**
398  * To be used when the input parameters are rejected. The return data
399  * will also have debugging information provided.
400  * @param context The context to work in
401  * @param status The status the return data should have.
402  * @param description A short description of why the input was rejected.
403  */
404 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
405 {
406         if (description == NULL)
407                 description = "Unknown";
408         
409         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
410         FCGI_BeginJSON(context, status);
411         FCGI_JSONPair("description", description);
412         FCGI_JSONLong("responsenumber", context->response_number);
413         FCGI_JSONPair("params", getenv("QUERY_STRING"));
414         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
415         FCGI_JSONPair("user", getenv("REMOTE_USER"));
416         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
417         FCGI_EndJSON();
418 }
419
420 /**
421  * Generates a response to the client as described by the format parameter and
422  * extra arguments (exactly like printf). To be used when none of the other
423  * predefined functions will work exactly as needed. Extra care should be taken
424  * to ensure the correctness of the output.
425  * @param format The format string
426  * @param ... Any extra arguments as required by the format string.
427  */
428 void FCGI_PrintRaw(const char *format, ...)
429 {
430         va_list list;
431         va_start(list, format);
432         vprintf(format, list);
433         va_end(list);
434 }
435
436 /**
437  * Main FCGI request loop that receives/responds to client requests.
438  * @param data Reserved.
439  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
440  * TODO: Get this to exit with the rest of the program!
441  */ 
442 void * FCGI_RequestLoop (void *data)
443 {
444         FCGIContext context = {0};
445         
446         Log(LOGDEBUG, "First request...");
447         while (FCGI_Accept() >= 0) {
448                 Log(LOGDEBUG, "Got request #%d", context.response_number);
449                 ModuleHandler module_handler = NULL;
450                 char module[BUFSIZ], params[BUFSIZ];
451                 
452                 //strncpy doesn't zero-truncate properly
453                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
454                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
455                 
456                 //Remove trailing slashes (if present) from module query
457                 size_t lastchar = strlen(module) - 1;
458                 if (lastchar > 0 && module[lastchar] == '/')
459                         module[lastchar] = 0;
460
461                 //Default to the 'identify' module if none specified
462                 if (!*module) 
463                         strcpy(module, "identify");
464                 
465                 if (!strcmp("identify", module)) {
466                         module_handler = IdentifyHandler;
467                 } else if (!strcmp("control", module)) {
468                         module_handler = Control_Handler;
469                 } else if (!strcmp("sensors", module)) {
470                         module_handler = Sensor_Handler;
471                 } else if (!strcmp("actuators", module)) {
472                         module_handler = Actuator_Handler;
473                 }
474
475                 context.current_module = module;
476                 if (module_handler) {
477                         module_handler(&context, params);
478                 } else {
479                         FCGI_RejectJSON(&context, "Unhandled module");
480                 }
481                 context.response_number++;
482
483                 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
484         }
485
486         Log(LOGDEBUG, "Thread exiting.");
487         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
488         return NULL;
489 }

UCC git Repository :: git.ucc.asn.au