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>
19 /**The time period (in seconds) before the control key expires */
20 #define CONTROL_TIMEOUT 180
22 /**Contextual information related to FCGI requests*/
24 /**The time of last valid user access possessing the control key*/
25 time_t control_timestamp;
28 /**The name of the current module**/
29 const char *current_module;
30 /**For debugging purposes?**/
35 * Identifies build information and the current API version to the user.
36 * Also useful for testing that the API is running and identifying the
37 * sensors and actuators present.
38 * @param context The context to work in
39 * @param params User specified paramters: [actuators, sensors]
41 static void IdentifyHandler(FCGIContext *context, char *params) {
42 bool ident_sensors = false, ident_actuators = false;
46 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
47 {"actuators", &ident_actuators, FCGI_BOOL_T}};
48 if (!FCGI_ParseRequest(context, params, values, 2))
51 FCGI_BeginJSON(context, STATUS_OK);
52 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
53 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
54 FCGI_JSONLong("api_version", API_VERSION);
56 //Sensor and actuator information
58 FCGI_JSONKey("sensors");
59 FCGI_JSONValue("{\n\t\t");
60 for (i = 0; i < NUMSENSORS; i++) {
62 FCGI_JSONValue(",\n\t\t");
64 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
66 FCGI_JSONValue("\n\t}");
68 if (ident_actuators) {
69 FCGI_JSONKey("actuators");
70 FCGI_JSONValue("{\n\t\t");
71 for (i = 0; i < NUMACTUATORS; i++) {
73 FCGI_JSONValue(",\n\t\t");
75 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
77 FCGI_JSONValue("\n\t}");
83 * Gives the user a key that determines who has control over
84 * the system at any one time. The key can be forcibly generated, revoking
85 * any previous control keys. To be used in conjunction with HTTP
86 * basic authentication.
87 * This function will generate a JSON response that indicates success/failure.
88 * @param context The context to work in
89 * @param force Whether to force key generation or not.
91 void FCGI_LockControl(FCGIContext *context, bool force) {
92 time_t now = time(NULL);
93 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
95 if (force || !*(context->control_key) || expired) {
97 unsigned char sha1[20];
101 SHA1_Update(&sha1ctx, &now, sizeof(now));
102 SHA1_Update(&sha1ctx, &i, sizeof(i));
103 SHA1_Final(sha1, &sha1ctx);
105 context->control_timestamp = now;
106 for (i = 0; i < 20; i++)
107 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
108 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
109 FCGI_BeginJSON(context, STATUS_OK);
110 FCGI_JSONPair("key", context->control_key);
114 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
115 localtime(&(context->control_timestamp)));
116 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
117 FCGI_JSONPair("description", "Another user already has control");
118 FCGI_JSONPair("current_user", context->control_ip);
119 FCGI_JSONPair("when", buf);
125 * Given an FCGIContext, determines if the current user (as specified by
126 * the key) has control or not. If validated, the context control_timestamp is
128 * @param context The context to work in
129 * @param key The control key to be validated.
130 * @return TRUE if authorized, FALSE if not.
132 bool FCGI_HasControl(FCGIContext *context, const char *key) {
133 time_t now = time(NULL);
134 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
135 key != NULL && !strcmp(context->control_key, key);
137 context->control_timestamp = now; //Update the control_timestamp
144 * Revokes the current control key, if present.
145 * @param context The context to work in
147 void FCGI_ReleaseControl(FCGIContext *context) {
148 *(context->control_key) = 0;
149 FCGI_BeginJSON(context, STATUS_OK);
155 * Extracts a key/value pair from a request string.
156 * Note that the input is modified by this function.
157 * @param in The string from which to extract the pair
158 * @param key A pointer to a variable to hold the key string
159 * @param value A pointer to a variable to hold the value string
160 * @return A pointer to the start of the next search location, or NULL if
161 * the EOL is reached.
163 char *FCGI_KeyPair(char *in, const char **key, const char **value)
166 if (!in || !*in) { //Invalid input or string is EOL
171 //Find either = or &, whichever comes first
172 if ((ptr = strpbrk(in, "=&"))) {
173 if (*ptr == '&') { //No value specified
177 //Stopped at an '=' sign
180 if ((ptr = strchr(ptr,'&'))) {
186 } else { //No value specified and no other pair
194 * Aids in parsing request parameters.
195 * Input: The expected keys along with their type and whether or not
197 * @param context The context to work in
198 * @param params The parameter string to be parsed
199 * @param values An array of FCGIValue's that specify expected keys
200 * @param count The number of elements in 'values'.
201 * @return true If the parameter string was parsed successfully, false otherwise.
202 * Modes of failure include: Invalid a parsing error on the value,
203 * an unknown key is specified,
204 * a key/value pair is specified more than once, or
205 * not all required keys were present.
206 * If this function returns false, it is guaranteed that FCGI_RejectJSON
207 * has already been called with the appropriate description message.
209 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
211 const char *key, *value;
212 char buf[BUFSIZ], *ptr;
215 while ((params = FCGI_KeyPair(params, &key, &value))) {
216 for (i = 0; i < count; i++) {
217 if (!strcmp(key, values[i].key)) {
218 FCGIValue *val = &values[i];
220 if (FCGI_RECEIVED(val->flags)) {
221 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
222 FCGI_RejectJSON(context, buf);
225 val->flags |= FCGI_PARAM_RECEIVED;
227 switch(FCGI_TYPE(val->flags)) {
229 *((bool*) val->value) = true;
231 case FCGI_INT_T: case FCGI_LONG_T: {
232 long parsed = strtol(value, &ptr, 10);
233 if (!*value || *ptr) {
234 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
235 FCGI_RejectJSON(context, buf);
239 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
240 *((int*) val->value) = (int) parsed;
242 *((long*) val->value) = parsed;
245 *((double*) val->value) = strtod(value, &ptr);
246 if (!*value || *ptr) {
247 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
248 FCGI_RejectJSON(context, buf);
253 *((const char**) val->value) = value;
256 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
258 break; //No need to search any more
262 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
263 FCGI_RejectJSON(context, buf);
268 //Check that required parameters are received
269 for (i = 0; i < count; i++) {
270 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
271 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
272 FCGI_RejectJSON(context, buf);
280 * Begins a response to the client in JSON format.
281 * @param context The context to work in.
282 * @param status_code The status code to be returned.
284 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
286 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
288 printf("\t\"module\" : \"%s\"", context->current_module);
289 FCGI_JSONLong("status", status_code);
290 //Time and running statistics
292 gettimeofday(&now, NULL);
293 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
294 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
295 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
299 * Adds a key/value pair to a JSON response. The response must have already
300 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
301 * @param key The key of the JSON entry
302 * @param value The value associated with the key.
304 void FCGI_JSONPair(const char *key, const char *value)
306 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
310 * Similar to FCGI_JSONPair except for signed integer values.
311 * @param key The key of the JSON entry
312 * @param value The value associated with the key
314 void FCGI_JSONLong(const char *key, long value)
316 printf(",\r\n\t\"%s\" : %ld", key, value);
320 * Similar to FCGI_JsonPair except for floating point values.
321 * @param key The key of the JSON entry
322 * @param value The value associated with the key
324 void FCGI_JSONDouble(const char *key, double value)
326 printf(",\r\n\t\"%s\" : %f", key, value);
330 * Similar to FCGI_JsonPair except for boolean values.
331 * @param key The key of the JSON entry
332 * @param value The value associated with the key
334 void FCGI_JSONBool(const char *key, bool value)
336 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
340 * Begins a JSON entry by writing the key. To be used in conjunction
341 * with FCGI_JsonValue.
342 * @param key The key of the JSON entry
344 void FCGI_JSONKey(const char *key)
346 printf(",\r\n\t\"%s\" : ", key);
350 * Ends a JSON response that was initiated by FCGI_BeginJSON.
358 * To be used when the input parameters are rejected. The return data
359 * will also have debugging information provided.
360 * @param context The context to work in
361 * @param status The status the return data should have.
362 * @param description A short description of why the input was rejected.
364 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
366 if (description == NULL)
367 description = "Unknown";
369 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
370 FCGI_BeginJSON(context, status);
371 FCGI_JSONPair("description", description);
372 FCGI_JSONLong("responsenumber", context->response_number);
373 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
374 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
375 FCGI_JSONPair("user", getenv("REMOTE_USER"));
376 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
381 * Generates a response to the client as described by the format parameter and
382 * extra arguments (exactly like printf). To be used when none of the other
383 * predefined functions will work exactly as needed. Extra care should be taken
384 * to ensure the correctness of the output.
385 * @param format The format string
386 * @param ... Any extra arguments as required by the format string.
388 void FCGI_PrintRaw(const char *format, ...)
391 va_start(list, format);
392 vprintf(format, list);
397 * Escapes a string so it can be used safely.
398 * Currently escapes to ensure the validity for use as a JSON string
399 * Does not support unicode specifiers in the form of \uXXXX.
400 * @param buf The string to be escaped
401 * @return The escaped string (return value == buf)
403 char *FCGI_EscapeText(char *buf)
406 length = strlen(buf);
408 //Escape special characters. Must count down to escape properly
409 for (i = length - 1; i >= 0; i--) {
410 if (buf[i] < 0x20) { //Control characters
412 } else if (buf[i] == '"') {
413 if (i-1 >= 0 && buf[i-1] == '\\')
417 } else if (buf[i] == '\\') {
418 if (i-1 >= 0 && buf[i-1] == '\'')
428 * Main FCGI request loop that receives/responds to client requests.
429 * @param data Reserved.
430 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
431 * TODO: Get this to exit with the rest of the program!
433 void * FCGI_RequestLoop (void *data)
435 FCGIContext context = {0};
437 Log(LOGDEBUG, "First request...");
438 while (FCGI_Accept() >= 0) {
439 Log(LOGDEBUG, "Got request #%d", context.response_number);
440 ModuleHandler module_handler = NULL;
441 char module[BUFSIZ], params[BUFSIZ];
443 //strncpy doesn't zero-truncate properly
444 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
445 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
447 //Remove trailing slashes (if present) from module query
448 size_t lastchar = strlen(module) - 1;
449 if (lastchar > 0 && module[lastchar] == '/')
450 module[lastchar] = 0;
452 //Escape all special characters
453 FCGI_EscapeText(params);
455 //Default to the 'identify' module if none specified
457 strcpy(module, "identify");
459 if (!strcmp("identify", module)) {
460 module_handler = IdentifyHandler;
461 } else if (!strcmp("control", module)) {
462 module_handler = Control_Handler;
463 } else if (!strcmp("sensors", module)) {
464 module_handler = Sensor_Handler;
465 } else if (!strcmp("actuators", module)) {
466 module_handler = Actuator_Handler;
469 context.current_module = module;
470 if (module_handler) {
471 module_handler(&context, params);
473 FCGI_RejectJSON(&context, "Unhandled module");
475 context.response_number++;
477 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
480 Log(LOGDEBUG, "Thread exiting.");
481 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.