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;
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", FCGI_HasControl(context, getenv("COOKIE_STRING")));
49 FCGI_JSONPair("friendly_name", "");
51 //Sensor and actuator information
53 FCGI_JSONKey("sensors");
54 FCGI_JSONValue("{\n\t\t");
55 for (i = 0; i < NUMSENSORS; i++) {
57 FCGI_JSONValue(",\n\t\t");
59 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[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 * This function will generate a JSON response that indicates success/failure.
83 * @param context The context to work in
84 * @param force Whether to force key generation or not.
86 void 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"));
109 * Given an FCGIContext, determines if the current user (as specified by
110 * the key) has control or not. If validated, the context control_timestamp is
112 * @param context The context to work in
113 * @param key The control key to be validated.
114 * @return TRUE if authorized, FALSE if not.
116 bool FCGI_HasControl(FCGIContext *context, const char *key) {
117 time_t now = time(NULL);
118 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
119 key != NULL && !strcmp(context->control_key, key);
121 context->control_timestamp = now; //Update the control_timestamp
128 * Revokes the current control key, if present.
129 * @param context The context to work in
131 void FCGI_ReleaseControl(FCGIContext *context) {
132 *(context->control_key) = 0;
133 FCGI_BeginJSON(context, STATUS_OK);
139 * Extracts a key/value pair from a request string.
140 * Note that the input is modified by this function.
141 * @param in The string from which to extract the pair
142 * @param key A pointer to a variable to hold the key string
143 * @param value A pointer to a variable to hold the value string
144 * @return A pointer to the start of the next search location, or NULL if
145 * the EOL is reached.
147 char *FCGI_KeyPair(char *in, const char **key, const char **value)
150 if (!in || !*in) { //Invalid input or string is EOL
155 //Find either = or &, whichever comes first
156 if ((ptr = strpbrk(in, "=&"))) {
157 if (*ptr == '&') { //No value specified
161 //Stopped at an '=' sign
164 if ((ptr = strchr(ptr,'&'))) {
170 } else { //No value specified and no other pair
178 * Aids in parsing request parameters.
179 * Input: The expected keys along with their type and whether or not
181 * @param context The context to work in
182 * @param params The parameter string to be parsed
183 * @param values An array of FCGIValue's that specify expected keys
184 * @param count The number of elements in 'values'.
185 * @return true If the parameter string was parsed successfully, false otherwise.
186 * Modes of failure include: Invalid a parsing error on the value,
187 * an unknown key is specified,
188 * a key/value pair is specified more than once, or
189 * not all required keys were present.
190 * If this function returns false, it is guaranteed that FCGI_RejectJSON
191 * has already been called with the appropriate description message.
193 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
195 const char *key, *value;
196 char buf[BUFSIZ], *ptr;
199 while ((params = FCGI_KeyPair(params, &key, &value))) {
200 for (i = 0; i < count; i++) {
201 if (!strcmp(key, values[i].key)) {
202 FCGIValue *val = &values[i];
204 if (FCGI_RECEIVED(val->flags)) {
205 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
206 FCGI_RejectJSON(context, buf);
209 val->flags |= FCGI_PARAM_RECEIVED;
211 switch(FCGI_TYPE(val->flags)) {
213 if (!*value) //No value: Default true
214 *((bool*) val->value) = true;
216 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
218 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
219 FCGI_RejectJSON(context, buf);
224 case FCGI_INT_T: case FCGI_LONG_T: {
225 long parsed = strtol(value, &ptr, 10);
226 if (!*value || *ptr) {
227 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
228 FCGI_RejectJSON(context, buf);
232 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
233 *((int*) val->value) = (int) parsed;
235 *((long*) val->value) = parsed;
238 *((double*) val->value) = strtod(value, &ptr);
239 if (!*value || *ptr) {
240 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
241 FCGI_RejectJSON(context, buf);
246 *((const char**) val->value) = value;
249 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
251 break; //No need to search any more
255 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
256 FCGI_RejectJSON(context, buf);
261 //Check that required parameters are received
262 for (i = 0; i < count; i++) {
263 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
264 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
265 FCGI_RejectJSON(context, buf);
273 * Begins a response to the client in JSON format.
274 * @param context The context to work in.
275 * @param status_code The status code to be returned.
277 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
279 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
281 printf("\t\"module\" : \"%s\"", context->current_module);
282 FCGI_JSONLong("status", status_code);
283 //Time and running statistics
285 gettimeofday(&now, NULL);
286 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
287 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
288 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
289 FCGI_JSONPair("control_state", Control_GetModeName());
293 * Generic accept response in JSON format.
294 * @param context The context to work in
295 * @param description A short description.
296 * @param cookie Optional. If given, the cookie field is set to that value.
298 void FCGI_AcceptJSON(FCGIContext *context, const char *description, const char *cookie)
300 printf("Content-type: application/json; charset=utf-8\r\n");
302 printf("Set-Cookie: %s\r\n", cookie);
305 printf("\t\"module\" : \"%s\"", context->current_module);
306 FCGI_JSONLong("status", STATUS_OK);
307 FCGI_JSONPair("description", description);
312 * Adds a key/value pair to a JSON response. The response must have already
313 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
314 * @param key The key of the JSON entry
315 * @param value The value associated with the key.
317 void FCGI_JSONPair(const char *key, const char *value)
319 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
323 * Similar to FCGI_JSONPair except for signed integer values.
324 * @param key The key of the JSON entry
325 * @param value The value associated with the key
327 void FCGI_JSONLong(const char *key, long value)
329 printf(",\r\n\t\"%s\" : %ld", key, value);
333 * Similar to FCGI_JsonPair except for floating point values.
334 * @param key The key of the JSON entry
335 * @param value The value associated with the key
337 void FCGI_JSONDouble(const char *key, double value)
339 printf(",\r\n\t\"%s\" : %f", key, value);
343 * Similar to FCGI_JsonPair except for boolean values.
344 * @param key The key of the JSON entry
345 * @param value The value associated with the key
347 void FCGI_JSONBool(const char *key, bool value)
349 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
353 * Begins a JSON entry by writing the key. To be used in conjunction
354 * with FCGI_JsonValue.
355 * @param key The key of the JSON entry
357 void FCGI_JSONKey(const char *key)
359 printf(",\r\n\t\"%s\" : ", key);
363 * Ends a JSON response that was initiated by FCGI_BeginJSON.
371 * To be used when the input parameters are rejected. The return data
372 * will also have debugging information provided.
373 * @param context The context to work in
374 * @param status The status the return data should have.
375 * @param description A short description of why the input was rejected.
377 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
379 if (description == NULL)
380 description = "Unknown";
382 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
383 FCGI_BeginJSON(context, status);
384 FCGI_JSONPair("description", description);
385 FCGI_JSONLong("responsenumber", context->response_number);
386 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
387 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
388 FCGI_JSONPair("user", getenv("REMOTE_USER"));
389 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
394 * Generates a response to the client as described by the format parameter and
395 * extra arguments (exactly like printf). To be used when none of the other
396 * predefined functions will work exactly as needed. Extra care should be taken
397 * to ensure the correctness of the output.
398 * @param format The format string
399 * @param ... Any extra arguments as required by the format string.
401 void FCGI_PrintRaw(const char *format, ...)
404 va_start(list, format);
405 vprintf(format, list);
414 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
416 Log(LOGDEBUG,"Writing!");
417 fwrite(data, size, num_elem, stdout);
421 * Escapes a string so it can be used safely.
422 * Currently escapes to ensure the validity for use as a JSON string
423 * Does not support unicode specifiers in the form of \uXXXX.
424 * @param buf The string to be escaped
425 * @return The escaped string (return value == buf)
427 char *FCGI_EscapeText(char *buf)
430 length = strlen(buf);
432 //Escape special characters. Must count down to escape properly
433 for (i = length - 1; i >= 0; i--) {
434 if (buf[i] < 0x20) { //Control characters
436 } else if (buf[i] == '"') {
437 if (i-1 >= 0 && buf[i-1] == '\\')
441 } else if (buf[i] == '\\') {
442 if (i-1 >= 0 && buf[i-1] == '\'')
452 * Main FCGI request loop that receives/responds to client requests.
453 * @param data Reserved.
454 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
455 * TODO: Get this to exit with the rest of the program!
457 void * FCGI_RequestLoop (void *data)
459 FCGIContext context = {0};
461 Log(LOGDEBUG, "Start loop");
462 while (FCGI_Accept() >= 0) {
464 ModuleHandler module_handler = NULL;
465 char module[BUFSIZ], params[BUFSIZ];
466 //Don't need to copy if we're not modifying string contents
467 const char *cookie = getenv("COOKIE_STRING");
469 //strncpy doesn't zero-truncate properly
470 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
471 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
473 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
474 Log(LOGDEBUG, "Cookie: %s", cookie);
477 //Remove trailing slashes (if present) from module query
478 size_t lastchar = strlen(module) - 1;
479 if (lastchar > 0 && module[lastchar] == '/')
480 module[lastchar] = 0;
482 //Escape all special characters
483 FCGI_EscapeText(params);
485 //Default to the 'identify' module if none specified
487 strcpy(module, "identify");
489 if (!strcmp("identify", module)) {
490 module_handler = IdentifyHandler;
491 } else if (!strcmp("control", module)) {
492 module_handler = Control_Handler;
493 } else if (!strcmp("sensors", module)) {
494 module_handler = Sensor_Handler;
495 } else if (!strcmp("actuators", module)) {
496 module_handler = Actuator_Handler;
497 } else if (!strcmp("image", module)) {
498 module_handler = Image_Handler;
499 } else if (!strcmp("pin", module)) {
500 module_handler = Pin_Handler; // *Debug only* pin test module
501 } else if (!strcmp("bind", module)) {
502 module_handler = Login_Handler;
503 } else if (!strcmp("unbind", module)) {
504 module_handler = Logout_Handler;
507 context.current_module = module;
508 context.response_number++;
512 if (module_handler != Login_Handler && module_handler != IdentifyHandler)
514 if (cookie[0] == '\0')
516 FCGI_RejectJSON(&context, "Please login.");
519 if (!FCGI_HasControl(&context, cookie))
521 FCGI_RejectJSON(&context, "Invalid control key.");
526 module_handler(&context, params);
530 FCGI_RejectJSON(&context, "Unhandled module");
537 Log(LOGDEBUG, "Thread exiting.");
538 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.