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;
43 //const char *key, *value;
47 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
48 {"actuators", &ident_actuators, FCGI_BOOL_T}};
50 if (!FCGI_ParseRequest(context, params, values, 2))
53 /*while ((params = FCGI_KeyPair(params, &key, &value))) {
54 if (!strcmp(key, "sensors")) {
55 ident_sensors = !ident_sensors;
56 } else if (!strcmp(key, "actuators")) {
57 ident_actuators = !ident_actuators;
61 FCGI_BeginJSON(context, STATUS_OK);
62 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
63 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
64 FCGI_JSONLong("api_version", API_VERSION);
66 //Sensor and actuator information
68 FCGI_JSONKey("sensors");
69 FCGI_JSONValue("{\n\t\t");
70 for (i = 0; i < NUMSENSORS; i++) {
72 FCGI_JSONValue(",\n\t\t");
74 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
76 FCGI_JSONValue("\n\t}");
78 if (ident_actuators) {
79 FCGI_JSONKey("actuators");
80 FCGI_JSONValue("{\n\t\t");
81 for (i = 0; i < NUMACTUATORS; i++) {
83 FCGI_JSONValue(",\n\t\t");
85 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
87 FCGI_JSONValue("\n\t}");
93 * Gives the user a key that determines who has control over
94 * the system at any one time. The key can be forcibly generated, revoking
95 * any previous control keys. To be used in conjunction with HTTP
96 * basic authentication.
97 * This function will generate a JSON response that indicates success/failure.
98 * @param context The context to work in
99 * @param force Whether to force key generation or not.
101 void FCGI_BeginControl(FCGIContext *context, bool force) {
102 time_t now = time(NULL);
103 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
105 if (force || !*(context->control_key) || expired) {
107 unsigned char sha1[20];
111 SHA1_Update(&sha1ctx, &now, sizeof(now));
112 SHA1_Update(&sha1ctx, &i, sizeof(i));
113 SHA1_Final(sha1, &sha1ctx);
115 context->control_timestamp = now;
116 for (i = 0; i < 20; i++)
117 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
118 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
119 FCGI_BeginJSON(context, STATUS_OK);
120 FCGI_JSONPair("key", context->control_key);
124 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
125 localtime(&(context->control_timestamp)));
126 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
127 FCGI_JSONPair("description", "Another user already has control");
128 FCGI_JSONPair("current_user", context->control_ip);
129 FCGI_JSONPair("when", buf);
135 * Given an FCGIContext, determines if the current user (as specified by
136 * the key) has control or not. If validated, the context control_timestamp is
138 * @param context The context to work in
139 * @param key The control key to be validated.
140 * @return TRUE if authorized, FALSE if not.
142 bool FCGI_HasControl(FCGIContext *context, const char *key) {
143 time_t now = time(NULL);
144 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
145 key != NULL && !strcmp(context->control_key, key);
147 context->control_timestamp = now; //Update the control_timestamp
154 * Revokes the current control key, if present.
155 * @param context The context to work in
157 void FCGI_EndControl(FCGIContext *context) {
158 *(context->control_key) = 0;
159 FCGI_BeginJSON(context, STATUS_OK);
165 * Extracts a key/value pair from a request string.
166 * Note that the input is modified by this function.
167 * @param in The string from which to extract the pair
168 * @param key A pointer to a variable to hold the key string
169 * @param value A pointer to a variable to hold the value string
170 * @return A pointer to the start of the next search location, or NULL if
171 * the EOL is reached.
173 char *FCGI_KeyPair(char *in, const char **key, const char **value)
176 if (!in || !*in) { //Invalid input or string is EOL
181 //Find either = or &, whichever comes first
182 if ((ptr = strpbrk(in, "=&"))) {
183 if (*ptr == '&') { //No value specified
187 //Stopped at an '=' sign
190 if ((ptr = strchr(ptr,'&'))) {
196 } else { //No value specified and no other pair
204 * Aids in parsing request parameters. Expected keys along with their type
205 * and whether or not they're required are provided. This function will then
206 * parse the parameter string to find these keys.
207 * @param context The context to work in
208 * @param params The parameter string to be parsed
209 * @param values An array of FCGIValue's that specify expected keys
210 * @param count The number of elements in 'values'.
211 * @return true If the parameter string was parsed successfully, false otherwise.
212 * Modes of failure include: Invalid a parsing error on the value,
213 * an unknown key is specified,
214 * a key/value pair is specified more than once, or
215 * not all required keys were present.
216 * If this function returns false, it is guaranteed that FCGI_RejectJSON
217 * has already been called with the appropriate description message.
219 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
221 const char *key, *value;
222 char buf[BUFSIZ], *ptr;
225 while ((params = FCGI_KeyPair(params, &key, &value))) {
226 for (i = 0; i < count; i++) {
227 if (!strcmp(key, values[i].key)) {
228 FCGIValue *val = &values[i];
230 if (FCGI_RECEIVED(val->flags)) {
231 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
232 FCGI_RejectJSON(context, buf);
235 val->flags |= FCGI_PARAM_RECEIVED;
237 switch(FCGI_TYPE(val->flags)) {
239 *((bool*) val->value) = true;
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, FCGI_EscapeJSON(buf));
249 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
250 *((int*) val->value) = 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, 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);
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));
309 * Adds a key/value pair to a JSON response. The response must have already
310 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
311 * @param key The key of the JSON entry
312 * @param value The value associated with the key.
314 void FCGI_JSONPair(const char *key, const char *value)
316 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
320 * Similar to FCGI_JSONPair except for signed integer values.
321 * @param key The key of the JSON entry
322 * @param value The value associated with the key
324 void FCGI_JSONLong(const char *key, long value)
326 printf(",\r\n\t\"%s\" : %ld", key, value);
330 * Similar to FCGI_JsonPair except for floating point values.
331 * @param key The key of the JSON entry
332 * @param value The value associated with the key
334 void FCGI_JSONDouble(const char *key, double value)
336 printf(",\r\n\t\"%s\" : %f", key, value);
340 * Similar to FCGI_JsonPair except for boolean values.
341 * @param key The key of the JSON entry
342 * @param value The value associated with the key
344 void FCGI_JSONBool(const char *key, bool value)
346 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
350 * Begins a JSON entry by writing the key. To be used in conjunction
351 * with FCGI_JsonValue.
352 * @param key The key of the JSON entry
354 void FCGI_JSONKey(const char *key)
356 printf(",\r\n\t\"%s\" : ", key);
360 * Ends a JSON response that was initiated by FCGI_BeginJSON.
368 * Escapes a string so it can be used as a JSON string value.
369 * Does not support unicode specifiers in the form of \uXXXX.
370 * @param buf The string to be escaped
371 * @return The escaped string (return value == buf)
373 char *FCGI_EscapeJSON(char *buf)
376 length = strlen(buf);
378 //Escape special characters. Must count down to escape properly
379 for (i = length - 1; i >= 0; i--) {
380 if (buf[i] < 0x20) { //Control characters
382 } else if (buf[i] == '"') {
383 if (i-1 >= 0 && buf[i-1] == '\\')
387 } else if (buf[i] == '\\') {
388 if (i-1 >= 0 && buf[i-1] == '\'')
398 * To be used when the input parameters are rejected. The return data
399 * will also have debugging information provided.
400 * @param context The context to work in
401 * @param status The status the return data should have.
402 * @param description A short description of why the input was rejected.
404 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
406 if (description == NULL)
407 description = "Unknown";
409 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
410 FCGI_BeginJSON(context, status);
411 FCGI_JSONPair("description", description);
412 FCGI_JSONLong("responsenumber", context->response_number);
413 FCGI_JSONPair("params", getenv("QUERY_STRING"));
414 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
415 FCGI_JSONPair("user", getenv("REMOTE_USER"));
416 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
421 * Generates a response to the client as described by the format parameter and
422 * extra arguments (exactly like printf). To be used when none of the other
423 * predefined functions will work exactly as needed. Extra care should be taken
424 * to ensure the correctness of the output.
425 * @param format The format string
426 * @param ... Any extra arguments as required by the format string.
428 void FCGI_PrintRaw(const char *format, ...)
431 va_start(list, format);
432 vprintf(format, list);
437 * Main FCGI request loop that receives/responds to client requests.
438 * @param data Reserved.
439 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
440 * TODO: Get this to exit with the rest of the program!
442 void * FCGI_RequestLoop (void *data)
444 FCGIContext context = {0};
446 Log(LOGDEBUG, "First request...");
447 while (FCGI_Accept() >= 0) {
448 Log(LOGDEBUG, "Got request #%d", context.response_number);
449 ModuleHandler module_handler = NULL;
450 char module[BUFSIZ], params[BUFSIZ];
452 //strncpy doesn't zero-truncate properly
453 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
454 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
456 //Remove trailing slashes (if present) from module query
457 size_t lastchar = strlen(module) - 1;
458 if (lastchar > 0 && module[lastchar] == '/')
459 module[lastchar] = 0;
461 //Default to the 'identify' module if none specified
463 strcpy(module, "identify");
465 if (!strcmp("identify", module)) {
466 module_handler = IdentifyHandler;
467 } else if (!strcmp("control", module)) {
468 module_handler = Control_Handler;
469 } else if (!strcmp("sensors", module)) {
470 module_handler = Sensor_Handler;
471 } else if (!strcmp("actuators", module)) {
472 module_handler = Actuator_Handler;
475 context.current_module = module;
476 if (module_handler) {
477 module_handler(&context, params);
479 FCGI_RejectJSON(&context, "Unhandled module");
481 context.response_number++;
483 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
486 Log(LOGDEBUG, "Thread exiting.");
487 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.