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

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