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

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