-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_with_debug.cpp
315 lines (284 loc) · 7.18 KB
/
server_with_debug.cpp
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
/*
* Created by: Artem Golotin
* CS360
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <dirent.h>
#include <vector>
#include <queue>
using namespace std;
#define SOCKET_ERROR -1
#define SERVER_ERROR -1
#define MAX_MSG_SZ 1024
#define QUEUE_SIZE 100
#define OK "200 OK"
int hSocket,hServerSocket; /* handle to socket */
struct hostent* pHostInfo; /* holds info about a machine */
struct sockaddr_in Address; /* Internet socket address stuct */
int nAddressSize=sizeof(struct sockaddr_in);
char pBuffer[MAX_MSG_SZ];
int nHostPort;
int THREADS = 10;
string dir;
int error_counter;
sem_t e;
sem_t s;
sem_t n;
queue<int> work_load;
bool isWhitespace(char c)
{
switch (c)
{
case '\r':
case '\n':
case ' ':
case '\0':
return true;
default:
return false;
}
}
void chomp(char *line)
{
int len = strlen(line);
while (isWhitespace(line[len]))
line[len--] = '\0';
}
char* getLine(int hSocket)
{
char tline[MAX_MSG_SZ];
char* line;
int messagesize = 0;
int amtread = 0;
while ((amtread = read(hSocket, tline+messagesize, 1)) < MAX_MSG_SZ)
{
if (amtread > 0)
messagesize += amtread;
else
{
// perror("Socket Error is: ");
//fprintf(stderr, "Read failed on file descriptor %d messagesize = %d\n", hSocket, messagesize);
//exit(2);
error_counter++;
return NULL;
}
if (tline[messagesize-1] == '\n')
break;
}
tline[messagesize] = '\0';
chomp(tline);
line = (char *)malloc((strlen(tline)+1)*sizeof(char));
strcpy(line, tline);
return line;
}
void getHeaderLines(vector<string> &headerLines, int socket)
{
char* line = getLine(socket);
while (strlen(line) != 0)
{
headerLines.push_back(line);
line = getLine(socket);
}
}
string generalHeaderResponse(string status, string cont_type, string cont_len)
{
string response = "HTTP/1.1 " + status + "\r\n" +
"Content-Type: " + cont_type + "\r\n" +
"Content-Length: " + cont_len + "\r\n\r\n";
return response;
}
void sendResponse(int socket, string header, string filename, bool isfile)
{
strcpy(pBuffer, header.c_str());
send(socket, pBuffer, strlen(pBuffer), 0);
int buffer_len = 1;
if (isfile)
{
unsigned int file = open(filename.c_str(), O_RDONLY, S_IREAD);
while (buffer_len > 0)
{
buffer_len = read(file, pBuffer, MAX_MSG_SZ);
if (buffer_len > 0)
send(socket, pBuffer, buffer_len, 0);
}
}
else
{
strcpy(pBuffer, filename.c_str());
write(socket, pBuffer, strlen(pBuffer)+1);
}
}
string buildDirectoryHTML(vector<string> names)
{
string html = "<!DOCTYPE html>\n<html>\n\t<body>\n";
for (int i = 0; i < names.size(); i++)
html += "\t\t<a href=\"" + names[i] + "\">" + names[i] + "</a><br />\n";
html += "\t</body>\n</head>\n";
return html;
}
void* serve(void* thread_id)
{
while (work_load.size() != -1)
{
sem_wait(&n); // wait until there's a request
sem_wait(&s);
int socket = work_load.front();
work_load.pop();
vector<string> headerLines;
getHeaderLines(headerLines, socket);
struct stat filestat;
string tempfn = headerLines[0];
string filename = "";
for (int i = 0; i < tempfn.length(); i++)
{
if (i > 3)
{
if (isspace(tempfn[i]))
break;
else
filename += tempfn[i];
}
}
string temp = dir;
temp.append(filename);
filename = "." + temp;
if ((stat(filename.c_str(), &filestat) == -1)) /* Case 404 Not Found */
{
struct stat st;
stat("404.html", &st);
char size[256];
sprintf(size, "%d", st.st_size);
string header = generalHeaderResponse("404 Not Found", "text/html", size);
/* Sending the response */
sendResponse(socket, header, "404.html", true);
}
if (S_ISREG(filestat.st_mode)) /* Case 200 OK; file */
{
char size[256];
sprintf(size, "%d", filestat.st_size);
string header;
if (strstr(filename.c_str(), ".txt"))
header = generalHeaderResponse(OK, "text/plain", size);
else if (strstr(filename.c_str(), ".html"))
header = generalHeaderResponse(OK, "text/html", size);
else if (strstr(filename.c_str(), ".jpg"))
header = generalHeaderResponse(OK, "image/jpg", size);
else if (strstr(filename.c_str(), ".gif"))
header = generalHeaderResponse(OK, "image/gif", size);
/* Sending the response */
sendResponse(socket, header, filename, true);
}
if (S_ISDIR(filestat.st_mode)) /* Case 200 OK; directory */
{
DIR *dirp;
struct dirent *dp;
bool sent = false;
vector<string> dir_names;
string header;
dirp = opendir(filename.c_str());
while ((dp = readdir(dirp)) != NULL)
{
if (strstr(dp->d_name, "index.html"))
{
filename = filename + "/index.html";
struct stat st;
stat(filename.c_str(), &st);
char size[256];
sprintf(size, "%d", st.st_size);
header = generalHeaderResponse(OK, "text/html", size);
/* Sending the response */
sendResponse(socket, header, filename, true);
sent = true;
break;
}
else
dir_names.push_back(dp->d_name);
}
(void)closedir(dirp);
if (!sent)
{
string dirHTML = buildDirectoryHTML(dir_names);
char size[256];
sprintf(size, "%d", dirHTML.length());
header = generalHeaderResponse(OK, "text/html", size);
/* Sending the response */
sendResponse(socket, header, dirHTML, false);
}
}
close(socket);
sem_post(&s);
sem_post(&e);
}
}
int main(int argc, char* argv[])
{
// printf("Starting a server\n");
nHostPort = atoi(argv[1]);
THREADS = atoi(argv[2]);
dir = argv[3];
// printf("Making a socket\n");
hServerSocket = socket(AF_INET,SOCK_STREAM,0);
if (hServerSocket == SERVER_ERROR)
{
printf("\nERROR: Could not connect to host\n");
return 0;
}
Address.sin_addr.s_addr = INADDR_ANY;
Address.sin_port = htons(nHostPort);
Address.sin_family = AF_INET;
// printf("Binding to port %d\n", nHostPort);
if (bind(hServerSocket, (struct sockaddr*)&Address, sizeof(Address))
== SOCKET_ERROR)
{
printf("ERROR: Could not bind to port\n");
return 0;
}
getsockname(hServerSocket, (struct sockaddr*)&Address, (socklen_t*)&nAddressSize);
// printf("Making a listening queue of %d elements\n", QUEUE_SIZE);
if (listen(hServerSocket, QUEUE_SIZE) == SOCKET_ERROR)
{
printf("\nERROR: Could not create a listening queue\n");
return 0;
}
int optval = 1;
setsockopt(hServerSocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); // allows several requests on a port at the same time
/* Initializing threads */
sem_init(&s, 0, 1); // working semaphore
sem_init(&e, 0, 1000); // allowed connections
sem_init(&n, 0, 0); // thing that tells the thread to be able to work
pthread_t threads[THREADS];
for (int i = 0; i < THREADS; i++)
pthread_create(&threads[i], NULL, serve, &i);
/* End initializing threads */
/* Processing requests */
printf("The server is up and running\n");
for (;;)
{
hSocket = accept(hServerSocket, (struct sockaddr*)&Address, (socklen_t*)&nAddressSize);
if (hSocket < 0)
{
printf("ERROR: Could not accept connection\n");
}
else
{
sem_wait(&e);
sem_wait(&s);
work_load.push(hSocket);
sem_post(&s);
sem_post(&n);
}
}
close(hServerSocket);
}