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