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

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