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         FCGI_JSONPair("control_state", Control_GetModeName());
298 }
299
300 /**
301  * Adds a key/value pair to a JSON response. The response must have already
302  * been initiated by FCGI_BeginJSON. Special characters are not escaped.
303  * @param key The key of the JSON entry
304  * @param value The value associated with the key.
305  */
306 void FCGI_JSONPair(const char *key, const char *value)
307 {
308         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
309 }
310
311 /**
312  * Similar to FCGI_JSONPair except for signed integer values.
313  * @param key The key of the JSON entry
314  * @param value The value associated with the key
315  */
316 void FCGI_JSONLong(const char *key, long value)
317 {
318         printf(",\r\n\t\"%s\" : %ld", key, value);
319 }
320
321 /**
322  * Similar to FCGI_JsonPair except for floating point values.
323  * @param key The key of the JSON entry
324  * @param value The value associated with the key
325  */
326 void FCGI_JSONDouble(const char *key, double value)
327 {
328         printf(",\r\n\t\"%s\" : %f", key, value);
329 }
330
331 /**
332  * Similar to FCGI_JsonPair except for boolean values.
333  * @param key The key of the JSON entry
334  * @param value The value associated with the key
335  */
336 void FCGI_JSONBool(const char *key, bool value)
337 {
338         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
339 }
340
341 /**
342  * Begins a JSON entry by writing the key. To be used in conjunction
343  * with FCGI_JsonValue.
344  * @param key The key of the JSON entry
345  */
346 void FCGI_JSONKey(const char *key)
347 {
348         printf(",\r\n\t\"%s\" : ", key);
349 }
350
351 /**
352  * Ends a JSON response that was initiated by FCGI_BeginJSON.
353  */
354 void FCGI_EndJSON() 
355 {
356         printf("\r\n}\r\n");
357 }
358
359 /**
360  * To be used when the input parameters are rejected. The return data
361  * will also have debugging information provided.
362  * @param context The context to work in
363  * @param status The status the return data should have.
364  * @param description A short description of why the input was rejected.
365  */
366 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
367 {
368         if (description == NULL)
369                 description = "Unknown";
370         
371         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
372         FCGI_BeginJSON(context, status);
373         FCGI_JSONPair("description", description);
374         FCGI_JSONLong("responsenumber", context->response_number);
375         //FCGI_JSONPair("params", getenv("QUERY_STRING"));
376         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
377         FCGI_JSONPair("user", getenv("REMOTE_USER"));
378         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
379         FCGI_EndJSON();
380 }
381
382 /**
383  * Generates a response to the client as described by the format parameter and
384  * extra arguments (exactly like printf). To be used when none of the other
385  * predefined functions will work exactly as needed. Extra care should be taken
386  * to ensure the correctness of the output.
387  * @param format The format string
388  * @param ... Any extra arguments as required by the format string.
389  */
390 void FCGI_PrintRaw(const char *format, ...)
391 {
392         va_list list;
393         va_start(list, format);
394         vprintf(format, list);
395         va_end(list);
396 }
397
398
399 /**
400  * Write binary data
401  * See fwrite
402  */
403 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
404 {
405         Log(LOGDEBUG,"Writing!");
406         fwrite(data, size, num_elem, stdout);
407 }
408
409 /**
410  * Escapes a string so it can be used safely.
411  * Currently escapes to ensure the validity for use as a JSON string
412  * Does not support unicode specifiers in the form of \uXXXX.
413  * @param buf The string to be escaped
414  * @return The escaped string (return value == buf)
415  */
416 char *FCGI_EscapeText(char *buf)
417 {
418         int length, i;
419         length = strlen(buf);
420         
421         //Escape special characters. Must count down to escape properly
422         for (i = length - 1; i >= 0; i--) {
423                 if (buf[i] < 0x20) { //Control characters
424                         buf[i] = ' ';
425                 } else if (buf[i] == '"') {
426                         if (i-1 >= 0 && buf[i-1] == '\\') 
427                                 i--;
428                         else
429                                 buf[i] = '\'';
430                 } else if (buf[i] == '\\') {
431                         if (i-1 >= 0 && buf[i-1] == '\'')
432                                 i--;
433                         else
434                                 buf[i] = ' ';
435                 }
436         }
437         return buf;
438 }
439
440 /**
441  * Main FCGI request loop that receives/responds to client requests.
442  * @param data Reserved.
443  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
444  * TODO: Get this to exit with the rest of the program!
445  */ 
446 void * FCGI_RequestLoop (void *data)
447 {
448         FCGIContext context = {0};
449         
450         Log(LOGDEBUG, "Start loop");
451         while (FCGI_Accept() >= 0) {
452                 
453                 ModuleHandler module_handler = NULL;
454                 char module[BUFSIZ], params[BUFSIZ];
455                 
456                 //strncpy doesn't zero-truncate properly
457                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
458                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
459
460                 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
461                 
462                 //Remove trailing slashes (if present) from module query
463                 size_t lastchar = strlen(module) - 1;
464                 if (lastchar > 0 && module[lastchar] == '/')
465                         module[lastchar] = 0;
466
467                 //Escape all special characters
468                 FCGI_EscapeText(params);
469
470                 //Default to the 'identify' module if none specified
471                 if (!*module) 
472                         strcpy(module, "identify");
473                 
474                 if (!strcmp("identify", module)) {
475                         module_handler = IdentifyHandler;
476                 } else if (!strcmp("control", module)) {
477                         module_handler = Control_Handler;
478                 } else if (!strcmp("sensors", module)) {
479                         module_handler = Sensor_Handler;
480                 } else if (!strcmp("actuators", module)) {
481                         module_handler = Actuator_Handler;
482                 } else if (!strcmp("image", module)) {
483                         module_handler = Image_Handler;
484                 }
485
486                 context.current_module = module;
487                 if (module_handler) {
488                         module_handler(&context, params);
489                 } else {
490                         FCGI_RejectJSON(&context, "Unhandled module");
491                 }
492                 context.response_number++;
493
494                 
495         }
496
497         Log(LOGDEBUG, "Thread exiting.");
498         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
499         return NULL;
500 }

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