Update fastcgi bool type
[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                                                 if (!*value) //No value: Default true
231                                                         *((bool*) val->value) = true;
232                                                 else {
233                                                         *((bool*) val->value) = !!(strtol(value, &ptr, 10));
234                                                         if (*ptr) {
235                                                                 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
236                                                                 FCGI_RejectJSON(context, buf);
237                                                                 return false;
238                                                         }
239                                                 }
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, buf);
246                                                         return false;
247                                                 }
248
249                                                 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
250                                                         *((int*) val->value) = (int) 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, 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, 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         FCGI_JSONPair("control_state", Control_GetModeName());
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  * To be used when the input parameters are rejected. The return data
370  * will also have debugging information provided.
371  * @param context The context to work in
372  * @param status The status the return data should have.
373  * @param description A short description of why the input was rejected.
374  */
375 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
376 {
377         if (description == NULL)
378                 description = "Unknown";
379         
380         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
381         FCGI_BeginJSON(context, status);
382         FCGI_JSONPair("description", description);
383         FCGI_JSONLong("responsenumber", context->response_number);
384         //FCGI_JSONPair("params", getenv("QUERY_STRING"));
385         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
386         FCGI_JSONPair("user", getenv("REMOTE_USER"));
387         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
388         FCGI_EndJSON();
389 }
390
391 /**
392  * Generates a response to the client as described by the format parameter and
393  * extra arguments (exactly like printf). To be used when none of the other
394  * predefined functions will work exactly as needed. Extra care should be taken
395  * to ensure the correctness of the output.
396  * @param format The format string
397  * @param ... Any extra arguments as required by the format string.
398  */
399 void FCGI_PrintRaw(const char *format, ...)
400 {
401         va_list list;
402         va_start(list, format);
403         vprintf(format, list);
404         va_end(list);
405 }
406
407
408 /**
409  * Write binary data
410  * See fwrite
411  */
412 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
413 {
414         Log(LOGDEBUG,"Writing!");
415         fwrite(data, size, num_elem, stdout);
416 }
417
418 /**
419  * Escapes a string so it can be used safely.
420  * Currently escapes to ensure the validity for use as a JSON string
421  * Does not support unicode specifiers in the form of \uXXXX.
422  * @param buf The string to be escaped
423  * @return The escaped string (return value == buf)
424  */
425 char *FCGI_EscapeText(char *buf)
426 {
427         int length, i;
428         length = strlen(buf);
429         
430         //Escape special characters. Must count down to escape properly
431         for (i = length - 1; i >= 0; i--) {
432                 if (buf[i] < 0x20) { //Control characters
433                         buf[i] = ' ';
434                 } else if (buf[i] == '"') {
435                         if (i-1 >= 0 && buf[i-1] == '\\') 
436                                 i--;
437                         else
438                                 buf[i] = '\'';
439                 } else if (buf[i] == '\\') {
440                         if (i-1 >= 0 && buf[i-1] == '\'')
441                                 i--;
442                         else
443                                 buf[i] = ' ';
444                 }
445         }
446         return buf;
447 }
448
449 /**
450  * Main FCGI request loop that receives/responds to client requests.
451  * @param data Reserved.
452  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
453  * TODO: Get this to exit with the rest of the program!
454  */ 
455 void * FCGI_RequestLoop (void *data)
456 {
457         FCGIContext context = {0};
458         
459         Log(LOGDEBUG, "Start loop");
460         while (FCGI_Accept() >= 0) {
461                 
462                 ModuleHandler module_handler = NULL;
463                 char module[BUFSIZ], params[BUFSIZ];
464                 
465                 //strncpy doesn't zero-truncate properly
466                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
467                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
468
469                 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
470                 
471                 //Remove trailing slashes (if present) from module query
472                 size_t lastchar = strlen(module) - 1;
473                 if (lastchar > 0 && module[lastchar] == '/')
474                         module[lastchar] = 0;
475
476                 //Escape all special characters
477                 FCGI_EscapeText(params);
478
479                 //Default to the 'identify' module if none specified
480                 if (!*module) 
481                         strcpy(module, "identify");
482                 
483                 if (!strcmp("identify", module)) {
484                         module_handler = IdentifyHandler;
485                 } else if (!strcmp("control", module)) {
486                         module_handler = Control_Handler;
487                 } else if (!strcmp("sensors", module)) {
488                         module_handler = Sensor_Handler;
489                 } else if (!strcmp("actuators", module)) {
490                         module_handler = Actuator_Handler;
491                 } else if (!strcmp("image", module)) {
492                         module_handler = Image_Handler;
493                 }
494
495                 context.current_module = module;
496                 if (module_handler) {
497                         module_handler(&context, params);
498                 } else {
499                         FCGI_RejectJSON(&context, "Unhandled module");
500                 }
501                 context.response_number++;
502
503                 
504         }
505
506         Log(LOGDEBUG, "Thread exiting.");
507         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
508         return NULL;
509 }

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