Nicen the rego form and add back the change password form
[matches/MCTX3420.git] / testing / fastcgi-approach / 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 "fastcgi.h"
12 #include "common.h"
13 #include <time.h>
14
15 #define LOGIN_TIMEOUT 180
16
17
18 struct FCGIContext {
19         /**The time of last valid logged-in user access*/
20         time_t login_timestamp;
21         char login_key[41];
22         char login_ip[16];
23         /**The name of the current module**/
24         const char *current_module;
25         /**For debugging purposes?**/
26         int response_number;
27 };
28
29 /**
30  * Handles user logins.
31  * @param context The context to work in
32  * @param params User specified parameters
33  */
34 static void LoginHandler(FCGIContext *context, char *params) {
35         const char *key, *value;
36         bool force = 0, end = 0;
37
38         while ((params = FCGI_KeyPair(params, &key, &value))) {
39                 if (!strcmp(key, "force"))
40                         force = !force;
41                 else if (!strcmp(key, "end"))
42                         end = !end;
43         }
44
45         if (end) {
46                 *(context->login_key) = 0;
47                 FCGI_BeginJSON(context, STATUS_OK);
48                 FCGI_EndJSON();
49                 return;
50         }
51
52         time_t now = time(NULL);
53         if (force || !*(context->login_key) || 
54            (now - context->login_timestamp > LOGIN_TIMEOUT)) 
55         {
56                 SHA_CTX sha1ctx;
57                 unsigned char sha1[20];
58                 int i = rand();
59
60                 SHA1_Init(&sha1ctx);
61                 SHA1_Update(&sha1ctx, &now, sizeof(now));
62                 SHA1_Update(&sha1ctx, &i, sizeof(i));
63                 SHA1_Final(sha1, &sha1ctx);
64
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);
71                 FCGI_EndJSON();
72         } else {
73                 char buf[128];
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);
80                 FCGI_EndJSON();
81         }
82 }
83
84 /**
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
87  * updated.
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.
91  */
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);
96         if (result) {
97                 context->login_timestamp = now; //Update the login_timestamp
98         }
99         return result;
100 }
101
102 /**
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.
110  */
111 char *FCGI_KeyPair(char *in, const char **key, const char **value)
112 {
113         char *ptr;
114         if (!in || !*in) { //Invalid input or string is EOL
115                 return NULL;
116         }
117
118         *key = in;
119         //Find either = or &, whichever comes first
120         if ((ptr = strpbrk(in, "=&"))) {
121                 if (*ptr == '&') { //No value specified
122                         *value = ptr;
123                         *ptr++ = 0;
124                 } else {
125                         //Stopped at an '=' sign
126                         *ptr++ = 0;
127                         *value = ptr;
128                         if ((ptr = strchr(ptr,'&'))) {
129                                 *ptr++ = 0;
130                         } else {
131                                 ptr = "";
132                         }
133                 }
134         } else { //No value specified and no other pair
135                 ptr = "";
136                 *value = ptr;
137         }
138         return ptr;
139 }
140
141 /**
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.
145  */
146 void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
147 {
148         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
149         printf("{\r\n");
150         printf("\t\"module\" : \"%s\"", context->current_module);
151         FCGI_JSONLong("status", status_code);
152 }
153
154 /**
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  * &param value The value associated with the key.
159  */
160 void FCGI_JSONPair(const char *key, const char *value)
161 {
162         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
163 }
164
165 /**
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
169  */
170 void FCGI_JSONLong(const char *key, long value)
171 {
172         printf(",\r\n\t\"%s\" : %ld", key, value);
173 }
174
175 /**
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
179  */
180 void FCGI_JSONDouble(const char *key, double value)
181 {
182         printf(",\r\n\t\"%s\" : %f", key, value);
183 }
184
185 /**
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
189  */
190 void FCGI_JSONKey(const char *key)
191 {
192         printf(",\r\n\t\"%s\" : ", key);
193 }
194
195 /**
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. 
199  */
200 void FCGI_JSONValue(const char *format, ...)
201 {
202         va_list list;
203         va_start(list, format);
204         vprintf(format, list);
205         va_end(list);
206 }
207
208 /**
209  * Ends a JSON response that was initiated by FCGI_BeginJSON.
210  */
211 void FCGI_EndJSON() 
212 {
213         printf("\r\n}\r\n");
214 }
215
216 /**
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.
222  */
223 void FCGI_RejectJSON(FCGIContext *context, const char *params)
224 {
225         printf("Status: 400 Bad Request\r\n");
226         
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"));
234         FCGI_EndJSON();
235 }
236
237 /**
238  * Main FCGI request loop that receives/responds to client requests.
239  * @param data Reserved.
240  */ 
241 void FCGI_RequestLoop (void *data)
242 {
243         FCGIContext context = {0};
244         
245         while (FCGI_Accept() >= 0) {
246                 ModuleHandler module_handler = NULL;
247                 char module[BUFSIZ], params[BUFSIZ];
248                 
249                 //strncpy doesn't zero-truncate properly
250                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
251                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
252                 
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;
257                 
258
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)) {
264                         
265                 }
266
267                 context.current_module = module;
268                 if (module_handler) {
269                         module_handler(&context, params);
270                 } else {
271                         strncat(module, " [unknown]", BUFSIZ);
272                         FCGI_RejectJSON(&context, params);
273                 }
274                 
275                 context.response_number++;
276         }
277 }

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