-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.c
More file actions
221 lines (188 loc) · 6.29 KB
/
webserver.c
File metadata and controls
221 lines (188 loc) · 6.29 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
/*
* webserver.c - A concurrent TCP echo server using threads
* using C code template from httpechosrv.c (same dir)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* for fgets */
#include <strings.h> /* for bzero, bcopy */
#include <unistd.h> /* for read, write */
#include <sys/socket.h> /* for socket use */
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h> /* for open */
#include <sys/types.h> /* for open (UNIX)*/
#include <sys/stat.h> /* for open (UNIX)*/
#include <pthread.h>
#include <signal.h> /* to gracefully stop */
#include <limits.h>
#include <time.h> /* for time keeping */
#define MAXLINE 8192 /* max text line length */
#define MAXBUF 8192 /* max I/O buffer size */
#define LISTENQ 1024 /* second argument to listen() */
#define TYPELENGTH 7
#define WWW_SERVER_PATH "/www"
volatile sig_atomic_t done = 0;
int open_listenfd(int port);
void echo(int connfd);
void *thread(void *vargp);
void error500(char buf[MAXLINE], int connfd);
void term(int signum);
void server_res(int n);
char *getcwd(char *buf, size_t size);
char *file_types[TYPELENGTH] = {"html", "txt", "png", "gif", "jpg", "css", "js"};
char *content_types[TYPELENGTH] = {"text/html", "text/plain", "image/png", "image/gif",
"image/jpg", "text/css", "application/javascript"};
/*
* main driver
*/
int main(int argc, char **argv) {
int listenfd, *connfdp, port;
struct sockaddr_in clientaddr;
socklen_t clientlen;
pthread_t tid;
// check arguments
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
port = atoi(argv[1]);
// gracefully exit
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = term;
sigaction(SIGINT, &action, NULL);
printf("Graceful exit: escape character is 'Ctrl+C'.\n");
// continuous listening of server
listenfd = open_listenfd(port);
while (!done) {
connfdp = malloc(sizeof(int));
*connfdp = accept(listenfd, (struct sockaddr *)&clientaddr, &clientlen);
// printf("Connected to http://localhost:%i on socket %i\n", port, *connfdp);
pthread_create(&tid, NULL, thread, connfdp);
}
}
/*
* requests sent to server & server's response
*/
void server_res(int connfd) {
size_t n;
char buf[MAXLINE], httpmsg[MAXLINE], *http_request[3], *filetype;
int filedesc, socket_msg, filesize, filetype_index;
FILE file;
// set working directory
char cwd[MAXLINE];
getcwd(cwd, sizeof(cwd));
strcat(cwd, WWW_SERVER_PATH);
// receive message from socket
socket_msg = recv(connfd, httpmsg, MAXLINE, 0);
// idle response
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
if (socket_msg == 0) {
printf("Connection has idled at %s. Refresh page to continue.\n", asctime (timeinfo));
}
// connected
else if (socket_msg > 0) {
http_request[0] = strtok(httpmsg, " \t\n");
if (strncmp(http_request[0], "GET\0", 4) == 0) {
http_request[1] = strtok(NULL, " \t");
http_request[2] = strtok(NULL, " \t\n");
// default landing page/route, no file requested
if (strncmp(http_request[1], "/\0", 2) == 0)
http_request[1] = "/index.html";
// for specific files, get file type (extension)
char *ext = strrchr(http_request[1], '.');
if (!ext) filetype = "";
else filetype = ext + 1;
// make sure incoming file types are supported
for (int i = 0; i < TYPELENGTH; i++)
if (strcmp(file_types[i], filetype) == 0) {
filetype_index = i;
break;
}
// get directory of file, with request URI
strcpy(buf, cwd);
strcpy(&buf[strlen(cwd)], http_request[1]);
// system call, open file and read in descriptor
if ((filedesc = open(buf, 0)) != -1) {
// get content type for the header
char *content_type = malloc(100);
strcpy(content_type, "Content-Type:");
/* using filetype index for supported content type */
strcat(content_type, content_types[filetype_index]);
strcat(content_type, "\r\n");
// set content length for the header
filesize = lseek(filedesc, 0L, SEEK_END);
lseek(filedesc, 0L, SEEK_SET);
char filesize_string[20];
sprintf(filesize_string, "%d", filesize);
char *content_length = malloc(100);
strcpy(content_length, "Content-Length:");
strcat(content_length, filesize_string);
strcat(content_length, "\r\n");
// send response
send(connfd, "HTTP/1.1 200 Document Follows\r\n", 31, 0);
send(connfd, content_type, strlen(content_type), 0);
send(connfd, content_length, strlen(content_length), 0);
send(connfd, "Connection: Keep-alive\r\n\r\n", 26, 0);
// write based on buffer size limit
while ((n = read(filedesc, buf, MAXBUF)) > 0)
write(connfd, buf, n);
/** If any cases fail above, respond with Error 500 **/
} else error500(buf, connfd);
} else error500(buf, connfd);
} else error500(buf, connfd);
shutdown(connfd, 0);
close(connfd);
}
/* thread routine */
void *thread(void *vargp) {
int connfd = *((int *)vargp);
pthread_detach(pthread_self());
free(vargp);
server_res(connfd);
close(connfd);
return NULL;
}
/*
* open_listenfd - open and return a listening socket on port
* Returns -1 in case of failure
*/
int open_listenfd(int port) {
int listenfd, optval = 1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
/* Eliminates "Address already in use" error from bind. */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int)) < 0)
return -1;
/* listenfd will be an endpoint for all requests to port
on any IP address for this host */
bzero((char *)&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if (bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
/* Make it a listening socket ready to accept connection requests */
if (listen(listenfd, LISTENQ) < 0) {
perror("listenfd, listen fn\n");
return -1;
}
return listenfd;
} /* end open_listenfd */
/* Error 500 Internal Server Error handling */
void error500(char buf[MAXLINE], int connfd) {
strcpy(buf, "HTTP/1.1 500 Internal Server Error");
strcat(buf, "\n");
write(connfd, buf, strlen(buf));
}
/* Gracefully exit program (while loop) */
void term(int signum){
done = 1;
}