vdmodem.c 41.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* Synchronet Virtual DOS Modem for Windows */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
 *																			*
 * 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.	*
 ****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define WIN32_LEAN_AND_MEAN
#define NOGDI
#include <windows.h>
#include <process.h>
30
#include <mmsystem.h>	/* SND_ASYNC */
31 32

#include "genwrap.h"
33
#include "findstr.h"
34
#include "dirwrap.h"
35 36
#include "gen_defs.h"
#include "sockwrap.h"
Rob Swindell's avatar
Rob Swindell committed
37
#include "telnet.h"
38
#include "ini_file.h"
39
#include "vdd_func.h"
40 41
#include "git_branch.h"
#include "git_hash.h"
42 43

#define TITLE "Synchronet Virtual DOS Modem for Windows"
44
#define VERSION "0.2"
45

46
bool external_socket;
47
union xp_sockaddr addr;
48 49 50 51 52 53 54
SOCKET sock = INVALID_SOCKET;
SOCKET listening_sock = INVALID_SOCKET;
HANDLE hangup_event = INVALID_HANDLE_VALUE;	// e.g. program drops DTR
HANDLE hungup_event = INVALID_HANDLE_VALUE;	// e.g. ATH0
HANDLE carrier_event = INVALID_HANDLE_VALUE;
HANDLE rdslot = INVALID_HANDLE_VALUE;
HANDLE wrslot = INVALID_HANDLE_VALUE;
55 56
str_list_t ini;
char ini_fname[MAX_PATH + 1];
57
union xp_sockaddr listening_interface;
Rob Swindell's avatar
Rob Swindell committed
58 59 60 61
enum {
	 RAW
	,TELNET
} mode;
62
char* modeNames[] = {"raw", "telnet", NULL};
Rob Swindell's avatar
Rob Swindell committed
63 64 65 66 67 68
struct {
	uint8_t	local_option[0x100];
	uint8_t	remote_option[0x100];
	uint cmdlen;
	uchar cmd[64];
} telnet;
69
unsigned int sbbsexec_mode = SBBSEXEC_MODE_UNSPECIFIED;
70 71 72 73 74
#define XTRN_IO_BUF_LEN 10000
#define RING_DELAY 6000 /* US standard is 6 seconds */

struct {
	int node_num;
Rob Swindell's avatar
Rob Swindell committed
75
	uint16_t port;
76 77 78 79
	bool listen;
	bool debug;
	bool terminate_on_disconnect;
	ulong data_rate;
80
	bool server_echo;
81
	bool server_binary;
82
	char client_file[MAX_PATH + 1];
83
	char ip_filter_file[MAX_PATH + 1];
84 85 86
	char ring_sound[MAX_PATH + 1];
	char connect_sound[MAX_PATH + 1];
	char disconnect_sound[MAX_PATH + 1];
87
	char busy_notice[INI_MAX_VALUE_LEN];
88
	char answer_banner[INI_MAX_VALUE_LEN];
89 90 91 92 93 94
	enum {
		 ADDRESS_FAMILY_UNSPEC
		,ADDRESS_FAMILY_INET
		,ADDRESS_FAMILY_INET6
	} address_family;
} cfg;
95
char* addrFamilyNames[] = {"unspec", "ipv4", "ipv6", NULL};
96 97 98 99 100 101 102 103 104 105 106 107 108 109

static void dprintf(const char *fmt, ...)
{
	char buf[1024] = "SBBSVDM: ";
	va_list argptr;

    va_start(argptr,fmt);
	size_t offset = strlen(buf);
    _vsnprintf(buf + offset, sizeof(buf) - offset, fmt, argptr);
	TERMINATE(buf);
    va_end(argptr);
    OutputDebugString(buf);
}

110
void usage(const char* progname)
111
{
112 113 114 115 116 117 118 119 120
	fprintf(stderr, "usage: %s [-opts] <program> [options]\n"
		"opts:\n"
		"\t-telnet   Use Telnet protocol by default\n"
		"\t-raw      Use Raw TCP by default\n"
		"\t-4        Use IPv4 address family by default\n"
		"\t-6        Use IPv6 address family by default\n"
		"\t-l[addr]  Listen for incoming TCP connections\n"
		"\t          [on optionally-specified network interface]\n"
		"\t-p<port>  Specify default TCP port number (decimal)\n"
121
		"\t-n<node>  Specify node number\n"
122 123 124
		"\t-d        Enable debug output\n"
		"\t-h<sock>  Specify socket descriptor/handle to use (decimal)\n"
		"\t-r<cps>   Specify maximum receive data rate (chars/second)\n"
125 126
		"\t-c<fname> Specify alternate configuration (.ini) path/filename\n"
		"\t-V        Display detailed version information and exit\n"
127 128
		,progname
	);
129 130 131 132
	exit(EXIT_SUCCESS);
}

const char* string_cmds = "D";
133
#define MAX_SAVES 20
134 135 136 137 138 139 140 141 142 143
struct modem {
	enum {
		 INIT
		,A
		,AT
	} cmdstate;
	char cr;
	char lf;
	char bs;
	char esc;
144 145
	char save[MAX_SAVES][INI_MAX_VALUE_LEN];
	char last[INI_MAX_VALUE_LEN];
146 147 148 149
	bool echo_off;
	bool numeric_mode;
	bool offhook;
	bool online; // false means "command mode"
150
	bool caller_id;
151
	bool ringing;
152
	bool speaker;
153 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
	ulong ringcount;
	ulong auto_answer;
	ulong dial_wait;
	ulong guard_time;
	ulong esc_count;
	ulong ext_results;
	ulong quiet;
	uint8_t buf[128];
	size_t buflen;
};

void newcmd(struct modem* modem)
{
	modem->cmdstate = INIT;
	modem->buflen = 0;
}

ulong guard_time(struct modem* modem)
{
	return modem->guard_time * 20;
}

ulong count_esc(struct modem* modem, uint8_t* buf, size_t rd)
{
	if(modem->esc < 0 || modem->esc > 127)
		return 0;

	ulong count = 0;
	for(size_t i = 0; i < rd; i++) {
		if(buf[i] == modem->esc)
			count++;
184 185
		else
			return 0;
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
	}
	return count;
}

// Basic Hayes modem responses
enum modem_response {
	OK				= 0,
	CONNECT			= 1,
	RING			= 2,
	NO_CARRIER		= 3,
	ERROR			= 4,
	CONNECT_1200	= 5,
	NO_DIAL_TONE	= 6,
	BUSY			= 7,
	NO_ANSWER		= 8,
	RESERVED1		= 9,
	CONNECT_2400	= 10,
	RESERVED2		= 11,
	RESERVED3		= 12,
	CONNECT_9600	= 13
};

const char* response_str[] = {
	"OK",
	"CONNECT",
	"RING",
	"NO CARRIER",
	"ERROR",
	"CONNECT 1200",
	"NO DIAL TONE",
	"BUSY",
	"NO ANSWER",
	"RESERVED1",
	"CONNECT 2400",
	"RESERVED2",
	"RESERVED3",
	"CONNECT 9600"
};

225 226 227 228 229 230 231 232
char* verbal_response(struct modem* modem, const char* response)
{
	static char str[128];
	safe_snprintf(str, sizeof(str), "%c%c%s%c%c", modem->cr, modem->lf, response, modem->cr, modem->lf);
	return str;
}

char* numeric_response(struct modem* modem, int code)
233 234
{
	static char str[128];
235 236 237
	safe_snprintf(str, sizeof(str), "%u%c", code, modem->cr);
	return str;
}
238

239 240
char* response(struct modem* modem, enum modem_response code)
{
241 242 243
	if(modem->quiet)
		return "";
	if(modem->numeric_mode)
244 245
		return numeric_response(modem, code);
	return verbal_response(modem, response_str[code]);
246 247 248 249 250 251 252 253 254 255 256 257
}

char* ok(struct modem* modem)
{
	return response(modem, OK);
}

char* error(struct modem* modem)
{
	return response(modem, ERROR);
}

258 259 260 261 262 263 264 265 266
char* text_response(struct modem* modem, const char* text)
{
	static char str[512];

	SAFECOPY(str, verbal_response(modem, text));
	SAFECAT(str, response(modem, OK));
	return str;
}

267 268 269 270 271 272 273
char* connect_result(struct modem* modem)
{
	return response(modem, modem->ext_results ? CONNECT_9600 : CONNECT);
}

char* connected(struct modem* modem)
{
274 275
	if(modem->speaker && cfg.connect_sound[0])
		PlaySound(cfg.connect_sound, NULL, SND_ASYNC|SND_FILENAME);
276 277
	modem->online = true;
	modem->ringing = false;
278
	ResetEvent(hangup_event);
279 280 281 282 283 284 285
	ResetEvent(hungup_event);
	SetEvent(carrier_event);
	return connect_result(modem);
}

void disconnect(struct modem* modem)
{
286 287
	if(modem->speaker && cfg.disconnect_sound[0])
		PlaySound(cfg.disconnect_sound, NULL, SND_ASYNC|SND_FILENAME);
288
	modem->online = false;
289 290 291 292
	if(!external_socket) {
		shutdown(sock, SD_SEND);
		closesocket(sock);
	}
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
	sock = INVALID_SOCKET;
	SetEvent(hungup_event);
	SetEvent(carrier_event);
}

bool kbhit()
{
	unsigned long waiting = 0;
	if(!GetMailslotInfo(
		rdslot,				// mailslot handle
 		NULL,				// address of maximum message size
		NULL,				// address of size of next message
		&waiting,			// address of number of messages
 		NULL				// address of read time-out
		))
		return false;
	return waiting != 0;
}

312 313 314 315
const char* iniKeyAutoAnswer = "AutoAnswer";
const char* iniKeyEcho = "Echo";
const char* iniKeyQuiet = "Quiet";
const char* iniKeyNumeric = "Numeric";
316
const char* iniKeySpeaker = "Speaker";
317 318 319 320 321 322 323
const char* iniKeyCR = "CR";
const char* iniKeyLF = "LF";
const char* iniKeyBS = "BS";
const char* iniKeyESC = "ESC";
const char* iniKeyExtResults = "ExtResults";
const char* iniKeyDialWait = "DialWait";
const char* iniKeyGuardTime = "GuardTime";
324
const char* iniKeyCallerID = "CallerID";
325

326 327 328 329
void init(struct modem* modem)
{
	const char* section = "modem";
	memset(modem, 0, sizeof(*modem));
330 331 332
	modem->auto_answer = iniGetBool(ini, section, iniKeyAutoAnswer, FALSE);
	modem->echo_off = !iniGetBool(ini, section, iniKeyEcho, TRUE);
	modem->quiet = iniGetBool(ini, section, iniKeyQuiet, FALSE);
333
	modem->speaker = iniGetBool(ini, section, iniKeySpeaker, FALSE);
334
	modem->numeric_mode = iniGetBool(ini, section, iniKeyNumeric, FALSE);
335
	modem->caller_id = iniGetBool(ini, section, iniKeyCallerID, FALSE);
336 337 338 339 340 341 342
	modem->cr = (char)iniGetInteger(ini, section,  iniKeyCR, '\r');
	modem->lf = (char)iniGetInteger(ini, section, iniKeyLF, '\n');
	modem->bs = (char)iniGetInteger(ini, section, iniKeyBS, '\b');
	modem->esc = (char)iniGetInteger(ini, section, iniKeyESC, '+');
	modem->ext_results = iniGetInteger(ini, section, iniKeyExtResults, 4);
	modem->dial_wait = iniGetInteger(ini, section, iniKeyDialWait, 60);
	modem->guard_time = iniGetInteger(ini, section, iniKeyGuardTime, 50);
343 344 345 346 347
}

bool write_cfg(struct modem* modem)
{
	dprintf(__FUNCTION__);
348
	ini_style_t* style = NULL;
349
	const char* section = "modem";
350 351 352
	iniSetBool(&ini, section, iniKeyAutoAnswer, modem->auto_answer, style);
	iniSetBool(&ini, section, iniKeyEcho, !modem->echo_off, style);
	iniSetBool(&ini, section, iniKeyQuiet, modem->quiet, style);
353
	iniSetBool(&ini, section, iniKeySpeaker, modem->speaker, style);
354
	iniSetBool(&ini, section, iniKeyNumeric, modem->numeric_mode, style);
355
	iniSetBool(&ini, section, iniKeyCallerID, modem->caller_id, style);
356 357 358 359 360 361 362
	iniSetInteger(&ini, section, iniKeyCR, modem->cr, style);
	iniSetInteger(&ini, section, iniKeyLF, modem->lf, style);
	iniSetInteger(&ini, section, iniKeyBS, modem->bs, style);
	iniSetInteger(&ini, section, iniKeyESC, modem->esc, style);
	iniSetInteger(&ini, section, iniKeyExtResults, modem->ext_results, style);
	iniSetInteger(&ini, section, iniKeyDialWait, modem->dial_wait, style);
	iniSetInteger(&ini, section, iniKeyGuardTime, modem->guard_time, style);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	bool result = false;
	FILE* fp = iniOpenFile(ini_fname, /* create: */TRUE);
	if(fp != NULL) {
		if(iniWriteFile(fp, ini)) {
			dprintf("Wrote config to: %s", ini_fname);
			result = true;
		}
		iniCloseFile(fp);
	}
	return result;
}

bool write_save(struct modem* modem, ulong savnum)
{
	char key[128];
	str_list_t ini;

	if(savnum >= MAX_SAVES)
		return false;
382
	SAFEPRINTF(key, "Save%lu", savnum);
383 384 385 386 387 388 389
	FILE* fp = iniOpenFile(ini_fname, /* create: */TRUE);
	if(fp == NULL)
		return false;
	ini = iniReadFile(fp);
	iniSetString(&ini, "modem", key, modem->save[savnum], /* style: */NULL);
	bool result = iniWriteFile(fp, ini);
	iniCloseFile(fp);
390
	iniFreeStringList(ini);
391 392 393
	return result;
}

Rob Swindell's avatar
Rob Swindell committed
394 395 396 397 398 399 400 401
const char* protocol(enum mode mode)
{
	switch(mode) {
	case TELNET: return "Telnet";
	}
	return "Raw";
}

402
int address_family(BOOL for_listen)
Rob Swindell's avatar
Rob Swindell committed
403 404 405 406 407
{
	switch(cfg.address_family) {
		case ADDRESS_FAMILY_INET:	return PF_INET;
		case ADDRESS_FAMILY_INET6:	return PF_INET6;
	}
408 409 410 411 412 413
	return for_listen ? PF_INET : PF_UNSPEC;
}

int listen_address_family()
{
	return address_family(true);
Rob Swindell's avatar
Rob Swindell committed
414 415
}

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 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 565 566 567 568 569 570 571 572 573
int putcom(char* buf, size_t len)
{
	return send(sock, buf, len, /* flags: */0);
}

static void send_telnet_cmd(uchar cmd, uchar opt)
{
	char buf[16];
	
	if(cmd<TELNET_WILL) {
		dprintf("TELNET TX: %s"
			,telnet_cmd_desc(cmd));
		sprintf(buf,"%c%c",TELNET_IAC,cmd);
		putcom(buf,2);
	} else {
		dprintf("TELNET TX: %s %s"
			,telnet_cmd_desc(cmd), telnet_opt_desc(opt));
		sprintf(buf,"%c%c%c",TELNET_IAC,cmd,opt);
		putcom(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, size_t inlen, BYTE* outbuf, size_t *outlen)
{
	BYTE	command;
	BYTE	option;
	BYTE*   first_cr=NULL;
	BYTE*   first_int=NULL;
	size_t 	i;

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

    first_int=(BYTE*)memchr(inbuf, TELNET_IAC, inlen);
	if(telnet.remote_option[TELNET_BINARY_TX]!=TELNET_WILL) {
		first_cr=(BYTE*)memchr(inbuf, '\r', inlen);
		if(first_cr) {
			if(first_int==NULL || first_cr < first_int)
				first_int=first_cr;
		}
	}

    if(telnet.cmdlen==0 && first_int==NULL) {
        *outlen=inlen;
        return(inbuf);	/* no interpretation needed */
    }

    if(telnet.cmdlen==0 /* If we haven't returned and telnet.cmdlen==0 then first_int is not NULL */  ) {
   		*outlen=first_int-inbuf;
	    memcpy(outbuf, inbuf, *outlen);
    } else
    	*outlen=0;

    for(i=*outlen;i<inlen;i++) {
		if(telnet.remote_option[TELNET_BINARY_TX]!=TELNET_WILL) {
			if(telnet.cmdlen==1 && telnet.cmd[0]=='\r') {
            	outbuf[(*outlen)++]='\r';
				if(inbuf[i]!=0 && inbuf[i]!=TELNET_IAC)
	            	outbuf[(*outlen)++]=inbuf[i];
				telnet.cmdlen=0;
				if(inbuf[i]!=TELNET_IAC)
					continue;
			}
			if(inbuf[i]=='\r' && telnet.cmdlen==0) {
				telnet.cmd[telnet.cmdlen++]='\r';
				continue;
			}
		}

        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) {
					telnet.cmdlen=0;
				}
			}
            else if(telnet.cmdlen==2 && inbuf[i]<TELNET_WILL) {
                telnet.cmdlen=0;
            }
            else if(telnet.cmdlen>=3) {	/* telnet option negotiation */

				dprintf("TELNET RX: %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:
							case TELNET_SUP_GA:
							case TELNET_NEGOTIATE_WINDOW_SIZE:
								telnet.local_option[option]=command;
								send_telnet_cmd(telnet_opt_ack(command),option);
								break;
							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:
							case TELNET_NEGOTIATE_WINDOW_SIZE:
								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);
}

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
void setsockopts(SOCKET sock)
{
	char error[256] = "";
	dprintf("Setting socket options");
	if(iniGetSocketOptions(ini, "sockopts", sock, error, sizeof(error)) != 0)
		dprintf("!ERROR %s", error);
	int value = 0;
	socklen_t len = sizeof(value);
	if(getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&value, &len) == 0)
		dprintf("Socket send buffer length: %d bytes", value);
	value = 0;
	len = sizeof(value);
	if(getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&value, &len) == 0)
		dprintf("Socket receive buffer length: %d bytes", value);
	value = 0;
	len = sizeof(value);
	if(getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&value, &len) == 0)
		dprintf("Socket TCP_NODELAY: %d", value);
}

594 595 596 597 598 599
// Significant portions copies from syncterm/conn.c
char* dial(struct modem* modem, const char* number)
{
	struct addrinfo	hints;
	struct addrinfo	*res=NULL;
	char host[128];
Rob Swindell's avatar
Rob Swindell committed
600
	char portnum[16];
601
	char value[INI_MAX_VALUE_LEN];
Rob Swindell's avatar
Rob Swindell committed
602
	uint16_t port = cfg.port;
603

Rob Swindell's avatar
Rob Swindell committed
604 605
	dprintf("dial(%s)", number);
	if(stricmp(number, "L") == 0)
606 607
		number = modem->last;
	else {
608 609 610 611
		const char* p = iniGetString(ini, "alias", number, NULL, value);
		if(p != NULL)
			number = p;
		else if(toupper(*number) == 'S' && IS_DIGIT(number[1])) {
612 613 614 615 616 617 618
			char* p;
			ulong val = strtoul(number+1, &p, 10);
			if(val < MAX_SAVES && *p == '\0')
				number = modem->save[val];
		}
		SAFECOPY(modem->last, number);
	}
Rob Swindell's avatar
Rob Swindell committed
619 620 621 622 623 624 625 626 627
	if(strncmp(number, "raw:", 4) == 0) {
		mode = RAW;
		number += 4;
	}
	else if(strncmp(number, "telnet:", 7) == 0) {
		mode = TELNET;
		number += 7;
	}
	SKIP_WHITESPACE(number);
628 629 630 631
	SAFECOPY(host, number);
	char* p = strrchr(host, ':');
	char* b = strrchr(host, ']'); 
	if(p != NULL && p > b) {
Rob Swindell's avatar
Rob Swindell committed
632
		port = (uint16_t)strtol(p + 1, NULL, 10);
633 634
		*p = 0;
	}
Rob Swindell's avatar
Rob Swindell committed
635
	dprintf("Connecting to port %hu at host '%s' via %s", port, host, protocol(mode));
636
	memset(&hints, 0, sizeof(hints));
637
	hints.ai_family = address_family(/* for listen: */false);
638 639 640
	hints.ai_socktype=SOCK_STREAM;
	hints.ai_protocol=IPPROTO_TCP;
	dprintf("%s %d calling getaddrinfo", __FILE__, __LINE__);
Rob Swindell's avatar
Rob Swindell committed
641
	SAFEPRINTF(portnum, "%hu", port);
642 643
	int result = getaddrinfo(host, portnum, &hints, &res);
	if(result != 0) {
Rob Swindell's avatar
Rob Swindell committed
644
		dprintf("getaddrinfo(%s, %s) [family=%d] returned %d", host, portnum, hints.ai_family, result);
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
		return response(modem, NO_ANSWER);
	}

	int				nonblock;
	struct addrinfo	*cur;
	for(cur=res; cur && sock == INVALID_SOCKET; cur=cur->ai_next) {
		if(sock==INVALID_SOCKET) {
			sock=socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
			if(sock==INVALID_SOCKET) {
				dprintf("Error %ld creating socket", WSAGetLastError());
				return response(modem, NO_DIAL_TONE);
			}
			/* Set to non-blocking for the connect */
			nonblock=-1;
			ioctlsocket(sock, FIONBIO, &nonblock);
		}

		dprintf("%s %d calling connect", __FILE__, __LINE__);
		if(connect(sock, cur->ai_addr, cur->ai_addrlen)) {
			switch(ERROR_VALUE) {
				case EINPROGRESS:
				case EINTR:
				case EAGAIN:
				case EWOULDBLOCK:
					for(;sock!=INVALID_SOCKET;) {
						if (socket_writable(sock, 1000)) {
							if (socket_recvdone(sock, 0)) {
								closesocket(sock);
								sock=INVALID_SOCKET;
								continue;
							}
							else {
								goto connected;
							}
						}
						else {
							if (kbhit()) {
								dprintf("%s %d kbhit", __FILE__, __LINE__);
								closesocket(sock);
								sock = INVALID_SOCKET;
								return response(modem, NO_CARRIER);
							}
						}
					}

connected:
					break;
				default:
					closesocket(sock);
					sock=INVALID_SOCKET;
					continue;
			}
		}
	}
	if (sock == INVALID_SOCKET) {
		dprintf("%s %d invalid hostname?", __FILE__, __LINE__);
		return response(modem, NO_ANSWER);
	}

	freeaddrinfo(res);
	res=NULL;
	nonblock=0;
	ioctlsocket(sock, FIONBIO, &nonblock);
708
	setsockopts(sock);
709 710 711 712 713 714 715 716
	if(socket_recvdone(sock, 0)) {
		dprintf("%s %d socket_recvdone", __FILE__, __LINE__);
		return response(modem, NO_CARRIER);
	}

	dprintf("%s %d connected!", __FILE__, __LINE__);
	int keepalives = TRUE;
	setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepalives, sizeof(keepalives));
717
	ZERO_VAR(telnet);
718 719 720 721 722 723 724 725
	return connected(modem);
}

char* answer(struct modem* modem)
{
	if(listening_sock == INVALID_SOCKET)
		return response(modem, NO_DIAL_TONE);

726
	if(sock == INVALID_SOCKET)
727 728
		return response(modem, NO_CARRIER);

729
	setsockopts(sock);
730 731 732 733 734
	if(cfg.client_file[0]) {
		FILE* fp = fopen(cfg.client_file, "wt");
		if(fp == NULL)
			dprintf("!Error %d creating '%s'", errno, cfg.client_file);
		else {
735
			char tmp[256];
736 737 738 739 740 741 742
			fprintf(fp, "sock=%d\n", sock);
			fprintf(fp, "addr=%s\n", inet_addrtop(&addr, tmp, sizeof(tmp)));
			fprintf(fp, "port=%u\n", inet_addrport(&addr));
			fprintf(fp, "prot=%s\n", protocol(mode));
			fclose(fp);
		}
	}
743 744
	if(mode == TELNET) {
		ZERO_VAR(telnet);
745 746 747 748
		if(cfg.server_echo) {
			/* Disable Telnet Terminal Echo */
			request_telnet_opt(TELNET_WILL,TELNET_ECHO);
		}
749 750 751 752
		if(cfg.server_binary) {
			/* Will send in binary mode (no CR->CRLF expansion on receiver side) */
			request_telnet_opt(TELNET_WILL,TELNET_BINARY_TX);
		}
753 754 755
		/* Will suppress Go Ahead */
		request_telnet_opt(TELNET_WILL,TELNET_SUP_GA);
	}
756
	putcom(cfg.answer_banner, strlen(cfg.answer_banner));
757 758 759
	return connected(modem);
}

760 761
bool read_ini(const char* ini_fname);

762 763 764 765 766 767 768 769
char* atmodem_exec(struct modem* modem)
{
	static char respbuf[128];
	char* resp = ok(modem);
	modem->buf[modem->buflen] = '\0';
	for(char* p = modem->buf; *p != '\0';) {
		char ch = toupper(*p);
		p++;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
		if(ch == '&') {
			ch = toupper(*p);
			ulong val = strtoul(p + 1, &p, 10);
			switch(ch) {
				case 'W':
					resp = write_cfg(modem) ? ok(modem) : error(modem);
					break;
				case 'Z':
					if(val >= MAX_SAVES)
						return error(modem);
					if(*p == '=') {
						p++;
						if(stricmp(p, "L") == 0)
							p = modem->last;
						SAFECOPY(modem->save[val], p);
						return write_save(modem, val) ? ok(modem) : error(modem);
					}
					if(*p == '?' || stricmp(p, "L?") == 0) {
						if(stricmp(p, "L?") == 0)
							p = modem->last;
						else
							p = modem->save[val];
						safe_snprintf(respbuf, sizeof(respbuf), "%c%s%c%c%s"
							,modem->lf, p, modem->cr, modem->lf, ok(modem));
						return respbuf;
					}
			}
			continue;
		}
		// Caller ID control
		if(ch == '#' || ch == '+') {
			if(ch == '+' && toupper(*p) == 'V')
				p++;
			if(stricmp(p, "CID?") == 0) {
				safe_snprintf(respbuf, sizeof(respbuf), "%c%u%c%c%s"
					,modem->lf, modem->caller_id, modem->cr, modem->lf, ok(modem));
				return respbuf;
			}
			if(stricmp(p, "CID=?") == 0) {
				safe_snprintf(respbuf, sizeof(respbuf), "%c0,1%c%c%s"
					,modem->lf, modem->cr, modem->lf, ok(modem));
				return respbuf;
			}
			if(strnicmp(p, "CID=", 4) == 0) {
				modem->caller_id = strtoul(p + 4, &p, 10);
				continue;
			}
817
			return error(modem);
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
		}
		// Numeric argument commands
		ulong val = 0;
		if(strchr(string_cmds, ch) == NULL)
			val = strtoul(p, &p, 10);
		switch(ch) {
			case 'A':
				return answer(modem);
			case 'D':
				if(sock != INVALID_SOCKET) {
					dprintf("Can't dial: Already connected");
					return error(modem);
				}
				if(*p == 'T' /* tone */|| *p == 'P' /* pulse */)
					p++;
				return dial(modem, p);
			case 'E':
				modem->echo_off = !val;
				break;
			case 'H':
				modem->offhook = val;
				modem->ringing = false;
				if(!modem->offhook) {
					if(sock != INVALID_SOCKET) {
						disconnect(modem);
					}
				}
				break;
			case 'I':
				switch(val) {
					case 0:
						safe_snprintf(respbuf, sizeof(respbuf)
850
							,TITLE " v" VERSION " Copyright %s Rob Swindell\r\n%s/%s"
851 852 853 854
							,&__DATE__[7]
							,GIT_BRANCH
							,GIT_HASH
							);
855
						return text_response(modem, respbuf);
856
					case 1:
857
						return text_response(modem, ini_fname);
858 859
					default:
						return error(modem);
860
				}
861
				return respbuf;
862 863 864 865 866
			case 'L': /* Speaker volume */
				break;
			case 'M':
				modem->speaker = val;
				break;
867 868 869 870 871 872 873 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
			case 'O':
				if(sock == INVALID_SOCKET)
					return error(modem);
				modem->online = true;
				return connect_result(modem);
				break;
			case 'V':
				modem->numeric_mode = !val;
				resp = ok(modem); // Use the new verbal/numeric mode in response (ala USRobotics)
				break;
			case 'Q':
				modem->quiet = val;
				resp = ok(modem); // Use the new quiet/verbose mode in response (ala USRobotics)
				break;
			case 'S':
				if(*p == '=') {
					ulong sreg = val;
					ulong val = strtoul(p + 1, &p, 10);
					dprintf("S%lu = %lu", sreg, val);
					switch(sreg) {
						case 0:
							if(val && listening_sock == INVALID_SOCKET) {
								dprintf("Can't enable auto-answer when not in listening mode");
								return error(modem);
							}
							modem->auto_answer = val;
							break;
						case 1:
							modem->ringcount = val;
							break;
						case 2:
							modem->esc = (char)val;
							break;
						case 3:
							modem->cr = (char)val;
							break;
						case 4:
							modem->lf = (char)val;
							break;
						case 5:
							modem->bs = (char)val;
							break;
						case 7:
							modem->dial_wait = val;
							break;
						case 12:
							modem->guard_time = val;
							break;
915
					}
916
				} else if(*p == '?') {
917 918
					switch(val) {
						case 0:
919
							val = modem->auto_answer;
920 921
							break;
						case 1:
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
							val = modem->ringcount;
							break;
						case 2:
							val = modem->esc;
							break;
						case 3:
							val = modem->cr;
							break;
						case 4:
							val = modem->lf;
							break;
						case 5:
							val = modem->bs;
							break;
						case 7:
							val = modem->dial_wait;
							break;
						case 12:
							val = modem->guard_time;
941 942
							break;
						default:
943 944
							val = 0;
							break;
945
					}
946 947
					safe_snprintf(respbuf, sizeof(respbuf), "%c%03lu%c%c%s"
						,modem->lf, val, modem->cr, modem->lf, ok(modem));
948
					return respbuf;
949 950 951
				} else
					return error(modem);
				break;
952 953 954 955
			case 'P': /* Pulse */
				break;
			case 'T': /* Tone */
				break;
956 957 958 959
			case 'X':
				modem->ext_results = val;
				break;
			case 'Z':
960 961 962 963
				if(fexist(ini_fname)) {
					if(!read_ini(ini_fname))
						return error(modem);
				}
964 965 966 967
				init(modem);
				break;
			default:
				return error(modem);
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
		}
	}
	return resp;
}

char* atmodem_parsech(struct modem* modem, uint8_t ch)
{
	switch(modem->cmdstate) {
		case INIT:
			if(toupper(ch) == 'A')
				modem->cmdstate = A;
			break;
		case A:
			if(toupper(ch) == 'T')
				modem->cmdstate = AT;
			else
				newcmd(modem);
			break;
		case AT:
			if(ch == modem->cr) {
				char* retval = atmodem_exec(modem);
				newcmd(modem);
				return retval;
			} else if(ch == modem->bs) {
				if(modem->buflen)
					modem->buflen--;
			} else {
				if(modem->buflen >= sizeof(modem->buf))
					return error(modem);
				if(ch != ' ')
					modem->buf[modem->buflen++] = ch;
			}
			break;
	}
	return NULL;
}

char* atmodem_parse(struct modem* modem, uint8_t* buf, size_t len)
{
	for(size_t i = 0; i < len; i++) {
		char* resp = atmodem_parsech(modem, buf[i]);
		if(resp != NULL)
			return resp;
	}
	return NULL;
}

BOOL vdd_write(HANDLE* slot, uint8_t* buf, size_t buflen)
{
	if(*slot == INVALID_HANDLE_VALUE) {
		char path[MAX_PATH + 1];
1019
		SAFEPRINTF(path, "\\\\.\\mailslot\\sbbsexec\\wr%d", cfg.node_num);
1020 1021 1022 1023 1024 1025 1026 1027
		*slot = CreateFile(path
			,GENERIC_WRITE
			,FILE_SHARE_READ
			,NULL
			,OPEN_EXISTING
			,FILE_ATTRIBUTE_NORMAL
			,(HANDLE) NULL);
		if(*slot == INVALID_HANDLE_VALUE) {
Rob Swindell's avatar
Rob Swindell committed
1028 1029
			dprintf("!ERROR %u (%s) opening '%s'", GetLastError(), strerror(GetLastError()), path);
			return FALSE;
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
		}
	}
	DWORD wr = 0;
	BOOL result = WriteFile(*slot, buf, buflen, &wr, /* LPOVERLAPPED */NULL);
	if(wr != buflen)
		dprintf("WriteFile wrote %ld instead of %ld", wr, buflen);
	return result;
}

BOOL vdd_writestr(HANDLE* slot, char* str)
{
	return vdd_write(slot, str, strlen(str));
}

void listen_thread(void* arg)
{
	struct modem* modem = (struct modem*)arg;

	for(;;) {
		fd_set fds = {0};
		FD_SET(listening_sock, &fds);
		struct timeval tv = { 1, 0 };
		if(select(/* ignored: */0, &fds, NULL, NULL, &tv) == 1) {
1053 1054 1055 1056 1057
			union xp_sockaddr newaddr;
			socklen_t addrlen = sizeof(newaddr);
			SOCKET newsock = accept(listening_sock, (SOCKADDR*)&newaddr, &addrlen);
			if(newsock == INVALID_SOCKET)
				continue;
1058 1059
			char ipaddr[256];
			inet_addrtop(&newaddr, ipaddr, sizeof(ipaddr));
1060
			dprintf("Connection accepted from TCP port %hu at %s"
1061 1062 1063 1064 1065 1066 1067
				,inet_addrport(&newaddr), ipaddr);
			if(findstr(ipaddr, cfg.ip_filter_file)) {
				dprintf("IP address blocked: %s", ipaddr);
				shutdown(newsock, SD_SEND);
				closesocket(newsock);
				continue;
			}
1068
			if(sock != INVALID_SOCKET) {	// In-use
1069 1070 1071
				send(newsock, cfg.busy_notice, strlen(cfg.busy_notice), /* flags: */0);
				shutdown(newsock, SD_SEND);
				closesocket(newsock);
1072 1073
				continue;
			}
1074 1075
			sock = newsock;
			addr = newaddr;
1076
			if(!modem->offhook && !modem->online) {
1077
				modem->ringing = true;
1078 1079
				modem->ringcount = 0;
			}
1080 1081 1082 1083
		}
	}
}

1084 1085 1086 1087 1088 1089
bool read_ini(const char* ini_fname)
{
	FILE* fp = iniOpenFile(ini_fname, /* create: */false);
	if(fp == NULL)
		return false;

1090
	iniFreeStringList(ini);
1091 1092 1093 1094 1095 1096 1097 1098
	ini = iniReadFile(fp);
	iniCloseFile(fp);
	mode = iniGetEnum(ini, ROOT_SECTION, "Mode", modeNames, mode);
	cfg.port = iniGetShortInt(ini, ROOT_SECTION, "Port", cfg.port);
	cfg.node_num = iniGetInteger(ini, ROOT_SECTION, "Node", cfg.node_num);
	cfg.listen = iniGetBool(ini, ROOT_SECTION, "Listen", cfg.listen);
	cfg.debug = iniGetBool(ini, ROOT_SECTION, "Debug", cfg.debug);
	cfg.server_echo = iniGetBool(ini, ROOT_SECTION, "ServerEcho", cfg.server_echo);
1099
	cfg.server_binary = iniGetBool(ini, ROOT_SECTION, "ServerBinary", cfg.server_binary);
1100 1101
	cfg.data_rate = iniGetLongInt(ini, ROOT_SECTION, "Rate", cfg.data_rate);
	cfg.address_family = iniGetEnum(ini, ROOT_SECTION, "AddressFamily", addrFamilyNames, cfg.address_family);
1102 1103 1104 1105
	char value[INI_MAX_VALUE_LEN];
	const char* p = iniGetString(ini, ROOT_SECTION, "BusyNotice", NULL, value);
	if(p != NULL)
		SAFECOPY(cfg.busy_notice, p);
1106
	if((p = iniGetString(ini, ROOT_SECTION, "AnswerBanner", NULL, value)) != NULL)
1107
		SAFECOPY(cfg.answer_banner, p);
1108 1109
	if((p = iniGetString(ini, ROOT_SECTION, "ClientFile", NULL, value)) != NULL)
		SAFECOPY(cfg.client_file, p);
1110 1111
	if((p = iniGetString(ini, ROOT_SECTION, "IpFilterFile", NULL, value)) != NULL)
		SAFECOPY(cfg.ip_filter_file, p);
1112 1113 1114 1115 1116 1117
	if((p = iniGetString(ini, ROOT_SECTION, "RingSound", NULL, value)) != NULL)
		SAFECOPY(cfg.ring_sound, p);
	if((p = iniGetString(ini, ROOT_SECTION, "ConnectSound", NULL, value)) != NULL)
		SAFECOPY(cfg.connect_sound, p);
	if((p = iniGetString(ini, ROOT_SECTION, "DisconnectSound", NULL, value)) != NULL)
		SAFECOPY(cfg.disconnect_sound, p);
1118 1119 1120
	return true;
}

1121 1122 1123 1124 1125
int main(int argc, char** argv)
{
	int argn = 1;
	char tmp[256];
	char path[MAX_PATH + 1];
1126
	char fullcmdline[MAX_PATH + 1];
1127
	uint8_t buf[XTRN_IO_BUF_LEN];
Rob Swindell's avatar
Rob Swindell committed
1128
	uint8_t telnet_buf[sizeof(buf) * 2];
1129 1130 1131 1132 1133
	size_t rx_buflen = sizeof(buf);
	ULONGLONG rx_delay = 0;
	WSADATA WSAData;
	int	result;

1134
	fprintf(stdout, TITLE " v" VERSION " Copyright %s Rob Swindell\n", &__DATE__[7]);
1135 1136 1137 1138 1139 1140 1141
    if((result = WSAStartup(MAKEWORD(1,1), &WSAData)) == 0)
		dprintf("%s %s",WSAData.szDescription, WSAData.szSystemStatus);
	else {
		fprintf(stderr,"!WinSock startup ERROR %d", result);
		return EXIT_FAILURE;
	}

1142
	// Default configuration values
Rob Swindell's avatar
Rob Swindell committed
1143
	mode = TELNET;
1144
	cfg.server_echo = TRUE;
1145
	cfg.server_binary = TRUE;
Rob Swindell's avatar
Rob Swindell committed
1146
	cfg.port = IPPORT_TELNET;
Rob Swindell's avatar
Rob Swindell committed
1147
	cfg.address_family = ADDRESS_FAMILY_UNSPEC;
1148
	SAFECOPY(cfg.client_file, "client.ini");
1149
	SAFECOPY(cfg.busy_notice, "\r\nSorry, not available right now\r\n");
1150
	SAFEPRINTF(cfg.answer_banner, "\r\n" TITLE " v" VERSION " Copyright %s Rob Swindell\r\n", &__DATE__[7]);
1151 1152

	ini = strListInit();
1153
	GetModuleFileName(NULL, ini_fname, sizeof(ini_fname) - 1);
1154 1155 1156 1157
	char* ext = getfext(ini_fname);
	if(ext != NULL)
		*ext = 0;
	SAFECAT(ini_fname, ".ini");
1158 1159
	if(fexist(ini_fname))
		read_ini(ini_fname);
1160 1161 1162 1163 1164 1165 1166

	for(; argn < argc; argn++) {
		char* arg = argv[argn];
		if(*arg != '-')
			break;
		while(*arg == '-')
			arg++;
Rob Swindell's avatar
Rob Swindell committed
1167
		if(stricmp(arg, "telnet") == 0) {
Rob Swindell's avatar
Rob Swindell committed
1168 1169 1170
			mode = TELNET;
			continue;
		}
Rob Swindell's avatar
Rob Swindell committed
1171
		if(stricmp(arg, "raw") == 0) {
Rob Swindell's avatar
Rob Swindell committed
1172 1173 1174
			mode = RAW;
			continue;
		}
1175
		switch(*arg) {
Rob Swindell's avatar
Rob Swindell committed
1176 1177 1178
			case '4':
				cfg.address_family = ADDRESS_FAMILY_INET;
				break;
1179
			case '6':
Rob Swindell's avatar
Rob Swindell committed
1180
				cfg.address_family = ADDRESS_FAMILY_INET6;
1181 1182 1183 1184 1185
				break;
			case 'l':
				cfg.listen = true;
				arg++;
				if(*arg != '\0') {
1186
					listening_interface.addr.sa_family = listen_address_family();
1187 1188 1189 1190 1191 1192
					if(inet_ptoaddr(arg, &listening_interface, sizeof(listening_interface)) == NULL) {
						fprintf(stderr, "!Error parsing network address: %s", arg);
						return EXIT_FAILURE;
					}
				}
				break;
1193 1194 1195
			case 'n':
				cfg.node_num = atoi(arg + 1);
				break;
1196
			case 'p':
Rob Swindell's avatar
Rob Swindell committed
1197
				cfg.port = atoi(arg + 1);
1198
				break;
1199
			case 'c':
1200 1201 1202
				SAFECOPY(ini_fname, arg + 1);
				if(!read_ini(ini_fname)) {
					fprintf(stderr, "!Error %d reading: %s\n", errno, ini_fname);
1203 1204 1205
					return EXIT_FAILURE;
				}
				break;
1206 1207 1208 1209 1210
			case 'd':
				cfg.debug = true;
				break;
			case 'h':
				sock = strtoul(arg + 1, NULL, 10);
1211
				external_socket = true;
1212 1213 1214 1215
				break;
			case 'r':
				cfg.data_rate = strtoul(arg + 1, NULL, 10);
				break;
Rob Swindell's avatar
Rob Swindell committed
1216
			case 'B':
1217
				rx_buflen = min(strtoul(arg + 1, NULL, 10), sizeof(buf));
1218
				break;
1219 1220 1221
			case 'R':
				rx_delay = strtoul(arg + 1, NULL, 10);
				break;
1222 1223 1224 1225 1226 1227 1228 1229 1230
			case 'I':
				sbbsexec_mode |= SBBSEXEC_MODE_DOS_IN;
				break;
			case 'O':
				sbbsexec_mode |= SBBSEXEC_MODE_DOS_OUT;
				break;
			case 'M':
				sbbsexec_mode = strtoul(arg + 1, NULL, 0);
				break;
1231
			case 'V':
1232 1233 1234 1235
			{
				char compiler[128];
				DESCRIBE_COMPILER(compiler);
				fprintf(stdout, "%s/%s built %s %s using %s\n", GIT_BRANCH, GIT_HASH, __DATE__, __TIME__, compiler);
1236
				return EXIT_SUCCESS;
1237
			}
1238
			default:
1239
				usage(argv[0]);
1240 1241 1242 1243
				break;
		}
	}
	if(argn >= argc) {
1244
		usage(argv[0]);
1245 1246 1247 1248 1249 1250 1251 1252 1253
	}

	struct modem modem = {0};
	init(&modem);

	if(cfg.listen) {
		if(sock != INVALID_SOCKET)
			listening_sock = sock;
		else {
1254
			listening_sock = socket(listen_address_family(), SOCK_STREAM, IPPROTO_IP);
1255 1256 1257 1258 1259
			if(listening_sock == INVALID_SOCKET) {
				fprintf(stderr, "Error %ld creating socket\n", WSAGetLastError());
				return EXIT_FAILURE;
			}
		}