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>
17 /**The time period (in seconds) before the control key expires @ */
18 #define CONTROL_TIMEOUT 180
20 /**Contextual information related to FCGI requests*/
22 /**The time of last valid user access possessing the control key*/
23 time_t control_timestamp;
26 /**The name of the current module**/
27 const char *current_module;
28 /**For debugging purposes?**/
33 * Identifies build information and the current API version to the user.
34 * Also useful for testing that the API is running and identifying the
35 * sensors and actuators present.
36 * @param context The context to work in
37 * @param params User specified paramters: [actuators, sensors]
39 static void IdentifyHandler(FCGIContext *context, char *params) {
40 bool identSensors = false, identActuators = false;
41 const char *key, *value;
44 while ((params = FCGI_KeyPair(params, &key, &value))) {
45 if (!strcmp(key, "sensors")) {
46 identSensors = !identSensors;
47 } else if (!strcmp(key, "actuators")) {
48 identActuators = !identActuators;
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 FCGI_JSONKey("sensors");
58 FCGI_JSONValue("{\n\t\t");
59 for (i = 0; i < NUMSENSORS; i++) {
61 FCGI_JSONValue(",\n\t\t");
63 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
65 FCGI_JSONValue("\n\t}");
68 FCGI_JSONKey("actuators");
69 FCGI_JSONValue("{\n\t\t");
70 for (i = 0; i < NUMACTUATORS; i++) {
72 FCGI_JSONValue(",\n\t\t");
74 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
76 FCGI_JSONValue("\n\t}");
82 * Gives the user a key that determines who has control over
83 * the system at any one time. The key can be forcibly generated, revoking
84 * any previous control keys. To be used in conjunction with HTTP
85 * basic authentication.
86 * This function will generate a JSON response that indicates success/failure.
87 * @param context The context to work in
88 * @param force Whether to force key generation or not.
90 void FCGI_BeginControl(FCGIContext *context, bool force) {
91 time_t now = time(NULL);
92 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
94 if (force || !*(context->control_key) || expired) {
96 unsigned char sha1[20];
100 SHA1_Update(&sha1ctx, &now, sizeof(now));
101 SHA1_Update(&sha1ctx, &i, sizeof(i));
102 SHA1_Final(sha1, &sha1ctx);
104 context->control_timestamp = now;
105 for (i = 0; i < 20; i++)
106 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
107 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
108 FCGI_BeginJSON(context, STATUS_OK);
109 FCGI_JSONPair("key", context->control_key);
113 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
114 localtime(&(context->control_timestamp)));
115 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
116 FCGI_JSONPair("description", "Another user already has control");
117 FCGI_JSONPair("current_user", context->control_ip);
118 FCGI_JSONPair("when", buf);
124 * Given an FCGIContext, determines if the current user (as specified by
125 * the key) has control or not. If validated, the context control_timestamp is
127 * @param context The context to work in
128 * @param key The control key to be validated.
129 * @return TRUE if authorized, FALSE if not.
131 bool FCGI_HasControl(FCGIContext *context, const char *key) {
132 time_t now = time(NULL);
133 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
134 key != NULL && !strcmp(context->control_key, key);
136 context->control_timestamp = now; //Update the control_timestamp
143 * Revokes the current control key, if present.
144 * @param context The context to work in
146 void FCGI_EndControl(FCGIContext *context) {
147 *(context->control_key) = 0;
148 FCGI_BeginJSON(context, STATUS_OK);
154 * Extracts a key/value pair from a request string.
155 * Note that the input is modified by this function.
156 * @param in The string from which to extract the pair
157 * @param key A pointer to a variable to hold the key string
158 * @param value A pointer to a variable to hold the value string
159 * @return A pointer to the start of the next search location, or NULL if
160 * the EOL is reached.
162 char *FCGI_KeyPair(char *in, const char **key, const char **value)
165 if (!in || !*in) { //Invalid input or string is EOL
170 //Find either = or &, whichever comes first
171 if ((ptr = strpbrk(in, "=&"))) {
172 if (*ptr == '&') { //No value specified
176 //Stopped at an '=' sign
179 if ((ptr = strchr(ptr,'&'))) {
185 } else { //No value specified and no other pair
193 * Begins a response to the client in JSON format.
194 * @param context The context to work in.
195 * @param status_code The status code to be returned.
197 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
199 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
201 printf("\t\"module\" : \"%s\"", context->current_module);
202 FCGI_JSONLong("status", status_code);
204 // Jeremy: Should we include a timestamp in the JSON; something like this?
205 double start_time = g_options.start_time.tv_sec + 1e-6*(g_options.start_time.tv_usec);
207 gettimeofday(&now, NULL);
208 double current_time = now.tv_sec + 1e-6*(now.tv_usec);
209 FCGI_JSONDouble("start_time", start_time);
210 FCGI_JSONDouble("current_time", current_time);
211 FCGI_JSONDouble("running_time", current_time - start_time);
215 * Adds a key/value pair to a JSON response. The response must have already
216 * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
217 * @param key The key of the JSON entry
218 * @param value The value associated with the key.
220 void FCGI_JSONPair(const char *key, const char *value)
222 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
226 * Similar to FCGI_JSONPair except for signed integer values.
227 * @param key The key of the JSON entry
228 * @param value The value associated with the key
230 void FCGI_JSONLong(const char *key, long value)
232 printf(",\r\n\t\"%s\" : %ld", key, value);
236 * Similar to FCGI_JsonPair except for floating point values.
237 * @param key The key of the JSON entry
238 * @param value The value associated with the key
240 void FCGI_JSONDouble(const char *key, double value)
242 printf(",\r\n\t\"%s\" : %f", key, value);
246 * Similar to FCGI_JsonPair except for boolean values.
247 * @param key The key of the JSON entry
248 * @param value The value associated with the key
250 void FCGI_JSONBool(const char *key, bool value)
252 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
256 * Begins a JSON entry by writing the key. To be used in conjunction
257 * with FCGI_JsonValue.
258 * @param key The key of the JSON entry
260 void FCGI_JSONKey(const char *key)
262 printf(",\r\n\t\"%s\" : ", key);
266 * Ends a JSON response that was initiated by FCGI_BeginJSON.
274 * To be used when the input parameters are rejected. The return data
275 * will also have debugging information provided.
276 * @param context The context to work in
277 * @param status The status the return data should have.
278 * @param description A short description of why the input was rejected.
280 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
282 if (description == NULL)
283 description = "Unknown";
285 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
286 FCGI_BeginJSON(context, status);
287 FCGI_JSONPair("description", description);
288 FCGI_JSONLong("responsenumber", context->response_number);
289 FCGI_JSONPair("params", getenv("QUERY_STRING"));
290 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
291 FCGI_JSONPair("user", getenv("REMOTE_USER"));
292 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
297 * Generates a response to the client as described by the format parameter and
298 * extra arguments (exactly like printf). To be used when none of the other
299 * predefined functions will work exactly as needed. Extra care should be taken
300 * to ensure the correctness of the output.
301 * @param format The format string
302 * @param ... Any extra arguments as required by the format string.
304 void FCGI_PrintRaw(const char *format, ...)
307 va_start(list, format);
308 vprintf(format, list);
313 * Main FCGI request loop that receives/responds to client requests.
314 * @param data Reserved.
315 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
316 * TODO: Get this to exit with the rest of the program!
318 void * FCGI_RequestLoop (void *data)
320 FCGIContext context = {0};
322 Log(LOGDEBUG, "First request...");
323 //TODO: The FCGI_Accept here is blocking.
324 // That means that if another thread terminates the program, this thread
325 // will not terminate until the next request is made.
326 while (FCGI_Accept() >= 0) {
328 if (Thread_Runstate() != RUNNING)
330 //TODO: Yeah... deal with this better :P
331 Log(LOGERR, "FIXME; FCGI gets request after other threads have finished.");
332 printf("Content-type: text/plain\r\n\r\n+++OUT OF CHEESE ERROR+++\n");
336 Log(LOGDEBUG, "Got request #%d", context.response_number);
337 ModuleHandler module_handler = NULL;
338 char module[BUFSIZ], params[BUFSIZ];
340 //strncpy doesn't zero-truncate properly
341 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
342 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
344 //Remove trailing slashes (if present) from module query
345 size_t lastchar = strlen(module) - 1;
346 if (lastchar > 0 && module[lastchar] == '/')
347 module[lastchar] = 0;
349 //Default to the 'identify' module if none specified
351 strcpy(module, "identify");
353 if (!strcmp("identify", module)) {
354 module_handler = IdentifyHandler;
355 } else if (!strcmp("control", module)) {
356 module_handler = Control_Handler;
357 } else if (!strcmp("sensors", module)) {
358 module_handler = Sensor_Handler;
361 context.current_module = module;
362 if (module_handler) {
363 module_handler(&context, params);
365 FCGI_RejectJSON(&context, "Unhandled module");
367 context.response_number++;
369 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
372 Log(LOGDEBUG, "Thread exiting.");
373 Thread_QuitProgram(false);
374 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.