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 FCGI_JSONValue("\"%d\" : \"%s\"", i, Sensor_GetName(i));
69 FCGI_JSONValue("\n\t}");
71 if (ident_actuators) {
72 FCGI_JSONKey("actuators");
73 FCGI_JSONValue("{\n\t\t");
74 for (i = 0; i < g_num_actuators; i++) {
76 FCGI_JSONValue(",\n\t\t");
78 FCGI_JSONValue("\"%d\" : \"%s\"", i, Actuator_GetName(i));
80 FCGI_JSONValue("\n\t}");
86 * Given an authorised user, attempt to set the control over the system.
87 * Modifies members in the context structure appropriately if successful.
88 * @param context The context to work in
89 * @param user_name - Name of the user
90 * @param user_type - Type of the user, passed after successful authentication
91 * @return true on success, false otherwise (eg someone else already in control)
93 bool FCGI_LockControl(FCGIContext *context, const char * user_name, UserType user_type)
96 time_t now = time(NULL);
97 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
100 // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
101 if (user_type == USER_UNAUTH ||
102 (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
105 // Release any existing control (if any)
106 FCGI_ReleaseControl(context);
109 context->control_timestamp = now;
111 // Generate a SHA1 hash for the user
113 unsigned char sha1[20];
116 SHA1_Update(&sha1ctx, &now, sizeof(now));
117 SHA1_Update(&sha1ctx, &i, sizeof(i));
118 SHA1_Final(sha1, &sha1ctx);
119 for (i = 0; i < sizeof(sha1); i++)
120 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
122 // Set the IPv4 address
123 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
126 int uname_len = strlen(user_name);
127 i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
129 Log(LOGERR, "Username at %d characters too long (limit %d)",
130 uname_len, sizeof(context->user_name));
134 context->user_type = user_type;
136 // Build the user directory
137 i = snprintf(context->user_dir, sizeof(context->user_dir), "%s/%s",
138 g_options.experiment_dir, context->user_name);
139 if (i >= sizeof(context->user_dir)) {
140 Log(LOGERR, "Experiment dir too long (required %d, limit %d)",
141 i, sizeof(context->user_dir));
145 Log(LOGDEBUG, "User dir: %s", context->user_dir);
147 if (mkdir(context->user_dir, 0777) != 0 && errno != EEXIST)
149 Log(LOGERR, "Couldn't create user directory %s - %s",
150 context->user_dir, strerror(errno));
158 * Given an FCGIContext, determines if the current user (as specified by
159 * the key) has control or not. If validated, the context control_timestamp is
161 * @param context The context to work in
162 * @param key The control key to be validated.
163 * @return TRUE if authorized, FALSE if not.
165 bool FCGI_HasControl(FCGIContext *context)
167 time_t now = time(NULL);
168 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
169 context->control_key[0] != '\0' &&
170 !strcmp(context->control_key, context->received_key);
172 context->control_timestamp = now; //Update the control_timestamp
179 * Revokes the current control key, if present.
180 * @param context The context to work in
182 void FCGI_ReleaseControl(FCGIContext *context)
184 *(context->control_key) = 0;
185 // Note: context->user_name should *not* be cleared
190 * Gets the control cookie
191 * @param buffer A storage buffer of exactly CONTROL_KEY_BUFSIZ length to
192 store the control key
194 void FCGI_GetControlCookie(char buffer[CONTROL_KEY_BUFSIZ])
196 const char *cookies = getenv("COOKIE_STRING");
197 const char *start = strstr(cookies, "mctxkey=");
199 *buffer = 0; //Clear the buffer
202 start += 8; //length of mctxkey=
203 for (i = 0; i < CONTROL_KEY_BUFSIZ; i++) {
204 if (*start == 0 || *start == ';') {
207 buffer[i] = *start++;
214 * Sends the control key to the user as a cookie.
215 * @param context the context to work in
216 * @param set Whether to set or unset the control cookie
218 void FCGI_SendControlCookie(FCGIContext *context, bool set) {
220 printf("Set-Cookie: mctxkey=%s\r\n", context->control_key);
222 printf("Set-Cookie: mctxkey=\r\n");
227 * Extracts a key/value pair from a request string.
228 * Note that the input is modified by this function.
229 * @param in The string from which to extract the pair
230 * @param key A pointer to a variable to hold the key string
231 * @param value A pointer to a variable to hold the value string
232 * @return A pointer to the start of the next search location, or NULL if
233 * the EOL is reached.
235 char *FCGI_KeyPair(char *in, const char **key, const char **value)
238 if (!in || !*in) { //Invalid input or string is EOL
243 //Find either = or &, whichever comes first
244 if ((ptr = strpbrk(in, "=&"))) {
245 if (*ptr == '&') { //No value specified
249 //Stopped at an '=' sign
252 if ((ptr = strchr(ptr,'&'))) {
258 } else { //No value specified and no other pair
266 * Aids in parsing request parameters.
267 * Input: The expected keys along with their type and whether or not
269 * @param context The context to work in
270 * @param params The parameter string to be parsed
271 * @param values An array of FCGIValue's that specify expected keys
272 * @param count The number of elements in 'values'.
273 * @return true If the parameter string was parsed successfully, false otherwise.
274 * Modes of failure include: Invalid a parsing error on the value,
275 * an unknown key is specified,
276 * a key/value pair is specified more than once, or
277 * not all required keys were present.
278 * If this function returns false, it is guaranteed that FCGI_RejectJSON
279 * has already been called with the appropriate description message.
281 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
283 const char *key, *value;
284 char buf[BUFSIZ], *ptr;
287 while ((params = FCGI_KeyPair(params, &key, &value))) {
288 for (i = 0; i < count; i++) {
289 if (!strcmp(key, values[i].key)) {
290 FCGIValue *val = &values[i];
292 if (FCGI_RECEIVED(val->flags)) {
293 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
294 FCGI_RejectJSON(context, buf);
297 val->flags |= FCGI_PARAM_RECEIVED;
299 switch(FCGI_TYPE(val->flags)) {
301 if (!*value) //No value: Default true
302 *((bool*) val->value) = true;
304 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
306 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
307 FCGI_RejectJSON(context, buf);
312 case FCGI_INT_T: case FCGI_LONG_T: {
313 long parsed = strtol(value, &ptr, 10);
314 if (!*value || *ptr) {
315 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
316 FCGI_RejectJSON(context, buf);
320 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
321 *((int*) val->value) = (int) parsed;
323 *((long*) val->value) = parsed;
326 *((double*) val->value) = strtod(value, &ptr);
327 if (!*value || *ptr) {
328 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
329 FCGI_RejectJSON(context, buf);
334 *((const char**) val->value) = value;
337 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
339 break; //No need to search any more
343 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
344 FCGI_RejectJSON(context, buf);
349 //Check that required parameters are received
350 for (i = 0; i < count; i++) {
351 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
352 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
353 FCGI_RejectJSON(context, buf);
361 * Begins a response to the client in JSON format.
362 * @param context The context to work in.
363 * @param status_code The status code to be returned.
365 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
367 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
369 printf("\t\"module\" : \"%s\"", context->current_module);
370 FCGI_JSONLong("status", status_code);
371 //Time and running statistics
373 clock_gettime(CLOCK_MONOTONIC, &now);
374 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
375 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
376 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
377 FCGI_JSONPair("control_state", Control_GetModeName());
381 * Generic accept response in JSON format.
382 * @param context The context to work in
383 * @param description A short description.
384 * @param cookie Optional. If given, the cookie field is set to that value.
386 void FCGI_AcceptJSON(FCGIContext *context, const char *description)
388 printf("Content-type: application/json; charset=utf-8\r\n");
390 printf("\t\"module\" : \"%s\"", context->current_module);
391 FCGI_JSONLong("status", STATUS_OK);
392 FCGI_JSONPair("description", description);
397 * Adds a key/value pair to a JSON response. The response must have already
398 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
399 * @param key The key of the JSON entry
400 * @param value The value associated with the key.
402 void FCGI_JSONPair(const char *key, const char *value)
404 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
408 * Similar to FCGI_JSONPair except for signed integer values.
409 * @param key The key of the JSON entry
410 * @param value The value associated with the key
412 void FCGI_JSONLong(const char *key, long value)
414 printf(",\r\n\t\"%s\" : %ld", key, value);
418 * Similar to FCGI_JsonPair except for floating point values.
419 * @param key The key of the JSON entry
420 * @param value The value associated with the key
422 void FCGI_JSONDouble(const char *key, double value)
424 printf(",\r\n\t\"%s\" : %.9f", key, value);
428 * Similar to FCGI_JsonPair except for boolean values.
429 * @param key The key of the JSON entry
430 * @param value The value associated with the key
432 void FCGI_JSONBool(const char *key, bool value)
434 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
438 * Begins a JSON entry by writing the key. To be used in conjunction
439 * with FCGI_JsonValue.
440 * @param key The key of the JSON entry
442 void FCGI_JSONKey(const char *key)
444 printf(",\r\n\t\"%s\" : ", key);
448 * Ends a JSON response that was initiated by FCGI_BeginJSON.
456 * To be used when the input parameters are rejected. The return data
457 * will also have debugging information provided.
458 * @param context The context to work in
459 * @param status The status the return data should have.
460 * @param description A short description of why the input was rejected.
462 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
464 if (description == NULL)
465 description = "Unknown";
467 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
468 FCGI_BeginJSON(context, status);
469 FCGI_JSONPair("description", description);
470 FCGI_JSONLong("responsenumber", context->response_number);
471 //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
472 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
473 FCGI_JSONPair("user", getenv("REMOTE_USER"));
474 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
479 * Generates a response to the client as described by the format parameter and
480 * extra arguments (exactly like printf). To be used when none of the other
481 * predefined functions will work exactly as needed. Extra care should be taken
482 * to ensure the correctness of the output.
483 * @param format The format string
484 * @param ... Any extra arguments as required by the format string.
486 void FCGI_PrintRaw(const char *format, ...)
489 va_start(list, format);
490 vprintf(format, list);
499 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
501 Log(LOGDEBUG,"Writing!");
502 fwrite(data, size, num_elem, stdout);
506 * Escapes a string so it can be used safely.
507 * Currently escapes to ensure the validity for use as a JSON string
508 * Does not support unicode specifiers in the form of \uXXXX.
509 * @param buf The string to be escaped
510 * @return The escaped string (return value == buf)
512 char *FCGI_EscapeText(char *buf)
515 length = strlen(buf);
517 //Escape special characters. Must count down to escape properly
518 for (i = length - 1; i >= 0; i--) {
519 if (buf[i] < 0x20) { //Control characters
521 } else if (buf[i] == '"') {
522 if (i-1 >= 0 && buf[i-1] == '\\')
526 } else if (buf[i] == '\\') {
527 if (i-1 >= 0 && buf[i-1] == '\'')
537 * Main FCGI request loop that receives/responds to client requests.
538 * @param data Reserved.
539 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
540 * TODO: Get this to exit with the rest of the program!
542 void * FCGI_RequestLoop (void *data)
544 FCGIContext context = {0};
546 Log(LOGDEBUG, "Start loop");
547 while (FCGI_Accept() >= 0) {
549 ModuleHandler module_handler = NULL;
550 char module[BUFSIZ], params[BUFSIZ];
552 //strncpy doesn't zero-truncate properly
553 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
554 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
556 FCGI_GetControlCookie(context.received_key);
557 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
558 Log(LOGDEBUG, "Control key: %s", context.received_key);
561 //Remove trailing slashes (if present) from module query
562 size_t lastchar = strlen(module) - 1;
563 if (lastchar > 0 && module[lastchar] == '/')
564 module[lastchar] = 0;
566 //Default to the 'identify' module if none specified
568 strcpy(module, "identify");
570 if (!strcmp("identify", module)) {
571 module_handler = IdentifyHandler;
572 } else if (!strcmp("control", module)) {
573 module_handler = Control_Handler;
574 } else if (!strcmp("sensors", module)) {
575 module_handler = Sensor_Handler;
576 } else if (!strcmp("actuators", module)) {
577 module_handler = Actuator_Handler;
578 } else if (!strcmp("image", module)) {
579 module_handler = Image_Handler;
580 } else if (!strcmp("pin", module)) {
581 module_handler = Pin_Handler; // *Debug only* pin test module
582 } else if (!strcmp("bind", module)) {
583 module_handler = Login_Handler;
584 } else if (!strcmp("unbind", module)) {
585 module_handler = Logout_Handler;
588 context.current_module = module;
589 context.response_number++;
593 if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
594 //if (false) // Testing
596 if (!FCGI_HasControl(&context))
598 if (g_options.auth_method == AUTH_NONE)
600 Log(LOGWARN, "Locking control (no auth!)");
601 FCGI_LockControl(&context, NOAUTH_USERNAME, USER_ADMIN);
605 FCGI_RejectJSON(&context, "Please login. Invalid control key.");
610 //Escape all special characters.
611 //Don't escape for login (password may have special chars?)
612 FCGI_EscapeText(params);
615 module_handler(&context, params);
619 FCGI_RejectJSON(&context, "Unhandled module");
623 Log(LOGDEBUG, "Thread exiting.");
624 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.