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>
12 #include <sys/types.h>
24 /**The time period (in seconds) before the control key expires */
25 #define CONTROL_TIMEOUT 180
30 * Identifies build information and the current API version to the user.
31 * Also useful for testing that the API is running and identifying the
32 * sensors and actuators present.
33 * @param context The context to work in
34 * @param params User specified paramters: [actuators, sensors]
36 static void IdentifyHandler(FCGIContext *context, char *params)
38 bool ident_sensors = false, ident_actuators = false;
41 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
42 {"actuators", &ident_actuators, FCGI_BOOL_T}};
43 if (!FCGI_ParseRequest(context, params, values, 2))
46 FCGI_BeginJSON(context, STATUS_OK);
47 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
48 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
49 struct timespec t = {0};
50 clock_getres(CLOCK_MONOTONIC, &t);
51 FCGI_JSONDouble("clock_getres", TIMEVAL_TO_DOUBLE(t));
52 FCGI_JSONLong("api_version", API_VERSION);
54 bool has_control = FCGI_HasControl(context);
55 FCGI_JSONBool("logged_in", has_control);
56 FCGI_JSONPair("user_name", has_control ? context->user_name : "");
59 //Sensor and actuator information
61 FCGI_JSONKey("sensors");
62 FCGI_JSONValue("{\n\t\t");
63 for (i = 0; i < g_num_sensors; i++) {
65 FCGI_JSONValue(",\n\t\t");
67 DataPoint d = Sensor_LastData(i);
68 FCGI_JSONValue("\"%d\" : {\"name\" : \"%s\", \"value\" : [%f,%f] }",
69 i, Sensor_GetName(i), d.time_stamp, d.value);
71 FCGI_JSONValue("\n\t}");
73 if (ident_actuators) {
74 FCGI_JSONKey("actuators");
75 FCGI_JSONValue("{\n\t\t");
76 for (i = 0; i < g_num_actuators; i++) {
78 FCGI_JSONValue(",\n\t\t");
81 DataPoint d = Sensor_LastData(i);
82 FCGI_JSONValue("\"%d\" : {\"name\" : \"%s\", \"value\" : [%f, %f] }", i, Actuator_GetName(i), d.time_stamp, d.value);
84 FCGI_JSONValue("\n\t}");
90 * Given an authorised user, attempt to set the control over the system.
91 * Modifies members in the context structure appropriately if successful.
92 * @param context The context to work in
93 * @param user_name - Name of the user
94 * @param user_type - Type of the user, passed after successful authentication
95 * @return true on success, false otherwise (eg someone else already in control)
97 bool FCGI_LockControl(FCGIContext *context, const char * user_name, UserType user_type)
100 time_t now = time(NULL);
101 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
104 // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
105 if (user_type == USER_UNAUTH ||
106 (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
109 // Release any existing control (if any)
110 FCGI_ReleaseControl(context);
113 context->control_timestamp = now;
115 // Generate a SHA1 hash for the user
117 unsigned char sha1[20];
120 SHA1_Update(&sha1ctx, &now, sizeof(now));
121 SHA1_Update(&sha1ctx, &i, sizeof(i));
122 SHA1_Final(sha1, &sha1ctx);
123 for (i = 0; i < sizeof(sha1); i++)
124 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
126 // Set the IPv4 address
127 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
130 int uname_len = strlen(user_name);
131 i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
133 Log(LOGERR, "Username at %d characters too long (limit %d)",
134 uname_len, sizeof(context->user_name));
138 context->user_type = user_type;
140 // Build the user directory
141 i = snprintf(context->user_dir, sizeof(context->user_dir), "%s/%s",
142 g_options.experiment_dir, context->user_name);
143 if (i >= sizeof(context->user_dir)) {
144 Log(LOGERR, "Experiment dir too long (required %d, limit %d)",
145 i, sizeof(context->user_dir));
149 Log(LOGDEBUG, "User dir: %s", context->user_dir);
151 if (mkdir(context->user_dir, 0777) != 0 && errno != EEXIST)
153 Log(LOGERR, "Couldn't create user directory %s - %s",
154 context->user_dir, strerror(errno));
162 * Given an FCGIContext, determines if the current user (as specified by
163 * the key) has control or not. If validated, the context control_timestamp is
165 * @param context The context to work in
166 * @param key The control key to be validated.
167 * @return TRUE if authorized, FALSE if not.
169 bool FCGI_HasControl(FCGIContext *context)
171 time_t now = time(NULL);
172 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
173 context->control_key[0] != '\0' &&
174 !strcmp(context->control_key, context->received_key);
176 context->control_timestamp = now; //Update the control_timestamp
183 * Revokes the current control key, if present.
184 * @param context The context to work in
186 void FCGI_ReleaseControl(FCGIContext *context)
188 *(context->control_key) = 0;
189 // Note: context->user_name should *not* be cleared
194 * Gets the control cookie
195 * @param buffer A storage buffer of exactly CONTROL_KEY_BUFSIZ length to
196 store the control key
198 void FCGI_GetControlCookie(char buffer[CONTROL_KEY_BUFSIZ])
200 const char *cookies = getenv("COOKIE_STRING");
201 const char *start = strstr(cookies, "mctxkey=");
203 *buffer = 0; //Clear the buffer
206 start += 8; //length of mctxkey=
207 for (i = 0; i < CONTROL_KEY_BUFSIZ; i++) {
208 if (*start == 0 || *start == ';') {
211 buffer[i] = *start++;
218 * Sends the control key to the user as a cookie.
219 * @param context the context to work in
220 * @param set Whether to set or unset the control cookie
222 void FCGI_SendControlCookie(FCGIContext *context, bool set) {
224 printf("Set-Cookie: mctxkey=%s\r\n", context->control_key);
226 printf("Set-Cookie: mctxkey=\r\n");
231 * Extracts a key/value pair from a request string.
232 * Note that the input is modified by this function.
233 * @param in The string from which to extract the pair
234 * @param key A pointer to a variable to hold the key string
235 * @param value A pointer to a variable to hold the value string
236 * @return A pointer to the start of the next search location, or NULL if
237 * the EOL is reached.
239 char *FCGI_KeyPair(char *in, const char **key, const char **value)
242 if (!in || !*in) { //Invalid input or string is EOL
247 //Find either = or &, whichever comes first
248 if ((ptr = strpbrk(in, "=&"))) {
249 if (*ptr == '&') { //No value specified
253 //Stopped at an '=' sign
256 if ((ptr = strchr(ptr,'&'))) {
262 } else { //No value specified and no other pair
270 * Aids in parsing request parameters.
271 * Input: The expected keys along with their type and whether or not
273 * @param context The context to work in
274 * @param params The parameter string to be parsed
275 * @param values An array of FCGIValue's that specify expected keys
276 * @param count The number of elements in 'values'.
277 * @return true If the parameter string was parsed successfully, false otherwise.
278 * Modes of failure include: Invalid a parsing error on the value,
279 * an unknown key is specified,
280 * a key/value pair is specified more than once, or
281 * not all required keys were present.
282 * If this function returns false, it is guaranteed that FCGI_RejectJSON
283 * has already been called with the appropriate description message.
285 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
287 const char *key, *value;
288 char buf[BUFSIZ], *ptr;
291 while ((params = FCGI_KeyPair(params, &key, &value))) {
292 for (i = 0; i < count; i++) {
293 if (!strcmp(key, values[i].key)) {
294 FCGIValue *val = &values[i];
296 if (FCGI_RECEIVED(val->flags)) {
297 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
298 FCGI_RejectJSON(context, buf);
301 val->flags |= FCGI_PARAM_RECEIVED;
303 switch(FCGI_TYPE(val->flags)) {
305 if (!*value) //No value: Default true
306 *((bool*) val->value) = true;
308 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
310 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
311 FCGI_RejectJSON(context, buf);
316 case FCGI_INT_T: case FCGI_LONG_T: {
317 long parsed = strtol(value, &ptr, 10);
318 if (!*value || *ptr) {
319 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
320 FCGI_RejectJSON(context, buf);
324 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
325 *((int*) val->value) = (int) parsed;
327 *((long*) val->value) = parsed;
330 *((double*) val->value) = strtod(value, &ptr);
331 if (!*value || *ptr) {
332 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
333 FCGI_RejectJSON(context, buf);
338 *((const char**) val->value) = value;
341 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
343 break; //No need to search any more
347 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
348 FCGI_RejectJSON(context, buf);
353 //Check that required parameters are received
354 for (i = 0; i < count; i++) {
355 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
356 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
357 FCGI_RejectJSON(context, buf);
365 * Begins a response to the client in JSON format.
366 * @param context The context to work in.
367 * @param status_code The status code to be returned.
369 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
371 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
373 printf("\t\"module\" : \"%s\"", context->current_module);
374 FCGI_JSONLong("status", status_code);
375 //Time and running statistics
377 clock_gettime(CLOCK_MONOTONIC, &now);
378 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
379 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
380 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
381 FCGI_JSONPair("control_state", Control_GetModeName());
385 * Generic accept response in JSON format.
386 * @param context The context to work in
387 * @param description A short description.
388 * @param cookie Optional. If given, the cookie field is set to that value.
390 void FCGI_AcceptJSON(FCGIContext *context, const char *description)
392 printf("Content-type: application/json; charset=utf-8\r\n");
394 printf("\t\"module\" : \"%s\"", context->current_module);
395 FCGI_JSONLong("status", STATUS_OK);
396 FCGI_JSONPair("description", description);
401 * Adds a key/value pair to a JSON response. The response must have already
402 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
403 * @param key The key of the JSON entry
404 * @param value The value associated with the key.
406 void FCGI_JSONPair(const char *key, const char *value)
408 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
412 * Similar to FCGI_JSONPair except for signed integer values.
413 * @param key The key of the JSON entry
414 * @param value The value associated with the key
416 void FCGI_JSONLong(const char *key, long value)
418 printf(",\r\n\t\"%s\" : %ld", key, value);
422 * Similar to FCGI_JsonPair except for floating point values.
423 * @param key The key of the JSON entry
424 * @param value The value associated with the key
426 void FCGI_JSONDouble(const char *key, double value)
428 printf(",\r\n\t\"%s\" : %.9f", key, value);
432 * Similar to FCGI_JsonPair except for boolean values.
433 * @param key The key of the JSON entry
434 * @param value The value associated with the key
436 void FCGI_JSONBool(const char *key, bool value)
438 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
442 * Begins a JSON entry by writing the key. To be used in conjunction
443 * with FCGI_JsonValue.
444 * @param key The key of the JSON entry
446 void FCGI_JSONKey(const char *key)
448 printf(",\r\n\t\"%s\" : ", key);
452 * Ends a JSON response that was initiated by FCGI_BeginJSON.
460 * To be used when the input parameters are rejected. The return data
461 * will also have debugging information provided.
462 * @param context The context to work in
463 * @param status The status the return data should have.
464 * @param description A short description of why the input was rejected.
466 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
468 if (description == NULL)
469 description = "Unknown";
471 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
472 FCGI_BeginJSON(context, status);
473 FCGI_JSONPair("description", description);
474 FCGI_JSONLong("responsenumber", context->response_number);
475 //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
476 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
477 FCGI_JSONPair("user", getenv("REMOTE_USER"));
478 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
483 * Generates a response to the client as described by the format parameter and
484 * extra arguments (exactly like printf). To be used when none of the other
485 * predefined functions will work exactly as needed. Extra care should be taken
486 * to ensure the correctness of the output.
487 * @param format The format string
488 * @param ... Any extra arguments as required by the format string.
490 void FCGI_PrintRaw(const char *format, ...)
493 va_start(list, format);
494 vprintf(format, list);
503 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
505 Log(LOGDEBUG,"Writing!");
506 fwrite(data, size, num_elem, stdout);
510 * Escapes a string so it can be used safely.
511 * Currently escapes to ensure the validity for use as a JSON string
512 * Does not support unicode specifiers in the form of \uXXXX.
513 * @param buf The string to be escaped
514 * @return The escaped string (return value == buf)
516 char *FCGI_EscapeText(char *buf)
519 length = strlen(buf);
521 //Escape special characters. Must count down to escape properly
522 for (i = length - 1; i >= 0; i--) {
523 if (buf[i] < 0x20) { //Control characters
525 } else if (buf[i] == '"') {
526 if (i-1 >= 0 && buf[i-1] == '\\')
530 } else if (buf[i] == '\\') {
531 if (i-1 >= 0 && buf[i-1] == '\'')
541 * Main FCGI request loop that receives/responds to client requests.
542 * @param data Reserved.
543 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
544 * TODO: Get this to exit with the rest of the program!
546 void * FCGI_RequestLoop (void *data)
548 FCGIContext context = {0};
550 Log(LOGDEBUG, "Start loop");
551 while (FCGI_Accept() >= 0) {
553 ModuleHandler module_handler = NULL;
554 char module[BUFSIZ], params[BUFSIZ];
556 //strncpy doesn't zero-truncate properly
557 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
558 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
560 FCGI_GetControlCookie(context.received_key);
561 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
562 Log(LOGDEBUG, "Control key: %s", context.received_key);
565 //Remove trailing slashes (if present) from module query
566 size_t lastchar = strlen(module) - 1;
567 if (lastchar > 0 && module[lastchar] == '/')
568 module[lastchar] = 0;
570 //Default to the 'identify' module if none specified
572 strcpy(module, "identify");
574 if (!strcmp("identify", module)) {
575 module_handler = IdentifyHandler;
576 } else if (!strcmp("control", module)) {
577 module_handler = Control_Handler;
578 } else if (!strcmp("sensors", module)) {
579 module_handler = Sensor_Handler;
580 } else if (!strcmp("actuators", module)) {
581 module_handler = Actuator_Handler;
582 } else if (!strcmp("image", module)) {
583 module_handler = Image_Handler;
584 } else if (!strcmp("pin", module)) {
585 module_handler = Pin_Handler; // *Debug only* pin test module
586 } else if (!strcmp("bind", module)) {
587 module_handler = Login_Handler;
588 } else if (!strcmp("unbind", module)) {
589 module_handler = Logout_Handler;
592 context.current_module = module;
593 context.response_number++;
597 if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
598 //if (false) // Testing
600 if (!FCGI_HasControl(&context))
602 if (g_options.auth_method == AUTH_NONE)
604 Log(LOGWARN, "Locking control (no auth!)");
605 FCGI_LockControl(&context, NOAUTH_USERNAME, USER_ADMIN);
606 FCGI_SendControlCookie(&context, true);
610 FCGI_RejectJSON(&context, "Please login. Invalid control key.");
615 //Escape all special characters.
616 //Don't escape for login (password may have special chars?)
617 FCGI_EscapeText(params);
620 module_handler(&context, params);
624 FCGI_RejectJSON(&context, "Unhandled module");
628 Log(LOGDEBUG, "Thread exiting.");
629 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.