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

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