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__);
50 t.tv_sec = 0; t.tv_nsec = 0;
51 clock_getres(CLOCK_MONOTONIC, &t);
52 FCGI_JSONDouble("clock_getres", TIMEVAL_TO_DOUBLE(t));
53 FCGI_JSONLong("api_version", API_VERSION);
55 bool has_control = FCGI_HasControl(context);
56 FCGI_JSONBool("logged_in", has_control);
57 FCGI_JSONPair("user_name", has_control ? context->user_name : "");
60 //Sensor and actuator information
62 FCGI_JSONKey("sensors");
63 FCGI_JSONValue("{\n\t\t");
64 for (i = 0; i < g_num_sensors; i++) {
66 FCGI_JSONValue(",\n\t\t");
68 FCGI_JSONValue("\"%d\" : \"%s\"", i, Sensor_GetName(i));
70 FCGI_JSONValue("\n\t}");
72 if (ident_actuators) {
73 FCGI_JSONKey("actuators");
74 FCGI_JSONValue("{\n\t\t");
75 for (i = 0; i < g_num_actuators; i++) {
77 FCGI_JSONValue(",\n\t\t");
79 FCGI_JSONValue("\"%d\" : \"%s\"", i, Actuator_GetName(i));
81 FCGI_JSONValue("\n\t}");
87 * Given an authorised user, attempt to set the control over the system.
88 * Modifies members in the context structure appropriately if successful.
89 * @param context The context to work in
90 * @param user_name - Name of the user
91 * @param user_type - Type of the user, passed after successful authentication
92 * @return true on success, false otherwise (eg someone else already in control)
94 bool FCGI_LockControl(FCGIContext *context, const char * user_name, UserType user_type)
97 time_t now = time(NULL);
98 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
101 // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
102 if (user_type == USER_UNAUTH ||
103 (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
106 // Release any existing control (if any)
107 FCGI_ReleaseControl(context);
110 context->control_timestamp = now;
112 // Generate a SHA1 hash for the user
114 unsigned char sha1[20];
117 SHA1_Update(&sha1ctx, &now, sizeof(now));
118 SHA1_Update(&sha1ctx, &i, sizeof(i));
119 SHA1_Final(sha1, &sha1ctx);
120 for (i = 0; i < sizeof(sha1); i++)
121 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
123 // Set the IPv4 address
124 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
127 int uname_len = strlen(user_name);
128 i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
130 Log(LOGERR, "Username at %d characters too long (limit %d)",
131 uname_len, sizeof(context->user_name));
135 context->user_type = user_type;
137 // Build the user directory
138 i = snprintf(context->user_dir, sizeof(context->user_dir), "%s/%s",
139 g_options.experiment_dir, context->user_name);
140 if (i >= sizeof(context->user_dir)) {
141 Log(LOGERR, "Experiment dir too long (required %d, limit %d)",
142 i, sizeof(context->user_dir));
146 Log(LOGDEBUG, "User dir: %s", context->user_dir);
148 if (mkdir(context->user_dir, 0777) != 0 && errno != EEXIST)
150 Log(LOGERR, "Couldn't create user directory %s - %s",
151 context->user_dir, strerror(errno));
159 * Given an FCGIContext, determines if the current user (as specified by
160 * the key) has control or not. If validated, the context control_timestamp is
162 * @param context The context to work in
163 * @param key The control key to be validated.
164 * @return TRUE if authorized, FALSE if not.
166 bool FCGI_HasControl(FCGIContext *context)
168 time_t now = time(NULL);
169 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
170 context->control_key[0] != '\0' &&
171 !strcmp(context->control_key, context->received_key);
173 context->control_timestamp = now; //Update the control_timestamp
180 * Revokes the current control key, if present.
181 * @param context The context to work in
183 void FCGI_ReleaseControl(FCGIContext *context)
185 *(context->control_key) = 0;
186 // Note: context->user_name should *not* be cleared
191 * Gets the control cookie
192 * @param buffer A storage buffer of exactly CONTROL_KEY_BUFSIZ length to
193 store the control key
195 void FCGI_GetControlCookie(char buffer[CONTROL_KEY_BUFSIZ])
197 const char *cookies = getenv("COOKIE_STRING");
198 const char *start = strstr(cookies, "mctxkey=");
200 *buffer = 0; //Clear the buffer
203 start += 8; //length of mctxkey=
204 for (i = 0; i < CONTROL_KEY_BUFSIZ; i++) {
205 if (*start == 0 || *start == ';') {
208 buffer[i] = *start++;
215 * Sends the control key to the user as a cookie.
216 * @param context the context to work in
217 * @param set Whether to set or unset the control cookie
219 void FCGI_SendControlCookie(FCGIContext *context, bool set) {
221 printf("Set-Cookie: mctxkey=%s\r\n", context->control_key);
223 printf("Set-Cookie: mctxkey=\r\n");
228 * Extracts a key/value pair from a request string.
229 * Note that the input is modified by this function.
230 * @param in The string from which to extract the pair
231 * @param key A pointer to a variable to hold the key string
232 * @param value A pointer to a variable to hold the value string
233 * @return A pointer to the start of the next search location, or NULL if
234 * the EOL is reached.
236 char *FCGI_KeyPair(char *in, const char **key, const char **value)
239 if (!in || !*in) { //Invalid input or string is EOL
244 //Find either = or &, whichever comes first
245 if ((ptr = strpbrk(in, "=&"))) {
246 if (*ptr == '&') { //No value specified
250 //Stopped at an '=' sign
253 if ((ptr = strchr(ptr,'&'))) {
259 } else { //No value specified and no other pair
267 * Aids in parsing request parameters.
268 * Input: The expected keys along with their type and whether or not
270 * @param context The context to work in
271 * @param params The parameter string to be parsed
272 * @param values An array of FCGIValue's that specify expected keys
273 * @param count The number of elements in 'values'.
274 * @return true If the parameter string was parsed successfully, false otherwise.
275 * Modes of failure include: Invalid a parsing error on the value,
276 * an unknown key is specified,
277 * a key/value pair is specified more than once, or
278 * not all required keys were present.
279 * If this function returns false, it is guaranteed that FCGI_RejectJSON
280 * has already been called with the appropriate description message.
282 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
284 const char *key, *value;
285 char buf[BUFSIZ], *ptr;
288 while ((params = FCGI_KeyPair(params, &key, &value))) {
289 for (i = 0; i < count; i++) {
290 if (!strcmp(key, values[i].key)) {
291 FCGIValue *val = &values[i];
293 if (FCGI_RECEIVED(val->flags)) {
294 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
295 FCGI_RejectJSON(context, buf);
298 val->flags |= FCGI_PARAM_RECEIVED;
300 switch(FCGI_TYPE(val->flags)) {
302 if (!*value) //No value: Default true
303 *((bool*) val->value) = true;
305 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
307 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
308 FCGI_RejectJSON(context, buf);
313 case FCGI_INT_T: case FCGI_LONG_T: {
314 long parsed = strtol(value, &ptr, 10);
315 if (!*value || *ptr) {
316 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
317 FCGI_RejectJSON(context, buf);
321 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
322 *((int*) val->value) = (int) parsed;
324 *((long*) val->value) = parsed;
327 *((double*) val->value) = strtod(value, &ptr);
328 if (!*value || *ptr) {
329 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
330 FCGI_RejectJSON(context, buf);
335 *((const char**) val->value) = value;
338 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
340 break; //No need to search any more
344 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
345 FCGI_RejectJSON(context, buf);
350 //Check that required parameters are received
351 for (i = 0; i < count; i++) {
352 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
353 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
354 FCGI_RejectJSON(context, buf);
362 * Begins a response to the client in JSON format.
363 * @param context The context to work in.
364 * @param status_code The status code to be returned.
366 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
368 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
370 printf("\t\"module\" : \"%s\"", context->current_module);
371 FCGI_JSONLong("status", status_code);
372 //Time and running statistics
374 clock_gettime(CLOCK_MONOTONIC, &now);
375 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
376 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
377 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
378 FCGI_JSONPair("control_state", Control_GetModeName());
382 * Generic accept response in JSON format.
383 * @param context The context to work in
384 * @param description A short description.
385 * @param cookie Optional. If given, the cookie field is set to that value.
387 void FCGI_AcceptJSON(FCGIContext *context, const char *description)
389 printf("Content-type: application/json; charset=utf-8\r\n");
391 printf("\t\"module\" : \"%s\"", context->current_module);
392 FCGI_JSONLong("status", STATUS_OK);
393 FCGI_JSONPair("description", description);
398 * Adds a key/value pair to a JSON response. The response must have already
399 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
400 * @param key The key of the JSON entry
401 * @param value The value associated with the key.
403 void FCGI_JSONPair(const char *key, const char *value)
405 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
409 * Similar to FCGI_JSONPair except for signed integer values.
410 * @param key The key of the JSON entry
411 * @param value The value associated with the key
413 void FCGI_JSONLong(const char *key, long value)
415 printf(",\r\n\t\"%s\" : %ld", key, value);
419 * Similar to FCGI_JsonPair except for floating point values.
420 * @param key The key of the JSON entry
421 * @param value The value associated with the key
423 void FCGI_JSONDouble(const char *key, double value)
425 printf(",\r\n\t\"%s\" : %.9f", key, value);
429 * Similar to FCGI_JsonPair except for boolean values.
430 * @param key The key of the JSON entry
431 * @param value The value associated with the key
433 void FCGI_JSONBool(const char *key, bool value)
435 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
439 * Begins a JSON entry by writing the key. To be used in conjunction
440 * with FCGI_JsonValue.
441 * @param key The key of the JSON entry
443 void FCGI_JSONKey(const char *key)
445 printf(",\r\n\t\"%s\" : ", key);
449 * Ends a JSON response that was initiated by FCGI_BeginJSON.
457 * To be used when the input parameters are rejected. The return data
458 * will also have debugging information provided.
459 * @param context The context to work in
460 * @param status The status the return data should have.
461 * @param description A short description of why the input was rejected.
463 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
465 if (description == NULL)
466 description = "Unknown";
468 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
469 FCGI_BeginJSON(context, status);
470 FCGI_JSONPair("description", description);
471 FCGI_JSONLong("responsenumber", context->response_number);
472 //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
473 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
474 FCGI_JSONPair("user", getenv("REMOTE_USER"));
475 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
480 * Generates a response to the client as described by the format parameter and
481 * extra arguments (exactly like printf). To be used when none of the other
482 * predefined functions will work exactly as needed. Extra care should be taken
483 * to ensure the correctness of the output.
484 * @param format The format string
485 * @param ... Any extra arguments as required by the format string.
487 void FCGI_PrintRaw(const char *format, ...)
490 va_start(list, format);
491 vprintf(format, list);
500 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
502 Log(LOGDEBUG,"Writing!");
503 fwrite(data, size, num_elem, stdout);
507 * Escapes a string so it can be used safely.
508 * Currently escapes to ensure the validity for use as a JSON string
509 * Does not support unicode specifiers in the form of \uXXXX.
510 * @param buf The string to be escaped
511 * @return The escaped string (return value == buf)
513 char *FCGI_EscapeText(char *buf)
516 length = strlen(buf);
518 //Escape special characters. Must count down to escape properly
519 for (i = length - 1; i >= 0; i--) {
520 if (buf[i] < 0x20) { //Control characters
522 } else if (buf[i] == '"') {
523 if (i-1 >= 0 && buf[i-1] == '\\')
527 } else if (buf[i] == '\\') {
528 if (i-1 >= 0 && buf[i-1] == '\'')
538 * Main FCGI request loop that receives/responds to client requests.
539 * @param data Reserved.
540 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
541 * TODO: Get this to exit with the rest of the program!
543 void * FCGI_RequestLoop (void *data)
545 FCGIContext context = {0};
547 Log(LOGDEBUG, "Start loop");
548 while (FCGI_Accept() >= 0) {
550 ModuleHandler module_handler = NULL;
551 char module[BUFSIZ], params[BUFSIZ];
553 //strncpy doesn't zero-truncate properly
554 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
555 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
557 FCGI_GetControlCookie(context.received_key);
558 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
559 Log(LOGDEBUG, "Control key: %s", context.received_key);
562 //Remove trailing slashes (if present) from module query
563 size_t lastchar = strlen(module) - 1;
564 if (lastchar > 0 && module[lastchar] == '/')
565 module[lastchar] = 0;
567 //Default to the 'identify' module if none specified
569 strcpy(module, "identify");
571 if (!strcmp("identify", module)) {
572 module_handler = IdentifyHandler;
573 } else if (!strcmp("control", module)) {
574 module_handler = Control_Handler;
575 } else if (!strcmp("sensors", module)) {
576 module_handler = Sensor_Handler;
577 } else if (!strcmp("actuators", module)) {
578 module_handler = Actuator_Handler;
579 } else if (!strcmp("image", module)) {
580 module_handler = Image_Handler;
581 } else if (!strcmp("pin", module)) {
582 module_handler = Pin_Handler; // *Debug only* pin test module
583 } else if (!strcmp("bind", module)) {
584 module_handler = Login_Handler;
585 } else if (!strcmp("unbind", module)) {
586 module_handler = Logout_Handler;
589 context.current_module = module;
590 context.response_number++;
594 if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
595 //if (false) // Testing
597 if (!FCGI_HasControl(&context))
599 FCGI_RejectJSON(&context, "Please login. Invalid control key.");
603 //Escape all special characters.
604 //Don't escape for login (password may have special chars?)
605 FCGI_EscapeText(params);
608 module_handler(&context, params);
612 FCGI_RejectJSON(&context, "Unhandled module");
616 Log(LOGDEBUG, "Thread exiting.");
617 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.