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;
241 *((long*) val->value) = 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));
249 *((double*) val->value) = strtod(value, &ptr);
250 if (!*value || *ptr) {
251 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
252 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
257 *((const char**) val->value) = value;
260 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
262 break; //No need to search any more
266 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
267 FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
272 //Check that required parameters are received
273 for (i = 0; i < count; i++) {
274 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
275 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
276 FCGI_RejectJSON(context, buf);
284 * Begins a response to the client in JSON format.
285 * @param context The context to work in.
286 * @param status_code The status code to be returned.
288 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
290 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
292 printf("\t\"module\" : \"%s\"", context->current_module);
293 FCGI_JSONLong("status", status_code);
294 //Time and running statistics
295 gettimeofday(&now, NULL);
296 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
297 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
298 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
302 * Adds a key/value pair to a JSON response. The response must have already
303 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
304 * @param key The key of the JSON entry
305 * @param value The value associated with the key.
307 void FCGI_JSONPair(const char *key, const char *value)
309 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
313 * Similar to FCGI_JSONPair except for signed integer values.
314 * @param key The key of the JSON entry
315 * @param value The value associated with the key
317 void FCGI_JSONLong(const char *key, long value)
319 printf(",\r\n\t\"%s\" : %ld", key, value);
323 * Similar to FCGI_JsonPair except for floating point values.
324 * @param key The key of the JSON entry
325 * @param value The value associated with the key
327 void FCGI_JSONDouble(const char *key, double value)
329 printf(",\r\n\t\"%s\" : %f", key, value);
333 * Similar to FCGI_JsonPair except for boolean values.
334 * @param key The key of the JSON entry
335 * @param value The value associated with the key
337 void FCGI_JSONBool(const char *key, bool value)
339 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
343 * Begins a JSON entry by writing the key. To be used in conjunction
344 * with FCGI_JsonValue.
345 * @param key The key of the JSON entry
347 void FCGI_JSONKey(const char *key)
349 printf(",\r\n\t\"%s\" : ", key);
353 * Ends a JSON response that was initiated by FCGI_BeginJSON.
361 * Escapes a string so it can be used as a JSON string value.
362 * Does not support unicode specifiers in the form of \uXXXX.
363 * @param buf The string to be escaped
364 * @return The escaped string (return value == buf)
366 char *FCGI_EscapeJSON(char *buf)
369 length = strlen(buf);
371 //Escape special characters. Must count down to escape properly
372 for (i = length - 1; i >= 0; i--) {
373 if (buf[i] < 0x20) { //Control characters
375 } else if (buf[i] == '"') {
376 if (i-1 >= 0 && buf[i-1] == '\\')
380 } else if (buf[i] == '\\') {
381 if (i-1 >= 0 && buf[i-1] == '\'')
391 * To be used when the input parameters are rejected. The return data
392 * will also have debugging information provided.
393 * @param context The context to work in
394 * @param status The status the return data should have.
395 * @param description A short description of why the input was rejected.
397 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
399 if (description == NULL)
400 description = "Unknown";
402 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
403 FCGI_BeginJSON(context, status);
404 FCGI_JSONPair("description", description);
405 FCGI_JSONLong("responsenumber", context->response_number);
406 FCGI_JSONPair("params", getenv("QUERY_STRING"));
407 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
408 FCGI_JSONPair("user", getenv("REMOTE_USER"));
409 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
414 * Generates a response to the client as described by the format parameter and
415 * extra arguments (exactly like printf). To be used when none of the other
416 * predefined functions will work exactly as needed. Extra care should be taken
417 * to ensure the correctness of the output.
418 * @param format The format string
419 * @param ... Any extra arguments as required by the format string.
421 void FCGI_PrintRaw(const char *format, ...)
424 va_start(list, format);
425 vprintf(format, list);
430 * Main FCGI request loop that receives/responds to client requests.
431 * @param data Reserved.
432 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
433 * TODO: Get this to exit with the rest of the program!
435 void * FCGI_RequestLoop (void *data)
437 FCGIContext context = {0};
439 Log(LOGDEBUG, "First request...");
440 //TODO: The FCGI_Accept here is blocking.
441 // That means that if another thread terminates the program, this thread
442 // will not terminate until the next request is made.
443 while (FCGI_Accept() >= 0) {
445 if (Thread_Runstate() != RUNNING)
447 //TODO: Yeah... deal with this better :P
448 Log(LOGERR, "FIXME; FCGI gets request after other threads have finished.");
449 printf("Content-type: text/plain\r\n\r\n+++OUT OF CHEESE ERROR+++\n");
453 Log(LOGDEBUG, "Got request #%d", context.response_number);
454 ModuleHandler module_handler = NULL;
455 char module[BUFSIZ], params[BUFSIZ];
457 //strncpy doesn't zero-truncate properly
458 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
459 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
461 //Remove trailing slashes (if present) from module query
462 size_t lastchar = strlen(module) - 1;
463 if (lastchar > 0 && module[lastchar] == '/')
464 module[lastchar] = 0;
466 //Default to the 'identify' module if none specified
468 strcpy(module, "identify");
470 if (!strcmp("identify", module)) {
471 module_handler = IdentifyHandler;
472 } else if (!strcmp("control", module)) {
473 module_handler = Control_Handler;
474 } else if (!strcmp("sensors", module)) {
475 module_handler = Sensor_Handler;
478 context.current_module = module;
479 if (module_handler) {
480 module_handler(&context, params);
482 FCGI_RejectJSON(&context, "Unhandled module");
484 context.response_number++;
486 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
489 Log(LOGDEBUG, "Thread exiting.");
490 Thread_QuitProgram(false);
491 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.