4 * Copyright (C) 2011 Simon Ruderich
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.
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.
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/>.
21 #include "connection.h"
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
42 /* Helper macro for LOG/LOG_PERROR. Print file/line number if compiled with
45 #define LOG_PRINT_LOCATION fprintf(stdout, "%s:%-3d ", __FILE__, __LINE__);
47 #define LOG_PRINT_LOCATION
49 /* Call log_message() and print current file and line number. */
53 /* perror() replacement with debug level support. */
54 #define LOG_PERROR(level, message) \
56 log_message(level, "%s: %s", message, strerror(errno))
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);
63 static void transfer_data(int client, int server);
64 static int read_from_write_to(int from, int to);
66 static int connect_to_host(const char *hostname, const char *port);
68 static int parse_request(const char *buffer, char *host, char *port,
71 static void log_message(int level, const char *format, ...);
74 void handle_connection(int client_socket) {
76 FILE *client_fd, *server_fd;
78 char buffer[MAX_REQUEST_LINE];
79 char host[MAX_REQUEST_LINE];
85 LOG(LOG_DEBUG, "new connection");
87 client_fd = fdopen(client_socket, "a+");
88 if (NULL == client_fd) {
89 LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
94 /* Read request line (CONNECT ..) and headers (they are discarded). */
95 result = read_http_request(client_fd, buffer, sizeof(buffer));
97 /* Read error, client_fd already closed. */
98 LOG(LOG_WARNING, "read_http_request(): client read error");
100 } else if (-2 == result) {
102 LOG(LOG_WARNING, "read_http_request(): client EOF");
103 send_close_bad_request(client_fd);
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);
113 LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
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,
119 server_socket = connect_to_host(global_proxy_host, global_proxy_port);
121 LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
122 server_socket = connect_to_host(host, port);
125 if (-1 == server_socket) {
126 LOG(LOG_WARNING, "failed to connect to server");
127 send_close_forwarding_failure(client_fd);
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);
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");
143 /* Read response line from proxy server. */
144 result = read_http_request(server_fd, buffer, sizeof(buffer));
146 /* Read error, server_fd already closed. */
147 LOG(LOG_WARNING, "read_http_request(): proxy read error");
148 send_close_forwarding_failure(client_fd);
150 } else if (-2 == result) {
152 LOG(LOG_WARNING, "read_http_request(): proxy EOF");
154 send_close_forwarding_failure(client_fd);
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);
162 send_close_forwarding_failure(client_fd);
167 LOG(LOG_DEBUG, "connection to server established");
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");
174 /* And transfer all data between client and server transparently. */
175 transfer_data(client_socket, server_socket);
180 LOG(LOG_DEBUG, "connection to server closed");
182 LOG(LOG_DEBUG, "connection finished");
185 /* Read HTTP request line and headers (ignored).
187 * On success 0 is returned, -1 on client error (we close client descriptor in
188 * this case), -2 on unexpected EOF.
190 static int read_http_request(FILE *client_fd, char *request, size_t length) {
191 char buffer[MAX_REQUEST_LINE];
193 if (NULL == fgets(request, (int)length, client_fd)) {
194 if (ferror(client_fd)) {
195 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
203 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
205 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
209 if (ferror(client_fd)) {
210 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
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");
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");
230 /* Transfer data between client and server sockets until one closes the
232 static void transfer_data(int client, int server) {
233 struct pollfd fds[2];
235 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
238 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
242 int result = poll(fds, 2, -1 /* no timeout */);
244 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
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) */
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) */
263 /* Client closed connection. */
264 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
267 /* Server closed connection. */
268 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
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) {
278 ssize_t size_written;
281 size_read = read(from, buffer, sizeof(buffer));
283 LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
287 if (0 == size_read) {
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()");
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);
306 static int connect_to_host(const char *hostname, const char *port) {
307 struct addrinfo gai_hints;
308 struct addrinfo *gai_result;
312 struct addrinfo *server;
314 if (NULL == hostname || NULL == port) {
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()");
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,
337 server->ai_protocol);
338 if (-1 == server_socket) {
339 LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
343 if (-1 != connect(server_socket, server->ai_addr,
344 server->ai_addrlen)) {
347 LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
349 close(server_socket);
351 /* Make sure we free the result from getaddrinfo(). */
352 freeaddrinfo(gai_result);
354 if (NULL == server) {
355 LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
359 return server_socket;
363 /* Parse HTTP CONNECT request string and save its parameters.
365 * The following format is expected: "CONNECT host:port HTTP/1.x".
367 * request and host must have the same size! port must be at least 6 bytes
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 */
375 /* scanf() doesn't check spaces. */
376 if (0 != strncmp(request, "CONNECT ", 8)) {
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)) {
384 /* Make sure ":port" is there. */
385 if (NULL == (position = strchr(host, ':'))) {
388 /* Make sure port is numeric. */
389 if (1 != sscanf(position + 1, "%d", &port_unused)) {
392 /* Store it in *port. */
393 strncpy(port, position + 1, 5);
395 /* And remove port from host. */
402 static void log_message(int level, const char *format, ...) {
404 const char *level_string;
406 if (global_log_level < 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";
417 va_start(ap, format);
418 fprintf(stdout, "[%s] [%d] ", level_string, (int)pthread_self());
419 vfprintf(stdout, format, ap);
420 fprintf(stdout, "\n");