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