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

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