Merge remote-tracking branch 'upstream/master'
[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 #include <sys/types.h>
13 #include <sys/stat.h>
14
15 #include "common.h"
16 #include "sensor.h"
17 #include "actuator.h"
18 #include "control.h"
19 #include "options.h"
20 #include "image.h"
21 #include "pin_test.h"
22 #include "login.h"
23
24 /**The time period (in seconds) before the control key expires */
25 #define CONTROL_TIMEOUT 180
26
27
28
29 /**
30  * Identifies build information and the current API version to the user.
31  * Also useful for testing that the API is running and identifying the 
32  * sensors and actuators present.
33  * @param context The context to work in
34  * @param params User specified paramters: [actuators, sensors]
35  */ 
36 static void IdentifyHandler(FCGIContext *context, char *params) {
37         bool ident_sensors = false, ident_actuators = false;
38         char control_key[CONTROL_KEY_BUFSIZ];
39         bool has_control;
40         int i;
41
42         snprintf(control_key, CONTROL_KEY_BUFSIZ, "%s", getenv("COOKIE_STRING"));
43         has_control = FCGI_HasControl(context, control_key);
44         
45         FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
46                                          {"actuators", &ident_actuators, FCGI_BOOL_T}};
47         if (!FCGI_ParseRequest(context, params, values, 2))
48                 return;
49
50         FCGI_BeginJSON(context, STATUS_OK);
51         FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
52         FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
53         struct timespec t;
54         t.tv_sec = 0; t.tv_nsec = 0;
55         clock_getres(CLOCK_MONOTONIC, &t);
56         FCGI_JSONDouble("clock_getres", TIMEVAL_TO_DOUBLE(t));
57         FCGI_JSONLong("api_version", API_VERSION);
58         FCGI_JSONBool("logged_in", has_control);
59         FCGI_JSONPair("user_name", has_control ? context->user_name : "");
60         
61
62         //Sensor and actuator information
63         if (ident_sensors) {
64                 FCGI_JSONKey("sensors");
65                 FCGI_JSONValue("{\n\t\t");
66                 for (i = 0; i < g_num_sensors; i++) {
67                         if (i > 0) {
68                                 FCGI_JSONValue(",\n\t\t");
69                         }
70                         FCGI_JSONValue("\"%d\" : \"%s\"", i, Sensor_GetName(i)); 
71                 }
72                 FCGI_JSONValue("\n\t}");
73         }
74         if (ident_actuators) {
75                 FCGI_JSONKey("actuators");
76                 FCGI_JSONValue("{\n\t\t");
77                 for (i = 0; i < g_num_actuators; i++) {
78                         if (i > 0) {
79                                 FCGI_JSONValue(",\n\t\t");
80                         }
81                         FCGI_JSONValue("\"%d\" : \"%s\"", i, Actuator_GetName(i)); 
82                 }
83                 FCGI_JSONValue("\n\t}");
84         }
85         FCGI_EndJSON();
86 }
87
88 /**
89  * Given an authorised user, attempt to set the control over the system.
90  * Modifies members in the context structure appropriately if successful.
91  * @param context The context to work in
92  * @param user_name - Name of the user
93  * @param user_type - Type of the user, passed after successful authentication
94  * @return true on success, false otherwise (eg someone else  already in control)
95  */
96 bool FCGI_LockControl(FCGIContext *context, const char * user_name, UserType user_type) 
97 {
98         // Get current time
99         time_t now = time(NULL);
100         bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
101         int i;
102
103         // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
104         if (user_type == USER_UNAUTH || 
105                 (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
106                 return false;
107
108         // Release any existing control (if any)
109         FCGI_ReleaseControl(context);
110
111         // Set timestamp
112         context->control_timestamp = now;
113
114         // Generate a SHA1 hash for the user
115         SHA_CTX sha1ctx;
116         unsigned char sha1[20];
117         i = rand();
118         SHA1_Init(&sha1ctx);
119         SHA1_Update(&sha1ctx, &now, sizeof(now));
120         SHA1_Update(&sha1ctx, &i, sizeof(i));
121         SHA1_Final(sha1, &sha1ctx);
122         for (i = 0; i < sizeof(sha1); i++)
123                 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
124
125         // Set the IPv4 address
126         snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
127
128         // Set the user name
129         int uname_len = strlen(user_name);
130         i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
131         if (i < uname_len) {
132                 Log(LOGERR, "Username at %d characters too long (limit %d)", 
133                         uname_len, sizeof(context->user_name));
134                 return false; // :-(
135         }
136         // Set the user type
137         context->user_type = user_type;
138
139         // Build the user directory
140         i = snprintf(context->user_dir, sizeof(context->user_dir), "%s/%s", 
141                                         g_options.experiment_dir, context->user_name);
142         if (i >= sizeof(context->user_dir)) {
143                 Log(LOGERR, "Experiment dir too long (required %d, limit %d)",
144                         i, sizeof(context->user_dir));
145                 return false;
146         }
147
148         Log(LOGDEBUG, "User dir: %s", context->user_dir);
149         // Create directory
150         if (mkdir(context->user_dir, 0777) != 0 && errno != EEXIST)
151         {
152                 Log(LOGERR, "Couldn't create user directory %s - %s", 
153                         context->user_dir, strerror(errno));
154                 return false; // :-(
155         }
156
157         return true; // :-)
158 }
159
160 /**
161  * Given an FCGIContext, determines if the current user (as specified by
162  * the key) has control or not. If validated, the context control_timestamp is
163  * updated.
164  * @param context The context to work in
165  * @param key The control key to be validated.
166  * @return TRUE if authorized, FALSE if not.
167  */
168 bool FCGI_HasControl(FCGIContext *context, const char *key) {
169         time_t now = time(NULL);
170         int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
171                         key != NULL && context->control_key[0] != '\0' &&
172                         !strcmp(context->control_key, key);
173         if (result) {
174                 context->control_timestamp = now; //Update the control_timestamp
175         }
176         return result;
177 }
178
179
180 /**
181  * Revokes the current control key, if present.
182  * @param context The context to work in
183  */
184 void FCGI_ReleaseControl(FCGIContext *context) {
185         *(context->control_key) = 0;
186         // Note: context->user_name should *not* be cleared
187         return;
188 }
189
190 /**
191  * Extracts a key/value pair from a request string.
192  * Note that the input is modified by this function.
193  * @param in The string from which to extract the pair
194  * @param key A pointer to a variable to hold the key string
195  * @param value A pointer to a variable to hold the value string
196  * @return A pointer to the start of the next search location, or NULL if
197  *         the EOL is reached.
198  */
199 char *FCGI_KeyPair(char *in, const char **key, const char **value)
200 {
201         char *ptr;
202         if (!in || !*in) { //Invalid input or string is EOL
203                 return NULL;
204         }
205
206         *key = in;
207         //Find either = or &, whichever comes first
208         if ((ptr = strpbrk(in, "=&"))) {
209                 if (*ptr == '&') { //No value specified
210                         *value = ptr;
211                         *ptr++ = 0;
212                 } else {
213                         //Stopped at an '=' sign
214                         *ptr++ = 0;
215                         *value = ptr;
216                         if ((ptr = strchr(ptr,'&'))) {
217                                 *ptr++ = 0;
218                         } else {
219                                 ptr = "";
220                         }
221                 }
222         } else { //No value specified and no other pair
223                 ptr = "";
224                 *value = ptr;
225         }
226         return ptr;
227 }
228
229 /**
230  * Aids in parsing request parameters. 
231  * Input: The expected keys along with their type and whether or not
232  * they're required.
233  * @param context The context to work in
234  * @param params The parameter string to be parsed
235  * @param values An array of FCGIValue's that specify expected keys
236  * @param count The number of elements in 'values'.
237  * @return true If the parameter string was parsed successfully, false otherwise.
238  *         Modes of failure include: Invalid a parsing error on the value,
239  *                                   an unknown key is specified,
240  *                                   a key/value pair is specified more than once, or
241  *                                   not all required keys were present.
242  *         If this function returns false, it is guaranteed that FCGI_RejectJSON
243  *         has already been called with the appropriate description message.
244  */
245 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
246 {
247         const char *key, *value;
248         char buf[BUFSIZ], *ptr;
249         size_t i;
250         
251         while ((params = FCGI_KeyPair(params, &key, &value))) {
252                 for (i = 0; i < count; i++) {
253                         if (!strcmp(key, values[i].key)) {
254                                 FCGIValue *val = &values[i];
255
256                                 if (FCGI_RECEIVED(val->flags)) {
257                                         snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
258                                         FCGI_RejectJSON(context, buf);
259                                         return false;
260                                 }
261                                 val->flags |= FCGI_PARAM_RECEIVED;
262
263                                 switch(FCGI_TYPE(val->flags)) {
264                                         case FCGI_BOOL_T:
265                                                 if (!*value) //No value: Default true
266                                                         *((bool*) val->value) = true;
267                                                 else {
268                                                         *((bool*) val->value) = !!(strtol(value, &ptr, 10));
269                                                         if (*ptr) {
270                                                                 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
271                                                                 FCGI_RejectJSON(context, buf);
272                                                                 return false;
273                                                         }
274                                                 }
275                                                 break;
276                                         case FCGI_INT_T: case FCGI_LONG_T: {
277                                                 long parsed = strtol(value, &ptr, 10);
278                                                 if (!*value || *ptr) {
279                                                         snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
280                                                         FCGI_RejectJSON(context, buf);
281                                                         return false;
282                                                 }
283
284                                                 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
285                                                         *((int*) val->value) = (int) parsed;
286                                                 else
287                                                         *((long*) val->value) = parsed;
288                                         }       break;
289                                         case FCGI_DOUBLE_T:
290                                                 *((double*) val->value) = strtod(value, &ptr);
291                                                 if (!*value || *ptr) {
292                                                         snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
293                                                         FCGI_RejectJSON(context, buf);
294                                                         return false;
295                                                 }
296                                                 break;
297                                         case FCGI_STRING_T:
298                                                 *((const char**) val->value) = value;
299                                                 break;
300                                         default:
301                                                 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
302                                 }
303                                 break; //No need to search any more
304                         }
305                 } //End for loop
306                 if (i == count) {
307                         snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
308                         FCGI_RejectJSON(context, buf);
309                         return false;
310                 }
311         }
312
313         //Check that required parameters are received
314         for (i = 0; i < count; i++) {
315                 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
316                         snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
317                         FCGI_RejectJSON(context, buf);
318                         return false;
319                 }
320         }
321         return true;
322 }
323
324 /**
325  * Begins a response to the client in JSON format.
326  * @param context The context to work in.
327  * @param status_code The status code to be returned.
328  */
329 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
330 {
331         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
332         printf("{\r\n");
333         printf("\t\"module\" : \"%s\"", context->current_module);
334         FCGI_JSONLong("status", status_code);
335         //Time and running statistics
336         struct timespec now;
337         clock_gettime(CLOCK_MONOTONIC, &now);
338         FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
339         FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
340         FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
341         FCGI_JSONPair("control_state", Control_GetModeName());
342 }
343
344 /**
345  * Generic accept response in JSON format.
346  * @param context The context to work in
347  * @param description A short description.
348  * @param cookie Optional. If given, the cookie field is set to that value.
349  */
350 void FCGI_AcceptJSON(FCGIContext *context, const char *description, const char *cookie)
351 {
352         printf("Content-type: application/json; charset=utf-8\r\n");
353         if (cookie) {
354                 printf("Set-Cookie: %s\r\n", cookie);
355         }
356         printf("\r\n{\r\n");
357         printf("\t\"module\" : \"%s\"", context->current_module);
358         FCGI_JSONLong("status", STATUS_OK);
359         FCGI_JSONPair("description", description);
360         FCGI_EndJSON();
361 }
362
363 /**
364  * Adds a key/value pair to a JSON response. The response must have already
365  * been initiated by FCGI_BeginJSON. Special characters are not escaped.
366  * @param key The key of the JSON entry
367  * @param value The value associated with the key.
368  */
369 void FCGI_JSONPair(const char *key, const char *value)
370 {
371         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
372 }
373
374 /**
375  * Similar to FCGI_JSONPair except for signed integer values.
376  * @param key The key of the JSON entry
377  * @param value The value associated with the key
378  */
379 void FCGI_JSONLong(const char *key, long value)
380 {
381         printf(",\r\n\t\"%s\" : %ld", key, value);
382 }
383
384 /**
385  * Similar to FCGI_JsonPair except for floating point values.
386  * @param key The key of the JSON entry
387  * @param value The value associated with the key
388  */
389 void FCGI_JSONDouble(const char *key, double value)
390 {
391         printf(",\r\n\t\"%s\" : %.9f", key, value);
392 }
393
394 /**
395  * Similar to FCGI_JsonPair except for boolean values.
396  * @param key The key of the JSON entry
397  * @param value The value associated with the key
398  */
399 void FCGI_JSONBool(const char *key, bool value)
400 {
401         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
402 }
403
404 /**
405  * Begins a JSON entry by writing the key. To be used in conjunction
406  * with FCGI_JsonValue.
407  * @param key The key of the JSON entry
408  */
409 void FCGI_JSONKey(const char *key)
410 {
411         printf(",\r\n\t\"%s\" : ", key);
412 }
413
414 /**
415  * Ends a JSON response that was initiated by FCGI_BeginJSON.
416  */
417 void FCGI_EndJSON() 
418 {
419         printf("\r\n}\r\n");
420 }
421
422 /**
423  * To be used when the input parameters are rejected. The return data
424  * will also have debugging information provided.
425  * @param context The context to work in
426  * @param status The status the return data should have.
427  * @param description A short description of why the input was rejected.
428  */
429 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
430 {
431         if (description == NULL)
432                 description = "Unknown";
433         
434         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
435         FCGI_BeginJSON(context, status);
436         FCGI_JSONPair("description", description);
437         FCGI_JSONLong("responsenumber", context->response_number);
438         //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
439         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
440         FCGI_JSONPair("user", getenv("REMOTE_USER"));
441         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
442         FCGI_EndJSON();
443 }
444
445 /**
446  * Generates a response to the client as described by the format parameter and
447  * extra arguments (exactly like printf). To be used when none of the other
448  * predefined functions will work exactly as needed. Extra care should be taken
449  * to ensure the correctness of the output.
450  * @param format The format string
451  * @param ... Any extra arguments as required by the format string.
452  */
453 void FCGI_PrintRaw(const char *format, ...)
454 {
455         va_list list;
456         va_start(list, format);
457         vprintf(format, list);
458         va_end(list);
459 }
460
461
462 /**
463  * Write binary data
464  * See fwrite
465  */
466 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
467 {
468         Log(LOGDEBUG,"Writing!");
469         fwrite(data, size, num_elem, stdout);
470 }
471
472 /**
473  * Escapes a string so it can be used safely.
474  * Currently escapes to ensure the validity for use as a JSON string
475  * Does not support unicode specifiers in the form of \uXXXX.
476  * @param buf The string to be escaped
477  * @return The escaped string (return value == buf)
478  */
479 char *FCGI_EscapeText(char *buf)
480 {
481         int length, i;
482         length = strlen(buf);
483         
484         //Escape special characters. Must count down to escape properly
485         for (i = length - 1; i >= 0; i--) {
486                 if (buf[i] < 0x20) { //Control characters
487                         buf[i] = ' ';
488                 } else if (buf[i] == '"') {
489                         if (i-1 >= 0 && buf[i-1] == '\\') 
490                                 i--;
491                         else
492                                 buf[i] = '\'';
493                 } else if (buf[i] == '\\') {
494                         if (i-1 >= 0 && buf[i-1] == '\'')
495                                 i--;
496                         else
497                                 buf[i] = ' ';
498                 }
499         }
500         return buf;
501 }
502
503 /**
504  * Main FCGI request loop that receives/responds to client requests.
505  * @param data Reserved.
506  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
507  * TODO: Get this to exit with the rest of the program!
508  */ 
509 void * FCGI_RequestLoop (void *data)
510 {
511         FCGIContext context = {0};
512         
513         Log(LOGDEBUG, "Start loop");
514         while (FCGI_Accept() >= 0) {
515                 
516                 ModuleHandler module_handler = NULL;
517                 char module[BUFSIZ], params[BUFSIZ], control_key[CONTROL_KEY_BUFSIZ];
518                 
519                 //strncpy doesn't zero-truncate properly
520                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
521                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
522
523                 //Hack to get the nameless cookie only
524                 snprintf(control_key, CONTROL_KEY_BUFSIZ, "%s", getenv("COOKIE_STRING"));
525
526                 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
527                 Log(LOGDEBUG, "Control key: %s", control_key);
528
529                 
530                 //Remove trailing slashes (if present) from module query
531                 size_t lastchar = strlen(module) - 1;
532                 if (lastchar > 0 && module[lastchar] == '/')
533                         module[lastchar] = 0;
534
535                 //Default to the 'identify' module if none specified
536                 if (!*module) 
537                         strcpy(module, "identify");
538                 
539                 if (!strcmp("identify", module)) {
540                         module_handler = IdentifyHandler;
541                 } else if (!strcmp("control", module)) {
542                         module_handler = Control_Handler;
543                 } else if (!strcmp("sensors", module)) {
544                         module_handler = Sensor_Handler;
545                 } else if (!strcmp("actuators", module)) {
546                         module_handler = Actuator_Handler;
547                 } else if (!strcmp("image", module)) {
548                         module_handler = Image_Handler;
549                 } else if (!strcmp("pin", module)) { 
550                         module_handler = Pin_Handler; // *Debug only* pin test module
551                 } else if (!strcmp("bind", module)) {
552                         module_handler = Login_Handler;
553                 } else if (!strcmp("unbind", module)) {
554                         module_handler = Logout_Handler;
555                 }
556
557                 context.current_module = module;
558                 context.response_number++;
559                 
560                 if (module_handler) 
561                 {
562                         //if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
563                         if (false) // Testing
564                         {
565                                 if (!FCGI_HasControl(&context, control_key))
566                                 {
567                                         FCGI_RejectJSON(&context, "Please login. Invalid control key.");
568                                         continue;       
569                                 }
570
571                                 //Escape all special characters.
572                                 //Don't escape for login (password may have special chars?)
573                                 FCGI_EscapeText(params);
574                         }
575
576                         module_handler(&context, params);
577                 } 
578                 else 
579                 {
580                         FCGI_RejectJSON(&context, "Unhandled module");
581                 }
582         }
583
584         Log(LOGDEBUG, "Thread exiting.");
585         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
586         return NULL;
587 }

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