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

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