3 * @brief Runs the FCGI request loop to handle web interface requests.
5 * fcgi_stdio.h must be included before all else so the stdio function
6 * redirection works ok.
9 #include <fcgi_stdio.h>
10 #include <openssl/sha.h>
20 /**The time period (in seconds) before the control key expires */
21 #define CONTROL_TIMEOUT 180
23 /**Contextual information related to FCGI requests*/
25 /**The time of last valid user access possessing the control key*/
26 time_t control_timestamp;
29 /**The name of the current module**/
30 const char *current_module;
31 /**For debugging purposes?**/
36 * Identifies build information and the current API version to the user.
37 * Also useful for testing that the API is running and identifying the
38 * sensors and actuators present.
39 * @param context The context to work in
40 * @param params User specified paramters: [actuators, sensors]
42 static void IdentifyHandler(FCGIContext *context, char *params) {
43 bool ident_sensors = false, ident_actuators = false;
47 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
48 {"actuators", &ident_actuators, FCGI_BOOL_T}};
49 if (!FCGI_ParseRequest(context, params, values, 2))
52 FCGI_BeginJSON(context, STATUS_OK);
53 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
54 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
55 FCGI_JSONLong("api_version", API_VERSION);
57 //Sensor and actuator information
59 FCGI_JSONKey("sensors");
60 FCGI_JSONValue("{\n\t\t");
61 for (i = 0; i < NUMSENSORS; i++) {
63 FCGI_JSONValue(",\n\t\t");
65 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
67 FCGI_JSONValue("\n\t}");
69 if (ident_actuators) {
70 FCGI_JSONKey("actuators");
71 FCGI_JSONValue("{\n\t\t");
72 for (i = 0; i < NUMACTUATORS; i++) {
74 FCGI_JSONValue(",\n\t\t");
76 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
78 FCGI_JSONValue("\n\t}");
84 * Gives the user a key that determines who has control over
85 * the system at any one time. The key can be forcibly generated, revoking
86 * any previous control keys. To be used in conjunction with HTTP
87 * basic authentication.
88 * This function will generate a JSON response that indicates success/failure.
89 * @param context The context to work in
90 * @param force Whether to force key generation or not.
92 void FCGI_LockControl(FCGIContext *context, bool force) {
93 time_t now = time(NULL);
94 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
96 if (force || !*(context->control_key) || expired) {
98 unsigned char sha1[20];
102 SHA1_Update(&sha1ctx, &now, sizeof(now));
103 SHA1_Update(&sha1ctx, &i, sizeof(i));
104 SHA1_Final(sha1, &sha1ctx);
106 context->control_timestamp = now;
107 for (i = 0; i < 20; i++)
108 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
109 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
110 FCGI_BeginJSON(context, STATUS_OK);
111 FCGI_JSONPair("key", context->control_key);
115 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
116 localtime(&(context->control_timestamp)));
117 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
118 FCGI_JSONPair("description", "Another user already has control");
119 FCGI_JSONPair("current_user", context->control_ip);
120 FCGI_JSONPair("when", buf);
126 * Given an FCGIContext, determines if the current user (as specified by
127 * the key) has control or not. If validated, the context control_timestamp is
129 * @param context The context to work in
130 * @param key The control key to be validated.
131 * @return TRUE if authorized, FALSE if not.
133 bool FCGI_HasControl(FCGIContext *context, const char *key) {
134 time_t now = time(NULL);
135 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
136 key != NULL && !strcmp(context->control_key, key);
138 context->control_timestamp = now; //Update the control_timestamp
145 * Revokes the current control key, if present.
146 * @param context The context to work in
148 void FCGI_ReleaseControl(FCGIContext *context) {
149 *(context->control_key) = 0;
150 FCGI_BeginJSON(context, STATUS_OK);
156 * Extracts a key/value pair from a request string.
157 * Note that the input is modified by this function.
158 * @param in The string from which to extract the pair
159 * @param key A pointer to a variable to hold the key string
160 * @param value A pointer to a variable to hold the value string
161 * @return A pointer to the start of the next search location, or NULL if
162 * the EOL is reached.
164 char *FCGI_KeyPair(char *in, const char **key, const char **value)
167 if (!in || !*in) { //Invalid input or string is EOL
172 //Find either = or &, whichever comes first
173 if ((ptr = strpbrk(in, "=&"))) {
174 if (*ptr == '&') { //No value specified
178 //Stopped at an '=' sign
181 if ((ptr = strchr(ptr,'&'))) {
187 } else { //No value specified and no other pair
195 * Aids in parsing request parameters.
196 * Input: The expected keys along with their type and whether or not
198 * @param context The context to work in
199 * @param params The parameter string to be parsed
200 * @param values An array of FCGIValue's that specify expected keys
201 * @param count The number of elements in 'values'.
202 * @return true If the parameter string was parsed successfully, false otherwise.
203 * Modes of failure include: Invalid a parsing error on the value,
204 * an unknown key is specified,
205 * a key/value pair is specified more than once, or
206 * not all required keys were present.
207 * If this function returns false, it is guaranteed that FCGI_RejectJSON
208 * has already been called with the appropriate description message.
210 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
212 const char *key, *value;
213 char buf[BUFSIZ], *ptr;
216 while ((params = FCGI_KeyPair(params, &key, &value))) {
217 for (i = 0; i < count; i++) {
218 if (!strcmp(key, values[i].key)) {
219 FCGIValue *val = &values[i];
221 if (FCGI_RECEIVED(val->flags)) {
222 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
223 FCGI_RejectJSON(context, buf);
226 val->flags |= FCGI_PARAM_RECEIVED;
228 switch(FCGI_TYPE(val->flags)) {
230 *((bool*) val->value) = true;
232 case FCGI_INT_T: case FCGI_LONG_T: {
233 long parsed = strtol(value, &ptr, 10);
234 if (!*value || *ptr) {
235 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
236 FCGI_RejectJSON(context, buf);
240 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
241 *((int*) val->value) = (int) parsed;
243 *((long*) val->value) = parsed;
246 *((double*) val->value) = strtod(value, &ptr);
247 if (!*value || *ptr) {
248 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
249 FCGI_RejectJSON(context, buf);
254 *((const char**) val->value) = value;
257 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
259 break; //No need to search any more
263 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
264 FCGI_RejectJSON(context, buf);
269 //Check that required parameters are received
270 for (i = 0; i < count; i++) {
271 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
272 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
273 FCGI_RejectJSON(context, buf);
281 * Begins a response to the client in JSON format.
282 * @param context The context to work in.
283 * @param status_code The status code to be returned.
285 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
287 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
289 printf("\t\"module\" : \"%s\"", context->current_module);
290 FCGI_JSONLong("status", status_code);
291 //Time and running statistics
293 gettimeofday(&now, NULL);
294 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
295 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
296 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
297 FCGI_JSONPair("control_state", Control_GetModeName());
301 * Adds a key/value pair to a JSON response. The response must have already
302 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
303 * @param key The key of the JSON entry
304 * @param value The value associated with the key.
306 void FCGI_JSONPair(const char *key, const char *value)
308 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
312 * Similar to FCGI_JSONPair except for signed integer values.
313 * @param key The key of the JSON entry
314 * @param value The value associated with the key
316 void FCGI_JSONLong(const char *key, long value)
318 printf(",\r\n\t\"%s\" : %ld", key, value);
322 * Similar to FCGI_JsonPair except for floating point values.
323 * @param key The key of the JSON entry
324 * @param value The value associated with the key
326 void FCGI_JSONDouble(const char *key, double value)
328 printf(",\r\n\t\"%s\" : %f", key, value);
332 * Similar to FCGI_JsonPair except for boolean values.
333 * @param key The key of the JSON entry
334 * @param value The value associated with the key
336 void FCGI_JSONBool(const char *key, bool value)
338 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
342 * Begins a JSON entry by writing the key. To be used in conjunction
343 * with FCGI_JsonValue.
344 * @param key The key of the JSON entry
346 void FCGI_JSONKey(const char *key)
348 printf(",\r\n\t\"%s\" : ", key);
352 * Ends a JSON response that was initiated by FCGI_BeginJSON.
360 * To be used when the input parameters are rejected. The return data
361 * will also have debugging information provided.
362 * @param context The context to work in
363 * @param status The status the return data should have.
364 * @param description A short description of why the input was rejected.
366 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
368 if (description == NULL)
369 description = "Unknown";
371 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
372 FCGI_BeginJSON(context, status);
373 FCGI_JSONPair("description", description);
374 FCGI_JSONLong("responsenumber", context->response_number);
375 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
376 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
377 FCGI_JSONPair("user", getenv("REMOTE_USER"));
378 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
383 * Generates a response to the client as described by the format parameter and
384 * extra arguments (exactly like printf). To be used when none of the other
385 * predefined functions will work exactly as needed. Extra care should be taken
386 * to ensure the correctness of the output.
387 * @param format The format string
388 * @param ... Any extra arguments as required by the format string.
390 void FCGI_PrintRaw(const char *format, ...)
393 va_start(list, format);
394 vprintf(format, list);
403 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
405 Log(LOGDEBUG,"Writing!");
406 fwrite(data, size, num_elem, stdout);
410 * Escapes a string so it can be used safely.
411 * Currently escapes to ensure the validity for use as a JSON string
412 * Does not support unicode specifiers in the form of \uXXXX.
413 * @param buf The string to be escaped
414 * @return The escaped string (return value == buf)
416 char *FCGI_EscapeText(char *buf)
419 length = strlen(buf);
421 //Escape special characters. Must count down to escape properly
422 for (i = length - 1; i >= 0; i--) {
423 if (buf[i] < 0x20) { //Control characters
425 } else if (buf[i] == '"') {
426 if (i-1 >= 0 && buf[i-1] == '\\')
430 } else if (buf[i] == '\\') {
431 if (i-1 >= 0 && buf[i-1] == '\'')
441 * Main FCGI request loop that receives/responds to client requests.
442 * @param data Reserved.
443 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
444 * TODO: Get this to exit with the rest of the program!
446 void * FCGI_RequestLoop (void *data)
448 FCGIContext context = {0};
450 Log(LOGDEBUG, "First request...");
451 while (FCGI_Accept() >= 0) {
452 Log(LOGDEBUG, "Got request #%d", context.response_number);
453 ModuleHandler module_handler = NULL;
454 char module[BUFSIZ], params[BUFSIZ];
456 //strncpy doesn't zero-truncate properly
457 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
458 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
460 //Remove trailing slashes (if present) from module query
461 size_t lastchar = strlen(module) - 1;
462 if (lastchar > 0 && module[lastchar] == '/')
463 module[lastchar] = 0;
465 //Escape all special characters
466 FCGI_EscapeText(params);
468 //Default to the 'identify' module if none specified
470 strcpy(module, "identify");
472 if (!strcmp("identify", module)) {
473 module_handler = IdentifyHandler;
474 } else if (!strcmp("control", module)) {
475 module_handler = Control_Handler;
476 } else if (!strcmp("sensors", module)) {
477 module_handler = Sensor_Handler;
478 } else if (!strcmp("actuators", module)) {
479 module_handler = Actuator_Handler;
480 } else if (!strcmp("image", module)) {
481 module_handler = Image_Handler;
484 context.current_module = module;
485 if (module_handler) {
486 module_handler(&context, params);
488 FCGI_RejectJSON(&context, "Unhandled module");
490 context.response_number++;
492 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
495 Log(LOGDEBUG, "Thread exiting.");
496 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.