comm.c 45.8 KB
Newer Older
1
/*
Alexandre Julliard's avatar
Alexandre Julliard committed
2
 * DEC 93 Erik Bos <erik@xs4all.nl>
Alexandre Julliard's avatar
Alexandre Julliard committed
3 4
 *
 * Copyright 1996 Marcus Meissner
5
 *
6 7 8 9 10 11 12 13 14 15 16 17
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
19 20
 */

21
#include "config.h"
22
#include "wine/port.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
23

Alexandre Julliard's avatar
Alexandre Julliard committed
24
#include <stdlib.h>
25
#include <stdarg.h>
26
#include <stdio.h>
27

28 29
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
30
#include "windef.h"
31
#include "winbase.h"
32
#include "winerror.h"
33 34
#include "winioctl.h"
#include "ddk/ntddser.h"
35 36

#include "wine/server.h"
37
#include "wine/unicode.h"
38

39
#include "wine/debug.h"
40

41
WINE_DEFAULT_DEBUG_CHANNEL(comm);
42

43
/***********************************************************************
44
 *           COMM_Parse*   (Internal)
45
 *
46 47
 *  The following COMM_Parse* functions are used by the BuildCommDCB
 *  functions to help parse the various parts of the device control string.
48
 */
49
static LPCWSTR COMM_ParseStart(LPCWSTR ptr)
50
{
51
	static const WCHAR comW[] = {'C','O','M',0};
52

53 54
	/* The device control string may optionally start with "COMx" followed
	   by an optional ':' and spaces. */
55
	if(!strncmpiW(ptr, comW, 3))
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	{
		ptr += 3;

		/* Allow any com port above 0 as Win 9x does (NT only allows
		   values for com ports which are actually present) */
		if(*ptr < '1' || *ptr > '9')
			return NULL;
		
		/* Advance pointer past port number */
		while(*ptr >= '0' && *ptr <= '9') ptr++;
		
		/* The com port number must be followed by a ':' or ' ' */
		if(*ptr != ':' && *ptr != ' ')
			return NULL;

		/* Advance pointer to beginning of next parameter */
		while(*ptr == ' ') ptr++;
		if(*ptr == ':')
		{
			ptr++;
			while(*ptr == ' ') ptr++;
		}
	}
	/* The device control string must not start with a space. */
	else if(*ptr == ' ')
		return NULL;
	
	return ptr;
}
 
86
static LPCWSTR COMM_ParseNumber(LPCWSTR ptr, LPDWORD lpnumber)
87 88
{
	if(*ptr < '0' || *ptr > '9') return NULL;
89
	*lpnumber = strtoulW(ptr, NULL, 10);
90 91 92 93
	while(*ptr >= '0' && *ptr <= '9') ptr++;
	return ptr;
}

94
static LPCWSTR COMM_ParseParity(LPCWSTR ptr, LPBYTE lpparity)
95 96 97 98 99
{
	/* Contrary to what you might expect, Windows only sets the Parity
	   member of DCB and not fParity even when parity is specified in the
	   device control string */

100
	switch(toupperW(*ptr++))
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	{
	case 'E':
		*lpparity = EVENPARITY;
		break;
	case 'M':
		*lpparity = MARKPARITY;
		break;
	case 'N':
		*lpparity = NOPARITY;
		break;
	case 'O':
		*lpparity = ODDPARITY;
		break;
	case 'S':
		*lpparity = SPACEPARITY;
		break;
	default:
		return NULL;
	}

	return ptr;
}

124
static LPCWSTR COMM_ParseByteSize(LPCWSTR ptr, LPBYTE lpbytesize)
125
{
126 127 128 129 130 131
	DWORD temp;

	if(!(ptr = COMM_ParseNumber(ptr, &temp)))
		return NULL;

	if(temp >= 5 && temp <= 8)
132
	{
133 134
		*lpbytesize = temp;
		return ptr;
135
	}
136 137 138
	else
		return NULL;
}
139

140
static LPCWSTR COMM_ParseStopBits(LPCWSTR ptr, LPBYTE lpstopbits)
141 142
{
	DWORD temp;
143
	static const WCHAR stopbits15W[] = {'1','.','5',0};
144

145
	if(!strncmpW(stopbits15W, ptr, 3))
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
	{
		ptr += 3;
		*lpstopbits = ONE5STOPBITS;
	}
	else
	{
		if(!(ptr = COMM_ParseNumber(ptr, &temp)))
			return NULL;

		if(temp == 1)
			*lpstopbits = ONESTOPBIT;
		else if(temp == 2)
			*lpstopbits = TWOSTOPBITS;
		else
			return NULL;
	}
	
	return ptr;
}

166
static LPCWSTR COMM_ParseOnOff(LPCWSTR ptr, LPDWORD lponoff)
167
{
168 169
	static const WCHAR onW[] = {'o','n',0};
	static const WCHAR offW[] = {'o','f','f',0};
170 171

	if(!strncmpiW(onW, ptr, 2))
172 173 174 175
	{
		ptr += 2;
		*lponoff = 1;
	}
176
	else if(!strncmpiW(offW, ptr, 3))
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	{
		ptr += 3;
		*lponoff = 0;
	}
	else
		return NULL;

	return ptr;
}

/***********************************************************************
 *           COMM_BuildOldCommDCB   (Internal)
 *
 *  Build a DCB using the old style settings string eg: "96,n,8,1"
 */
192
static BOOL COMM_BuildOldCommDCB(LPCWSTR device, LPDCB lpdcb)
193
{
194
	WCHAR last = 0;
195 196 197 198 199 200

	if(!(device = COMM_ParseNumber(device, &lpdcb->BaudRate)))
		return FALSE;
	
	switch(lpdcb->BaudRate)
	{
201 202 203
	case 11:
	case 30:
	case 60:
204
		lpdcb->BaudRate *= 10;
205 206 207 208 209
		break;
	case 12:
	case 24:
	case 48:
	case 96:
210
		lpdcb->BaudRate *= 100;
211 212
		break;
	case 19:
213
		lpdcb->BaudRate = 19200;
214 215
		break;
	}
216

217 218 219
	while(*device == ' ') device++;
	if(*device++ != ',') return FALSE;
	while(*device == ' ') device++;
220

221 222
	if(!(device = COMM_ParseParity(device, &lpdcb->Parity)))
		return FALSE;
223

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	while(*device == ' ') device++;
	if(*device++ != ',') return FALSE;
	while(*device == ' ') device++;
		
	if(!(device = COMM_ParseByteSize(device, &lpdcb->ByteSize)))
		return FALSE;

	while(*device == ' ') device++;
	if(*device++ != ',') return FALSE;
	while(*device == ' ') device++;

	if(!(device = COMM_ParseStopBits(device, &lpdcb->StopBits)))
		return FALSE;

	/* The last parameter for flow control is optional. */
	while(*device == ' ') device++;
	if(*device == ',')
	{
		device++;
		while(*device == ' ') device++;
244
		if(*device) last = toupperW(*device++);
245 246
		while(*device == ' ') device++;
	}
247 248 249

	/* Win NT sets the flow control members based on (or lack of) the last
	   parameter.  Win 9x does not set these members. */
250 251 252 253 254 255 256 257 258
	switch(last)
	{
	case 0:
		lpdcb->fInX = FALSE;
		lpdcb->fOutX = FALSE;
		lpdcb->fOutxCtsFlow = FALSE;
		lpdcb->fOutxDsrFlow = FALSE;
		lpdcb->fDtrControl = DTR_CONTROL_ENABLE;
		lpdcb->fRtsControl = RTS_CONTROL_ENABLE;
259
		break;
260 261 262 263 264 265 266
	case 'X':
		lpdcb->fInX = TRUE;
		lpdcb->fOutX = TRUE;
		lpdcb->fOutxCtsFlow = FALSE;
		lpdcb->fOutxDsrFlow = FALSE;
		lpdcb->fDtrControl = DTR_CONTROL_ENABLE;
		lpdcb->fRtsControl = RTS_CONTROL_ENABLE;
267
		break;
268 269 270 271 272 273 274
	case 'P':
		lpdcb->fInX = FALSE;
		lpdcb->fOutX = FALSE;
		lpdcb->fOutxCtsFlow = TRUE;
		lpdcb->fOutxDsrFlow = TRUE;
		lpdcb->fDtrControl = DTR_CONTROL_HANDSHAKE;
		lpdcb->fRtsControl = RTS_CONTROL_HANDSHAKE;
275
		break;
276 277 278 279
	default:
		return FALSE;
	}

280 281 282 283 284
	/* This should be the end of the string. */
	if(*device) return FALSE;
	
	return TRUE;
}
285

286 287 288 289 290 291
/***********************************************************************
 *           COMM_BuildNewCommDCB   (Internal)
 *
 *  Build a DCB using the new style settings string.
 *   eg: "baud=9600 parity=n data=8 stop=1 xon=on to=on"
 */
292
static BOOL COMM_BuildNewCommDCB(LPCWSTR device, LPDCB lpdcb, LPCOMMTIMEOUTS lptimeouts)
293 294 295
{
	DWORD temp;
	BOOL baud = FALSE, stop = FALSE;
296 297 298 299 300 301 302 303 304 305 306
	static const WCHAR baudW[] = {'b','a','u','d','=',0};
	static const WCHAR parityW[] = {'p','a','r','i','t','y','=',0};
	static const WCHAR dataW[] = {'d','a','t','a','=',0};
	static const WCHAR stopW[] = {'s','t','o','p','=',0};
	static const WCHAR toW[] = {'t','o','=',0};
	static const WCHAR xonW[] = {'x','o','n','=',0};
	static const WCHAR odsrW[] = {'o','d','s','r','=',0};
	static const WCHAR octsW[] = {'o','c','t','s','=',0};
	static const WCHAR dtrW[] = {'d','t','r','=',0};
	static const WCHAR rtsW[] = {'r','t','s','=',0};
	static const WCHAR idsrW[] = {'i','d','s','r','=',0};
307 308 309 310 311

	while(*device)
	{
		while(*device == ' ') device++;

312
		if(!strncmpiW(baudW, device, 5))
313 314 315 316 317 318
		{
			baud = TRUE;
			
			if(!(device = COMM_ParseNumber(device + 5, &lpdcb->BaudRate)))
				return FALSE;
		}
319
		else if(!strncmpiW(parityW, device, 7))
320 321 322 323
		{
			if(!(device = COMM_ParseParity(device + 7, &lpdcb->Parity)))
				return FALSE;
		}
324
		else if(!strncmpiW(dataW, device, 5))
325 326 327 328
		{
			if(!(device = COMM_ParseByteSize(device + 5, &lpdcb->ByteSize)))
				return FALSE;
		}
329
		else if(!strncmpiW(stopW, device, 5))
330 331 332 333 334 335
		{
			stop = TRUE;
			
			if(!(device = COMM_ParseStopBits(device + 5, &lpdcb->StopBits)))
				return FALSE;
		}
336
		else if(!strncmpiW(toW, device, 3))
337 338 339 340 341 342 343 344 345 346
		{
			if(!(device = COMM_ParseOnOff(device + 3, &temp)))
				return FALSE;

			lptimeouts->ReadIntervalTimeout = 0;
			lptimeouts->ReadTotalTimeoutMultiplier = 0;
			lptimeouts->ReadTotalTimeoutConstant = 0;
			lptimeouts->WriteTotalTimeoutMultiplier = 0;
			lptimeouts->WriteTotalTimeoutConstant = temp ? 60000 : 0;
		}
347
		else if(!strncmpiW(xonW, device, 4))
348 349 350 351 352 353 354
		{
			if(!(device = COMM_ParseOnOff(device + 4, &temp)))
				return FALSE;

			lpdcb->fOutX = temp;
			lpdcb->fInX = temp;
		}
355
		else if(!strncmpiW(odsrW, device, 5))
356 357 358 359 360 361
		{
			if(!(device = COMM_ParseOnOff(device + 5, &temp)))
				return FALSE;

			lpdcb->fOutxDsrFlow = temp;
		}
362
		else if(!strncmpiW(octsW, device, 5))
363 364 365 366 367 368
		{
			if(!(device = COMM_ParseOnOff(device + 5, &temp)))
				return FALSE;

			lpdcb->fOutxCtsFlow = temp;
		}
369
		else if(!strncmpiW(dtrW, device, 4))
370 371 372 373 374 375
		{
			if(!(device = COMM_ParseOnOff(device + 4, &temp)))
				return FALSE;

			lpdcb->fDtrControl = temp;
		}
376
		else if(!strncmpiW(rtsW, device, 4))
377 378 379 380 381 382
		{
			if(!(device = COMM_ParseOnOff(device + 4, &temp)))
				return FALSE;

			lpdcb->fRtsControl = temp;
		}
383
		else if(!strncmpiW(idsrW, device, 5))
384 385 386 387
		{
			if(!(device = COMM_ParseOnOff(device + 5, &temp)))
				return FALSE;

388 389
			/* Win NT sets the fDsrSensitivity member based on the
			   idsr parameter.  Win 9x sets fOutxDsrFlow instead. */
390 391 392 393 394 395 396 397 398
			lpdcb->fDsrSensitivity = temp;
		}
		else
			return FALSE;

		/* After the above parsing, the next character (if not the end of
		   the string) should be a space */
		if(*device && *device != ' ')
			return FALSE;
399
	}
400

401 402 403 404 405 406 407
	/* If stop bits were not specified, a default is always supplied. */
	if(!stop)
	{
		if(baud && lpdcb->BaudRate == 110)
			lpdcb->StopBits = TWOSTOPBITS;
		else
			lpdcb->StopBits = ONESTOPBIT;
408 409
	}

410
	return TRUE;
411 412
}

413
/**************************************************************************
414
 *         BuildCommDCBA		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
415 416 417 418 419 420 421
 *
 *  Updates a device control block data structure with values from an
 *  ascii device control string.  The device control string has two forms
 *  normal and extended, it must be exclusively in one or the other form.
 *
 * RETURNS
 *
Andreas Mohr's avatar
Andreas Mohr committed
422
 *  True on success, false on a malformed control string.
423
 */
Andrew Johnston's avatar
Andrew Johnston committed
424
BOOL WINAPI BuildCommDCBA(
425 426
    LPCSTR device, /* [in] The ascii device control string used to update the DCB. */
    LPDCB  lpdcb)  /* [out] The device control block to be updated. */
427 428 429 430 431
{
	return BuildCommDCBAndTimeoutsA(device,lpdcb,NULL);
}

/**************************************************************************
432
 *         BuildCommDCBAndTimeoutsA		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
433 434
 *
 *  Updates a device control block data structure with values from an
Andreas Mohr's avatar
Andreas Mohr committed
435
 *  ascii device control string.  Taking timeout values from a timeouts
Andrew Johnston's avatar
Andrew Johnston committed
436 437 438 439
 *  struct if desired by the control string.
 *
 * RETURNS
 *
440
 *  True on success, false bad handles etc.
441
 */
Andrew Johnston's avatar
Andrew Johnston committed
442
BOOL WINAPI BuildCommDCBAndTimeoutsA(
443 444
    LPCSTR         device,     /* [in] The ascii device control string. */
    LPDCB          lpdcb,      /* [out] The device control block to be updated. */
445
    LPCOMMTIMEOUTS lptimeouts) /* [in] The COMMTIMEOUTS structure to be updated. */
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
{
	BOOL ret = FALSE;
	UNICODE_STRING deviceW;

	TRACE("(%s,%p,%p)\n",device,lpdcb,lptimeouts);
	if(device) RtlCreateUnicodeStringFromAsciiz(&deviceW,device);
	else deviceW.Buffer = NULL;

	if(deviceW.Buffer) ret = BuildCommDCBAndTimeoutsW(deviceW.Buffer,lpdcb,lptimeouts);

	RtlFreeUnicodeString(&deviceW);
	return ret;
}

/**************************************************************************
 *         BuildCommDCBAndTimeoutsW	(KERNEL32.@)
 *
 *  Updates a device control block data structure with values from a
 *  unicode device control string.  Taking timeout values from a timeouts
 *  struct if desired by the control string.
 *
 * RETURNS
 *
 *  True on success, false bad handles etc
 */
BOOL WINAPI BuildCommDCBAndTimeoutsW(
    LPCWSTR        devid,      /* [in] The unicode device control string. */
    LPDCB          lpdcb,      /* [out] The device control block to be updated. */
    LPCOMMTIMEOUTS lptimeouts) /* [in] The COMMTIMEOUTS structure to be updated. */
475
{
476 477 478
	DCB dcb;
	COMMTIMEOUTS timeouts;
	BOOL result;
479
	LPCWSTR ptr = devid;
480

481
	TRACE("(%s,%p,%p)\n",debugstr_w(devid),lpdcb,lptimeouts);
482

483 484
	memset(&timeouts, 0, sizeof timeouts);

485 486
	/* Set DCBlength. (Windows NT does not do this, but 9x does) */
	lpdcb->DCBlength = sizeof(DCB);
487

488 489 490
	/* Make a copy of the original data structures to work with since if
	   if there is an error in the device control string the originals
	   should not be modified (except possibly DCBlength) */
491 492
	dcb = *lpdcb;
	if(lptimeouts) timeouts = *lptimeouts;
493

494 495 496 497
	ptr = COMM_ParseStart(ptr);

	if(ptr == NULL)
		result = FALSE;
498
	else if(strchrW(ptr, ','))
499 500 501 502 503 504
		result = COMM_BuildOldCommDCB(ptr, &dcb);
	else
		result = COMM_BuildNewCommDCB(ptr, &dcb, &timeouts);

	if(result)
	{
505 506
		*lpdcb = dcb;
		if(lptimeouts) *lptimeouts = timeouts;
507
		return TRUE;
508
	}
509 510
	else
	{
511
		WARN("Invalid device control string: %s\n", debugstr_w(devid));
512 513 514
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}	
515 516 517
}

/**************************************************************************
518
 *         BuildCommDCBW		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
519 520 521 522 523 524 525
 *
 *  Updates a device control block structure with values from an
 *  unicode device control string.  The device control string has two forms
 *  normal and extended, it must be exclusively in one or the other form.
 *
 * RETURNS
 *
526
 *  True on success, false on a malformed control string.
527
 */
Andrew Johnston's avatar
Andrew Johnston committed
528
BOOL WINAPI BuildCommDCBW(
529 530
    LPCWSTR devid, /* [in] The unicode device control string. */
    LPDCB   lpdcb) /* [out] The device control block to be updated. */
531 532 533 534 535
{
	return BuildCommDCBAndTimeoutsW(devid,lpdcb,NULL);
}

/*****************************************************************************
536
 *	SetCommBreak		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
537 538 539
 *
 *  Halts the transmission of characters to a communications device.
 *
540 541 542
 * PARAMS
 *      handle  [in] The communications device to suspend
 *
Andrew Johnston's avatar
Andrew Johnston committed
543 544 545 546 547 548 549
 * RETURNS
 *
 *  True on success, and false if the communications device could not be found,
 *  the control is not supported.
 *
 * BUGS
 *
550
 *  Only TIOCSBRK and TIOCCBRK are supported.
551
 */
552
BOOL WINAPI SetCommBreak(HANDLE handle)
553
{
554 555
    DWORD dwBytesReturned;
    return DeviceIoControl(handle, IOCTL_SERIAL_SET_BREAK_ON, NULL, 0, NULL, 0, &dwBytesReturned, NULL);
556 557 558
}

/*****************************************************************************
559
 *	ClearCommBreak		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
560 561 562
 *
 *  Resumes character transmission from a communication device.
 *
563 564 565 566
 * PARAMS
 *
 *      handle [in] The halted communication device whose character transmission is to be resumed
 *
Andrew Johnston's avatar
Andrew Johnston committed
567 568 569 570 571 572
 * RETURNS
 *
 *  True on success and false if the communications device could not be found.
 *
 * BUGS
 *
573
 *  Only TIOCSBRK and TIOCCBRK are supported.
574
 */
575
BOOL WINAPI ClearCommBreak(HANDLE handle)
576
{
577 578
    DWORD dwBytesReturned;
    return DeviceIoControl(handle, IOCTL_SERIAL_SET_BREAK_OFF, NULL, 0, NULL, 0, &dwBytesReturned, NULL);
579 580 581
}

/*****************************************************************************
582
 *	EscapeCommFunction	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
583 584 585
 *
 *  Directs a communication device to perform an extended function.
 *
586 587 588 589 590
 * PARAMS
 *
 *      handle          [in] The communication device to perform the extended function
 *      nFunction       [in] The extended function to be performed
 *
Andrew Johnston's avatar
Andrew Johnston committed
591 592 593 594 595
 * RETURNS
 *
 *  True or requested data on successful completion of the command,
 *  false if the device is not present cannot execute the command
 *  or the command failed.
596
 */
597
BOOL WINAPI EscapeCommFunction(HANDLE handle, UINT func)
598
{
599
    DWORD       ioc;
600
    DWORD dwBytesReturned;
601

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    switch (func)
    {
    case CLRDTR:        ioc = IOCTL_SERIAL_CLR_DTR;             break;
    case CLRRTS:        ioc = IOCTL_SERIAL_CLR_RTS;             break;
    case SETDTR:        ioc = IOCTL_SERIAL_SET_DTR;             break;
    case SETRTS:        ioc = IOCTL_SERIAL_SET_RTS;             break;
    case SETXOFF:       ioc = IOCTL_SERIAL_SET_XOFF;            break;
    case SETXON:        ioc = IOCTL_SERIAL_SET_XON;             break;
    case SETBREAK:      ioc = IOCTL_SERIAL_SET_BREAK_ON;        break;
    case CLRBREAK:      ioc = IOCTL_SERIAL_SET_BREAK_OFF;       break;
    case RESETDEV:      ioc = IOCTL_SERIAL_RESET_DEVICE;        break;
    default:
        ERR("Unknown function code (%u)\n", func);
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
618
    return DeviceIoControl(handle, ioc, NULL, 0, NULL, 0, &dwBytesReturned, NULL);
619 620 621
}

/********************************************************************
622
 *      PurgeComm        (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
623 624 625 626
 *
 *  Terminates pending operations and/or discards buffers on a
 *  communication resource.
 *
627 628 629 630 631
 * PARAMS
 *
 *      handle  [in] The communication resource to be purged
 *      flags   [in] Flags for clear pending/buffer on input/output
 *
Andrew Johnston's avatar
Andrew Johnston committed
632 633 634
 * RETURNS
 *
 *  True on success and false if the communications handle is bad.
635
 */
636
BOOL WINAPI PurgeComm(HANDLE handle, DWORD flags)
637
{
638
    DWORD dwBytesReturned;
639
    return DeviceIoControl(handle, IOCTL_SERIAL_PURGE, &flags, sizeof(flags),
640
                           NULL, 0, &dwBytesReturned, NULL);
641 642 643
}

/*****************************************************************************
644
 *	ClearCommError	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
645 646 647 648
 *
 *  Enables further I/O operations on a communications resource after
 *  supplying error and current status information.
 *
649 650 651 652 653
 * PARAMS
 *
 *      handle  [in]    The communication resource with the error
 *      errors  [out]   Flags indicating error the resource experienced
 *      lpStat  [out] The status of the communication resource
Andrew Johnston's avatar
Andrew Johnston committed
654 655 656
 * RETURNS
 *
 *  True on success, false if the communication resource handle is bad.
657
 */
658
BOOL WINAPI ClearCommError(HANDLE handle, LPDWORD errors, LPCOMSTAT lpStat)
659
{
660
    SERIAL_STATUS       ss;
661
    DWORD dwBytesReturned;
662

663
    if (!DeviceIoControl(handle, IOCTL_SERIAL_GET_COMMSTATUS, NULL, 0,
664
                         &ss, sizeof(ss), &dwBytesReturned, NULL))
665
        return FALSE;
666

667 668 669 670 671 672 673 674 675 676
    if (errors)
    {
        *errors = 0;
        if (ss.Errors & SERIAL_ERROR_BREAK)             *errors |= CE_BREAK;
        if (ss.Errors & SERIAL_ERROR_FRAMING)           *errors |= CE_FRAME;
        if (ss.Errors & SERIAL_ERROR_OVERRUN)           *errors |= CE_OVERRUN;
        if (ss.Errors & SERIAL_ERROR_QUEUEOVERRUN)      *errors |= CE_RXOVER;
        if (ss.Errors & SERIAL_ERROR_PARITY)            *errors |= CE_RXPARITY;
    }
 
677
    if (lpStat)
678
    {
679 680 681 682 683 684 685 686 687 688 689
        memset(lpStat, 0, sizeof(*lpStat));

        if (ss.HoldReasons & SERIAL_TX_WAITING_FOR_CTS)         lpStat->fCtsHold = TRUE;
        if (ss.HoldReasons & SERIAL_TX_WAITING_FOR_DSR)         lpStat->fDsrHold = TRUE;
        if (ss.HoldReasons & SERIAL_TX_WAITING_FOR_DCD)         lpStat->fRlsdHold = TRUE;
        if (ss.HoldReasons & SERIAL_TX_WAITING_FOR_XON)         lpStat->fXoffHold = TRUE;
        if (ss.HoldReasons & SERIAL_TX_WAITING_XOFF_SENT)       lpStat->fXoffSent = TRUE;
        if (ss.EofReceived)                                     lpStat->fEof = TRUE;
        if (ss.WaitForImmediate)                                lpStat->fTxim = TRUE;
        lpStat->cbInQue = ss.AmountInInQueue;
        lpStat->cbOutQue = ss.AmountInOutQueue;
690 691 692 693 694
    }
    return TRUE;
}

/*****************************************************************************
695
 *      SetupComm       (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
696 697 698 699
 *
 *  Called after CreateFile to hint to the communication resource to use
 *  specified sizes for input and output buffers rather than the default values.
 *
700 701 702 703 704
 * PARAMS
 *      handle  [in]    The just created communication resource handle
 *      insize  [in]    The suggested size of the communication resources input buffer in bytes
 *      outsize [in]    The suggested size of the communication resources output buffer in bytes
 *
Andrew Johnston's avatar
Andrew Johnston committed
705 706 707 708 709 710 711
 * RETURNS
 *
 *  True if successful, false if the communications resource handle is bad.
 *
 * BUGS
 *
 *  Stub.
712
 */
713
BOOL WINAPI SetupComm(HANDLE handle, DWORD insize, DWORD outsize)
714
{
715
    SERIAL_QUEUE_SIZE   sqs;
716
    DWORD dwBytesReturned;
717

718 719 720
    sqs.InSize = insize;
    sqs.OutSize = outsize;
    return DeviceIoControl(handle, IOCTL_SERIAL_SET_QUEUE_SIZE,
721
                           &sqs, sizeof(sqs), NULL, 0, &dwBytesReturned, NULL);
722
}
723 724

/*****************************************************************************
725
 *	GetCommMask	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
726
 *
Andreas Mohr's avatar
Andreas Mohr committed
727 728
 *  Obtain the events associated with a communication device that will cause
 *  a call WaitCommEvent to return.
Andrew Johnston's avatar
Andrew Johnston committed
729
 *
730 731 732 733 734
 *  PARAMS
 *
 *      handle  [in]    The communications device
 *      evtmask [out]   The events which cause WaitCommEvent to return
 *
Andrew Johnston's avatar
Andrew Johnston committed
735 736 737
 *  RETURNS
 *
 *   True on success, fail on bad device handle etc.
738
 */
739
BOOL WINAPI GetCommMask(HANDLE handle, LPDWORD evtmask)
740
{
741
    DWORD dwBytesReturned;
742
    TRACE("handle %p, mask %p\n", handle, evtmask);
743
    return DeviceIoControl(handle, IOCTL_SERIAL_GET_WAIT_MASK,
744
                           NULL, 0, evtmask, sizeof(*evtmask), &dwBytesReturned, NULL);
745 746 747
}

/*****************************************************************************
748
 *	SetCommMask	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
749 750 751 752 753
 *
 *  There be some things we need to hear about yon there communications device.
 *  (Set which events associated with a communication device should cause
 *  a call WaitCommEvent to return.)
 *
754 755 756 757 758
 * PARAMS
 *
 *      handle  [in]    The communications device
 *      evtmask [in]    The events that are to be monitored
 *
Andrew Johnston's avatar
Andrew Johnston committed
759 760 761
 * RETURNS
 *
 *  True on success, false on bad handle etc.
762
 */
763
BOOL WINAPI SetCommMask(HANDLE handle, DWORD evtmask)
764
{
765
    DWORD dwBytesReturned;
766
    TRACE("handle %p, mask %x\n", handle, evtmask);
767
    return DeviceIoControl(handle, IOCTL_SERIAL_SET_WAIT_MASK,
768
                           &evtmask, sizeof(evtmask), NULL, 0, &dwBytesReturned, NULL);
Alexandre Julliard's avatar
Alexandre Julliard committed
769 770
}

771 772
static void dump_dcb(const DCB* lpdcb)
{
773
    TRACE("bytesize=%d baudrate=%d fParity=%d Parity=%d stopbits=%d\n",
774 775 776
          lpdcb->ByteSize, lpdcb->BaudRate, lpdcb->fParity, lpdcb->Parity,
          (lpdcb->StopBits == ONESTOPBIT) ? 1 :
          (lpdcb->StopBits == TWOSTOPBITS) ? 2 : 0);
777
    TRACE("%sIXON %sIXOFF\n", (lpdcb->fOutX) ? "" : "~", (lpdcb->fInX) ? "" : "~");
778 779 780 781 782 783 784 785
    TRACE("fOutxCtsFlow=%d fRtsControl=%d\n", lpdcb->fOutxCtsFlow, lpdcb->fRtsControl);
    TRACE("fOutxDsrFlow=%d fDtrControl=%d\n", lpdcb->fOutxDsrFlow, lpdcb->fDtrControl);
    if (lpdcb->fOutxCtsFlow || lpdcb->fRtsControl == RTS_CONTROL_HANDSHAKE)
        TRACE("CRTSCTS\n");
    else
        TRACE("~CRTSCTS\n");
}

Alexandre Julliard's avatar
Alexandre Julliard committed
786
/*****************************************************************************
787
 *	SetCommState    (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
788 789
 *
 *  Re-initializes all hardware and control settings of a communications device,
Austin English's avatar
Austin English committed
790
 *  with values from a device control block without affecting the input and output
Andrew Johnston's avatar
Andrew Johnston committed
791 792
 *  queues.
 *
793 794 795 796 797
 * PARAMS
 *
 *      handle  [in]    The communications device
 *      lpdcb   [out]   The device control block
 *
Andrew Johnston's avatar
Andrew Johnston committed
798 799
 * RETURNS
 *
Austin English's avatar
Austin English committed
800
 *  True on success, false on failure, e.g., if the XonChar is equal to the XoffChar.
Alexandre Julliard's avatar
Alexandre Julliard committed
801
 */
802
BOOL WINAPI SetCommState( HANDLE handle, LPDCB lpdcb)
Alexandre Julliard's avatar
Alexandre Julliard committed
803
{
804 805
    SERIAL_BAUD_RATE           sbr;
    SERIAL_LINE_CONTROL        slc;
806
    SERIAL_HANDFLOW            shf;
807
    SERIAL_CHARS               sc;
808
    DWORD dwBytesReturned;
809

810 811 812 813 814 815 816 817
    if (lpdcb == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    dump_dcb(lpdcb);

    sbr.BaudRate = lpdcb->BaudRate;
818 819 820 821 822
             
    slc.StopBits = lpdcb->StopBits;
    slc.Parity = lpdcb->Parity;
    slc.WordLength = lpdcb->ByteSize;

823 824 825 826 827 828 829 830 831 832 833 834 835
    shf.ControlHandShake = 0;
    shf.FlowReplace = 0;
    if (lpdcb->fOutxCtsFlow)      shf.ControlHandShake |= SERIAL_CTS_HANDSHAKE;
    if (lpdcb->fOutxDsrFlow)      shf.ControlHandShake |= SERIAL_DSR_HANDSHAKE;
    switch (lpdcb->fDtrControl)
    {
    case DTR_CONTROL_DISABLE:                                                  break;
    case DTR_CONTROL_ENABLE:      shf.ControlHandShake |= SERIAL_DTR_CONTROL;  break;
    case DTR_CONTROL_HANDSHAKE:   shf.ControlHandShake |= SERIAL_DTR_HANDSHAKE;break;
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
836
    switch (lpdcb->fRtsControl)
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    {
    case RTS_CONTROL_DISABLE:                                                  break;
    case RTS_CONTROL_ENABLE:      shf.FlowReplace |= SERIAL_RTS_CONTROL;       break;
    case RTS_CONTROL_HANDSHAKE:   shf.FlowReplace |= SERIAL_RTS_HANDSHAKE;     break;
    case RTS_CONTROL_TOGGLE:      shf.FlowReplace |= SERIAL_RTS_CONTROL | 
                                                     SERIAL_RTS_HANDSHAKE;     break;
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    if (lpdcb->fDsrSensitivity)   shf.ControlHandShake |= SERIAL_DSR_SENSITIVITY;
    if (lpdcb->fAbortOnError)     shf.ControlHandShake |= SERIAL_ERROR_ABORT;

    if (lpdcb->fErrorChar)        shf.FlowReplace |= SERIAL_ERROR_CHAR;
    if (lpdcb->fNull)             shf.FlowReplace |= SERIAL_NULL_STRIPPING;
    if (lpdcb->fTXContinueOnXoff) shf.FlowReplace |= SERIAL_XOFF_CONTINUE;
    if (lpdcb->fOutX)             shf.FlowReplace |= SERIAL_AUTO_TRANSMIT;
    if (lpdcb->fInX)              shf.FlowReplace |= SERIAL_AUTO_RECEIVE;

    shf.XonLimit = lpdcb->XonLim;
    shf.XoffLimit = lpdcb->XoffLim;

859 860 861 862 863 864 865
    sc.EofChar = lpdcb->EofChar;
    sc.ErrorChar = lpdcb->ErrorChar;
    sc.BreakChar = 0;
    sc.EventChar = lpdcb->EvtChar;
    sc.XonChar = lpdcb->XonChar;
    sc.XoffChar = lpdcb->XoffChar;

866 867 868
    /* note: change DTR/RTS lines after setting the comm attributes,
     * so flow control does not interfere.
     */
869
    return (DeviceIoControl(handle, IOCTL_SERIAL_SET_BAUD_RATE,
870
                            &sbr, sizeof(sbr), NULL, 0, &dwBytesReturned, NULL) &&
871
            DeviceIoControl(handle, IOCTL_SERIAL_SET_LINE_CONTROL,
872
                            &slc, sizeof(slc), NULL, 0, &dwBytesReturned, NULL) &&
873
            DeviceIoControl(handle, IOCTL_SERIAL_SET_HANDFLOW,
874
                            &shf, sizeof(shf), NULL, 0, &dwBytesReturned, NULL) &&
875
            DeviceIoControl(handle, IOCTL_SERIAL_SET_CHARS,
876
                            &sc, sizeof(sc), NULL, 0, &dwBytesReturned, NULL));
Alexandre Julliard's avatar
Alexandre Julliard committed
877 878 879 880
}


/*****************************************************************************
881
 *	GetCommState	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
882 883 884
 *
 *  Fills in a device control block with information from a communications device.
 *
885 886 887 888
 * PARAMS
 *      handle          [in]    The communications device
 *      lpdcb           [out]   The device control block
 *
Andrew Johnston's avatar
Andrew Johnston committed
889 890 891
 * RETURNS
 *
 *  True on success, false if the communication device handle is bad etc
892
 *
Andrew Johnston's avatar
Andrew Johnston committed
893 894 895
 * BUGS
 *
 *  XonChar and XoffChar are not set.
Alexandre Julliard's avatar
Alexandre Julliard committed
896
 */
897
BOOL WINAPI GetCommState(HANDLE handle, LPDCB lpdcb)
Alexandre Julliard's avatar
Alexandre Julliard committed
898
{
899
    SERIAL_BAUD_RATE    sbr;
900
    SERIAL_LINE_CONTROL slc;
901
    SERIAL_HANDFLOW     shf;
902
    SERIAL_CHARS        sc;
903
    DWORD dwBytesReturned;
904 905

    TRACE("handle %p, ptr %p\n", handle, lpdcb);
906

907 908 909 910 911 912 913
    if (!lpdcb)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    
    if (!DeviceIoControl(handle, IOCTL_SERIAL_GET_BAUD_RATE,
914
                         NULL, 0, &sbr, sizeof(sbr), &dwBytesReturned, NULL) ||
915
        !DeviceIoControl(handle, IOCTL_SERIAL_GET_LINE_CONTROL,
916
                         NULL, 0, &slc, sizeof(slc), &dwBytesReturned, NULL) ||
917
        !DeviceIoControl(handle, IOCTL_SERIAL_GET_HANDFLOW,
918
                         NULL, 0, &shf, sizeof(shf), &dwBytesReturned, NULL) ||
919
        !DeviceIoControl(handle, IOCTL_SERIAL_GET_CHARS,
920
                         NULL, 0, &sc, sizeof(sc), &dwBytesReturned, NULL))
921
        return FALSE;
922

923 924 925
    memset(lpdcb, 0, sizeof(*lpdcb));
    lpdcb->DCBlength = sizeof(*lpdcb);

926 927 928 929 930
    /* yes, they seem no never be (re)set on NT */
    lpdcb->fBinary = 1;
    lpdcb->fParity = 0;

    lpdcb->BaudRate = sbr.BaudRate;
931 932 933 934 935

    lpdcb->StopBits = slc.StopBits;
    lpdcb->Parity = slc.Parity;
    lpdcb->ByteSize = slc.WordLength;

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
    if (shf.ControlHandShake & SERIAL_CTS_HANDSHAKE)    lpdcb->fOutxCtsFlow = 1;
    if (shf.ControlHandShake & SERIAL_DSR_HANDSHAKE)    lpdcb->fOutxDsrFlow = 1;
    switch (shf.ControlHandShake & (SERIAL_DTR_CONTROL | SERIAL_DTR_HANDSHAKE))
    {
    case 0:                     lpdcb->fDtrControl = DTR_CONTROL_DISABLE; break;
    case SERIAL_DTR_CONTROL:    lpdcb->fDtrControl = DTR_CONTROL_ENABLE; break;
    case SERIAL_DTR_HANDSHAKE:  lpdcb->fDtrControl = DTR_CONTROL_HANDSHAKE; break;
    }
    switch (shf.FlowReplace & (SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE))
    {
    case 0:                     lpdcb->fRtsControl = RTS_CONTROL_DISABLE; break;
    case SERIAL_RTS_CONTROL:    lpdcb->fRtsControl = RTS_CONTROL_ENABLE; break;
    case SERIAL_RTS_HANDSHAKE:  lpdcb->fRtsControl = RTS_CONTROL_HANDSHAKE; break;
    case SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE:
                                lpdcb->fRtsControl = RTS_CONTROL_TOGGLE; break;
    }
    if (shf.ControlHandShake & SERIAL_DSR_SENSITIVITY)  lpdcb->fDsrSensitivity = 1;
    if (shf.ControlHandShake & SERIAL_ERROR_ABORT)      lpdcb->fAbortOnError = 1;
    if (shf.FlowReplace & SERIAL_ERROR_CHAR)            lpdcb->fErrorChar = 1;
    if (shf.FlowReplace & SERIAL_NULL_STRIPPING)        lpdcb->fNull = 1;
    if (shf.FlowReplace & SERIAL_XOFF_CONTINUE)         lpdcb->fTXContinueOnXoff = 1;
    lpdcb->XonLim = shf.XonLimit;
    lpdcb->XoffLim = shf.XoffLimit;
Alexandre Julliard's avatar
Alexandre Julliard committed
959

960 961
    if (shf.FlowReplace & SERIAL_AUTO_TRANSMIT) lpdcb->fOutX = 1;
    if (shf.FlowReplace & SERIAL_AUTO_RECEIVE)  lpdcb->fInX = 1;
Alexandre Julliard's avatar
Alexandre Julliard committed
962

963 964 965 966 967
    lpdcb->EofChar = sc.EofChar;
    lpdcb->ErrorChar = sc.ErrorChar;
    lpdcb->EvtChar = sc.EventChar;
    lpdcb->XonChar = sc.XonChar;
    lpdcb->XoffChar = sc.XoffChar;
Alexandre Julliard's avatar
Alexandre Julliard committed
968

969 970
    TRACE("OK\n");
    dump_dcb(lpdcb);
971

972
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
973 974 975
}

/*****************************************************************************
976
 *	TransmitCommChar	(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
977 978 979 980
 *
 *  Transmits a single character in front of any pending characters in the
 *  output buffer.  Usually used to send an interrupt character to a host.
 *
981 982 983 984
 * PARAMS
 *      hComm           [in]    The communication device in need of a command character
 *      chTransmit      [in]    The character to transmit
 *
Andrew Johnston's avatar
Andrew Johnston committed
985 986 987 988 989
 * RETURNS
 *
 *  True if the call succeeded, false if the previous command character to the
 *  same device has not been sent yet the handle is bad etc.
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
990
 */
991
BOOL WINAPI TransmitCommChar(HANDLE hComm, CHAR chTransmit)
Alexandre Julliard's avatar
Alexandre Julliard committed
992
{
993
    DWORD dwBytesReturned;
994
    return DeviceIoControl(hComm, IOCTL_SERIAL_IMMEDIATE_CHAR,
995
                           &chTransmit, sizeof(chTransmit), NULL, 0, &dwBytesReturned, NULL);
Alexandre Julliard's avatar
Alexandre Julliard committed
996 997
}

998

Alexandre Julliard's avatar
Alexandre Julliard committed
999
/*****************************************************************************
1000
 *	GetCommTimeouts		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
1001
 *
Andreas Mohr's avatar
Andreas Mohr committed
1002
 *  Obtains the request timeout values for the communications device.
Andrew Johnston's avatar
Andrew Johnston committed
1003
 *
1004 1005 1006 1007
 * PARAMS
 *      hComm           [in]    The communications device
 *      lptimeouts      [out]   The struct of request timeouts
 *
Andrew Johnston's avatar
Andrew Johnston committed
1008 1009 1010 1011
 * RETURNS
 *
 *  True on success, false if communications device handle is bad
 *  or the target structure is null.
Alexandre Julliard's avatar
Alexandre Julliard committed
1012
 */
1013
BOOL WINAPI GetCommTimeouts(HANDLE hComm, LPCOMMTIMEOUTS lptimeouts)
Alexandre Julliard's avatar
Alexandre Julliard committed
1014
{
1015
    SERIAL_TIMEOUTS     st;
1016
    DWORD dwBytesReturned;
1017

1018 1019
    TRACE("(%p, %p)\n", hComm, lptimeouts);
    if (!lptimeouts)
1020 1021 1022 1023
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
1024
    if (!DeviceIoControl(hComm, IOCTL_SERIAL_GET_TIMEOUTS,
1025
                         NULL, 0, &st, sizeof(st), &dwBytesReturned, NULL))
1026 1027 1028 1029 1030 1031 1032
        return FALSE;
    lptimeouts->ReadIntervalTimeout         = st.ReadIntervalTimeout;
    lptimeouts->ReadTotalTimeoutMultiplier  = st.ReadTotalTimeoutMultiplier;
    lptimeouts->ReadTotalTimeoutConstant    = st.ReadTotalTimeoutConstant;
    lptimeouts->WriteTotalTimeoutMultiplier = st.WriteTotalTimeoutMultiplier;
    lptimeouts->WriteTotalTimeoutConstant   = st.WriteTotalTimeoutConstant;
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1033 1034 1035
}

/*****************************************************************************
1036
 *	SetCommTimeouts		(KERNEL32.@)
1037 1038 1039
 *
 * Sets the timeouts used when reading and writing data to/from COMM ports.
 *
1040 1041 1042 1043
 * PARAMS
 *      hComm           [in]    handle of COMM device
 *      lptimeouts      [in]    pointer to COMMTIMEOUTS structure
 *
1044
 * ReadIntervalTimeout
1045 1046 1047 1048 1049
 *     - converted and passes to linux kernel as c_cc[VTIME]
 * ReadTotalTimeoutMultiplier, ReadTotalTimeoutConstant
 *     - used in ReadFile to calculate GetOverlappedResult's timeout
 * WriteTotalTimeoutMultiplier, WriteTotalTimeoutConstant
 *     - used in WriteFile to calculate GetOverlappedResult's timeout
Andrew Johnston's avatar
Andrew Johnston committed
1050 1051 1052
 *
 * RETURNS
 *
Andreas Mohr's avatar
Andreas Mohr committed
1053
 *  True if the timeouts were set, false otherwise.
Alexandre Julliard's avatar
Alexandre Julliard committed
1054
 */
1055
BOOL WINAPI SetCommTimeouts(HANDLE hComm, LPCOMMTIMEOUTS lptimeouts)
1056
{
1057
    SERIAL_TIMEOUTS     st;
1058
    DWORD dwBytesReturned;
1059

1060
    TRACE("(%p, %p)\n", hComm, lptimeouts);
1061

1062
    if (lptimeouts == NULL)
1063 1064 1065
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
1066
    }
1067 1068 1069 1070 1071 1072 1073
    st.ReadIntervalTimeout         = lptimeouts->ReadIntervalTimeout;
    st.ReadTotalTimeoutMultiplier  = lptimeouts->ReadTotalTimeoutMultiplier;
    st.ReadTotalTimeoutConstant    = lptimeouts->ReadTotalTimeoutConstant;
    st.WriteTotalTimeoutMultiplier = lptimeouts->WriteTotalTimeoutMultiplier;
    st.WriteTotalTimeoutConstant   = lptimeouts->WriteTotalTimeoutConstant;
 
    return DeviceIoControl(hComm, IOCTL_SERIAL_SET_TIMEOUTS,
1074
                           &st, sizeof(st), NULL, 0, &dwBytesReturned, NULL);
Alexandre Julliard's avatar
Alexandre Julliard committed
1075 1076
}

1077
/***********************************************************************
1078
 *           GetCommModemStatus   (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
1079 1080 1081
 *
 *  Obtains the four control register bits if supported by the hardware.
 *
1082 1083 1084 1085 1086
 * PARAMS
 *
 *      hFile           [in]    The communications device
 *      lpModemStat     [out]   The control register bits
 *
Andrew Johnston's avatar
Andrew Johnston committed
1087 1088 1089 1090
 * RETURNS
 *
 *  True if the communications handle was good and for hardware that
 *  control register access, false otherwise.
1091
 */
1092
BOOL WINAPI GetCommModemStatus(HANDLE hFile, LPDWORD lpModemStat)
1093
{
1094
    DWORD dwBytesReturned;
1095
    return DeviceIoControl(hFile, IOCTL_SERIAL_GET_MODEMSTATUS,
1096
                           NULL, 0, lpModemStat, sizeof(DWORD), &dwBytesReturned, NULL);
1097
}
1098

1099
/***********************************************************************
1100
 *           WaitCommEvent   (KERNEL32.@)
1101 1102 1103 1104 1105
 *
 * Wait until something interesting happens on a COMM port.
 * Interesting things (events) are set by calling SetCommMask before
 * this function is called.
 *
1106
 * RETURNS
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
 *   TRUE if successful
 *   FALSE if failure
 *
 *   The set of detected events will be written to *lpdwEventMask
 *   ERROR_IO_PENDING will be returned the overlapped structure was passed
 *
 * BUGS:
 *  Only supports EV_RXCHAR and EV_TXEMPTY
 */
BOOL WINAPI WaitCommEvent(
    HANDLE hFile,              /* [in] handle of comm port to wait for */
    LPDWORD lpdwEvents,        /* [out] event(s) that were detected */
    LPOVERLAPPED lpOverlapped) /* [in/out] for Asynchronous waiting */
{
1121 1122
    return DeviceIoControl(hFile, IOCTL_SERIAL_WAIT_ON_MASK, NULL, 0,
                           lpdwEvents, sizeof(DWORD), NULL, lpOverlapped);
1123
}
1124

1125
/***********************************************************************
1126
 *           GetCommProperties   (KERNEL32.@)
1127
 *
1128
 * This function fills in a structure with the capabilities of the
1129 1130 1131 1132 1133 1134 1135
 * communications port driver.
 *
 * RETURNS
 *
 *  TRUE on success, FALSE on failure
 *  If successful, the lpCommProp structure be filled in with
 *  properties of the comm port.
1136
 */
1137
BOOL WINAPI GetCommProperties(
1138 1139 1140
    HANDLE hFile,          /* [in] handle of the comm port */
    LPCOMMPROP lpCommProp) /* [out] pointer to struct to be filled */
{
1141
    TRACE("(%p %p)\n",hFile,lpCommProp);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    if(!lpCommProp)
        return FALSE;

    /*
     * These values should be valid for LINUX's serial driver
     * FIXME: Perhaps they deserve an #ifdef LINUX
     */
    memset(lpCommProp,0,sizeof(COMMPROP));
    lpCommProp->wPacketLength       = 1;
    lpCommProp->wPacketVersion      = 1;
    lpCommProp->dwServiceMask       = SP_SERIALCOMM;
    lpCommProp->dwMaxTxQueue        = 4096;
    lpCommProp->dwMaxRxQueue        = 4096;
    lpCommProp->dwMaxBaud           = BAUD_115200;
    lpCommProp->dwProvSubType       = PST_RS232;
1157
    lpCommProp->dwProvCapabilities  = PCF_DTRDSR | PCF_PARITY_CHECK | PCF_RTSCTS | PCF_TOTALTIMEOUTS | PCF_INTTIMEOUTS;
1158
    lpCommProp->dwSettableParams    = SP_BAUD | SP_DATABITS | SP_HANDSHAKING |
1159 1160 1161 1162 1163
                                      SP_PARITY | SP_PARITY_CHECK | SP_STOPBITS ;
    lpCommProp->dwSettableBaud      = BAUD_075 | BAUD_110 | BAUD_134_5 | BAUD_150 |
                BAUD_300 | BAUD_600 | BAUD_1200 | BAUD_1800 | BAUD_2400 | BAUD_4800 |
                BAUD_9600 | BAUD_19200 | BAUD_38400 | BAUD_57600 | BAUD_115200 ;
    lpCommProp->wSettableData       = DATABITS_5 | DATABITS_6 | DATABITS_7 | DATABITS_8 ;
1164
    lpCommProp->wSettableStopParity = STOPBITS_10 | STOPBITS_15 | STOPBITS_20 |
1165 1166 1167 1168
                PARITY_NONE | PARITY_ODD |PARITY_EVEN | PARITY_MARK | PARITY_SPACE;
    lpCommProp->dwCurrentTxQueue    = lpCommProp->dwMaxTxQueue;
    lpCommProp->dwCurrentRxQueue    = lpCommProp->dwMaxRxQueue;

1169 1170 1171
    return TRUE;
}

1172 1173 1174 1175 1176 1177
/***********************************************************************
 * FIXME:
 * The functionality of CommConfigDialogA, GetDefaultCommConfig and
 * SetDefaultCommConfig is implemented in a DLL (usually SERIALUI.DLL).
 * This is dependent on the type of COMM port, but since it is doubtful
 * anybody will get around to implementing support for fancy serial
1178 1179
 * ports in WINE, this is hardcoded for the time being.  The name of
 * this DLL should be stored in and read from the system registry in
1180 1181 1182
 * the hive HKEY_LOCAL_MACHINE, key
 * System\\CurrentControlSet\\Services\\Class\\Ports\\????
 * where ???? is the port number... that is determined by PNP
1183
 * The DLL should be loaded when the COMM port is opened, and closed
1184 1185
 * when the COMM port is closed. - MJM 20 June 2000
 ***********************************************************************/
1186
static const WCHAR lpszSerialUI[] = { 
1187
   's','e','r','i','a','l','u','i','.','d','l','l',0 };
1188 1189 1190


/***********************************************************************
1191
 *           CommConfigDialogA   (KERNEL32.@)
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
 *
 * Raises a dialog that allows the user to configure a comm port.
 * Fills the COMMCONFIG struct with information specified by the user.
 * This function should call a similar routine in the COMM driver...
 *
 * RETURNS
 *
 *  TRUE on success, FALSE on failure
 *  If successful, the lpCommConfig structure will contain a new
 *  configuration for the comm port, as specified by the user.
 *
 * BUGS
 *  The library with the CommConfigDialog code is never unloaded.
 * Perhaps this should be done when the comm port is closed?
 */
BOOL WINAPI CommConfigDialogA(
1208
    LPCSTR lpszDevice,         /* [in] name of communications device */
1209
    HWND hWnd,                 /* [in] parent window for the dialog */
1210 1211
    LPCOMMCONFIG lpCommConfig) /* [out] pointer to struct to fill */
{
1212 1213 1214
    LPWSTR  lpDeviceW = NULL;
    DWORD   len;
    BOOL    r;
1215

1216
    TRACE("(%s, %p, %p)\n", debugstr_a(lpszDevice), hWnd, lpCommConfig);
1217

1218 1219 1220 1221 1222 1223 1224 1225
    if (lpszDevice)
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpszDevice, -1, NULL, 0 );
        lpDeviceW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpszDevice, -1, lpDeviceW, len );
    }
    r = CommConfigDialogW(lpDeviceW, hWnd, lpCommConfig);
    HeapFree( GetProcessHeap(), 0, lpDeviceW );
1226 1227 1228 1229
    return r;
}

/***********************************************************************
1230
 *           CommConfigDialogW   (KERNEL32.@)
1231
 *
1232
 * See CommConfigDialogA.
1233 1234
 */
BOOL WINAPI CommConfigDialogW(
1235
    LPCWSTR lpszDevice,        /* [in] name of communications device */
1236
    HWND hWnd,                 /* [in] parent window for the dialog */
1237 1238
    LPCOMMCONFIG lpCommConfig) /* [out] pointer to struct to fill */
{
1239
    DWORD (WINAPI *pCommConfigDialog)(LPCWSTR, HWND, LPCOMMCONFIG);
1240
    HMODULE hConfigModule;
1241
    DWORD   res = ERROR_INVALID_PARAMETER;
1242

1243
    TRACE("(%s, %p, %p)\n", debugstr_w(lpszDevice), hWnd, lpCommConfig);
1244 1245
    hConfigModule = LoadLibraryW(lpszSerialUI);

1246
    if (hConfigModule) {
1247
        pCommConfigDialog = (void *)GetProcAddress(hConfigModule, "drvCommConfigDialogW");
1248 1249 1250 1251 1252
        if (pCommConfigDialog) {
            res = pCommConfigDialog(lpszDevice, hWnd, lpCommConfig);
        }
        FreeLibrary(hConfigModule);
    }
1253

1254 1255
    if (res) SetLastError(res);
    return (res == ERROR_SUCCESS);
1256 1257 1258
}

/***********************************************************************
1259
 *           GetCommConfig     (KERNEL32.@)
1260 1261 1262 1263 1264 1265 1266
 *
 * Fill in the COMMCONFIG structure for the comm port hFile
 *
 * RETURNS
 *
 *  TRUE on success, FALSE on failure
 *  If successful, lpCommConfig contains the comm port configuration.
Andrew Johnston's avatar
Andrew Johnston committed
1267 1268 1269
 *
 * BUGS
 *
1270 1271
 */
BOOL WINAPI GetCommConfig(
1272
    HANDLE       hFile,        /* [in] The communications device. */
1273
    LPCOMMCONFIG lpCommConfig, /* [out] The communications configuration of the device (if it fits). */
1274
    LPDWORD      lpdwSize)     /* [in/out] Initially the size of the configuration buffer/structure,
1275
                                  afterwards the number of bytes copied to the buffer or
1276 1277
                                  the needed size of the buffer. */
{
1278 1279
    BOOL r;

1280
    TRACE("(%p, %p, %p) *lpdwSize: %u\n", hFile, lpCommConfig, lpdwSize, lpdwSize ? *lpdwSize : 0 );
1281 1282 1283

    if(lpCommConfig == NULL)
        return FALSE;
1284
    r = *lpdwSize < sizeof(COMMCONFIG); /* TRUE if not enough space */
1285
    *lpdwSize = sizeof(COMMCONFIG);
1286
    if(r)
1287 1288
        return FALSE;

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    lpCommConfig->dwSize = sizeof(COMMCONFIG);
    lpCommConfig->wVersion = 1;
    lpCommConfig->wReserved = 0;
    r = GetCommState(hFile,&lpCommConfig->dcb);
    lpCommConfig->dwProviderSubType = PST_RS232;
    lpCommConfig->dwProviderOffset = 0;
    lpCommConfig->dwProviderSize = 0;

    return r;
}

/***********************************************************************
1301
 *           SetCommConfig     (KERNEL32.@)
1302
 *
Andreas Mohr's avatar
Andreas Mohr committed
1303
 *  Sets the configuration of the communications device.
Andrew Johnston's avatar
Andrew Johnston committed
1304 1305 1306 1307
 *
 * RETURNS
 *
 *  True on success, false if the handle was bad is not a communications device.
1308 1309
 */
BOOL WINAPI SetCommConfig(
1310 1311 1312
    HANDLE       hFile,		/* [in] The communications device. */
    LPCOMMCONFIG lpCommConfig,	/* [in] The desired configuration. */
    DWORD dwSize) 		/* [in] size of the lpCommConfig struct */
1313
{
1314
    TRACE("(%p, %p, %u)\n", hFile, lpCommConfig, dwSize);
Andrew Johnston's avatar
Andrew Johnston committed
1315
    return SetCommState(hFile,&lpCommConfig->dcb);
1316 1317 1318
}

/***********************************************************************
1319
 *           SetDefaultCommConfigW  (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
1320
 *
1321 1322 1323 1324 1325 1326
 * Initializes the default configuration for a communication device.
 *
 * PARAMS
 *  lpszDevice   [I] Name of the device targeted for configuration
 *  lpCommConfig [I] PTR to a buffer with the configuration for the device
 *  dwSize       [I] Number of bytes in the buffer
Andrew Johnston's avatar
Andrew Johnston committed
1327 1328
 *
 * RETURNS
1329 1330
 *  Failure: FALSE
 *  Success: TRUE, and default configuration saved
Andrew Johnston's avatar
Andrew Johnston committed
1331
 *
1332
 */
1333
BOOL WINAPI SetDefaultCommConfigW(LPCWSTR lpszDevice, LPCOMMCONFIG lpCommConfig, DWORD dwSize)
1334
{
1335
    BOOL (WINAPI *lpfnSetDefaultCommConfig)(LPCWSTR, LPCOMMCONFIG, DWORD);
1336
    HMODULE hConfigModule;
1337
    BOOL r = FALSE;
1338

1339
    TRACE("(%s, %p, %u)\n", debugstr_w(lpszDevice), lpCommConfig, dwSize);
1340

1341
    hConfigModule = LoadLibraryW(lpszSerialUI);
1342
    if(!hConfigModule)
1343
        return r;
1344

1345
    lpfnSetDefaultCommConfig = (void *)GetProcAddress(hConfigModule, "drvSetDefaultCommConfigW");
1346 1347
    if (lpfnSetDefaultCommConfig)
        r = lpfnSetDefaultCommConfig(lpszDevice, lpCommConfig, dwSize);
1348

1349
    FreeLibrary(hConfigModule);
1350 1351 1352 1353 1354 1355

    return r;
}


/***********************************************************************
1356
 *           SetDefaultCommConfigA     (KERNEL32.@)
1357
 *
1358
 * Initializes the default configuration for a communication device.
Andrew Johnston's avatar
Andrew Johnston committed
1359
 *
1360
 * See SetDefaultCommConfigW.
Andrew Johnston's avatar
Andrew Johnston committed
1361
 *
1362
 */
1363
BOOL WINAPI SetDefaultCommConfigA(LPCSTR lpszDevice, LPCOMMCONFIG lpCommConfig, DWORD dwSize)
1364
{
1365
    BOOL r;
1366 1367
    LPWSTR lpDeviceW = NULL;
    DWORD len;
1368

1369
    TRACE("(%s, %p, %u)\n", debugstr_a(lpszDevice), lpCommConfig, dwSize);
1370

1371 1372 1373 1374 1375 1376 1377
    if (lpszDevice)
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpszDevice, -1, NULL, 0 );
        lpDeviceW = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpszDevice, -1, lpDeviceW, len );
    }
    r = SetDefaultCommConfigW(lpDeviceW,lpCommConfig,dwSize);
1378
    HeapFree( GetProcessHeap(), 0, lpDeviceW );
1379 1380 1381 1382
    return r;
}


1383
/***********************************************************************
1384
 *           GetDefaultCommConfigW   (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
1385 1386 1387 1388 1389 1390 1391
 *
 *   Acquires the default configuration of the specified communication device. (unicode)
 *
 *  RETURNS
 *
 *   True on successful reading of the default configuration,
 *   if the device is not found or the buffer is too small.
1392
 */
1393 1394
BOOL WINAPI GetDefaultCommConfigW(
    LPCWSTR      lpszName, /* [in] The unicode name of the device targeted for configuration. */
1395 1396 1397 1398
    LPCOMMCONFIG lpCC,     /* [out] The default configuration for the device. */
    LPDWORD      lpdwSize) /* [in/out] Initially the size of the default configuration buffer,
                              afterwards the number of bytes copied to the buffer or
                              the needed size of the buffer. */
Andrew Johnston's avatar
Andrew Johnston committed
1399
{
1400
    DWORD (WINAPI *pGetDefaultCommConfig)(LPCWSTR, LPCOMMCONFIG, LPDWORD);
1401 1402
    HMODULE hConfigModule;
    DWORD   res = ERROR_INVALID_PARAMETER;
1403

1404 1405
    TRACE("(%s, %p, %p)  *lpdwSize: %u\n", debugstr_w(lpszName), lpCC, lpdwSize, lpdwSize ? *lpdwSize : 0 );
    hConfigModule = LoadLibraryW(lpszSerialUI);
1406

1407
    if (hConfigModule) {
1408
        pGetDefaultCommConfig = (void *)GetProcAddress(hConfigModule, "drvGetDefaultCommConfigW");
1409 1410 1411 1412 1413
        if (pGetDefaultCommConfig) {
            res = pGetDefaultCommConfig(lpszName, lpCC, lpdwSize);
        }
        FreeLibrary(hConfigModule);
    }
1414

1415 1416
    if (res) SetLastError(res);
    return (res == ERROR_SUCCESS);
1417 1418 1419
}

/**************************************************************************
1420
 *         GetDefaultCommConfigA		(KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
1421
 *
1422
 *   Acquires the default configuration of the specified communication device. (ascii)
Andrew Johnston's avatar
Andrew Johnston committed
1423 1424 1425 1426 1427
 *
 *  RETURNS
 *
 *   True on successful reading of the default configuration,
 *   if the device is not found or the buffer is too small.
1428
 */
1429 1430
BOOL WINAPI GetDefaultCommConfigA(
    LPCSTR       lpszName, /* [in] The ascii name of the device targeted for configuration. */
1431 1432 1433 1434 1435
    LPCOMMCONFIG lpCC,     /* [out] The default configuration for the device. */
    LPDWORD      lpdwSize) /* [in/out] Initially the size of the default configuration buffer,
			      afterwards the number of bytes copied to the buffer or
                              the needed size of the buffer. */
{
Andrew Johnston's avatar
Andrew Johnston committed
1436
	BOOL ret = FALSE;
1437
	UNICODE_STRING lpszNameW;
1438

1439
	TRACE("(%s, %p, %p)  *lpdwSize: %u\n", debugstr_a(lpszName), lpCC, lpdwSize, lpdwSize ? *lpdwSize : 0 );
1440 1441 1442
	if(lpszName) RtlCreateUnicodeStringFromAsciiz(&lpszNameW,lpszName);
	else lpszNameW.Buffer = NULL;

1443
	ret = GetDefaultCommConfigW(lpszNameW.Buffer,lpCC,lpdwSize);
1444 1445

	RtlFreeUnicodeString(&lpszNameW);
1446 1447
	return ret;
}