Added module for direct control over pins
[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                                                 *((bool*) val->value) = true;
232                                                 break;
233                                         case FCGI_INT_T: case FCGI_LONG_T: {
234                                                 long parsed = strtol(value, &ptr, 10);
235                                                 if (!*value || *ptr) {
236                                                         snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
237                                                         FCGI_RejectJSON(context, buf);
238                                                         return false;
239                                                 }
240
241                                                 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
242                                                         *((int*) val->value) = (int) parsed;
243                                                 else
244                                                         *((long*) val->value) = parsed;
245                                         }       break;
246                                         case FCGI_DOUBLE_T:
247                                                 *((double*) val->value) = strtod(value, &ptr);
248                                                 if (!*value || *ptr) {
249                                                         snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
250                                                         FCGI_RejectJSON(context, buf);
251                                                         return false;
252                                                 }
253                                                 break;
254                                         case FCGI_STRING_T:
255                                                 *((const char**) val->value) = value;
256                                                 break;
257                                         default:
258                                                 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
259                                 }
260                                 break; //No need to search any more
261                         }
262                 } //End for loop
263                 if (i == count) {
264                         snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
265                         FCGI_RejectJSON(context, buf);
266                         return false;
267                 }
268         }
269
270         //Check that required parameters are received
271         for (i = 0; i < count; i++) {
272                 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
273                         snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
274                         FCGI_RejectJSON(context, buf);
275                         return false;
276                 }
277         }
278         return true;
279 }
280
281 /**
282  * Begins a response to the client in JSON format.
283  * @param context The context to work in.
284  * @param status_code The status code to be returned.
285  */
286 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
287 {
288         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
289         printf("{\r\n");
290         printf("\t\"module\" : \"%s\"", context->current_module);
291         FCGI_JSONLong("status", status_code);
292         //Time and running statistics
293         struct timeval now;
294         gettimeofday(&now, NULL);
295         FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
296         FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
297         FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
298         FCGI_JSONPair("control_state", Control_GetModeName());
299 }
300
301 /**
302  * Adds a key/value pair to a JSON response. The response must have already
303  * been initiated by FCGI_BeginJSON. Special characters are not escaped.
304  * @param key The key of the JSON entry
305  * @param value The value associated with the key.
306  */
307 void FCGI_JSONPair(const char *key, const char *value)
308 {
309         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
310 }
311
312 /**
313  * Similar to FCGI_JSONPair except for signed integer values.
314  * @param key The key of the JSON entry
315  * @param value The value associated with the key
316  */
317 void FCGI_JSONLong(const char *key, long value)
318 {
319         printf(",\r\n\t\"%s\" : %ld", key, value);
320 }
321
322 /**
323  * Similar to FCGI_JsonPair except for floating point values.
324  * @param key The key of the JSON entry
325  * @param value The value associated with the key
326  */
327 void FCGI_JSONDouble(const char *key, double value)
328 {
329         printf(",\r\n\t\"%s\" : %f", key, value);
330 }
331
332 /**
333  * Similar to FCGI_JsonPair except for boolean values.
334  * @param key The key of the JSON entry
335  * @param value The value associated with the key
336  */
337 void FCGI_JSONBool(const char *key, bool value)
338 {
339         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
340 }
341
342 /**
343  * Begins a JSON entry by writing the key. To be used in conjunction
344  * with FCGI_JsonValue.
345  * @param key The key of the JSON entry
346  */
347 void FCGI_JSONKey(const char *key)
348 {
349         printf(",\r\n\t\"%s\" : ", key);
350 }
351
352 /**
353  * Ends a JSON response that was initiated by FCGI_BeginJSON.
354  */
355 void FCGI_EndJSON() 
356 {
357         printf("\r\n}\r\n");
358 }
359
360 /**
361  * To be used when the input parameters are rejected. The return data
362  * will also have debugging information provided.
363  * @param context The context to work in
364  * @param status The status the return data should have.
365  * @param description A short description of why the input was rejected.
366  */
367 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
368 {
369         if (description == NULL)
370                 description = "Unknown";
371         
372         Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
373         FCGI_BeginJSON(context, status);
374         FCGI_JSONPair("description", description);
375         FCGI_JSONLong("responsenumber", context->response_number);
376         //FCGI_JSONPair("params", getenv("QUERY_STRING"));
377         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
378         FCGI_JSONPair("user", getenv("REMOTE_USER"));
379         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
380         FCGI_EndJSON();
381 }
382
383 /**
384  * Generates a response to the client as described by the format parameter and
385  * extra arguments (exactly like printf). To be used when none of the other
386  * predefined functions will work exactly as needed. Extra care should be taken
387  * to ensure the correctness of the output.
388  * @param format The format string
389  * @param ... Any extra arguments as required by the format string.
390  */
391 void FCGI_PrintRaw(const char *format, ...)
392 {
393         va_list list;
394         va_start(list, format);
395         vprintf(format, list);
396         va_end(list);
397 }
398
399
400 /**
401  * Write binary data
402  * See fwrite
403  */
404 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
405 {
406         Log(LOGDEBUG,"Writing!");
407         fwrite(data, size, num_elem, stdout);
408 }
409
410 /**
411  * Escapes a string so it can be used safely.
412  * Currently escapes to ensure the validity for use as a JSON string
413  * Does not support unicode specifiers in the form of \uXXXX.
414  * @param buf The string to be escaped
415  * @return The escaped string (return value == buf)
416  */
417 char *FCGI_EscapeText(char *buf)
418 {
419         int length, i;
420         length = strlen(buf);
421         
422         //Escape special characters. Must count down to escape properly
423         for (i = length - 1; i >= 0; i--) {
424                 if (buf[i] < 0x20) { //Control characters
425                         buf[i] = ' ';
426                 } else if (buf[i] == '"') {
427                         if (i-1 >= 0 && buf[i-1] == '\\') 
428                                 i--;
429                         else
430                                 buf[i] = '\'';
431                 } else if (buf[i] == '\\') {
432                         if (i-1 >= 0 && buf[i-1] == '\'')
433                                 i--;
434                         else
435                                 buf[i] = ' ';
436                 }
437         }
438         return buf;
439 }
440
441 /**
442  * Main FCGI request loop that receives/responds to client requests.
443  * @param data Reserved.
444  * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
445  * TODO: Get this to exit with the rest of the program!
446  */ 
447 void * FCGI_RequestLoop (void *data)
448 {
449         FCGIContext context = {0};
450         
451         Log(LOGDEBUG, "Start loop");
452         while (FCGI_Accept() >= 0) {
453                 
454                 ModuleHandler module_handler = NULL;
455                 char module[BUFSIZ], params[BUFSIZ];
456                 
457                 //strncpy doesn't zero-truncate properly
458                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
459                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
460
461                 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
462                 
463                 //Remove trailing slashes (if present) from module query
464                 size_t lastchar = strlen(module) - 1;
465                 if (lastchar > 0 && module[lastchar] == '/')
466                         module[lastchar] = 0;
467
468                 //Escape all special characters
469                 FCGI_EscapeText(params);
470
471                 //Default to the 'identify' module if none specified
472                 if (!*module) 
473                         strcpy(module, "identify");
474                 
475                 if (!strcmp("identify", module)) {
476                         module_handler = IdentifyHandler;
477                 } else if (!strcmp("control", module)) {
478                         module_handler = Control_Handler;
479                 } else if (!strcmp("sensors", module)) {
480                         module_handler = Sensor_Handler;
481                 } else if (!strcmp("actuators", module)) {
482                         module_handler = Actuator_Handler;
483                 } else if (!strcmp("image", module)) {
484                         module_handler = Image_Handler;
485                 } else if (!strcmp("pin", module)) { 
486                         module_handler = Pin_Handler; // *Debug only* pin test module
487                 }
488
489                 context.current_module = module;
490                 if (module_handler) {
491                         module_handler(&context, params);
492                 } else {
493                         FCGI_RejectJSON(&context, "Unhandled module");
494                 }
495                 context.response_number++;
496
497                 
498         }
499
500         Log(LOGDEBUG, "Thread exiting.");
501         // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.
502         return NULL;
503 }

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