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>
22 /**The time period (in seconds) before the control key expires */
23 #define CONTROL_TIMEOUT 180
28 * Identifies build information and the current API version to the user.
29 * Also useful for testing that the API is running and identifying the
30 * sensors and actuators present.
31 * @param context The context to work in
32 * @param params User specified paramters: [actuators, sensors]
34 static void IdentifyHandler(FCGIContext *context, char *params) {
35 bool ident_sensors = false, ident_actuators = false;
39 FCGIValue values[2] = {{"sensors", &ident_sensors, FCGI_BOOL_T},
40 {"actuators", &ident_actuators, FCGI_BOOL_T}};
41 if (!FCGI_ParseRequest(context, params, values, 2))
44 FCGI_BeginJSON(context, STATUS_OK);
45 FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
46 FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
47 FCGI_JSONLong("api_version", API_VERSION);
49 //Sensor and actuator information
51 FCGI_JSONKey("sensors");
52 FCGI_JSONValue("{\n\t\t");
53 for (i = 0; i < NUMSENSORS; i++) {
55 FCGI_JSONValue(",\n\t\t");
57 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]);
59 FCGI_JSONValue("\n\t}");
61 if (ident_actuators) {
62 FCGI_JSONKey("actuators");
63 FCGI_JSONValue("{\n\t\t");
64 for (i = 0; i < NUMACTUATORS; i++) {
66 FCGI_JSONValue(",\n\t\t");
68 FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]);
70 FCGI_JSONValue("\n\t}");
76 * Gives the user a key that determines who has control over
77 * the system at any one time. The key can be forcibly generated, revoking
78 * any previous control keys. To be used in conjunction with HTTP
79 * basic authentication.
80 * This function will generate a JSON response that indicates success/failure.
81 * @param context The context to work in
82 * @param force Whether to force key generation or not.
84 void FCGI_LockControl(FCGIContext *context, bool force) {
85 time_t now = time(NULL);
86 bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
88 if (force || !*(context->control_key) || expired)
91 unsigned char sha1[20];
95 SHA1_Update(&sha1ctx, &now, sizeof(now));
96 SHA1_Update(&sha1ctx, &i, sizeof(i));
97 SHA1_Final(sha1, &sha1ctx);
99 context->control_timestamp = now;
100 for (i = 0; i < 20; i++)
101 sprintf(context->control_key + i * 2, "%02x", sha1[i]);
102 snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
107 * Given an FCGIContext, determines if the current user (as specified by
108 * the key) has control or not. If validated, the context control_timestamp is
110 * @param context The context to work in
111 * @param key The control key to be validated.
112 * @return TRUE if authorized, FALSE if not.
114 bool FCGI_HasControl(FCGIContext *context, const char *key) {
115 time_t now = time(NULL);
116 int result = (now - context->control_timestamp) <= CONTROL_TIMEOUT &&
117 key != NULL && !strcmp(context->control_key, key);
119 context->control_timestamp = now; //Update the control_timestamp
126 * Revokes the current control key, if present.
127 * @param context The context to work in
129 void FCGI_ReleaseControl(FCGIContext *context) {
130 *(context->control_key) = 0;
131 FCGI_BeginJSON(context, STATUS_OK);
137 * Extracts a key/value pair from a request string.
138 * Note that the input is modified by this function.
139 * @param in The string from which to extract the pair
140 * @param key A pointer to a variable to hold the key string
141 * @param value A pointer to a variable to hold the value string
142 * @return A pointer to the start of the next search location, or NULL if
143 * the EOL is reached.
145 char *FCGI_KeyPair(char *in, const char **key, const char **value)
148 if (!in || !*in) { //Invalid input or string is EOL
153 //Find either = or &, whichever comes first
154 if ((ptr = strpbrk(in, "=&"))) {
155 if (*ptr == '&') { //No value specified
159 //Stopped at an '=' sign
162 if ((ptr = strchr(ptr,'&'))) {
168 } else { //No value specified and no other pair
176 * Aids in parsing request parameters.
177 * Input: The expected keys along with their type and whether or not
179 * @param context The context to work in
180 * @param params The parameter string to be parsed
181 * @param values An array of FCGIValue's that specify expected keys
182 * @param count The number of elements in 'values'.
183 * @return true If the parameter string was parsed successfully, false otherwise.
184 * Modes of failure include: Invalid a parsing error on the value,
185 * an unknown key is specified,
186 * a key/value pair is specified more than once, or
187 * not all required keys were present.
188 * If this function returns false, it is guaranteed that FCGI_RejectJSON
189 * has already been called with the appropriate description message.
191 bool FCGI_ParseRequest(FCGIContext *context, char *params, FCGIValue values[], size_t count)
193 const char *key, *value;
194 char buf[BUFSIZ], *ptr;
197 while ((params = FCGI_KeyPair(params, &key, &value))) {
198 for (i = 0; i < count; i++) {
199 if (!strcmp(key, values[i].key)) {
200 FCGIValue *val = &values[i];
202 if (FCGI_RECEIVED(val->flags)) {
203 snprintf(buf, BUFSIZ, "Value already specified for '%s'.", key);
204 FCGI_RejectJSON(context, buf);
207 val->flags |= FCGI_PARAM_RECEIVED;
209 switch(FCGI_TYPE(val->flags)) {
211 if (!*value) //No value: Default true
212 *((bool*) val->value) = true;
214 *((bool*) val->value) = !!(strtol(value, &ptr, 10));
216 snprintf(buf, BUFSIZ, "Expected bool for '%s' but got '%s'", key, value);
217 FCGI_RejectJSON(context, buf);
222 case FCGI_INT_T: case FCGI_LONG_T: {
223 long parsed = strtol(value, &ptr, 10);
224 if (!*value || *ptr) {
225 snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
226 FCGI_RejectJSON(context, buf);
230 if (FCGI_TYPE(val->flags) == FCGI_INT_T)
231 *((int*) val->value) = (int) parsed;
233 *((long*) val->value) = parsed;
236 *((double*) val->value) = strtod(value, &ptr);
237 if (!*value || *ptr) {
238 snprintf(buf, BUFSIZ, "Expected float for '%s' but got '%s'", key, value);
239 FCGI_RejectJSON(context, buf);
244 *((const char**) val->value) = value;
247 Fatal("Invalid type %d given", FCGI_TYPE(val->flags));
249 break; //No need to search any more
253 snprintf(buf, BUFSIZ, "Unknown key '%s' specified", key);
254 FCGI_RejectJSON(context, buf);
259 //Check that required parameters are received
260 for (i = 0; i < count; i++) {
261 if (FCGI_IS_REQUIRED(values[i].flags) && !FCGI_RECEIVED(values[i].flags)) {
262 snprintf(buf, BUFSIZ, "Key '%s' required, but was not given.", values[i].key);
263 FCGI_RejectJSON(context, buf);
271 * Begins a response to the client in JSON format.
272 * @param context The context to work in.
273 * @param status_code The status code to be returned.
275 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
277 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
279 printf("\t\"module\" : \"%s\"", context->current_module);
280 FCGI_JSONLong("status", status_code);
281 //Time and running statistics
283 gettimeofday(&now, NULL);
284 FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
285 FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
286 FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
287 FCGI_JSONPair("control_state", Control_GetModeName());
291 * Adds a key/value pair to a JSON response. The response must have already
292 * been initiated by FCGI_BeginJSON. Special characters are not escaped.
293 * @param key The key of the JSON entry
294 * @param value The value associated with the key.
296 void FCGI_JSONPair(const char *key, const char *value)
298 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
302 * Similar to FCGI_JSONPair except for signed integer values.
303 * @param key The key of the JSON entry
304 * @param value The value associated with the key
306 void FCGI_JSONLong(const char *key, long value)
308 printf(",\r\n\t\"%s\" : %ld", key, value);
312 * Similar to FCGI_JsonPair except for floating point values.
313 * @param key The key of the JSON entry
314 * @param value The value associated with the key
316 void FCGI_JSONDouble(const char *key, double value)
318 printf(",\r\n\t\"%s\" : %f", key, value);
322 * Similar to FCGI_JsonPair except for boolean values.
323 * @param key The key of the JSON entry
324 * @param value The value associated with the key
326 void FCGI_JSONBool(const char *key, bool value)
328 printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
332 * Begins a JSON entry by writing the key. To be used in conjunction
333 * with FCGI_JsonValue.
334 * @param key The key of the JSON entry
336 void FCGI_JSONKey(const char *key)
338 printf(",\r\n\t\"%s\" : ", key);
342 * Ends a JSON response that was initiated by FCGI_BeginJSON.
350 * To be used when the input parameters are rejected. The return data
351 * will also have debugging information provided.
352 * @param context The context to work in
353 * @param status The status the return data should have.
354 * @param description A short description of why the input was rejected.
356 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
358 if (description == NULL)
359 description = "Unknown";
361 Log(LOGINFO, "%s: Rejected query with: %d: %s", context->current_module, status, description);
362 FCGI_BeginJSON(context, status);
363 FCGI_JSONPair("description", description);
364 FCGI_JSONLong("responsenumber", context->response_number);
365 //FCGI_JSONPair("params", getenv("QUERY_STRING"));
366 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
367 FCGI_JSONPair("user", getenv("REMOTE_USER"));
368 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
373 * Generates a response to the client as described by the format parameter and
374 * extra arguments (exactly like printf). To be used when none of the other
375 * predefined functions will work exactly as needed. Extra care should be taken
376 * to ensure the correctness of the output.
377 * @param format The format string
378 * @param ... Any extra arguments as required by the format string.
380 void FCGI_PrintRaw(const char *format, ...)
383 va_start(list, format);
384 vprintf(format, list);
393 void FCGI_WriteBinary(void * data, size_t size, size_t num_elem)
395 Log(LOGDEBUG,"Writing!");
396 fwrite(data, size, num_elem, stdout);
400 * Escapes a string so it can be used safely.
401 * Currently escapes to ensure the validity for use as a JSON string
402 * Does not support unicode specifiers in the form of \uXXXX.
403 * @param buf The string to be escaped
404 * @return The escaped string (return value == buf)
406 char *FCGI_EscapeText(char *buf)
409 length = strlen(buf);
411 //Escape special characters. Must count down to escape properly
412 for (i = length - 1; i >= 0; i--) {
413 if (buf[i] < 0x20) { //Control characters
415 } else if (buf[i] == '"') {
416 if (i-1 >= 0 && buf[i-1] == '\\')
420 } else if (buf[i] == '\\') {
421 if (i-1 >= 0 && buf[i-1] == '\'')
431 * Main FCGI request loop that receives/responds to client requests.
432 * @param data Reserved.
433 * @returns NULL (void* required for consistency with pthreads, although at the moment this runs in the main thread anyway)
434 * TODO: Get this to exit with the rest of the program!
436 void * FCGI_RequestLoop (void *data)
438 FCGIContext context = {0};
440 Log(LOGDEBUG, "Start loop");
441 while (FCGI_Accept() >= 0) {
443 ModuleHandler module_handler = NULL;
444 char module[BUFSIZ], params[BUFSIZ], cookie[BUFSIZ];
446 //strncpy doesn't zero-truncate properly
447 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
448 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
449 snprintf(cookie, BUFSIZ, "%s", getenv("COOKIE_STRING"));
451 Log(LOGDEBUG, "Got request #%d - Module %s, params %s", context.response_number, module, params);
452 Log(LOGDEBUG, "Cookie: %s", cookie);
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 //Escape all special characters
462 FCGI_EscapeText(params);
464 //Default to the 'identify' module if none specified
466 strcpy(module, "identify");
468 if (!strcmp("identify", module)) {
469 module_handler = IdentifyHandler;
470 } else if (!strcmp("control", module)) {
471 module_handler = Control_Handler;
472 } else if (!strcmp("sensors", module)) {
473 module_handler = Sensor_Handler;
474 } else if (!strcmp("actuators", module)) {
475 module_handler = Actuator_Handler;
476 } else if (!strcmp("image", module)) {
477 module_handler = Image_Handler;
478 } else if (!strcmp("pin", module)) {
479 module_handler = Pin_Handler; // *Debug only* pin test module
480 } else if (!strcmp("bind", module)) {
481 module_handler = Login_Handler;
482 } else if (!strcmp("unbind", module)) {
483 module_handler = Logout_Handler;
486 context.current_module = module;
487 context.response_number++;
493 if (module_handler != Login_Handler)
495 if (cookie[0] == '\0')
497 FCGI_RejectJSON(&context, "Please login.");
500 if (!FCGI_HasControl(&context, cookie))
502 FCGI_RejectJSON(&context, "Invalid control key.");
507 module_handler(&context, params);
511 FCGI_RejectJSON(&context, "Unhandled module");
518 Log(LOGDEBUG, "Thread exiting.");
519 // NOTE: Don't call pthread_exit, because this runs in the main thread. Just return.