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

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