sexpots.c 47.9 KB
Newer Older
1 2 3 4 5 6
/* Synchronet External Plain Old Telephone System (POTS) support */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
7
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *																			*
 * This program is free software; you can redistribute it and/or			*
 * modify it under the terms of the GNU General Public License				*
 * as published by the Free Software Foundation; either version 2			*
 * of the License, or (at your option) any later version.					*
 * See the GNU General Public License for more details: gpl.txt or			*
 * http://www.fsf.org/copyleft/gpl.html										*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

/* ANSI C */
deuce's avatar
deuce committed
23
#include <stdarg.h>
24 25 26 27 28 29
#include <stdio.h>

/* xpdev lib */
#include "dirwrap.h"
#include "datewrap.h"
#include "sockwrap.h"
Rob Swindell's avatar
Rob Swindell committed
30
#include "threadwrap.h"
31 32 33 34 35 36 37 38 39
#include "ini_file.h"

/* comio lib */
#include "comio.h"

/* sbbs */
#include "telnet.h"

/* constants */
rswindell's avatar
rswindell committed
40
#define NAME					"SEXPOTS"
rswindell's avatar
rswindell committed
41
#define TITLE					"Synchronet External POTS Support"
42
#define DESCRIPTION				"Connects a communications port (e.g. COM1) to a TCP port (e.g. Telnet)"
43 44 45
#define MDM_TILDE_DELAY			500	/* milliseconds */

/* global vars */
46
BOOL	daemonize=FALSE;
47
BOOL	cls=FALSE;
48
char	prompt[INI_MAX_VALUE_LEN+1];
49
int		prompt_timeout = 60; // seconds
50 51
char	termtype[INI_MAX_VALUE_LEN+1]	= NAME;
char	termspeed[INI_MAX_VALUE_LEN+1]	= "28800,28800";	/* "tx,rx", max length not defined */
52

53 54 55 56
char	mdm_init[INI_MAX_VALUE_LEN]		= "AT&F";
char	mdm_autoans[INI_MAX_VALUE_LEN]	= "ATS0=1";
char	mdm_cid[INI_MAX_VALUE_LEN]		= "AT+VCID=1";
char	mdm_cleanup[INI_MAX_VALUE_LEN]	= "ATS0=0";
57 58
char	mdm_answer[INI_MAX_VALUE_LEN]	= "ATA";
char	mdm_ring[INI_MAX_VALUE_LEN]		= "RING";
59 60
int		mdm_ringcount = 1;
int		mdm_ringinterval = 6000;
61
BOOL	mdm_null=FALSE;
62 63
BOOL	mdm_manswer=FALSE;		/* Manual Answer */

64
int		mdm_timeout=5;			/* seconds */
65
int		mdm_reinit=60;			/* minutes */
rswindell's avatar
rswindell committed
66
int		mdm_cmdretry=2;			/* command retries (total attempts-1) */
67

deuce's avatar
deuce committed
68
#ifdef _WIN32
69
char	com_dev[MAX_PATH+1]				= "COM1";
deuce's avatar
deuce committed
70 71 72 73
#else
char	com_dev[MAX_PATH+1]				= "/dev/ttyd0";
#endif
COM_HANDLE	com_handle=COM_HANDLE_INVALID;
74 75 76
BOOL	com_handle_passed=FALSE;
BOOL	com_alreadyconnected=FALSE;
BOOL	com_hangup=TRUE;
77
ulong	com_baudrate=0;
78
BOOL	dcd_ignore=FALSE;
79
int		dcd_timeout=10;	/* seconds */
rswindell's avatar
rswindell committed
80
ulong	dtr_delay=100;	/* milliseconds */
81
int		hangup_attempts=10;
82

83 84 85
BOOL	terminated=FALSE;
BOOL	terminate_after_one_call=FALSE;

86
SOCKET	sock=INVALID_SOCKET;
87
char	host[MAX_PATH+1]				= "localhost";
88
ushort	port=IPPORT_TELNET;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

/* stats */
ulong	total_calls=0;
ulong	bytes_sent=0;
ulong	bytes_received=0;

/* .ini over-rideable */
int		log_level=LOG_INFO;
BOOL	pause_on_exit=FALSE;
BOOL	tcp_nodelay=TRUE;

/* telnet stuff */
BOOL	telnet=TRUE;
BOOL	debug_telnet=FALSE;
uchar	telnet_local_option[0x100];
uchar	telnet_remote_option[0x100];
BYTE	telnet_cmd[64];
int		telnet_cmdlen;
107
BOOL	telnet_advertise_cid=FALSE;
108

rswindell's avatar
rswindell committed
109
/* ident (RFC1413) server stuff */
110 111 112
BOOL	ident=FALSE;
ushort	ident_port=IPPORT_IDENT;
ulong	ident_interface=INADDR_ANY;
113
char	ident_response[INI_MAX_VALUE_LEN]	= "CALLERID:SEXPOTS";
114 115 116 117 118

/* Caller-ID stuff */
char	cid_name[64];
char	cid_number[64];

119 120 121 122
/****************************************************************************/
/****************************************************************************/
int usage(const char* fname)
{
123 124
	printf("usage: %s [ini file] [options]\n"
		"\nOptions:"
rswindell's avatar
rswindell committed
125
		"\n"
126 127
		"\n-null                 No 'AT commands' sent to modem"
		"\n-com <device>         Specify communications port device"
rswindell's avatar
rswindell committed
128
		"\n-baud <rate>          Specify baud rate for communications port"
129 130 131 132
		"\n-live [handle]        Communications port is already open/connected"
		"\n-nohangup             Do not hangup (drop DTR) after call"
		"\n-host <addr | name>   Specify TCP server hostname or IP address"
		"\n-port <number>        Specify TCP port number"
133
		"\n-debug                Enable debug log output"
rswindell's avatar
rswindell committed
134 135 136 137 138
#if defined(_WIN32)
		"\n\nNT Service\n"
		"\n-install              install and enable NT service (%s)"
		"\n-service              run as an NT service (background execution)"
		"\n-remove               remove NT service"
rswindell's avatar
rswindell committed
139
		"\n-enable               enable NT service (auto-start during boot)"
rswindell's avatar
rswindell committed
140
		"\n-disable              disable NT service"
141 142
#else
		"\n-syslog               log to syslog rather than stdout/err"
rswindell's avatar
rswindell committed
143
#endif
144
		"\n"
rswindell's avatar
rswindell committed
145
		,getfname(fname)
146 147 148
#if defined(_WIN32)
		,NAME
#endif
Rob Swindell's avatar
Rob Swindell committed
149
		);
150 151 152 153

	return 0;
}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
#if defined(_WIN32)

static WORD event_type(int level)
{
	switch(level) {
		case LOG_WARNING:
			return(EVENTLOG_WARNING_TYPE);
		case LOG_NOTICE:
		case LOG_INFO:
		case LOG_DEBUG:
			return(EVENTLOG_INFORMATION_TYPE);
	}
/*
	LOG_EMERG
	LOG_ALERT
	LOG_CRIT
	LOG_ERR
*/
	return(EVENTLOG_ERROR_TYPE);
}

static int syslog(int level, char *fmt, ...)
{
	va_list argptr;
	char sbuf[1024];
	char* p=sbuf;
	int	retval;
	static HANDLE event_handle;

    va_start(argptr,fmt);
    retval=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
	sbuf[sizeof(sbuf)-1]=0;
    va_end(argptr);

	if(event_handle == NULL)
		event_handle = RegisterEventSource(
			NULL,		// server name for source (NULL = local computer)
			TITLE);		// source name for registered handle

	if(event_handle != NULL)
		ReportEvent(event_handle,	// event log handle
			event_type(level),		// event type
			0,						// category zero
			0,						// event identifier
			NULL,					// no user security identifier
			1,						// one string
			0,						// no data
			&p,						// pointer to string array
			NULL);					// pointer to data

    return(retval);
}

207 208 209 210
#endif

/****************************************************************************/
/****************************************************************************/
211
void lputs(int level, const char* str)
212 213 214 215 216 217 218 219 220 221 222 223
{
	time_t		t;
	struct tm	tm;
	char		tstr[32];
#if defined(_WIN32)
	char dbgmsg[1024];
	_snprintf(dbgmsg,sizeof(dbgmsg),"%s %s", NAME, str);
	if(log_level==LOG_DEBUG)
		OutputDebugString(dbgmsg);
#endif

	if(level>log_level)
224
		return;
225

deuce's avatar
deuce committed
226
	if(daemonize) {
227 228 229 230 231 232 233 234 235
		syslog(level, "%s", str);
	} else {
		t=time(NULL);
		if(localtime_r(&t,&tm)==NULL)
			tstr[0]=0;
		else
			sprintf(tstr,"%d/%d %02d:%02d:%02d "
				,tm.tm_mon+1,tm.tm_mday
				,tm.tm_hour,tm.tm_min,tm.tm_sec);
deuce's avatar
deuce committed
236

237
		fprintf(level>=LOG_NOTICE ? stdout:stderr, "%s %s\n", tstr, str);
deuce's avatar
deuce committed
238
	}
239 240 241 242
}

/****************************************************************************/
/****************************************************************************/
243
void lprintf(int level, char *fmt, ...)
244 245 246 247 248 249 250 251
{
	va_list argptr;
	char sbuf[1024];

    va_start(argptr,fmt);
    vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
	sbuf[sizeof(sbuf)-1]=0;
    va_end(argptr);
252
    lputs(level,sbuf);
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
}


#if defined(_WIN32)

#define NTSVC_TIMEOUT_STARTUP	30000	/* Milliseconds */
#define NTSVC_TIMEOUT_SHUTDOWN	30000	/* Milliseconds */

SERVICE_STATUS_HANDLE	svc_status_handle;
SERVICE_STATUS			svc_status;

void WINAPI ServiceControlHandler(DWORD dwCtrlCode)
{
	switch(dwCtrlCode) {
		case SERVICE_CONTROL_STOP:
		case SERVICE_CONTROL_SHUTDOWN:
			lprintf(LOG_NOTICE,"Received termination control signal: %d", dwCtrlCode);
			svc_status.dwWaitHint=NTSVC_TIMEOUT_SHUTDOWN;
			svc_status.dwCurrentState=SERVICE_STOP_PENDING;
			SetServiceStatus(svc_status_handle, &svc_status);
			terminated=TRUE;
//			SetEvent(service_event);
			break;
		case SERVICE_CONTROL_INTERROGATE:
			lprintf(LOG_DEBUG,"Ignoring service control signal: SERVICE_CONTROL_INTERROGATE");
			break;
		default:
			lprintf(LOG_WARNING,"Received unsupported service control signal: %d", dwCtrlCode);
			break;
	}
}
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

/* ChangeServiceConfig2 is a Win2K+ API function, must call dynamically */
typedef WINADVAPI BOOL (WINAPI *ChangeServiceConfig2_t)(SC_HANDLE, DWORD, LPCVOID);

static void describe_service(HANDLE hSCMlib, SC_HANDLE hService, char* description)
{
	ChangeServiceConfig2_t changeServiceConfig2;
	static SERVICE_DESCRIPTION service_desc;
  
	if(hSCMlib==NULL)
		return;

	service_desc.lpDescription=description;

	if((changeServiceConfig2 = (ChangeServiceConfig2_t)GetProcAddress(hSCMlib, "ChangeServiceConfig2A"))!=NULL)
		changeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &service_desc);
}

static BOOL register_event_source(char* name, char* path)
{
	char	keyname[256];
	HKEY	hKey;
	DWORD	type;
	DWORD	disp;
	LONG	retval;
	char*	value;

	sprintf(keyname,"system\\CurrentControlSet\\services\\eventlog\\application\\%s",name);

	retval=RegCreateKeyEx(
		HKEY_LOCAL_MACHINE,			/* handle to an open key */
		keyname,			/* address of subkey name */
		0,				/* reserved */
		"",				/* address of class string */
		0,				/* special options flag */
		KEY_ALL_ACCESS, /* desired security access */
		NULL,           /* address of key security structure */
		&hKey,			/* address of buffer for opened handle */
		&disp			/* address of disposition value buffer */
		);

	if(retval!=ERROR_SUCCESS) {
		fprintf(stderr,"!Error %d creating/opening registry key (HKLM\\%s)\n"
			,retval,keyname);
		return(FALSE);
	}

	value="EventMessageFile";
	retval=RegSetValueEx(
		hKey,			/* handle to key to set value for */
		value,			/* name of the value to set */
		0,				/* reserved */
		REG_SZ,			/* flag for value type */
		path,			/* address of value data */
		strlen(path)	/* size of value data */
		);

	if(retval!=ERROR_SUCCESS) {
		RegCloseKey(hKey);
		fprintf(stderr,"!Error %d setting registry key value (%s)\n"
			,retval,value);
		return(FALSE);
	}

	value="TypesSupported";
	type=EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
	retval=RegSetValueEx(
		hKey,			/* handle to key to set value for */
		value,			/* name of the value to set */
		0,				/* reserved */
		REG_DWORD,		/* flag for value type */
		(BYTE*)&type,	/* address of value data */
		sizeof(type)	/* size of value data */
		);

	RegCloseKey(hKey);

	if(retval!=ERROR_SUCCESS) {
		fprintf(stderr,"!Error %d setting registry key value (%s)\n"
			,retval,value);
		return(FALSE);
	}

	return(TRUE);
}


/****************************************************************************/
/* Install NT service														*/
/****************************************************************************/
static int install(void)
{
	HANDLE		hSCMlib;
    SC_HANDLE   hSCManager;
    SC_HANDLE   hService;
    char		path[MAX_PATH+1];
	char		cmdline[MAX_PATH+1];

	printf("Installing service: %-40s ... ", TITLE);

	hSCMlib = LoadLibrary("ADVAPI32.DLL");

    if(GetModuleFileName(NULL,path,sizeof(path))==0)
    {
        fprintf(stderr,"\n!ERROR %d getting module file name\n",GetLastError());
        return(-1);
    }

    hSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if(hSCManager==NULL) {
		fprintf(stderr,"\n!ERROR %d opening SC manager\n",GetLastError());
		return(-1);
	}

	/* Install new service */
	wsprintf(cmdline,"%s service", path);
    hService = CreateService(
        hSCManager,						// SCManager database
        NAME,							// name of service
        TITLE,							// name to display
        SERVICE_ALL_ACCESS,				// desired access
        SERVICE_WIN32_OWN_PROCESS,		// service type
		SERVICE_AUTO_START,				// start type (auto or manual)
        SERVICE_ERROR_NORMAL,			// error control type
        cmdline,						// service's binary
        NULL,							// no load ordering group
        NULL,							// no tag identifier
        "",								// dependencies
        NULL,							// LocalSystem account
        NULL);							// no password

	if(hService==NULL)
		fprintf(stderr,"\n!ERROR %d creating service\n",GetLastError());
	else {
		describe_service(hSCMlib, hService, DESCRIPTION);
		CloseServiceHandle(hService);
		printf("Successful\n");

		register_event_source(TITLE,path);
	}


	if(hSCMlib!=NULL)
		FreeLibrary(hSCMlib);

	CloseServiceHandle(hSCManager);

	return(0);
}
rswindell's avatar
rswindell committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

/****************************************************************************/
/* Utility function to remove a service cleanly (stopping if necessary)		*/
/****************************************************************************/
static void remove_service(SC_HANDLE hSCManager, SC_HANDLE hService, char* name, char* disp_name)
{
	SERVICE_STATUS	status;

	printf("Removing service: %-40s ... ", disp_name);

	if(hService==NULL) {

		hService = OpenService(hSCManager, name, SERVICE_ALL_ACCESS);

		if(hService==NULL) {
			printf("\n!ERROR %d opening service: %s\n",GetLastError(),name);
			return;
		}
	}

    // try to stop the service
    if(ControlService( hService, SERVICE_CONTROL_STOP, &status))
    {
        printf("\nStopping: %s ... ",name);

        while(QueryServiceStatus(hService, &status) && status.dwCurrentState == SERVICE_STOP_PENDING)
			Sleep(1000);

        if(status.dwCurrentState == SERVICE_STOPPED)
            printf("Stopped.\n");
        else
            printf("FAILED!\n");
    }

    // now remove the service
    if(DeleteService(hService))
		printf("Successful\n");
	else
		printf("!ERROR %d\n",GetLastError());
    CloseServiceHandle(hService);
}

/****************************************************************************/
/* Uninstall one or all services											*/
/****************************************************************************/
static int uninstall(void)
{
    SC_HANDLE   hSCManager;

    hSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if(hSCManager==NULL) {
		fprintf(stderr,"!ERROR %d opening SC manager\n",GetLastError());
		return(-1);
	}

	remove_service(hSCManager,NULL,NAME,TITLE);

	CloseServiceHandle(hSCManager);

	return(0);
}

/****************************************************************************/
/* Utility function to disable a service									*/
/****************************************************************************/
static void set_service_start_type(SC_HANDLE hSCManager, DWORD start_type)
{
    SC_HANDLE		hService;

	printf("%s service: %-40s ... "
		,start_type==SERVICE_DISABLED ? "Disabling" : "Enabling", TITLE);

    hService = OpenService(hSCManager, NAME, SERVICE_ALL_ACCESS);

	if(hService==NULL) {
		printf("\n!ERROR %d opening service: %s\n",GetLastError(),NAME);
		return;
	}

	if(!ChangeServiceConfig(
		hService,				// handle to service
		SERVICE_NO_CHANGE,		// type of service
		start_type,				// when to start service
		SERVICE_NO_CHANGE,		// severity if service fails to start
		NULL,					// pointer to service binary file name
		NULL,					// pointer to load ordering group name
		NULL,					// pointer to variable to get tag identifier
		NULL,					// pointer to array of dependency names
		NULL,					// pointer to account name of service
		NULL,					// pointer to password for service account
		NULL					// pointer to display name
		))
		printf("\n!ERROR %d changing service config for: %s\n",GetLastError(),NAME);
	else
		printf("Successful\n");

    CloseServiceHandle(hService);
}

/****************************************************************************/
/* Enable (set to auto-start) or disable one or all services				*/
/****************************************************************************/
static int enable(BOOL enabled)
{
    SC_HANDLE   hSCManager;

    hSCManager = OpenSCManager(
                        NULL,                   // machine (NULL == local)
                        NULL,                   // database (NULL == default)
                        SC_MANAGER_ALL_ACCESS   // access required
                        );
    if(hSCManager==NULL) {
		fprintf(stderr,"!ERROR %d opening SC manager\n",GetLastError());
		return(-1);
	}

	set_service_start_type(hSCManager
		,enabled ? SERVICE_AUTO_START : SERVICE_DISABLED);

	CloseServiceHandle(hSCManager);

	return(0);
}

565 566
#endif

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
#ifdef _WINSOCKAPI_

/* Note: Don't call WSACleanup() or TCP session will close! */
WSADATA WSAData;	

static BOOL winsock_startup(void)
{
	int		status;             /* Status Code */

    if((status = WSAStartup(MAKEWORD(1,1), &WSAData))==0) {
		lprintf(LOG_INFO,"%s %s",WSAData.szDescription, WSAData.szSystemStatus);
		return(TRUE);
	}

    lprintf(LOG_ERR,"WinSock startup ERROR %d", status);
	return(FALSE);
}

#else /* No WINSOCK */

#define winsock_startup()	(TRUE)	

#endif

/****************************************************************************/
/****************************************************************************/
BOOL modem_send(COM_HANDLE com_handle, const char* str)
{
	const char* p;
596
	char		ch;
597 598 599

	lprintf(LOG_INFO,"Modem Command: %s", str);
	for(p=str; *p; p++) {
600 601
		ch=*p;
		if(ch=='~') {
602 603 604
			SLEEP(MDM_TILDE_DELAY);
			continue;
		}
605 606 607 608 609 610 611
		if(ch=='^' && *(p+1)) {	/* Support ^X for control characters embedded in modem command strings */
			p++;
			ch=*p;
			if(ch!='^' && ch>='@')	/* ^^ to send an '^' char to the modem */
				ch-='@';
		}
		if(!comWriteByte(com_handle,ch))
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
			return FALSE;
	}
	SLEEP(100);
	comPurgeInput(com_handle);
	return comWriteByte(com_handle, '\r');
}

/****************************************************************************/
/****************************************************************************/
BOOL modem_response(COM_HANDLE com_handle, char *str, size_t maxlen)
{
	BYTE	ch;
	size_t	len=0;
	time_t	start;

	lprintf(LOG_DEBUG,"Waiting for Modem Response ...");
	start=time(NULL);
	while(1){
		if(time(NULL)-start >= mdm_timeout) {
rswindell's avatar
rswindell committed
631
			lprintf(LOG_WARNING,"Modem Response TIMEOUT (%lu seconds) on %s", mdm_timeout, com_dev);
632 633 634
			return FALSE;
		}
		if(len >= maxlen) {
rswindell's avatar
rswindell committed
635 636
			lprintf(LOG_WARNING,"Modem Response too long (%u >= %u) from %s"
				,len, maxlen, com_dev);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
			return FALSE;
		}
		if(!comReadByte(com_handle, &ch)) {
			YIELD();
			continue;
		}
		if(ch<' ' && len==0)	/* ignore prepended control chars */
			continue;

		if(ch=='\r') {
			while(comReadByte(com_handle,&ch))	/* eat trailing ctrl chars (e.g. 'LF') */
#if 0
				lprintf(LOG_DEBUG, "eating ch=%02X", ch)
#endif
				;
			break;
		}
		str[len++]=ch;
	}
	str[len]=0;

	return TRUE;
}

/****************************************************************************/
/****************************************************************************/
BOOL modem_command(COM_HANDLE com_handle, const char* cmd)
{
rswindell's avatar
rswindell committed
665 666 667 668
	char	resp[128];
	int		i;

	for(i=0;i<=mdm_cmdretry;i++) {
669 670
		if(terminated)
			return FALSE;
rswindell's avatar
rswindell committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
		if(i) {
			lprintf(LOG_WARNING,"Retry #%u: sending modem command (%s) on %s", i, cmd, com_dev);
			lprintf(LOG_DEBUG,"Dropping DTR on %s", com_dev);
			if(!comLowerDTR(com_handle))
				lprintf(LOG_ERR,"ERROR %u lowering DTR on %s", COM_ERROR_VALUE, com_dev);
			SLEEP(dtr_delay);
			lprintf(LOG_DEBUG,"Raising DTR on %s", com_dev);
			if(!comRaiseDTR(com_handle))
				lprintf(LOG_ERR,"ERROR %u raising DTR on %s", COM_ERROR_VALUE, com_dev);
		}
		if(!modem_send(com_handle, cmd)) {
			lprintf(LOG_ERR,"ERROR %u sending modem command (%s) on %s"
				,COM_ERROR_VALUE, cmd, com_dev);
			continue;
		}
686

rswindell's avatar
rswindell committed
687 688
		if(modem_response(com_handle, resp, sizeof(resp)))
			break;
689 690
	}

rswindell's avatar
rswindell committed
691 692 693 694 695 696
	if(i<=mdm_cmdretry) {
		lprintf(LOG_INFO,"Modem Response: %s", resp);
		return TRUE;
	}
	lprintf(LOG_ERR,"Modem command (%s) failure on %s (%u attempts)", cmd, com_dev, i);
	return FALSE;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
}

/****************************************************************************/
/****************************************************************************/
void close_socket(SOCKET* sock)
{
	if(*sock != INVALID_SOCKET) {
		shutdown(*sock,SHUT_RDWR);	/* required on Unix */
		closesocket(*sock);
		*sock=INVALID_SOCKET;
	}
}

/****************************************************************************/
/****************************************************************************/
void cleanup(void)
{
714 715
	terminated=TRUE;

716 717 718 719
	lprintf(LOG_INFO,"Cleaning up ...");


	if(com_handle!=COM_HANDLE_INVALID) {
720
		if(!mdm_null && mdm_cleanup[0])
721
			modem_command(com_handle, mdm_cleanup);
722 723
		if(!com_handle_passed)
			comClose(com_handle);
724 725 726 727 728 729 730 731 732
	}

	close_socket(&sock);

#ifdef _WINSOCKAPI_
	WSACleanup();
#endif

	lprintf(LOG_INFO,"Done (handled %lu calls).", total_calls);
rswindell's avatar
rswindell committed
733 734 735 736 737 738 739

#if defined(_WIN32)
	if(daemonize && svc_status_handle!=0) {
		svc_status.dwCurrentState=SERVICE_STOPPED;
		SetServiceStatus(svc_status_handle, &svc_status);
	} else
#endif
740 741 742 743 744 745
	if(pause_on_exit) {
		printf("Hit enter to continue...");
		getchar();
	}
}

rswindell's avatar
rswindell committed
746 747
/* Returns 0 on error, Modem status bit-map value otherwise */
int modem_status(COM_HANDLE com_handle)
748
{
rswindell's avatar
rswindell committed
749
	int	mdm_status;
750

rswindell's avatar
rswindell committed
751 752 753 754 755 756 757
	if((mdm_status=comGetModemStatus(com_handle)) == COM_ERROR) {
		lprintf(LOG_ERR,"ERROR %u getting modem status"
			,COM_ERROR_VALUE);
		return 0;
	}
	return mdm_status;
}
758

rswindell's avatar
rswindell committed
759 760 761 762
/* Returns TRUE if DCD (Data Carrier Detect) is high */
BOOL carrier_detect(COM_HANDLE com_handle)
{
	return (modem_status(com_handle)&COM_DCD) ? TRUE:FALSE;
763 764
}

765 766
/****************************************************************************/
/****************************************************************************/
deuce's avatar
deuce committed
767
BOOL wait_for_call(COM_HANDLE com_handle)
768 769
{
	char		str[128];
rswindell's avatar
rswindell committed
770
	char*		p;
771
	time_t		start=time(NULL);
772 773 774
	msclock_t	now;
	msclock_t	lastring=0;
	int			ring_count=0;
775

776 777 778
	ZERO_VAR(cid_name);
	ZERO_VAR(cid_number);

rswindell's avatar
rswindell committed
779 780
	if(!comRaiseDTR(com_handle))
		lprintf(LOG_ERR,"ERROR %u raising DTR", COM_ERROR_VALUE);
781

782 783 784
	if(com_alreadyconnected)
		return TRUE;

rswindell's avatar
rswindell committed
785 786 787 788 789 790
	if(!mdm_null) {
		if(mdm_init[0]) {
			lprintf(LOG_INFO,"Initializing modem:");
			if(!modem_command(com_handle, mdm_init))
				return FALSE;
		}
791
		if(!mdm_manswer && mdm_autoans[0]) {
rswindell's avatar
rswindell committed
792 793 794 795 796 797 798 799 800
			lprintf(LOG_INFO,"Setting modem to auto-answer:");
			if(!modem_command(com_handle, mdm_autoans))
				return FALSE;
		}
		if(mdm_cid[0]) {
			lprintf(LOG_INFO,"Enabling modem Caller-ID:");
			if(!modem_command(com_handle, mdm_cid))
				return FALSE;
		}
801 802
	}

803
	lprintf(LOG_INFO,"Waiting for incoming call (%s) ...", mdm_manswer ? "Ring Indication" : "Carrier Detect");
804 805 806
	while(1) {
		if(terminated)
			return FALSE;
807
		if(comReadLine(com_handle, str, sizeof(str), /* timeout (ms): */250) > 0) {
808
			truncsp(str);
809 810
			if(str[0]==0)
				continue;
rswindell's avatar
rswindell committed
811
			lprintf(LOG_DEBUG,"Received from modem: '%s'", str);
rswindell's avatar
rswindell committed
812 813
			p=str;
			SKIP_WHITESPACE(p);
814 815 816 817 818
			if(*p) {
				lprintf(LOG_INFO, "Modem Message: %s", p);
				if(strncmp(p,"CONNECT ",8)==0) {
					long rate=atoi(p+8);
					if(rate)
Rob Swindell's avatar
Rob Swindell committed
819
						SAFEPRINTF2(termspeed,"%ld,%ld", rate, rate);
820
				}
rswindell's avatar
rswindell committed
821 822 823
				else if(strncmp(p,"NMBR",4)==0 || strncmp(p,"MESG",4)==0) {
					p+=4;
					FIND_CHAR(p,'=');
824
					SKIP_CHAR(p,'=');
rswindell's avatar
rswindell committed
825 826 827 828 829 830 831
					SKIP_WHITESPACE(p);
					if(cid_number[0]==0)	/* Don't overwrite, if multiple messages received */
						SAFECOPY(cid_number, p);
				}
				else if(strncmp(p,"NAME",4)==0) {
					p+=4;
					FIND_CHAR(p,'=');
832
					SKIP_CHAR(p,'=');
rswindell's avatar
rswindell committed
833 834 835 836 837 838 839
					SKIP_WHITESPACE(p);
					SAFECOPY(cid_name, p);
				}
				else if(strcmp(p,"NO CARRIER")==0) {
					ZERO_VAR(cid_name);
					ZERO_VAR(cid_number);
				}
840
				else if(mdm_ring[0] && strcmp(p,mdm_ring)==0 && mdm_manswer && mdm_answer[0]) {
841 842 843 844 845 846 847 848 849
					now = msclock();
					if(now < lastring || now - lastring > mdm_ringinterval)
						ring_count = 0;
					lastring = now;
					if(++ring_count >= mdm_ringcount) {
						if(!modem_send(com_handle, mdm_answer)) {
							lprintf(LOG_ERR,"ERROR %u sending modem command (%s) on %s"
								,COM_ERROR_VALUE, mdm_answer, com_dev);
						}
850 851
					}
				}
852
			}
853
			continue;	/* don't check DCD until we've received all the modem msgs */
854
		}
855
		if(carrier_detect(com_handle))
856
			break;
rswindell's avatar
rswindell committed
857
		if(mdm_reinit && (time(NULL)-start)/60 >= mdm_reinit) {
858 859 860
			lprintf(LOG_INFO,"Re-initialization timer elapsed: %u minutes", mdm_reinit);
			return TRUE;
		}
861 862
	}

863 864 865 866 867 868 869 870 871 872
	if(strcmp(cid_name,"P")==0)
		SAFECOPY(cid_name,"Private");
	else if(strcmp(cid_name,"O")==0)
		SAFECOPY(cid_name,"Out-of-area");

	if(strcmp(cid_number,"P")==0)
		SAFECOPY(cid_number,"Private");
	else if(strcmp(cid_number,"O")==0)
		SAFECOPY(cid_number,"Out-of-area");

rswindell's avatar
rswindell committed
873
	lprintf(LOG_INFO,"Carrier detected");
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
	return TRUE;
}

/****************************************************************************/
/****************************************************************************/
u_long resolve_ip(const char *addr)
{
	HOSTENT*	host;
	const char*	p;

	if(*addr==0)
		return((u_long)INADDR_NONE);

	for(p=addr;*p;p++)
		if(*p!='.' && !isdigit(*p))
			break;
	if(!(*p))
		return(inet_addr(addr));
	if((host=gethostbyname(addr))==NULL) 
		return((u_long)INADDR_NONE);
	return(*((ulong*)host->h_addr_list[0]));
}

/****************************************************************************/
/****************************************************************************/
SOCKET connect_socket(const char* host, ushort port)
{
	SOCKET		sock;
	SOCKADDR_IN	addr;

	if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == INVALID_SOCKET) {
		lprintf(LOG_ERR,"ERROR %u creating socket", ERROR_VALUE);
		return INVALID_SOCKET;
	}

	lprintf(LOG_DEBUG,"Setting TCP_NODELAY to %d",tcp_nodelay);
	setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char*)&tcp_nodelay,sizeof(tcp_nodelay));

	ZERO_VAR(addr);
	addr.sin_addr.s_addr = resolve_ip(host);
	addr.sin_family = AF_INET;
	addr.sin_port   = htons(port);

	lprintf(LOG_INFO,"Connecting to %s port %u", host, port);
	if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
rswindell's avatar
rswindell committed
919 920
		lprintf(LOG_INFO,"Connected from COM Port (handle %u) to %s TCP port %u using socket descriptor %u"
			,com_handle, host, port, sock);
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
		return sock;
	}

	lprintf(LOG_ERR,"SOCKET ERROR %u connecting to %s port %u", ERROR_VALUE, host, port);
	closesocket(sock);

	return INVALID_SOCKET;
}

BOOL call_terminated;
BOOL input_thread_terminated;

/****************************************************************************/
/****************************************************************************/
void input_thread(void* arg)
{
	BYTE		ch;

	lprintf(LOG_DEBUG,"Input thread started");
	while(!call_terminated) {
		if(!comReadByte(com_handle, &ch)) {
			YIELD();
			continue;
		}
		if(telnet && ch==TELNET_IAC)
			sendsocket(sock, &ch, sizeof(ch));	/* escape Telnet IAC char (255) when in telnet mode */
		sendsocket(sock, &ch, sizeof(ch));
		bytes_received++;
	}
	lprintf(LOG_DEBUG,"Input thread terminated");
	input_thread_terminated=TRUE;
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
void ident_server_thread(void* arg)
{
	int				result;
	SOCKET			sock;
	SOCKADDR_IN		server_addr={0};
	fd_set			socket_set;
	struct timeval tv;

	lprintf(LOG_DEBUG,"Ident server thread started");

	if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) == INVALID_SOCKET) {
		lprintf(LOG_ERR,"ERROR %u creating socket", ERROR_VALUE);
		return;
	}
	
    memset(&server_addr, 0, sizeof(server_addr));

	server_addr.sin_addr.s_addr = htonl(ident_interface);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port   = htons(ident_port);

    if(bind(sock,(struct sockaddr *)&server_addr,sizeof(server_addr))!=0) {
		lprintf(LOG_ERR,"ERROR %u binding ident server socket", ERROR_VALUE);
		close_socket(&sock);
		return;
	}

    if(listen(sock, 1)) {
		lprintf(LOG_ERR,"!ERROR %u listening on ident server socket", ERROR_VALUE);
		close_socket(&sock);
		return;
	}

	while(!terminated) {
		/* now wait for connection */

		FD_ZERO(&socket_set);
		FD_SET(sock,&socket_set);

		tv.tv_sec=5;
		tv.tv_usec=0;

		if((result=select(sock+1,&socket_set,NULL,NULL,&tv))<1) {
			if(result==0)
				continue;
			if(ERROR_VALUE==EINTR)
				lprintf(LOG_DEBUG,"Ident Server listening interrupted");
			else if(ERROR_VALUE == ENOTSOCK)
            	lprintf(LOG_NOTICE,"Ident Server sockets closed");
			else
				lprintf(LOG_WARNING,"!ERROR %d selecting ident socket",ERROR_VALUE);
			continue;
		}

		if(FD_ISSET(sock,&socket_set)) {
			SOCKADDR_IN		client_addr;
			socklen_t		client_addr_len;
			SOCKET			client_socket=INVALID_SOCKET;
			char			request[128];
			char			response[256];
			int				rd;

			client_addr_len = sizeof(client_addr);
			client_socket = accept(sock, (struct sockaddr *)&client_addr, &client_addr_len);
			if(client_socket != INVALID_SOCKET) {
				lprintf(LOG_INFO,"Ident request from %s : %u"
					,inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
				FD_ZERO(&socket_set);
				FD_SET(client_socket,&socket_set);
				tv.tv_sec=5;
				tv.tv_usec=0;
				if(select(client_socket+1,&socket_set,NULL,NULL,&tv)==1) {
					lprintf(LOG_DEBUG,"Ident select");
					if((rd=recv(client_socket, request, sizeof(request), 0)) > 0) {
						request[rd]=0;
						truncsp(request);
						lprintf(LOG_INFO,"Ident request: %s", request);
						/* example response: "40931,23:USERID:UNIX:cyan" */
						SAFEPRINTF4(response,"%s:%s:%s %s\r\n"
							,request, ident_response, cid_number, cid_name);
						sendsocket(client_socket,response,strlen(response));
					} else
						lprintf(LOG_DEBUG,"ident recv=%d %d", rd, ERROR_VALUE);
				}
				close_socket(&client_socket);
			}
		}
	}

	close_socket(&sock);
	lprintf(LOG_DEBUG,"Ident server thread terminated");
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
static void send_telnet_cmd(uchar cmd, uchar opt)
{
	char buf[16];
	
	if(cmd<TELNET_WILL) {
		if(debug_telnet)
			lprintf(LOG_INFO,"TX Telnet command: %s"
				,telnet_cmd_desc(cmd));
		sprintf(buf,"%c%c",TELNET_IAC,cmd);
		sendsocket(sock,buf,2);
	} else {
		if(debug_telnet)
			lprintf(LOG_INFO,"TX Telnet command: %s %s"
				,telnet_cmd_desc(cmd), telnet_opt_desc(opt));
		sprintf(buf,"%c%c%c",TELNET_IAC,cmd,opt);
		sendsocket(sock,buf,3);
	}
}

void request_telnet_opt(uchar cmd, uchar opt)
{
	if(cmd==TELNET_DO || cmd==TELNET_DONT) {	/* remote option */
		if(telnet_remote_option[opt]==telnet_opt_ack(cmd))
			return;	/* already set in this mode, do nothing */
		telnet_remote_option[opt]=telnet_opt_ack(cmd);
	} else {	/* local option */
		if(telnet_local_option[opt]==telnet_opt_ack(cmd))
			return;	/* already set in this mode, do nothing */
		telnet_local_option[opt]=telnet_opt_ack(cmd);
	}
	send_telnet_cmd(cmd,opt);
}

/****************************************************************************/
/****************************************************************************/
BYTE* telnet_interpret(BYTE* inbuf, int inlen, BYTE* outbuf, int *outlen)
{
	BYTE	command;
	BYTE	option;
	BYTE*   first_iac;
	int 	i;

	if(inlen<1) {
		*outlen=0;
		return(inbuf);	/* no length? No interpretation */
	}

    first_iac=(BYTE*)memchr(inbuf, TELNET_IAC, inlen);

    if(!telnet_cmdlen && first_iac==NULL) {
        *outlen=inlen;
        return(inbuf);	/* no interpretation needed */
    }

    if(first_iac!=NULL) {
   		*outlen=first_iac-inbuf;
	    memcpy(outbuf, inbuf, *outlen);
    } else
    	*outlen=0;

    for(i=*outlen;i<inlen;i++) {
        if(inbuf[i]==TELNET_IAC && telnet_cmdlen==1) { /* escaped 255 */
            telnet_cmdlen=0;
            outbuf[(*outlen)++]=TELNET_IAC;
            continue;
        }
        if(inbuf[i]==TELNET_IAC || telnet_cmdlen) {

			if(telnet_cmdlen<sizeof(telnet_cmd))
				telnet_cmd[telnet_cmdlen++]=inbuf[i];

			command	= telnet_cmd[1];
			option	= telnet_cmd[2];

			if(telnet_cmdlen>=2 && command==TELNET_SB) {
				if(inbuf[i]==TELNET_SE 
					&& telnet_cmd[telnet_cmdlen-2]==TELNET_IAC) {
1124 1125 1126
					if(debug_telnet)
						lprintf(LOG_INFO,"RX Telnet sub-negotiation command: %s"
							,telnet_opt_desc(option));
1127 1128
					/* sub-option terminated */
					if(option==TELNET_TERM_TYPE && telnet_cmd[3]==TELNET_TERM_SEND) {
1129
						char buf[sizeof(termtype) + 32];
1130 1131 1132 1133 1134 1135 1136 1137
						int len=sprintf(buf,"%c%c%c%c%s%c%c"
							,TELNET_IAC,TELNET_SB
							,TELNET_TERM_TYPE,TELNET_TERM_IS
							,termtype
							,TELNET_IAC,TELNET_SE);
						if(debug_telnet)
							lprintf(LOG_INFO,"TX Telnet command: Terminal Type is %s", termtype);
						sendsocket(sock,buf,len);
1138
/*						request_telnet_opt(TELNET_WILL, TELNET_TERM_SPEED); */
1139
					} else if(option==TELNET_TERM_SPEED && telnet_cmd[3]==TELNET_TERM_SEND) {
1140
						char buf[sizeof(termspeed) + 32];
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
						int len=sprintf(buf,"%c%c%c%c%s%c%c"
							,TELNET_IAC,TELNET_SB
							,TELNET_TERM_SPEED,TELNET_TERM_IS
							,termspeed
							,TELNET_IAC,TELNET_SE);
						if(debug_telnet)
							lprintf(LOG_INFO,"TX Telnet command: Terminal Speed is %s", termspeed);
						sendsocket(sock,buf,len);
					}

					telnet_cmdlen=0;
				}
			}
            else if(telnet_cmdlen==2 && inbuf[i]<TELNET_WILL) {
                telnet_cmdlen=0;
            }
            else if(telnet_cmdlen>=3) {	/* telnet option negotiation */

				if(debug_telnet)
					lprintf(LOG_INFO,"RX Telnet command: %s %s"
						,telnet_cmd_desc(command),telnet_opt_desc(option));

				if(command==TELNET_DO || command==TELNET_DONT) {	/* local options */
					if(telnet_local_option[option]!=command) {
						switch(option) {
							case TELNET_BINARY_TX:
							case TELNET_ECHO:
							case TELNET_TERM_TYPE:
1169
							case TELNET_TERM_SPEED:
1170 1171 1172 1173
							case TELNET_SUP_GA:
								telnet_local_option[option]=command;
								send_telnet_cmd(telnet_opt_ack(command),option);
								break;
1174 1175
							case TELNET_SEND_LOCATION:
								if(command==TELNET_DO) {
Rob Swindell's avatar
Rob Swindell committed
1176
									char buf[128];
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
									int len=safe_snprintf(buf,sizeof(buf),"%c%c%c%s %s%c%c"
										,TELNET_IAC,TELNET_SB
										,TELNET_SEND_LOCATION
										,cid_number, cid_name
										,TELNET_IAC,TELNET_SE);
									if(debug_telnet)
										lprintf(LOG_INFO,"TX Telnet command: Location is %s %s", cid_number, cid_name);
									sendsocket(sock,buf,len);
								} else
									send_telnet_cmd(telnet_opt_ack(command),option);
								break;
		
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
							default: /* unsupported local options */
								if(command==TELNET_DO) /* NAK */
									send_telnet_cmd(telnet_opt_nak(command),option);
								break;
						}
					}
				} else { /* WILL/WONT (remote options) */ 
					if(telnet_remote_option[option]!=command) {	

						switch(option) {
							case TELNET_BINARY_TX:
							case TELNET_ECHO:
							case TELNET_TERM_TYPE:
							case TELNET_SUP_GA:
								telnet_remote_option[option]=command;
								send_telnet_cmd(telnet_opt_ack(command),option);
								break;
							default: /* unsupported remote options */
								if(command==TELNET_WILL) /* NAK */
									send_telnet_cmd(telnet_opt_nak(command),option);
								break;
						}
					}
				}

                telnet_cmdlen=0;

            }
        } else
        	outbuf[(*outlen)++]=inbuf[i];
    }
    return(outbuf);
}

/****************************************************************************/
/****************************************************************************/
BOOL handle_call(void)
{
	BYTE		buf[4096];
	BYTE		telnet_buf[sizeof(buf)];
	BYTE*		p;
	int			result;
	int			rd;
	int			wr;
	fd_set		socket_set;
	struct		timeval tv = {0, 0};

	bytes_sent=0;
	bytes_received=0;
	call_terminated=FALSE;

	/* Reset Telnet state information */
	telnet_cmdlen=0;
	ZERO_VAR(telnet_local_option);
	ZERO_VAR(telnet_remote_option);

1245 1246 1247
	if(telnet && telnet_advertise_cid && (cid_number[0] || cid_name[0]))	/* advertise the ability to send our location */
		send_telnet_cmd(TELNET_WILL, TELNET_SEND_LOCATION);

1248 1249 1250 1251 1252
	input_thread_terminated=FALSE;
	_beginthread(input_thread, 0, NULL);

	while(!terminated) {

rswindell's avatar
rswindell committed
1253 1254 1255
		if(!dcd_ignore && !carrier_detect(com_handle)) {
			lprintf(LOG_WARNING,"Loss of Carrier Detect (DCD) detected");
			break;
1256
		}
rswindell's avatar
rswindell committed
1257
#if 0	/* single-threaded mode: */
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
		if(comReadByte(com_handle, &ch)) {
			lprintf(LOG_DEBUG,"read byte: %c", ch);
			send(sock, &ch, sizeof(ch), 0);
		}
#endif

		FD_ZERO(&socket_set);
		FD_SET(sock,&socket_set);
		if((result = select(sock+1,&socket_set,NULL,NULL,&tv)) == 0) {
			YIELD();
			continue;
		}
		if(result == SOCKET_ERROR) {
			lprintf(LOG_ERR,"SOCKET ERROR %u on select", ERROR_VALUE);
			break;
		}

		rd=recv(sock,buf,sizeof(buf),0);

		if(rd < 1) {
			if(rd==0) {
				lprintf(LOG_WARNING,"Socket Disconnected");
				break;
			}
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
			if(ERROR_VALUE == EAGAIN)
				continue;
        	else if(ERROR_VALUE == ENOTSOCK)
   	            lprintf(LOG_WARNING,"Socket closed by peer on receive");
       	    else if(ERROR_VALUE==ECONNRESET) 
				lprintf(LOG_WARNING,"Connection reset by peer on receive");
			else if(ERROR_VALUE==ESHUTDOWN)
				lprintf(LOG_WARNING,"Socket shutdown on receive");
       	    else if(ERROR_VALUE==ECONNABORTED) 
				lprintf(LOG_WARNING,"Connection aborted by peer on receive");
			else
				lprintf(LOG_ERR,"SOCKET RECV ERROR %d",ERROR_VALUE);
			break;
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
		}

		if(telnet)
			p=telnet_interpret(buf,rd,telnet_buf,&rd);
		else
			p=buf;

		if((wr=comWriteBuf(com_handle, p, rd)) != COM_ERROR)
			bytes_sent += wr;
	}

	call_terminated=TRUE;	/* terminate input_thread() */
	while(!input_thread_terminated) {
		YIELD();
	}

rswindell's avatar
rswindell committed
1311 1312
	lprintf(LOG_INFO,"Bytes sent-to, received-from COM Port: %lu, %lu"
		,bytes_sent, bytes_received);
1313 1314 1315 1316 1317 1318

	return TRUE;
}

/****************************************************************************/
/****************************************************************************/
deuce's avatar
deuce committed
1319
BOOL hangup_call(COM_HANDLE com_handle)
1320
{
rswindell's avatar
rswindell committed
1321
	time_t	start;
1322
	int		attempt;
rswindell's avatar
rswindell committed
1323
	int		mdm_status;
1324

rswindell's avatar
rswindell committed
1325
	if(!carrier_detect(com_handle))/* DCD already low */
1326 1327
		return TRUE;

rswindell's avatar
rswindell committed
1328 1329
	lprintf(LOG_DEBUG,"Waiting for transmit buffer to empty");
	SLEEP(dtr_delay);
1330 1331 1332 1333 1334 1335
	for(attempt=0; attempt<hangup_attempts; attempt++) {
		lprintf(LOG_INFO,"Dropping DTR (attempt #%d)", attempt+1);
		if(!comLowerDTR(com_handle)) {
			lprintf(LOG_ERR,"ERROR %u lowering DTR", COM_ERROR);
			continue;
		}
rswindell's avatar
rswindell committed
1336
		lprintf(LOG_DEBUG,"Waiting for loss of Carrier Detect (DCD)");
1337 1338
		start=time(NULL);
		while(time(NULL)-start <= dcd_timeout) {
rswindell's avatar
rswindell committed
1339
			if(((mdm_status=modem_status(com_handle))&COM_DCD)==0)
1340 1341 1342 1343
				return TRUE;
			SLEEP(1000); 
		}
		lprintf(LOG_ERR,"TIMEOUT waiting for DCD to drop (attempt #%d of %d)"
rswindell's avatar
rswindell committed
1344 1345
			,attempt+1, hangup_attempts);
		lprintf(LOG_DEBUG,"Modem status: 0x%lX", mdm_status);
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
	}

	return FALSE;
}

/****************************************************************************/
/****************************************************************************/
void break_handler(int type)
{
	lprintf(LOG_NOTICE,"-> Terminated Locally (signal: %d)",type);
	terminated=TRUE;
}

#if defined(_WIN32)
BOOL WINAPI ControlHandler(DWORD CtrlType)
{
	break_handler((int)CtrlType);
	return TRUE;
}
#endif

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
/****************************************************************************/
/****************************************************************************/
char* iniGetExistingWord(str_list_t list, const char* section, const char* key
					,const char* deflt, char* value)
{
	char* p;

	if((p=iniGetExistingString(list, section, key, deflt, value)) !=NULL) {
		FIND_WHITESPACE(value);
		*value=0;
	}
	return p;
}

1381 1382
str_list_t	ini = NULL;

1383 1384 1385 1386 1387 1388 1389 1390
void parse_tcp_section(const char* section)
{
	iniGetExistingWord(ini, section, "Host", NULL, host);
	port					= iniGetShortInt(ini, section, "Port", port);
	tcp_nodelay				= iniGetBool(ini,section,"NODELAY", tcp_nodelay);
	telnet					= iniGetBool(ini,section,"Telnet", telnet);
}

1391 1392 1393
void parse_ini_file(const char* ini_fname)
{
	FILE* fp;
1394
	char* section;
1395

1396
	strListFree(&ini);
1397
	if((fp=fopen(ini_fname,"r"))!=NULL) {
1398
		lprintf(LOG_INFO,"Reading %s",ini_fname);
1399
		ini = iniReadFile(fp);
1400 1401
		fclose(fp);
	}
1402 1403

	/* Root section */
1404 1405
	pause_on_exit			= iniGetBool(ini,ROOT_SECTION,"PauseOnExit",FALSE);
	log_level				= iniGetLogLevel(ini,ROOT_SECTION,"LogLevel",log_level);
1406
	cls = iniGetBool(ini, ROOT_SECTION, "CLS", cls);
1407
	iniGetString(ini, ROOT_SECTION, "Prompt", NULL, prompt);
1408
	prompt_timeout = iniGetInteger(ini, ROOT_SECTION, "PromptTimeout", prompt_timeout);
1409

1410
	if(iniGetBool(ini,ROOT_SECTION,"Debug",FALSE))
1411 1412 1413
		log_level=LOG_DEBUG;
	
	/* [COM] Section */
1414
	section="COM";
1415 1416 1417 1418 1419 1420 1421 1422
	iniGetExistingWord(ini, section, "Device", NULL, com_dev);
	com_baudrate    = iniGetLongInt(ini, section, "BaudRate", com_baudrate);
	com_hangup	    = iniGetBool(ini, section, "Hangup", com_hangup);
	hangup_attempts = iniGetInteger(ini, section, "HangupAttempts", hangup_attempts);
	dcd_timeout     = iniGetInteger(ini, section, "DCDTimeout", dcd_timeout);
	dcd_ignore