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

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