Fix brief string
[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  * @return TRUE if authorized, FALSE if not.
168  */
169 bool FCGI_HasControl(FCGIContext *context)
170 {
171         time_t now = time(NULL);
172         int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
173                         context->control_key[0] != '\0' &&
174                         !strcmp(context->control_key, context->received_key);
175         if (result) {
176                 context->control_timestamp = now; //Update the control_timestamp
177         }
178         return result;
179 }
180
181
182 /**
183  * Revokes the current control key, if present.
184  * @param context The context to work in
185  */
186 void FCGI_ReleaseControl(FCGIContext *context)
187 {
188         *(context->control_key) = 0;
189         // Note: context->user_name should *not* be cleared
190         return;
191 }
192
193 /**
194  * Gets the control cookie
195  * @param buffer A storage buffer of exactly CONTROL_KEY_BUFSIZ length to
196                  store the control key
197  */
198 void FCGI_GetControlCookie(char buffer[CONTROL_KEY_BUFSIZ])
199 {
200         const char *cookies = getenv("COOKIE_STRING");
201         const char *start = strstr(cookies, "mctxkey=");
202
203         *buffer = 0; //Clear the buffer
204         if (start != NULL) {
205                 int i;
206                 start += 8; //length of mctxkey=
207                 for (i = 0; i < CONTROL_KEY_BUFSIZ; i++) {
208                         if (*start == 0 || *start == ';') {
209                                 break;
210                         }
211                         buffer[i] = *start++;
212                 }
213                 buffer[i] = 0;
214         }
215 }
216
217 /**
218  * Sends the control key to the user as a cookie.
219  * @param context the context to work in
220  * @param set Whether to set or unset the control cookie
221  */
222 void FCGI_SendControlCookie(FCGIContext *context, bool set) {
223         if (set) {
224                 printf("Set-Cookie: mctxkey=%s\r\n", context->control_key);
225         } else {
226                 printf("Set-Cookie: mctxkey=\r\n");
227         }
228 }
229
230 /**
231  * Extracts a key/value pair from a request string.
232  * Note that the input is modified by this function.
233  * @param in The string from which to extract the pair
234  * @param key A pointer to a variable to hold the key string
235  * @param value A pointer to a variable to hold the value string
236  * @return A pointer to the start of the next search location, or NULL if
237  *         the EOL is reached.
238  */
239 char *FCGI_KeyPair(char *in, const char **key, const char **value)
240 {
241         char *ptr;
242         if (!in || !*in) { //Invalid input or string is EOL
243                 return NULL;
244         }
245
246         *key = in;
247         //Find either = or &, whichever comes first
248         if ((ptr = strpbrk(in, "=&"))) {
249                 if (*ptr == '&') { //No value specified
250                         *value = ptr;
251                         *ptr++ = 0;
252                 } else {
253                         //Stopped at an '=' sign
254                         *ptr++ = 0;
255                         *value = ptr;
256                         if ((ptr = strchr(ptr,'&'))) {
257                                 *ptr++ = 0;
258                         } else {
259                                 ptr = "";
260                         }
261                 }
262         } else { //No value specified and no other pair
263                 ptr = "";
264                 *value = ptr;
265         }
266         return ptr;
267 }
268
269 /**
270  * Aids in parsing request parameters. 
271  * Input: The expected keys along with their type and whether or not
272  * they're required.
273  * @param context The context to work in
274  * @param params The parameter string to be parsed
275  * @param values An array of FCGIValue's that specify expected keys
276  * @param count The number of elements in 'values'.
277  * @return true If the parameter string was parsed successfully, false otherwise.
278  *         Modes of failure include: Invalid a parsing error on the value,
279  *                                   an unknown key is specified,
280  *                                   a key/value pair is specified more than once, or
281  *                                   not all required keys were present.
282  *         If this function returns false, it is guaranteed that FCGI_RejectJSON
283  *         has already been called with the appropriate description message.
284  */
285 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
286 {
287         const char *key, *value;
288         char buf[BUFSIZ], *ptr;
289         size_t i;
290         
291         while ((params = FCGI_KeyPair(params, &key, &value))) {
292                 for (i = 0; i < count; i++) {
293                         if (!strcmp(key, values[i].key)) {
294                                 FCGIValue *val = &values[i];
295
296                                 if (FCGI_RECEIVED(val->flags)) {
297                                         snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
298                                         FCGI_RejectJSON(context, buf);
299                                         return false;
300                                 }
301                                 val->flags |= FCGI_PARAM_RECEIVED;
302
303                                 switch(FCGI_TYPE(val->flags)) {
304                                         case FCGI_BOOL_T:
305                                                 if (!*value) //No value: Default true
306                                                         *((bool*) val->value) = true;
307                                                 else {
308                                                         *((bool*) val->value) = !!(strtol(value, &ptr, 10));
309                                                         if (*ptr) {
310                                                                 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
311                                                                 FCGI_RejectJSON(context, buf);
312                                                                 return false;
313                                                         }
314                                                 }
315                                                 break;
316                                         case FCGI_INT_T: case FCGI_LONG_T: {
317                                                 long parsed = strtol(value, &ptr, 10);
318                                                 if (!*value || *ptr) {
319                                                         snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
320                                                         FCGI_RejectJSON(context, buf);
321                                                         return false;
322                                                 }
323
324                                                 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
325                                                         *((int*) val->value) = (int) parsed;
326                                                 else
327                                                         *((long*) val->value) = parsed;
328                                         }       break;
329                                         case FCGI_DOUBLE_T:
330                                                 *((double*) val->value) = strtod(value, &ptr);
331                                                 if (!*value || *ptr) {
332                                                         snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
333                                                         FCGI_RejectJSON(context, buf);
334                                                         return false;
335                                                 }
336                                                 break;
337                                         case FCGI_STRING_T:
338                                                 *((const char**) val->value) = value;
339                                                 break;
340                                         default:
341                                                 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
342                                 }
343                                 break; //No need to search any more
344                         }
345                 } //End for loop
346                 if (i == count) {
347                         snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
348                         FCGI_RejectJSON(context, buf);
349                         return false;
350                 }
351         }
352
353         //Check that required parameters are received
354         for (i = 0; i < count; i++) {
355                 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
356                         snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
357                         FCGI_RejectJSON(context, buf);
358                         return false;
359                 }
360         }
361         return true;
362 }
363
364 /**
365  * Begins a response to the client in JSON format.
366  * @param context The context to work in.
367  * @param status_code The status code to be returned.
368  */
369 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
370 {
371         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
372         printf("{\r\n");
373         printf("\t\"module\" : \"%s\"", context->current_module);
374         FCGI_JSONLong("status", status_code);
375         //Time and running statistics
376         struct timespec now;
377         clock_gettime(CLOCK_MONOTONIC, &now);
378         FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
379         FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
380         FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
381         FCGI_JSONPair("control_state", Control_GetModeName());
382 }
383
384 /**
385  * Generic accept response in JSON format.
386  * @param context The context to work in
387  * @param description A short description.
388  */
389 void FCGI_AcceptJSON(FCGIContext *context, const char *description)
390 {
391         printf("Content-type: application/json; charset=utf-8\r\n");
392         printf("\r\n{\r\n");
393         printf("\t\"module\" : \"%s\"", context->current_module);
394         FCGI_JSONLong("status", STATUS_OK);
395         FCGI_JSONPair("description", description);
396         FCGI_EndJSON();
397 }
398
399 /**
400  * Adds a key/value pair to a JSON response. The response must have already
401  * been initiated by FCGI_BeginJSON. Special characters are not escaped.
402  * @param key The key of the JSON entry
403  * @param value The value associated with the key.
404  */
405 void FCGI_JSONPair(const char *key, const char *value)
406 {
407         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
408 }
409
410 /**
411  * Similar to FCGI_JSONPair except for signed integer values.
412  * @param key The key of the JSON entry
413  * @param value The value associated with the key
414  */
415 void FCGI_JSONLong(const char *key, long value)
416 {
417         printf(",\r\n\t\"%s\" : %ld", key, value);
418 }
419
420 /**
421  * Similar to FCGI_JsonPair except for floating point values.
422  * @param key The key of the JSON entry
423  * @param value The value associated with the key
424  */
425 void FCGI_JSONDouble(const char *key, double value)
426 {
427         printf(",\r\n\t\"%s\" : %.9f", key, value);
428 }
429
430 /**
431  * Similar to FCGI_JsonPair except for boolean values.
432  * @param key The key of the JSON entry
433  * @param value The value associated with the key
434  */
435 void FCGI_JSONBool(const char *key, bool value)
436 {
437         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
438 }
439
440 /**
441  * Begins a JSON entry by writing the key. To be used in conjunction
442  * with FCGI_JsonValue.
443  * @param key The key of the JSON entry
444  */
445 void FCGI_JSONKey(const char *key)
446 {
447         printf(",\r\n\t\"%s\" : ", key);
448 }
449
450 /**
451  * Ends a JSON response that was initiated by FCGI_BeginJSON.
452  */
453 void FCGI_EndJSON() 
454 {
455         printf("\r\n}\r\n");
456 }
457
458 /**
459  * To be used when the input parameters are rejected. The return data
460  * will also have debugging information provided.
461  * @param context The context to work in
462  * @param status The status the return data should have.
463  * @param description A short description of why the input was rejected.
464  */
465 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
466 {
467         if (description == NULL)
468                 description = "Unknown";
469         
470         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
471         FCGI_BeginJSON(context, status);
472         FCGI_JSONPair("description", description);
473         FCGI_JSONLong("responsenumber", context->response_number);
474         //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
475         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
476         FCGI_JSONPair("user", getenv("REMOTE_USER"));
477         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
478         FCGI_EndJSON();
479 }
480
481 /**
482  * Generates a response to the client as described by the format parameter and
483  * extra arguments (exactly like printf). To be used when none of the other
484  * predefined functions will work exactly as needed. Extra care should be taken
485  * to ensure the correctness of the output.
486  * @param format The format string
487  * @param ... Any extra arguments as required by the format string.
488  */
489 void FCGI_PrintRaw(const char *format, ...)
490 {
491         va_list list;
492         va_start(list, format);
493         vprintf(format, list);
494         va_end(list);
495 }
496
497
498 /**
499  * Write binary data
500  * See fwrite
501  */
502 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
503 {
504         Log(LOGDEBUG,"Writing!");
505         fwrite(data, size, num_elem, stdout);
506 }
507
508 /**
509  * Escapes a string so it can be used safely.
510  * Currently escapes to ensure the validity for use as a JSON string
511  * Does not support unicode specifiers in the form of \\uXXXX.
512  * @param buf The string to be escaped
513  * @return The escaped string (return value == buf)
514  */
515 char *FCGI_EscapeText(char *buf)
516 {
517         int length, i;
518         length = strlen(buf);
519         
520         //Escape special characters. Must count down to escape properly
521         for (i = length - 1; i >= 0; i--) {
522                 if (buf[i] < 0x20) { //Control characters
523                         buf[i] = ' ';
524                 } else if (buf[i] == '"') {
525                         if (i-1 >= 0 && buf[i-1] == '\\') 
526                                 i--;
527                         else
528                                 buf[i] = '\'';
529                 } else if (buf[i] == '\\') {
530                         if (i-1 >= 0 && buf[i-1] == '\'')
531                                 i--;
532                         else
533                                 buf[i] = ' ';
534                 }
535         }
536         return buf;
537 }
538
539 /**
540  * Unescapes a URL encoded string in-place. The string
541  * must be NULL terminated.
542  * (e.g this%2d+string --> this- string)
543  * @param buf The buffer to decode. Will be modified in-place.
544  * @return The same buffer.
545  */
546 char *FCGI_URLDecode(char *buf)
547 {
548         char *head = buf, *tail = buf;
549         char val, hex[3] = {0};
550
551         while (*tail) {
552                 if (*tail == '%') { //%hh hex to char
553                         tail++;
554                         if (isxdigit(*tail) && isxdigit(*(tail+1))) {
555                                 hex[0] = *tail++;
556                                 hex[1] = *tail++;
557                                 val = (char)strtol(hex, NULL, 16);
558                                 //Control codes --> Space character
559                                 *head++ = (val < 0x20) ? 0x20 : val;
560                         } else { //Not valid format; keep original
561                                 head++;
562                         }
563                 } else if (*tail == '+') { //Plus to space
564                         tail++;
565                         *head++ = ' ';
566                 } else { //Anything else
567                         *head++ = *tail++;
568                 }
569         }
570         *head = 0; //NULL-terminate at new end point
571
572         return buf;
573 }
574
575 /**
576  * Main FCGI request loop that receives/responds to client requests.
577  * @param data Reserved.
578  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
579  * TODO: Get this to exit with the rest of the program!
580  */ 
581 void * FCGI_RequestLoop (void *data)
582 {
583         FCGIContext context = {0};
584         
585         Log(LOGDEBUG, "Start loop");
586         while (FCGI_Accept() >= 0) {
587                 
588                 ModuleHandler module_handler = NULL;
589                 char module[BUFSIZ], params[BUFSIZ];
590                 
591                 //strncpy doesn't zero-truncate properly
592                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
593                 
594                 //Get the GET query string
595                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
596                 //URL decode the parameters
597                 FCGI_URLDecode(params);
598
599                 FCGI_GetControlCookie(context.received_key);
600                 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
601                 Log(LOGDEBUG, "Control key: %s", context.received_key);
602
603                 
604                 //Remove trailing slashes (if present) from module query
605                 size_t lastchar = strlen(module) - 1;
606                 if (lastchar > 0 && module[lastchar] == '/')
607                         module[lastchar] = 0;
608
609                 //Default to the 'identify' module if none specified
610                 if (!*module) 
611                         strcpy(module, "identify");
612                 
613                 if (!strcmp("identify", module)) {
614                         module_handler = IdentifyHandler;
615                 } else if (!strcmp("control", module)) {
616                         module_handler = Control_Handler;
617                 } else if (!strcmp("sensors", module)) {
618                         module_handler = Sensor_Handler;
619                 } else if (!strcmp("actuators", module)) {
620                         module_handler = Actuator_Handler;
621                 } else if (!strcmp("image", module)) {
622                         module_handler = Image_Handler;
623                 } else if (!strcmp("pin", module)) { 
624                         module_handler = Pin_Handler; // *Debug only* pin test module
625                 } else if (!strcmp("bind", module)) {
626                         module_handler = Login_Handler;
627                 } else if (!strcmp("unbind", module)) {
628                         module_handler = Logout_Handler;
629                 }
630
631                 context.current_module = module;
632                 context.response_number++;
633                 
634                 if (module_handler) {
635                         if (module_handler == IdentifyHandler) {
636                                 FCGI_EscapeText(params);
637                         } else if (module_handler != Login_Handler) {
638                                 if (!FCGI_HasControl(&context))
639                                 {
640                                         if (g_options.auth_method == AUTH_NONE) {       //:(
641                                                 Log(LOGWARN, "Locking control (no auth!)");
642                                                 FCGI_LockControl(&context, NOAUTH_USERNAME, USER_ADMIN);
643                                                 FCGI_SendControlCookie(&context, true);
644                                         }
645                                         else {
646                                                 FCGI_RejectJSON(&context, "Please login. Invalid control key.");
647                                                 continue;
648                                         }
649                                 }
650                                 
651                                 //Escape all special characters.
652                                 //Don't escape for login (password may have special chars?)
653                                 FCGI_EscapeText(params);
654                         } else { //Only for Login handler.
655                                 //If GET data is empty, use POST instead.
656                                 if (*params == '\0') {
657                                         Log(LOGDEBUG, "Using POST!");
658                                         fgets(params, BUFSIZ, stdin); 
659                                         FCGI_URLDecode(params);
660                                 }
661                         }
662
663                         module_handler(&context, params);
664                 } 
665                 else {
666                         FCGI_RejectJSON(&context, "Unhandled module");
667                 }
668         }
669
670         Log(LOGDEBUG, "Thread exiting.");
671         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
672         return NULL;
673 }

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