Synchronet now requires the libarchive development package (e.g. libarchive-dev on Debian-based Linux distros, libarchive.org for more info) to build successfully.

conn.c 14.1 KB
Newer Older
deuce's avatar
deuce committed
1 2
/* Copyright (C), 2007 by Stephen Hurd */

3
/* $Id: conn.c,v 1.81 2020/06/27 00:04:49 deuce Exp $ */
4

deuce's avatar
deuce committed
5 6
#include <stdlib.h>

7 8
#include "ciolib.h"

9 10
#include "gen_defs.h"
#include "genwrap.h"
11
#include "sockwrap.h"
12
#include "threadwrap.h"
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#ifdef _WIN32
 #undef socklen_t
 // Borland hack (broken header)
 #ifdef __BORLANDC__
  #define _MSC_VER 1
 #endif
 #include "ws2tcpip.h"
 #ifdef __BORLANDC__
  #undef _MSC_VER
 #endif
 #ifndef AI_ADDRCONFIG
  #define AI_ADDRCONFIG 0x0400	// Vista or later.
 #endif
 #ifndef AI_NUMERICSERV
  #define AI_NUMERICSERV 0		// No supported by Windows
 #endif
#endif

32
#include "bbslist.h"
33
#include "uifcinit.h"
34 35 36
#include "conn.h"
#include "rlogin.h"
#include "raw.h"
Deucе's avatar
Deucе committed
37
#ifndef WITHOUT_CRYPTLIB
38
#include "ssh.h"
39
#include "telnets.h"
Deucе's avatar
Deucе committed
40
#endif
deuce's avatar
deuce committed
41
#ifndef __HAIKU__
deuce's avatar
deuce committed
42
#include "modem.h"
deuce's avatar
deuce committed
43
#endif
44 45 46
#ifdef __unix__
#include "conn_pty.h"
#endif
47
#include "conn_telnet.h"
48

49
struct conn_api conn_api;
50 51 52
char *conn_types_enum[]={"Unknown","RLogin","RLoginReversed","Telnet","Raw","SSH","SSHNA","Modem","Serial","Shell","MBBSGhost","TelnetS", NULL};
char *conn_types[]={"Unknown","RLogin","RLogin Reversed","Telnet","Raw","SSH","SSH (no auth)","Modem","Serial","Shell","MBBS GHost","TelnetS",NULL};
short unsigned int conn_ports[]={0,513,513,23,0,22,22,0,0,0,65535,992,0};
53

54 55 56 57 58
struct conn_buffer conn_inbuf;
struct conn_buffer conn_outbuf;

/* Buffer functions */
struct conn_buffer *create_conn_buf(struct conn_buffer *buf, size_t size)
59
{
60 61 62 63 64 65
	buf->buf=(unsigned char *)malloc(size);
	if(buf->buf==NULL)
		return(NULL);
	buf->bufsize=size;
	buf->buftop=0;
	buf->bufbot=0;
66
	buf->isempty=1;
67
	if(pthread_mutex_init(&(buf->mutex), NULL)) {
68
		FREE_AND_NULL(buf->buf);
69 70 71
		return(NULL);
	}
	if(sem_init(&(buf->in_sem), 0, 0)) {
72
		FREE_AND_NULL(buf->buf);
73 74 75 76
		pthread_mutex_destroy(&(buf->mutex));
		return(NULL);
	}
	if(sem_init(&(buf->out_sem), 0, 0)) {
77
		FREE_AND_NULL(buf->buf);
78 79 80
		pthread_mutex_destroy(&(buf->mutex));
		sem_destroy(&(buf->in_sem));
		return(NULL);
81
	}
82
	return(buf);
83 84
}

85
void destroy_conn_buf(struct conn_buffer *buf)
86
{
87
	if(buf->buf != NULL) {
deuce's avatar
deuce committed
88
		FREE_AND_NULL(buf->buf);
89 90 91 92
		while(pthread_mutex_destroy(&(buf->mutex)));
		while(sem_destroy(&(buf->in_sem)));
		while(sem_destroy(&(buf->out_sem)));
	}
93
}
deuce's avatar
deuce committed
94

95 96 97 98 99 100
/*
 * The mutex should always be locked by the caller
 * for the rest of the buffer functions
 */
size_t conn_buf_bytes(struct conn_buffer *buf)
{
101 102 103 104 105 106
	if(buf->isempty)
		return(0);

	if(buf->buftop > buf->bufbot)
		return(buf->buftop - buf->bufbot);
	return(buf->bufsize - buf->bufbot + buf->buftop);
107 108 109 110
}

size_t conn_buf_free(struct conn_buffer *buf)
{
111
	return(buf->bufsize - conn_buf_bytes(buf));
112 113 114 115 116 117 118
}

/*
 * Copies up to outlen bytes from the buffer into outbuf,
 * leaving them in the buffer.  Returns the number of bytes
 * copied out of the buffer
 */
119
size_t conn_buf_peek(struct conn_buffer *buf, void *voutbuf, size_t outlen)
120
{
121
	unsigned char *outbuf = (unsigned char *)voutbuf;
122 123 124 125 126 127
	size_t copy_bytes;
	size_t chunk;

	copy_bytes=conn_buf_bytes(buf);
	if(copy_bytes > outlen)
		copy_bytes=outlen;
128
	chunk=buf->bufsize - buf->bufbot;
129 130 131
	if(chunk > copy_bytes)
		chunk=copy_bytes;

132 133
	if(chunk)
		memcpy(outbuf, buf->buf+buf->bufbot, chunk);
134 135 136 137 138 139 140 141 142 143 144
	if(chunk < copy_bytes)
		memcpy(outbuf+chunk, buf->buf, copy_bytes-chunk);

	return(copy_bytes);
}

/*
 * Copies up to outlen bytes from the buffer into outbuf,
 * removing them from the buffer.  Returns the number of
 * bytes removed from the buffer.
 */
145
size_t conn_buf_get(struct conn_buffer *buf, void *voutbuf, size_t outlen)
146
{
147
	unsigned char *outbuf = (unsigned char *)voutbuf;
148
	size_t ret;
149
	size_t atstart;
150

151
	atstart=conn_buf_bytes(buf);
152
	ret=conn_buf_peek(buf, outbuf, outlen);
153 154 155 156 157 158 159 160
	if(ret) {
		buf->bufbot+=ret;
		if(buf->bufbot >= buf->bufsize)
			buf->bufbot -= buf->bufsize;
		if(ret==atstart)
			buf->isempty=1;
		sem_post(&(buf->out_sem));
	}
161 162 163 164 165 166 167
	return(ret);
}

/*
 * Places up to outlen bytes from outbuf into the buffer
 * returns the number of bytes written into the buffer
 */
168
size_t conn_buf_put(struct conn_buffer *buf, const void *voutbuf, size_t outlen)
169
{
170
	const unsigned char *outbuf = (unsigned char *)voutbuf;
171 172 173
	size_t write_bytes;
	size_t chunk;

174
	write_bytes=conn_buf_free(buf);
175 176
	if(write_bytes > outlen)
		write_bytes = outlen;
177 178 179 180 181 182 183 184 185 186 187 188 189 190
	if(write_bytes) {
		chunk=buf->bufsize - buf->buftop;
		if(chunk > write_bytes)
			chunk=write_bytes;
		if(chunk)
			memcpy(buf->buf+buf->buftop, outbuf, chunk);
		if(chunk < write_bytes)
			memcpy(buf->buf, outbuf+chunk, write_bytes-chunk);
		buf->buftop+=write_bytes;
		if(buf->buftop >= buf->bufsize)
			buf->buftop -= buf->bufsize;
		buf->isempty=0;
		sem_post(&(buf->in_sem));
	}
191 192 193 194 195 196 197
	return(write_bytes);
}

/*
 * Waits up to timeout milliseconds for bcount bytes to be available/free
 * in the buffer.
 */
deuce's avatar
deuce committed
198
size_t conn_buf_wait_cond(struct conn_buffer *buf, size_t bcount, unsigned long timeout, int do_free)
199 200 201 202 203 204 205 206
{
	long double now;
	long double end;
	size_t found;
	unsigned long timeleft;
	int retnow=0;
	sem_t	*sem;
	size_t (*cond)(struct conn_buffer *buf);
207

deuce's avatar
deuce committed
208
	if(do_free) {
209 210
		sem=&(buf->out_sem);
		cond=conn_buf_free;
211
	}
212 213 214 215 216 217 218 219
	else {
		sem=&(buf->in_sem);
		cond=conn_buf_bytes;
	}

	found=cond(buf);
	if(found > bcount)
		found=bcount;
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
	if(found == bcount || timeout==0)
		return(found);

	pthread_mutex_unlock(&(buf->mutex));

	end=timeout;
	end/=1000;
	now=xp_timer();
	end+=now;

	for(;;) {
		now=xp_timer();
		if(end <= now)
			timeleft=0;
		else {
			timeleft=(end-now)*1000;
			if(timeleft<1 || timeleft > timeout)
				timeleft=1;
239
		}
240 241
		if(sem_trywait_block(sem, timeleft))
			retnow=1;
rswindell's avatar
rswindell committed
242
		pthread_mutex_lock(&(buf->mutex));	/* term.c data_waiting() blocks here, seemingly forever */
243 244 245 246 247 248 249 250
		found=cond(buf);
		if(found > bcount)
			found=bcount;

		if(found == bcount || retnow)
			return(found);

		pthread_mutex_unlock(&(buf->mutex));
251
	}
252 253 254 255 256 257 258 259
}

/*
 * Connection functions
 */

BOOL conn_connected(void)
{
260
	if(conn_api.input_thread_running == 1 && conn_api.output_thread_running == 1)
261 262 263 264
		return(TRUE);
	return(FALSE);
}

265
int conn_recv_upto(void *vbuffer, size_t buflen, unsigned timeout)
266
{
267
	char *buffer = (char *)vbuffer;
deuce's avatar
deuce committed
268
	size_t	found=0;
269 270 271
	size_t obuflen;
	void *expanded;
	size_t max_rx = buflen;
272

273 274 275 276
	if (conn_api.rx_parse_cb != NULL) {
		if (max_rx > 1)
			max_rx /= 2;
	}
277
	pthread_mutex_lock(&(conn_inbuf.mutex));
deuce's avatar
deuce committed
278
	if(conn_buf_wait_bytes(&conn_inbuf, 1, timeout))
279
		found=conn_buf_get(&conn_inbuf, buffer, max_rx);
280 281
	pthread_mutex_unlock(&(conn_inbuf.mutex));

282 283 284 285 286 287 288 289 290 291 292 293
	if (found) {
		if (conn_api.rx_parse_cb != NULL) {
			expanded = conn_api.rx_parse_cb(buffer, found, &obuflen);
			memcpy(vbuffer, expanded, obuflen);
			free(expanded);
			found = obuflen;
		}
		else {
			expanded = buffer;
			obuflen = buflen;
		}
	}
294 295 296 297

	return(found);
}

298 299

int conn_send_raw(const void *vbuffer, size_t buflen, unsigned int timeout)
300
{
301
	const char *buffer = vbuffer;
302 303
	size_t found;

304 305
	pthread_mutex_lock(&(conn_outbuf.mutex));
	found=conn_buf_wait_free(&conn_outbuf, buflen, timeout);
306
	if(found)
307 308
		found=conn_buf_put(&conn_outbuf, buffer, found);
	pthread_mutex_unlock(&(conn_outbuf.mutex));
309
	return(found);
310 311
}

312
int conn_send(const void *vbuffer, size_t buflen, unsigned int timeout)
313
{
314
	const char *buffer = vbuffer;
315
	size_t found;
316 317 318 319 320 321 322 323 324 325
	size_t obuflen;
	void *expanded;

	if (conn_api.tx_parse_cb != NULL) {
		expanded = conn_api.tx_parse_cb(buffer, buflen, &obuflen);
	}
	else {
		expanded = (void *)buffer;
		obuflen = buflen;
	}
326 327

	pthread_mutex_lock(&(conn_outbuf.mutex));
328
	found=conn_buf_wait_free(&conn_outbuf, obuflen, timeout);
329 330 331
	if(found)
		found=conn_buf_put(&conn_outbuf, buffer, found);
	pthread_mutex_unlock(&(conn_outbuf.mutex));
332 333 334 335 336

	if (conn_api.tx_parse_cb != NULL) {
		free(expanded);
	}

337 338
	return(found);
}
deuce's avatar
deuce committed
339

340 341
int conn_connect(struct bbslist *bbs)
{
342 343
	char	str[64];

344 345
	memset(&conn_api, 0, sizeof(conn_api));

346 347
	conn_api.nostatus = bbs->nostatus;
	conn_api.emulation = get_emulation(bbs);
348 349
	switch(bbs->conn_type) {
		case CONN_TYPE_RLOGIN:
350
		case CONN_TYPE_RLOGIN_REVERSED:
351 352 353 354 355 356 357 358 359 360
			conn_api.connect=rlogin_connect;
			conn_api.close=rlogin_close;
			break;
		case CONN_TYPE_TELNET:
			conn_api.connect=telnet_connect;
			conn_api.close=telnet_close;
			conn_api.binary_mode_on=telnet_binary_mode_on;
			conn_api.binary_mode_off=telnet_binary_mode_off;
			break;
		case CONN_TYPE_RAW:
361
		case CONN_TYPE_MBBS_GHOST:
362 363 364
			conn_api.connect=raw_connect;
			conn_api.close=raw_close;
			break;
365
#ifndef WITHOUT_CRYPTLIB
366 367 368 369 370 371
		case CONN_TYPE_TELNETS:
			conn_api.connect=telnets_connect;
			conn_api.close=telnets_close;
			conn_api.binary_mode_on=telnet_binary_mode_on;
			conn_api.binary_mode_off=telnet_binary_mode_off;
			break;
372
		case CONN_TYPE_SSHNA:
373 374 375 376
		case CONN_TYPE_SSH:
			conn_api.connect=ssh_connect;
			conn_api.close=ssh_close;
			break;
377
#endif
deuce's avatar
deuce committed
378
#ifndef __HAIKU__
deuce's avatar
deuce committed
379
		case CONN_TYPE_SERIAL:
380 381 382
			conn_api.connect=modem_connect;
			conn_api.close=serial_close;
			break;
deuce's avatar
deuce committed
383 384 385
		case CONN_TYPE_MODEM:
			conn_api.connect=modem_connect;
			conn_api.close=modem_close;
386
			break;
deuce's avatar
deuce committed
387
#endif
388 389 390 391 392 393
#ifdef __unix__
		case CONN_TYPE_SHELL:
			conn_api.connect=pty_connect;
			conn_api.close=pty_close;
			break;
#endif
394
		default:
395 396 397 398 399
			sprintf(str,"%s connections not supported.",conn_types[bbs->conn_type]);
			uifcmsg(str,	"`Connection type not supported`\n\n"
							"The connection type of this entry is not supported by this build.\n"
							"Either the protocol was disabled at compile time, or is\n"
							"unsupported on this plattform.");
400
			conn_api.terminate=1;
401
	}
402
	if(conn_api.connect) {
403 404
		if(conn_api.connect(bbs)) {
			conn_api.terminate = 1;
405
			while(conn_api.input_thread_running == 1 || conn_api.output_thread_running == 1)
406 407 408 409 410 411
				SLEEP(1);
		}
		else {
			while(conn_api.terminate == 0 && (conn_api.input_thread_running == 0 || conn_api.output_thread_running == 0))
				SLEEP(1);
		}
412
	}
413
	return(conn_api.terminate);
414 415
}

416
size_t conn_data_waiting(void)
417
{
418 419 420 421 422
	size_t found;

	pthread_mutex_lock(&(conn_inbuf.mutex));
	found=conn_buf_bytes(&conn_inbuf);
	pthread_mutex_unlock(&(conn_inbuf.mutex));
423
	return(found);
424 425 426 427 428 429
}

int conn_close(void)
{
	if(conn_api.close)
		return(conn_api.close());
430
	return(0);
431 432
}

433
enum failure_reason {
434 435
	 FAILURE_WHAT_FAILURE
	,FAILURE_RESOLVE
436 437 438
	,FAILURE_CANT_CREATE
	,FAILURE_CONNECT_ERROR
	,FAILURE_ABORTED
deuce's avatar
deuce committed
439
	,FAILURE_DISCONNECTED
440 441
};

442 443
int conn_socket_connect(struct bbslist *bbs)
{
444 445 446 447
	SOCKET			sock=INVALID_SOCKET;
	int				nonblock;
	int				failcode=FAILURE_WHAT_FAILURE;
	struct addrinfo	hints;
448
	struct addrinfo	*res=NULL;
449 450
	struct addrinfo	*cur;
	char			portnum[6];
451
	char str[LIST_ADDR_MAX+40];
452

453 454 455
	if (!bbs->hidepopups) {
		uifc.pop("Looking up host");
	}
456 457
	memset(&hints, 0, sizeof(hints));
	hints.ai_flags=PF_UNSPEC;
458 459 460 461 462 463 464 465 466 467 468 469
	switch(bbs->address_family) {
		case ADDRESS_FAMILY_INET:
			hints.ai_family=PF_INET;
			break;
		case ADDRESS_FAMILY_INET6:
			hints.ai_family=PF_INET6;
			break;
		case ADDRESS_FAMILY_UNSPEC:
		default:
			hints.ai_family=PF_UNSPEC;
			break;
	}
470 471
	hints.ai_socktype=SOCK_STREAM;
	hints.ai_protocol=IPPROTO_TCP;
472 473 474 475
	hints.ai_flags=AI_NUMERICSERV;
#ifdef AI_ADDRCONFIG
	hints.ai_flags|=AI_ADDRCONFIG;
#endif
476 477 478
	sprintf(portnum, "%hu", bbs->port);
	if(getaddrinfo(bbs->addr, portnum, &hints, &res)!=0) {
		failcode=FAILURE_RESOLVE;
479
		res=NULL;
480
	}
481 482 483 484
	if (!bbs->hidepopups) {
		uifc.pop(NULL);
		uifc.pop("Connecting...");
	}
485

486 487 488
	/* Drain the input buffer to avoid accidental cancel */
	while(kbhit())
		getch();
489 490

	for(cur=res; cur && sock == INVALID_SOCKET && failcode == FAILURE_WHAT_FAILURE; cur=cur->ai_next) {
491 492 493 494
		if(sock==INVALID_SOCKET) {
			sock=socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
			if(sock==INVALID_SOCKET) {
				failcode=FAILURE_CANT_CREATE;
495
				break;
496 497 498 499 500
			}
			/* Set to non-blocking for the connect */
			nonblock=-1;
			ioctlsocket(sock, FIONBIO, &nonblock);
		}
deuce's avatar
deuce committed
501

502 503 504 505 506
		if(connect(sock, cur->ai_addr, cur->ai_addrlen)) {
			switch(ERROR_VALUE) {
				case EINPROGRESS:
				case EINTR:
				case EAGAIN:
deuce's avatar
deuce committed
507
#if (EAGAIN!=EWOULDBLOCK)
508
				case EWOULDBLOCK:
deuce's avatar
deuce committed
509
#endif
510
					for(;sock!=INVALID_SOCKET;) {
511
						if (socket_writable(sock, 1000)) {
512
							if (socket_recvdone(sock, 0)) {
513 514 515
								closesocket(sock);
								sock=INVALID_SOCKET;
								continue;
516 517 518 519
							}
							else {
								goto connected;
							}
520
						}
521 522 523 524 525 526 527
						else {
							if (kbhit()) {
								failcode = FAILURE_ABORTED;
								closesocket(sock);
								sock = INVALID_SOCKET;
							}
						}
528 529
					}

530
connected:
531 532 533 534 535 536
					break;
				default:
					closesocket(sock);
					sock=INVALID_SOCKET;
					continue;
			}
537 538
		}
	}
539 540 541 542 543
	if (sock != INVALID_SOCKET) {
		freeaddrinfo(res);
		res=NULL;
		nonblock=0;
		ioctlsocket(sock, FIONBIO, &nonblock);
544
		if (!socket_recvdone(sock, 0)) {
545 546 547
			int keepalives = TRUE;
			setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepalives, sizeof(keepalives));

548 549 550
			if (!bbs->hidepopups) {
				uifc.pop(NULL);
			}
551 552
			return(sock);
		}
deuce's avatar
Typo.  
deuce committed
553
		failcode=FAILURE_DISCONNECTED;
deuce's avatar
deuce committed
554
	}
555 556
	if (failcode == FAILURE_WHAT_FAILURE)
		failcode=FAILURE_CONNECT_ERROR;
557

558 559
	if(res)
		freeaddrinfo(res);
560 561 562
	if (!bbs->hidepopups) {
		uifc.pop(NULL);
	}
563
	conn_api.terminate=-1;
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
	if (!bbs->hidepopups) {
		switch(failcode) {
			case FAILURE_RESOLVE:
				sprintf(str,"Cannot resolve %s!",bbs->addr);
				uifcmsg(str,	"`Cannot Resolve Host`\n\n"
								"The system is unable to resolve the hostname... double check the spelling.\n"
								"If it's not an issue with your DNS settings, the issue is probobly\n"
								"with the DNS settings of the system you are trying to contact.");
				break;
			case FAILURE_CANT_CREATE:
				sprintf(str,"Cannot create socket (%d)!",ERROR_VALUE);
				uifcmsg(str,
								"`Unable to create socket`\n\n"
								"Your system is either dangerously low on resources, or there\n"
								"is a problem with your TCP/IP stack.");
				break;
			case FAILURE_CONNECT_ERROR:
				sprintf(str,"Connect error (%d)!",ERROR_VALUE);
				uifcmsg(str
								,"`The connect call returned an error`\n\n"
								 "The call to connect() returned an unexpected error code.");
				break;
			case FAILURE_ABORTED:
				uifcmsg("Connection Aborted.",	"`Connection Aborted`\n\n"
								"Connection to the remote system aborted by keystroke.");
				break;
			case FAILURE_DISCONNECTED:
				sprintf(str,"Connect error (%d)!",ERROR_VALUE);
				uifcmsg(str
								,"`SyncTERM failed to connect`\n\n"
								 "After connect() succeeded, the socket was in a disconnected state.");
				break;
		}
597
	}
598 599 600 601
	conn_close();
	if (sock != INVALID_SOCKET)
		closesocket(sock);
	return(INVALID_SOCKET);
602
}
603

604 605 606 607
void conn_binary_mode_on(void)
{
	if(conn_api.binary_mode_on)
		conn_api.binary_mode_on();
608 609
}

610
void conn_binary_mode_off(void)
611
{
612 613
	if(conn_api.binary_mode_off)
		conn_api.binary_mode_off();
614
}