]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/connection.c
src/connection.c: Add missing close() in handle_connection().
[tlsproxy/tlsproxy.git] / src / connection.c
1 /*
2  * Handle connections.
3  *
4  * Copyright (C) 2011  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "tlsproxy.h"
21 #include "connection.h"
22
23 /* close() */
24 #include <unistd.h>
25 /* getaddrinfo() */
26 #include <netdb.h>
27 /* poll() */
28 #include <poll.h>
29
30
31 /* Maximum line of a HTTP request line. Longer request lines are aborted with
32  * an error. The standard doesn't specify a maximum line length but this
33  * should be a good limit to make processing simpler. */
34 #define MAX_REQUEST_LINE 4096
35
36
37 static int read_http_request(FILE *client_fd, char *request, size_t length);
38 static void send_close_bad_request(FILE *client_fd);
39 static void send_close_forwarding_failure(FILE *client_fd);
40
41 static void transfer_data(int client, int server);
42 static int read_from_write_to(int from, int to);
43
44 static int connect_to_host(const char *hostname, const char *port);
45
46 static int parse_request(const char *buffer, char *host, char *port,
47                                              int *version_minor);
48
49
50 void handle_connection(int client_socket) {
51     int server_socket;
52     FILE *client_fd, *server_fd;
53
54     char buffer[MAX_REQUEST_LINE];
55     char host[MAX_REQUEST_LINE];
56     char port[5 + 1];
57
58     int version_minor;
59     int result;
60
61     client_fd = fdopen(client_socket, "a+");
62     if (NULL == client_fd) {
63         perror("fdopen()");
64         close(client_socket);
65         return;
66     }
67
68 #ifdef DEBUG
69     printf("New connection:\n");
70 #endif
71
72     /* Read request line (CONNECT ..) and headers (they are discarded). */
73     result = read_http_request(client_fd, buffer, sizeof(buffer));
74     if (-1 == result) {
75         /* Read error, client_fd already closed. */
76         return;
77     } else if (-2 == result) {
78         /* EOF */
79         send_close_bad_request(client_fd);
80         return;
81     }
82
83 #ifdef DEBUG
84     printf("  request: %s", buffer);
85 #endif
86
87     if (0 != parse_request(buffer, host, port, &version_minor)) {
88         send_close_bad_request(client_fd);
89 #ifdef DEBUG
90         printf("  bad request\n");
91 #endif
92         return;
93     }
94
95 #ifdef DEBUG
96     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
97 #endif
98
99     /* Connect to proxy server or directly to server. */
100     if (NULL != use_proxy_host && NULL != use_proxy_port) {
101         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
102     } else {
103         server_socket = connect_to_host(host, port);
104     }
105
106     if (-1 == server_socket) {
107         send_close_forwarding_failure(client_fd);
108         return;
109     }
110     server_fd = fdopen(server_socket, "a+");
111     if (NULL == server_fd) {
112         send_close_forwarding_failure(client_fd);
113         close(server_socket);
114         return;
115     }
116
117     /* Connect to proxy if requested (command line option). */
118     if (NULL != use_proxy_host && NULL != use_proxy_port) {
119         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
120         fprintf(server_fd, "\r\n");
121
122         /* Read response line from proxy server. */
123         result = read_http_request(server_fd, buffer, sizeof(buffer));
124         if (-1 == result) {
125             /* Read error, server_fd already closed. */
126             send_close_forwarding_failure(client_fd);
127             return;
128         } else if (-2 == result) {
129             /* EOF */
130             fclose(server_fd);
131             send_close_forwarding_failure(client_fd);
132             return;
133         }
134
135         /* Check response of proxy server. */
136         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
137 #ifdef DEBUG
138             printf("  bad proxy response\n");
139 #endif
140             fclose(server_fd);
141             send_close_forwarding_failure(client_fd);
142             return;
143         }
144     }
145
146 #ifdef DEBUG
147     printf("  connection to server established\n");
148 #endif
149
150     /* We've established a connection, tell the client. */
151     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
152     fprintf(client_fd, "\r\n");
153     fflush(client_fd);
154
155     /* And transfer all data between client and server transparently. */
156     transfer_data(client_socket, server_socket);
157
158     fclose(client_fd);
159     fclose(server_fd);
160 }
161
162 /* Read HTTP request line and headers (ignored).
163  *
164  * On success 0 is returned, -1 on client error (we close client descriptor in
165  * this case), -2 on unexpected EOF.
166  */
167 static int read_http_request(FILE *client_fd, char *request, size_t length) {
168     char buffer[MAX_REQUEST_LINE];
169
170     if (NULL == fgets(request, (int)length, client_fd)) {
171         if (ferror(client_fd)) {
172             perror("fgets(), request");
173             fclose(client_fd);
174             return -1;
175         }
176
177         return -2;
178     }
179
180     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
181         /* End of header. */
182         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
183             break;
184         }
185     }
186     if (ferror(client_fd)) {
187         perror("fgets(), header");
188         fclose(client_fd);
189         return -1;
190     }
191
192     return 0;
193 }
194
195 static void send_close_bad_request(FILE *client_fd) {
196     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
197     fprintf(client_fd, "\r\n");
198     fclose(client_fd);
199 }
200 static void send_close_forwarding_failure(FILE *client_fd) {
201     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
202     fprintf(client_fd, "\r\n");
203     fclose(client_fd);
204 }
205
206
207 /* Transfer data between client and server sockets until one closes the
208  * connection. */
209 static void transfer_data(int client, int server) {
210     struct pollfd fds[2];
211     fds[0].fd      = client;
212     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
213     fds[0].revents = 0;
214     fds[1].fd      = server;
215     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
216     fds[1].revents = 0;
217
218     for (;;) {
219         int result = poll(fds, 2, -1 /* no timeout */);
220         if (result < 0) {
221             perror("poll()");
222             return;
223         }
224
225         /* Data available from client. */
226         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
227             if (0 != read_from_write_to(client, server)) {
228                 /* EOF (or other error) */
229                 break;
230             }
231         }
232         /* Data available from server. */
233         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
234             if (0 != read_from_write_to(server, client)) {
235                 /* EOF (or other error) */
236                 break;
237             }
238         }
239
240         /* Client closed connection. */
241         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
242             break;
243         }
244         /* Server closed connection. */
245         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
246             break;
247         }
248     }
249 }
250
251 /* Read available data from socket from and write it to socket to. At maximum
252  * 4096 bytes are read/written. */
253 static int read_from_write_to(int from, int to) {
254     ssize_t size_read;
255     ssize_t size_written;
256     char buffer[4096];
257
258     size_read = read(from, buffer, sizeof(buffer));
259     if (0 > size_read) {
260         perror("read()");
261         return -1;
262     }
263     /* EOF */
264     if (0 == size_read) {
265         return -1;
266     }
267
268     size_written = write(to, buffer, (size_t)size_read);
269     if (0 > size_written) {
270         perror("write()");
271         return -1;
272     }
273     if (size_read != size_written) {
274         printf("only written %ld of %ld bytes!\n", (long int)size_read,
275                                                    (long int)size_written);
276         return -1;
277     }
278
279     return 0;
280 }
281
282
283 static int connect_to_host(const char *hostname, const char *port) {
284     struct addrinfo gai_hints;
285     struct addrinfo *gai_result;
286     int gai_return;
287
288     int server_socket;
289     struct addrinfo *server;
290
291     if (NULL == hostname || NULL == port) {
292         return -1;
293     }
294
295     /* Get IP of hostname server. */
296     memset(&gai_hints, 0, sizeof(gai_hints));
297     gai_hints.ai_family   = AF_UNSPEC;
298     gai_hints.ai_socktype = SOCK_STREAM;
299     gai_hints.ai_protocol = 0;
300     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
301                           | AI_ADDRCONFIG  /* supported by this computer */
302                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
303     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
304     if (0 != gai_return) {
305         perror("getaddrinfo()");
306         return -1;
307     }
308
309     /* Now try to connect to each server returned by getaddrinfo(), use the
310      * first successful connect. */
311     for (server = gai_result; NULL != server; server = server->ai_next) {
312         server_socket = socket(server->ai_family,
313                                server->ai_socktype,
314                                server->ai_protocol);
315         if (-1 == server_socket) {
316             perror("socket(), trying next");
317             continue;
318         }
319
320         if (-1 != connect(server_socket, server->ai_addr,
321                                          server->ai_addrlen)) {
322             break;
323         }
324         perror("connect(), trying next");
325
326         close(server_socket);
327     }
328     /* Make sure we free the result from getaddrinfo(). */
329     freeaddrinfo(gai_result);
330
331     if (NULL == server) {
332         fprintf(stderr, "no server found, aborting\n");
333         return -1;
334     }
335
336     return server_socket;
337 }
338
339
340 /* Parse HTTP CONNECT request string and save its parameters.
341  *
342  * The following format is expected: "CONNECT host:port HTTP/1.x".
343  *
344  * request and host must have the same size! port must be at least 6 bytes
345  * long (5 + '\0').
346  */
347 static int parse_request(const char *request, char *host, char *port,
348                                               int *version_minor) {
349     int port_unused; /* just used to verify the port is numeric */
350     char *position;
351
352     /* scanf() doesn't check spaces. */
353     if (0 != strncmp(request, "CONNECT ", 8)) {
354         return -1;
355     }
356     /* Check request and extract data, "host:port" is not yet separated. */
357     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
358                              host, version_minor)) {
359         return -1;
360     }
361     /* Make sure ":port" is there. */
362     if (NULL == (position = strchr(host, ':'))) {
363         return -1;
364     }
365     /* Make sure port is numeric. */
366     if (1 != sscanf(position + 1, "%d", &port_unused)) {
367         return -1;
368     }
369     /* Store it in *port. */
370     strncpy(port, position + 1, 5);
371     port[5] = '\0';
372     /* And remove port from host. */
373     *position = '\0';
374
375     return 0;
376 }