-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
379 lines (338 loc) · 9.14 KB
/
server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include <string.h>
#include <netdb.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "server.h"
#ifndef COMMON_HEADERS
#define COMMON_HEADERS
#include "httpHeaderManager.h"
#include "httpStatusCodes.h"
#include "permissions.h"
#include "mimeTypeManager.h"
#include "messageHandler.h"
#endif
#define PATH_MAX 4096
void handle_childfork(int singal)
{
//TODO: wait and handle child exit
int status = -1;
int pid = waitpid(-1, &status, WNOHANG);
if (pid == -1)
{
//TODO: handle ERROR with errno etc
exit(EXIT_FAILURE);
}
if (WEXITSTATUS(status) == EXIT_SUCCESS)
{
//everything was ok
debug("Client exit ok!");
}
else
{
//print error message and kill everything
fprintf(stderr, "Client exit not ok!\n");
exit(EXIT_FAILURE);
}
}
/**
* @brief registers the SIGCHILD singal for this programm
*
*/
void registerWaitSignal()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa)); // initialize sa to 0
sa.sa_handler = handle_childfork;
sigaction(SIGCHLD, &sa, NULL);
}
/**
* @brief registers all the singals in this programm
*
*/
void signalRegistry()
{
registerWaitSignal();
}
/**
* @brief Prints the usage of this programm to stderr
*
*/
void usage(void)
{
fprintf(stderr, "Usage: %s [-p PORT] [-h]\n", PROGRAMNAME);
}
/**
* @brief Prings the usage of this programm to stderr and exits with EXIT_FAILURE
*
*/
void usageAndExit(void)
{
usage();
exit(EXIT_FAILURE);
}
/**
* @brief Checks if a given port is valid
*
* @param port the port to check if it is valid
* @return int whether the port was valid or not
*/
int validPort(char *port)
{
uintmax_t num = strtoumax(port, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
{
/* Could not convert. */
return 0;
}
// check if in valid range
if (num < 0 || num > 65535)
{
return 0;
}
return 1;
}
/**
* @brief Reads the arguments from the commandline
*
* @param argc the argument counter
* @param argv the argument vector
* @param args the container holding the arguments for further processing
*/
void readArguments(int argc, char *argv[], serverarguments_t *args)
{
int portFlag = 0;
int ch = -1;
while ((ch = getopt(argc, argv, "hp:")) != -1)
{
switch (ch)
{
case 'h':
// help message and exit with success
usage();
exit(EXIT_SUCCESS);
break;
case 'p':
if (portFlag == 1)
{
usageAndExit();
}
if (optarg == NULL)
{
//forgot the PORT NUMBER
usageAndExit();
}
args->port = optarg;
//check Port range
if (validPort(args->port) != 1)
{
fprintf(stderr, "./%s: The port %s you specified is not valid\n", PROGRAMNAME, args->port);
exit(EXIT_FAILURE);
}
break;
case '?':
default:
usageAndExit();
}
}
}
/**
* @brief Starts the server and registers the port on the system
*
* @param args the arguments of this programm
* @return int the servers filedescriptor
*/
int startServer(serverarguments_t *args)
{
struct addrinfo hints, *ai;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int res = getaddrinfo(NULL, args->port, &hints, &ai);
if (res != 0)
{
// error
fprintf(stderr, "./%s: Error while getaddrinfo: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
int sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (sockfd < 0)
{
// error
fprintf(stderr, "./%s: Error while socket generation: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
// allow to reuse the port
int optval = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) < 0)
{
// error
fprintf(stderr, "./%s: Error while setting socketoptions: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)
{
// error
fprintf(stderr, "./%s: Error while binding socket to port: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
if (listen(sockfd, DEFAULT_CLIENT_LISTEN_SIZE) < 0)
{
// error
fprintf(stderr, "./%s: Error while listening to port: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
freeaddrinfo(ai);
return sockfd;
}
char *readClientReqest(int clientFd, char *requestContent)
{
FILE *clientInput = fdopen(clientFd, "r");
char line[1024];
while ((fgets(line, sizeof(line), clientInput)) != 0)
{
int newLength = strlen(line) + strlen(requestContent) + 2;
requestContent = realloc(requestContent, newLength);
strcat(requestContent, line);
if (strcmp("\r\n", line) == 0)
{
//done
break;
}
}
return requestContent;
}
void processClientRequest(int clientFd)
{
// duplicate fd so its safe to close
int duplicatedClientSocket = dup(clientFd);
close(clientFd);
clientFd = duplicatedClientSocket;
// reading the content
char *requestContent = calloc(1024, sizeof(char));
requestContent = readClientReqest(clientFd, requestContent);
// parsing the header and storing into the header struct
httpheader_t requestHttpheader;
parseHttpHeader(requestContent, &requestHttpheader);
//fixing the relative path to the absolute
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL)
{
strcat(cwd, requestHttpheader.file);
requestHttpheader.file = cwd;
}
else
{
fprintf(stderr, "getcwd() error");
exit(EXIT_FAILURE);
}
// check if file exists and if the current running user has permission to access the file
permission_t permissionStatus = checkFileForPermissionAndExistence(&requestHttpheader);
if (permissionStatus == PERMISSION_DENIED)
{
//send permission denied message to client
debug("Client tried to access a file which the current running user has no read permission!");
sendNoPermissionMessage(clientFd);
free(requestContent);
return;
}
else if (permissionStatus == FILE_NOT_EXISTS)
{
//send FILE not exists message to client
debug("Client tried to access a file which does not exist!");
sendFileNotExistsMessage(clientFd);
free(requestContent);
return;
}
// file stats
struct stat fileInfo;
stat(requestHttpheader.file, &fileInfo);
// last modified timestamp
char *lastModTime = calloc(50, sizeof(char));
struct tm *info = gmtime(&fileInfo.st_mtime);
strftime(lastModTime, 50, "%c GMT", info);
// getting the mimetype
char *mimeType = getMimeTypFromFilename(requestHttpheader.file);
// generating the resposne header
httpheader_t responseHttpheader = getDefaultResponseHeader();
responseHttpheader.statuscode = 200;
responseHttpheader.content_length = fileInfo.st_size;
responseHttpheader.last_modified = lastModTime;
responseHttpheader.content_type = mimeType;
// sending the content to the client
sentFileContent(responseHttpheader, requestHttpheader.file, clientFd);
free(requestContent);
free(lastModTime);
fflush(stdout);
}
/**
* @brief Handles the incoming request of a client
*
* @param clientFd the clients filedescriptor
*/
void handleNewClient(int clientFd)
{
pid_t pid = fork();
switch (pid)
{
case -1:
fprintf(stderr, "Cannot fork!\n");
exit(EXIT_FAILURE);
case 0:
// child tasks ...
processClientRequest(clientFd);
exit(EXIT_SUCCESS);
break;
default:
// parent tasks ...
// nothing to do
// handle in sigaction
close(clientFd);
break;
}
}
/**
* @brief Waits for a client to send a request
*
* @param serverFd the servers filedescriptor to accept on
*/
void clientWaiting(int serverFd)
{
while (1)
{
int clientFd = accept(serverFd, NULL, NULL);
if (clientFd < 0)
{
if (errno == EINTR)
{
//TODO: check if it is really a sigchild
// maybe a SIGCHILD is incomming
// so catch it
continue;
}
// error
fprintf(stderr, "./%s: Error accepting new client: %s\n", PROGRAMNAME, strerror(errno));
exit(EXIT_FAILURE);
}
handleNewClient(clientFd);
}
}
int main(int argc, char *argv[])
{
signalRegistry();
serverarguments_t args = {
.port = DEFAULTPORT};
readArguments(argc, argv, &args);
int serverFd = startServer(&args);
clientWaiting(serverFd);
return EXIT_SUCCESS;
}