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