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

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