-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.c
406 lines (357 loc) · 9.58 KB
/
socket.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <signal.h>
#include <fastdb.h>
// Server control functions
#define CONNMAX 1000
FILE *logFile;
static int listenfd, clients[CONNMAX];
static void error(char *);
static void startServer(const char *);
static void respond(int);
typedef struct
{
char *name, *value;
} header_t;
static header_t reqhdr[17] = {{"\0", "\0"}};
static int clientfd;
static char *buf;
void serve_forever(const char *PORT);
// Client request
char *method, // "GET" or "POST"
*uri, // "/index.html" things before '?'
*qs, // "a=1&b=2" things after '?'
*prot; // "HTTP/1.1"
char *payload; // for POST
int payload_size;
char *request_header(const char *name);
// user shall implement this function
char *filePath;
char rer[2048];
char *indPath;
void route();
// some interesting macro for `route()`
#define ROUTE_START() \
if (0) \
{
#define ROUTE(METHOD, URI) \
} \
else if (strcmp(URI, uri) == 0 && strcmp(METHOD, method) == 0) \
{
#define ROUTE_GET(URI) ROUTE("GET", URI)
#define ROUTE_POST(URI) ROUTE("POST", URI)
#define ROUTE_END(URI) \
ROUTE("END", URI) \
}
void route()
{
bool responded = false;
printf("HTTP/1.1 200 OK\r\n\r\n");
ROUTE_START()
ROUTE_GET("/")
{
char *prot = NULL;
char *tokenKey = NULL;
char *path = NULL;
char *content = NULL;
strtok(rer, "&");
prot = strtok(NULL, "&");
if (prot != NULL)
path = strtok(NULL, "&");
if (path != NULL)
tokenKey = strtok(NULL, "&");
if (tokenKey != NULL)
content = strtok(NULL, "&");
fprintf(stderr, "\nprot: %s\npath: %s\ncontent: %s\ntokenKey %s\n", prot, path, content, tokenKey);
if (true)
{
// if (isValidTokenKey(tokenKey))
if (prot != NULL)
{
if (strcmp(prot, "get") == 0)
{
char *args[4] = {"", filePath, "-read", path};
startDB(4, args);
responded = true;
}
else if (strcmp(prot, "write") == 0)
{
char *args[5] = {"", filePath, "-write", path, content};
startDB(5, args);
responded = true;
}
else if (strcmp(prot, "info") == 0)
{
char *args[4] = {"", filePath, "-info", path};
startDB(4, args);
responded = true;
}
else if (strcmp(prot, "delete") == 0)
{
char *args[4] = {"", filePath, "-delete", path};
startDB(4, args);
responded = true;
}
else if (strcmp(prot, "rename") == 0)
{
char *args[5] = {"", filePath, "-rename", path, content};
startDB(5, args);
responded = true;
}
else
{
}
}
}
/*else if (prot != NULL && strcmp(prot, "aus") == 0)
{
uint64_t key = loginUser(path, tokenKey);
fprintf(stderr, "%lli", (uint64_t)key);
char dat[256];
sprintf(dat, "%lli", key);
if (key != 1 && key != 0)
sendSucessResponse(dat);
else if (key == 0)
{
sendOtherErroResponse("Max Seq Key count reached!");
}
else
{
sendUnAuthResponse("Invalid loing credentials");
}
responded = true;
}
else if (prot != NULL && strcmp(prot, "reg") == 0)
{
int res = registerUser(path, tokenKey);
if (res == 0)
{
char dat[256];
sprintf(dat, "%lli", loginUser(path, tokenKey));
sendSucessResponse(dat);
}
else
{
sendUnAuthResponse("User already exist");
}
responded = true;
}*/
else if (prot != NULL)
sendUnAuthResponse("Invalid Seq Key");
}
ROUTE_POST("/")
{
printf("HTTP/1.1 200 OK\r\n\r\n");
}
ROUTE_END("/")
{
if (!responded)
{
char *path = rer;
for (int i = 0; i < strlen(path); i++)
{
if (path[i] == '/')
{
path += ++i;
break;
}
}
if (strlen(path) == 0)
{
path = "index.html";
}
wchar_t *buff = malloc(1024);
sprintf(buff, "%s/%s", indPath, path);
FILE *file = fopen(buff, "r");
if (file != NULL)
{
while (fgets(buff, 500, file) != NULL)
{
printf("%s", buff);
}
fclose(file);
}
free(buff);
}
}
}
void serve_forever(const char *PORT)
{
struct sockaddr_in clientaddr;
socklen_t addrlen;
char c;
int slot = 0;
printf(
"Server started %shttp://127.0.0.1:%s%s\n",
"\033[92m", PORT, "\033[0m");
// Setting all elements to -1: signifies there is no client connected
int i;
for (i = 0; i < CONNMAX; i++)
clients[i] = -1;
startServer(PORT);
// Ignore SIGCHLD to avoid zombie threads
signal(SIGCHLD, SIG_IGN);
// ACCEPT connections
int klr = 0;
time_t ts;
ts = time(NULL);
while (1)
{
addrlen = sizeof(clientaddr);
clients[slot] = accept(listenfd, (struct sockaddr *)&clientaddr, &addrlen);
if (clients[slot] < 0)
{
perror("accept() error");
}
else
{
if (fork() == 0)
{
respond(slot);
exit(0);
}
}
klr++;
for (int i = 0; i < CONNMAX; i++)
{
if (clients[i] == -1)
{
slot = i;
break;
}
if (i == CONNMAX - 1)
{
printf("meow");
for (int j = 0; j < CONNMAX; j++)
{
int clientfdr = clients[j];
shutdown(clientfdr, SHUT_RDWR);
close(clientfdr);
clients[j] = -1;
}
slot = 0;
break;
}
}
}
}
// start server
void startServer(const char *port)
{
struct addrinfo hints, *res, *p;
// getaddrinfo for host
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL, port, &hints, &res) != 0)
{
perror("getaddrinfo() error");
exit(1);
}
// socket and bind
for (p = res; p != NULL; p = p->ai_next)
{
int option = 1;
listenfd = socket(p->ai_family, p->ai_socktype, 0);
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
if (listenfd == -1)
continue;
if (bind(listenfd, p->ai_addr, p->ai_addrlen) == 0)
break;
}
if (p == NULL)
{
perror("socket() or bind()");
exit(1);
}
freeaddrinfo(res);
// listen for incoming connections
if (listen(listenfd, 1000000) != 0)
{
perror("listen() error");
exit(1);
}
}
// get request header
char *request_header(const char *name)
{
header_t *h = reqhdr;
while (h->name)
{
if (strcmp(h->name, name) == 0)
return h->value;
h++;
}
return NULL;
}
// client connection
void respond(int n)
{
int rcvd, fd, bytes_read;
char *ptr;
buf = malloc(65535);
rcvd = recv(clients[n], buf, 65535, 0);
if (rcvd < 0) // receive error
fprintf(logFile, ("recv() error\n"));
else if (rcvd == 0) // receive socket closed
fprintf(logFile, "Client disconnected upexpectedly.\n");
else // message received
{
buf[rcvd] = '\0';
method = strtok(buf, " \t\r\n");
uri = strtok(NULL, " \t");
strcpy(rer, uri);
prot = strtok(NULL, " \t\r\n");
// fprintf(logFile, "\x1b[32m + [%s] %s\x1b[0m\n", method, uri);
if (qs = strchr(uri, '?'))
{
*qs++ = '\0'; // split URI
}
else
{
qs = uri - 1; // use an empty string
}
// bind clientfd to stdout, making it easier to write
clientfd = clients[n];
dup2(clientfd, STDOUT_FILENO);
close(clientfd);
// call router
route();
// tidy up
fflush(stdout);
shutdown(STDOUT_FILENO, SHUT_WR);
close(STDOUT_FILENO);
}
free(buf);
// Closing SOCKET
shutdown(clientfd, SHUT_RDWR); // All further send and recieve operations are DISABLED...
close(clientfd);
clients[n] = -1;
}
int smain(int argc, char **argv)
{
if (argc > 1)
{
filePath = argv[1];
}
else
{
printf("DB file required\n");
return -1;
}
if (argc > 3)
{
indPath = argv[3];
}
serve_forever("9001");
}