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