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

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