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

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