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

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