Merge branch 'master' of https://github.com/szmoore/MCTX3420.git
[matches/MCTX3420.git] / server / fastcgi.c
1 /**
2  * @file fastcgi.c
3  * @brief Runs the FCGI request loop to handle web interface requests.
4  *
5  * fcgi_stdio.h must be included before all else so the stdio function
6  * redirection works ok.
7  */
8
9 #include <fcgi_stdio.h>
10 #include <openssl/sha.h>
11
12 #include "common.h"
13 #include "sensor.h"
14 #include "control.h"
15 #include "options.h"
16
17 /**The time period (in seconds) before the control key expires @ */
18 #define CONTROL_TIMEOUT 180
19
20 /**Contextual information related to FCGI requests*/
21 struct FCGIContext {
22         /**The time of last valid user access possessing the control key*/
23         time_t control_timestamp;
24         char control_key[41];
25         char control_ip[16];
26         /**The name of the current module**/
27         const char *current_module;
28         /**For debugging purposes?**/
29         int response_number;
30 };
31
32 /**
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]
38  */ 
39 static void IdentifyHandler(FCGIContext *context, char *params) {
40         bool identSensors = false, identActuators = false;
41         const char *key, *value;
42         int i;
43
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;
49                 }
50         }
51
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);
56         if (identSensors) {
57                 FCGI_JSONKey("sensors");
58                 FCGI_JSONValue("{\n\t\t");
59                 for (i = 0; i < NUMSENSORS; i++) {
60                         if (i > 0) {
61                                 FCGI_JSONValue(",\n\t\t");
62                         }
63                         FCGI_JSONValue("\"%d\" : \"%s\"", i, g_sensor_names[i]); 
64                 }
65                 FCGI_JSONValue("\n\t}");
66         }
67         if (identActuators) {
68                 FCGI_JSONKey("actuators");
69                 FCGI_JSONValue("{\n\t\t");
70                 for (i = 0; i < NUMACTUATORS; i++) {
71                         if (i > 0) {
72                                 FCGI_JSONValue(",\n\t\t");
73                         }
74                         FCGI_JSONValue("\"%d\" : \"%s\"", i, g_actuator_names[i]); 
75                 }
76                 FCGI_JSONValue("\n\t}");
77         }
78         FCGI_EndJSON();
79 }
80
81 /**
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.
89  */ 
90 void FCGI_BeginControl(FCGIContext *context, bool force) {
91         time_t now = time(NULL);
92         bool expired = now - context->control_timestamp > CONTROL_TIMEOUT;
93         
94         if (force || !*(context->control_key) || expired) {
95                 SHA_CTX sha1ctx;
96                 unsigned char sha1[20];
97                 int i = rand();
98
99                 SHA1_Init(&sha1ctx);
100                 SHA1_Update(&sha1ctx, &now, sizeof(now));
101                 SHA1_Update(&sha1ctx, &i, sizeof(i));
102                 SHA1_Final(sha1, &sha1ctx);
103
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);
110                 FCGI_EndJSON();         
111         } else {
112                 char buf[128];
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);
119                 FCGI_EndJSON();
120         }
121 }
122
123 /**
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
126  * updated.
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.
130  */
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);
135         if (result) {
136                 context->control_timestamp = now; //Update the control_timestamp
137         }
138         return result;
139 }
140
141
142 /**
143  * Revokes the current control key, if present.
144  * @param context The context to work in
145  */
146 void FCGI_EndControl(FCGIContext *context) {
147         *(context->control_key) = 0;
148         FCGI_BeginJSON(context, STATUS_OK);
149         FCGI_EndJSON();
150         return;
151 }
152
153 /**
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.
161  */
162 char *FCGI_KeyPair(char *in, const char **key, const char **value)
163 {
164         char *ptr;
165         if (!in || !*in) { //Invalid input or string is EOL
166                 return NULL;
167         }
168
169         *key = in;
170         //Find either = or &, whichever comes first
171         if ((ptr = strpbrk(in, "=&"))) {
172                 if (*ptr == '&') { //No value specified
173                         *value = ptr;
174                         *ptr++ = 0;
175                 } else {
176                         //Stopped at an '=' sign
177                         *ptr++ = 0;
178                         *value = ptr;
179                         if ((ptr = strchr(ptr,'&'))) {
180                                 *ptr++ = 0;
181                         } else {
182                                 ptr = "";
183                         }
184                 }
185         } else { //No value specified and no other pair
186                 ptr = "";
187                 *value = ptr;
188         }
189         return ptr;
190 }
191
192 /**
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.
196  */
197 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
198 {
199         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
200         printf("{\r\n");
201         printf("\t\"module\" : \"%s\"", context->current_module);
202         FCGI_JSONLong("status", status_code);
203
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);
206         struct timeval now;
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);
212 }
213
214 /**
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.
219  */
220 void FCGI_JSONPair(const char *key, const char *value)
221 {
222         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
223 }
224
225 /**
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
229  */
230 void FCGI_JSONLong(const char *key, long value)
231 {
232         printf(",\r\n\t\"%s\" : %ld", key, value);
233 }
234
235 /**
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
239  */
240 void FCGI_JSONDouble(const char *key, double value)
241 {
242         printf(",\r\n\t\"%s\" : %f", key, value);
243 }
244
245 /**
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
249  */
250 void FCGI_JSONBool(const char *key, bool value)
251 {
252         printf(",\r\n\t\"%s\" : %s", key, value ? "true" : "false");
253 }
254
255 /**
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
259  */
260 void FCGI_JSONKey(const char *key)
261 {
262         printf(",\r\n\t\"%s\" : ", key);
263 }
264
265 /**
266  * Ends a JSON response that was initiated by FCGI_BeginJSON.
267  */
268 void FCGI_EndJSON() 
269 {
270         printf("\r\n}\r\n");
271 }
272
273 /**
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.
279  */
280 void FCGI_RejectJSONEx(FCGIContext *context, StatusCodes status, const char *description)
281 {
282         if (description == NULL)
283                 description = "Unknown";
284         
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"));
293         FCGI_EndJSON();
294 }
295
296 /**
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.
303  */
304 void FCGI_PrintRaw(const char *format, ...)
305 {
306         va_list list;
307         va_start(list, format);
308         vprintf(format, list);
309         va_end(list);
310 }
311
312 /**
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!
317  */ 
318 void * FCGI_RequestLoop (void *data)
319 {
320         FCGIContext context = {0};
321         
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) {
327
328                 if (Thread_Runstate() != RUNNING)
329                 {
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");
333                         break;
334                 }
335                 
336                 Log(LOGDEBUG, "Got request #%d", context.response_number);
337                 ModuleHandler module_handler = NULL;
338                 char module[BUFSIZ], params[BUFSIZ];
339                 
340                 //strncpy doesn't zero-truncate properly
341                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
342                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
343                 
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;
348
349                 //Default to the 'identify' module if none specified
350                 if (!*module) 
351                         strcpy(module, "identify");
352                 
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_Handler2;
359                 }
360
361                 context.current_module = module;
362                 if (module_handler) {
363                         module_handler(&context, params);
364                 } else {
365                         FCGI_RejectJSON(&context, "Unhandled module");
366                 }
367                 context.response_number++;
368
369                 Log(LOGDEBUG, "Waiting for request #%d", context.response_number);
370         }
371
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.
375         return NULL;
376 }

UCC git Repository :: git.ucc.asn.au