-
Notifications
You must be signed in to change notification settings - Fork 158
/
https_server.c
408 lines (311 loc) · 10.8 KB
/
https_server.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
407
/*
* MIT License
*
* Copyright (c) 2018 Lewis Van Winkle
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "chap10.h"
const char *get_content_type(const char* path) {
const char *last_dot = strrchr(path, '.');
if (last_dot) {
if (strcmp(last_dot, ".css") == 0) return "text/css";
if (strcmp(last_dot, ".csv") == 0) return "text/csv";
if (strcmp(last_dot, ".gif") == 0) return "image/gif";
if (strcmp(last_dot, ".htm") == 0) return "text/html";
if (strcmp(last_dot, ".html") == 0) return "text/html";
if (strcmp(last_dot, ".ico") == 0) return "image/x-icon";
if (strcmp(last_dot, ".jpeg") == 0) return "image/jpeg";
if (strcmp(last_dot, ".jpg") == 0) return "image/jpeg";
if (strcmp(last_dot, ".js") == 0) return "application/javascript";
if (strcmp(last_dot, ".json") == 0) return "application/json";
if (strcmp(last_dot, ".png") == 0) return "image/png";
if (strcmp(last_dot, ".pdf") == 0) return "application/pdf";
if (strcmp(last_dot, ".svg") == 0) return "image/svg+xml";
if (strcmp(last_dot, ".txt") == 0) return "text/plain";
}
return "application/octet-stream";
}
SOCKET create_socket(const char* host, const char *port) {
printf("Configuring local address...\n");
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo *bind_address;
getaddrinfo(host, port, &hints, &bind_address);
printf("Creating socket...\n");
SOCKET socket_listen;
socket_listen = socket(bind_address->ai_family,
bind_address->ai_socktype, bind_address->ai_protocol);
if (!ISVALIDSOCKET(socket_listen)) {
fprintf(stderr, "socket() failed. (%d)\n", GETSOCKETERRNO());
exit(1);
}
printf("Binding socket to local address...\n");
if (bind(socket_listen,
bind_address->ai_addr, bind_address->ai_addrlen)) {
fprintf(stderr, "bind() failed. (%d)\n", GETSOCKETERRNO());
exit(1);
}
freeaddrinfo(bind_address);
printf("Listening...\n");
if (listen(socket_listen, 10) < 0) {
fprintf(stderr, "listen() failed. (%d)\n", GETSOCKETERRNO());
exit(1);
}
return socket_listen;
}
#define MAX_REQUEST_SIZE 2047
struct client_info {
socklen_t address_length;
struct sockaddr_storage address;
SOCKET socket;
SSL *ssl;
char request[MAX_REQUEST_SIZE + 1];
int received;
struct client_info *next;
};
static struct client_info *clients = 0;
struct client_info *get_client(SOCKET s) {
struct client_info *ci = clients;
while(ci) {
if (ci->socket == s)
break;
ci = ci->next;
}
if (ci) return ci;
struct client_info *n =
(struct client_info*) calloc(1, sizeof(struct client_info));
if (!n) {
fprintf(stderr, "Out of memory.\n");
exit(1);
}
n->address_length = sizeof(n->address);
n->next = clients;
clients = n;
return n;
}
void drop_client(struct client_info *client) {
SSL_shutdown(client->ssl);
CLOSESOCKET(client->socket);
SSL_free(client->ssl);
struct client_info **p = &clients;
while(*p) {
if (*p == client) {
*p = client->next;
free(client);
return;
}
p = &(*p)->next;
}
exit(1);
}
const char *get_client_address(struct client_info *ci) {
static char address_buffer[100];
getnameinfo((struct sockaddr*)&ci->address,
ci->address_length,
address_buffer, sizeof(address_buffer), 0, 0,
NI_NUMERICHOST);
return address_buffer;
}
fd_set wait_on_clients(SOCKET server) {
fd_set reads;
FD_ZERO(&reads);
FD_SET(server, &reads);
SOCKET max_socket = server;
struct client_info *ci = clients;
while(ci) {
FD_SET(ci->socket, &reads);
if (ci->socket > max_socket)
max_socket = ci->socket;
ci = ci->next;
}
if (select(max_socket+1, &reads, 0, 0, 0) < 0) {
fprintf(stderr, "select() failed. (%d)\n", GETSOCKETERRNO());
exit(1);
}
return reads;
}
void send_400(struct client_info *client) {
const char *c400 = "HTTP/1.1 400 Bad Request\r\n"
"Connection: close\r\n"
"Content-Length: 11\r\n\r\nBad Request";
SSL_write(client->ssl, c400, strlen(c400));
drop_client(client);
}
void send_404(struct client_info *client) {
const char *c404 = "HTTP/1.1 404 Not Found\r\n"
"Connection: close\r\n"
"Content-Length: 9\r\n\r\nNot Found";
SSL_write(client->ssl, c404, strlen(c404));
drop_client(client);
}
void serve_resource(struct client_info *client, const char *path) {
printf("serve_resource %s %s\n", get_client_address(client), path);
if (strcmp(path, "/") == 0) path = "/index.html";
if (strlen(path) > 100) {
send_400(client);
return;
}
if (strstr(path, "..")) {
send_404(client);
return;
}
char full_path[128];
sprintf(full_path, "../chap07/public%s", path);
#if defined(_WIN32)
char *p = full_path;
while (*p) {
if (*p == '/') *p = '\\';
++p;
}
#endif
FILE *fp = fopen(full_path, "rb");
if (!fp) {
send_404(client);
return;
}
fseek(fp, 0L, SEEK_END);
size_t cl = ftell(fp);
rewind(fp);
const char *ct = get_content_type(full_path);
#define BSIZE 1024
char buffer[BSIZE];
sprintf(buffer, "HTTP/1.1 200 OK\r\n");
SSL_write(client->ssl, buffer, strlen(buffer));
sprintf(buffer, "Connection: close\r\n");
SSL_write(client->ssl, buffer, strlen(buffer));
sprintf(buffer, "Content-Length: %u\r\n", cl);
SSL_write(client->ssl, buffer, strlen(buffer));
sprintf(buffer, "Content-Type: %s\r\n", ct);
SSL_write(client->ssl, buffer, strlen(buffer));
sprintf(buffer, "\r\n");
SSL_write(client->ssl, buffer, strlen(buffer));
int r = fread(buffer, 1, BSIZE, fp);
while (r) {
SSL_write(client->ssl, buffer, r);
r = fread(buffer, 1, BSIZE, fp);
}
fclose(fp);
drop_client(client);
}
int main() {
#if defined(_WIN32)
WSADATA d;
if (WSAStartup(MAKEWORD(2, 2), &d)) {
fprintf(stderr, "Failed to initialize.\n");
return 1;
}
#endif
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
if (!ctx) {
fprintf(stderr, "SSL_CTX_new() failed.\n");
return 1;
}
if (!SSL_CTX_use_certificate_file(ctx, "cert.pem" , SSL_FILETYPE_PEM)
|| !SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM)) {
fprintf(stderr, "SSL_CTX_use_certificate_file() failed.\n");
ERR_print_errors_fp(stderr);
return 1;
}
SOCKET server = create_socket(0, "8080");
while(1) {
fd_set reads;
reads = wait_on_clients(server);
if (FD_ISSET(server, &reads)) {
struct client_info *client = get_client(-1);
client->socket = accept(server,
(struct sockaddr*) &(client->address),
&(client->address_length));
if (!ISVALIDSOCKET(client->socket)) {
fprintf(stderr, "accept() failed. (%d)\n",
GETSOCKETERRNO());
return 1;
}
client->ssl = SSL_new(ctx);
if (!client->ssl) {
fprintf(stderr, "SSL_new() failed.\n");
return 1;
}
SSL_set_fd(client->ssl, client->socket);
if (SSL_accept(client->ssl) != 1) {
//SSL_get_error(client->ssl, SSL_accept(...));
ERR_print_errors_fp(stderr);
drop_client(client);
} else {
printf("New connection from %s.\n",
get_client_address(client));
printf ("SSL connection using %s\n",
SSL_get_cipher(client->ssl));
}
}
struct client_info *client = clients;
while(client) {
struct client_info *next = client->next;
if (FD_ISSET(client->socket, &reads)) {
if (MAX_REQUEST_SIZE == client->received) {
send_400(client);
client = next;
continue;
}
int r = SSL_read(client->ssl,
client->request + client->received,
MAX_REQUEST_SIZE - client->received);
if (r < 1) {
printf("Unexpected disconnect from %s.\n",
get_client_address(client));
drop_client(client);
} else {
client->received += r;
client->request[client->received] = 0;
char *q = strstr(client->request, "\r\n\r\n");
if (q) {
*q = 0;
if (strncmp("GET /", client->request, 5)) {
send_400(client);
} else {
char *path = client->request + 4;
char *end_path = strstr(path, " ");
if (!end_path) {
send_400(client);
} else {
*end_path = 0;
serve_resource(client, path);
}
}
} //if (q)
}
}
client = next;
}
} //while(1)
printf("\nClosing socket...\n");
CLOSESOCKET(server);
SSL_CTX_free(ctx);
#if defined(_WIN32)
WSACleanup();
#endif
printf("Finished.\n");
return 0;
}