83c43c30e408277a3e688da5aedf98cd8a7e43a5
[matches/MCTX3420.git] / testing / web2io / webserver.c
1 /**
2  * @file webserver.c
3  * @purpose Test implementing a minimalistic webserver
4  * 
5  */
6
7 #define _POSIX_C_SOURCE 200809L // needed for some POSIX stuff to work
8
9 // --- Standard headers --- //
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h> // string helper functions
13 #include <ctype.h> // character types
14 #include <signal.h> // for signal handling
15
16 // --- Custom headers --- //
17 #include "log.h" // C functions to handle logging
18 #include "options.h" // Options structure
19 #include "network.h" // C functions to handle low level networking
20
21 // --- Variable definitions --- //
22 Options options; // declared in "options.h"
23
24 // --- Function definitions --- //
25
26 /**
27  * @funct ParseArguments
28  * @purpose Parse Arguments and setup the global options variable
29  * @param argc - Num args
30  * @param argv - Array of args
31  */
32 void ParseArguments(int argc, char ** argv)
33 {
34         options.program = argv[0];
35         options.verbosity = LOGDEBUG;
36         if (argc > 1)
37                 options.port = atoi(argv[1]); // Allow us change the port for testing (I keep getting "address in use" errors)
38         else
39                 options.port = 8080; // Using 8080 instead of 80 for now because to use 80 you have to run the program as root
40         options.sfd = -1;
41         options.bound_sfd = -1;
42         log_print(LOGDEBUG, "ParseArguments", "Called as %s with %d arguments.", options.program, argc);
43 }
44
45 /**
46  * @funct SignalHandler
47  * @purpose Handle signals
48  * @param sig - The signal
49  */
50 void SignalHandler(int sig)
51 {
52         // At the moment just always exit.
53         // Call `exit` so that Cleanup will be called to... clean up.
54         log_print(LOGWARN, "SignalHandler", "Got signal %d (%s). Exiting.", sig, strsignal(sig));
55         exit(sig);
56 }
57
58 /**
59  * @funct Cleanup
60  * @purpose Called when program exits
61  */
62 void Cleanup()
63 {
64         log_print(LOGDEBUG, "Cleanup", "Begin cleanup.");
65         if (options.sfd >= 0)
66         {
67                 Network_close(options.sfd); // close socket
68                 options.sfd = -1;
69         }
70         if (options.bound_sfd >= 0)
71         {
72                 Network_close(options.bound_sfd); // unbind
73                 options.bound_sfd = -1;
74         }
75         log_print(LOGDEBUG, "Cleanup", "Unbound from port %d successfully", options.port);
76         log_print(LOGDEBUG, "Cleanup", "Done.");
77
78 }
79
80
81 /**
82  * @funct Get
83  * @purpose Respond to a GET request
84  * @param request - The request string
85  * @param sfd - Socket to respond through
86  */
87 void Get(char * request, int sfd)
88 {
89         log_print(LOGDEBUG, "Get", "Got GET request: \"%s\"", request);
90
91         int i = 0;
92         while (!isspace(request[++i]) && request[i] != '\0'); //NOTE: Don't need to check first character
93         request[i] = '\0';
94
95         char response[BUFSIZ];
96         int len = 0;
97         // TODO: Magical low level interfacing stuff!
98         if (strcmp("/sensor", request) == 0) // dummy test
99         {
100                 len = sprintf(response, "SENSOR OFFLINE\n");
101         }
102         else
103         {
104                 FILE * f = fopen(request+1, "r");
105                 if (f == NULL)
106                 {
107                         log_print(LOGWARN, "Get", "File \"%s\" doesn't exist", request+1);
108                         len = sprintf(response, "You requested \"%s\" using GET\n", request);
109                 }
110                 else
111                 {
112                         while (fgets(response, sizeof(response), f) != NULL)
113                         {
114                                 write(sfd, response, strlen(response));
115                         }
116                 }
117         }
118         if (len > 0)
119                 write(sfd, response, len);
120 }
121
122 /**
123  * @funct Post
124  * @purpose Respond to a POST request
125  * @param request - The request string
126  * @param sfd - Socket to respond through
127  */
128 void Post(char * request, int sfd)
129 {
130         log_print(LOGDEBUG, "Post", "Got POST request: \"%s\"", request);
131         int i = 0;
132         while (!isspace(request[++i]) && request[i] != '\0'); //NOTE: Don't need to check first character
133         request[i] = '\0';
134
135         char response[BUFSIZ];
136         int len = 0;
137
138         // TODO: Magical low level interfacing stuff!
139
140
141         if (strcmp("/actuator", request) == 0) // dummy test
142         {
143                 len = sprintf(response, "ACTUATOR OFFLINE\n");
144         }
145         else
146         {       
147                 len = sprintf(response, "You requested \"%s\" using POST\n", request);
148         }
149         if (len > 0)
150                 write(sfd, response, len);
151
152 }
153
154 /**
155  * @funct main
156  * @purpose Main program
157  * @param argc - Num arguments
158  * @param argv - Argument string array
159  * @returns error code (0 for no error)
160  */
161
162 int main(int argc, char ** argv)
163 {
164         // Parse Arguments
165         ParseArguments(argc, argv);
166         // Set Cleanup to be called on program exit
167         atexit(Cleanup);
168
169         // Setup signal handlers
170         int signals_to_handle[] = {SIGTERM, SIGINT, SIGHUP, SIGPIPE};
171         for (int i = 0; i < sizeof(signals_to_handle)/sizeof(int); ++i)
172         {
173                 int s = signals_to_handle[i];
174                 if (signal(s, SignalHandler) == SIG_ERR)
175                         error("main", "Setting signal handler for %d (%s): %s", s, strsignal(s), strerror(errno));
176         }
177
178         // Bind to the port
179         options.bound_sfd = Network_server_bind(options.port, &(options.port));
180         log_print(LOGDEBUG, "main", "Bound to port %d succesfully", options.port);
181
182         while (true)
183         {
184                         // Listen for a client
185                         options.sfd = Network_server_listen(options.bound_sfd, NULL);
186                         
187                         log_print(LOGDEBUG, "main", "Connected to client");
188         
189                         char buffer[BUFSIZ]; //NOTE: Won't be able to respond to requests longer than BUFSIZ
190                         // read a request
191                         int len = read(options.sfd, buffer, sizeof(buffer));
192                         log_print(LOGDEBUG, "main", "Read %d characters. Buffer is \"%s\"", len, buffer);
193
194                         // Parse request
195                         for (int i = 0; i < sizeof(buffer) && buffer[i] != '\0'; ++i)
196                         {
197                                 // Look for "GET" or "POST" followed by a whitespace
198                                 if (isspace(buffer[i])) // whitespace
199                                 {
200                                         while (isspace(buffer[++i]) && buffer[i] != '\0'); // Skip whitespace
201                                         char * req = buffer+i; // set request string
202                                 
203                                         buffer[i-1] = '\0'; // terminate request type
204                                         while (buffer[++i] != '\n' && buffer[i] != '\0'); // find next newline
205                                         buffer[i-1] = '\0';
206                                         
207                                         if (strcmp("GET", buffer) == 0) // Compare with "GET"
208                                         {
209                                                 Get(req, options.sfd);
210                                         }
211                                         else if (strcmp("POST", buffer) == 0) // Compare with "POST"
212                                         {
213                                                 Post(req, options.sfd);
214                                         }
215                                         else // Unknown request
216                                         {
217                                                 log_print(LOGWARN, "main", "Unrecognised request type \"%s\" (request \"%s\")", buffer, req);
218                                                 char response[] = "Error: Unrecognised request\n";
219                                                 write(options.sfd, response, sizeof(response));
220                                         }
221                                         break;
222                                 }
223                         }
224
225                         // Close connection
226                         Network_close(options.sfd);
227                         Network_close(options.bound_sfd);
228                         options.sfd = -1;
229                         log_print(LOGDEBUG, "main", "Closed connection to client");
230                         break;
231         }
232
233
234         
235         
236         return 0;
237 }
238
239

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