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>
15 #define LOGIN_TIMEOUT 180
19 /**The time of last valid logged-in user access*/
20 time_t login_timestamp;
23 /**The name of the current module**/
24 const char *current_module;
25 /**For debugging purposes?**/
30 * Handles user logins.
31 * @param context The context to work in
32 * @param params User specified parameters
34 static void LoginHandler(FCGIContext *context, char *params) {
35 const char *key, *value;
36 bool force = 0, end = 0;
38 while ((params = FCGI_KeyPair(params, &key, &value))) {
39 if (!strcmp(key, "force"))
41 else if (!strcmp(key, "end"))
46 *(context->login_key) = 0;
47 FCGI_BeginJSON(context, STATUS_OK);
52 time_t now = time(NULL);
53 if (force || !*(context->login_key) ||
54 (now - context->login_timestamp > LOGIN_TIMEOUT))
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("user", context->login_ip);
79 FCGI_JSONPair("time", buf);
85 * Given an FCGIContext, determines if the current user (as specified by
86 * the key) is authorized or not. If validated, the context login_timestamp is
88 * @param context The context to work in
89 * @param key The login key to be validated.
90 * @return TRUE if authorized, FALSE if not.
92 int FCGI_Authorized(FCGIContext *context, const char *key) {
93 time_t now = time(NULL);
94 int result = (now - context->login_timestamp) <= LOGIN_TIMEOUT &&
95 !strcmp(context->login_key, key);
97 context->login_timestamp = now; //Update the login_timestamp
103 * Extracts a key/value pair from a request string.
104 * Note that the input is modified by this function.
105 * @param in The string from which to extract the pair
106 * @param key A pointer to a variable to hold the key string
107 * @param value A pointer to a variable to hold the value string
108 * @return A pointer to the start of the next search location, or NULL if
109 * the EOL is reached.
111 char *FCGI_KeyPair(char *in, const char **key, const char **value)
114 if (!in || !*in) { //Invalid input or string is EOL
119 //Find either = or &, whichever comes first
120 if ((ptr = strpbrk(in, "=&"))) {
121 if (*ptr == '&') { //No value specified
125 //Stopped at an '=' sign
128 if ((ptr = strchr(ptr,'&'))) {
134 } else { //No value specified and no other pair
142 * Begins a response to the client in JSON format.
143 * @param context The context to work in.
144 * @param status_code The status code to be returned.
146 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
148 printf("Content-type: application/json; charset=utf-8\r\n\r\n");
150 printf("\t\"module\" : \"%s\"", context->current_module);
151 FCGI_JSONLong("status", status_code);
155 * Adds a key/value pair to a JSON response. The response must have already
156 * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
157 * @param key The key of the JSON entry
158 * ¶m value The value associated with the key.
160 void FCGI_JSONPair(const char *key, const char *value)
162 printf(",\r\n\t\"%s\" : \"%s\"", key, value);
166 * Similar to FCGI_JSONPair except for signed integer values.
167 * @param key The key of the JSON entry
168 * @param value The value associated with the key
170 void FCGI_JSONLong(const char *key, long value)
172 printf(",\r\n\t\"%s\" : %ld", key, value);
176 * Similar to FCGI_JsonPair except for floating point values.
177 * @param key The key of the JSON entry
178 * @param value The value associated with the key
180 void FCGI_JSONDouble(const char *key, double value)
182 printf(",\r\n\t\"%s\" : %f", key, value);
186 * Begins a JSON entry by writing the key. To be used in conjunction
187 * with FCGI_JsonValue.
188 * @param key The key of the JSON entry
190 void FCGI_JSONKey(const char *key)
192 printf(",\r\n\t\"%s\" : ", key);
196 * Should be used to write out the value of a JSON key. This has
197 * the same format as the printf functions. Care should be taken to format
198 * the output in valid JSON.
200 void FCGI_JSONValue(const char *format, ...)
203 va_start(list, format);
204 vprintf(format, list);
209 * Ends a JSON response that was initiated by FCGI_BeginJSON.
217 * To be used when the input parameters are invalid.
218 * Sends a response with HTTP status 400 Bad request, along with
219 * JSON data for debugging.
220 * @param context The context to work in
221 * @param params The parameters that the module handler received.
223 void FCGI_RejectJSON(FCGIContext *context, const char *params)
225 printf("Status: 400 Bad Request\r\n");
227 FCGI_BeginJSON(context, STATUS_ERROR);
228 FCGI_JSONPair("description", "Invalid request");
229 FCGI_JSONLong("responsenumber", context->response_number);
230 FCGI_JSONPair("params", params);
231 FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
232 FCGI_JSONPair("user", getenv("REMOTE_USER"));
233 FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
238 * Main FCGI request loop that receives/responds to client requests.
239 * @param data Reserved.
241 void FCGI_RequestLoop (void *data)
243 FCGIContext context = {0};
245 while (FCGI_Accept() >= 0) {
246 ModuleHandler module_handler = NULL;
247 char module[BUFSIZ], params[BUFSIZ];
249 //strncpy doesn't zero-truncate properly
250 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
251 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
253 //Remove trailing slashes (if present) from module query
254 size_t lastchar = strlen(module) - 1;
255 if (lastchar > 0 && module[lastchar] == '/')
256 module[lastchar] = 0;
259 if (!strcmp("sensors", module)) {
260 module_handler = Handler_Sensors;
261 } else if (!strcmp("login", module)) {
262 module_handler = LoginHandler;
263 } else if (!strcmp("actuators", module)) {
267 context.current_module = module;
268 if (module_handler) {
269 module_handler(&context, params);
271 strncat(module, " [unknown]", BUFSIZ);
272 FCGI_RejectJSON(&context, params);
275 context.response_number++;