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>
21 /**The time period (in seconds) before the control key expires */
22 #define CONTROL_TIMEOUT 180
24 /**Contextual information related to FCGI requests*/
26 /**The time of last valid user access possessing the control key*/
27 time_t control_timestamp;
30 /**The name of the current module**/
31 const char *current_module;
32 /**For debugging purposes?**/
37 * Identifies build information and the current API version to the user.
38 * Also useful for testing that the API is running and identifying the
39 * sensors and actuators present.
40 * @param context The context to work in
41 * @param params User specified paramters: [actuators, sensors]
43 static void IdentifyHandler(FCGIContext *context, char *params) {
44 bool ident_sensors = false, ident_actuators = false;
48 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
49 {"actuators", &ident_actuators, FCGI_BOOL_T}};
50 if (!FCGI_ParseRequest(context, params, values, 2))
53 FCGI_BeginJSON(context, STATUS_OK);
54 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
55 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
56 FCGI_JSONLong("api_version", API_VERSION);
58 //Sensor and actuator information
60 FCGI_JSONKey("sensors");
61 FCGI_JSONValue("{\n\t\t");
62 for (i = 0; i < NUMSENSORS; i++) {
64 FCGI_JSONValue(",\n\t\t");
66 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
68 FCGI_JSONValue("\n\t}");
70 if (ident_actuators) {
71 FCGI_JSONKey("actuators");
72 FCGI_JSONValue("{\n\t\t");
73 for (i = 0; i < NUMACTUATORS; i++) {
75 FCGI_JSONValue(",\n\t\t");
77 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
79 FCGI_JSONValue("\n\t}");
85 * Gives the user a key that determines who has control over
86 * the system at any one time. The key can be forcibly generated, revoking
87 * any previous control keys. To be used in conjunction with HTTP
88 * basic authentication.
89 * This function will generate a JSON response that indicates success/failure.
90 * @param context The context to work in
91 * @param force Whether to force key generation or not.
93 void FCGI_LockControl(FCGIContext *context, bool force) {
94 time_t now = time(NULL);
95 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
97 if (force || !*(context->control_key) || expired) {
99 unsigned char sha1[20];
103 SHA1_Update(&sha1ctx, &now, sizeof(now));
104 SHA1_Update(&sha1ctx, &i, sizeof(i));
105 SHA1_Final(sha1, &sha1ctx);
107 context->control_timestamp = now;
108 for (i = 0; i < 20; i++)
109 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
110 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
111 FCGI_BeginJSON(context, STATUS_OK);
112 FCGI_JSONPair("key", context->control_key);
116 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
117 localtime(&(context->control_timestamp)));
118 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
119 FCGI_JSONPair("description", "Another user already has control");
120 FCGI_JSONPair("current_user", context->control_ip);
121 FCGI_JSONPair("when", buf);
127 * Given an FCGIContext, determines if the current user (as specified by
128 * the key) has control or not. If validated, the context control_timestamp is
130 * @param context The context to work in
131 * @param key The control key to be validated.
132 * @return TRUE if authorized, FALSE if not.
134 bool FCGI_HasControl(FCGIContext *context, const char *key) {
135 time_t now = time(NULL);
136 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
137 key != NULL && !strcmp(context->control_key, key);
139 context->control_timestamp = now; //Update the control_timestamp
146 * Revokes the current control key, if present.
147 * @param context The context to work in
149 void FCGI_ReleaseControl(FCGIContext *context) {
150 *(context->control_key) = 0;
151 FCGI_BeginJSON(context, STATUS_OK);
157 * Extracts a key/value pair from a request string.
158 * Note that the input is modified by this function.
159 * @param in The string from which to extract the pair
160 * @param key A pointer to a variable to hold the key string
161 * @param value A pointer to a variable to hold the value string
162 * @return A pointer to the start of the next search location, or NULL if
163 * the EOL is reached.
165 char *FCGI_KeyPair(char *in, const char **key, const char **value)
168 if (!in || !*in) { //Invalid input or string is EOL
173 //Find either = or &, whichever comes first
174 if ((ptr = strpbrk(in, "=&"))) {
175 if (*ptr == '&') { //No value specified
179 //Stopped at an '=' sign
182 if ((ptr = strchr(ptr,'&'))) {
188 } else { //No value specified and no other pair
196 * Aids in parsing request parameters.
197 * Input: The expected keys along with their type and whether or not
199 * @param context The context to work in
200 * @param params The parameter string to be parsed
201 * @param values An array of FCGIValue's that specify expected keys
202 * @param count The number of elements in 'values'.
203 * @return true If the parameter string was parsed successfully, false otherwise.
204 * Modes of failure include: Invalid a parsing error on the value,
205 * an unknown key is specified,
206 * a key/value pair is specified more than once, or
207 * not all required keys were present.
208 * If this function returns false, it is guaranteed that FCGI_RejectJSON
209 * has already been called with the appropriate description message.
211 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
213 const char *key, *value;
214 char buf[BUFSIZ], *ptr;
217 while ((params = FCGI_KeyPair(params, &key, &value))) {
218 for (i = 0; i < count; i++) {
219 if (!strcmp(key, values[i].key)) {
220 FCGIValue *val = &values[i];
222 if (FCGI_RECEIVED(val->flags)) {
223 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
224 FCGI_RejectJSON(context, buf);
227 val->flags |= FCGI_PARAM_RECEIVED;
229 switch(FCGI_TYPE(val->flags)) {
231 *((bool*) val->value) = true;
233 case FCGI_INT_T: case FCGI_LONG_T: {
234 long parsed = strtol(value, &ptr, 10);
235 if (!*value || *ptr) {
236 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
237 FCGI_RejectJSON(context, buf);
241 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
242 *((int*) val->value) = (int) parsed;
244 *((long*) val->value) = parsed;
247 *((double*) val->value) = strtod(value, &ptr);
248 if (!*value || *ptr) {
249 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
250 FCGI_RejectJSON(context, buf);
255 *((const char**) val->value) = value;
258 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
260 break; //No need to search any more
264 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
265 FCGI_RejectJSON(context, buf);
270 //Check that required parameters are received
271 for (i = 0; i < count; i++) {
272 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
273 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
274 FCGI_RejectJSON(context, buf);
282 * Begins a response to the client in JSON format.
283 * @param context The context to work in.
284 * @param status_code The status code to be returned.
286 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
288 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
290 printf("\t\"module\" : \"%s\"", context->current_module);
291 FCGI_JSONLong("status", status_code);
292 //Time and running statistics
294 gettimeofday(&now, NULL);
295 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
296 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
297 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
298 FCGI_JSONPair("control_state", Control_GetModeName());
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 * To be used when the input parameters are rejected. The return data
362 * will also have debugging information provided.
363 * @param context The context to work in
364 * @param status The status the return data should have.
365 * @param description A short description of why the input was rejected.
367 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
369 if (description == NULL)
370 description = "Unknown";
372 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
373 FCGI_BeginJSON(context, status);
374 FCGI_JSONPair("description", description);
375 FCGI_JSONLong("responsenumber", context->response_number);
376 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
377 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
378 FCGI_JSONPair("user", getenv("REMOTE_USER"));
379 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
384 * Generates a response to the client as described by the format parameter and
385 * extra arguments (exactly like printf). To be used when none of the other
386 * predefined functions will work exactly as needed. Extra care should be taken
387 * to ensure the correctness of the output.
388 * @param format The format string
389 * @param ... Any extra arguments as required by the format string.
391 void FCGI_PrintRaw(const char *format, ...)
394 va_start(list, format);
395 vprintf(format, list);
404 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
406 Log(LOGDEBUG,"Writing!");
407 fwrite(data, size, num_elem, stdout);
411 * Escapes a string so it can be used safely.
412 * Currently escapes to ensure the validity for use as a JSON string
413 * Does not support unicode specifiers in the form of \uXXXX.
414 * @param buf The string to be escaped
415 * @return The escaped string (return value == buf)
417 char *FCGI_EscapeText(char *buf)
420 length = strlen(buf);
422 //Escape special characters. Must count down to escape properly
423 for (i = length - 1; i >= 0; i--) {
424 if (buf[i] < 0x20) { //Control characters
426 } else if (buf[i] == '"') {
427 if (i-1 >= 0 && buf[i-1] == '\\')
431 } else if (buf[i] == '\\') {
432 if (i-1 >= 0 && buf[i-1] == '\'')
442 * Main FCGI request loop that receives/responds to client requests.
443 * @param data Reserved.
444 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
445 * TODO: Get this to exit with the rest of the program!
447 void * FCGI_RequestLoop (void *data)
449 FCGIContext context = {0};
451 Log(LOGDEBUG, "Start loop");
452 while (FCGI_Accept() >= 0) {
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 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
463 //Remove trailing slashes (if present) from module query
464 size_t lastchar = strlen(module) - 1;
465 if (lastchar > 0 && module[lastchar] == '/')
466 module[lastchar] = 0;
468 //Escape all special characters
469 FCGI_EscapeText(params);
471 //Default to the 'identify' module if none specified
473 strcpy(module, "identify");
475 if (!strcmp("identify", module)) {
476 module_handler = IdentifyHandler;
477 } else if (!strcmp("control", module)) {
478 module_handler = Control_Handler;
479 } else if (!strcmp("sensors", module)) {
480 module_handler = Sensor_Handler;
481 } else if (!strcmp("actuators", module)) {
482 module_handler = Actuator_Handler;
483 } else if (!strcmp("image", module)) {
484 module_handler = Image_Handler;
485 } else if (!strcmp("pin", module)) {
486 module_handler = Pin_Handler; // *Debug only* pin test module
489 context.current_module = module;
490 if (module_handler) {
491 module_handler(&context, params);
493 FCGI_RejectJSON(&context, "Unhandled module");
495 context.response_number++;
500 Log(LOGDEBUG, "Thread exiting.");
501 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.