socket.c 83.5 KB
Newer Older
Danny Mayer's avatar
Danny Mayer committed
1
/*
2
 * Copyright (C) 2000, 2001  Internet Software Consortium.
Danny Mayer's avatar
Danny Mayer committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
 * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

18
/* $Id: socket.c,v 1.20 2002/08/02 03:45:56 mayer Exp $ */
Danny Mayer's avatar
Danny Mayer committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

#define MAKE_EXTERNAL 1
#include <config.h>

#include <sys/types.h>

#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_   /* Prevent inclusion of winsock.h in windows.h */
#endif

#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <io.h>
#include <fcntl.h>
36
#include <process.h>
Danny Mayer's avatar
Danny Mayer committed
37 38 39 40 41 42 43 44 45 46

#include <isc/buffer.h>
#include <isc/bufferlist.h>
#include <isc/condition.h>
#include <isc/list.h>
#include <isc/log.h>
#include <isc/mem.h>
#include <isc/msgs.h>
#include <isc/mutex.h>
#include <isc/net.h>
47
#include <isc/os.h>
Danny Mayer's avatar
Danny Mayer committed
48 49 50 51
#include <isc/platform.h>
#include <isc/print.h>
#include <isc/region.h>
#include <isc/socket.h>
52 53
#include <isc/strerror.h>
#include <isc/syslog.h>
Danny Mayer's avatar
Danny Mayer committed
54 55 56
#include <isc/task.h>
#include <isc/thread.h>
#include <isc/util.h>
57
#include <isc/win32os.h>
Danny Mayer's avatar
Danny Mayer committed
58

59
#include "errno2result.h"
60

61 62 63 64 65 66 67 68 69 70 71
/*
 * Define this macro to control the behavior of connection
 * resets on UDP sockets.  See Microsoft KnowledgeBase Article Q263823
 * for details.
 * NOTE: This requires that Windows 2000 systems install Service Pack 2
 * or later.
 */
#ifndef SIO_UDP_CONNRESET 
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12) 
#endif

Danny Mayer's avatar
Danny Mayer committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/*
 * Some systems define the socket length argument as an int, some as size_t,
 * some as socklen_t.  This is here so it can be easily changed if needed.
 */
#ifndef ISC_SOCKADDR_LEN_T
#define ISC_SOCKADDR_LEN_T unsigned int
#endif

/*
 * Define what the possible "soft" errors can be.  These are non-fatal returns
 * of various network related functions, like recv() and so on.
 *
 * For some reason, BSDI (and perhaps others) will sometimes return <0
 * from recv() but will have errno==0.  This is broken, but we have to
 * work around it here.
 */
88
#define SOFT_ERROR(e)	((e) == WSAEINTR || \
89
			 (e) == WSA_IO_PENDING || \
90
			 (e) == WSAEWOULDBLOCK || \
91 92 93
			 (e) == EWOULDBLOCK || \
			 (e) == EINTR || \
			 (e) == EAGAIN || \
Danny Mayer's avatar
Danny Mayer committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
			 (e) == 0)

#define DLVL(x) ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(x)

/*
 * DLVL(90)  --  Function entry/exit and other tracing.
 * DLVL(70)  --  Socket "correctness" -- including returning of events, etc.
 * DLVL(60)  --  Socket data send/receive
 * DLVL(50)  --  Event tracing, including receiving/sending completion events.
 * DLVL(20)  --  Socket creation/destruction.
 */
#define TRACE_LEVEL		90
#define CORRECTNESS_LEVEL	70
#define IOEVENT_LEVEL		60
#define EVENT_LEVEL		50
#define CREATION_LEVEL		20

#define TRACE		DLVL(TRACE_LEVEL)
#define CORRECTNESS	DLVL(CORRECTNESS_LEVEL)
#define IOEVENT		DLVL(IOEVENT_LEVEL)
#define EVENT		DLVL(EVENT_LEVEL)
#define CREATION	DLVL(CREATION_LEVEL)

typedef isc_event_t intev_t;

119 120
#define SOCKET_MAGIC		ISC_MAGIC('I', 'O', 'i', 'o')
#define VALID_SOCKET(t)		ISC_MAGIC_VALID(t, SOCKET_MAGIC)
Danny Mayer's avatar
Danny Mayer committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

/*
 * IPv6 control information.  If the socket is an IPv6 socket we want
 * to collect the destination address and interface so the client can
 * set them on outgoing packets.
 */
#ifdef ISC_PLATFORM_HAVEIPV6
#ifndef USE_CMSG
#define USE_CMSG	1
#endif
#endif

/*
 * NetBSD and FreeBSD can timestamp packets.  XXXMLG Should we have
 * a setsockopt() like interface to request timestamps, and if the OS
 * doesn't do it for us, call gettimeofday() on every UDP receive?
 */

/*
 * We really  don't want to try and use these control messages. Win32
 * doesn't have this mechanism
 */
#undef USE_CMSG

/*
 * Message header for recvmsg and sendmsg calls.
 * Used value-result for recvmsg, value only for sendmsg.
 */
149

Danny Mayer's avatar
Danny Mayer committed
150 151 152 153

struct msghdr {
        void	*msg_name;              /* optional address */
        u_int   msg_namelen;            /* size of address */
Danny Mayer's avatar
Danny Mayer committed
154
        WSABUF  *msg_iov;		/* scatter/gather array */
Danny Mayer's avatar
Danny Mayer committed
155 156 157 158 159
        u_int   msg_iovlen;             /* # elements in msg_iov */
        void	*msg_control;           /* ancillary data, see below */
        u_int   msg_controllen;         /* ancillary data buffer len */
        int     msg_flags;              /* flags on received message */
} msghdr;
160
	
161 162 163 164 165
/*
 * The number of times a send operation is repeated if the result is EINTR.
 */
#define NRETRIES 10

Danny Mayer's avatar
Danny Mayer committed
166 167 168 169 170 171
struct isc_socket {
	/* Not locked. */
	unsigned int		magic;
	isc_socketmgr_t	       *manager;
	isc_mutex_t		lock;
	isc_sockettype_t	type;
172 173 174 175 176 177 178
	OVERLAPPED		overlapped;
	/* Pointers to scatter/gather buffers */
	WSABUF			iov[ISC_SOCKET_MAXSCATTERGATHER];
	size_t			totalBytes;
	int			iEvent;		/* Index into Event Array */
	WSAEVENT		hEvent;		/* Event Handle */
	long			wait_type;	/* Events to wait on */
Danny Mayer's avatar
Danny Mayer committed
179 180 181 182

	/* Locked by socket lock. */
	ISC_LINK(isc_socket_t)	link;
	unsigned int		references;
183
	SOCKET			fd;
Danny Mayer's avatar
Danny Mayer committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	int			pf;

	ISC_LIST(isc_socketevent_t)		send_list;
	ISC_LIST(isc_socketevent_t)		recv_list;
	ISC_LIST(isc_socket_newconnev_t)	accept_list;
	isc_socket_connev_t		       *connect_ev;

	/*
	 * Internal events.  Posted when a descriptor is readable or
	 * writable.  These are statically allocated and never freed.
	 * They will be set to non-purgable before use.
	 */
	intev_t			readable_ev;
	intev_t			writable_ev;

	isc_sockaddr_t		address;  /* remote address */

201
	unsigned int		pending_close : 1,
Danny Mayer's avatar
Danny Mayer committed
202
				pending_accept : 1,
203 204
				iocp : 1,	/* I/O Completion Port */
				listener : 1,	/* listener socket */
Danny Mayer's avatar
Danny Mayer committed
205 206
				connected : 1,
				connecting : 1, /* connect pending */
207
				bound : 1;	/* bound to local addr */
Danny Mayer's avatar
Danny Mayer committed
208 209 210

};

211 212 213 214 215 216 217 218
/*
 * I/O Completion ports Info structures
 */

static HANDLE hHeapHandle = NULL;
static int iocp_total = 0;
typedef struct IoCompletionInfo {
	OVERLAPPED			overlapped;
219
	isc_socketevent_t		*dev;
220
	int				request_type;
221
	struct msghdr			messagehdr;
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
} IoCompletionInfo;

/*
 * Define a maximum number of I/O Completion Port worker threads
 * to handle the load on the Completion Port
 */
#define MAX_IOCPTHREADS 20

/*
 * event_change structure to handle adds and deletes from the list of
 * events in the Wait
 */
typedef struct event_change event_change_t;

struct event_change {
	isc_socket_t			*sock;
	int				iEvent;
	SOCKET				fd;
	unsigned int			action;
	ISC_LINK(event_change_t)	link;
};

/*
 * Note: We are using an array here since *WaitForMultiple* wants an array
 */

#define MAX_EVENTS 64

/*
 * List of events being waited on and their associated sockets
 */
typedef struct sock_event_list {
	int max_event;
	int total_events;
	isc_socket_t			*aSockList[MAX_EVENTS];
	WSAEVENT			aEventList[MAX_EVENTS];
	isc_mutex_t			EventLock;
	ISC_LIST(event_change_t)	event_updates;
} sock_event_list;

262 263 264
#define SOCKET_MANAGER_MAGIC	ISC_MAGIC('I', 'O', 'm', 'g')
#define VALID_MANAGER(m)	ISC_MAGIC_VALID(m, SOCKET_MANAGER_MAGIC)

Danny Mayer's avatar
Danny Mayer committed
265 266 267 268 269 270 271
struct isc_socketmgr {
	/* Not locked. */
	unsigned int		magic;
	isc_mem_t	       *mctx;
	isc_mutex_t		lock;
	/* Locked by manager lock. */
	ISC_LIST(isc_socket_t)	socklist;
272 273 274
	sock_event_list		sockev_list;
	int			event_written;
	isc_boolean_t		bShutdown;
Danny Mayer's avatar
Danny Mayer committed
275 276
	isc_thread_t		watcher;
	isc_condition_t		shutdown_ok;
277 278 279 280
	HANDLE			hIoCompletionPort;
	int			maxIOCPThreads;
	HANDLE			hIOCPThreads[MAX_IOCPTHREADS];
	DWORD			dwIOCPThreadIds[MAX_IOCPTHREADS];
Danny Mayer's avatar
Danny Mayer committed
281 282 283 284 285 286 287 288 289 290
};

#define CLOSED		0	/* this one must be zero */
#define MANAGED		1
#define CLOSE_PENDING	2

/*
 * send() and recv() iovec counts
 */
#define MAXSCATTERGATHER_SEND	(ISC_SOCKET_MAXSCATTERGATHER)
291
#define MAXSCATTERGATHER_RECV	(ISC_SOCKET_MAXSCATTERGATHER)
Danny Mayer's avatar
Danny Mayer committed
292

293
static isc_threadresult_t WINAPI SocketIoThread(LPVOID ThreadContext);
Danny Mayer's avatar
Danny Mayer committed
294 295
static void free_socket(isc_socket_t **);

296 297 298 299 300 301 302 303 304 305 306 307
enum {
	SOCKET_CANCEL,
	SOCKET_SHUTDOWN,
	SOCKET_RECV,
	SOCKET_SEND,
	SOCK_ACCEPT
};

enum {
	EVENT_ADD,
	EVENT_DELETE
};
Danny Mayer's avatar
Danny Mayer committed
308 309 310

#define SOCK_DEAD(s)			((s)->references == 0)

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

#if defined(ISC_SOCKET_DEBUG)
/*
 * This is used to duump the contents of the sock structure
 * You should make sure that the sock is locked before
 * dumping it. Since the code uses simple printf() statements
 * it should only be used interactively.
 */
void
sock_dump(isc_socket_t *sock) {
	isc_socketevent_t *ldev;
	isc_socket_newconnev_t *ndev;
	isc_sockaddr_t addr;
	char socktext[256];


	isc_socket_getpeername(sock, &addr);
	isc_sockaddr_format(&addr, socktext, sizeof(socktext));
	printf("Remote Socket: %s\n", socktext);
	isc_socket_getsockname(sock, &addr);
	isc_sockaddr_format(&addr, socktext, sizeof(socktext));
	printf("This Socket: %s\n", socktext);

	printf("\n\t\tSock Dump\n");
	printf("\t\tfd: %u\n", sock->fd);
	printf("\t\treferences: %d\n", sock->references);
	printf("\t\tpending_accept: %d\n", sock->pending_accept);
	printf("\t\tpending_close: %d\n", sock->pending_close);
	printf("\t\tconnecting: %d\n", sock->connecting);
	printf("\t\tconnected: %d\n", sock->connected);
	printf("\t\tbound: %d\n", sock->bound);
	printf("\t\tiocp: %d\n", sock->iocp);
	printf("\t\tsocket type: %d\n", sock->type);

	printf("\n\t\tSock Recv List\n");
	ldev = ISC_LIST_HEAD(sock->recv_list);
	while (ldev != NULL) {
		printf("\t\tdev: %p\n", ldev);
		ldev = ISC_LIST_NEXT(ldev, ev_link);
	}
	printf("\n\t\tSock Send List\n");
	ldev = ISC_LIST_HEAD(sock->send_list);
	while (ldev != NULL) {
		printf("\t\tdev: %p\n", ldev);
		ldev = ISC_LIST_NEXT(ldev, ev_link);
	}
	printf("\n\t\tSock Accept List\n");
	ndev = ISC_LIST_HEAD(sock->accept_list);
	while (ndev != NULL) {
		printf("\t\tdev: %p\n", ldev);
		ndev = ISC_LIST_NEXT(ndev, ev_link);
	}
}
#endif

/*  This function will add an entry to the I/O completion port
 *  that will signal the I/O thread to exit (gracefully)
 */
static void
signal_iocompletionport_exit(isc_socketmgr_t *manager) {
	int i;
	int errval;
	char strbuf[ISC_STRERRORSIZE];

	for (i = 0; i < manager->maxIOCPThreads; i++) {
		if (!PostQueuedCompletionStatus(manager->hIoCompletionPort, 0, 0, 0)) {
			errval = GetLastError();
			isc__strerror(errval, strbuf, sizeof(strbuf));
			FATAL_ERROR(__FILE__, __LINE__,
				isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
				ISC_MSG_FAILED,
				"Can't request service thread to exit: %s"),
				strbuf);
		}
	}
}

/*
 * Create the worker threads for the I/O Completion Port
 */
void
iocompletionport_createthreads(int total_threads, isc_socketmgr_t *manager) {
	int errval;
	char strbuf[ISC_STRERRORSIZE];
	int i = 0;

	/*
	 * We need at least one
	 */
	for (i = 0; i < total_threads; i++) {
		manager->hIOCPThreads[i] = CreateThread( NULL, 0, SocketIoThread,
						manager, 0,
						&manager->dwIOCPThreadIds[i]);
		if(manager->hIOCPThreads[i] == NULL) {
			errval = GetLastError();
			isc__strerror(errval, strbuf, sizeof(strbuf));
			FATAL_ERROR(__FILE__, __LINE__,
				isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
				ISC_MSG_FAILED,
				"Can't create IOCP thread: %s"),
				strbuf);
		}
	}
}

416
/*
417
 *  Create/initialise the I/O completion port
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
void
iocompletionport_init(isc_socketmgr_t *manager) {
	int errval;
	char strbuf[ISC_STRERRORSIZE];
	/*
	 * Create a private heap to handle the socket overlapped structure
	 * The miniumum number of structures is 10, there is no maximum
	 */
	hHeapHandle = HeapCreate(0, 10*sizeof(IoCompletionInfo), 0);
	manager->maxIOCPThreads = min(isc_os_ncpus() + 1,
					MAX_IOCPTHREADS);

	/* Now Create the Completion Port */
	manager->hIoCompletionPort = CreateIoCompletionPort(
				     INVALID_HANDLE_VALUE, NULL,
				     0, manager->maxIOCPThreads);
	if (manager->hIoCompletionPort == NULL) {
		errval = GetLastError();
		isc__strerror(errval, strbuf, sizeof(strbuf));
		FATAL_ERROR(__FILE__, __LINE__,
				isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
				ISC_MSG_FAILED,
				"CreateIoCompletionPort() failed "
				"during initialization: %s"),
				strbuf);
		exit(1);
	}
	
	/*
	 * Worker threads for servicing the I/O
 	 */
	iocompletionport_createthreads(manager->maxIOCPThreads, manager);
}
	
453

454 455 456 457 458 459 460 461
void
iocompletionport_exit(isc_socketmgr_t *manager) {
	if (manager->hIoCompletionPort != NULL) {
		/*  Get each of the service threads to exit
		*/
		signal_iocompletionport_exit(manager);
	}
}
462

463 464 465
/*
 * Add sockets in here and pass the sock data in as part of the information needed
 */
466
void
467
iocompletionport_update(isc_socket_t *sock) {
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
	HANDLE hiocp;
	if(sock->iocp == 0) {
		sock->iocp = 1;
		hiocp = CreateIoCompletionPort((HANDLE) sock->fd,
			sock->manager->hIoCompletionPort, (DWORD) sock,
			sock->manager->maxIOCPThreads);
		InterlockedIncrement(&iocp_total);

	}
}

void
socket_event_minit(sock_event_list *evlist) {
	BOOL bReset;
	int i;

	/* Initialize the Event List */
	evlist->max_event = 0;
	evlist->total_events = 0;
	for (i = 0; i < MAX_EVENTS; i++) {
		evlist->aSockList[i] = NULL;
		evlist->aEventList[i] = (WSAEVENT) 0;
	}

	/*
	 * initialize the lock
	 */
	if (isc_mutex_init(&(evlist->EventLock)) != ISC_R_SUCCESS) {
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "isc_mutex_init() %s Event Lock",
				 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
						ISC_MSG_FAILED, "failed"));
	}
	evlist->aEventList[0] = WSACreateEvent();
	(evlist->max_event)++;
	bReset = WSAResetEvent(evlist->aEventList[0]);

	ISC_LIST_INIT(evlist->event_updates);
}

/*
 * Note that the eventLock is already locked before calling this function
 */
isc_result_t
socket_eventlist_add(isc_socket_t *sock, sock_event_list *evlist) {
	int max_event;

	REQUIRE(sock != NULL);
	REQUIRE(sock->hEvent != NULL);
	REQUIRE(evlist != NULL);

	max_event = evlist->max_event;
	if(max_event >= MAX_EVENTS) {
		return(ISC_R_NOSPACE);
	}

	sock->iEvent = max_event;
	evlist->aSockList[max_event] = sock;
	evlist->aEventList[max_event] = sock->hEvent;
	evlist->max_event++;
	evlist->total_events++;
	return (ISC_R_SUCCESS);
}
/*
 * Note that the eventLock is locked before calling this function
 * All Events and associated sockets are closed here
 */
void
socket_eventlist_delete(isc_socket_t *sock, SOCKET fd, int iEvent,
			sock_event_list *evlist) {
	int i;
	WSAEVENT hEvent;

	REQUIRE(evlist != NULL);
	REQUIRE(iEvent > 0);

	hEvent = evlist->aEventList[iEvent];
	if (hEvent != NULL)
		WSACloseEvent(hEvent);


	for(i = iEvent; i < evlist->max_event; i++) {
		evlist->aEventList[i] = evlist->aEventList[i + 1];
		evlist->aSockList[i] = evlist->aSockList[i + 1];
		if(evlist->aSockList[i] != NULL)
			evlist->aSockList[i]->iEvent = i;
	}
	evlist->aEventList[evlist->max_event] = 0;
	evlist->aSockList[evlist->max_event] = NULL;
	if(sock != NULL) {
		sock->iEvent = 0;
		sock->pending_close = 1;
	}
	if (fd >= 0)
		closesocket(fd);
	evlist->max_event--;
	evlist->total_events--;
566 567

}
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
/*
 * Get the event changes off of the list and apply the
 * requested changes
 */
isc_result_t
process_eventlist(sock_event_list *evlist, isc_socketmgr_t *manager) {
	event_change_t *evchange;

	evchange = ISC_LIST_HEAD(evlist->event_updates);
	while (evchange != NULL) {
		switch (evchange->action) {
		case EVENT_ADD: 
			socket_eventlist_add(evchange->sock, evlist);
			break;
		case EVENT_DELETE: 
			socket_eventlist_delete(evchange->sock, evchange->fd,
						evchange->iEvent, evlist);
			break;
		default:
			break;
		}

		ISC_LIST_DEQUEUE(evlist->event_updates, evchange, link);
		HeapFree(hHeapHandle, 0, evchange);
		manager->event_written--;
		evchange = ISC_LIST_HEAD(evlist->event_updates);
	}
	manager->event_written = 0;
	return (ISC_R_SUCCESS);
}
/*
 * Add the event list changes to the queue and notify the
 * event loop
 */
static void
notify_eventlist(isc_socket_t *sock, sock_event_list *evlist,
		 unsigned int action) {

	event_change_t *evchange;
	
	evchange = HeapAlloc(hHeapHandle, HEAP_ZERO_MEMORY,
			     sizeof(event_change_t));
	evchange->sock = sock;
	evchange->action = action;
	evchange->iEvent = sock->iEvent;
	evchange->fd = sock->fd;

	LOCK(&evlist->EventLock);
	ISC_LIST_APPEND(evlist->event_updates, evchange, link);

	sock->manager->event_written++;
	UNLOCK(&evlist->EventLock);
	WSASetEvent(evlist->aEventList[0]);	/* Alert the Wait List */
}
/*
 * Note that the socket is already locked before calling this function
 */
isc_result_t
socket_event_add(isc_socket_t *sock, long type) {
	int stat;
	WSAEVENT hEvent;
	sock_event_list *evlist;

	REQUIRE(sock != NULL);
	evlist = &(sock->manager->sockev_list);
633

634 635 636 637 638 639 640 641 642 643 644
	hEvent = WSACreateEvent();
	if (hEvent == WSA_INVALID_EVENT) {
		stat = WSAGetLastError();
		return (ISC_R_UNEXPECTED);
	}
	if (WSAEventSelect(sock->fd, hEvent, type) != 0) {
		stat = WSAGetLastError();
		WSACloseEvent(hEvent);
		return (ISC_R_UNEXPECTED);
	}
	sock->hEvent = hEvent;
645

646 647 648 649
	sock->wait_type = type;
	notify_eventlist(sock, evlist, EVENT_ADD);
	return (ISC_R_SUCCESS);
}
Danny Mayer's avatar
Danny Mayer committed
650
/*
651
 * Note that the socket is not locked before calling this function
Danny Mayer's avatar
Danny Mayer committed
652
 */
653 654 655 656 657 658 659
void
socket_event_delete(isc_socket_t *sock) {
	sock_event_list *evlist;

	REQUIRE(sock != NULL);
	REQUIRE(sock->hEvent != NULL);
	evlist = &(sock->manager->sockev_list);
Danny Mayer's avatar
Danny Mayer committed
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
	if (sock->hEvent != NULL) {
		sock->wait_type = 0;
		sock->pending_close = 1;
		notify_eventlist(sock, evlist, EVENT_DELETE);
		sock->hEvent = NULL;
	}

}
/*
 * Routine to cleanup and then close the socket.
 * Only close the socket here if it is NOT associated
 * with an event, otherwise the WSAWaitForMultipleEvents
 * may fail due to the fact that the the Wait should not
 * be running while closing an event or a socket.
 */
void
socket_close(isc_socket_t *sock) {
	sock->pending_close = 1;
	if (sock->hEvent != NULL)
		socket_event_delete(sock);
	else {
		closesocket(sock->fd);
	}
	if (sock->iocp) {
		sock->iocp = 0;
		InterlockedDecrement(&iocp_total);
	}

}
Danny Mayer's avatar
Danny Mayer committed
690 691 692
/*
 * Initialize socket services
 */
Andreas Gustafsson's avatar
Andreas Gustafsson committed
693
BOOL InitSockets() {
Danny Mayer's avatar
Danny Mayer committed
694 695 696 697 698 699 700 701
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	/* Need Winsock 2.0 or better */
	wVersionRequested = MAKEWORD(2, 0);
 
	err = WSAStartup(wVersionRequested, &wsaData);
Andreas Gustafsson's avatar
Andreas Gustafsson committed
702
	if ( err != 0 ) {
Danny Mayer's avatar
Danny Mayer committed
703
		/* Tell the user that we could not find a usable Winsock DLL */
704 705 706
		NTReportError("named",
			"Application Requires Winsock 2.0 or later. Exiting");
		return(FALSE);
Danny Mayer's avatar
Danny Mayer committed
707
	}
708
	return(TRUE);
Danny Mayer's avatar
Danny Mayer committed
709 710
}

Andreas Gustafsson's avatar
Andreas Gustafsson committed
711
int
712 713
internal_sendmsg(isc_socket_t *sock, IoCompletionInfo *lpo,
		 struct msghdr *messagehdr, int flags, int *Error) {
714
	int Result;
Danny Mayer's avatar
Danny Mayer committed
715 716
	DWORD BytesSent;
	DWORD Flags = flags;
717 718 719 720
	int total_sent;

	*Error = 0;
	Result = WSASendTo((SOCKET) sock->fd, 
721 722
			messagehdr->msg_iov, 
			messagehdr->msg_iovlen, 
723 724
			&BytesSent,
			Flags,
725 726
			messagehdr->msg_name,
			messagehdr->msg_namelen,
727 728 729 730
			(LPOVERLAPPED) lpo,
			NULL);

	total_sent = (int) BytesSent;
Danny Mayer's avatar
Danny Mayer committed
731
    
732 733 734 735 736 737
	/* Check for errors.*/
	if (Result == SOCKET_ERROR) {

		*Error = WSAGetLastError();
        
	        switch (*Error) {
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
			case NO_ERROR :
			case WSA_IO_INCOMPLETE :
			case WSA_WAIT_IO_COMPLETION :
			case WSA_IO_PENDING :
				break ;

			default :
				return (-1);
				break;
			}
	}
	if(lpo != NULL)
		return (0);
	else
		return (total_sent);
Danny Mayer's avatar
Danny Mayer committed
754 755 756
}

int
757 758
internal_recvmsg(isc_socket_t *sock, IoCompletionInfo *lpo,
		 struct msghdr *messagehdr, int flags, int *Error) {
759 760 761
	DWORD Flags = 0;
	DWORD NumBytes = 0;
	int total_bytes = 0;
Danny Mayer's avatar
Danny Mayer committed
762
	int Result;
Andreas Gustafsson's avatar
Andreas Gustafsson committed
763

764 765
	*Error = 0;
	Result = WSARecvFrom((SOCKET) sock->fd,
766 767
			messagehdr->msg_iov,
			messagehdr->msg_iovlen,
768 769
			&NumBytes,
			&Flags,
770 771
			messagehdr->msg_name,
			(int *)&(messagehdr->msg_namelen),
772 773
			(LPOVERLAPPED) lpo,
			NULL);
Andreas Gustafsson's avatar
Andreas Gustafsson committed
774

775
	total_bytes = (int) NumBytes;
Andreas Gustafsson's avatar
Andreas Gustafsson committed
776 777 778

	/* Check for errors. */
	if (Result == SOCKET_ERROR) {
779 780

		*Error = WSAGetLastError();
Danny Mayer's avatar
Danny Mayer committed
781
        
782
	        switch (*Error) {
Danny Mayer's avatar
Danny Mayer committed
783

784 785 786 787 788 789 790 791 792 793
			case NO_ERROR :
			case WSA_IO_INCOMPLETE :
			case WSA_WAIT_IO_COMPLETION :
			case WSA_IO_PENDING :
					break ;

			default :
					return (-1);
					break;
			}
Danny Mayer's avatar
Danny Mayer committed
794
	}
795
	/* Return the flags received in header */
796
	messagehdr->msg_flags = Flags;
797 798 799 800 801 802
	if(lpo != NULL)
		return (-1);
	else
		return (total_bytes);

} 
Danny Mayer's avatar
Danny Mayer committed
803 804 805 806

static void
manager_log(isc_socketmgr_t *sockmgr,
	    isc_logcategory_t *category, isc_logmodule_t *module, int level,
807
	    const char *fmt, ...) {
Danny Mayer's avatar
Danny Mayer committed
808 809 810
	char msgbuf[2048];
	va_list ap;

811
	if (!isc_log_wouldlog(isc_lctx, level))
Danny Mayer's avatar
Danny Mayer committed
812 813 814 815 816 817 818 819 820 821
		return;

	va_start(ap, fmt);
	vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
	va_end(ap);

	isc_log_write(isc_lctx, category, module, level,
		      "sockmgr %p: %s", sockmgr, msgbuf);
}

822 823 824 825 826
static void
socket_log(isc_socket_t *sock, isc_sockaddr_t *address,
	   isc_logcategory_t *category, isc_logmodule_t *module, int level,
	   isc_msgcat_t *msgcat, int msgset, int message,
	   const char *fmt, ...) ISC_FORMAT_PRINTF(9, 10);
Danny Mayer's avatar
Danny Mayer committed
827 828 829 830
static void
socket_log(isc_socket_t *sock, isc_sockaddr_t *address,
	   isc_logcategory_t *category, isc_logmodule_t *module, int level,
	   isc_msgcat_t *msgcat, int msgset, int message,
831
	   const char *fmt, ...) {
Danny Mayer's avatar
Danny Mayer committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
	char msgbuf[2048];
	char peerbuf[256];
	va_list ap;

	if (! isc_log_wouldlog(isc_lctx, level))
		return;

	va_start(ap, fmt);
	vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
	va_end(ap);

	if (address == NULL) {
		isc_log_iwrite(isc_lctx, category, module, level,
			       msgcat, msgset, message,
			       "socket %p: %s", sock, msgbuf);
847 848 849 850 851
	} else {
		isc_sockaddr_format(address, peerbuf, sizeof peerbuf);
		isc_log_iwrite(isc_lctx, category, module, level,
			       msgcat, msgset, message,
			       "socket %p %s: %s", sock, peerbuf, msgbuf);
Danny Mayer's avatar
Danny Mayer committed
852 853
	}
}
854

Danny Mayer's avatar
Danny Mayer committed
855
/*
856
 * Make an fd SOCKET non-blocking.
Danny Mayer's avatar
Danny Mayer committed
857 858
 */
static isc_result_t
859
make_nonblock(SOCKET fd) {
Danny Mayer's avatar
Danny Mayer committed
860 861
	int ret;
	unsigned long flags = 1;
862
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
863 864

	/* Set the socket to non-blocking */
865
	ret = ioctlsocket(fd, FIONBIO, &flags);
Danny Mayer's avatar
Danny Mayer committed
866 867

	if (ret == -1) {
868
		isc__strerror(errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
869 870
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "ioctlsocket(%d, FIOBIO, %d): %s",
871
				 fd, flags, strbuf);
Danny Mayer's avatar
Danny Mayer committed
872 873 874 875 876 877 878

		return (ISC_R_UNEXPECTED);
	}

	return (ISC_R_SUCCESS);
}
/*
879 880 881 882 883 884 885 886
 * Windows 2000 systems incorrectly cause UDP sockets using WASRecvFrom
 * to not work correctly, returning a WSACONNRESET error when a WSASendTo
 * fails with an "ICMP port unreachable" response and preventing the
 * socket from using the WSARecvFrom in subsequent operations.
 * The function below fixes this, but requires that Windows 2000
 * Service Pack 2 or later be installed on the system.  NT 4.0
 * systems are not affected by this and work correctly.
 * See Microsoft Knowledge Base Article Q263823 for details of this.
Danny Mayer's avatar
Danny Mayer committed
887
 */
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
isc_result_t
connection_reset_fix(SOCKET fd) {
	DWORD dwBytesReturned = 0;
	BOOL  bNewBehavior = FALSE;
	DWORD status;

	if(isc_win32os_majorversion() < 5)
		return (ISC_R_SUCCESS); /*  NT 4.0 has no problem */

	/* disable new behavior using IOCTL: SIO_UDP_CONNRESET */
	status = WSAIoctl(fd, SIO_UDP_CONNRESET, &bNewBehavior,
			  sizeof(bNewBehavior), NULL, 0,
			  &dwBytesReturned, NULL, NULL);
	if (status != SOCKET_ERROR)
		return (ISC_R_SUCCESS);
	else
		return (ISC_R_UNEXPECTED);
Danny Mayer's avatar
Danny Mayer committed
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
}

/*
 * Construct an iov array and attach it to the msghdr passed in.  This is
 * the SEND constructor, which will use the used region of the buffer
 * (if using a buffer list) or will use the internal region (if a single
 * buffer I/O is requested).
 *
 * Nothing can be NULL, and the done event must list at least one buffer
 * on the buffer linked list for this function to be meaningful.
 *
 * If write_countp != NULL, *write_countp will hold the number of bytes
 * this transaction can send.
 */
static void
build_msghdr_send(isc_socket_t *sock, isc_socketevent_t *dev,
		  struct msghdr *msg, char *cmsg,
922
		  WSABUF *iov, size_t *write_countp) {
Danny Mayer's avatar
Danny Mayer committed
923 924 925 926 927 928
	unsigned int iovcount;
	isc_buffer_t *buffer;
	isc_region_t used;
	size_t write_count;
	size_t skip_count;

929
	memset(msg, 0, sizeof (*msg));
Danny Mayer's avatar
Danny Mayer committed
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

	if (sock->type == isc_sockettype_udp) {
		msg->msg_name = (void *)&dev->address.type.sa;
		msg->msg_namelen = dev->address.length;
	} else {
		msg->msg_name = NULL;
		msg->msg_namelen = 0;
	}

	buffer = ISC_LIST_HEAD(dev->bufferlist);
	write_count = 0;
	iovcount = 0;

	/*
	 * Single buffer I/O?  Skip what we've done so far in this region.
	 */
	if (buffer == NULL) {
		write_count = dev->region.length - dev->n;
		iov[0].buf = (void *)(dev->region.base + dev->n);
		iov[0].len = write_count;
		iovcount = 1;

		goto config;
	}

	/*
	 * Multibuffer I/O.
	 * Skip the data in the buffer list that we have already written.
	 */
	skip_count = dev->n;
	while (buffer != NULL) {
		REQUIRE(ISC_BUFFER_VALID(buffer));
		if (skip_count < isc_buffer_usedlength(buffer))
			break;
		skip_count -= isc_buffer_usedlength(buffer);
		buffer = ISC_LIST_NEXT(buffer, link);
	}

	while (buffer != NULL) {
		INSIST(iovcount < MAXSCATTERGATHER_SEND);

		isc_buffer_usedregion(buffer, &used);

		if (used.length > 0) {
			iov[iovcount].buf = (void *)(used.base
975
							  + skip_count);
Danny Mayer's avatar
Danny Mayer committed
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
			iov[iovcount].len = used.length - skip_count;
			write_count += (used.length - skip_count);
			skip_count = 0;
			iovcount++;
		}
		buffer = ISC_LIST_NEXT(buffer, link);
	}

	INSIST(skip_count == 0);

 config:
	msg->msg_iov = iov;
	msg->msg_iovlen = iovcount;

	if (write_countp != NULL)
		*write_countp = write_count;
}

/*
 * Construct an iov array and attach it to the msghdr passed in.  This is
 * the RECV constructor, which will use the available region of the buffer
 * (if using a buffer list) or will use the internal region (if a single
 * buffer I/O is requested).
 *
 * Nothing can be NULL, and the done event must list at least one buffer
 * on the buffer linked list for this function to be meaningful.
 *
 * If read_countp != NULL, *read_countp will hold the number of bytes
 * this transaction can receive.
 */
static void
build_msghdr_recv(isc_socket_t *sock, isc_socketevent_t *dev,
		  struct msghdr *msg, char *cmsg,
1009
		  WSABUF *iov, size_t *read_countp) {
Danny Mayer's avatar
Danny Mayer committed
1010 1011 1012 1013 1014
	unsigned int iovcount;
	isc_buffer_t *buffer;
	isc_region_t available;
	size_t read_count;

1015
	memset(msg, 0, sizeof (struct msghdr));
Danny Mayer's avatar
Danny Mayer committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

	if (sock->type == isc_sockettype_udp) {
		memset(&dev->address, 0, sizeof(dev->address));
		msg->msg_name = (void *)&dev->address.type.sa;
		msg->msg_namelen = sizeof(dev->address.type);
	} else { /* TCP */
		msg->msg_name = NULL;
		msg->msg_namelen = 0;
		dev->address = sock->address;
	}

	buffer = ISC_LIST_HEAD(dev->bufferlist);
	read_count = 0;

	/*
	 * Single buffer I/O?  Skip what we've done so far in this region.
	 */
	if (buffer == NULL) {
		read_count = dev->region.length - dev->n;
		iov[0].buf = (void *)(dev->region.base + dev->n);
		iov[0].len = read_count;
		iovcount = 1;
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1038
	} else {
1039 1040 1041 1042
	/*
	 * Multibuffer I/O.
	 * Skip empty buffers.
	 */
Danny Mayer's avatar
Danny Mayer committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
		while (buffer != NULL) {
			REQUIRE(ISC_BUFFER_VALID(buffer));
			if (isc_buffer_availablelength(buffer) != 0)
				break;
			buffer = ISC_LIST_NEXT(buffer, link);
		}

		iovcount = 0;
		while (buffer != NULL) {
			INSIST(iovcount < MAXSCATTERGATHER_RECV);

			isc_buffer_availableregion(buffer, &available);

			if (available.length > 0) {
				iov[iovcount].buf = (void *)(available.base);
				iov[iovcount].len = available.length;
				read_count += available.length;
				iovcount++;
			}
			buffer = ISC_LIST_NEXT(buffer, link);
		}
	}

	/*
	 * If needed, set up to receive that one extra byte.  Note that
	 * we know there is at least one iov left, since we stole it
	 * at the top of this function.
	 */

	msg->msg_iov = iov;
	msg->msg_iovlen = iovcount;

	if (read_countp != NULL)
		*read_countp = read_count;
}

static void
set_dev_address(isc_sockaddr_t *address, isc_socket_t *sock,
1081
		isc_socketevent_t *dev) {
Danny Mayer's avatar
Danny Mayer committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	if (sock->type == isc_sockettype_udp) {
		if (address != NULL)
			dev->address = *address;
		else
			dev->address = sock->address;
	} else if (sock->type == isc_sockettype_tcp) {
		INSIST(address == NULL);
		dev->address = sock->address;
	}
}

static isc_socketevent_t *
allocate_socketevent(isc_socket_t *sock, isc_eventtype_t eventtype,
1095
		     isc_taskaction_t action, const void *arg) {
Danny Mayer's avatar
Danny Mayer committed
1096 1097 1098 1099 1100
	isc_socketevent_t *ev;

	ev = (isc_socketevent_t *)isc_event_allocate(sock->manager->mctx,
						     sock, eventtype,
						     action, arg,
1101
						     sizeof (*ev));
Danny Mayer's avatar
Danny Mayer committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

	if (ev == NULL)
		return (NULL);

	ev->result = ISC_R_UNEXPECTED;
	ISC_LINK_INIT(ev, ev_link);
	ISC_LIST_INIT(ev->bufferlist);
	ev->region.base = NULL;
	ev->n = 0;
	ev->offset = 0;
	ev->attributes = 0;

	return (ev);
}

#if defined(ISC_SOCKET_DEBUG)
static void
dump_msg(struct msghdr *msg, isc_socket_t *sock) {
	unsigned int i;

1122
	printf("MSGHDR %p, Socket #: %u\n", msg, sock->fd);
Danny Mayer's avatar
Danny Mayer committed
1123 1124
	printf("\tname %p, namelen %d\n", msg->msg_name, msg->msg_namelen);
	printf("\tiov %p, iovlen %d\n", msg->msg_iov, msg->msg_iovlen);
1125
	for (i = 0 ; i < (unsigned int)msg->msg_iovlen ; i++)
Danny Mayer's avatar
Danny Mayer committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
		printf("\t\t%d\tbase %p, len %d\n", i,
		       msg->msg_iov[i].buf,
		       msg->msg_iov[i].len);
}
#endif

#define DOIO_SUCCESS		0	/* i/o ok, event sent */
#define DOIO_SOFT		1	/* i/o ok, soft error, no event sent */
#define DOIO_HARD		2	/* i/o error, event sent */
#define DOIO_EOF		3	/* EOF, no event sent */

static int
1138 1139
completeio_recv(isc_socket_t *sock, isc_socketevent_t *dev,
		struct msghdr *messagehdr, int cc, int recv_errno) {
Danny Mayer's avatar
Danny Mayer committed
1140 1141 1142 1143
	size_t actual_count;
	isc_buffer_t *buffer;

#define SOFT_OR_HARD(_system, _isc) \
1144
	if (recv_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1145 1146 1147 1148 1149 1150
		if (sock->connected) { \
			dev->result = _isc; \
			return (DOIO_HARD); \
		} \
		return (DOIO_SOFT); \
	}
1151

Danny Mayer's avatar
Danny Mayer committed
1152
#define ALWAYS_HARD(_system, _isc) \
1153
	if (recv_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1154 1155 1156 1157
		dev->result = _isc; \
		return (DOIO_HARD); \
	}

1158 1159 1160 1161 1162
	if (recv_errno != 0) {

		if (SOFT_ERROR(recv_errno))
			return (DOIO_SOFT);

1163 1164 1165 1166 1167
		SOFT_OR_HARD(WSAECONNREFUSED, ISC_R_CONNREFUSED);
		SOFT_OR_HARD(WSAENETUNREACH, ISC_R_NETUNREACH);
		SOFT_OR_HARD(WSAEHOSTUNREACH, ISC_R_HOSTUNREACH);
		SOFT_OR_HARD(WSAECONNRESET, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETRESET, ISC_R_CONNECTIONRESET);
1168
		SOFT_OR_HARD(WSAECONNABORTED, ISC_R_CONNECTIONRESET);
1169 1170
		SOFT_OR_HARD(WSAEDISCON, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETDOWN, ISC_R_NETDOWN);
1171 1172 1173 1174
		ALWAYS_HARD(ERROR_OPERATION_ABORTED, ISC_R_CONNECTIONRESET);
		ALWAYS_HARD(ERROR_PORT_UNREACHABLE, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(ERROR_HOST_UNREACHABLE, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(ERROR_NETWORK_UNREACHABLE, ISC_R_NETUNREACH);
1175
		ALWAYS_HARD(WSAENOBUFS, ISC_R_NORESOURCES);
Danny Mayer's avatar
Danny Mayer committed
1176 1177 1178 1179

#undef SOFT_OR_HARD
#undef ALWAYS_HARD

1180
		dev->result = isc__errno2result(recv_errno);
Danny Mayer's avatar
Danny Mayer committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
		return (DOIO_HARD);
	}

	/*
	 * On TCP, zero length reads indicate EOF, while on
	 * UDP, zero length reads are perfectly valid, although
	 * strange.
	 */
	if ((sock->type == isc_sockettype_tcp) && (cc == 0))
		return (DOIO_EOF);

1192
	if (sock->type == isc_sockettype_udp) {
1193
		dev->address.length = messagehdr->msg_namelen;
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
		if (isc_sockaddr_getport(&dev->address) == 0) {
			if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
				socket_log(sock, &dev->address, IOEVENT,
					   isc_msgcat, ISC_MSGSET_SOCKET,
					   ISC_MSG_ZEROPORT, 
					   "dropping source port zero packet");
			}
			return (DOIO_SOFT);
		}
	}
Danny Mayer's avatar
Danny Mayer committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

	socket_log(sock, &dev->address, IOEVENT,
		   isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PKTRECV,
		   "packet received correctly");

	/*
	 * Overflow bit detection.  If we received MORE bytes than we should,
	 * this indicates an overflow situation.  Set the flag in the
	 * dev entry and adjust how much we read by one.
	 */
#ifdef ISC_NET_RECVOVERFLOW
	if ((sock->type == isc_sockettype_udp) && ((size_t)cc > read_count)) {
		dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
		cc--;
	}
#endif

	/*
	 * update the buffers (if any) and the i/o count
	 */
	dev->n += cc;
	actual_count = cc;
	buffer = ISC_LIST_HEAD(dev->bufferlist);
	while (buffer != NULL && actual_count > 0) {
		REQUIRE(ISC_BUFFER_VALID(buffer));
		if (isc_buffer_availablelength(buffer) <= actual_count) {
			actual_count -= isc_buffer_availablelength(buffer);
			isc_buffer_add(buffer,
				       isc_buffer_availablelength(buffer));
		} else {
			isc_buffer_add(buffer, actual_count);
			actual_count = 0;
			break;
		}
		buffer = ISC_LIST_NEXT(buffer, link);
		if (buffer == NULL) {
			INSIST(actual_count == 0);
		}
	}

	/*
	 * If we read less than we expected, update counters,
	 * and let the upper layer poke the descriptor.
	 */
1248
	if (((size_t)cc != sock->totalBytes) && (dev->n < dev->minimum))
Danny Mayer's avatar
Danny Mayer committed
1249 1250 1251 1252 1253 1254 1255 1256
		return (DOIO_SOFT);

	/*
	 * Full reads are posted, or partials if partials are ok.
	 */
	dev->result = ISC_R_SUCCESS;
	return (DOIO_SUCCESS);
}
1257 1258 1259 1260 1261 1262 1263
static int
startio_recv(isc_socket_t *sock, isc_socketevent_t *dev, int *nbytes,
	     BOOL bwait, int *recv_errno) {
	char *cmsg = NULL;
	char strbuf[ISC_STRERRORSIZE];
	IoCompletionInfo *lpo;
	int status;
1264 1265
	struct msghdr messagehdr;
	struct msghdr *msghdr;
1266 1267 1268 1269 1270 1271

	if (!bwait) {
		lpo = (IoCompletionInfo *) HeapAlloc(hHeapHandle,
			HEAP_ZERO_MEMORY, sizeof(IoCompletionInfo));
		lpo->request_type = SOCKET_RECV;
		lpo->dev = dev;
1272
		msghdr = &lpo->messagehdr;
1273 1274
	} else {	/* Wait for recv to complete */
		lpo = NULL;
1275
		msghdr = &messagehdr;
1276 1277
	}
	sock->references++;
1278
	memset(msghdr, 0, sizeof(struct msghdr));
1279

1280
	build_msghdr_recv(sock, dev, msghdr, cmsg, sock->iov,
1281
			&(sock->totalBytes));
Danny Mayer's avatar
Danny Mayer committed
1282

1283
#if defined(ISC_SOCKET_DEBUG)
1284
	dump_msg(msghdr, sock);
1285 1286
#endif

1287
	*nbytes = internal_recvmsg(sock, lpo, msghdr, 0, recv_errno);
1288 1289

	if (*nbytes < 0) {
1290 1291 1292 1293
		if (SOFT_ERROR(*recv_errno)) {
			status = DOIO_SOFT;
			goto done;
		}
1294 1295 1296 1297 1298 1299 1300 1301 1302

		if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
			isc__strerror(*recv_errno, strbuf, sizeof(strbuf));
			socket_log(sock, NULL, IOEVENT,
				   isc_msgcat, ISC_MSGSET_SOCKET,
				   ISC_MSG_DOIORECV, 
				  "startio_recv: recvmsg(%d) %d bytes, err %d/%s",
				   sock->fd, *nbytes, *recv_errno, strbuf);
		}
1303
		status = completeio_recv(sock, dev, msghdr, *nbytes, *recv_errno);
1304 1305 1306
		if(status != DOIO_SOFT) {
			sock->references--;
		}
1307
		goto done;
1308 1309
	}
	dev->result = ISC_R_SUCCESS;
1310 1311 1312
	status = DOIO_SOFT;
done:
	return (status);
1313
}
Danny Mayer's avatar
Danny Mayer committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
/*
 * Returns:
 *	DOIO_SUCCESS	The operation succeeded.  dev->result contains
 *			ISC_R_SUCCESS.
 *
 *	DOIO_HARD	A hard or unexpected I/O error was encountered.
 *			dev->result contains the appropriate error.
 *
 *	DOIO_SOFT	A soft I/O error was encountered.  No senddone
 *			event was sent.  The operation should be retried.
 *
 *	No other return values are possible.
 */
static int
1328
completeio_send(isc_socket_t *sock, isc_socketevent_t *dev, struct msghdr *messagehdr, int cc,
1329
		int send_errno) {
Danny Mayer's avatar
Danny Mayer committed
1330
	char addrbuf[ISC_SOCKADDR_FORMATSIZE];
1331
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
1332

1333
	if(send_errno != 0) {
1334 1335

		if (SOFT_ERROR(send_errno))
Danny Mayer's avatar
Danny Mayer committed
1336 1337 1338
			return (DOIO_SOFT);

#define SOFT_OR_HARD(_system, _isc) \
1339
	if (send_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1340 1341 1342 1343 1344 1345 1346
		if (sock->connected) { \
			dev->result = _isc; \
			return (DOIO_HARD); \
		} \
		return (DOIO_SOFT); \
	}
#define ALWAYS_HARD(_system, _isc) \
1347
	if (send_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1348 1349 1350 1351
		dev->result = _isc; \
		return (DOIO_HARD); \
	}

1352 1353 1354
		SOFT_OR_HARD(WSAEACCES, ISC_R_NOPERM);
		SOFT_OR_HARD(WSAEAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
		SOFT_OR_HARD(WSAECONNREFUSED, ISC_R_CONNREFUSED);
1355
		SOFT_OR_HARD(WSAENOTCONN, ISC_R_CONNREFUSED);
1356
		SOFT_OR_HARD(WSAECONNRESET, ISC_R_CONNECTIONRESET);
1357
		SOFT_OR_HARD(WSAECONNABORTED, ISC_R_CONNECTIONRESET);
1358 1359 1360
		SOFT_OR_HARD(WSAENETRESET, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAEDISCON, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETDOWN, ISC_R_NETDOWN);
1361 1362 1363 1364
		ALWAYS_HARD(ERROR_OPERATION_ABORTED, ISC_R_CONNECTIONRESET);
		ALWAYS_HARD(ERROR_PORT_UNREACHABLE, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(ERROR_HOST_UNREACHABLE, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(ERROR_NETWORK_UNREACHABLE, ISC_R_NETUNREACH);
1365 1366 1367 1368 1369
		ALWAYS_HARD(WSAEADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
		ALWAYS_HARD(WSAEHOSTUNREACH, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(WSAEHOSTDOWN, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(WSAENETUNREACH, ISC_R_NETUNREACH);
		ALWAYS_HARD(WSAENOBUFS, ISC_R_NORESOURCES);