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

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