-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.c
More file actions
348 lines (271 loc) · 10.3 KB
/
functions.c
File metadata and controls
348 lines (271 loc) · 10.3 KB
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
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <sys/time.h>
#include "functions.h"
extern int bytes, pages;
extern pthread_mutex_t mtx, statistics;
extern pthread_cond_t cond_nonempty;
extern pthread_cond_t cond_nonfull;
extern pool_t pool;
time_t start;
void initialize(pool_t *pool) {
pool->start = 0;
pool->end = -1;
pool->count = 0;
}
// Place fd in the pool
void place(pool_t *pool, int fd) {
pthread_mutex_lock(&mtx);
while (pool->count >= POOL_SIZE){
pthread_cond_wait(&cond_nonfull, &mtx);
}
pool->end = (pool->end + 1) % POOL_SIZE;
pool->fd[pool->end] = fd;
pool->count++;
pthread_mutex_unlock(&mtx);
}
// Get fd from the pool
int obtain(pool_t *pool) {
int fd = 0;
pthread_mutex_lock(&mtx);
while (pool->count <= 0){
pthread_cond_wait(&cond_nonempty, &mtx);
}
fd = pool->fd[pool->start];
pool->start = (pool->start + 1) % POOL_SIZE;
pool->count--;
pthread_mutex_unlock(&mtx);
return fd;
}
// Thread responsible for listening requests
void *producer(void *ptr) {
struct sockaddr_in myaddr;
int lsock, csock, serving_port;
serving_port = *((int *) ptr);
time (&start);
if((lsock = socket( AF_INET, SOCK_STREAM, 0)) < 0)
perror_exit("socket");
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(serving_port);
myaddr.sin_family = AF_INET;
// Resolve address already in use
if (setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &myaddr, sizeof(myaddr)) == -1) {
perror("setsockopt");
exit(1);
}
if(bind(lsock, (struct sockaddr *)&myaddr, sizeof(myaddr)))
perror_exit("bind");
if(listen(lsock, 5) != 0)
perror_exit("listen");
printf("Server is ready. Awaiting client connections on port %d\n", serving_port);
while(1){
if((csock = accept(lsock, NULL, NULL)) < 0)
perror_exit("accept");
place(&pool, csock);
pthread_cond_signal(&cond_nonempty);
}
close(csock);
}
// Get fds from the pool and serve them to the user
void *consumer(void *ptr) {
char temp[1000], *type, *requestPath, rootDir[100], header[1000], *payload = NULL, *packet = NULL;
int fd, bytesWrote, socketID, getRequest;
while (1){
pthread_cond_signal(&cond_nonfull);
socketID = obtain(&pool); // Pop a fd from the pool
printf("Consumer received a request\n");
if((getRequest = read(socketID, temp, 1000)) < 0) // Read request
perror_exit("Reading request");
if(getRequest == 0) // If the crawler has closed
continue;
type = strtok(temp, " "); // Save GET request
requestPath = strtok(NULL, " "); // Get the given file path
if(strcmp(type, "GET") != 0) // If it isn't a GET request
continue;
strcpy(rootDir, "./root_dir");
strcat(rootDir, requestPath); // Concatenate the path
if(fileExists(rootDir) == 1){ // File doesn't exist 404
sprintf(header,
"HTTP/1.1 404 Not Found\nDate: %s\nServer: myhttpd/1.0.0 (Ubuntu64)\nContent-Length: %d\nContent-Type: text/html\nConnection: Closed\n\n<html>The page you were looking for could not be found.</html>"
, getFormattedTime(), 62);
write(socketID, header, strlen(header));
}
else if (hasPermissions(rootDir) == 0) { // Forbidden 403
sprintf(header,
"HTTP/1.1 403 Forbidden\nDate: %s\nServer: myhttpd/1.0.0 (Ubuntu64)\nContent-Length: %d\nContent-Type: text/html\nConnection: Closed\n\n<html>These are not the droids you are looking for..or you are not allowed to access this page.</html>",
getFormattedTime(), 102);
write(socketID, header, strlen(header));
}
else { // OK to send
sprintf(header,
"HTTP/1.1 200 OK\nDate: %s\nServer: myhttpd/1.0.0 (Ubuntu64)\nContent-Length: %d\nContent-Type: text/html\nConnection: Closed\n\n",
getFormattedTime(), getFilesize(rootDir));
if((fd = open(rootDir, O_RDONLY)) < 0) // Open the file
perror_exit("open");
payload = (char *) malloc(sizeof(char) * getFilesize(rootDir)); // Allocate memory for the text
if((customRead(fd, payload, getFilesize(rootDir))) < 0) // Custom read function to read the entire doc
perror_exit("read");
packet = (char *) malloc(strlen(header) + strlen(payload) + 1); // Allocate memory for the header + payload
strcpy(packet, header);
strcat(packet, payload); // Header + payload
printf("Serving document\n");
bytesWrote = customWrite(socketID, packet, strlen(packet)); // Write to socket and save bytes for STATS
close(fd);
pthread_mutex_lock(&statistics); // Use mutexes
bytes += bytesWrote; // Update stats
pages++;
pthread_mutex_unlock(&statistics); // Release lock
}
close(socketID);
free(packet);
free(payload);
}
}
void *command(void *ptr){
char telbuf[20], *command, stats[200], runTime[100];
struct sockaddr_in myaddr;
int lsock, csock, command_port;
command_port = *((int *) ptr);
if((lsock = socket( AF_INET, SOCK_STREAM, 0)) < 0)
perror_exit("socket");
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(command_port);
myaddr.sin_family = AF_INET;
// Resolve address already in use
if (setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &myaddr, sizeof(myaddr)) == -1) {
perror("setsockopt");
exit(1);
}
if(bind(lsock, (struct sockaddr *)&myaddr, sizeof(myaddr)))
perror_exit("bind");
if(listen(lsock, 5) != 0)
perror_exit("listen");
printf("Waiting for commands on port %d\n", command_port);
while(1){
printf("Waiting for clients\n");
if((csock = accept(lsock, NULL, NULL)) < 0)
perror_exit("accept");
bzero(telbuf, strlen(telbuf));
if((read(csock, telbuf, 20)) < 0)
perror_exit("Reading request");
telbuf[20] = '\0'; // Append terminating character
command = strtok(telbuf, "\r\n"); // Remove chars appended by telnet
if (!strcmp(command, "STATS")){
bzero(stats, 200);
sprintf(stats, "Server up for %s, served %d pages, %d bytes\n", getRunTime(runTime, start), pages, bytes);
customWrite(csock, stats, strlen(stats));
}
else if (!strcmp(command, "SHUTDOWN")){
bzero(stats, 200);
sprintf(stats, "Server shutting down...\n");
customWrite(csock, stats, 25);
printf("Received shutdown command.\n");
close(csock);
exit(0);
}
else {
bzero(stats, 200);
sprintf(stats, "Invalid command\n");
customWrite(csock, stats, 17);
}
}
}
void perror_exit(char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
// Check if the file exists for 404
int fileExists(char *filename) {
struct stat buffer;
// printf("Searching for file\n");
if(stat(filename, &buffer) != 0)
return 1;
else
return 0;
}
// Check whether the server has permissions to access file for 403
int hasPermissions(char *filename) {
struct stat buffer;
// printf("Checking file permissions\n");
if(stat(filename, &buffer) != 0)
perror_exit("stat");
mode_t bits = buffer.st_mode;
if(bits & S_IRUSR){
// User doesn't have read privileges
return 1;
}
}
// Return file size or 0 if it doesn't exist
int getFilesize(char *filename) {
struct stat buffer;
if(stat(filename, &buffer) != 0) {
return 0;
}
return (int) buffer.st_size;
}
// Get timestamp for the header
char *getFormattedTime(void) {
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
static char timeStamp[200];
strftime(timeStamp, sizeof(timeStamp), "%a, %d %b %Y %H:%M:%S GMT", timeinfo);
return timeStamp;
}
// Read from socket and make sure we don't miss chunks
int customRead(int fd, char *payload, int remaining){
int received = 0, b = 0;
while (remaining > 0){
b = read(fd, payload + received, remaining); // Advance pointer by bytes read
if(b < 0)
perror_exit("customRead");
received += b;
remaining -= b;
}
return b;
}
// Write to socket taking care of packet loss
int customWrite(int fd, char *payload, int remaining) {
int sent = 0, b = 0;
while (remaining > 0){
b = write(fd, payload + sent, remaining); // Advance pointer by sent bytes
if(b < 0)
perror_exit("customWrite");
sent += b;
remaining -= b;
}
return b;
}
char *getRunTime(char *runTime, time_t start){
int min, sec, hr, n, ms;
time_t end;
double dif;
time (&end);
dif = difftime (end,start);
n = floor(dif);
if(dif>3600){ // If the server has been running for over an hour
min = n/60;
sec = n%60;
hr = min/60;
min = min%60;
ms = sec%60;
sprintf(runTime, "%.2d:%.2d:%.2d.%.2d", hr, min, sec, ms);
return runTime;
}
else{ // If the server has been running for under an hour
min = n/60;
sec = n%60;
ms = sec%60;
sprintf(runTime, "%.2d:%.2d.%.2d", min, sec, ms);
return runTime;
}
}