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_bad_request(FILE *client_fd);
61 static void send_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");
91 client_fd = fdopen(client_socket, "a+");
92 if (NULL == client_fd) {
93 LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
97 /* Read request line (CONNECT ..) and headers (they are discarded). */
98 result = read_http_request(client_fd, buffer, sizeof(buffer));
101 LOG(LOG_WARNING, "read_http_request(): client read error");
103 } else if (-2 == result) {
105 LOG(LOG_WARNING, "read_http_request(): client EOF");
106 send_bad_request(client_fd);
110 if (0 != parse_request(buffer, host, port, &version_minor)) {
111 LOG(LOG_WARNING, "bad request: %s", buffer);
112 send_bad_request(client_fd);
116 LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
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,
122 server_socket = connect_to_host(global_proxy_host, global_proxy_port);
124 LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
125 server_socket = connect_to_host(host, port);
128 if (-1 == server_socket) {
129 LOG(LOG_WARNING, "failed to connect to server");
130 send_forwarding_failure(client_fd);
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);
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");
145 /* Read response line from proxy server. */
146 result = read_http_request(server_fd, buffer, sizeof(buffer));
149 LOG(LOG_WARNING, "read_http_request(): proxy read error");
150 send_forwarding_failure(client_fd);
152 } else if (-2 == result) {
154 LOG(LOG_WARNING, "read_http_request(): proxy EOF");
155 send_forwarding_failure(client_fd);
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);
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);
178 /* Close connection to server/proxy. */
179 if (NULL != server_fd) {
181 } else if (-1 != server_socket) {
182 close(server_socket);
184 LOG(LOG_DEBUG, "connection to server closed");
185 /* Close connection to client. */
186 if (NULL != client_fd) {
189 close(client_socket);
191 LOG(LOG_DEBUG, "connection to client closed");
193 LOG(LOG_DEBUG, "connection finished");
196 /* Read HTTP request line and headers (ignored).
198 * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
200 static int read_http_request(FILE *client_fd, char *request, size_t length) {
201 char buffer[MAX_REQUEST_LINE];
203 if (NULL == fgets(request, (int)length, client_fd)) {
204 if (ferror(client_fd)) {
205 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
212 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
214 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
218 if (ferror(client_fd)) {
219 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
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");
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");
236 /* Transfer data between client and server sockets until one closes the
238 static void transfer_data(int client, int server) {
239 struct pollfd fds[2];
241 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
244 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
248 int result = poll(fds, 2, -1 /* no timeout */);
250 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
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) */
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) */
269 /* Client closed connection. */
270 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
273 /* Server closed connection. */
274 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
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) {
284 ssize_t size_written;
287 size_read = read(from, buffer, sizeof(buffer));
289 LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
293 if (0 == size_read) {
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()");
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);
312 static int connect_to_host(const char *hostname, const char *port) {
313 struct addrinfo gai_hints;
314 struct addrinfo *gai_result;
318 struct addrinfo *server;
320 if (NULL == hostname || NULL == port) {
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()");
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,
343 server->ai_protocol);
344 if (-1 == server_socket) {
345 LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
349 if (-1 != connect(server_socket, server->ai_addr,
350 server->ai_addrlen)) {
353 LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
355 close(server_socket);
357 /* Make sure we free the result from getaddrinfo(). */
358 freeaddrinfo(gai_result);
360 if (NULL == server) {
361 LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
365 return server_socket;
369 /* Parse HTTP CONNECT request string and save its parameters.
371 * The following format is expected: "CONNECT host:port HTTP/1.x".
373 * request and host must have the same size! port must be at least 6 bytes
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 */
381 /* scanf() doesn't check spaces. */
382 if (0 != strncmp(request, "CONNECT ", 8)) {
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)) {
390 /* Make sure ":port" is there. */
391 if (NULL == (position = strchr(host, ':'))) {
394 /* Make sure port is numeric. */
395 if (1 != sscanf(position + 1, "%d", &port_unused)) {
398 /* Store it in *port. */
399 strncpy(port, position + 1, 5);
401 /* And remove port from host. */
408 static void log_message(int level, const char *format, ...) {
410 const char *level_string;
412 if (global_log_level < 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";
423 va_start(ap, format);
424 fprintf(stdout, "[%s] [%d] ", level_string, (int)pthread_self());
425 vfprintf(stdout, format, ap);
426 fprintf(stdout, "\n");