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>
20 /**The time period (in seconds) before the control key expires */
21 #define CONTROL_TIMEOUT 180
23 /**Contextual information related to FCGI requests*/
25 /**The time of last valid user access possessing the control key*/
26 time_t control_timestamp;
29 /**The name of the current module**/
30 const char *current_module;
31 /**For debugging purposes?**/
36 * Identifies build information and the current API version to the user.
37 * Also useful for testing that the API is running and identifying the
38 * sensors and actuators present.
39 * @param context The context to work in
40 * @param params User specified paramters: [actuators, sensors]
42 static void IdentifyHandler(FCGIContext *context, char *params) {
43 bool ident_sensors = false, ident_actuators = false;
47 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
48 {"actuators", &ident_actuators, FCGI_BOOL_T}};
49 if (!FCGI_ParseRequest(context, params, values, 2))
52 FCGI_BeginJSON(context, STATUS_OK);
53 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
54 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
55 FCGI_JSONLong("api_version", API_VERSION);
57 //Sensor and actuator information
59 FCGI_JSONKey("sensors");
60 FCGI_JSONValue("{\n\t\t");
61 for (i = 0; i < NUMSENSORS; i++) {
63 FCGI_JSONValue(",\n\t\t");
65 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
67 FCGI_JSONValue("\n\t}");
69 if (ident_actuators) {
70 FCGI_JSONKey("actuators");
71 FCGI_JSONValue("{\n\t\t");
72 for (i = 0; i < NUMACTUATORS; i++) {
74 FCGI_JSONValue(",\n\t\t");
76 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
78 FCGI_JSONValue("\n\t}");
84 * Gives the user a key that determines who has control over
85 * the system at any one time. The key can be forcibly generated, revoking
86 * any previous control keys. To be used in conjunction with HTTP
87 * basic authentication.
88 * This function will generate a JSON response that indicates success/failure.
89 * @param context The context to work in
90 * @param force Whether to force key generation or not.
92 void FCGI_LockControl(FCGIContext *context, bool force) {
93 time_t now = time(NULL);
94 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
96 if (force || !*(context->control_key) || expired) {
98 unsigned char sha1[20];
102 SHA1_Update(&sha1ctx, &now, sizeof(now));
103 SHA1_Update(&sha1ctx, &i, sizeof(i));
104 SHA1_Final(sha1, &sha1ctx);
106 context->control_timestamp = now;
107 for (i = 0; i < 20; i++)
108 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
109 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
110 FCGI_BeginJSON(context, STATUS_OK);
111 FCGI_JSONPair("key", context->control_key);
115 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
116 localtime(&(context->control_timestamp)));
117 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
118 FCGI_JSONPair("description", "Another user already has control");
119 FCGI_JSONPair("current_user", context->control_ip);
120 FCGI_JSONPair("when", buf);
126 * Given an FCGIContext, determines if the current user (as specified by
127 * the key) has control or not. If validated, the context control_timestamp is
129 * @param context The context to work in
130 * @param key The control key to be validated.
131 * @return TRUE if authorized, FALSE if not.
133 bool FCGI_HasControl(FCGIContext *context, const char *key) {
134 time_t now = time(NULL);
135 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
136 key != NULL && !strcmp(context->control_key, key);
138 context->control_timestamp = now; //Update the control_timestamp
145 * Revokes the current control key, if present.
146 * @param context The context to work in
148 void FCGI_ReleaseControl(FCGIContext *context) {
149 *(context->control_key) = 0;
150 FCGI_BeginJSON(context, STATUS_OK);
156 * Extracts a key/value pair from a request string.
157 * Note that the input is modified by this function.
158 * @param in The string from which to extract the pair
159 * @param key A pointer to a variable to hold the key string
160 * @param value A pointer to a variable to hold the value string
161 * @return A pointer to the start of the next search location, or NULL if
162 * the EOL is reached.
164 char *FCGI_KeyPair(char *in, const char **key, const char **value)
167 if (!in || !*in) { //Invalid input or string is EOL
172 //Find either = or &, whichever comes first
173 if ((ptr = strpbrk(in, "=&"))) {
174 if (*ptr == '&') { //No value specified
178 //Stopped at an '=' sign
181 if ((ptr = strchr(ptr,'&'))) {
187 } else { //No value specified and no other pair
195 * Aids in parsing request parameters.
196 * Input: The expected keys along with their type and whether or not
198 * @param context The context to work in
199 * @param params The parameter string to be parsed
200 * @param values An array of FCGIValue's that specify expected keys
201 * @param count The number of elements in 'values'.
202 * @return true If the parameter string was parsed successfully, false otherwise.
203 * Modes of failure include: Invalid a parsing error on the value,
204 * an unknown key is specified,
205 * a key/value pair is specified more than once, or
206 * not all required keys were present.
207 * If this function returns false, it is guaranteed that FCGI_RejectJSON
208 * has already been called with the appropriate description message.
210 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
212 const char *key, *value;
213 char buf[BUFSIZ], *ptr;
216 while ((params = FCGI_KeyPair(params, &key, &value))) {
217 for (i = 0; i < count; i++) {
218 if (!strcmp(key, values[i].key)) {
219 FCGIValue *val = &values[i];
221 if (FCGI_RECEIVED(val->flags)) {
222 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
223 FCGI_RejectJSON(context, buf);
226 val->flags |= FCGI_PARAM_RECEIVED;
228 switch(FCGI_TYPE(val->flags)) {
230 if (!*value) //No value: Default true
231 *((bool*) val->value) = true;
233 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
235 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
236 FCGI_RejectJSON(context, buf);
241 case FCGI_INT_T: case FCGI_LONG_T: {
242 long parsed = strtol(value, &ptr, 10);
243 if (!*value || *ptr) {
244 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
245 FCGI_RejectJSON(context, buf);
249 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
250 *((int*) val->value) = (int) parsed;
252 *((long*) val->value) = parsed;
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, 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, 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);
300 //Time and running statistics
302 gettimeofday(&now, NULL);
303 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
304 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
305 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
306 FCGI_JSONPair("control_state", Control_GetModeName());
310 * Adds a key/value pair to a JSON response. The response must have already
311 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
312 * @param key The key of the JSON entry
313 * @param value The value associated with the key.
315 void FCGI_JSONPair(const char *key, const char *value)
317 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
321 * Similar to FCGI_JSONPair except for signed integer values.
322 * @param key The key of the JSON entry
323 * @param value The value associated with the key
325 void FCGI_JSONLong(const char *key, long value)
327 printf(",\r\n\t\"%s\" : %ld", key, value);
331 * Similar to FCGI_JsonPair except for floating point values.
332 * @param key The key of the JSON entry
333 * @param value The value associated with the key
335 void FCGI_JSONDouble(const char *key, double value)
337 printf(",\r\n\t\"%s\" : %f", key, value);
341 * Similar to FCGI_JsonPair except for boolean values.
342 * @param key The key of the JSON entry
343 * @param value The value associated with the key
345 void FCGI_JSONBool(const char *key, bool value)
347 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
351 * Begins a JSON entry by writing the key. To be used in conjunction
352 * with FCGI_JsonValue.
353 * @param key The key of the JSON entry
355 void FCGI_JSONKey(const char *key)
357 printf(",\r\n\t\"%s\" : ", key);
361 * Ends a JSON response that was initiated by FCGI_BeginJSON.
369 * To be used when the input parameters are rejected. The return data
370 * will also have debugging information provided.
371 * @param context The context to work in
372 * @param status The status the return data should have.
373 * @param description A short description of why the input was rejected.
375 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
377 if (description == NULL)
378 description = "Unknown";
380 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
381 FCGI_BeginJSON(context, status);
382 FCGI_JSONPair("description", description);
383 FCGI_JSONLong("responsenumber", context->response_number);
384 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
385 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
386 FCGI_JSONPair("user", getenv("REMOTE_USER"));
387 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
392 * Generates a response to the client as described by the format parameter and
393 * extra arguments (exactly like printf). To be used when none of the other
394 * predefined functions will work exactly as needed. Extra care should be taken
395 * to ensure the correctness of the output.
396 * @param format The format string
397 * @param ... Any extra arguments as required by the format string.
399 void FCGI_PrintRaw(const char *format, ...)
402 va_start(list, format);
403 vprintf(format, list);
412 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
414 Log(LOGDEBUG,"Writing!");
415 fwrite(data, size, num_elem, stdout);
419 * Escapes a string so it can be used safely.
420 * Currently escapes to ensure the validity for use as a JSON string
421 * Does not support unicode specifiers in the form of \uXXXX.
422 * @param buf The string to be escaped
423 * @return The escaped string (return value == buf)
425 char *FCGI_EscapeText(char *buf)
428 length = strlen(buf);
430 //Escape special characters. Must count down to escape properly
431 for (i = length - 1; i >= 0; i--) {
432 if (buf[i] < 0x20) { //Control characters
434 } else if (buf[i] == '"') {
435 if (i-1 >= 0 && buf[i-1] == '\\')
439 } else if (buf[i] == '\\') {
440 if (i-1 >= 0 && buf[i-1] == '\'')
450 * Main FCGI request loop that receives/responds to client requests.
451 * @param data Reserved.
452 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
453 * TODO: Get this to exit with the rest of the program!
455 void * FCGI_RequestLoop (void *data)
457 FCGIContext context = {0};
459 Log(LOGDEBUG, "Start loop");
460 while (FCGI_Accept() >= 0) {
462 ModuleHandler module_handler = NULL;
463 char module[BUFSIZ], params[BUFSIZ];
465 //strncpy doesn't zero-truncate properly
466 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
467 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
469 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
471 //Remove trailing slashes (if present) from module query
472 size_t lastchar = strlen(module) - 1;
473 if (lastchar > 0 && module[lastchar] == '/')
474 module[lastchar] = 0;
476 //Escape all special characters
477 FCGI_EscapeText(params);
479 //Default to the 'identify' module if none specified
481 strcpy(module, "identify");
483 if (!strcmp("identify", module)) {
484 module_handler = IdentifyHandler;
485 } else if (!strcmp("control", module)) {
486 module_handler = Control_Handler;
487 } else if (!strcmp("sensors", module)) {
488 module_handler = Sensor_Handler;
489 } else if (!strcmp("actuators", module)) {
490 module_handler = Actuator_Handler;
491 } else if (!strcmp("image", module)) {
492 module_handler = Image_Handler;
495 context.current_module = module;
496 if (module_handler) {
497 module_handler(&context, params);
499 FCGI_RejectJSON(&context, "Unhandled module");
501 context.response_number++;
506 Log(LOGDEBUG, "Thread exiting.");
507 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.