Update FastCGI code and restructure includes a bit
[matches/MCTX3420.git] / server / fastcgi.c
1 /**
2  * @file fastcgi.c
3  * @purpose 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 #include <time.h>
12
13 #include "common.h"
14 #include "fastcgi.h"
15 #include "sensor.h"
16 #include "log.h"
17
18 #define LOGIN_TIMEOUT 180
19
20 struct FCGIContext {
21         /**The time of last valid logged-in user access*/
22         time_t login_timestamp;
23         char login_key[41];
24         char login_ip[16];
25         /**The name of the current module**/
26         const char *current_module;
27         /**For debugging purposes?**/
28         int response_number;
29 };
30
31 /**
32  * Handles user logins.
33  * @param context The context to work in
34  * @param params User specified parameters
35  */
36 static void LoginHandler(FCGIContext *context, char *params) {
37         const char *key, *value;
38         bool force = 0, end = 0;
39
40         while ((params = FCGI_KeyPair(params, &key, &value))) {
41                 if (!strcmp(key, "force"))
42                         force = !force;
43                 else if (!strcmp(key, "end"))
44                         end = !end;
45         }
46
47         if (end) {
48                 *(context->login_key) = 0;
49                 FCGI_BeginJSON(context, STATUS_OK);
50                 FCGI_EndJSON();
51                 return;
52         }
53
54         time_t now = time(NULL);
55         if (force || !*(context->login_key) || 
56            (now - context->login_timestamp > LOGIN_TIMEOUT)) 
57         {
58                 SHA_CTX sha1ctx;
59                 unsigned char sha1[20];
60                 int i = rand();
61
62                 SHA1_Init(&sha1ctx);
63                 SHA1_Update(&sha1ctx, &now, sizeof(now));
64                 SHA1_Update(&sha1ctx, &i, sizeof(i));
65                 SHA1_Final(sha1, &sha1ctx);
66
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);
73                 FCGI_EndJSON();
74         } else {
75                 char buf[128];
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);
82                 FCGI_EndJSON();
83         }
84 }
85
86 /**
87  * Given an FCGIContext, determines if the current user (as specified by
88  * the key) is authorized or not. If validated, the context login_timestamp is
89  * updated.
90  * @param context The context to work in
91  * @param key The login key to be validated.
92  * @return TRUE if authorized, FALSE if not.
93  */
94 bool FCGI_Authorized(FCGIContext *context, const char *key) {
95         time_t now = time(NULL);
96         int result = (now - context->login_timestamp) <= LOGIN_TIMEOUT && 
97                                  !strcmp(context->login_key, key);
98         if (result) {
99                 context->login_timestamp = now; //Update the login_timestamp
100         }
101         return result;
102 }
103
104 /**
105  * Extracts a key/value pair from a request string.
106  * Note that the input is modified by this function.
107  * @param in The string from which to extract the pair
108  * @param key A pointer to a variable to hold the key string
109  * @param value A pointer to a variable to hold the value string
110  * @return A pointer to the start of the next search location, or NULL if
111  *         the EOL is reached.
112  */
113 char *FCGI_KeyPair(char *in, const char **key, const char **value)
114 {
115         char *ptr;
116         if (!in || !*in) { //Invalid input or string is EOL
117                 return NULL;
118         }
119
120         *key = in;
121         //Find either = or &, whichever comes first
122         if ((ptr = strpbrk(in, "=&"))) {
123                 if (*ptr == '&') { //No value specified
124                         *value = ptr;
125                         *ptr++ = 0;
126                 } else {
127                         //Stopped at an '=' sign
128                         *ptr++ = 0;
129                         *value = ptr;
130                         if ((ptr = strchr(ptr,'&'))) {
131                                 *ptr++ = 0;
132                         } else {
133                                 ptr = "";
134                         }
135                 }
136         } else { //No value specified and no other pair
137                 ptr = "";
138                 *value = ptr;
139         }
140         return ptr;
141 }
142
143 /**
144  * Begins a response to the client in JSON format.
145  * @param context The context to work in.
146  * @param status_code The status code to be returned.
147  */
148 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
149 {
150         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
151         printf("{\r\n");
152         printf("\t\"module\" : \"%s\"", context->current_module);
153         FCGI_JSONLong("status", status_code);
154 }
155
156 /**
157  * Adds a key/value pair to a JSON response. The response must have already
158  * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
159  * @param key The key of the JSON entry
160  * &param value The value associated with the key.
161  */
162 void FCGI_JSONPair(const char *key, const char *value)
163 {
164         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
165 }
166
167 /**
168  * Similar to FCGI_JSONPair except for signed integer values.
169  * @param key The key of the JSON entry
170  * @param value The value associated with the key
171  */
172 void FCGI_JSONLong(const char *key, long value)
173 {
174         printf(",\r\n\t\"%s\" : %ld", key, value);
175 }
176
177 /**
178  * Similar to FCGI_JsonPair except for floating point values.
179  * @param key The key of the JSON entry
180  * @param value The value associated with the key
181  */
182 void FCGI_JSONDouble(const char *key, double value)
183 {
184         printf(",\r\n\t\"%s\" : %f", key, value);
185 }
186
187 /**
188  * Begins a JSON entry by writing the key. To be used in conjunction
189  * with FCGI_JsonValue.
190  * @param key The key of the JSON entry
191  */
192 void FCGI_JSONKey(const char *key)
193 {
194         printf(",\r\n\t\"%s\" : ", key);
195 }
196
197 /**
198  * Should be used to write out the value of a JSON key. This has
199  * the same format as the printf functions. Care should be taken to format
200  * the output in valid JSON. 
201  */
202 void FCGI_JSONValue(const char *format, ...)
203 {
204         va_list list;
205         va_start(list, format);
206         vprintf(format, list);
207         va_end(list);
208 }
209
210 /**
211  * Ends a JSON response that was initiated by FCGI_BeginJSON.
212  */
213 void FCGI_EndJSON() 
214 {
215         printf("\r\n}\r\n");
216 }
217
218 /**
219  * To be used when the input parameters are invalid.
220  * Sends a response with HTTP status 400 Bad request, along with
221  * JSON data for debugging.
222  * @param context The context to work in
223  * @param params The parameters that the module handler received.
224  */
225 void FCGI_RejectJSON(FCGIContext *context)
226 {
227         printf("Status: 400 Bad Request\r\n");
228         
229         FCGI_BeginJSON(context, STATUS_ERROR);
230         FCGI_JSONPair("description", "Invalid request");
231         FCGI_JSONLong("responsenumber", context->response_number);
232         FCGI_JSONPair("params", getenv("DOCUMENT_URI_LOCAL"));
233         FCGI_JSONPair("host", getenv("SERVER_HOSTNAME"));
234         FCGI_JSONPair("user", getenv("REMOTE_USER"));
235         FCGI_JSONPair("ip", getenv("REMOTE_ADDR"));
236         FCGI_EndJSON();
237 }
238
239 /**
240  * Main FCGI request loop that receives/responds to client requests.
241  * @param data Reserved.
242  */ 
243 void FCGI_RequestLoop (void *data)
244 {
245         FCGIContext context = {0};
246         
247         while (FCGI_Accept() >= 0) {
248                 ModuleHandler module_handler = NULL;
249                 char module[BUFSIZ], params[BUFSIZ];
250                 
251                 //strncpy doesn't zero-truncate properly
252                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
253                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
254                 
255                 //Remove trailing slashes (if present) from module query
256                 size_t lastchar = strlen(module) - 1;
257                 if (lastchar > 0 && module[lastchar] == '/')
258                         module[lastchar] = 0;
259                 
260
261                 if (!strcmp("login", module)) {
262                         module_handler = LoginHandler;
263                 } else if (!strcmp("sensors", module)) {
264                         module_handler = Sensor_Handler;
265                 } else if (!strcmp("actuators", module)) {
266                         
267                 }
268
269                 context.current_module = module;
270                 if (module_handler) {
271                         module_handler(&context, params);
272                 } else {
273                         strncat(module, " [unknown]", BUFSIZ);
274                         FCGI_RejectJSON(&context);
275                 }
276                 
277                 context.response_number++;
278         }
279 }

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