This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsws_q5.cpp
82 lines (68 loc) · 2.05 KB
/
sws_q5.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
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <signal.h>
#include "utility.h"
#include "inet_socket.h"
#define BUF_SIZE 300
#define LISTEN_PORT "8080"
#define BACKLOG 5
int main(int argc, char *argv[])
{
if (argc < 2) {
errExit("invalid number of arguments");
return EXIT_FAILURE;
}
int listen_fd = inetListen(LISTEN_PORT, BACKLOG, NULL);
if (listen_fd == -1)
errExit("inetListen");
// Turn on non-blocking mode on the passive socket
int flags = fcntl(listen_fd, F_GETFL);
if (fcntl(listen_fd, F_SETFL, flags | O_NONBLOCK) == -1)
errExit("listen fd non block");
for (;; ) {
int client_fd = accept(listen_fd, NULL, NULL);
if (client_fd == -1 && errno != EWOULDBLOCK)
errExit("accept");
if (client_fd != -1) {
char buf[BUF_SIZE];
printf("Accept a new connection... \n");
int numRead = read(client_fd, buf, BUF_SIZE);
if (write(STDOUT_FILENO, buf, numRead) != numRead)
errExit("partial/failed write");
char *request = strtok(buf, " ");
request = strtok(NULL, " ");
char path[BUF_SIZE];
snprintf(path, BUF_SIZE, ".%s", request);
struct stat sb;
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
char path2[BUF_SIZE];
strcpy(path2, path);
snprintf(path, BUF_SIZE, "%s%s", argv[1], request);
printf("PATH = %s\n", path);
}
int fd = open(path, O_RDONLY);
if (fd < 0) {
char headers[BUF_SIZE];
ssize_t nbBytes = snprintf(headers, BUF_SIZE, "HTTP/1.x 404 NOT FOUND\r\n\r\n");
write(client_fd, headers, nbBytes);
} else {
struct stat stat_buf;
fstat(fd, &stat_buf);
char headers[BUF_SIZE];
ssize_t nbBytes = snprintf(headers, BUF_SIZE, "HTTP/1.x 200 OK\r\nContent-Type: text/html;\r\nContent-Length: %i\r\ncharset=UTF-8\r\n\r\n", stat_buf.st_size);
write(client_fd, headers, nbBytes);
sendfile(client_fd, fd, 0, stat_buf.st_size);
close(fd);
}
close(client_fd);
printf("Closed connection... \n");
}
}
close(listen_fd);
}