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 * Identifies current version info. Useful for testing that the API is running.
33 * TODO - Consider adding info about available sensors and actuators (eg capabilities)?
35 static void IdentifyHandler(FCGIContext *context, char *params) {
36 FCGI_BeginJSON(context, STATUS_OK);
37 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
38 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
43 * Gives the user an authorization key that determines who has control over
44 * the system at any one time. The key can be forcibly generated, revoking
45 * any previous control keys. To be used in conjunction with HTTP
46 * basic authentication.
47 * This function will generate a JSON response that indicates success/failure.
48 * @param context The context to work in
49 * @param force Whether to force key generation or not.
51 void FCGI_Authorize(FCGIContext *context, bool force) {
52 time_t now = time(NULL);
53 bool expired = now - context->login_timestamp > LOGIN_TIMEOUT;
55 if (force || !*(context->login_key) || expired) {
57 unsigned char sha1[20];
61 SHA1_Update(&sha1ctx, &now, sizeof(now));
62 SHA1_Update(&sha1ctx, &i, sizeof(i));
63 SHA1_Final(sha1, &sha1ctx);
65 context->login_timestamp = now;
66 for (i = 0; i < 20; i++)
67 sprintf(context->login_key + i * 2, "%02x", sha1[i]);
68 snprintf(context->login_ip, 16, "%s", getenv("REMOTE_ADDR"));
69 FCGI_BeginJSON(context, STATUS_OK);
70 FCGI_JSONPair("key", context->login_key);
74 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
75 localtime(&(context->login_timestamp)));
76 FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
77 FCGI_JSONPair("description", "Already logged in");
78 FCGI_JSONPair("current_user", context->login_ip);
79 FCGI_JSONPair("when", buf);
85 * Revokes the current authorization key, if present.
86 * @param context The context to work in
88 void FCGI_AuthorizeEnd(FCGIContext *context) {
89 *(context->login_key) = 0;
90 FCGI_BeginJSON(context, STATUS_OK);
96 * Given an FCGIContext, determines if the current user (as specified by
97 * the key) is authorized or not. If validated, the context login_timestamp is
99 * @param context The context to work in
100 * @param key The login key to be validated.
101 * @return TRUE if authorized, FALSE if not.
103 bool FCGI_Authorized(FCGIContext *context, const char *key) {
104 time_t now = time(NULL);
105 int result = (now - context->login_timestamp) <= LOGIN_TIMEOUT &&
106 key != NULL && !strcmp(context->login_key, key);
108 context->login_timestamp = now; //Update the login_timestamp
114 * Extracts a key/value pair from a request string.
115 * Note that the input is modified by this function.
116 * @param in The string from which to extract the pair
117 * @param key A pointer to a variable to hold the key string
118 * @param value A pointer to a variable to hold the value string
119 * @return A pointer to the start of the next search location, or NULL if
120 * the EOL is reached.
122 char *FCGI_KeyPair(char *in, const char **key, const char **value)
125 if (!in || !*in) { //Invalid input or string is EOL
130 //Find either = or &, whichever comes first
131 if ((ptr = strpbrk(in, "=&"))) {
132 if (*ptr == '&') { //No value specified
136 //Stopped at an '=' sign
139 if ((ptr = strchr(ptr,'&'))) {
145 } else { //No value specified and no other pair
153 * Begins a response to the client in JSON format.
154 * @param context The context to work in.
155 * @param status_code The status code to be returned.
157 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
159 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
161 printf("\t\"module\" : \"%s\"", context->current_module);
162 FCGI_JSONLong("status", status_code);
164 // Jeremy: Should we include a timestamp in the JSON; something like this?
165 double start_time = g_options.start_time.tv_sec + 1e-6*(g_options.start_time.tv_usec);
167 gettimeofday(&now, NULL);
168 double current_time = now.tv_sec + 1e-6*(now.tv_usec);
169 FCGI_JSONDouble("start_time", start_time);
170 FCGI_JSONDouble("current_time", current_time);
171 FCGI_JSONDouble("running_time", current_time - start_time);
176 * Adds a key/value pair to a JSON response. The response must have already
177 * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
178 * @param key The key of the JSON entry
179 * ¶m value The value associated with the key.
181 void FCGI_JSONPair(const char *key, const char *value)
183 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
187 * Similar to FCGI_JSONPair except for signed integer values.
188 * @param key The key of the JSON entry
189 * @param value The value associated with the key
191 void FCGI_JSONLong(const char *key, long value)
193 printf(",\r\n\t\"%s\" : %ld", key, value);
197 * Similar to FCGI_JsonPair except for floating point values.
198 * @param key The key of the JSON entry
199 * @param value The value associated with the key
201 void FCGI_JSONDouble(const char *key, double value)
203 printf(",\r\n\t\"%s\" : %f", key, value);
207 * Similar to FCGI_JsonPair except for boolean values.
208 * @param key The key of the JSON entry
209 * @param value The value associated with the key
211 void FCGI_JSONBool(const char *key, bool value)
213 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
217 * Begins a JSON entry by writing the key. To be used in conjunction
218 * with FCGI_JsonValue.
219 * @param key The key of the JSON entry
221 void FCGI_JSONKey(const char *key)
223 printf(",\r\n\t\"%s\" : ", key);
227 * Should be used to write out the value of a JSON key. This has
228 * the same format as the printf functions. Care should be taken to format
229 * the output in valid JSON.
231 void FCGI_JSONValue(const char *format, ...)
234 va_start(list, format);
235 vprintf(format, list);
240 * Ends a JSON response that was initiated by FCGI_BeginJSON.
248 * To be used when the input parameters are invalid.
249 * Sends a response with HTTP status 400 Bad request, along with
250 * JSON data for debugging.
251 * @param context The context to work in
252 * @param params The parameters that the module handler received.
254 void FCGI_RejectJSON(FCGIContext *context)
256 printf("Status: 400 Bad Request\r\n");
258 FCGI_BeginJSON(context, STATUS_ERROR);
259 FCGI_JSONPair("description", "Invalid request");
260 FCGI_JSONLong("responsenumber", context->response_number);
261 FCGI_JSONPair("params", getenv("QUERY_STRING"));
262 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
263 FCGI_JSONPair("user", getenv("REMOTE_USER"));
264 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
269 * Main FCGI request loop that receives/responds to client requests.
270 * @param data Reserved.
271 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
272 * TODO: Get this to exit with the rest of the program!
274 void * FCGI_RequestLoop (void *data)
276 FCGIContext context = {0};
278 Log(LOGDEBUG, "First request...");
279 //TODO: The FCGI_Accept here is blocking.
280 // That means that if another thread terminates the program, this thread
281 // will not terminate until the next request is made.
282 while (FCGI_Accept() >= 0) {
284 if (Thread_Runstate() != RUNNING)
286 //TODO: Yeah... deal with this better :P
287 Log(LOGERR, "FIXME; FCGI gets request after other threads have finished.");
288 printf("Content-type: text/plain\r\n\r\n+++OUT OF CHEESE ERROR+++\n");
292 Log(LOGDEBUG, "Got request #%d", context.response_number);
293 ModuleHandler module_handler = NULL;
294 char module[BUFSIZ], params[BUFSIZ];
296 //strncpy doesn't zero-truncate properly
297 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
298 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
300 //Remove trailing slashes (if present) from module query
301 size_t lastchar = strlen(module) - 1;
302 if (lastchar > 0 && module[lastchar] == '/')
303 module[lastchar] = 0;
305 if (!*module || !strcmp("identify", module)) {
306 module_handler = IdentifyHandler;
307 } else if (!strcmp("control", module)) {
308 module_handler = Control_Handler;
309 } else if (!strcmp("sensors", module)) {
310 module_handler = Sensor_Handler;
313 context.current_module = module;
314 if (module_handler) {
315 module_handler(&context, params);
317 strncat(module, " (unhandled)", BUFSIZ);
318 FCGI_RejectJSON(&context);
320 context.response_number++;
322 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
325 Log(LOGDEBUG, "Thread exiting.");
326 Thread_QuitProgram(false);
327 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.