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

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