Exemplo n.º 1
0
stcp_t *stcp_connect(const char *host, int port)
{
	stcp_t *ret;
	proxy_t *proxy;

	proxy = proxy_connect(host, port);
	if (proxy == NULL)
		return stcp_connect_np(host, port);

	ret = (stcp_t*)calloc(1,sizeof(stcp_t));
	if (ret == NULL)
		return NULL;

	ret->proxy = proxy;

	return ret;
}
Exemplo n.º 2
0
int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA	ws;
	WSAStartup(MAKEWORD(2, 2), &ws);;

	struct proxy *prox;

	prox = proxy_create();
	assert(prox);


	proxy_set(prox, "192.168.79.1", 1080, "test", "0");
	proxy_connect(prox, "113.108.16.44", 25);
	proxy_recv_line(prox, buff, 512);

	return 0;
}
Exemplo n.º 3
0
/**
 * aim_newconn - Open a new connection
 * @sess: Session to create connection in
 * @type: Type of connection to create
 * @dest: Host to connect to (in "host:port" syntax)
 *
 * Opens a new connection to the specified dest host of specified
 * type, using the proxy settings if available.  If @host is %NULL,
 * the connection is allocated and returned, but no connection 
 * is made.
 *
 * FIXME: Return errors in a more sane way.
 *
 */
aim_conn_t *aim_newconn(aim_session_t *sess, int type, const char *dest)
{
	aim_conn_t *connstruct;
	guint16 port = AIM_LOGIN_PORT;
	char *host;
	int i;

	if (!(connstruct = aim_conn_getnext(sess)))
		return NULL;

	connstruct->sessv = (void *)sess;
	connstruct->type = type;

	if (!dest) { /* just allocate a struct */
		connstruct->fd = -1;
		connstruct->status = 0;
		return connstruct;
	}

	/* 
	 * As of 23 Jul 1999, AOL now sends the port number, preceded by a 
	 * colon, in the BOS redirect.  This fatally breaks all previous 
	 * libfaims.  Bad, bad AOL.
	 *
	 * We put this here to catch every case. 
	 *
	 */

	for(i = 0; i < (int)strlen(dest); i++) {
		if (dest[i] == ':') {
			port = atoi(&(dest[i+1]));
			break;
		}
	}

	host = (char *)g_malloc(i+1);
	strncpy(host, dest, i);
	host[i] = '\0';

	connstruct->fd = proxy_connect(host, port, NULL, NULL);

	g_free(host);

	return connstruct;
}
Exemplo n.º 4
0
gboolean msn_ns_connect( struct im_connection *ic, struct msn_handler_data *handler, const char *host, int port )
{
	if( handler->fd >= 0 )
		closesocket( handler->fd );
	
	handler->exec_command = msn_ns_command;
	handler->exec_message = msn_ns_message;
	handler->data = ic;
	handler->fd = proxy_connect( host, port, msn_ns_connected, handler );
	if( handler->fd < 0 )
	{
		imcb_error( ic, "Could not connect to server" );
		imc_logout( ic, TRUE );
		return FALSE;
	}
	
	return TRUE;
}
Exemplo n.º 5
0
int
main(int argc, char **argv)
{
	int sock;
	struct config_t config;
	struct buffer_t buffer;
	
	/* initialize buffer */
	buffer_init(&buffer);
	
	/* parse arguments and config file */
	if (setup(&config, argc, argv) != SETUP_OK) {
		usage(stderr);
		return EX_USAGE;
	}
	
	/* ask password if none was given, but username is set */
	if (config.username && !config.password) {
		config.password = askpass_tty(PASSWORD_PROMPT);
		/* exit if unable to get password */
		if (!config.password)
			return EX_NOINPUT;
	}
	
	/* connect to proxy */
	if ((sock = tcp_connect(config.proxyname, config.proxyport)) == -1)
		return EX_UNAVAILABLE;
	
	/* tunnel setup */
	if (proxy_connect(sock, &buffer, config.hostname, config.hostport,
		config.username, config.password) != 0)
	{
		close(sock);
		return EX_UNAVAILABLE;
	}
	
	/* tunnel data (does not return on failure) */
	tunnel_handler(&buffer, config.ifd, config.ofd, sock, sock);
	
	/* cleanup */
	close(sock);
	
	return EX_OK;
}
Exemplo n.º 6
0
int connect_address(unsigned int addy, unsigned short port)
{
        int fd;
	struct sockaddr_in sin;

	sin.sin_addr.s_addr = addy;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);
	
	fd = socket(AF_INET, SOCK_STREAM, 0);
	
	if (fd > -1) {
		quad_addr=strdup(inet_ntoa(sin.sin_addr));
		if (proxy_connect(fd, (struct sockaddr *)&sin, sizeof(sin)) > -1) {
			return fd;
		}
	}
	return -1;
}
Exemplo n.º 7
0
void *ssl_connect( char *host, int port, gboolean verify, ssl_input_function func, gpointer data )
{
	struct scd *conn = g_new0( struct scd, 1 );
	
	conn->fd = proxy_connect( host, port, ssl_connected, conn );
	conn->func = func;
	conn->data = data;
	conn->inpa = -1;
	conn->hostname = g_strdup( host );
	conn->verify = verify && global.conf->cafile;
	
	if( conn->fd < 0 )
	{
		g_free( conn );
		return NULL;
	}
	
	return conn;
}
Exemplo n.º 8
0
Arquivo: sb.c Projeto: shiplu/bitlbee
struct msn_switchboard *msn_sb_create( struct im_connection *ic, char *host, int port, char *key, int session )
{
    struct msn_data *md = ic->proto_data;
    struct msn_switchboard *sb = g_new0( struct msn_switchboard, 1 );

    sb->fd = proxy_connect( host, port, msn_sb_connected, sb );
    if( sb->fd < 0 )
    {
        g_free( sb );
        return( NULL );
    }

    sb->ic = ic;
    sb->key = g_strdup( key );
    sb->session = session;

    msn_switchboards = g_slist_append( msn_switchboards, sb );
    md->switchboards = g_slist_append( md->switchboards, sb );

    return( sb );
}
Exemplo n.º 9
0
void *ssl_connect(char *host, int port, gboolean verify,
		  ssl_input_function func, gpointer data)
{
	struct scd *conn = g_new0(struct scd, 1);

	conn->fd = proxy_connect(host, port, ssl_connected, conn);
	conn->func = func;
	conn->data = data;
	conn->hostname = g_strdup(host);

	if (conn->fd < 0) {
		g_free(conn->hostname);
		g_free(conn);
		return (NULL);
	}

	if (!initialized) {
		ssl_init();
	}

	return (conn);
}
Exemplo n.º 10
0
struct http_request *http_dorequest( char *host, int port, int ssl, char *request, http_input_function func, gpointer data )
{
	struct http_request *req;
	int error = 0;
	
	req = g_new0( struct http_request, 1 );
	
	if( ssl )
	{
		req->ssl = ssl_connect( host, port, TRUE, http_ssl_connected, req );
		if( req->ssl == NULL )
			error = 1;
	}
	else
	{
		req->fd = proxy_connect( host, port, http_connected, req );
		if( req->fd < 0 )
			error = 1;
	}
	
	if( error )
	{
		http_free( req );
		return NULL;
	}
	
	req->func = func;
	req->data = data;
	req->request = g_strdup( request );
	req->request_length = strlen( request );
	req->redir_ttl = 3;
	req->content_length = -1;
	
	if( getenv( "BITLBEE_DEBUG" ) )
		printf( "About to send HTTP request:\n%s\n", req->request );
	
	return req;
}
Exemplo n.º 11
0
void *ssl_connect( char *host, int port, ssl_input_function func, gpointer data )
{
	struct scd *conn = g_new0( struct scd, 1 );
	
	conn->fd = proxy_connect( host, port, ssl_connected, conn );
	conn->func = func;
	conn->data = data;
	
	if( conn->fd < 0 )
	{
		g_free( conn );
		return( NULL );
	}
	
	if( !initialized )
	{
		PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
		NSS_NoDB_Init(NULL);
		NSS_SetDomesticPolicy();
	}

	
	return( conn );
}
Exemplo n.º 12
0
unsigned int sockroutine(acetables *g_ape)
{
	struct _socks_list sl;
	
	int new_fd, nfds, sin_size = sizeof(struct sockaddr_in), i, tfd = 0;
	ape_socket *co = g_ape->co;

	struct timeval t_start, t_end;	
	long int ticks = 0, uticks = 0, lticks = 0;
	struct sockaddr_in their_addr;
	
	sl.co = co;
	sl.tfd = &tfd;
	
	g_ape->bufout = xmalloc(sizeof(struct _socks_bufout) * g_ape->basemem);

	#if 0
	add_periodical(5, 0, check_idle, &sl, g_ape);
	#endif
	
	while (1) {
	//	int timeout_to_hang = MAX((1000/TICKS_RATE)-ticks, 1);
		/* Linux 2.6.25 provides a fd-driven timer system. It could be usefull to implement */
		gettimeofday(&t_start, NULL);

		nfds = events_poll(g_ape->events, 1);
		
		if (nfds < 0) {
			continue;
		}
		
		if (nfds > 0) {
			for (i = 0; i < nfds; i++) {

				int active_fd = events_get_current_fd(g_ape->events, i);
				
				if (co[active_fd].stream_type == STREAM_SERVER) {
				
					while (1) {

						http_state http = {0, HTTP_NULL, 0, -1, 0, 0, 0};
					
						new_fd = accept(active_fd, 
							(struct sockaddr *)&their_addr,
							(unsigned int *)&sin_size);
					
						if (new_fd == -1) {
							break;
						}
						
						if (new_fd + 4 == g_ape->basemem) {
							/* Increase connection & events size */
							growup(&g_ape->basemem, &g_ape->co, g_ape->events, &g_ape->bufout);
							co = g_ape->co;
						}

						strncpy(co[new_fd].ip_client, inet_ntoa(their_addr.sin_addr), 16);
						
						co[new_fd].buffer_in.data = xmalloc(sizeof(char) * (DEFAULT_BUFFER_SIZE + 1));
						co[new_fd].buffer_in.size = DEFAULT_BUFFER_SIZE;
						co[new_fd].buffer_in.length = 0;
						co[new_fd].buffer_in.slot = NULL;
						co[new_fd].buffer_in.islot = 0;
						
						co[new_fd].http = http;
						co[new_fd].attach = NULL;
						co[new_fd].data = NULL;
						co[new_fd].idle = time(NULL);
						co[new_fd].fd = new_fd;
						
						co[new_fd].stream_type = STREAM_IN;
						co[new_fd].state = STREAM_ONLINE;
					
						g_ape->bufout[new_fd].fd = new_fd;
						g_ape->bufout[new_fd].buf = NULL;
						g_ape->bufout[new_fd].buflen = 0;
						g_ape->bufout[new_fd].allocsize = 0;
						
						co[new_fd].callbacks.on_disconnect = co[active_fd].callbacks.on_disconnect;
						co[new_fd].callbacks.on_read = co[active_fd].callbacks.on_read;
						co[new_fd].callbacks.on_read_lf = co[active_fd].callbacks.on_read_lf;
						co[new_fd].callbacks.on_data_completly_sent = co[active_fd].callbacks.on_data_completly_sent;
						co[new_fd].callbacks.on_write = co[active_fd].callbacks.on_write;
						
						co[new_fd].attach = co[active_fd].attach;
						
						setnonblocking(new_fd);
									
						events_add(g_ape->events, new_fd, EVENT_READ|EVENT_WRITE);
						
						tfd++;
						
						if (co[active_fd].callbacks.on_accept != NULL) {
							co[active_fd].callbacks.on_accept(&co[new_fd], g_ape);
						}
					
					}
					continue;
				} else {
					int readb = 0;
					int bitev = events_revent(g_ape->events, i);
						
					if (bitev & EVENT_WRITE) {
						
						if (co[active_fd].stream_type == STREAM_OUT && co[active_fd].state == STREAM_PROGRESS) {
							
							int serror = 0, ret;
							socklen_t serror_len = sizeof(serror);
						
							ret = getsockopt(active_fd, SOL_SOCKET, SO_ERROR, &serror, &serror_len);
							
							if (ret == 0 && serror == 0) {

								co[active_fd].state = STREAM_ONLINE;
								if (co[active_fd].callbacks.on_connect != NULL) {

									co[active_fd].callbacks.on_connect(&co[active_fd], g_ape);
								}
							} else { /* This can happen ? epoll seems set EPOLLIN as if the host is disconnecting */

								if (co[active_fd].callbacks.on_disconnect != NULL) {
									co[active_fd].callbacks.on_disconnect(&co[active_fd], g_ape);
								}
								clear_buffer(&co[active_fd], &tfd);
								close(active_fd);
							}							
						}
						#if 0
						if (co[active_fd].stream_type == STREAM_OUT && 
						((ape_proxy *)(co[active_fd].attach))->state == PROXY_IN_PROGRESS) {
							
							int serror = 0, ret;
							socklen_t serror_len = sizeof(serror);
						
							ret = getsockopt(active_fd, SOL_SOCKET, SO_ERROR, &serror, &serror_len);
							
							if (ret == 0 && serror == 0) {
								((ape_proxy *)(co[active_fd].attach))->state = PROXY_CONNECTED;
								((ape_proxy *)(co[active_fd].attach))->sock.fd = active_fd;
								proxy_onevent((ape_proxy *)(co[active_fd].attach), "CONNECT", g_ape);
								
								if (co[active_fd].callbacks.on_connect != NULL) {
									co[active_fd].callbacks.on_connect(&co[active_fd]);
								}
							} else { /* This can happen ? epoll seems set EPOLLIN as if the host is disconnecting */
								if (co[active_fd].callbacks.on_disconnect != NULL) {
									co[active_fd].callbacks.on_disconnect(&co[active_fd]);
								}
								((ape_proxy *)(co[active_fd].attach))->state = PROXY_THROTTLED;
								//epoll_ctl(event_fd, EPOLL_CTL_DEL, active_fd, NULL);
								clear_buffer(&co[active_fd], &tfd);
								close(active_fd);
							}

						}
						#endif
						else if (co[active_fd].stream_type == STREAM_IN && g_ape->bufout[active_fd].buf != NULL) {

							if (sendqueue(active_fd, g_ape) == 1) {
								
								if (co[active_fd].callbacks.on_data_completly_sent != NULL) {
									co[active_fd].callbacks.on_data_completly_sent(&co[active_fd], g_ape);
								}

							}
						} else if (co[active_fd].stream_type == STREAM_DELEGATE) {
							if (co[active_fd].callbacks.on_write != NULL) {
								co[active_fd].callbacks.on_write(&co[active_fd], g_ape);

							}							
						}
					}

					if (bitev & EVENT_READ) {
						if (co[active_fd].stream_type == STREAM_DELEGATE) {
							if (co[active_fd].callbacks.on_read != NULL) {
								co[active_fd].callbacks.on_read(&co[active_fd], NULL, 0, g_ape);
								continue;
							}							
						}
						do {
							/*
								TODO : Check if maximum data read can improve perf
								Huge data may attempt to increase third parameter
							*/
							readb = read(active_fd, 
										co[active_fd].buffer_in.data + co[active_fd].buffer_in.length, 
										co[active_fd].buffer_in.size - co[active_fd].buffer_in.length);
						
						
							if (readb == -1 && errno == EAGAIN) {
							
								/*
									Nothing to read again
								*/
								
								if (co[active_fd].stream_type == STREAM_OUT) {
									
										//proxy_process_eol(&co[active_fd], g_ape);
										//co[active_fd].buffer_in.length = 0;
								} else {
								//	co[active_fd].buffer_in.data[co[active_fd].buffer_in.length] = '\0';
								}
								break;
							} else {
								if (readb < 1) {

									if (co[active_fd].callbacks.on_disconnect != NULL) { 
										co[active_fd].callbacks.on_disconnect(&co[active_fd], g_ape);
									}
									
									#if 0
									if (co[active_fd].stream_type == STREAM_IN && co[active_fd].attach != NULL) {
										
										if (active_fd == ((subuser *)(co[active_fd].attach))->fd) {
											((subuser *)(co[active_fd].attach))->headers_sent = 0;
											((subuser *)(co[active_fd].attach))->state = ADIED;
										}
										if (((subuser *)(co[active_fd].attach))->wait_for_free == 1) {
											free(co[active_fd].attach);
											co[active_fd].attach = NULL;						
										}
									} else if (co[active_fd].stream_type == STREAM_OUT) {
									
										if (((ape_proxy *)(co[active_fd].attach))->state == PROXY_TOFREE) {
											free(co[active_fd].attach);
											co[active_fd].attach = NULL;								
										} else {
									
											((ape_proxy *)(co[active_fd].attach))->state = PROXY_THROTTLED;
											proxy_onevent((ape_proxy *)(co[active_fd].attach), "DISCONNECT", g_ape);
										}
									}
									#endif
									clear_buffer(&co[active_fd], &tfd);
								
									if (g_ape->bufout[active_fd].buf != NULL) {
										free(g_ape->bufout[active_fd].buf);
										g_ape->bufout[active_fd].buflen = 0;
										g_ape->bufout[active_fd].buf = NULL;
										g_ape->bufout[active_fd].allocsize = 0;
									}
									
									close(active_fd);
									
									break;
								} else {
									
									co[active_fd].buffer_in.length += readb;
									
									/* realloc the buffer for the next read (x2) */
									if (co[active_fd].buffer_in.length == co[active_fd].buffer_in.size) {
										co[active_fd].buffer_in.size *= 2;
										co[active_fd].buffer_in.data = xrealloc(co[active_fd].buffer_in.data, 
																sizeof(char) * (co[active_fd].buffer_in.size + 1));
									
									}
									if (co[active_fd].callbacks.on_read_lf != NULL) {
										int eol, len = co[active_fd].buffer_in.length;
										char *pBuf = co[active_fd].buffer_in.data;

										while ((eol = sneof(pBuf, len, 4096)) != -1) {
											pBuf[eol-1] = '\0';
											co[active_fd].callbacks.on_read_lf(&co[active_fd], pBuf, g_ape);
											pBuf = &pBuf[eol];
											len -= eol;
										}
										if (len > 4096 || !len) {
											co[active_fd].buffer_in.length = 0;
										} else if (len) {
											memmove(co[active_fd].buffer_in.data, &co[active_fd].buffer_in.data[co[active_fd].buffer_in.length - len], len);
											co[active_fd].buffer_in.length = len;
										}

									}
									
									/* on_read can't get along with on_read_lf */
									if (co[active_fd].callbacks.on_read != NULL && co[active_fd].callbacks.on_read_lf == NULL) {
										co[active_fd].callbacks.on_read(&co[active_fd], &co[active_fd].buffer_in, co[active_fd].buffer_in.length - readb, g_ape);
									}
								} 
							}
						} while(readb >= 0);
					}
				}			
			}
		}
		
		gettimeofday(&t_end, NULL);

		ticks = 0;
		
		uticks = 1000000 * (t_end.tv_sec - t_start.tv_sec);
		uticks += (t_end.tv_usec - t_start.tv_usec);
		
		lticks += uticks;

		/* Tic tac, tic tac :-) */
		{
			unsigned long int nticks;
			ape_proxy *proxy = g_ape->proxy.list;
			int psock;

			while (proxy != NULL) {

				if (proxy->state == PROXY_NOT_CONNECTED && ((psock = proxy_connect(proxy, g_ape)) != 0)) {
					http_state http_s = {0, HTTP_NULL, 0, -1, 0, 0, 0};
					if (psock + 4 == g_ape->basemem) {
						growup(&g_ape->basemem, &g_ape->co, g_ape->events, &g_ape->bufout);
						co = g_ape->co;
					}
					co[psock].ip_client[0] = '\0';
					co[psock].buffer_in.data = xmalloc(sizeof(char) * (DEFAULT_BUFFER_SIZE + 1));
					co[psock].buffer_in.size = DEFAULT_BUFFER_SIZE;
					co[psock].buffer_in.length = 0;
					co[psock].buffer_in.slot = NULL;
					co[psock].buffer_in.islot = 0;
					
					co[psock].idle = time(NULL);
					co[psock].http = http_s;
					co[psock].attach = proxy;
					co[psock].stream_type = STREAM_OUT;
					co[psock].fd = psock;
					
					tfd++;
				}

				proxy = proxy->next;
			}
			
			while (lticks > 1000) {
				ticks++;
				lticks -= 1000;
			}
			for (nticks = 0; nticks < ticks; nticks++) {
				process_tick(g_ape);
			}
		}
	}

	return 0;
}
Exemplo n.º 13
0
static int rpc_channel_tls_connect(RpcChannel* channel, int timeout)
{
	int sockfd;
	rdpTls* tls;
	int tlsStatus;
	BIO* socketBio;
	BIO* bufferedBio;
	rdpRpc* rpc = channel->rpc;
	rdpContext* context = rpc->context;
	rdpSettings* settings = context->settings;
	const char* peerHostname = settings->GatewayHostname;
	UINT16 peerPort = settings->GatewayPort;
	const char *proxyUsername = settings->ProxyUsername, *proxyPassword = settings->ProxyPassword;
	BOOL isProxyConnection = proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
	sockfd = freerdp_tcp_connect(context, settings, peerHostname,
	                             peerPort, timeout);

	if (sockfd < 1)
		return -1;

	socketBio = BIO_new(BIO_s_simple_socket());

	if (!socketBio)
		return FALSE;

	BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
	bufferedBio = BIO_new(BIO_s_buffered_socket());

	if (!bufferedBio)
		return FALSE;

	bufferedBio = BIO_push(bufferedBio, socketBio);

	if (!BIO_set_nonblock(bufferedBio, TRUE))
		return -1;

	if (isProxyConnection)
	{
		if (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword,	settings->GatewayHostname, settings->GatewayPort))
			return -1;
	}

	channel->bio = bufferedBio;
	tls = channel->tls = tls_new(settings);

	if (!tls)
		return -1;

	tls->hostname = settings->GatewayHostname;
	tls->port = settings->GatewayPort;
	tls->isGatewayTransport = TRUE;
	tlsStatus = tls_connect(tls, bufferedBio);

	if (tlsStatus < 1)
	{
		if (tlsStatus < 0)
		{
			if (!freerdp_get_last_error(context))
				freerdp_set_last_error(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
		}
		else
		{
			if (!freerdp_get_last_error(context))
				freerdp_set_last_error(context, FREERDP_ERROR_CONNECT_CANCELLED);
		}

		return -1;
	}

	return 1;
}
Exemplo n.º 14
0
/* Splits headers and body. Checks result code, in case of 300s it'll handle
   redirects. If this returns FALSE, don't call any callbacks! */
static gboolean http_handle_headers( struct http_request *req )
{
	char *end1, *end2, *s;
	int evil_server = 0;
	
	/* Zero termination is very convenient. */
	req->reply_headers[req->bytes_read] = '\0';
	
	/* Find the separation between headers and body, and keep stupid
	   webservers in mind. */
	end1 = strstr( req->reply_headers, "\r\n\r\n" );
	end2 = strstr( req->reply_headers, "\n\n" );
	
	if( end2 && end2 < end1 )
	{
		end1 = end2 + 1;
		evil_server = 1;
	}
	else if( end1 )
	{
		end1 += 2;
	}
	else
	{
		req->status_string = g_strdup( "Malformed HTTP reply" );
		return TRUE;
	}
	
	*end1 = '\0';
	
	if( getenv( "BITLBEE_DEBUG" ) )
		printf( "HTTP response headers:\n%s\n", req->reply_headers );
	
	if( evil_server )
		req->reply_body = end1 + 1;
	else
		req->reply_body = end1 + 2;
	
	/* Separately allocated space for headers and body. */
	req->sblen = req->body_size = req->reply_headers + req->bytes_read - req->reply_body;
	req->sbuf = req->reply_body = g_memdup( req->reply_body, req->body_size + 1 );
	req->reply_headers = g_realloc( req->reply_headers, end1 - req->reply_headers + 1 );
	
	if( ( end1 = strchr( req->reply_headers, ' ' ) ) != NULL )
	{
		if( sscanf( end1 + 1, "%hd", &req->status_code ) != 1 )
		{
			req->status_string = g_strdup( "Can't parse status code" );
			req->status_code = -1;
		}
		else
		{
			char *eol;
			
			if( evil_server )
				eol = strchr( end1, '\n' );
			else
				eol = strchr( end1, '\r' );
			
			req->status_string = g_strndup( end1 + 1, eol - end1 - 1 );
			
			/* Just to be sure... */
			if( ( eol = strchr( req->status_string, '\r' ) ) )
				*eol = 0;
			if( ( eol = strchr( req->status_string, '\n' ) ) )
				*eol = 0;
		}
	}
	else
	{
		req->status_string = g_strdup( "Can't locate status code" );
		req->status_code = -1;
	}
	
	if( ( ( req->status_code >= 301 && req->status_code <= 303 ) ||
	      req->status_code == 307 ) && req->redir_ttl-- > 0 )
	{
		char *loc, *new_request, *new_host;
		int error = 0, new_port, new_proto;
		
		/* We might fill it again, so let's not leak any memory. */
		g_free( req->status_string );
		req->status_string = NULL;
		
		loc = strstr( req->reply_headers, "\nLocation: " );
		if( loc == NULL ) /* We can't handle this redirect... */
		{
			req->status_string = g_strdup( "Can't locate Location: header" );
			return TRUE;
		}
		
		loc += 11;
		while( *loc == ' ' )
			loc ++;
		
		/* TODO/FIXME: Possibly have to handle relative redirections,
		   and rewrite Host: headers. Not necessary for now, it's
		   enough for passport authentication like this. */
		
		if( *loc == '/' )
		{
			/* Just a different pathname... */
			
			/* Since we don't cache the servername, and since we
			   don't need this yet anyway, I won't implement it. */
			
			req->status_string = g_strdup( "Can't handle relative redirects" );
			
			return TRUE;
		}
		else
		{
			/* A whole URL */
			url_t *url;
			char *s, *version, *headers;
			const char *new_method;
			
			s = strstr( loc, "\r\n" );
			if( s == NULL )
				return TRUE;
			
			url = g_new0( url_t, 1 );
			*s = 0;
			
			if( !url_set( url, loc ) )
			{
				req->status_string = g_strdup( "Malformed redirect URL" );
				g_free( url );
				return TRUE;
			}
			
			/* Find all headers and, if necessary, the POST request contents.
			   Skip the old Host: header though. This crappy code here means
			   anything using this http_client MUST put the Host: header at
			   the top. */
			if( !( ( s = strstr( req->request, "\r\nHost: " ) ) &&
			       ( s = strstr( s + strlen( "\r\nHost: " ), "\r\n" ) ) ) )
			{
				req->status_string = g_strdup( "Error while rebuilding request string" );
				g_free( url );
				return TRUE;
			}
			headers = s;
			
			/* More or less HTTP/1.0 compliant, from my reading of RFC 2616.
			   Always perform a GET request unless we received a 301. 303 was
			   meant for this but it's HTTP/1.1-only and we're specifically
			   speaking HTTP/1.0. ...
			   
			   Well except someone at identi.ca's didn't bother reading any
			   RFCs and just return HTTP/1.1-specific status codes to HTTP/1.0
			   requests. Fuckers. So here we are, handle 301..303,307. */
			if( strncmp( req->request, "GET", 3 ) == 0 )
				/* GETs never become POSTs. */
				new_method = "GET";
			else if( req->status_code == 302 || req->status_code == 303 )
				/* 302 de-facto becomes GET, 303 as specified by RFC 2616#10.3.3 */
				new_method = "GET";
			else
				/* 301 de-facto should stay POST, 307 specifally RFC 2616#10.3.8 */
				new_method = "POST";
			
			if( ( version = strstr( req->request, " HTTP/" ) ) &&
			    ( s = strstr( version, "\r\n" ) ) )
			{
				version ++;
				version = g_strndup( version, s - version );
			}
			else
				version = g_strdup( "HTTP/1.0" );
			
			/* Okay, this isn't fun! We have to rebuild the request... :-( */
			new_request = g_strdup_printf( "%s %s %s\r\nHost: %s%s",
			                               new_method, url->file, version,
			                               url->host, headers );
			
			new_host = g_strdup( url->host );
			new_port = url->port;
			new_proto = url->proto;
			
			/* If we went from POST to GET, truncate the request content. */
			if( new_request[0] != req->request[0] && new_request[0] == 'G' &&
			    ( s = strstr( new_request, "\r\n\r\n" ) ) )
				s[4] = '\0';
			
			g_free( url );
			g_free( version );
		}
		
		if( req->ssl )
			ssl_disconnect( req->ssl );
		else
			closesocket( req->fd );
		
		req->fd = -1;
		req->ssl = NULL;
		
		if( getenv( "BITLBEE_DEBUG" ) )
			printf( "New headers for redirected HTTP request:\n%s\n", new_request );
	
		if( new_proto == PROTO_HTTPS )
		{
			req->ssl = ssl_connect( new_host, new_port, TRUE, http_ssl_connected, req );
			if( req->ssl == NULL )
				error = 1;
		}
		else
		{
			req->fd = proxy_connect( new_host, new_port, http_connected, req );
			if( req->fd < 0 )
				error = 1;
		}
		g_free( new_host );
		
		if( error )
		{
			req->status_string = g_strdup( "Connection problem during redirect" );
			g_free( new_request );
			return TRUE;
		}
		
		g_free( req->request );
		g_free( req->reply_headers );
		g_free( req->sbuf );
		req->request = new_request;
		req->request_length = strlen( new_request );
		req->bytes_read = req->bytes_written = req->inpa = 0;
		req->reply_headers = req->reply_body = NULL;
		req->sbuf = req->cbuf = NULL;
		req->sblen = req->cblen = 0;
		
		return FALSE;
	}

	if( ( s = get_rfc822_header( req->reply_headers, "Content-Length", 0 ) ) &&
	    sscanf( s, "%d", &req->content_length ) != 1 )
		req->content_length = -1;
	g_free( s );
	
	if( ( s = get_rfc822_header( req->reply_headers, "Transfer-Encoding", 0 ) ) )
	{
		if( strcasestr( s, "chunked" ) )
		{
			req->flags |= HTTPC_CHUNKED;
			req->cbuf = req->sbuf;
			req->cblen = req->sblen;
			
			req->reply_body = req->sbuf = g_strdup( "" );
			req->body_size = req->sblen = 0;
		}
		g_free( s );
	}
	
	return TRUE;
}
Exemplo n.º 15
0
BOOL transport_connect(rdpTransport* transport, const char* hostname,
                       UINT16 port, int timeout)
{
	int sockfd;
	BOOL status = FALSE;
	rdpSettings* settings = transport->settings;
	rdpContext* context = transport->context;
	BOOL rpcFallback = !settings->GatewayHttpTransport;

	if (transport->GatewayEnabled)
	{
		if (!status && settings->GatewayHttpTransport)
		{
			transport->rdg = rdg_new(transport);

			if (!transport->rdg)
				return FALSE;

			status = rdg_connect(transport->rdg, timeout, &rpcFallback);

			if (status)
			{
				transport->frontBio = transport->rdg->frontBio;
				BIO_set_nonblock(transport->frontBio, 0);
				transport->layer = TRANSPORT_LAYER_TSG;
				status = TRUE;
			}
			else
			{
				rdg_free(transport->rdg);
				transport->rdg = NULL;
			}
		}

		if (!status && settings->GatewayRpcTransport && rpcFallback)
		{
			transport->tsg = tsg_new(transport);

			if (!transport->tsg)
				return FALSE;

			status = tsg_connect(transport->tsg, hostname, port, timeout);

			if (status)
			{
				transport->frontBio = tsg_get_bio(transport->tsg);
				transport->layer = TRANSPORT_LAYER_TSG;
				status = TRUE;
			}
			else
			{
				tsg_free(transport->tsg);
				transport->tsg = NULL;
			}
		}
	}
	else
	{
		UINT16 peerPort;
		const char* proxyHostname, *proxyUsername, *proxyPassword;
		BOOL isProxyConnection = proxy_prepare(settings, &proxyHostname, &peerPort,
		                                       &proxyUsername,	&proxyPassword);

		if (isProxyConnection)
			sockfd = freerdp_tcp_connect(context, settings, proxyHostname, peerPort, timeout);
		else
			sockfd = freerdp_tcp_connect(context, settings, hostname, port, timeout);

		if (sockfd < 0)
			return FALSE;

		if (!transport_attach(transport, sockfd))
			return FALSE;

		if (isProxyConnection)
		{
			if (!proxy_connect(settings, transport->frontBio, proxyUsername, proxyPassword, hostname, port))
				return FALSE;
		}

		status = TRUE;
	}

	return status;
}
Exemplo n.º 16
0
static gboolean http_incoming_data( gpointer data, int source, b_input_condition cond )
{
	struct http_request *req = data;
	int evil_server = 0;
	char buffer[2048];
	char *end1, *end2;
	int st;
	
	if( req->inpa > 0 )
		b_event_remove( req->inpa );
	
	if( req->ssl )
	{
		st = ssl_read( req->ssl, buffer, sizeof( buffer ) );
		if( st < 0 )
		{
			if( ssl_errno != SSL_AGAIN )
			{
				/* goto cleanup; */
				
				/* YAY! We have to deal with crappy Microsoft
				   servers that LOVE to send invalid TLS
				   packets that abort connections! \o/ */
				
				goto got_reply;
			}
		}
		else if( st == 0 )
		{
			goto got_reply;
		}
	}
	else
	{
		st = read( req->fd, buffer, sizeof( buffer ) );
		if( st < 0 )
		{
			if( !sockerr_again() )
			{
				req->status_string = g_strdup( strerror( errno ) );
				goto cleanup;
			}
		}
		else if( st == 0 )
		{
			goto got_reply;
		}
	}
	
	if( st > 0 )
	{
		req->reply_headers = g_realloc( req->reply_headers, req->bytes_read + st + 1 );
		memcpy( req->reply_headers + req->bytes_read, buffer, st );
		req->bytes_read += st;
	}
	
	/* There will be more! */
	req->inpa = b_input_add( req->fd,
	                         req->ssl ? ssl_getdirection( req->ssl ) : B_EV_IO_READ,
	                         http_incoming_data, req );
	
	if( ssl_pending( req->ssl ) )
		return http_incoming_data( data, source, cond );
	else
		return FALSE;

got_reply:
	/* Maybe if the webserver is overloaded, or when there's bad SSL
	   support... */
	if( req->bytes_read == 0 )
	{
		req->status_string = g_strdup( "Empty HTTP reply" );
		goto cleanup;
	}
	
	/* Zero termination is very convenient. */
	req->reply_headers[req->bytes_read] = 0;
	
	/* Find the separation between headers and body, and keep stupid
	   webservers in mind. */
	end1 = strstr( req->reply_headers, "\r\n\r\n" );
	end2 = strstr( req->reply_headers, "\n\n" );
	
	if( end2 && end2 < end1 )
	{
		end1 = end2 + 1;
		evil_server = 1;
	}
	else if( end1 )
	{
		end1 += 2;
	}
	else
	{
		req->status_string = g_strdup( "Malformed HTTP reply" );
		goto cleanup;
	}
	
	*end1 = 0;
	
	if( getenv( "BITLBEE_DEBUG" ) )
		printf( "HTTP response headers:\n%s\n", req->reply_headers );
	
	if( evil_server )
		req->reply_body = end1 + 1;
	else
		req->reply_body = end1 + 2;
	
	req->body_size = req->reply_headers + req->bytes_read - req->reply_body;
	
	if( ( end1 = strchr( req->reply_headers, ' ' ) ) != NULL )
	{
		if( sscanf( end1 + 1, "%d", &req->status_code ) != 1 )
		{
			req->status_string = g_strdup( "Can't parse status code" );
			req->status_code = -1;
		}
		else
		{
			char *eol;
			
			if( evil_server )
				eol = strchr( end1, '\n' );
			else
				eol = strchr( end1, '\r' );
			
			req->status_string = g_strndup( end1 + 1, eol - end1 - 1 );
			
			/* Just to be sure... */
			if( ( eol = strchr( req->status_string, '\r' ) ) )
				*eol = 0;
			if( ( eol = strchr( req->status_string, '\n' ) ) )
				*eol = 0;
		}
	}
	else
	{
		req->status_string = g_strdup( "Can't locate status code" );
		req->status_code = -1;
	}
	
	if( ( ( req->status_code >= 301 && req->status_code <= 303 ) ||
	      req->status_code == 307 ) && req->redir_ttl-- > 0 )
	{
		char *loc, *new_request, *new_host;
		int error = 0, new_port, new_proto;
		
		/* We might fill it again, so let's not leak any memory. */
		g_free( req->status_string );
		req->status_string = NULL;
		
		loc = strstr( req->reply_headers, "\nLocation: " );
		if( loc == NULL ) /* We can't handle this redirect... */
		{
			req->status_string = g_strdup( "Can't locate Location: header" );
			goto cleanup;
		}
		
		loc += 11;
		while( *loc == ' ' )
			loc ++;
		
		/* TODO/FIXME: Possibly have to handle relative redirections,
		   and rewrite Host: headers. Not necessary for now, it's
		   enough for passport authentication like this. */
		
		if( *loc == '/' )
		{
			/* Just a different pathname... */
			
			/* Since we don't cache the servername, and since we
			   don't need this yet anyway, I won't implement it. */
			
			req->status_string = g_strdup( "Can't handle recursive redirects" );
			
			goto cleanup;
		}
		else
		{
			/* A whole URL */
			url_t *url;
			char *s;
			const char *new_method;
			
			s = strstr( loc, "\r\n" );
			if( s == NULL )
				goto cleanup;
			
			url = g_new0( url_t, 1 );
			*s = 0;
			
			if( !url_set( url, loc ) )
			{
				req->status_string = g_strdup( "Malformed redirect URL" );
				g_free( url );
				goto cleanup;
			}
			
			/* Find all headers and, if necessary, the POST request contents.
			   Skip the old Host: header though. This crappy code here means
			   anything using this http_client MUST put the Host: header at
			   the top. */
			if( !( ( s = strstr( req->request, "\r\nHost: " ) ) &&
			       ( s = strstr( s + strlen( "\r\nHost: " ), "\r\n" ) ) ) )
			{
				req->status_string = g_strdup( "Error while rebuilding request string" );
				g_free( url );
				goto cleanup;
			}
			
			/* More or less HTTP/1.0 compliant, from my reading of RFC 2616.
			   Always perform a GET request unless we received a 301. 303 was
			   meant for this but it's HTTP/1.1-only and we're specifically
			   speaking HTTP/1.0. ...
			   
			   Well except someone at identi.ca's didn't bother reading any
			   RFCs and just return HTTP/1.1-specific status codes to HTTP/1.0
			   requests. Fuckers. So here we are, handle 301..303,307. */
			if( strncmp( req->request, "GET", 3 ) == 0 )
				/* GETs never become POSTs. */
				new_method = "GET";
			else if( req->status_code == 302 || req->status_code == 303 )
				/* 302 de-facto becomes GET, 303 as specified by RFC 2616#10.3.3 */
				new_method = "GET";
			else
				/* 301 de-facto should stay POST, 307 specifally RFC 2616#10.3.8 */
				new_method = "POST";
			
			/* Okay, this isn't fun! We have to rebuild the request... :-( */
			new_request = g_strdup_printf( "%s %s HTTP/1.0\r\nHost: %s%s",
			                               new_method, url->file, url->host, s );
			
			new_host = g_strdup( url->host );
			new_port = url->port;
			new_proto = url->proto;
			
			/* If we went from POST to GET, truncate the request content. */
			if( new_request[0] != req->request[0] && new_request[0] == 'G' &&
			    ( s = strstr( new_request, "\r\n\r\n" ) ) )
				s[4] = '\0';
			
			g_free( url );
		}
		
		if( req->ssl )
			ssl_disconnect( req->ssl );
		else
			closesocket( req->fd );
		
		req->fd = -1;
		req->ssl = NULL;
		
		if( getenv( "BITLBEE_DEBUG" ) )
			printf( "New headers for redirected HTTP request:\n%s\n", new_request );
	
		if( new_proto == PROTO_HTTPS )
		{
			req->ssl = ssl_connect( new_host, new_port, TRUE, http_ssl_connected, req );
			if( req->ssl == NULL )
				error = 1;
		}
		else
		{
			req->fd = proxy_connect( new_host, new_port, http_connected, req );
			if( req->fd < 0 )
				error = 1;
		}
		g_free( new_host );
		
		if( error )
		{
			req->status_string = g_strdup( "Connection problem during redirect" );
			g_free( new_request );
			goto cleanup;
		}
		
		g_free( req->request );
		g_free( req->reply_headers );
		req->request = new_request;
		req->request_length = strlen( new_request );
		req->bytes_read = req->bytes_written = req->inpa = 0;
		req->reply_headers = req->reply_body = NULL;
		
		return FALSE;
	}
	
	/* Assume that a closed connection means we're finished, this indeed
	   breaks with keep-alive connections and faulty connections. */
	req->finished = 1;

cleanup:
	if( req->ssl )
		ssl_disconnect( req->ssl );
	else
		closesocket( req->fd );
	
	if( getenv( "BITLBEE_DEBUG" ) && req )
		printf( "Finishing HTTP request with status: %s\n",
		        req->status_string ? req->status_string : "NULL" );
	
	req->func( req );
	http_free( req );
	return FALSE;
}
Exemplo n.º 17
0
unsigned int sockroutine(int s_listen, acetables *g_ape)
{
	int basemem = 512, epoll_fd;

	struct epoll_event ev, *events;

	int new_fd, nfds, sin_size = sizeof(struct sockaddr_in), i;
	
	struct timeval t_start, t_end;	
	unsigned int ticks = 0;
	struct sockaddr_in their_addr;
	
	
	connection *co = xmalloc(sizeof(*co) * basemem);

	epoll_fd = epoll_create(1); /* the param is not used */
	
	if (epoll_fd < 0) {
		printf("[ERR] Not enougth memory\n");
		exit(0);		
	}
	
	g_ape->epoll_fd = &epoll_fd;
	
	events = xmalloc(sizeof(*events) * basemem);
	
	g_ape->bufout = xmalloc(sizeof(struct _socks_bufout) * basemem);

	setnonblocking(s_listen);
	
	ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
	ev.data.fd = s_listen;
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, s_listen, &ev);
	
	while (1) {
		
		/* Linux 2.6.25 provide a fd-driven timer system. It could be usefull to implement */
		gettimeofday(&t_start, NULL);
		
		nfds = epoll_wait(epoll_fd, events, basemem, (1000/TICKS_RATE)-ticks);
		
		if (nfds < 0) {
			continue;
		}
		if (nfds > 0) {
			
			for (i = 0; i < nfds; i++) {

				if (events[i].data.fd == s_listen) {
				
					while (1) {
						struct epoll_event cev;
						http_state http = {0, HTTP_NULL, 0, -1, 0, 0, 0};
					
						new_fd = accept(s_listen, 
							(struct sockaddr *)&their_addr, 
							(unsigned int *)&sin_size);
					
						if (new_fd == -1) {
							break;
						}
						
						if (new_fd + 4 == basemem) {
							/* Increase connection & events size */
							growup(&basemem, &co, &events, &g_ape->bufout);
						}

						strncpy(co[new_fd].ip_client, inet_ntoa(their_addr.sin_addr), 16);
						
						co[new_fd].buffer.data = xmalloc(sizeof(char) * (DEFAULT_BUFFER_SIZE + 1));
						co[new_fd].buffer.size = DEFAULT_BUFFER_SIZE;
						co[new_fd].buffer.length = 0;
					
						co[new_fd].http = http;
						co[new_fd].attach = NULL;
						
						co[new_fd].stream_type = STREAM_IN;
					
						g_ape->bufout[new_fd].fd = new_fd;
						g_ape->bufout[new_fd].buf = NULL;
						g_ape->bufout[new_fd].buflen = 0;
						g_ape->bufout[new_fd].allocsize = 0;
						
						setnonblocking(new_fd);

						cev.events = EPOLLIN | EPOLLET | EPOLLPRI | EPOLLOUT;
						cev.data.fd = new_fd;
					
						epoll_ctl(epoll_fd, EPOLL_CTL_ADD, new_fd, &cev);
						
					
					}
					continue;
				} else {
					int readb = 0;
					
					if (events[i].events & EPOLLOUT) {
						if (co[events[i].data.fd].stream_type == STREAM_OUT && 
						((ape_proxy *)(co[events[i].data.fd].attach))->state == PROXY_IN_PROGRESS) {
							int serror = 0, ret;
							socklen_t serror_len = sizeof(serror);
						
							ret = getsockopt(events[i].data.fd, SOL_SOCKET, SO_ERROR, &serror, &serror_len);
							
							if (ret == 0 && serror == 0) {
								((ape_proxy *)(co[events[i].data.fd].attach))->state = PROXY_CONNECTED;
								((ape_proxy *)(co[events[i].data.fd].attach))->sock.fd = events[i].data.fd;
								proxy_onevent((ape_proxy *)(co[events[i].data.fd].attach), "CONNECT", g_ape);
							} else { /* This can be happen ? epoll seems set EPOLLIN as if the host is disconnecting */
								((ape_proxy *)(co[events[i].data.fd].attach))->state = PROXY_THROTTLED;
								//epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
								clear_buffer(&co[events[i].data.fd]);
								close(events[i].data.fd);
							}

						} else if (co[events[i].data.fd].stream_type == STREAM_IN && g_ape->bufout[events[i].data.fd].buf != NULL) {

							if (sendqueue(events[i].data.fd, g_ape) == 1) {
								if (co[events[i].data.fd].attach != NULL && ((subuser *)(co[events[i].data.fd].attach))->burn_after_writing) {
									do_died((subuser *)(co[events[i].data.fd].attach));
									((subuser *)(co[events[i].data.fd].attach))->burn_after_writing = 0;
								}
							}
						}
					}
					if (events[i].events & EPOLLIN) {
						do {
							/*
								TODO : Check if maximum data read can improve perf
								Huge data may attempt to increase third parameter
							*/
							readb = read(events[i].data.fd, 
										co[events[i].data.fd].buffer.data + co[events[i].data.fd].buffer.length, 
										co[events[i].data.fd].buffer.size - co[events[i].data.fd].buffer.length);
						
						
							if (readb == -1 && errno == EAGAIN) {
							
								/*
									Nothing to read again
								*/
							
								if (co[events[i].data.fd].stream_type == STREAM_OUT) {
									
										proxy_process_eol(&co[events[i].data.fd], g_ape);
										co[events[i].data.fd].buffer.length = 0;
								} else {
									co[events[i].data.fd].buffer.data[co[events[i].data.fd].buffer.length] = '\0';
								}
								break;
							} else {
								if (readb < 1) {

									#if 0
									TODO :
									if (events[i].events & EPOLLRDHUP) {
										/* 
										   Client hangup the connection (half-closed)
										*/
									}
									#endif
									if (co[events[i].data.fd].stream_type == STREAM_IN && co[events[i].data.fd].attach != NULL) {
									
										if (events[i].data.fd == ((subuser *)(co[events[i].data.fd].attach))->fd) {
											((subuser *)(co[events[i].data.fd].attach))->headers_sent = 0;
											((subuser *)(co[events[i].data.fd].attach))->state = ADIED;
										}
										if (((subuser *)(co[events[i].data.fd].attach))->wait_for_free == 1) {
											free(co[events[i].data.fd].attach);
											co[events[i].data.fd].attach = NULL;						
										}
									} else if (co[events[i].data.fd].stream_type == STREAM_OUT) {
									
										if (((ape_proxy *)(co[events[i].data.fd].attach))->state == PROXY_TOFREE) {
											free(co[events[i].data.fd].attach);
											co[events[i].data.fd].attach = NULL;								
										} else {
									
											((ape_proxy *)(co[events[i].data.fd].attach))->state = PROXY_THROTTLED;
											proxy_onevent((ape_proxy *)(co[events[i].data.fd].attach), "DISCONNECT", g_ape);
										}
									}
								
									clear_buffer(&co[events[i].data.fd]);
								
									if (g_ape->bufout[events[i].data.fd].buf != NULL) {
										free(g_ape->bufout[events[i].data.fd].buf);
										g_ape->bufout[events[i].data.fd].buflen = 0;
										g_ape->bufout[events[i].data.fd].buf = NULL;
										g_ape->bufout[events[i].data.fd].allocsize = 0;
									}
									
									close(events[i].data.fd);
							
									break;
								} else if (co[events[i].data.fd].http.ready != -1) {
									co[events[i].data.fd].buffer.length += readb;

									if (co[events[i].data.fd].buffer.length == co[events[i].data.fd].buffer.size) {
										co[events[i].data.fd].buffer.size *= 2;
										co[events[i].data.fd].buffer.data = xrealloc(co[events[i].data.fd].buffer.data, 
																sizeof(char) * (co[events[i].data.fd].buffer.size + 1));
									
									}
									if (co[events[i].data.fd].stream_type == STREAM_IN) {
										process_http(&co[events[i].data.fd]);
								
										if (co[events[i].data.fd].http.ready == 1) {
											co[events[i].data.fd].attach = checkrecv(co[events[i].data.fd].buffer.data, 
																events[i].data.fd, g_ape, co[events[i].data.fd].ip_client);
									
											co[events[i].data.fd].buffer.length = 0;
											co[events[i].data.fd].http.ready = -1;
			
										} else if (co[events[i].data.fd].http.error == 1) {
											shutdown(events[i].data.fd, 2);
										}
									}
								}
						
							}
					
						} while(readb >= 0);
					}
				}			
			}
		}
		
		gettimeofday(&t_end, NULL);

		ticks += (1000*(t_end.tv_sec - t_start.tv_sec))+((t_end.tv_usec - t_start.tv_usec)/1000);
		
		/* Tic tac, tic tac :-) */
		if (ticks >= 1000/TICKS_RATE) {
			ape_proxy *proxy = g_ape->proxy.list;
			int psock;
			
			ticks = 0;
			
			while (proxy != NULL) {

				if (proxy->state == PROXY_NOT_CONNECTED && ((psock = proxy_connect(proxy, g_ape)) != 0)) {
					http_state http_s = {0, HTTP_NULL, 0, -1, 0, 0, 0};
					if (psock + 4 == basemem) {
						growup(&basemem, &co, &events, &g_ape->bufout);
					}
					co[psock].ip_client[0] = '\0';
					co[psock].buffer.data = xmalloc(sizeof(char) * (DEFAULT_BUFFER_SIZE + 1));
					co[psock].buffer.size = DEFAULT_BUFFER_SIZE;
					co[psock].buffer.length = 0;
				
					co[psock].http = http_s;
					co[psock].attach = proxy;
					co[psock].stream_type = STREAM_OUT;
				}


				proxy = proxy->next;
			}
			
			process_tick(g_ape);
		}                

	}

	close(epoll_fd);
	return 0;
}
Exemplo n.º 18
0
/*
 * Retrieve URL, via the proxy in $proxyvar if necessary.
 * Modifies the string argument given.
 * Returns -1 on failure, 0 on success
 */
static int
url_get(const char *origline, const char *proxyenv, const char *outfile)
{
	char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
	char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
	char *epath, *redirurl, *loctail, *h, *p;
	int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1;
	struct addrinfo hints, *res0, *res, *ares = NULL;
	const char * volatile savefile;
	char * volatile proxyurl = NULL;
	char *cookie = NULL;
	volatile int s = -1, out;
	volatile sig_t oldintr, oldinti;
	FILE *fin = NULL;
	off_t hashbytes;
	const char *errstr;
	ssize_t len, wlen;
#ifndef SMALL
	char *sslpath = NULL, *sslhost = NULL;
	char *locbase, *full_host = NULL, *auth = NULL;
	const char *scheme;
	int ishttpsurl = 0;
	SSL_CTX *ssl_ctx = NULL;
#endif /* !SMALL */
	SSL *ssl = NULL;
	int status;
	int save_errno;
	const size_t buflen = 128 * 1024;

	direction = "received";

	newline = strdup(origline);
	if (newline == NULL)
		errx(1, "Can't allocate memory to parse URL");
	if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
		host = newline + sizeof(HTTP_URL) - 1;
#ifndef SMALL
		scheme = HTTP_URL;
#endif /* !SMALL */
	} else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
		host = newline + sizeof(FTP_URL) - 1;
		isftpurl = 1;
#ifndef SMALL
		scheme = FTP_URL;
#endif /* !SMALL */
	} else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
		host = newline + sizeof(FILE_URL) - 1;
		isfileurl = 1;
#ifndef SMALL
		scheme = FILE_URL;
	} else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
		host = newline + sizeof(HTTPS_URL) - 1;
		ishttpsurl = 1;
		scheme = HTTPS_URL;
#endif /* !SMALL */
	} else
		errx(1, "url_get: Invalid URL '%s'", newline);

	if (isfileurl) {
		path = host;
	} else {
		path = strchr(host, '/');		/* Find path */
		if (EMPTYSTRING(path)) {
			if (outfile) {			/* No slash, but */
				path=strchr(host,'\0');	/* we have outfile. */
				goto noslash;
			}
			if (isftpurl)
				goto noftpautologin;
			warnx("No `/' after host (use -o): %s", origline);
			goto cleanup_url_get;
		}
		*path++ = '\0';
		if (EMPTYSTRING(path) && !outfile) {
			if (isftpurl)
				goto noftpautologin;
			warnx("No filename after host (use -o): %s", origline);
			goto cleanup_url_get;
		}
	}

noslash:

#ifndef SMALL
	/*
	 * Look for auth header in host, since now host does not
	 * contain the path. Basic auth from RFC 2617, valid
	 * characters for path are in RFC 3986 section 3.3.
	 */
	if (proxyenv == NULL &&
	    (!strcmp(scheme, HTTP_URL) || !strcmp(scheme, HTTPS_URL))) {
		if ((p = strchr(host, '@')) != NULL) {
			size_t authlen = (strlen(host) + 5) * 4 / 3;
			*p = 0;	/* Kill @ */
			if ((auth = malloc(authlen)) == NULL)
				err(1, "Can't allocate memory for "
				    "authorization");
			if (b64_ntop(host, strlen(host),
			    auth, authlen) == -1)
				errx(1, "error in base64 encoding");
			host = p + 1;
		}
	}
#endif	/* SMALL */

	if (outfile)
		savefile = outfile;
	else {
		if (path[strlen(path) - 1] == '/')	/* Consider no file */
			savefile = NULL;		/* after dir invalid. */
		else
			savefile = basename(path);
	}

	if (EMPTYSTRING(savefile)) {
		if (isftpurl)
			goto noftpautologin;
		warnx("No filename after directory (use -o): %s", origline);
		goto cleanup_url_get;
	}

#ifndef SMALL
	if (resume && pipeout) {
		warnx("can't append to stdout");
		goto cleanup_url_get;
	}
#endif /* !SMALL */

	if (!isfileurl && proxyenv != NULL) {		/* use proxy */
#ifndef SMALL
		if (ishttpsurl) {
			sslpath = strdup(path);
			sslhost = strdup(host);
			if (! sslpath || ! sslhost)
				errx(1, "Can't allocate memory for https path/host.");
		}
#endif /* !SMALL */
		proxyurl = strdup(proxyenv);
		if (proxyurl == NULL)
			errx(1, "Can't allocate memory for proxy URL.");
		if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
			host = proxyurl + sizeof(HTTP_URL) - 1;
		else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
			host = proxyurl + sizeof(FTP_URL) - 1;
		else {
			warnx("Malformed proxy URL: %s", proxyenv);
			goto cleanup_url_get;
		}
		if (EMPTYSTRING(host)) {
			warnx("Malformed proxy URL: %s", proxyenv);
			goto cleanup_url_get;
		}
		if (*--path == '\0')
			*path = '/';		/* add / back to real path */
		path = strchr(host, '/');	/* remove trailing / on host */
		if (!EMPTYSTRING(path))
			*path++ = '\0';		/* i guess this ++ is useless */

		path = strchr(host, '@');	/* look for credentials in proxy */
		if (!EMPTYSTRING(path)) {
			*path = '\0';
			cookie = strchr(host, ':');
			if (EMPTYSTRING(cookie)) {
				warnx("Malformed proxy URL: %s", proxyenv);
				goto cleanup_url_get;
			}
			cookie  = malloc(COOKIE_MAX_LEN);
			if (cookie == NULL)
				errx(1, "out of memory");
			if (b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN) == -1)
				errx(1, "error in base64 encoding");
			*path = '@'; /* restore @ in proxyurl */
			/*
			 * This removes the password from proxyurl,
			 * filling with stars
			 */
			for (host = 1 + strchr(proxyurl + 5, ':');  *host != '@';
			     host++)
				*host = '*';

			host = path + 1;
		}
		path = newline;
	}

	if (isfileurl) {
		struct stat st;

		s = open(path, O_RDONLY);
		if (s == -1) {
			warn("Can't open file %s", path);
			goto cleanup_url_get;
		}

		if (fstat(s, &st) == -1)
			filesize = -1;
		else
			filesize = st.st_size;

		/* Open the output file.  */
		if (!pipeout) {
#ifndef SMALL
			if (resume)
				out = open(savefile, O_CREAT | O_WRONLY |
					O_APPEND, 0666);

			else
#endif /* !SMALL */
				out = open(savefile, O_CREAT | O_WRONLY |
					O_TRUNC, 0666);
			if (out < 0) {
				warn("Can't open %s", savefile);
				goto cleanup_url_get;
			}
		} else
			out = fileno(stdout);

#ifndef SMALL
		if (resume) {
			if (fstat(out, &st) == -1) {
				warn("Can't fstat %s", savefile);
				goto cleanup_url_get;
			}
			if (lseek(s, st.st_size, SEEK_SET) == -1) {
				warn("Can't lseek %s", path);
				goto cleanup_url_get;
			}
			restart_point = st.st_size;
		}
#endif /* !SMALL */

		/* Trap signals */
		oldintr = NULL;
		oldinti = NULL;
		if (setjmp(httpabort)) {
			if (oldintr)
				(void)signal(SIGINT, oldintr);
			if (oldinti)
				(void)signal(SIGINFO, oldinti);
			goto cleanup_url_get;
		}
		oldintr = signal(SIGINT, abortfile);

		bytes = 0;
		hashbytes = mark;
		progressmeter(-1, path);

		if ((buf = malloc(buflen)) == NULL)
			errx(1, "Can't allocate memory for transfer buffer");

		/* Finally, suck down the file. */
		i = 0;
		oldinti = signal(SIGINFO, psummary);
		while ((len = read(s, buf, buflen)) > 0) {
			bytes += len;
			for (cp = buf; len > 0; len -= i, cp += i) {
				if ((i = write(out, cp, len)) == -1) {
					warn("Writing %s", savefile);
					signal(SIGINFO, oldinti);
					goto cleanup_url_get;
				}
				else if (i == 0)
					break;
			}
			if (hash && !progress) {
				while (bytes >= hashbytes) {
					(void)putc('#', ttyout);
					hashbytes += mark;
				}
				(void)fflush(ttyout);
			}
		}
		signal(SIGINFO, oldinti);
		if (hash && !progress && bytes > 0) {
			if (bytes < mark)
				(void)putc('#', ttyout);
			(void)putc('\n', ttyout);
			(void)fflush(ttyout);
		}
		if (len != 0) {
			warn("Reading from file");
			goto cleanup_url_get;
		}
		progressmeter(1, NULL);
		if (verbose)
			ptransfer(0);
		(void)signal(SIGINT, oldintr);

		rval = 0;
		goto cleanup_url_get;
	}

	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
	    (hosttail[1] == '\0' || hosttail[1] == ':')) {
		host++;
		*hosttail++ = '\0';
#ifndef SMALL
		if (asprintf(&full_host, "[%s]", host) == -1)
			errx(1, "Cannot allocate memory for hostname");
#endif /* !SMALL */
	} else
		hosttail = host;

	portnum = strrchr(hosttail, ':');		/* find portnum */
	if (portnum != NULL)
		*portnum++ = '\0';

#ifndef SMALL
	if (full_host == NULL)
		if ((full_host = strdup(host)) == NULL)
			errx(1, "Cannot allocate memory for hostname");
	if (debug)
		fprintf(ttyout, "host %s, port %s, path %s, "
		    "save as %s, auth %s.\n",
		    host, portnum, path, savefile, auth);
#endif /* !SMALL */

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = family;
	hints.ai_socktype = SOCK_STREAM;
#ifndef SMALL
	port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
#else /* !SMALL */
	port = portnum ? portnum : httpport;
#endif /* !SMALL */
	error = getaddrinfo(host, port, &hints, &res0);
	/*
	 * If the services file is corrupt/missing, fall back
	 * on our hard-coded defines.
	 */
	if (error == EAI_SERVICE && port == httpport) {
		snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
		error = getaddrinfo(host, pbuf, &hints, &res0);
#ifndef SMALL
	} else if (error == EAI_SERVICE && port == httpsport) {
		snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
		error = getaddrinfo(host, pbuf, &hints, &res0);
#endif /* !SMALL */
	}
	if (error) {
		warnx("%s: %s", gai_strerror(error), host);
		goto cleanup_url_get;
	}

#ifndef SMALL
	if (srcaddr) {
		hints.ai_flags |= AI_NUMERICHOST;
		error = getaddrinfo(srcaddr, NULL, &hints, &ares);
		if (error) {
			warnx("%s: %s", gai_strerror(error), srcaddr);
			goto cleanup_url_get;
		}
	}
#endif /* !SMALL */

	s = -1;
	for (res = res0; res; res = res->ai_next) {
		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
			strlcpy(hbuf, "(unknown)", sizeof(hbuf));
		if (verbose)
			fprintf(ttyout, "Trying %s...\n", hbuf);

		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
		if (s == -1) {
			cause = "socket";
			continue;
		}

#ifndef SMALL
		if (srcaddr) {
			if (ares->ai_family != res->ai_family) {
				close(s);
				s = -1;
				errno = EINVAL;
				cause = "bind";
				continue;
			}
			if (bind(s, ares->ai_addr, ares->ai_addrlen) < 0) {
				save_errno = errno;
				close(s);
				errno = save_errno;
				s = -1;
				cause = "bind";
				continue;
			}
		}
#endif /* !SMALL */

again:
		if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
			if (errno == EINTR)
				goto again;
			save_errno = errno;
			close(s);
			errno = save_errno;
			s = -1;
			cause = "connect";
			continue;
		}

		/* get port in numeric */
		if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
		    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
			port = pbuf;
		else
			port = NULL;

#ifndef SMALL
		if (proxyenv && sslhost)
			proxy_connect(s, sslhost, cookie);
#endif /* !SMALL */
		break;
	}
	freeaddrinfo(res0);
#ifndef SMALL
	if (srcaddr)
		freeaddrinfo(ares);
#endif /* !SMALL */
	if (s < 0) {
		warn("%s", cause);
		goto cleanup_url_get;
	}

#ifndef SMALL
	if (ishttpsurl) {
		union { struct in_addr ip4; struct in6_addr ip6; } addrbuf;

		if (proxyenv && sslpath) {
			ishttpsurl = 0;
			proxyurl = NULL;
			path = sslpath;
		}
		SSL_library_init();
		SSL_load_error_strings();
		ssl_ctx = SSL_CTX_new(SSLv23_client_method());
		if (ssl_ctx == NULL) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		if (ssl_verify) {
			if (ssl_ca_file == NULL && ssl_ca_path == NULL)
				ssl_ca_file = _PATH_SSL_CAFILE;
			if (SSL_CTX_load_verify_locations(ssl_ctx,
			    ssl_ca_file, ssl_ca_path) != 1) {
				ERR_print_errors_fp(ttyout);
				goto cleanup_url_get;
			}
			SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
			if (ssl_verify_depth != -1)
				SSL_CTX_set_verify_depth(ssl_ctx,
				    ssl_verify_depth);
		}
		if (ssl_ciphers != NULL &&
		    SSL_CTX_set_cipher_list(ssl_ctx, ssl_ciphers) == -1) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		ssl = SSL_new(ssl_ctx);
		if (ssl == NULL) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		if (SSL_set_fd(ssl, s) == 0) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		/*
		 * RFC4366 (SNI): Literal IPv4 and IPv6 addresses are not
		 * permitted in "HostName".
		 */
		if (inet_pton(AF_INET,  host, &addrbuf) != 1 &&
		    inet_pton(AF_INET6, host, &addrbuf) != 1) {
			if (SSL_set_tlsext_host_name(ssl, host) == 0) {
				ERR_print_errors_fp(ttyout);
				goto cleanup_url_get;
			}
		}
		if (SSL_connect(ssl) <= 0) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		if (ssl_verify) {
			X509	*cert;

			cert = SSL_get_peer_certificate(ssl);
			if (cert == NULL) {
				fprintf(ttyout, "%s: no server certificate\n",
				    getprogname());
				goto cleanup_url_get;
			}

			if (ssl_check_hostname(cert, host) != 0) {
				fprintf(ttyout, "%s: host `%s' not present in"
				    " server certificate\n",
				    getprogname(), host);
				goto cleanup_url_get;
			}

			X509_free(cert);
		}
	} else {
		fin = fdopen(s, "r+");
	}
#else /* !SMALL */
	fin = fdopen(s, "r+");
#endif /* !SMALL */

	if (verbose)
		fprintf(ttyout, "Requesting %s", origline);

	/*
	 * Construct and send the request. Proxy requests don't want leading /.
	 */
#ifndef SMALL
	cookie_get(host, path, ishttpsurl, &buf);
#endif /* !SMALL */

	epath = url_encode(path);
	if (proxyurl) {
		if (verbose)
			fprintf(ttyout, " (via %s)\n", proxyurl);
		/*
		 * Host: directive must use the destination host address for
		 * the original URI (path).  We do not attach it at this moment.
		 */
		if (cookie)
			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n"
			    "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n",
			    epath, cookie, buf ? buf : "", HTTP_USER_AGENT);
		else
			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n",
			    epath, buf ? buf : "", HTTP_USER_AGENT);

	} else {
#ifndef SMALL
		if (resume) {
			struct stat stbuf;

			if (stat(savefile, &stbuf) == 0)
				restart_point = stbuf.st_size;
			else
				restart_point = 0;
		}
		if (auth) {
			ftp_printf(fin, ssl,
			    "GET /%s %s\r\nAuthorization: Basic %s\r\nHost: ",
			    epath, restart_point ?
			    "HTTP/1.1\r\nConnection: close" : "HTTP/1.0",
			    auth);
			free(auth);
			auth = NULL;
		} else
#endif	/* SMALL */
			ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", epath,
#ifndef SMALL
			    restart_point ? "HTTP/1.1\r\nConnection: close" :
#endif /* !SMALL */
			    "HTTP/1.0");
		if (strchr(host, ':')) {
			/*
			 * strip off scoped address portion, since it's
			 * local to node
			 */
			h = strdup(host);
			if (h == NULL)
				errx(1, "Can't allocate memory.");
			if ((p = strchr(h, '%')) != NULL)
				*p = '\0';
			ftp_printf(fin, ssl, "[%s]", h);
			free(h);
		} else
			ftp_printf(fin, ssl, "%s", host);

		/*
		 * Send port number only if it's specified and does not equal
		 * 80. Some broken HTTP servers get confused if you explicitly
		 * send them the port number.
		 */
#ifndef SMALL
		if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
			ftp_printf(fin, ssl, ":%s", port);
		if (restart_point)
			ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-",
				(long long)restart_point);
#else /* !SMALL */
		if (port && strcmp(port, "80") != 0)
			ftp_printf(fin, ssl, ":%s", port);
#endif /* !SMALL */
		ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n",
		    buf ? buf : "", HTTP_USER_AGENT);
		if (verbose)
			fprintf(ttyout, "\n");
	}
	free(epath);

#ifndef SMALL
	free(buf);
#endif /* !SMALL */
	buf = NULL;

	if (fin != NULL && fflush(fin) == EOF) {
		warn("Writing HTTP request");
		goto cleanup_url_get;
	}
	if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
		warn("Receiving HTTP reply");
		goto cleanup_url_get;
	}

	while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
		buf[--len] = '\0';
#ifndef SMALL
	if (debug)
		fprintf(ttyout, "received '%s'\n", buf);
#endif /* !SMALL */

	cp = strchr(buf, ' ');
	if (cp == NULL)
		goto improper;
	else
		cp++;

	strlcpy(ststr, cp, sizeof(ststr));
	status = strtonum(ststr, 200, 416, &errstr);
	if (errstr) {
		warnx("Error retrieving file: %s", cp);
		goto cleanup_url_get;
	}

	switch (status) {
	case 200:	/* OK */
#ifndef SMALL
		/*
		 * When we request a partial file, and we receive an HTTP 200
		 * it is a good indication that the server doesn't support
		 * range requests, and is about to send us the entire file.
		 * If the restart_point == 0, then we are not actually
		 * requesting a partial file, and an HTTP 200 is appropriate.
		 */
		if (resume && restart_point != 0) {
			warnx("Server does not support resume.");
			restart_point = resume = 0;
		}
		/* FALLTHROUGH */
	case 206:	/* Partial Content */
#endif /* !SMALL */
		break;
	case 301:	/* Moved Permanently */
	case 302:	/* Found */
	case 303:	/* See Other */
	case 307:	/* Temporary Redirect */
		isredirect++;
		if (redirect_loop++ > 10) {
			warnx("Too many redirections requested");
			goto cleanup_url_get;
		}
		break;
#ifndef SMALL
	case 416:	/* Requested Range Not Satisfiable */
		warnx("File is already fully retrieved.");
		goto cleanup_url_get;
#endif /* !SMALL */
	default:
		warnx("Error retrieving file: %s", cp);
		goto cleanup_url_get;
	}

	/*
	 * Read the rest of the header.
	 */
	free(buf);
	filesize = -1;

	for (;;) {
		if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
			warn("Receiving HTTP reply");
			goto cleanup_url_get;
		}

		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
			buf[--len] = '\0';
		if (len == 0)
			break;
#ifndef SMALL
		if (debug)
			fprintf(ttyout, "received '%s'\n", buf);
#endif /* !SMALL */

		/* Look for some headers */
		cp = buf;
#define CONTENTLEN "Content-Length: "
		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
			size_t s;
			cp += sizeof(CONTENTLEN) - 1;
			if ((s = strcspn(cp, " \t")))
				*(cp+s) = 0;
			filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
			if (errstr != NULL)
				goto improper;
#ifndef SMALL
			if (restart_point)
				filesize += restart_point;
#endif /* !SMALL */
#define LOCATION "Location: "
		} else if (isredirect &&
		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
			cp += sizeof(LOCATION) - 1;
			if (strstr(cp, "://") == NULL) {
#ifdef SMALL
				errx(1, "Relative redirect not supported");
#else /* SMALL */
				if (*cp == '/') {
					locbase = NULL;
					cp++;
				} else {
					locbase = strdup(path);
					if (locbase == NULL)
						errx(1, "Can't allocate memory"
						    " for location base");
					loctail = strchr(locbase, '#');
					if (loctail != NULL)
						*loctail = '\0';
					loctail = strchr(locbase, '?');
					if (loctail != NULL)
						*loctail = '\0';
					loctail = strrchr(locbase, '/');
					if (loctail == NULL) {
						free(locbase);
						locbase = NULL;
					} else
						loctail[1] = '\0';
				}
				/* Contruct URL from relative redirect */
				if (asprintf(&redirurl, "%s%s%s%s/%s%s",
				    scheme, full_host,
				    portnum ? ":" : "",
				    portnum ? portnum : "",
				    locbase ? locbase : "",
				    cp) == -1)
					errx(1, "Cannot build "
					    "redirect URL");
				free(locbase);
#endif /* SMALL */
			} else if ((redirurl = strdup(cp)) == NULL)
				errx(1, "Cannot allocate memory for URL");
			loctail = strchr(redirurl, '#');
			if (loctail != NULL)
				*loctail = '\0';
			if (verbose)
				fprintf(ttyout, "Redirected to %s\n", redirurl);
			if (fin != NULL)
				fclose(fin);
			else if (s != -1)
				close(s);
			rval = url_get(redirurl, proxyenv, savefile);
			free(redirurl);
			goto cleanup_url_get;
		}
		free(buf);
	}

	/* Open the output file.  */
	if (!pipeout) {
#ifndef SMALL
		if (resume)
			out = open(savefile, O_CREAT | O_WRONLY | O_APPEND,
				0666);
		else
#endif /* !SMALL */
			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
				0666);
		if (out < 0) {
			warn("Can't open %s", savefile);
			goto cleanup_url_get;
		}
	} else
		out = fileno(stdout);

	/* Trap signals */
	oldintr = NULL;
	oldinti = NULL;
	if (setjmp(httpabort)) {
		if (oldintr)
			(void)signal(SIGINT, oldintr);
		if (oldinti)
			(void)signal(SIGINFO, oldinti);
		goto cleanup_url_get;
	}
	oldintr = signal(SIGINT, aborthttp);

	bytes = 0;
	hashbytes = mark;
	progressmeter(-1, path);

	free(buf);

	/* Finally, suck down the file. */
	if ((buf = malloc(buflen)) == NULL)
		errx(1, "Can't allocate memory for transfer buffer");
	i = 0;
	len = 1;
	oldinti = signal(SIGINFO, psummary);
	while (len > 0) {
		len = ftp_read(fin, ssl, buf, buflen);
		bytes += len;
		for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
			if ((i = write(out, cp, wlen)) == -1) {
				warn("Writing %s", savefile);
				signal(SIGINFO, oldinti);
				goto cleanup_url_get;
			}
			else if (i == 0)
				break;
		}
		if (hash && !progress) {
			while (bytes >= hashbytes) {
				(void)putc('#', ttyout);
				hashbytes += mark;
			}
			(void)fflush(ttyout);
		}
	}
	signal(SIGINFO, oldinti);
	if (hash && !progress && bytes > 0) {
		if (bytes < mark)
			(void)putc('#', ttyout);
		(void)putc('\n', ttyout);
		(void)fflush(ttyout);
	}
	if (len != 0) {
		warn("Reading from socket");
		goto cleanup_url_get;
	}
	progressmeter(1, NULL);
	if (
#ifndef SMALL
		!resume &&
#endif /* !SMALL */
		filesize != -1 && len == 0 && bytes != filesize) {
		if (verbose)
			fputs("Read short file.\n", ttyout);
		goto cleanup_url_get;
	}

	if (verbose)
		ptransfer(0);
	(void)signal(SIGINT, oldintr);

	rval = 0;
	goto cleanup_url_get;

noftpautologin:
	warnx(
	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
	goto cleanup_url_get;

improper:
	warnx("Improper response from %s", host);

cleanup_url_get:
#ifndef SMALL
	if (ssl) {
		SSL_shutdown(ssl);
		SSL_free(ssl);
	}
	free(full_host);
	free(auth);
#endif /* !SMALL */
	if (fin != NULL)
		fclose(fin);
	else if (s != -1)
		close(s);
	free(buf);
	free(proxyurl);
	free(newline);
	free(cookie);
	return (rval);
}
Exemplo n.º 19
0
static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, int timeout)
{
	int sockfd = 0;
	int status = 0;
	BIO* socketBio = NULL;
	BIO* bufferedBio = NULL;
	rdpSettings* settings = rdg->settings;
	const char* peerHostname = settings->GatewayHostname;
	UINT16 peerPort = settings->GatewayPort;
	const char* proxyUsername, *proxyPassword;
	BOOL isProxyConnection = proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername,
	                                       &proxyPassword);
	sockfd = freerdp_tcp_connect(rdg->context, settings,
	                             peerAddress ? peerAddress : peerHostname,
	                             peerPort, timeout);

	if (sockfd < 0)
	{
		return FALSE;
	}

	socketBio = BIO_new(BIO_s_simple_socket());

	if (!socketBio)
	{
		closesocket(sockfd);
		return FALSE;
	}

	BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
	bufferedBio = BIO_new(BIO_s_buffered_socket());

	if (!bufferedBio)
	{
		closesocket(sockfd);
		BIO_free(socketBio);
		return FALSE;
	}

	bufferedBio = BIO_push(bufferedBio, socketBio);
	status = BIO_set_nonblock(bufferedBio, TRUE);

	if (isProxyConnection)
	{
		if (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword, settings->GatewayHostname,
		                   settings->GatewayPort))
			return FALSE;
	}

	if (!status)
	{
		BIO_free_all(bufferedBio);
		return FALSE;
	}

	tls->hostname = settings->GatewayHostname;
	tls->port = settings->GatewayPort;
	tls->isGatewayTransport = TRUE;
	status = tls_connect(tls, bufferedBio);
	return (status >= 1);
}
Exemplo n.º 20
0
/*
 * Retrieve URL, via the proxy in $proxyvar if necessary.
 * Modifies the string argument given.
 * Returns -1 on failure, 0 on success
 */
static int
url_get(const char *origline, const char *proxyenv, const char *outfile)
{
	char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4];
	char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL;
	int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1;
	struct addrinfo hints, *res0, *res;
	const char * volatile savefile;
	char * volatile proxyurl = NULL;
	char *cookie = NULL;
	volatile int s = -1, out;
	volatile sig_t oldintr;
	FILE *fin = NULL;
	off_t hashbytes;
	const char *errstr;
	size_t len, wlen;
#ifndef SMALL
	char *sslpath = NULL, *sslhost = NULL;
	int ishttpsurl = 0;
	SSL_CTX *ssl_ctx = NULL;
#endif /* !SMALL */
	SSL *ssl = NULL;
	int status;

	newline = strdup(origline);
	if (newline == NULL)
		errx(1, "Can't allocate memory to parse URL");
	if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
		host = newline + sizeof(HTTP_URL) - 1;
	else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
		host = newline + sizeof(FTP_URL) - 1;
		isftpurl = 1;
	} else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
		host = newline + sizeof(FILE_URL) - 1;
		isfileurl = 1;
#ifndef SMALL
	} else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) {
		host = newline + sizeof(HTTPS_URL) - 1;
		ishttpsurl = 1;
#endif /* !SMALL */
	} else
		errx(1, "url_get: Invalid URL '%s'", newline);

	if (isfileurl) {
		path = host;
	} else {
		path = strchr(host, '/');		/* find path */
		if (EMPTYSTRING(path)) {
			if (isftpurl)
				goto noftpautologin;
			warnx("Invalid URL (no `/' after host): %s", origline);
			goto cleanup_url_get;
		}
		*path++ = '\0';
		if (EMPTYSTRING(path)) {
			if (isftpurl)
				goto noftpautologin;
			warnx("Invalid URL (no file after host): %s", origline);
			goto cleanup_url_get;
		}
	}

	if (outfile)
		savefile = outfile;
	else
		savefile = basename(path);

#ifndef SMALL
	if (resume && (strcmp(savefile, "-") == 0)) {
		warnx("can't append to stdout");
		goto cleanup_url_get;
	}
#endif /* !SMALL */

	if (EMPTYSTRING(savefile)) {
		if (isftpurl)
			goto noftpautologin;
		warnx("Invalid URL (no file after directory): %s", origline);
		goto cleanup_url_get;
	}

	if (!isfileurl && proxyenv != NULL) {		/* use proxy */
#ifndef SMALL
		if (ishttpsurl) {
			sslpath = strdup(path);
			sslhost = strdup(host);
			if (! sslpath || ! sslhost)
				errx(1, "Can't allocate memory for https path/host.");
		}
#endif /* !SMALL */
		proxyurl = strdup(proxyenv);
		if (proxyurl == NULL)
			errx(1, "Can't allocate memory for proxy URL.");
		if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
			host = proxyurl + sizeof(HTTP_URL) - 1;
		else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0)
			host = proxyurl + sizeof(FTP_URL) - 1;
		else {
			warnx("Malformed proxy URL: %s", proxyenv);
			goto cleanup_url_get;
		}
		if (EMPTYSTRING(host)) {
			warnx("Malformed proxy URL: %s", proxyenv);
			goto cleanup_url_get;
		}
		*--path = '/';			/* add / back to real path */
		path = strchr(host, '/');	/* remove trailing / on host */
		if (!EMPTYSTRING(path))
			*path++ = '\0';		/* i guess this ++ is useless */

		path = strchr(host, '@');	/* look for credentials in proxy */
		if (!EMPTYSTRING(path)) {
			*path++ = '\0';
			cookie = strchr(host, ':');
			if (EMPTYSTRING(cookie)) {
				warnx("Malformed proxy URL: %s", proxyenv);
				goto cleanup_url_get;
			}
			cookie  = malloc(COOKIE_MAX_LEN);
			b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN);
			/*
			 * This removes the password from proxyenv,
			 * filling with stars
			 */
			for (host = strchr(proxyenv + 5, ':');  *host != '@';
			     host++)
				*host = '*';

			host = path;
		}
		path = newline;
	}

	if (isfileurl) {
		struct stat st;

		s = open(path, O_RDONLY);
		if (s == -1) {
			warn("Can't open file %s", path);
			goto cleanup_url_get;
		}

		if (fstat(s, &st) == -1)
			filesize = -1;
		else
			filesize = st.st_size;

		/* Open the output file.  */
		if (strcmp(savefile, "-") != 0) {
#ifndef SMALL
			if (resume)
				out = open(savefile, O_APPEND | O_WRONLY);
			else
#endif /* !SMALL */
				out = open(savefile, O_CREAT | O_WRONLY |
					O_TRUNC, 0666);
			if (out < 0) {
				warn("Can't open %s", savefile);
				goto cleanup_url_get;
			}
		} else
			out = fileno(stdout);

#ifndef SMALL
		if (resume) {
			if (fstat(out, &st) == -1) {
				warn("Can't fstat %s", savefile);
				goto cleanup_url_get;
			}
			if (lseek(s, st.st_size, SEEK_SET) == -1) {
				warn("Can't lseek %s", path);
				goto cleanup_url_get;
			}
			restart_point = st.st_size;
		}
#endif /* !SMALL */

		/* Trap signals */
		oldintr = NULL;
		if (setjmp(httpabort)) {
			if (oldintr)
				(void)signal(SIGINT, oldintr);
			goto cleanup_url_get;
		}
		oldintr = signal(SIGINT, abortfile);

		bytes = 0;
		hashbytes = mark;
		progressmeter(-1);

		if ((buf = malloc(4096)) == NULL)
			errx(1, "Can't allocate memory for transfer buffer");

		/* Finally, suck down the file. */
		i = 0;
		while ((len = read(s, buf, 4096)) > 0) {
			bytes += len;
			for (cp = buf; len > 0; len -= i, cp += i) {
				if ((i = write(out, cp, len)) == -1) {
					warn("Writing %s", savefile);
					goto cleanup_url_get;
				}
				else if (i == 0)
					break;
			}
			if (hash && !progress) {
				while (bytes >= hashbytes) {
					(void)putc('#', ttyout);
					hashbytes += mark;
				}
				(void)fflush(ttyout);
			}
		}
		if (hash && !progress && bytes > 0) {
			if (bytes < mark)
				(void)putc('#', ttyout);
			(void)putc('\n', ttyout);
			(void)fflush(ttyout);
		}
		if (len != 0) {
			warn("Reading from file");
			goto cleanup_url_get;
		}
		progressmeter(1);
		if (verbose)
			fputs("Successfully retrieved file.\n", ttyout);
		(void)signal(SIGINT, oldintr);

		rval = 0;
		goto cleanup_url_get;
	}

	if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL &&
	    (hosttail[1] == '\0' || hosttail[1] == ':')) {
		host++;
		*hosttail++ = '\0';
	} else
		hosttail = host;

	portnum = strrchr(hosttail, ':');		/* find portnum */
	if (portnum != NULL)
		*portnum++ = '\0';

#ifndef SMALL
	if (debug)
		fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n",
		    host, portnum, path, savefile);
#endif /* !SMALL */

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = family;
	hints.ai_socktype = SOCK_STREAM;
#ifndef SMALL
	port = portnum ? portnum : (ishttpsurl ? httpsport : httpport);
#else /* !SMALL */
	port = portnum ? portnum : httpport;
#endif /* !SMALL */
	error = getaddrinfo(host, port, &hints, &res0);
	/*
	 * If the services file is corrupt/missing, fall back
	 * on our hard-coded defines.
	 */
	if (error == EAI_SERVICE && port == httpport) {
		snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT);
		error = getaddrinfo(host, pbuf, &hints, &res0);
#ifndef SMALL
	} else if (error == EAI_SERVICE && port == httpsport) {
		snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT);
		error = getaddrinfo(host, pbuf, &hints, &res0);
#endif /* !SMALL */
	}
	if (error) {
		warnx("%s: %s", gai_strerror(error), host);
		goto cleanup_url_get;
	}

	s = -1;
	for (res = res0; res; res = res->ai_next) {
		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
			strlcpy(hbuf, "(unknown)", sizeof(hbuf));
		if (verbose)
			fprintf(ttyout, "Trying %s...\n", hbuf);

		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
		if (s == -1) {
			cause = "socket";
			continue;
		}

again:
		if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
			int save_errno;

			if (errno == EINTR)
				goto again;
			save_errno = errno;
			close(s);
			errno = save_errno;
			s = -1;
			cause = "connect";
			continue;
		}

		/* get port in numeric */
		if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0,
		    pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0)
			port = pbuf;
		else
			port = NULL;

#ifndef SMALL
		if (proxyenv && sslhost)
			proxy_connect(s, sslhost);
#endif /* !SMALL */
		break;
	}
	freeaddrinfo(res0);
	if (s < 0) {
		warn("%s", cause);
		goto cleanup_url_get;
	}

#ifndef SMALL
	if (ishttpsurl) {
		if (proxyenv && sslpath) {
			ishttpsurl = 0;
			proxyurl = NULL;
			path = sslpath;
		}
		SSL_library_init();
		SSL_load_error_strings();
		SSLeay_add_ssl_algorithms();
		ssl_ctx = SSL_CTX_new(SSLv23_client_method());
		ssl = SSL_new(ssl_ctx);
		if (ssl == NULL || ssl_ctx == NULL) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		if (SSL_set_fd(ssl, s) == 0) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
		if (SSL_connect(ssl) <= 0) {
			ERR_print_errors_fp(ttyout);
			goto cleanup_url_get;
		}
	} else {
		fin = fdopen(s, "r+");
	}
#else /* !SMALL */
	fin = fdopen(s, "r+");
#endif /* !SMALL */

	if (verbose)
		fprintf(ttyout, "Requesting %s", origline);
	/*
	 * Construct and send the request. Proxy requests don't want leading /.
	 */
#ifndef SMALL
	cookie_get(host, path, ishttpsurl, &buf);
#endif /* !SMALL */
	if (proxyurl) {
		if (verbose)
			fprintf(ttyout, " (via %s)\n", proxyenv);
		/*
		 * Host: directive must use the destination host address for
		 * the original URI (path).  We do not attach it at this moment.
		 */
		if (cookie)
			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n"
			    "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n",
			    path, cookie, buf ? buf : "", HTTP_USER_AGENT);
		else
			ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n",
			    path, buf ? buf : "", HTTP_USER_AGENT);

	} else {
		ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", path,
#ifndef SMALL
			resume ? "HTTP/1.1" :
#endif /* !SMALL */
			"HTTP/1.0");
		if (strchr(host, ':')) {
			char *h, *p;

			/*
			 * strip off scoped address portion, since it's
			 * local to node
			 */
			h = strdup(host);
			if (h == NULL)
				errx(1, "Can't allocate memory.");
			if ((p = strchr(h, '%')) != NULL)
				*p = '\0';
			ftp_printf(fin, ssl, "[%s]", h);
			free(h);
		} else
			ftp_printf(fin, ssl, "%s", host);

		/*
		 * Send port number only if it's specified and does not equal
		 * 80. Some broken HTTP servers get confused if you explicitly
		 * send them the port number.
		 */
#ifndef SMALL
		if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0)
			ftp_printf(fin, ssl, ":%s", port);
		if (resume) {
			int ret;
			struct stat stbuf;

			ret = stat(savefile, &stbuf);
			if (ret < 0) {
				if (verbose)
					fprintf(ttyout, "\n");
				warn("Can't open %s", savefile);
				goto cleanup_url_get;
			}
			restart_point = stbuf.st_size;
			ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-",
				(long long)restart_point);
		}
#else /* !SMALL */
		if (port && strcmp(port, "80") != 0)
			ftp_printf(fin, ssl, ":%s", port);
#endif /* !SMALL */
		ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n",
		    buf ? buf : "", HTTP_USER_AGENT);
		if (verbose)
			fprintf(ttyout, "\n");
	}


#ifndef SMALL
	free(buf);
#endif /* !SMALL */
	buf = NULL;

	if (fin != NULL && fflush(fin) == EOF) {
		warn("Writing HTTP request");
		goto cleanup_url_get;
	}
	if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
		warn("Receiving HTTP reply");
		goto cleanup_url_get;
	}

	while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
		buf[--len] = '\0';
#ifndef SMALL
	if (debug)
		fprintf(ttyout, "received '%s'\n", buf);
#endif /* !SMALL */

	cp = strchr(buf, ' ');
	if (cp == NULL)
		goto improper;
	else
		cp++;

	strlcpy(ststr, cp, sizeof(ststr));
	status = strtonum(ststr, 200, 416, &errstr);
	if (errstr) {
		warnx("Error retrieving file: %s", cp);
		goto cleanup_url_get;
	}

	switch (status) {
	case 200:	/* OK */
#ifndef SMALL
	case 206:	/* Partial Content */
		break;
#endif /* !SMALL */
	case 301:	/* Moved Permanently */
	case 302:	/* Found */
	case 303:	/* See Other */
	case 307:	/* Temporary Redirect */
		isredirect++;
		if (redirect_loop++ > 10) {
			warnx("Too many redirections requested");
			goto cleanup_url_get;
		}
		break;
#ifndef SMALL
	case 416:	/* Requested Range Not Satisfiable */
		warnx("File is already fully retrieved.");
		goto cleanup_url_get;
#endif /* !SMALL */
	default:
		warnx("Error retrieving file: %s", cp);
		goto cleanup_url_get;
	}

	/*
	 * Read the rest of the header.
	 */
	free(buf);
	filesize = -1;

	for (;;) {
		if ((buf = ftp_readline(fin, ssl, &len)) == NULL) {
			warn("Receiving HTTP reply");
			goto cleanup_url_get;
		}

		while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
			buf[--len] = '\0';
		if (len == 0)
			break;
#ifndef SMALL
		if (debug)
			fprintf(ttyout, "received '%s'\n", buf);
#endif /* !SMALL */

		/* Look for some headers */
		cp = buf;
#define CONTENTLEN "Content-Length: "
		if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) {
			cp += sizeof(CONTENTLEN) - 1;
			filesize = strtonum(cp, 0, LLONG_MAX, &errstr);
			if (errstr != NULL)
				goto improper;
#ifndef SMALL
			if (resume)
				filesize += restart_point;
#endif /* !SMALL */
#define LOCATION "Location: "
		} else if (isredirect &&
		    strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) {
			cp += sizeof(LOCATION) - 1;
			if (verbose)
				fprintf(ttyout, "Redirected to %s\n", cp);
			if (fin != NULL)
				fclose(fin);
			else if (s != -1)
				close(s);
			free(proxyurl);
			free(newline);
			rval = url_get(cp, proxyenv, outfile);
			free(buf);
			return (rval);
		}
	}

	/* Open the output file.  */
	if (strcmp(savefile, "-") != 0) {
#ifndef SMALL
		if (resume)
			out = open(savefile, O_APPEND | O_WRONLY);
		else
#endif /* !SMALL */
			out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC,
				0666);
		if (out < 0) {
			warn("Can't open %s", savefile);
			goto cleanup_url_get;
		}
	} else
		out = fileno(stdout);

	/* Trap signals */
	oldintr = NULL;
	if (setjmp(httpabort)) {
		if (oldintr)
			(void)signal(SIGINT, oldintr);
		goto cleanup_url_get;
	}
	oldintr = signal(SIGINT, aborthttp);

	bytes = 0;
	hashbytes = mark;
	progressmeter(-1);

	free(buf);

	/* Finally, suck down the file. */
	if ((buf = malloc(4096)) == NULL)
		errx(1, "Can't allocate memory for transfer buffer");
	i = 0;
	len = 1;
	while (len > 0) {
		len = ftp_read(fin, ssl, buf, 4096);
		bytes += len;
		for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) {
			if ((i = write(out, cp, wlen)) == -1) {
				warn("Writing %s", savefile);
				goto cleanup_url_get;
			}
			else if (i == 0)
				break;
		}
		if (hash && !progress) {
			while (bytes >= hashbytes) {
				(void)putc('#', ttyout);
				hashbytes += mark;
			}
			(void)fflush(ttyout);
		}
	}
	if (hash && !progress && bytes > 0) {
		if (bytes < mark)
			(void)putc('#', ttyout);
		(void)putc('\n', ttyout);
		(void)fflush(ttyout);
	}
	if (len != 0) {
		warn("Reading from socket");
		goto cleanup_url_get;
	}
	progressmeter(1);
	if (
#ifndef SMALL
		!resume &&
#endif /* !SMALL */
		filesize != -1 && len == 0 && bytes != filesize) {
		if (verbose)
			fputs("Read short file.\n", ttyout);
		goto cleanup_url_get;
	}

	if (verbose)
		fputs("Successfully retrieved file.\n", ttyout);
	(void)signal(SIGINT, oldintr);

	rval = 0;
	goto cleanup_url_get;

noftpautologin:
	warnx(
	    "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
	goto cleanup_url_get;

improper:
	warnx("Improper response from %s", host);

cleanup_url_get:
#ifndef SMALL
	if (ssl) {
		SSL_shutdown(ssl);
		SSL_free(ssl);
	}
#endif /* !SMALL */
	if (fin != NULL)
		fclose(fin);
	else if (s != -1)
		close(s);
	free(buf);
	free(proxyurl);
	free(newline);
	return (rval);
}
Exemplo n.º 21
0
Arquivo: jabber.c Projeto: AlD/bitlbee
/* Separate this from jabber_login() so we can do OAuth first if necessary.
   Putting this in io.c would probably be more correct. */
void jabber_connect( struct im_connection *ic )
{
	account_t *acc = ic->acc;
	struct jabber_data *jd = ic->proto_data;
	int i;
	char *connect_to;
	struct ns_srv_reply **srvl = NULL, *srv = NULL;
	
	/* Figure out the hostname to connect to. */
	if( acc->server && *acc->server )
		connect_to = acc->server;
	else if( ( srvl = srv_lookup( "xmpp-client", "tcp", jd->server ) ) ||
	         ( srvl = srv_lookup( "jabber-client", "tcp", jd->server ) ) )
	{
		/* Find the lowest-priority one. These usually come
		   back in random/shuffled order. Not looking at
		   weights etc for now. */
		srv = *srvl;
		for( i = 1; srvl[i]; i ++ )
			if( srvl[i]->prio < srv->prio )
				srv = srvl[i];
		
		connect_to = srv->name;
	}
	else
		connect_to = jd->server;
	
	imcb_log( ic, "Connecting" );
	
	for( i = 0; jabber_port_list[i] > 0; i ++ )
		if( set_getint( &acc->set, "port" ) == jabber_port_list[i] )
			break;

	if( jabber_port_list[i] == 0 )
	{
		imcb_log( ic, "Illegal port number" );
		imc_logout( ic, FALSE );
		return;
	}
	
	/* For non-SSL connections we can try to use the port # from the SRV
	   reply, but let's not do that when using SSL, SSL usually runs on
	   non-standard ports... */
	if( set_getbool( &acc->set, "ssl" ) )
	{
		jd->ssl = ssl_connect( connect_to, set_getint( &acc->set, "port" ), FALSE, jabber_connected_ssl, ic );
		jd->fd = jd->ssl ? ssl_getfd( jd->ssl ) : -1;
	}
	else
	{
		jd->fd = proxy_connect( connect_to, srv ? srv->port : set_getint( &acc->set, "port" ), jabber_connected_plain, ic );
	}
	srv_free( srvl );
	
	if( jd->fd == -1 )
	{
		imcb_error( ic, "Could not connect to server" );
		imc_logout( ic, TRUE );
		
		return;
	}
	
	if( set_getbool( &acc->set, "xmlconsole" ) )
	{
		jd->flags |= JFLAG_XMLCONSOLE;
		/* Shouldn't really do this at this stage already, maybe. But
		   I think this shouldn't break anything. */
		imcb_add_buddy( ic, JABBER_XMLCONSOLE_HANDLE, NULL );
	}
	
	jabber_generate_id_hash( jd );
}
Exemplo n.º 22
0
/* Separate this from jabber_login() so we can do OAuth first if necessary.
   Putting this in io.c would probably be more correct. */
void jabber_connect(struct im_connection *ic)
{
	account_t *acc = ic->acc;
	struct jabber_data *jd = ic->proto_data;
	int i;
	char *connect_to;
	struct ns_srv_reply **srvl = NULL, *srv = NULL;

	/* Figure out the hostname to connect to. */
	if (acc->server && *acc->server) {
		connect_to = acc->server;
	} else if ((srvl = srv_lookup("xmpp-client", "tcp", jd->server)) ||
	           (srvl = srv_lookup("jabber-client", "tcp", jd->server))) {
		/* Find the lowest-priority one. These usually come
		   back in random/shuffled order. Not looking at
		   weights etc for now. */
		srv = *srvl;
		for (i = 1; srvl[i]; i++) {
			if (srvl[i]->prio < srv->prio) {
				srv = srvl[i];
			}
		}

		connect_to = srv->name;
	} else {
		connect_to = jd->server;
	}

	imcb_log(ic, "Connecting");

	for (i = 0; jabber_port_list[i] > 0; i++) {
		if (set_getint(&acc->set, "port") == jabber_port_list[i]) {
			break;
		}
	}

	if (jabber_port_list[i] == 0) {
		imcb_log(ic, "Illegal port number");
		imc_logout(ic, FALSE);
		return;
	}

	/* For non-SSL connections we can try to use the port # from the SRV
	   reply, but let's not do that when using SSL, SSL usually runs on
	   non-standard ports... */
	if (set_getbool(&acc->set, "ssl")) {
		jd->ssl = ssl_connect(connect_to, set_getint(&acc->set, "port"), set_getbool(&acc->set,
		                                                                             "tls_verify"), jabber_connected_ssl,
		                      ic);
		jd->fd = jd->ssl ? ssl_getfd(jd->ssl) : -1;
	} else {
		jd->fd = proxy_connect(connect_to, srv ? srv->port : set_getint(&acc->set,
		                                                                "port"), jabber_connected_plain, ic);
	}
	srv_free(srvl);

	if (jd->fd == -1) {
		imcb_error(ic, "Could not connect to server");
		imc_logout(ic, TRUE);

		return;
	}

	if (set_getbool(&acc->set, "xmlconsole")) {
		jabber_xmlconsole_enable(ic);
	}

	if (set_getbool(&acc->set, "mail_notifications")) {
		/* It's gmail specific, but it checks for server support before enabling it */
		jd->flags |= JFLAG_GMAILNOTIFY;
		if (set_getstr(&acc->set, "mail_notifications_handle")) {
			imcb_add_buddy(ic, set_getstr(&acc->set, "mail_notifications_handle"), NULL);
		}
	}

	jabber_generate_id_hash(jd);
}