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>
22 /**The time period (in seconds) before the control key expires */
23 #define CONTROL_TIMEOUT 180
28 * Identifies build information and the current API version to the user.
29 * Also useful for testing that the API is running and identifying the
30 * sensors and actuators present.
31 * @param context The context to work in
32 * @param params User specified paramters: [actuators, sensors]
34 static void IdentifyHandler(FCGIContext *context, char *params) {
35 bool ident_sensors = false, ident_actuators = false;
36 bool has_control = FCGI_HasControl(context, getenv("COOKIE_STRING"));
39 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
40 {"actuators", &ident_actuators, FCGI_BOOL_T}};
41 if (!FCGI_ParseRequest(context, params, values, 2))
44 FCGI_BeginJSON(context, STATUS_OK);
45 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
46 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
47 FCGI_JSONLong("api_version", API_VERSION);
48 FCGI_JSONBool("logged_in", has_control);
49 FCGI_JSONPair("friendly_name", has_control ? context->friendly_name : "");
51 //Sensor and actuator information
53 FCGI_JSONKey("sensors");
54 FCGI_JSONValue("{\n\t\t");
55 for (i = 0; i < g_num_sensors; i++) {
57 FCGI_JSONValue(",\n\t\t");
59 FCGI_JSONValue("\"%d\" : \"%s\"", i, Sensor_GetName(i));
61 FCGI_JSONValue("\n\t}");
63 if (ident_actuators) {
64 FCGI_JSONKey("actuators");
65 FCGI_JSONValue("{\n\t\t");
66 for (i = 0; i < NUMACTUATORS; i++) {
68 FCGI_JSONValue(",\n\t\t");
70 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
72 FCGI_JSONValue("\n\t}");
78 * Gives the user a key that determines who has control over
79 * the system at any one time. The key can be forcibly generated, revoking
80 * any previous control keys. To be used in conjunction with HTTP
81 * basic authentication.
82 * @param context The context to work in
83 * @param force Whether to force key generation or not.
84 * @return true on success, false otherwise (eg someone else already in control)
86 bool FCGI_LockControl(FCGIContext *context, bool force) {
87 time_t now = time(NULL);
88 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
90 if (force || !*(context->control_key) || expired)
93 unsigned char sha1[20];
97 SHA1_Update(&sha1ctx, &now, sizeof(now));
98 SHA1_Update(&sha1ctx, &i, sizeof(i));
99 SHA1_Final(sha1, &sha1ctx);
101 context->control_timestamp = now;
102 for (i = 0; i < 20; i++)
103 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
104 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
111 * Given an FCGIContext, determines if the current user (as specified by
112 * the key) has control or not. If validated, the context control_timestamp is
114 * @param context The context to work in
115 * @param key The control key to be validated.
116 * @return TRUE if authorized, FALSE if not.
118 bool FCGI_HasControl(FCGIContext *context, const char *key) {
119 time_t now = time(NULL);
120 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
121 key != NULL && context->control_key[0] != '\0' &&
122 !strcmp(context->control_key, key);
124 context->control_timestamp = now; //Update the control_timestamp
131 * Revokes the current control key, if present.
132 * @param context The context to work in
134 void FCGI_ReleaseControl(FCGIContext *context) {
135 *(context->control_key) = 0;
140 * Extracts a key/value pair from a request string.
141 * Note that the input is modified by this function.
142 * @param in The string from which to extract the pair
143 * @param key A pointer to a variable to hold the key string
144 * @param value A pointer to a variable to hold the value string
145 * @return A pointer to the start of the next search location, or NULL if
146 * the EOL is reached.
148 char *FCGI_KeyPair(char *in, const char **key, const char **value)
151 if (!in || !*in) { //Invalid input or string is EOL
156 //Find either = or &, whichever comes first
157 if ((ptr = strpbrk(in, "=&"))) {
158 if (*ptr == '&') { //No value specified
162 //Stopped at an '=' sign
165 if ((ptr = strchr(ptr,'&'))) {
171 } else { //No value specified and no other pair
179 * Aids in parsing request parameters.
180 * Input: The expected keys along with their type and whether or not
182 * @param context The context to work in
183 * @param params The parameter string to be parsed
184 * @param values An array of FCGIValue's that specify expected keys
185 * @param count The number of elements in 'values'.
186 * @return true If the parameter string was parsed successfully, false otherwise.
187 * Modes of failure include: Invalid a parsing error on the value,
188 * an unknown key is specified,
189 * a key/value pair is specified more than once, or
190 * not all required keys were present.
191 * If this function returns false, it is guaranteed that FCGI_RejectJSON
192 * has already been called with the appropriate description message.
194 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
196 const char *key, *value;
197 char buf[BUFSIZ], *ptr;
200 while ((params = FCGI_KeyPair(params, &key, &value))) {
201 for (i = 0; i < count; i++) {
202 if (!strcmp(key, values[i].key)) {
203 FCGIValue *val = &values[i];
205 if (FCGI_RECEIVED(val->flags)) {
206 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
207 FCGI_RejectJSON(context, buf);
210 val->flags |= FCGI_PARAM_RECEIVED;
212 switch(FCGI_TYPE(val->flags)) {
214 if (!*value) //No value: Default true
215 *((bool*) val->value) = true;
217 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
219 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
220 FCGI_RejectJSON(context, buf);
225 case FCGI_INT_T: case FCGI_LONG_T: {
226 long parsed = strtol(value, &ptr, 10);
227 if (!*value || *ptr) {
228 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
229 FCGI_RejectJSON(context, buf);
233 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
234 *((int*) val->value) = (int) parsed;
236 *((long*) val->value) = parsed;
239 *((double*) val->value) = strtod(value, &ptr);
240 if (!*value || *ptr) {
241 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
242 FCGI_RejectJSON(context, buf);
247 *((const char**) val->value) = value;
250 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
252 break; //No need to search any more
256 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
257 FCGI_RejectJSON(context, buf);
262 //Check that required parameters are received
263 for (i = 0; i < count; i++) {
264 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
265 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
266 FCGI_RejectJSON(context, buf);
274 * Begins a response to the client in JSON format.
275 * @param context The context to work in.
276 * @param status_code The status code to be returned.
278 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
280 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
282 printf("\t\"module\" : \"%s\"", context->current_module);
283 FCGI_JSONLong("status", status_code);
284 //Time and running statistics
286 gettimeofday(&now, NULL);
287 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
288 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
289 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
290 FCGI_JSONPair("control_state", Control_GetModeName());
294 * Generic accept response in JSON format.
295 * @param context The context to work in
296 * @param description A short description.
297 * @param cookie Optional. If given, the cookie field is set to that value.
299 void FCGI_AcceptJSON(FCGIContext *context, const char *description, const char *cookie)
301 printf("Content-type: application/json; charset=utf-8\r\n");
303 printf("Set-Cookie: %s\r\n", cookie);
306 printf("\t\"module\" : \"%s\"", context->current_module);
307 FCGI_JSONLong("status", STATUS_OK);
308 FCGI_JSONPair("description", description);
313 * Adds a key/value pair to a JSON response. The response must have already
314 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
315 * @param key The key of the JSON entry
316 * @param value The value associated with the key.
318 void FCGI_JSONPair(const char *key, const char *value)
320 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
324 * Similar to FCGI_JSONPair except for signed integer values.
325 * @param key The key of the JSON entry
326 * @param value The value associated with the key
328 void FCGI_JSONLong(const char *key, long value)
330 printf(",\r\n\t\"%s\" : %ld", key, value);
334 * Similar to FCGI_JsonPair except for floating point values.
335 * @param key The key of the JSON entry
336 * @param value The value associated with the key
338 void FCGI_JSONDouble(const char *key, double value)
340 printf(",\r\n\t\"%s\" : %f", key, value);
344 * Similar to FCGI_JsonPair except for boolean values.
345 * @param key The key of the JSON entry
346 * @param value The value associated with the key
348 void FCGI_JSONBool(const char *key, bool value)
350 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
354 * Begins a JSON entry by writing the key. To be used in conjunction
355 * with FCGI_JsonValue.
356 * @param key The key of the JSON entry
358 void FCGI_JSONKey(const char *key)
360 printf(",\r\n\t\"%s\" : ", key);
364 * Ends a JSON response that was initiated by FCGI_BeginJSON.
372 * To be used when the input parameters are rejected. The return data
373 * will also have debugging information provided.
374 * @param context The context to work in
375 * @param status The status the return data should have.
376 * @param description A short description of why the input was rejected.
378 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
380 if (description == NULL)
381 description = "Unknown";
383 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
384 FCGI_BeginJSON(context, status);
385 FCGI_JSONPair("description", description);
386 FCGI_JSONLong("responsenumber", context->response_number);
387 //FCGI_JSONPair("params", getenv("QUERY_STRING")); //A bad idea if contains password but also if contains unescaped stuff
388 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
389 FCGI_JSONPair("user", getenv("REMOTE_USER"));
390 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
395 * Generates a response to the client as described by the format parameter and
396 * extra arguments (exactly like printf). To be used when none of the other
397 * predefined functions will work exactly as needed. Extra care should be taken
398 * to ensure the correctness of the output.
399 * @param format The format string
400 * @param ... Any extra arguments as required by the format string.
402 void FCGI_PrintRaw(const char *format, ...)
405 va_start(list, format);
406 vprintf(format, list);
415 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
417 Log(LOGDEBUG,"Writing!");
418 fwrite(data, size, num_elem, stdout);
422 * Escapes a string so it can be used safely.
423 * Currently escapes to ensure the validity for use as a JSON string
424 * Does not support unicode specifiers in the form of \uXXXX.
425 * @param buf The string to be escaped
426 * @return The escaped string (return value == buf)
428 char *FCGI_EscapeText(char *buf)
431 length = strlen(buf);
433 //Escape special characters. Must count down to escape properly
434 for (i = length - 1; i >= 0; i--) {
435 if (buf[i] < 0x20) { //Control characters
437 } else if (buf[i] == '"') {
438 if (i-1 >= 0 && buf[i-1] == '\\')
442 } else if (buf[i] == '\\') {
443 if (i-1 >= 0 && buf[i-1] == '\'')
453 * Main FCGI request loop that receives/responds to client requests.
454 * @param data Reserved.
455 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
456 * TODO: Get this to exit with the rest of the program!
458 void * FCGI_RequestLoop (void *data)
460 FCGIContext context = {0};
462 Log(LOGDEBUG, "Start loop");
463 while (FCGI_Accept() >= 0) {
465 ModuleHandler module_handler = NULL;
466 char module[BUFSIZ], params[BUFSIZ];
467 //Don't need to copy if we're not modifying string contents
468 const char *cookie = getenv("COOKIE_STRING");
470 //strncpy doesn't zero-truncate properly
471 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
472 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
474 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
475 Log(LOGDEBUG, "Cookie: %s", cookie);
478 //Remove trailing slashes (if present) from module query
479 size_t lastchar = strlen(module) - 1;
480 if (lastchar > 0 && module[lastchar] == '/')
481 module[lastchar] = 0;
483 //Default to the 'identify' module if none specified
485 strcpy(module, "identify");
487 if (!strcmp("identify", module)) {
488 module_handler = IdentifyHandler;
489 } else if (!strcmp("control", module)) {
490 module_handler = Control_Handler;
491 } else if (!strcmp("sensors", module)) {
492 module_handler = Sensor_Handler;
493 } else if (!strcmp("actuators", module)) {
494 module_handler = Actuator_Handler;
495 } else if (!strcmp("image", module)) {
496 module_handler = Image_Handler;
497 } else if (!strcmp("pin", module)) {
498 module_handler = Pin_Handler; // *Debug only* pin test module
499 } else if (!strcmp("bind", module)) {
500 module_handler = Login_Handler;
501 } else if (!strcmp("unbind", module)) {
502 module_handler = Logout_Handler;
505 context.current_module = module;
506 context.response_number++;
510 if (module_handler != Login_Handler && module_handler != IdentifyHandler)
512 if (cookie[0] == '\0')
514 FCGI_RejectJSONEx(&context, STATUS_UNAUTHORIZED, "Please login.");
518 if (!FCGI_HasControl(&context, cookie))
520 FCGI_RejectJSON(&context, "Invalid control key.");
524 //Escape all special characters.
525 //Don't escape for login (password may have special chars?)
526 FCGI_EscapeText(params);
529 module_handler(&context, params);
533 FCGI_RejectJSON(&context, "Unhandled module");
540 Log(LOGDEBUG, "Thread exiting.");
541 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.