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) {
37 bool ident_sensors = false, ident_actuators = false;
38 char control_key[CONTROL_KEY_BUFSIZ];
42 snprintf(control_key, CONTROL_KEY_BUFSIZ, "%s", getenv("COOKIE_STRING"));
43 has_control = FCGI_HasControl(context, control_key);
45 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
46 {"actuators", &ident_actuators, FCGI_BOOL_T}};
47 if (!FCGI_ParseRequest(context, params, values, 2))
50 FCGI_BeginJSON(context, STATUS_OK);
51 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
52 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
53 FCGI_JSONLong("api_version", API_VERSION);
54 FCGI_JSONBool("logged_in", has_control);
55 FCGI_JSONPair("user_name", has_control ? context->user_name : "");
57 //Sensor and actuator information
59 FCGI_JSONKey("sensors");
60 FCGI_JSONValue("{\n\t\t");
61 for (i = 0; i < g_num_sensors; i++) {
63 FCGI_JSONValue(",\n\t\t");
65 FCGI_JSONValue("\"%d\" : \"%s\"", i, Sensor_GetName(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 < g_num_actuators; i++) {
74 FCGI_JSONValue(",\n\t\t");
76 FCGI_JSONValue("\"%d\" : \"%s\"", i, Actuator_GetName(i));
78 FCGI_JSONValue("\n\t}");
84 * Given an authorised user, attempt to set the control over the system.
85 * Modifies members in the context structure appropriately if successful.
86 * @param context The context to work in
87 * @param user_name - Name of the user
88 * @param user_type - Type of the user, passed after successful authentication
89 * @return true on success, false otherwise (eg someone else already in control)
91 bool FCGI_LockControl(FCGIContext *context, const char * user_name, UserType user_type)
94 time_t now = time(NULL);
95 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
98 // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
99 if (user_type == USER_UNAUTH ||
100 (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
103 // Release any existing control (if any)
104 FCGI_ReleaseControl(context);
107 context->control_timestamp = now;
109 // Generate a SHA1 hash for the user
111 unsigned char sha1[20];
114 SHA1_Update(&sha1ctx, &now, sizeof(now));
115 SHA1_Update(&sha1ctx, &i, sizeof(i));
116 SHA1_Final(sha1, &sha1ctx);
117 for (i = 0; i < sizeof(sha1); i++)
118 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
120 // Set the IPv4 address
121 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
124 int uname_len = strlen(user_name);
125 i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
127 Log(LOGERR, "Username at %d characters too long (limit %d)",
128 uname_len, sizeof(context->user_name));
132 context->user_type = user_type;
134 // Build the user directory
135 i = snprintf(context->user_dir, sizeof(context->user_dir), "%s/%s",
136 g_options.experiment_dir, context->user_name);
137 if (i >= sizeof(context->user_dir)) {
138 Log(LOGERR, "Experiment dir too long (required %d, limit %d)",
139 i, sizeof(context->user_dir));
143 Log(LOGDEBUG, "User dir: %s", context->user_dir);
145 if (mkdir(context->user_dir, 0777) != 0 && errno != EEXIST)
147 Log(LOGERR, "Couldn't create user directory %s - %s",
148 context->user_dir, strerror(errno));
156 * Given an FCGIContext, determines if the current user (as specified by
157 * the key) has control or not. If validated, the context control_timestamp is
159 * @param context The context to work in
160 * @param key The control key to be validated.
161 * @return TRUE if authorized, FALSE if not.
163 bool FCGI_HasControl(FCGIContext *context, const char *key) {
164 time_t now = time(NULL);
165 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
166 key != NULL && context->control_key[0] != '\0' &&
167 !strcmp(context->control_key, key);
169 context->control_timestamp = now; //Update the control_timestamp
176 * Revokes the current control key, if present.
177 * @param context The context to work in
179 void FCGI_ReleaseControl(FCGIContext *context) {
180 *(context->control_key) = 0;
181 // Note: context->user_name should *not* be cleared
186 * Extracts a key/value pair from a request string.
187 * Note that the input is modified by this function.
188 * @param in The string from which to extract the pair
189 * @param key A pointer to a variable to hold the key string
190 * @param value A pointer to a variable to hold the value string
191 * @return A pointer to the start of the next search location, or NULL if
192 * the EOL is reached.
194 char *FCGI_KeyPair(char *in, const char **key, const char **value)
197 if (!in || !*in) { //Invalid input or string is EOL
202 //Find either = or &, whichever comes first
203 if ((ptr = strpbrk(in, "=&"))) {
204 if (*ptr == '&') { //No value specified
208 //Stopped at an '=' sign
211 if ((ptr = strchr(ptr,'&'))) {
217 } else { //No value specified and no other pair
225 * Aids in parsing request parameters.
226 * Input: The expected keys along with their type and whether or not
228 * @param context The context to work in
229 * @param params The parameter string to be parsed
230 * @param values An array of FCGIValue's that specify expected keys
231 * @param count The number of elements in 'values'.
232 * @return true If the parameter string was parsed successfully, false otherwise.
233 * Modes of failure include: Invalid a parsing error on the value,
234 * an unknown key is specified,
235 * a key/value pair is specified more than once, or
236 * not all required keys were present.
237 * If this function returns false, it is guaranteed that FCGI_RejectJSON
238 * has already been called with the appropriate description message.
240 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
242 const char *key, *value;
243 char buf[BUFSIZ], *ptr;
246 while ((params = FCGI_KeyPair(params, &key, &value))) {
247 for (i = 0; i < count; i++) {
248 if (!strcmp(key, values[i].key)) {
249 FCGIValue *val = &values[i];
251 if (FCGI_RECEIVED(val->flags)) {
252 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
253 FCGI_RejectJSON(context, buf);
256 val->flags |= FCGI_PARAM_RECEIVED;
258 switch(FCGI_TYPE(val->flags)) {
260 if (!*value) //No value: Default true
261 *((bool*) val->value) = true;
263 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
265 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
266 FCGI_RejectJSON(context, buf);
271 case FCGI_INT_T: case FCGI_LONG_T: {
272 long parsed = strtol(value, &ptr, 10);
273 if (!*value || *ptr) {
274 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
275 FCGI_RejectJSON(context, buf);
279 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
280 *((int*) val->value) = (int) parsed;
282 *((long*) val->value) = parsed;
285 *((double*) val->value) = strtod(value, &ptr);
286 if (!*value || *ptr) {
287 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
288 FCGI_RejectJSON(context, buf);
293 *((const char**) val->value) = value;
296 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
298 break; //No need to search any more
302 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
303 FCGI_RejectJSON(context, buf);
308 //Check that required parameters are received
309 for (i = 0; i < count; i++) {
310 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
311 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
312 FCGI_RejectJSON(context, buf);
320 * Begins a response to the client in JSON format.
321 * @param context The context to work in.
322 * @param status_code The status code to be returned.
324 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
326 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
328 printf("\t\"module\" : \"%s\"", context->current_module);
329 FCGI_JSONLong("status", status_code);
330 //Time and running statistics
332 gettimeofday(&now, NULL);
333 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
334 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
335 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
336 FCGI_JSONPair("control_state", Control_GetModeName());
340 * Generic accept response in JSON format.
341 * @param context The context to work in
342 * @param description A short description.
343 * @param cookie Optional. If given, the cookie field is set to that value.
345 void FCGI_AcceptJSON(FCGIContext *context, const char *description, const char *cookie)
347 printf("Content-type: application/json; charset=utf-8\r\n");
349 printf("Set-Cookie: %s\r\n", cookie);
352 printf("\t\"module\" : \"%s\"", context->current_module);
353 FCGI_JSONLong("status", STATUS_OK);
354 FCGI_JSONPair("description", description);
359 * Adds a key/value pair to a JSON response. The response must have already
360 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
361 * @param key The key of the JSON entry
362 * @param value The value associated with the key.
364 void FCGI_JSONPair(const char *key, const char *value)
366 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
370 * Similar to FCGI_JSONPair except for signed integer values.
371 * @param key The key of the JSON entry
372 * @param value The value associated with the key
374 void FCGI_JSONLong(const char *key, long value)
376 printf(",\r\n\t\"%s\" : %ld", key, value);
380 * Similar to FCGI_JsonPair except for floating point values.
381 * @param key The key of the JSON entry
382 * @param value The value associated with the key
384 void FCGI_JSONDouble(const char *key, double value)
386 printf(",\r\n\t\"%s\" : %f", key, value);
390 * Similar to FCGI_JsonPair except for boolean values.
391 * @param key The key of the JSON entry
392 * @param value The value associated with the key
394 void FCGI_JSONBool(const char *key, bool value)
396 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
400 * Begins a JSON entry by writing the key. To be used in conjunction
401 * with FCGI_JsonValue.
402 * @param key The key of the JSON entry
404 void FCGI_JSONKey(const char *key)
406 printf(",\r\n\t\"%s\" : ", key);
410 * Ends a JSON response that was initiated by FCGI_BeginJSON.
418 * To be used when the input parameters are rejected. The return data
419 * will also have debugging information provided.
420 * @param context The context to work in
421 * @param status The status the return data should have.
422 * @param description A short description of why the input was rejected.
424 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
426 if (description == NULL)
427 description = "Unknown";
429 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
430 FCGI_BeginJSON(context, status);
431 FCGI_JSONPair("description", description);
432 FCGI_JSONLong("responsenumber", context->response_number);
433 //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
434 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
435 FCGI_JSONPair("user", getenv("REMOTE_USER"));
436 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
441 * Generates a response to the client as described by the format parameter and
442 * extra arguments (exactly like printf). To be used when none of the other
443 * predefined functions will work exactly as needed. Extra care should be taken
444 * to ensure the correctness of the output.
445 * @param format The format string
446 * @param ... Any extra arguments as required by the format string.
448 void FCGI_PrintRaw(const char *format, ...)
451 va_start(list, format);
452 vprintf(format, list);
461 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
463 Log(LOGDEBUG,"Writing!");
464 fwrite(data, size, num_elem, stdout);
468 * Escapes a string so it can be used safely.
469 * Currently escapes to ensure the validity for use as a JSON string
470 * Does not support unicode specifiers in the form of \uXXXX.
471 * @param buf The string to be escaped
472 * @return The escaped string (return value == buf)
474 char *FCGI_EscapeText(char *buf)
477 length = strlen(buf);
479 //Escape special characters. Must count down to escape properly
480 for (i = length - 1; i >= 0; i--) {
481 if (buf[i] < 0x20) { //Control characters
483 } else if (buf[i] == '"') {
484 if (i-1 >= 0 && buf[i-1] == '\\')
488 } else if (buf[i] == '\\') {
489 if (i-1 >= 0 && buf[i-1] == '\'')
499 * Main FCGI request loop that receives/responds to client requests.
500 * @param data Reserved.
501 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
502 * TODO: Get this to exit with the rest of the program!
504 void * FCGI_RequestLoop (void *data)
506 FCGIContext context = {0};
508 Log(LOGDEBUG, "Start loop");
509 while (FCGI_Accept() >= 0) {
511 ModuleHandler module_handler = NULL;
512 char module[BUFSIZ], params[BUFSIZ], control_key[CONTROL_KEY_BUFSIZ];
514 //strncpy doesn't zero-truncate properly
515 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
516 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
518 //Hack to get the nameless cookie only
519 snprintf(control_key, CONTROL_KEY_BUFSIZ, "%s", getenv("COOKIE_STRING"));
521 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
522 Log(LOGDEBUG, "Control key: %s", control_key);
525 //Remove trailing slashes (if present) from module query
526 size_t lastchar = strlen(module) - 1;
527 if (lastchar > 0 && module[lastchar] == '/')
528 module[lastchar] = 0;
530 //Default to the 'identify' module if none specified
532 strcpy(module, "identify");
534 if (!strcmp("identify", module)) {
535 module_handler = IdentifyHandler;
536 } else if (!strcmp("control", module)) {
537 module_handler = Control_Handler;
538 } else if (!strcmp("sensors", module)) {
539 module_handler = Sensor_Handler;
540 } else if (!strcmp("actuators", module)) {
541 module_handler = Actuator_Handler;
542 } else if (!strcmp("image", module)) {
543 module_handler = Image_Handler;
544 } else if (!strcmp("pin", module)) {
545 module_handler = Pin_Handler; // *Debug only* pin test module
546 } else if (!strcmp("bind", module)) {
547 module_handler = Login_Handler;
548 } else if (!strcmp("unbind", module)) {
549 module_handler = Logout_Handler;
552 context.current_module = module;
553 context.response_number++;
557 if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
558 //if (false) // Testing
560 if (!FCGI_HasControl(&context, control_key))
562 FCGI_RejectJSON(&context, "Please login. Invalid control key.");
566 //Escape all special characters.
567 //Don't escape for login (password may have special chars?)
568 FCGI_EscapeText(params);
571 module_handler(&context, params);
575 FCGI_RejectJSON(&context, "Unhandled module");
579 Log(LOGDEBUG, "Thread exiting.");
580 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.