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>
18 /**The time period (in seconds) before the control key expires @ */
19 #define CONTROL_TIMEOUT 180
21 /**Contextual information related to FCGI requests*/
23 /**The time of last valid user access possessing the control key*/
24 time_t control_timestamp;
27 /**The name of the current module**/
28 const char *current_module;
29 /**For debugging purposes?**/
34 * Identifies build information and the current API version to the user.
35 * Also useful for testing that the API is running and identifying the
36 * sensors and actuators present.
37 * @param context The context to work in
38 * @param params User specified paramters: [actuators, sensors]
40 static void IdentifyHandler(FCGIContext *context, char *params) {
41 bool ident_sensors = false, ident_actuators = false;
42 //const char *key, *value;
46 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
47 {"actuators", &ident_actuators, FCGI_BOOL_T}};
49 if (!FCGI_ParseRequest(context, params, values, 2))
52 /*while ((params = FCGI_KeyPair(params, &key, &value))) {
53 if (!strcmp(key, "sensors")) {
54 ident_sensors = !ident_sensors;
55 } else if (!strcmp(key, "actuators")) {
56 ident_actuators = !ident_actuators;
60 FCGI_BeginJSON(context, STATUS_OK);
61 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
62 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
63 FCGI_JSONLong("api_version", API_VERSION);
65 //Sensor and actuator information
67 FCGI_JSONKey("sensors");
68 FCGI_JSONValue("{\n\t\t");
69 for (i = 0; i < NUMSENSORS; i++) {
71 FCGI_JSONValue(",\n\t\t");
73 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
75 FCGI_JSONValue("\n\t}");
77 if (ident_actuators) {
78 FCGI_JSONKey("actuators");
79 FCGI_JSONValue("{\n\t\t");
80 for (i = 0; i < NUMACTUATORS; i++) {
82 FCGI_JSONValue(",\n\t\t");
84 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
86 FCGI_JSONValue("\n\t}");
92 * Gives the user a key that determines who has control over
93 * the system at any one time. The key can be forcibly generated, revoking
94 * any previous control keys. To be used in conjunction with HTTP
95 * basic authentication.
96 * This function will generate a JSON response that indicates success/failure.
97 * @param context The context to work in
98 * @param force Whether to force key generation or not.
100 void FCGI_BeginControl(FCGIContext *context, bool force) {
101 time_t now = time(NULL);
102 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
104 if (force || !*(context->control_key) || expired) {
106 unsigned char sha1[20];
110 SHA1_Update(&sha1ctx, &now, sizeof(now));
111 SHA1_Update(&sha1ctx, &i, sizeof(i));
112 SHA1_Final(sha1, &sha1ctx);
114 context->control_timestamp = now;
115 for (i = 0; i < 20; i++)
116 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
117 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
118 FCGI_BeginJSON(context, STATUS_OK);
119 FCGI_JSONPair("key", context->control_key);
123 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
124 localtime(&(context->control_timestamp)));
125 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
126 FCGI_JSONPair("description", "Another user already has control");
127 FCGI_JSONPair("current_user", context->control_ip);
128 FCGI_JSONPair("when", buf);
134 * Given an FCGIContext, determines if the current user (as specified by
135 * the key) has control or not. If validated, the context control_timestamp is
137 * @param context The context to work in
138 * @param key The control key to be validated.
139 * @return TRUE if authorized, FALSE if not.
141 bool FCGI_HasControl(FCGIContext *context, const char *key) {
142 time_t now = time(NULL);
143 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
144 key != NULL && !strcmp(context->control_key, key);
146 context->control_timestamp = now; //Update the control_timestamp
153 * Revokes the current control key, if present.
154 * @param context The context to work in
156 void FCGI_EndControl(FCGIContext *context) {
157 *(context->control_key) = 0;
158 FCGI_BeginJSON(context, STATUS_OK);
164 * Extracts a key/value pair from a request string.
165 * Note that the input is modified by this function.
166 * @param in The string from which to extract the pair
167 * @param key A pointer to a variable to hold the key string
168 * @param value A pointer to a variable to hold the value string
169 * @return A pointer to the start of the next search location, or NULL if
170 * the EOL is reached.
172 char *FCGI_KeyPair(char *in, const char **key, const char **value)
175 if (!in || !*in) { //Invalid input or string is EOL
180 //Find either = or &, whichever comes first
181 if ((ptr = strpbrk(in, "=&"))) {
182 if (*ptr == '&') { //No value specified
186 //Stopped at an '=' sign
189 if ((ptr = strchr(ptr,'&'))) {
195 } else { //No value specified and no other pair
203 * Aids in parsing request parameters. Expected keys along with their type
204 * and whether or not they're required are provided. This function will then
205 * parse the parameter string to find these keys.
206 * @param context The context to work in
207 * @param params The parameter string to be parsed
208 * @param values An array of FCGIValue's that specify expected keys
209 * @param count The number of elements in 'values'.
210 * @return true If the parameter string was parsed successfully, false otherwise.
211 * Modes of failure include: Invalid a parsing error on the value,
212 * an unknown key is specified,
213 * a key/value pair is specified more than once, or
214 * not all required keys were present.
215 * If this function returns false, it is guaranteed that FCGI_RejectJSON
216 * has already been called with the appropriate description message.
218 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
220 const char *key, *value;
221 char buf[BUFSIZ], *ptr;
224 while ((params = FCGI_KeyPair(params, &key, &value))) {
225 for (i = 0; i < count; i++) {
226 if (!strcmp(key, values[i].key)) {
227 FCGIValue *val = &values[i];
229 if (FCGI_RECEIVED(val->flags)) {
230 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
231 FCGI_RejectJSON(context, buf);
234 val->flags |= FCGI_PARAM_RECEIVED;
236 switch(FCGI_TYPE(val->flags)) {
238 *((bool*) val->value) = true;
240 case FCGI_INT_T: case FCGI_LONG_T: {
241 long parsed = strtol(value, &ptr, 10);
242 if (!*value || *ptr) {
243 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
244 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
248 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
249 *((int*) val->value) = parsed;
251 *((long*) val->value) = parsed;
254 *((double*) val->value) = strtod(value, &ptr);
255 if (!*value || *ptr) {
256 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
257 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
262 *((const char**) val->value) = value;
265 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
267 break; //No need to search any more
271 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
272 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
277 //Check that required parameters are received
278 for (i = 0; i < count; i++) {
279 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
280 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
281 FCGI_RejectJSON(context, buf);
289 * Begins a response to the client in JSON format.
290 * @param context The context to work in.
291 * @param status_code The status code to be returned.
293 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
295 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
297 printf("\t\"module\" : \"%s\"", context->current_module);
298 FCGI_JSONLong("status", status_code);
299 //Time and running statistics
301 gettimeofday(&now, NULL);
302 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
303 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
304 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
308 * Adds a key/value pair to a JSON response. The response must have already
309 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
310 * @param key The key of the JSON entry
311 * @param value The value associated with the key.
313 void FCGI_JSONPair(const char *key, const char *value)
315 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
319 * Similar to FCGI_JSONPair except for signed integer values.
320 * @param key The key of the JSON entry
321 * @param value The value associated with the key
323 void FCGI_JSONLong(const char *key, long value)
325 printf(",\r\n\t\"%s\" : %ld", key, value);
329 * Similar to FCGI_JsonPair except for floating point values.
330 * @param key The key of the JSON entry
331 * @param value The value associated with the key
333 void FCGI_JSONDouble(const char *key, double value)
335 printf(",\r\n\t\"%s\" : %f", key, value);
339 * Similar to FCGI_JsonPair except for boolean values.
340 * @param key The key of the JSON entry
341 * @param value The value associated with the key
343 void FCGI_JSONBool(const char *key, bool value)
345 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
349 * Begins a JSON entry by writing the key. To be used in conjunction
350 * with FCGI_JsonValue.
351 * @param key The key of the JSON entry
353 void FCGI_JSONKey(const char *key)
355 printf(",\r\n\t\"%s\" : ", key);
359 * Ends a JSON response that was initiated by FCGI_BeginJSON.
367 * Escapes a string so it can be used as a JSON string value.
368 * Does not support unicode specifiers in the form of \uXXXX.
369 * @param buf The string to be escaped
370 * @return The escaped string (return value == buf)
372 char *FCGI_EscapeJSON(char *buf)
375 length = strlen(buf);
377 //Escape special characters. Must count down to escape properly
378 for (i = length - 1; i >= 0; i--) {
379 if (buf[i] < 0x20) { //Control characters
381 } else if (buf[i] == '"') {
382 if (i-1 >= 0 && buf[i-1] == '\\')
386 } else if (buf[i] == '\\') {
387 if (i-1 >= 0 && buf[i-1] == '\'')
397 * To be used when the input parameters are rejected. The return data
398 * will also have debugging information provided.
399 * @param context The context to work in
400 * @param status The status the return data should have.
401 * @param description A short description of why the input was rejected.
403 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
405 if (description == NULL)
406 description = "Unknown";
408 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
409 FCGI_BeginJSON(context, status);
410 FCGI_JSONPair("description", description);
411 FCGI_JSONLong("responsenumber", context->response_number);
412 FCGI_JSONPair("params", getenv("QUERY_STRING"));
413 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
414 FCGI_JSONPair("user", getenv("REMOTE_USER"));
415 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
420 * Generates a response to the client as described by the format parameter and
421 * extra arguments (exactly like printf). To be used when none of the other
422 * predefined functions will work exactly as needed. Extra care should be taken
423 * to ensure the correctness of the output.
424 * @param format The format string
425 * @param ... Any extra arguments as required by the format string.
427 void FCGI_PrintRaw(const char *format, ...)
430 va_start(list, format);
431 vprintf(format, list);
436 * Main FCGI request loop that receives/responds to client requests.
437 * @param data Reserved.
438 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
439 * TODO: Get this to exit with the rest of the program!
441 void * FCGI_RequestLoop (void *data)
443 FCGIContext context = {0};
445 Log(LOGDEBUG, "First request...");
446 while (FCGI_Accept() >= 0) {
447 Log(LOGDEBUG, "Got request #%d", context.response_number);
448 ModuleHandler module_handler = NULL;
449 char module[BUFSIZ], params[BUFSIZ];
451 //strncpy doesn't zero-truncate properly
452 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
453 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
455 //Remove trailing slashes (if present) from module query
456 size_t lastchar = strlen(module) - 1;
457 if (lastchar > 0 && module[lastchar] == '/')
458 module[lastchar] = 0;
460 //Default to the 'identify' module if none specified
462 strcpy(module, "identify");
464 if (!strcmp("identify", module)) {
465 module_handler = IdentifyHandler;
466 } else if (!strcmp("control", module)) {
467 module_handler = Control_Handler;
468 } else if (!strcmp("sensors", module)) {
469 module_handler = Sensor_Handler;
472 context.current_module = module;
473 if (module_handler) {
474 module_handler(&context, params);
476 FCGI_RejectJSON(&context, "Unhandled module");
478 context.response_number++;
480 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
483 Log(LOGDEBUG, "Thread exiting.");
484 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.