1/* crypto/bio/bss_conn.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60#include <errno.h>
61//asq:
62//#define USE_SOCKETS
63#undef USE_SOCKETS
64#define OPENSSL_NO_SOCK
65
66#include <openssl/local/cryptlib.h>
67#include <openssl/bio.h>
68
69#ifndef OPENSSL_NO_SOCK
70
71#ifdef OPENSSL_SYS_WIN16
72#define SOCKET_PROTOCOL 0 /* more microsoft stupidity */
73#else
74#define SOCKET_PROTOCOL IPPROTO_TCP
75#endif
76
77#if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
78/* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
79#undef FIONBIO
80#endif
81
82
83typedef struct bio_connect_st
84	{
85	int state;
86
87	char *param_hostname;
88	char *param_port;
89	int nbio;
90
91	unsigned char ip[4];
92	unsigned short port;
93
94	struct sockaddr_in them;
95
96	/* int socket; this will be kept in bio->num so that it is
97	 * compatible with the bss_sock bio */
98
99	/* called when the connection is initially made
100	 *  callback(BIO,state,ret);  The callback should return
101	 * 'ret'.  state is for compatibility with the ssl info_callback */
102	int (*info_callback)(const BIO *bio,int state,int ret);
103	} BIO_CONNECT;
104
105static int conn_write(BIO *h, const char *buf, int num);
106static int conn_read(BIO *h, char *buf, int size);
107static int conn_puts(BIO *h, const char *str);
108static long conn_ctrl(BIO *h, int cmd, long arg1, void *arg2);
109static int conn_new(BIO *h);
110static int conn_free(BIO *data);
111static long conn_callback_ctrl(BIO *h, int cmd, bio_info_cb *);
112
113static int conn_state(BIO *b, BIO_CONNECT *c);
114static void conn_close_socket(BIO *data);
115BIO_CONNECT *BIO_CONNECT_new(void );
116void BIO_CONNECT_free(BIO_CONNECT *a);
117
118static BIO_METHOD methods_connectp=
119	{
120	BIO_TYPE_CONNECT,
121	"socket connect",
122	conn_write,
123	conn_read,
124	conn_puts,
125	NULL, /* connect_gets, */
126	conn_ctrl,
127	conn_new,
128	conn_free,
129	conn_callback_ctrl,
130	};
131
132static int conn_state(BIO *b, BIO_CONNECT *c)
133	{
134	int ret= -1,i;
135	unsigned long l;
136	char *p,*q;
137	int (*cb)(const BIO *,int,int)=NULL;
138
139	if (c->info_callback != NULL)
140		cb=c->info_callback;
141
142	for (;;)
143		{
144		switch (c->state)
145			{
146		case BIO_CONN_S_BEFORE:
147			p=c->param_hostname;
148			if (p == NULL)
149				{
150				BIOerr(BIO_F_CONN_STATE,BIO_R_NO_HOSTNAME_SPECIFIED);
151				goto exit_loop;
152				}
153			for ( ; *p != '\0'; p++)
154				{
155				if ((*p == ':') || (*p == '/')) break;
156				}
157
158			i= *p;
159			if ((i == ':') || (i == '/'))
160				{
161
162				*(p++)='\0';
163				if (i == ':')
164					{
165					for (q=p; *q; q++)
166						if (*q == '/')
167							{
168							*q='\0';
169							break;
170							}
171					if (c->param_port != NULL)
172						OPENSSL_free(c->param_port);
173					c->param_port=BUF_strdup(p);
174					}
175				}
176
177			if (c->param_port == NULL)
178				{
179				BIOerr(BIO_F_CONN_STATE,BIO_R_NO_PORT_SPECIFIED);
180				ERR_add_error_data(2,"host=",c->param_hostname);
181				goto exit_loop;
182				}
183			c->state=BIO_CONN_S_GET_IP;
184			break;
185
186		case BIO_CONN_S_GET_IP:
187			if (BIO_get_host_ip(c->param_hostname,&(c->ip[0])) <= 0)
188				goto exit_loop;
189			c->state=BIO_CONN_S_GET_PORT;
190			break;
191
192		case BIO_CONN_S_GET_PORT:
193			if (c->param_port == NULL)
194				{
195				/* abort(); */
196				goto exit_loop;
197				}
198			else if (BIO_get_port(c->param_port,&c->port) <= 0)
199				goto exit_loop;
200			c->state=BIO_CONN_S_CREATE_SOCKET;
201			break;
202
203		case BIO_CONN_S_CREATE_SOCKET:
204			/* now setup address */
205			memset((char *)&c->them,0,sizeof(c->them));
206			c->them.sin_family=AF_INET;
207			c->them.sin_port=htons((unsigned short)c->port);
208			l=(unsigned long)
209				((unsigned long)c->ip[0]<<24L)|
210				((unsigned long)c->ip[1]<<16L)|
211				((unsigned long)c->ip[2]<< 8L)|
212				((unsigned long)c->ip[3]);
213			c->them.sin_addr.s_addr=htonl(l);
214			c->state=BIO_CONN_S_CREATE_SOCKET;
215
216			ret=socket(AF_INET,SOCK_STREAM,SOCKET_PROTOCOL);
217			if (ret == INVALID_SOCKET)
218				{
219				SYSerr(SYS_F_SOCKET,get_last_socket_error());
220				ERR_add_error_data(4,"host=",c->param_hostname,
221					":",c->param_port);
222				BIOerr(BIO_F_CONN_STATE,BIO_R_UNABLE_TO_CREATE_SOCKET);
223				goto exit_loop;
224				}
225			b->num=ret;
226			c->state=BIO_CONN_S_NBIO;
227			break;
228
229		case BIO_CONN_S_NBIO:
230			if (c->nbio)
231				{
232				if (!BIO_socket_nbio(b->num,1))
233					{
234					BIOerr(BIO_F_CONN_STATE,BIO_R_ERROR_SETTING_NBIO);
235					ERR_add_error_data(4,"host=",
236						c->param_hostname,
237						":",c->param_port);
238					goto exit_loop;
239					}
240				}
241			c->state=BIO_CONN_S_CONNECT;
242
243#if defined(SO_KEEPALIVE) && !defined(OPENSSL_SYS_MPE)
244			i=1;
245			i=setsockopt(b->num,SOL_SOCKET,SO_KEEPALIVE,(char *)&i,sizeof(i));
246			if (i < 0)
247				{
248				SYSerr(SYS_F_SOCKET,get_last_socket_error());
249				ERR_add_error_data(4,"host=",c->param_hostname,
250					":",c->param_port);
251				BIOerr(BIO_F_CONN_STATE,BIO_R_KEEPALIVE);
252				goto exit_loop;
253				}
254#endif
255			break;
256
257		case BIO_CONN_S_CONNECT:
258			BIO_clear_retry_flags(b);
259			ret=connect(b->num,
260				(struct sockaddr *)&c->them,
261				sizeof(c->them));
262			b->retry_reason=0;
263			if (ret < 0)
264				{
265				if (BIO_sock_should_retry(ret))
266					{
267					BIO_set_retry_special(b);
268					c->state=BIO_CONN_S_BLOCKED_CONNECT;
269					b->retry_reason=BIO_RR_CONNECT;
270					}
271				else
272					{
273					SYSerr(SYS_F_CONNECT,get_last_socket_error());
274					ERR_add_error_data(4,"host=",
275						c->param_hostname,
276						":",c->param_port);
277					BIOerr(BIO_F_CONN_STATE,BIO_R_CONNECT_ERROR);
278					}
279				goto exit_loop;
280				}
281			else
282				c->state=BIO_CONN_S_OK;
283			break;
284
285		case BIO_CONN_S_BLOCKED_CONNECT:
286			i=BIO_sock_error(b->num);
287			if (i)
288				{
289				BIO_clear_retry_flags(b);
290				SYSerr(SYS_F_CONNECT,i);
291				ERR_add_error_data(4,"host=",
292					c->param_hostname,
293					":",c->param_port);
294				BIOerr(BIO_F_CONN_STATE,BIO_R_NBIO_CONNECT_ERROR);
295				ret=0;
296				goto exit_loop;
297				}
298			else
299				c->state=BIO_CONN_S_OK;
300			break;
301
302		case BIO_CONN_S_OK:
303			ret=1;
304			goto exit_loop;
305		default:
306			/* abort(); */
307			goto exit_loop;
308			}
309
310		if (cb != NULL)
311			{
312			if (!(ret=cb((BIO *)b,c->state,ret)))
313				goto end;
314			}
315		}
316
317	/* Loop does not exit */
318exit_loop:
319	if (cb != NULL)
320		ret=cb((BIO *)b,c->state,ret);
321end:
322	return(ret);
323	}
324
325BIO_CONNECT *BIO_CONNECT_new(void)
326	{
327	BIO_CONNECT *ret;
328
329	if ((ret=(BIO_CONNECT *)OPENSSL_malloc(sizeof(BIO_CONNECT))) == NULL)
330		return(NULL);
331	ret->state=BIO_CONN_S_BEFORE;
332	ret->param_hostname=NULL;
333	ret->param_port=NULL;
334	ret->info_callback=NULL;
335	ret->nbio=0;
336	ret->ip[0]=0;
337	ret->ip[1]=0;
338	ret->ip[2]=0;
339	ret->ip[3]=0;
340	ret->port=0;
341	memset((char *)&ret->them,0,sizeof(ret->them));
342	return(ret);
343	}
344
345void BIO_CONNECT_free(BIO_CONNECT *a)
346	{
347	if(a == NULL)
348	    return;
349
350	if (a->param_hostname != NULL)
351		OPENSSL_free(a->param_hostname);
352	if (a->param_port != NULL)
353		OPENSSL_free(a->param_port);
354	OPENSSL_free(a);
355	}
356
357BIO_METHOD *BIO_s_connect(void)
358	{
359	return(&methods_connectp);
360	}
361
362static int conn_new(BIO *bi)
363	{
364	bi->init=0;
365	bi->num=INVALID_SOCKET;
366	bi->flags=0;
367	if ((bi->ptr=(char *)BIO_CONNECT_new()) == NULL)
368		return(0);
369	else
370		return(1);
371	}
372
373static void conn_close_socket(BIO *bio)
374	{
375	BIO_CONNECT *c;
376
377	c=(BIO_CONNECT *)bio->ptr;
378	if (bio->num != INVALID_SOCKET)
379		{
380		/* Only do a shutdown if things were established */
381		if (c->state == BIO_CONN_S_OK)
382			shutdown(bio->num,2);
383		closesocket(bio->num);
384		bio->num=INVALID_SOCKET;
385		}
386	}
387
388static int conn_free(BIO *a)
389	{
390	BIO_CONNECT *data;
391
392	if (a == NULL) return(0);
393	data=(BIO_CONNECT *)a->ptr;
394
395	if (a->shutdown)
396		{
397		conn_close_socket(a);
398		BIO_CONNECT_free(data);
399		a->ptr=NULL;
400		a->flags=0;
401		a->init=0;
402		}
403	return(1);
404	}
405
406static int conn_read(BIO *b, char *out, int outl)
407	{
408	int ret=0;
409	BIO_CONNECT *data;
410
411	data=(BIO_CONNECT *)b->ptr;
412	if (data->state != BIO_CONN_S_OK)
413		{
414		ret=conn_state(b,data);
415		if (ret <= 0)
416				return(ret);
417		}
418
419	if (out != NULL)
420		{
421		clear_socket_error();
422		ret=readsocket(b->num,out,outl);
423		BIO_clear_retry_flags(b);
424		if (ret <= 0)
425			{
426			if (BIO_sock_should_retry(ret))
427				BIO_set_retry_read(b);
428			}
429		}
430	return(ret);
431	}
432
433static int conn_write(BIO *b, const char *in, int inl)
434	{
435	int ret;
436	BIO_CONNECT *data;
437
438	data=(BIO_CONNECT *)b->ptr;
439	if (data->state != BIO_CONN_S_OK)
440		{
441		ret=conn_state(b,data);
442		if (ret <= 0) return(ret);
443		}
444
445	clear_socket_error();
446	ret=writesocket(b->num,in,inl);
447	BIO_clear_retry_flags(b);
448	if (ret <= 0)
449		{
450		if (BIO_sock_should_retry(ret))
451			BIO_set_retry_write(b);
452		}
453	return(ret);
454	}
455
456static long conn_ctrl(BIO *b, int cmd, long num, void *ptr)
457	{
458	BIO *dbio;
459	int *ip;
460	const char **pptr;
461	long ret=1;
462	BIO_CONNECT *data;
463
464	data=(BIO_CONNECT *)b->ptr;
465
466	switch (cmd)
467		{
468	case BIO_CTRL_RESET:
469		ret=0;
470		data->state=BIO_CONN_S_BEFORE;
471		conn_close_socket(b);
472		b->flags=0;
473		break;
474	case BIO_C_DO_STATE_MACHINE:
475		/* use this one to start the connection */
476		if (data->state != BIO_CONN_S_OK)
477			ret=(long)conn_state(b,data);
478		else
479			ret=1;
480		break;
481	case BIO_C_GET_CONNECT:
482		if (ptr != NULL)
483			{
484			pptr=(const char **)ptr;
485			if (num == 0)
486				{
487				*pptr=data->param_hostname;
488
489				}
490			else if (num == 1)
491				{
492				*pptr=data->param_port;
493				}
494			else if (num == 2)
495				{
496				*pptr= (char *)&(data->ip[0]);
497				}
498			else if (num == 3)
499				{
500				*((int *)ptr)=data->port;
501				}
502			if ((!b->init) || (ptr == NULL))
503				*pptr="not initialized";
504			ret=1;
505			}
506		break;
507	case BIO_C_SET_CONNECT:
508		if (ptr != NULL)
509			{
510			b->init=1;
511			if (num == 0)
512				{
513				if (data->param_hostname != NULL)
514					OPENSSL_free(data->param_hostname);
515				data->param_hostname=BUF_strdup(ptr);
516				}
517			else if (num == 1)
518				{
519				if (data->param_port != NULL)
520					OPENSSL_free(data->param_port);
521				data->param_port=BUF_strdup(ptr);
522				}
523			else if (num == 2)
524				{
525				char buf[16];
526				unsigned char *p = ptr;
527
528				BIO_snprintf(buf,sizeof buf,"%d.%d.%d.%d",
529					     p[0],p[1],p[2],p[3]);
530				if (data->param_hostname != NULL)
531					OPENSSL_free(data->param_hostname);
532				data->param_hostname=BUF_strdup(buf);
533				memcpy(&(data->ip[0]),ptr,4);
534				}
535			else if (num == 3)
536				{
537				char buf[DECIMAL_SIZE(int)+1];
538
539				BIO_snprintf(buf,sizeof buf,"%d",*(int *)ptr);
540				if (data->param_port != NULL)
541					OPENSSL_free(data->param_port);
542				data->param_port=BUF_strdup(buf);
543				data->port= *(int *)ptr;
544				}
545			}
546		break;
547	case BIO_C_SET_NBIO:
548		data->nbio=(int)num;
549		break;
550	case BIO_C_GET_FD:
551		if (b->init)
552			{
553			ip=(int *)ptr;
554			if (ip != NULL)
555				*ip=b->num;
556			ret=b->num;
557			}
558		else
559			ret= -1;
560		break;
561	case BIO_CTRL_GET_CLOSE:
562		ret=b->shutdown;
563		break;
564	case BIO_CTRL_SET_CLOSE:
565		b->shutdown=(int)num;
566		break;
567	case BIO_CTRL_PENDING:
568	case BIO_CTRL_WPENDING:
569		ret=0;
570		break;
571	case BIO_CTRL_FLUSH:
572		break;
573	case BIO_CTRL_DUP:
574		{
575		dbio=(BIO *)ptr;
576		if (data->param_port)
577			BIO_set_conn_port(dbio,data->param_port);
578		if (data->param_hostname)
579			BIO_set_conn_hostname(dbio,data->param_hostname);
580		BIO_set_nbio(dbio,data->nbio);
581		/* FIXME: the cast of the function seems unlikely to be a good idea */
582                (void)BIO_set_info_callback(dbio,(bio_info_cb *)data->info_callback);
583		}
584		break;
585	case BIO_CTRL_SET_CALLBACK:
586		{
587#if 0 /* FIXME: Should this be used?  -- Richard Levitte */
588		BIOerr(BIO_F_CONN_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
589		ret = -1;
590#else
591		ret=0;
592#endif
593		}
594		break;
595	case BIO_CTRL_GET_CALLBACK:
596		{
597		int (**fptr)(const BIO *bio,int state,int xret);
598
599		fptr=(int (**)(const BIO *bio,int state,int xret))ptr;
600		*fptr=data->info_callback;
601		}
602		break;
603	default:
604		ret=0;
605		break;
606		}
607	return(ret);
608	}
609
610static long conn_callback_ctrl(BIO *b, int cmd, bio_info_cb *fp)
611	{
612	long ret=1;
613	BIO_CONNECT *data;
614
615	data=(BIO_CONNECT *)b->ptr;
616
617	switch (cmd)
618		{
619	case BIO_CTRL_SET_CALLBACK:
620		{
621		data->info_callback=(int (*)(const struct bio_st *, int, int))fp;
622		}
623		break;
624	default:
625		ret=0;
626		break;
627		}
628	return(ret);
629	}
630
631static int conn_puts(BIO *bp, const char *str)
632	{
633	int n,ret;
634
635	n=strlen(str);
636	ret=conn_write(bp,str,n);
637	return(ret);
638	}
639
640BIO *BIO_new_connect(char *str)
641	{
642	BIO *ret;
643
644	ret=BIO_new(BIO_s_connect());
645	if (ret == NULL) return(NULL);
646	if (BIO_set_conn_hostname(ret,str))
647		return(ret);
648	else
649		{
650		BIO_free(ret);
651		return(NULL);
652		}
653	}
654
655#endif
656
657