Put FastCGI code into server framework
[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 "fastcgi.h"
12 #include "common.h"
13 #include "sensor.h"
14 #include "log.h"
15 #include <time.h>
16
17 static void LoginHandler(void *data, char *params) {
18         static char loginkey[41] = {0}, ip[256];
19         static time_t timestamp = 0;
20         const char *key, *value;
21         int force = 0, end = 0;
22
23         while ((params = FCGI_KeyPair(params, &key, &value))) {
24                 if (!strcmp(key, "force"))
25                         force = !force;
26                 else if (!strcmp(key, "end"))
27                         end = !end;
28         }
29
30         if (end) {
31                 *loginkey = 0;
32                 FCGI_BeginJSON(200, "login");
33                 FCGI_EndJSON();
34                 return;
35         }
36
37         time_t now = time(NULL);
38         if (force || !*loginkey || (now - timestamp > 180)) {
39                 SHA_CTX sha1ctx;
40                 unsigned char sha1[20];
41                 int i = rand();
42
43                 SHA1_Init(&sha1ctx);
44                 SHA1_Update(&sha1ctx, &now, sizeof(now));
45                 SHA1_Update(&sha1ctx, &i, sizeof(i));
46                 SHA1_Final(sha1, &sha1ctx);
47
48                 timestamp = now;
49                 for (i = 0; i < 20; i++)
50                         sprintf(loginkey+i*2, "%02x", sha1[i]);
51                 sprintf(ip, "%s", getenv("REMOTE_ADDR"));
52                 FCGI_BeginJSON(200, "login");
53                 FCGI_BuildJSON("key", loginkey);
54                 FCGI_EndJSON();
55         } else {
56                 char buf[128];
57                 strftime(buf, 128, "%H:%M:%S %d-%m-%Y",localtime(&timestamp)); 
58                 FCGI_BeginJSON(401, "login");
59                 FCGI_BuildJSON("description", "Already logged in");
60                 FCGI_BuildJSON("user", ip); 
61                 FCGI_BuildJSON("time", buf);
62                 FCGI_EndJSON();
63         }
64 }
65
66 /**
67  * Handle a request to the sensor module
68  * @param data - Data to pass to module (?)
69  * @param params - Parameters passed
70  */
71 static void SensorHandler(void * data, char * params)
72 {
73         static DataPoint buffer[SENSOR_QUERYBUFSIZ];
74         StatusCodes status = STATUS_OK;
75         const char * key; const char * value;
76
77         int sensor_id = SENSOR_NONE;
78
79         do
80         {
81                 params = FCGI_KeyPair(params, &key, &value);
82                 Log(LOGDEBUG, "Got key=%s and value=%s", key, value);
83                 if (strcmp(key, "id") == 0)
84                 {
85                         if (sensor_id != SENSOR_NONE)
86                         {
87                                 Log(LOGERR, "Only one sensor id should be specified");
88                                 status = STATUS_BADREQUEST;
89                                 break;
90                         }
91                         //TODO: Use human readable sensor identifier string for API?
92                         sensor_id = atoi(value);
93                         if (sensor_id == 0 && strcmp(value, "0") != 0)
94                         {
95                                 Log(LOGERR, "Sensor id not an integer; %s", value);
96                                 status = STATUS_BADREQUEST;
97                                 break;
98                         }
99                 }
100                 else
101                 {
102                         Log(LOGERR, "Unknown key \"%s\" (value = %s)", key, value);
103                         status = STATUS_BADREQUEST;
104                         break;
105                 }               
106         }
107         while (params != NULL && *params != '\0');
108         
109         if (sensor_id == SENSOR_NONE)
110         {
111                 Log(LOGERR, "No sensor id specified");
112                 status = STATUS_BADREQUEST;
113         }
114         if (sensor_id >= NUMSENSORS || sensor_id < 0)
115         {
116                 Log(LOGERR, "Invalid sensor id %d", sensor_id);
117                 status = STATUS_BADREQUEST;
118         }
119
120         FCGI_BeginJSON(status, "sensor");
121         
122         if (status != STATUS_BADREQUEST)
123         {
124                 FCGI_BuildJSON(key, value); // should spit back sensor ID
125                 //Log(LOGDEBUG, "Call Sensor_Query...");
126                 int amount_read = Sensor_Query(&(g_sensors[sensor_id]), buffer, SENSOR_QUERYBUFSIZ);
127                 //Log(LOGDEBUG, "Read %d DataPoints", amount_read);
128                 //Log(LOGDEBUG, "Produce JSON response");
129                 printf(",\r\n\t\"data\" : [");
130                 for (int i = 0; i < amount_read; ++i)
131                 {
132                         printf("[%f,%f]", buffer[i].time, buffer[i].value);
133                         if (i+1 < amount_read)
134                                 printf(",");
135                 }
136                 printf("]");
137                 //Log(LOGDEBUG, "Done producing JSON response");
138         }
139         FCGI_EndJSON();         
140         
141 }
142
143 /**
144  * Extracts a key/value pair from a request string.
145  * Note that the input is modified by this function.
146  * @param in The string from which to extract the pair
147  * @param key A pointer to a variable to hold the key string
148  * @param value A pointer to a variable to hold the value string
149  * @return A pointer to the start of the next search location, or NULL if
150  *         the EOL is reached.
151  */
152 char *FCGI_KeyPair(char *in, const char **key, const char **value)
153 {
154         char *ptr;
155         if (!in || !*in) { //Invalid input or string is EOL
156                 return NULL;
157         }
158
159         *key = in;
160         //Find either = or &, whichever comes first
161         if ((ptr = strpbrk(in, "=&"))) {
162                 if (*ptr == '&') { //No value specified
163                         *value = ptr;
164                         *ptr++ = 0;
165                 } else {
166                         //Stopped at an '=' sign
167                         *ptr++ = 0;
168                         *value = ptr;
169                         if ((ptr = strchr(ptr,'&'))) {
170                                 *ptr++ = 0;
171                         } else {
172                                 ptr = "";
173                         }
174                 }
175         } else { //No value specified and no other pair
176                 ptr = "";
177                 *value = ptr;
178         }
179         return ptr;
180 }
181
182 /**
183  * Begins a response to the client in JSON format.
184  * @param status_code The HTTP status code to be returned.
185  * @param module The name of the module that initiated the response.
186  */
187 void FCGI_BeginJSON(StatusCodes status_code, const char *module)
188 {
189         switch (status_code) {
190                 case STATUS_OK:
191                         break;
192                 case STATUS_UNAUTHORIZED:
193                         printf("Status: 401 Unauthorized\r\n");
194                         break;
195                 default:
196                         printf("Status: 400 Bad Request\r\n");
197         }
198         printf("Content-type: application/json; charset=utf-8\r\n\r\n");
199         printf("{\r\n");
200         printf("\t\"module\" : \"%s\"", module);
201 }
202
203 /**
204  * Adds a key/value pair to a JSON response. The response must have already
205  * been initiated by FCGI_BeginJSON. Note that characters are not escaped.
206  * @param key The key of the JSON entry
207  * &param value The value associated with the key.
208  */
209 void FCGI_BuildJSON(const char *key, const char *value)
210 {
211         printf(",\r\n\t\"%s\" : \"%s\"", key, value);
212 }
213
214 /**
215  * Ends a JSON response that was initiated by FCGI_BeginJSON.
216  */
217 void FCGI_EndJSON() 
218 {
219         printf("\r\n}\r\n");
220 }
221
222 /**
223  * Main FCGI request loop that receives/responds to client requests.
224  * @param data A data field to be passed to the selected module handler.
225  */ 
226 void FCGI_RequestLoop (void * data)
227 {
228         int count = 0;
229         while (FCGI_Accept() >= 0)   {
230                 ModuleHandler module_handler = NULL;
231                 char module[BUFSIZ], params[BUFSIZ];
232
233                 //strncpy doesn't zero-truncate properly
234                 snprintf(module, BUFSIZ, "%s", getenv("DOCUMENT_URI_LOCAL"));
235                 snprintf(params, BUFSIZ, "%s", getenv("QUERY_STRING"));
236                 
237                 //Remove trailing slashes (if present) from module query
238                 size_t lastchar = strlen(module) - 1;
239                 if (lastchar > 0 && module[lastchar] == '/')
240                         module[lastchar] = 0;
241                 
242
243                 if (!strcmp("sensors", module)) {
244                         module_handler = SensorHandler;
245                 } else if (!strcmp("login", module)) {
246                         module_handler = LoginHandler;
247                 } else if (!strcmp("actuators", module)) {
248                         
249                 }
250
251                 if (module_handler) {
252                         module_handler(data, params);
253                 } else {
254                         char buf[BUFSIZ];
255                         
256                         FCGI_BeginJSON(400, module);
257                         FCGI_BuildJSON("description", "400 Invalid response");
258                         snprintf(buf, BUFSIZ, "%d", count);
259                         FCGI_BuildJSON("request-number", buf);
260                         FCGI_BuildJSON("params", params);
261                         FCGI_BuildJSON("host", getenv("SERVER_HOSTNAME"));
262                         FCGI_BuildJSON("user", getenv("REMOTE_USER"));
263                         FCGI_BuildJSON("userip", getenv("REMOTE_ADDR"));
264                         FCGI_EndJSON();
265                 }
266
267                 count++;
268         }
269 }

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