1 |
/* |
2 |
http-server-bad-body.c - HTTP server that outputs a bad body |
3 |
Copyright (C) 2008 siliconforks.com |
4 |
|
5 |
This program is free software; you can redistribute it and/or modify |
6 |
it under the terms of the GNU General Public License as published by |
7 |
the Free Software Foundation; either version 2 of the License, or |
8 |
(at your option) any later version. |
9 |
|
10 |
This program is distributed in the hope that it will be useful, |
11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 |
GNU General Public License for more details. |
14 |
|
15 |
You should have received a copy of the GNU General Public License along |
16 |
with this program; if not, write to the Free Software Foundation, Inc., |
17 |
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
18 |
*/ |
19 |
|
20 |
#include <assert.h> |
21 |
#include <string.h> |
22 |
|
23 |
#include <netinet/in.h> |
24 |
#include <sys/socket.h> |
25 |
#include <unistd.h> |
26 |
|
27 |
int main(void) { |
28 |
int s = socket(PF_INET, SOCK_STREAM, 0); |
29 |
assert(s > 0); |
30 |
|
31 |
int optval = 1; |
32 |
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *) &optval, sizeof(optval)); |
33 |
|
34 |
struct sockaddr_in a; |
35 |
a.sin_family = AF_INET; |
36 |
a.sin_port = htons(8000); |
37 |
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); |
38 |
int result = bind(s, (struct sockaddr *) &a, sizeof(a)); |
39 |
assert(result == 0); |
40 |
|
41 |
result = listen(s, 5); |
42 |
assert(result == 0); |
43 |
|
44 |
for (;;) { |
45 |
struct sockaddr_in client_address; |
46 |
size_t size = sizeof(client_address); |
47 |
int client_socket = accept(s, (struct sockaddr *) &client_address, &size); |
48 |
assert(client_socket > 0); |
49 |
|
50 |
/* read request */ |
51 |
int state = 0; |
52 |
while (state != 2) { |
53 |
uint8_t buffer[8192]; |
54 |
ssize_t bytes_read = recv(client_socket, buffer, 8192, 0); |
55 |
assert(bytes_read > 0); |
56 |
for (int i = 0; i < bytes_read && state != 2; i++) { |
57 |
uint8_t byte = buffer[i]; |
58 |
switch (state) { |
59 |
case 0: |
60 |
if (byte == '\n') { |
61 |
state = 1; |
62 |
} |
63 |
else { |
64 |
state = 0; |
65 |
} |
66 |
break; |
67 |
case 1: |
68 |
if (byte == '\n') { |
69 |
state = 2; |
70 |
} |
71 |
else if (byte == '\r') { |
72 |
state = 1; |
73 |
} |
74 |
else { |
75 |
state = 0; |
76 |
} |
77 |
} |
78 |
} |
79 |
} |
80 |
|
81 |
/* send response */ |
82 |
char * message = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-type: text/html\r\nTransfer-Encoding: chunked\r\n\r\nHello\n"; |
83 |
size_t message_length = strlen(message); |
84 |
ssize_t bytes_sent = send(client_socket, message, message_length, 0); |
85 |
assert(bytes_sent == message_length); |
86 |
|
87 |
close(client_socket); |
88 |
} |
89 |
return 0; |
90 |
} |