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

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