]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/connection.c
src/connection.c: Minor source comment fixes.
[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         return;
114     }
115
116     /* Connect to proxy if requested (command line option). */
117     if (NULL != use_proxy_host && NULL != use_proxy_port) {
118         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
119         fprintf(server_fd, "\r\n");
120
121         /* Read response line from proxy server. */
122         result = read_http_request(server_fd, buffer, sizeof(buffer));
123         if (-1 == result) {
124             /* Read error, server_fd already closed. */
125             send_close_forwarding_failure(client_fd);
126             return;
127         } else if (-2 == result) {
128             /* EOF */
129             fclose(server_fd);
130             send_close_forwarding_failure(client_fd);
131             return;
132         }
133
134         /* Check response of proxy server. */
135         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
136 #ifdef DEBUG
137             printf("  bad proxy response\n");
138 #endif
139             fclose(server_fd);
140             send_close_forwarding_failure(client_fd);
141             return;
142         }
143     }
144
145 #ifdef DEBUG
146     printf("  connection to server established\n");
147 #endif
148
149     /* We've established a connection, tell the client. */
150     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
151     fprintf(client_fd, "\r\n");
152     fflush(client_fd);
153
154     /* And transfer all data between client and server transparently. */
155     transfer_data(client_socket, server_socket);
156
157     fclose(client_fd);
158     fclose(server_fd);
159 }
160
161 /* Read HTTP request line and headers (ignored).
162  *
163  * On success 0 is returned, -1 on client error (we close client descriptor in
164  * this case), -2 on unexpected EOF.
165  */
166 static int read_http_request(FILE *client_fd, char *request, size_t length) {
167     char buffer[MAX_REQUEST_LINE];
168
169     if (NULL == fgets(request, (int)length, client_fd)) {
170         if (ferror(client_fd)) {
171             perror("fgets(), request");
172             fclose(client_fd);
173             return -1;
174         }
175
176         return -2;
177     }
178
179     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
180         /* End of header. */
181         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
182             break;
183         }
184     }
185     if (ferror(client_fd)) {
186         perror("fgets(), header");
187         fclose(client_fd);
188         return -1;
189     }
190
191     return 0;
192 }
193
194 static void send_close_bad_request(FILE *client_fd) {
195     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
196     fprintf(client_fd, "\r\n");
197     fclose(client_fd);
198 }
199 static void send_close_forwarding_failure(FILE *client_fd) {
200     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
201     fprintf(client_fd, "\r\n");
202     fclose(client_fd);
203 }
204
205
206 /* Transfer data between client and server sockets until one closes the
207  * connection. */
208 static void transfer_data(int client, int server) {
209     struct pollfd fds[2];
210     fds[0].fd      = client;
211     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
212     fds[0].revents = 0;
213     fds[1].fd      = server;
214     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
215     fds[1].revents = 0;
216
217     for (;;) {
218         int result = poll(fds, 2, -1 /* no timeout */);
219         if (result < 0) {
220             perror("poll()");
221             return;
222         }
223
224         /* Data available from client. */
225         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
226             if (0 != read_from_write_to(client, server)) {
227                 /* EOF (or other error) */
228                 break;
229             }
230         }
231         /* Data available from server. */
232         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
233             if (0 != read_from_write_to(server, client)) {
234                 /* EOF (or other error) */
235                 break;
236             }
237         }
238
239         /* Client closed connection. */
240         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
241             break;
242         }
243         /* Server closed connection. */
244         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
245             break;
246         }
247     }
248 }
249
250 /* Read available data from socket from and write it to socket to. At maximum
251  * 4096 bytes are read/written. */
252 static int read_from_write_to(int from, int to) {
253     ssize_t size_read;
254     ssize_t size_written;
255     char buffer[4096];
256
257     size_read = read(from, buffer, sizeof(buffer));
258     if (0 > size_read) {
259         perror("read()");
260         return -1;
261     }
262     /* EOF */
263     if (0 == size_read) {
264         return -1;
265     }
266
267     size_written = write(to, buffer, (size_t)size_read);
268     if (0 > size_written) {
269         perror("write()");
270         return -1;
271     }
272     if (size_read != size_written) {
273         printf("only written %ld of %ld bytes!\n", (long int)size_read,
274                                                    (long int)size_written);
275         return -1;
276     }
277
278     return 0;
279 }
280
281
282 static int connect_to_host(const char *hostname, const char *port) {
283     struct addrinfo gai_hints;
284     struct addrinfo *gai_result;
285     int gai_return;
286
287     int server_socket;
288     struct addrinfo *server;
289
290     if (NULL == hostname || NULL == port) {
291         return -1;
292     }
293
294     /* Get IP of hostname server. */
295     memset(&gai_hints, 0, sizeof(gai_hints));
296     gai_hints.ai_family   = AF_UNSPEC;
297     gai_hints.ai_socktype = SOCK_STREAM;
298     gai_hints.ai_protocol = 0;
299     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
300                           | AI_ADDRCONFIG  /* supported by this computer */
301                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
302     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
303     if (0 != gai_return) {
304         perror("getaddrinfo()");
305         return -1;
306     }
307
308     /* Now try to connect to each server returned by getaddrinfo(), use the
309      * first successful connect. */
310     for (server = gai_result; NULL != server; server = server->ai_next) {
311         server_socket = socket(server->ai_family,
312                                server->ai_socktype,
313                                server->ai_protocol);
314         if (-1 == server_socket) {
315             perror("socket(), trying next");
316             continue;
317         }
318
319         if (-1 != connect(server_socket, server->ai_addr,
320                                          server->ai_addrlen)) {
321             break;
322         }
323         perror("connect(), trying next");
324
325         close(server_socket);
326     }
327     /* Make sure we free the result from getaddrinfo(). */
328     freeaddrinfo(gai_result);
329
330     if (NULL == server) {
331         fprintf(stderr, "no server found, aborting\n");
332         return -1;
333     }
334
335     return server_socket;
336 }
337
338
339 /* Parse HTTP CONNECT request string and save its parameters.
340  *
341  * The following format is expected: "CONNECT host:port HTTP/1.x".
342  *
343  * request and host must have the same size! port must be at least 6 bytes
344  * long (5 + '\0').
345  */
346 static int parse_request(const char *request, char *host, char *port,
347                                               int *version_minor) {
348     int port_unused; /* just used to verify the port is numeric */
349     char *position;
350
351     /* scanf() doesn't check spaces. */
352     if (0 != strncmp(request, "CONNECT ", 8)) {
353         return -1;
354     }
355     /* Check request and extract data, "host:port" is not yet separated. */
356     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
357                              host, version_minor)) {
358         return -1;
359     }
360     /* Make sure ":port" is there. */
361     if (NULL == (position = strchr(host, ':'))) {
362         return -1;
363     }
364     /* Make sure port is numeric. */
365     if (1 != sscanf(position + 1, "%d", &port_unused)) {
366         return -1;
367     }
368     /* Store it in *port. */
369     strncpy(port, position + 1, 5);
370     port[5] = '\0';
371     /* And remove port from host. */
372     *position = '\0';
373
374     return 0;
375 }