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

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