3 * @purpose 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 #define LOGIN_TIMEOUT 180
21 /**The time of last valid logged-in user access*/
22 time_t login_timestamp;
25 /**The name of the current module**/
26 const char *current_module;
27 /**For debugging purposes?**/
32 * Handles user logins.
33 * @param context The context to work in
34 * @param params User specified parameters
36 static void LoginHandler(FCGIContext *context, char *params) {
37 const char *key, *value;
38 bool force = 0, end = 0;
40 while ((params = FCGI_KeyPair(params, &key, &value))) {
41 if (!strcmp(key, "force"))
43 else if (!strcmp(key, "end"))
48 *(context->login_key) = 0;
49 FCGI_BeginJSON(context, STATUS_OK);
54 time_t now = time(NULL);
55 if (force || !*(context->login_key) ||
56 (now - context->login_timestamp > LOGIN_TIMEOUT))
59 unsigned char sha1[20];
63 SHA1_Update(&sha1ctx, &now, sizeof(now));
64 SHA1_Update(&sha1ctx, &i, sizeof(i));
65 SHA1_Final(sha1, &sha1ctx);
67 context->login_timestamp = now;
68 for (i = 0; i < 20; i++)
69 sprintf(context->login_key + i * 2, "%02x", sha1[i]);
70 snprintf(context->login_ip, 16, "%s", getenv("REMOTE_ADDR"));
71 FCGI_BeginJSON(context, STATUS_OK);
72 FCGI_JSONPair("key", context->login_key);
76 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
77 localtime(&(context->login_timestamp)));
78 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
79 FCGI_JSONPair("description", "Already logged in");
80 FCGI_JSONPair("user", context->login_ip);
81 FCGI_JSONPair("time", buf);
86 /*TODO: Remove and replace with the actual actuator code*/
87 static void ActuatorHandler(FCGIContext *context, char *params) {
88 const char *key, *value, *loginkey = NULL;
89 while ((params = FCGI_KeyPair(params, &key, &value))) {
90 if (!strcmp(key, "key")) {
94 if (!loginkey || !FCGI_Authorized(context, loginkey)) {
95 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
96 FCGI_JSONPair("description", "Invalid key specified.");
99 FCGI_BeginJSON(context, STATUS_OK);
100 FCGI_JSONPair("description", "Logged in!");
106 * Given an FCGIContext, determines if the current user (as specified by
107 * the key) is authorized or not. If validated, the context login_timestamp is
109 * @param context The context to work in
110 * @param key The login key to be validated.
111 * @return TRUE if authorized, FALSE if not.
113 bool FCGI_Authorized(FCGIContext *context, const char *key) {
114 time_t now = time(NULL);
115 int result = (now - context->login_timestamp) <= LOGIN_TIMEOUT &&
116 !strcmp(context->login_key, key);
118 context->login_timestamp = now; //Update the login_timestamp
124 * Extracts a key/value pair from a request string.
125 * Note that the input is modified by this function.
126 * @param in The string from which to extract the pair
127 * @param key A pointer to a variable to hold the key string
128 * @param value A pointer to a variable to hold the value string
129 * @return A pointer to the start of the next search location, or NULL if
130 * the EOL is reached.
132 char *FCGI_KeyPair(char *in, const char **key, const char **value)
135 if (!in || !*in) { //Invalid input or string is EOL
140 //Find either = or &, whichever comes first
141 if ((ptr = strpbrk(in, "=&"))) {
142 if (*ptr == '&') { //No value specified
146 //Stopped at an '=' sign
149 if ((ptr = strchr(ptr,'&'))) {
155 } else { //No value specified and no other pair
163 * Begins a response to the client in JSON format.
164 * @param context The context to work in.
165 * @param status_code The status code to be returned.
167 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
169 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
171 printf("\t\"module\" : \"%s\"", context->current_module);
172 FCGI_JSONLong("status", status_code);
174 // Jeremy: Should we include a timestamp in the JSON; something like this?
175 double start_time = g_options.start_time.tv_sec + 1e-6*(g_options.start_time.tv_usec);
177 gettimeofday(&now, NULL);
178 double current_time = now.tv_sec + 1e-6*(now.tv_usec);
179 FCGI_JSONDouble("start_time", start_time);
180 FCGI_JSONDouble("current_time", current_time);
181 FCGI_JSONDouble("running_time", current_time - start_time);
186 * Adds a key/value pair to a JSON response. The response must have already
187 * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
188 * @param key The key of the JSON entry
189 * ¶m value The value associated with the key.
191 void FCGI_JSONPair(const char *key, const char *value)
193 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
197 * Similar to FCGI_JSONPair except for signed integer values.
198 * @param key The key of the JSON entry
199 * @param value The value associated with the key
201 void FCGI_JSONLong(const char *key, long value)
203 printf(",\r\n\t\"%s\" : %ld", key, value);
207 * Similar to FCGI_JsonPair except for floating point values.
208 * @param key The key of the JSON entry
209 * @param value The value associated with the key
211 void FCGI_JSONDouble(const char *key, double value)
213 printf(",\r\n\t\"%s\" : %f", key, value);
217 * Similar to FCGI_JsonPair except for boolean values.
218 * @param key The key of the JSON entry
219 * @param value The value associated with the key
221 void FCGI_JSONBool(const char *key, bool value)
223 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
227 * Begins a JSON entry by writing the key. To be used in conjunction
228 * with FCGI_JsonValue.
229 * @param key The key of the JSON entry
231 void FCGI_JSONKey(const char *key)
233 printf(",\r\n\t\"%s\" : ", key);
237 * Should be used to write out the value of a JSON key. This has
238 * the same format as the printf functions. Care should be taken to format
239 * the output in valid JSON.
241 void FCGI_JSONValue(const char *format, ...)
244 va_start(list, format);
245 vprintf(format, list);
250 * Ends a JSON response that was initiated by FCGI_BeginJSON.
258 * To be used when the input parameters are invalid.
259 * Sends a response with HTTP status 400 Bad request, along with
260 * JSON data for debugging.
261 * @param context The context to work in
262 * @param params The parameters that the module handler received.
264 void FCGI_RejectJSON(FCGIContext *context)
266 printf("Status: 400 Bad Request\r\n");
268 FCGI_BeginJSON(context, STATUS_ERROR);
269 FCGI_JSONPair("description", "Invalid request");
270 FCGI_JSONLong("responsenumber", context->response_number);
271 FCGI_JSONPair("params", getenv("QUERY_STRING"));
272 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
273 FCGI_JSONPair("user", getenv("REMOTE_USER"));
274 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
279 * Main FCGI request loop that receives/responds to client requests.
280 * @param data Reserved.
281 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
282 * TODO: Get this to exit with the rest of the program!
284 void * FCGI_RequestLoop (void *data)
286 FCGIContext context = {0};
288 Log(LOGDEBUG, "First request...");
289 //TODO: The FCGI_Accept here is blocking.
290 // That means that if another thread terminates the program, this thread
291 // will not terminate until the next request is made.
292 while (FCGI_Accept() >= 0) {
294 if (Thread_Runstate() != RUNNING)
296 //TODO: Yeah... deal with this better :P
297 Log(LOGERR, "FIXME; FCGI gets request after other threads have finished.");
298 printf("Content-type: text/plain\r\n\r\n+++OUT OF CHEESE ERROR+++\n");
302 Log(LOGDEBUG, "Got request #%d", context.response_number);
303 ModuleHandler module_handler = NULL;
304 char module[BUFSIZ], params[BUFSIZ];
306 //strncpy doesn't zero-truncate properly
307 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
308 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
310 //Remove trailing slashes (if present) from module query
311 size_t lastchar = strlen(module) - 1;
312 if (lastchar > 0 && module[lastchar] == '/')
313 module[lastchar] = 0;
316 if (!strcmp("login", module)) {
317 module_handler = LoginHandler;
318 } else if (!strcmp("sensors", module)) {
319 module_handler = Sensor_Handler;
320 } else if (!strcmp("actuators", module)) {
321 module_handler = ActuatorHandler;
324 context.current_module = module;
325 if (module_handler) {
326 module_handler(&context, params);
328 strncat(module, " [unknown]", BUFSIZ);
329 FCGI_RejectJSON(&context);
331 context.response_number++;
333 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
336 Log(LOGDEBUG, "Thread exiting.");
337 Thread_QuitProgram(false);
338 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.