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 //Time and running statistics
66 gettimeofday(&now, NULL);
67 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
68 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
69 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
71 //Sensor and actuator information
73 FCGI_JSONKey("sensors");
74 FCGI_JSONValue("{\n\t\t");
75 for (i = 0; i < NUMSENSORS; i++) {
77 FCGI_JSONValue(",\n\t\t");
79 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
81 FCGI_JSONValue("\n\t}");
83 if (ident_actuators) {
84 FCGI_JSONKey("actuators");
85 FCGI_JSONValue("{\n\t\t");
86 for (i = 0; i < NUMACTUATORS; i++) {
88 FCGI_JSONValue(",\n\t\t");
90 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
92 FCGI_JSONValue("\n\t}");
98 * Gives the user a key that determines who has control over
99 * the system at any one time. The key can be forcibly generated, revoking
100 * any previous control keys. To be used in conjunction with HTTP
101 * basic authentication.
102 * This function will generate a JSON response that indicates success/failure.
103 * @param context The context to work in
104 * @param force Whether to force key generation or not.
106 void FCGI_BeginControl(FCGIContext *context, bool force) {
107 time_t now = time(NULL);
108 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
110 if (force || !*(context->control_key) || expired) {
112 unsigned char sha1[20];
116 SHA1_Update(&sha1ctx, &now, sizeof(now));
117 SHA1_Update(&sha1ctx, &i, sizeof(i));
118 SHA1_Final(sha1, &sha1ctx);
120 context->control_timestamp = now;
121 for (i = 0; i < 20; i++)
122 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
123 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
124 FCGI_BeginJSON(context, STATUS_OK);
125 FCGI_JSONPair("key", context->control_key);
129 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
130 localtime(&(context->control_timestamp)));
131 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
132 FCGI_JSONPair("description", "Another user already has control");
133 FCGI_JSONPair("current_user", context->control_ip);
134 FCGI_JSONPair("when", buf);
140 * Given an FCGIContext, determines if the current user (as specified by
141 * the key) has control or not. If validated, the context control_timestamp is
143 * @param context The context to work in
144 * @param key The control key to be validated.
145 * @return TRUE if authorized, FALSE if not.
147 bool FCGI_HasControl(FCGIContext *context, const char *key) {
148 time_t now = time(NULL);
149 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
150 key != NULL && !strcmp(context->control_key, key);
152 context->control_timestamp = now; //Update the control_timestamp
159 * Revokes the current control key, if present.
160 * @param context The context to work in
162 void FCGI_EndControl(FCGIContext *context) {
163 *(context->control_key) = 0;
164 FCGI_BeginJSON(context, STATUS_OK);
170 * Extracts a key/value pair from a request string.
171 * Note that the input is modified by this function.
172 * @param in The string from which to extract the pair
173 * @param key A pointer to a variable to hold the key string
174 * @param value A pointer to a variable to hold the value string
175 * @return A pointer to the start of the next search location, or NULL if
176 * the EOL is reached.
178 char *FCGI_KeyPair(char *in, const char **key, const char **value)
181 if (!in || !*in) { //Invalid input or string is EOL
186 //Find either = or &, whichever comes first
187 if ((ptr = strpbrk(in, "=&"))) {
188 if (*ptr == '&') { //No value specified
192 //Stopped at an '=' sign
195 if ((ptr = strchr(ptr,'&'))) {
201 } else { //No value specified and no other pair
209 * Aids in parsing request parameters. Expected keys along with their type
210 * and whether or not they're required are provided. This function will then
211 * parse the parameter string to find these keys.
212 * @param context The context to work in
213 * @param params The parameter string to be parsed
214 * @param values An array of FCGIValue's that specify expected keys
215 * @param count The number of elements in 'values'.
216 * @return true If the parameter string was parsed successfully, false otherwise.
217 * Modes of failure include: Invalid a parsing error on the value,
218 * an unknown key is specified,
219 * a key/value pair is specified more than once, or
220 * not all required keys were present.
221 * If this function returns false, it is guaranteed that FCGI_RejectJSON
222 * has already been called with the appropriate description message.
224 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
226 const char *key, *value;
227 char buf[BUFSIZ], *ptr;
230 while ((params = FCGI_KeyPair(params, &key, &value))) {
231 for (i = 0; i < count; i++) {
232 if (!strcmp(key, values[i].key)) {
233 FCGIValue *val = &values[i];
235 if (FCGI_RECEIVED(val->flags)) {
236 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
237 FCGI_RejectJSON(context, buf);
240 val->flags |= FCGI_PARAM_RECEIVED;
242 switch(FCGI_TYPE(val->flags)) {
244 *((bool*) val->value) = true;
247 *((long*) val->value) = strtol(value, &ptr, 10);
248 if (!*value || *ptr) {
249 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
250 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
255 *((double*) val->value) = strtod(value, &ptr);
256 if (!*value || *ptr) {
257 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
258 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
263 *((const char**) val->value) = value;
266 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
268 break; //No need to search any more
272 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
273 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
278 //Check that required parameters are received
279 for (i = 0; i < count; i++) {
280 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
281 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
282 FCGI_RejectJSON(context, buf);
290 * Begins a response to the client in JSON format.
291 * @param context The context to work in.
292 * @param status_code The status code to be returned.
294 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
296 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
298 printf("\t\"module\" : \"%s\"", context->current_module);
299 FCGI_JSONLong("status", status_code);
303 * Adds a key/value pair to a JSON response. The response must have already
304 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
305 * @param key The key of the JSON entry
306 * @param value The value associated with the key.
308 void FCGI_JSONPair(const char *key, const char *value)
310 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
314 * Similar to FCGI_JSONPair except for signed integer values.
315 * @param key The key of the JSON entry
316 * @param value The value associated with the key
318 void FCGI_JSONLong(const char *key, long value)
320 printf(",\r\n\t\"%s\" : %ld", key, value);
324 * Similar to FCGI_JsonPair except for floating point values.
325 * @param key The key of the JSON entry
326 * @param value The value associated with the key
328 void FCGI_JSONDouble(const char *key, double value)
330 printf(",\r\n\t\"%s\" : %f", key, value);
334 * Similar to FCGI_JsonPair except for boolean values.
335 * @param key The key of the JSON entry
336 * @param value The value associated with the key
338 void FCGI_JSONBool(const char *key, bool value)
340 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
344 * Begins a JSON entry by writing the key. To be used in conjunction
345 * with FCGI_JsonValue.
346 * @param key The key of the JSON entry
348 void FCGI_JSONKey(const char *key)
350 printf(",\r\n\t\"%s\" : ", key);
354 * Ends a JSON response that was initiated by FCGI_BeginJSON.
362 * Escapes a string so it can be used as a JSON string value.
363 * Does not support unicode specifiers in the form of \uXXXX.
364 * @param buf The string to be escaped
365 * @return The escaped string (return value == buf)
367 char *FCGI_EscapeJSON(char *buf)
370 length = strlen(buf);
372 //Escape special characters. Must count down to escape properly
373 for (i = length - 1; i >= 0; i--) {
374 if (buf[i] < 0x20) { //Control characters
376 } else if (buf[i] == '"') {
377 if (i-1 >= 0 && buf[i-1] == '\\')
381 } else if (buf[i] == '\\') {
382 if (i-1 >= 0 && buf[i-1] == '\'')
392 * To be used when the input parameters are rejected. The return data
393 * will also have debugging information provided.
394 * @param context The context to work in
395 * @param status The status the return data should have.
396 * @param description A short description of why the input was rejected.
398 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
400 if (description == NULL)
401 description = "Unknown";
403 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
404 FCGI_BeginJSON(context, status);
405 FCGI_JSONPair("description", description);
406 FCGI_JSONLong("responsenumber", context->response_number);
407 FCGI_JSONPair("params", getenv("QUERY_STRING"));
408 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
409 FCGI_JSONPair("user", getenv("REMOTE_USER"));
410 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
415 * Generates a response to the client as described by the format parameter and
416 * extra arguments (exactly like printf). To be used when none of the other
417 * predefined functions will work exactly as needed. Extra care should be taken
418 * to ensure the correctness of the output.
419 * @param format The format string
420 * @param ... Any extra arguments as required by the format string.
422 void FCGI_PrintRaw(const char *format, ...)
425 va_start(list, format);
426 vprintf(format, list);
431 * Main FCGI request loop that receives/responds to client requests.
432 * @param data Reserved.
433 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
434 * TODO: Get this to exit with the rest of the program!
436 void * FCGI_RequestLoop (void *data)
438 FCGIContext context = {0};
440 Log(LOGDEBUG, "First request...");
441 //TODO: The FCGI_Accept here is blocking.
442 // That means that if another thread terminates the program, this thread
443 // will not terminate until the next request is made.
444 while (FCGI_Accept() >= 0) {
446 if (Thread_Runstate() != RUNNING)
448 //TODO: Yeah... deal with this better :P
449 Log(LOGERR, "FIXME; FCGI gets request after other threads have finished.");
450 printf("Content-type: text/plain\r\n\r\n+++OUT OF CHEESE ERROR+++\n");
454 Log(LOGDEBUG, "Got request #%d", context.response_number);
455 ModuleHandler module_handler = NULL;
456 char module[BUFSIZ], params[BUFSIZ];
458 //strncpy doesn't zero-truncate properly
459 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
460 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
462 //Remove trailing slashes (if present) from module query
463 size_t lastchar = strlen(module) - 1;
464 if (lastchar > 0 && module[lastchar] == '/')
465 module[lastchar] = 0;
467 //Default to the 'identify' module if none specified
469 strcpy(module, "identify");
471 if (!strcmp("identify", module)) {
472 module_handler = IdentifyHandler;
473 } else if (!strcmp("control", module)) {
474 module_handler = Control_Handler;
475 } else if (!strcmp("sensors", module)) {
476 module_handler = Sensor_Handler;
479 context.current_module = module;
480 if (module_handler) {
481 module_handler(&context, params);
483 FCGI_RejectJSON(&context, "Unhandled module");
485 context.response_number++;
487 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
490 Log(LOGDEBUG, "Thread exiting.");
491 Thread_QuitProgram(false);
492 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.