socket.c 82.1 KB
Newer Older
Danny Mayer's avatar
Danny Mayer committed
1
/*
Andreas Gustafsson's avatar
Andreas Gustafsson committed
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.13 2002/01/10 03:50:13 marka Exp $ */
Danny Mayer's avatar
Danny Mayer committed
19

Danny Mayer's avatar
Danny Mayer committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

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

#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>
#include <isc/platform.h>
#include <isc/print.h>
#include <isc/region.h>
#include <isc/socket.h>
51
#include <isc/strerror.h>
Danny Mayer's avatar
Danny Mayer committed
52 53 54 55
#include <isc/task.h>
#include <isc/thread.h>
#include <isc/util.h>

56
#include "errno2result.h"
Danny Mayer's avatar
Danny Mayer committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/*
 * 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.
 */
73
#define SOFT_ERROR(e)	((e) == WSAEINTR || \
74
			 (e) == WSAEWOULDBLOCK || \
75 76 77
			 (e) == EWOULDBLOCK || \
			 (e) == EINTR || \
			 (e) == EAGAIN || \
Danny Mayer's avatar
Danny Mayer committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
			 (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;

103 104
#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
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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

/*
 * 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?
 */
#ifdef SO_TIMESTAMP
#ifndef USE_CMSG
#define USE_CMSG	1
#endif
#endif

/*
 * Check to see if we have even basic support for cracking messages from
 * the control data returned from/sent via recvmsg()/sendmsg().
 */
#if defined(USE_CMSG) && (!defined(CMSG_LEN) || !defined(CMSG_SPACE))
#undef USE_CMSG
#endif

/*
 * 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.
 */
struct iovec {
Andreas Gustafsson's avatar
Andreas Gustafsson committed
147 148
	void	*iov_base; 	/* starting address of buffer */
	size_t	iov_len; 	/* size of buffer */
Danny Mayer's avatar
Danny Mayer committed
149 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 160
        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;

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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
struct isc_socket {
	/* Not locked. */
	unsigned int		magic;
	isc_socketmgr_t	       *manager;
	isc_mutex_t		lock;
	isc_sockettype_t	type;

	/* Locked by socket lock. */
	ISC_LINK(isc_socket_t)	link;
	unsigned int		references;
	int			fd;
	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 */

	unsigned int		pending_recv : 1,
				pending_send : 1,
				pending_accept : 1,
				listener : 1, /* listener socket */
				connected : 1,
				connecting : 1, /* connect pending */
				bound : 1; /* bound to local addr */

#ifdef ISC_NET_RECVOVERFLOW
	unsigned char		overflow; /* used for MSG_TRUNC fake */
#endif
};

207 208 209
#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
210 211 212 213 214 215 216 217 218
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;
	fd_set			read_fds;
	fd_set			write_fds;
219
	fd_set			except_fds;
Danny Mayer's avatar
Danny Mayer committed
220 221 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 262 263 264 265 266
	isc_socket_t	       *fds[FD_SETSIZE];
	int			fdstate[FD_SETSIZE];
	int			maxfd;
#ifdef ISC_PLATFORM_USETHREADS
	isc_thread_t		watcher;
	isc_condition_t		shutdown_ok;
	int			pipe_fds[2];
#endif /* ISC_PLATFORM_USETHREADS */
};

#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)
#ifdef ISC_NET_RECVOVERFLOW
# define MAXSCATTERGATHER_RECV	(ISC_SOCKET_MAXSCATTERGATHER + 1)
#else
# define MAXSCATTERGATHER_RECV	(ISC_SOCKET_MAXSCATTERGATHER)
#endif

static void send_recvdone_event(isc_socket_t *, isc_socketevent_t **);
static void send_senddone_event(isc_socket_t *, isc_socketevent_t **);
static void free_socket(isc_socket_t **);
static isc_result_t allocate_socket(isc_socketmgr_t *, isc_sockettype_t,
				    isc_socket_t **);
static void destroy(isc_socket_t **);
static void internal_accept(isc_task_t *, isc_event_t *);
static void internal_connect(isc_task_t *, isc_event_t *);
static void internal_recv(isc_task_t *, isc_event_t *);
static void internal_send(isc_task_t *, isc_event_t *);
static void process_cmsg(isc_socket_t *, struct msghdr *, isc_socketevent_t *);
static void build_msghdr_send(isc_socket_t *, isc_socketevent_t *,
			      struct msghdr *, char *cmsg,
			      WSABUF *, size_t *);
static void build_msghdr_recv(isc_socket_t *, isc_socketevent_t *,
			      struct msghdr *, char *cmsg,
			      WSABUF *, size_t *);

#define SELECT_POKE_SHUTDOWN		(-1)
#define SELECT_POKE_NOTHING		(-2)
#define SELECT_POKE_READ		(-3)
#define SELECT_POKE_ACCEPT		(-3) /* Same as _READ */
#define SELECT_POKE_WRITE		(-4)
267 268
#define SELECT_POKE_CONNECT		(-5)
#define SELECT_POKE_CLOSE		(-6)
Danny Mayer's avatar
Danny Mayer committed
269 270 271 272 273 274

long bpipe_written = 0;

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

/*
Andreas Gustafsson's avatar
Andreas Gustafsson committed
275 276
 * The following routines are here to handle Unix emulation until we
 * can rewrite the the routines in Winsock2 style.
Danny Mayer's avatar
Danny Mayer committed
277 278 279 280 281
 */

/*
 * Initialize socket services
 */
Andreas Gustafsson's avatar
Andreas Gustafsson committed
282
BOOL InitSockets() {
Danny Mayer's avatar
Danny Mayer committed
283 284 285 286 287 288 289 290
	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
291
	if ( err != 0 ) {
Danny Mayer's avatar
Danny Mayer committed
292
		/* Tell the user that we could not find a usable Winsock DLL */
Danny Mayer's avatar
Danny Mayer committed
293
		return (FALSE);
Danny Mayer's avatar
Danny Mayer committed
294 295
	}
 
Andreas Gustafsson's avatar
Andreas Gustafsson committed
296
	return (TRUE);
Danny Mayer's avatar
Danny Mayer committed
297 298
}

Andreas Gustafsson's avatar
Andreas Gustafsson committed
299 300
int
internal_pipe(int filedes[2]) {
Danny Mayer's avatar
Danny Mayer committed
301 302 303 304 305 306 307 308 309 310
	int status;
	unsigned int pipesize = 65535;
	int mode = _O_TEXT;

	status = _pipe(filedes, pipesize, mode);
	return (status);
	InterlockedExchange(&bpipe_written, 0);
}

int
Andreas Gustafsson's avatar
Andreas Gustafsson committed
311
internal_sendmsg(int sock, const struct msghdr *msg, int flags) {
Danny Mayer's avatar
Danny Mayer committed
312 313 314 315 316 317 318 319 320
	int Error;
	DWORD BytesSent;
	DWORD Flags = flags;

	Error = WSASendTo((SOCKET) sock, 
                    msg->msg_iov, 
                    msg->msg_iovlen, 
                    &BytesSent, 
                    Flags, 
Danny Mayer's avatar
Danny Mayer committed
321 322
		    msg->msg_name,
		    msg->msg_namelen,
Danny Mayer's avatar
Danny Mayer committed
323 324 325
                    NULL,
                    NULL);
    
326 327 328 329 330
	if (Error == SOCKET_ERROR) {
		BytesSent = -1;
		/* There is an error... */
		Error = WSAGetLastError();
		if (Error == WSA_IO_PENDING) {
Andreas Gustafsson's avatar
Andreas Gustafsson committed
331 332
			/* Overlapped send successfully initiated. */
			errno = EAGAIN;
333 334 335 336 337 338 339 340
		} else {
			/* An unexpected error occurred. */
			errno = Error;
		}
	}

	/* No error -- the I/O request was completed immediately... */
	return (BytesSent);
Danny Mayer's avatar
Danny Mayer committed
341 342 343
}

int
Andreas Gustafsson's avatar
Andreas Gustafsson committed
344
internal_recvmsg(int sock, struct msghdr *msg, int flags) {
Danny Mayer's avatar
Danny Mayer committed
345 346 347 348
	DWORD Flags = flags;
	DWORD NumBytes;
	int Result;
	int Error;
Andreas Gustafsson's avatar
Andreas Gustafsson committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

	Result = WSARecvFrom((SOCKET) sock,
			     msg->msg_iov,
			     msg->msg_iovlen,
			     &NumBytes,
			     &Flags,
			     msg->msg_name,
			     (int *)&(msg->msg_namelen),
			     NULL,
			     NULL);


	/* Check for errors. */
	if (Result == SOCKET_ERROR) {
		Error = WSAGetLastError();
Danny Mayer's avatar
Danny Mayer committed
364 365
		NumBytes = -1;
        
Andreas Gustafsson's avatar
Andreas Gustafsson committed
366 367 368 369 370 371 372 373
		switch (Error) {
		case WSAEWOULDBLOCK:
			/*
			 * No data received; return to wait for another
			 * read event.
			 */
			errno = EAGAIN;
			break;
Danny Mayer's avatar
Danny Mayer committed
374

Andreas Gustafsson's avatar
Andreas Gustafsson committed
375 376 377 378 379
		default:
			/* Some other error... hit the panic button. */
			errno = Error;
			break;
		}
Danny Mayer's avatar
Danny Mayer committed
380
	}
Andreas Gustafsson's avatar
Andreas Gustafsson committed
381 382 383 384
	msg->msg_flags = Flags;	/* Return the flags received in header */
	
	return (NumBytes);
}
Danny Mayer's avatar
Danny Mayer committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

static void
manager_log(isc_socketmgr_t *sockmgr,
	    isc_logcategory_t *category, isc_logmodule_t *module, int level,
	    const char *fmt, ...)
{
	char msgbuf[2048];
	va_list ap;

	if (! isc_log_wouldlog(isc_lctx, level))
		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);
}

405 406 407 408 409
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
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
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, ...)
{
	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);
	} else {
Andreas Gustafsson's avatar
Andreas Gustafsson committed
432
		isc_sockaddr_format(address, peerbuf, sizeof(peerbuf));
Danny Mayer's avatar
Danny Mayer committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
		isc_log_iwrite(isc_lctx, category, module, level,
			       msgcat, msgset, message,
			       "socket %p %s: %s", sock, peerbuf, msgbuf);
	}
}

static void
wakeup_socket(isc_socketmgr_t *manager, int fd, int msg) {
	isc_socket_t *sock;

	/*
	 * This is a wakeup on a socket.  If the socket is not in the
	 * process of being closed, start watching it for either reads
	 * or writes.
	 */
448 449

	INSIST(fd >= 0 && fd < FD_SETSIZE);
Danny Mayer's avatar
Danny Mayer committed
450 451 452 453 454

	if (manager->fdstate[fd] == CLOSE_PENDING) {
		manager->fdstate[fd] = CLOSED;
		FD_CLR(fd, &manager->read_fds);
		FD_CLR(fd, &manager->write_fds);
455
		FD_CLR(fd, &manager->except_fds);
Danny Mayer's avatar
Danny Mayer committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
		closesocket(fd);
		return;
	}
	if (manager->fdstate[fd] != MANAGED)
		return;

	sock = manager->fds[fd];

	/*
	 * If there are no events, or there is an event but we
	 * have already queued up the internal event on a task's
	 * queue, clear the bit.  Otherwise, set it.
	 */
	if (msg == SELECT_POKE_READ)
		FD_SET(sock->fd, &manager->read_fds);
	if (msg == SELECT_POKE_WRITE)
		FD_SET(sock->fd, &manager->write_fds);
473 474 475 476
	if (msg == SELECT_POKE_CONNECT) {	/* Need both here */
		FD_SET(sock->fd, &manager->write_fds);
		FD_SET(sock->fd, &manager->except_fds);
	}
Danny Mayer's avatar
Danny Mayer committed
477 478 479 480 481 482 483 484 485 486 487 488
}

#ifdef ISC_PLATFORM_USETHREADS
/*
 * Poke the select loop when there is something for us to do.
 * The write is required (by POSIX) to complete.  That is, we
 * will not get partial writes.
 */
static void
select_poke(isc_socketmgr_t *mgr, int fd, int msg) {
	int cc;
	int buf[2];
489
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
490 491 492 493

	buf[0] = fd;
	buf[1] = msg;

Danny Mayer's avatar
Danny Mayer committed
494
	if (msg == SELECT_POKE_SHUTDOWN) {
Danny Mayer's avatar
Danny Mayer committed
495 496 497 498
		do {
			cc = _write(mgr->pipe_fds[1], buf, sizeof(buf));
		} while (cc < 0 && SOFT_ERROR(errno));
			        
499 500
	if (cc < 0) {
		isc__strerror(errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
501
			FATAL_ERROR(__FILE__, __LINE__,
502
			    isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
Danny Mayer's avatar
Danny Mayer committed
503
						   ISC_MSG_WRITEFAILED,
504
					   "write() failed "
Andreas Gustafsson's avatar
Andreas Gustafsson committed
505
						   "during watcher poke: %s"),
506 507
			    strbuf);
	}
Danny Mayer's avatar
Danny Mayer committed
508 509 510 511

		INSIST(cc == sizeof(buf));

		InterlockedIncrement(&bpipe_written);
Andreas Gustafsson's avatar
Andreas Gustafsson committed
512
	} else {
Danny Mayer's avatar
Danny Mayer committed
513 514 515
		wakeup_socket(mgr, fd, msg);
	}
}
Andreas Gustafsson's avatar
Andreas Gustafsson committed
516

Danny Mayer's avatar
Danny Mayer committed
517 518 519 520 521 522 523
/*
 * Read a message on the internal fd.
 */
static void
select_readmsg(isc_socketmgr_t *mgr, int *fd, int *msg) {
	int buf[2];
	int cc;
524
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
525 526 527 528 529 530 531

	cc = _read(mgr->pipe_fds[0], buf, sizeof(buf));
	if (cc < 0) {
		*msg = SELECT_POKE_NOTHING;
		if (SOFT_ERROR(errno))
			return;

532
		isc__strerror(errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
533 534 535
		FATAL_ERROR(__FILE__, __LINE__,
			    isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET,
					   ISC_MSG_READFAILED,
536
					   "read() failed "
Danny Mayer's avatar
Danny Mayer committed
537
					   "during watcher poke: %s"),
538 539
			    strbuf);
		
Danny Mayer's avatar
Danny Mayer committed
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
		return;
	}
	INSIST(cc == sizeof(buf));
	*fd  = buf[0];
	*msg = buf[1];

}
#else /* ISC_PLATFORM_USETHREADS */
/*
 * Update the state of the socketmgr when something changes.
 */
static void
select_poke(isc_socketmgr_t *manager, int fd, int msg) {
	if (msg == SELECT_POKE_SHUTDOWN)
		return;
	else if (fd >= 0)
		wakeup_socket(manager, fd, msg);
	return;
}
#endif /* ISC_PLATFORM_USETHREADS */

/*
 * Make a fd non-blocking.
 */
static isc_result_t
make_nonblock(int fd) {
	int ret;
	unsigned long flags = 1;
568
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
569 570 571 572 573

	/* Set the socket to non-blocking */
	ret = ioctlsocket((SOCKET) fd, FIONBIO, &flags);

	if (ret == -1) {
574
		isc__strerror(errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
575 576
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "ioctlsocket(%d, FIOBIO, %d): %s",
577
				 fd, flags, strbuf);
Danny Mayer's avatar
Danny Mayer committed
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 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

		return (ISC_R_UNEXPECTED);
	}

	return (ISC_R_SUCCESS);
}

/*
 * Process control messages received on a socket.
 */
static void
process_cmsg(isc_socket_t *sock, struct msghdr *msg, isc_socketevent_t *dev) {
#ifdef USE_CMSG
	struct cmsghdr *cmsgp;
#ifdef ISC_PLATFORM_HAVEIPV6
	struct in6_pktinfo *pktinfop;
#endif
#ifdef SO_TIMESTAMP
	struct timeval *timevalp;
#endif
#endif

	/*
	 * sock is used only when ISC_NET_BSD44MSGHDR and USE_CMSG are defined.
	 * msg and dev are used only when ISC_NET_BSD44MSGHDR is defined.
	 * They are all here, outside of the CPP tests, because it is
	 * more consistent with the usual ISC coding style.
	 */
	UNUSED(sock);
	UNUSED(msg);
	UNUSED(dev);

#ifndef ISC_NET_BSD44MSGHDR
	return;

#else  /* defined ISC_NET_BSD44MSGHDR */

#ifdef MSG_TRUNC
	if ((msg->msg_flags & MSG_TRUNC) == MSG_TRUNC)
		dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
#endif

#ifdef MSG_CTRUNC
	if ((msg->msg_flags & MSG_CTRUNC) == MSG_CTRUNC)
		dev->attributes |= ISC_SOCKEVENTATTR_CTRUNC;
#endif

#ifndef USE_CMSG
	return;
#else
	if (msg->msg_controllen == 0 || msg->msg_control == NULL)
		return;

#ifdef SO_TIMESTAMP
	timevalp = NULL;
#endif
#ifdef ISC_PLATFORM_HAVEIPV6
	pktinfop = NULL;
#endif

	cmsgp = CMSG_FIRSTHDR(msg);
	while (cmsgp != NULL) {
		socket_log(sock, NULL, TRACE,
			   isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PROCESSCMSG,
			   "processing cmsg %p", cmsgp);

#ifdef ISC_PLATFORM_HAVEIPV6
		if (cmsgp->cmsg_level == IPPROTO_IPV6
		    && cmsgp->cmsg_type == IPV6_PKTINFO) {

			pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
			memcpy(&dev->pktinfo, pktinfop,
			       sizeof(struct in6_pktinfo));
			dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO;
			socket_log(sock, NULL, TRACE,
				   isc_msgcat, ISC_MSGSET_SOCKET,
				   ISC_MSG_IFRECEIVED,
				   "interface received on ifindex %u",
				   dev->pktinfo.ipi6_ifindex);
657 658
			if (IN6_IS_ADDR_MULTICAST(&pktinfop->ipi6_addr))
				dev->attributes |= ISC_SOCKEVENTATTR_MULTICAST;				
Danny Mayer's avatar
Danny Mayer committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
			goto next;
		}
#endif

#ifdef SO_TIMESTAMP
		if (cmsgp->cmsg_level == SOL_SOCKET
		    && cmsgp->cmsg_type == SCM_TIMESTAMP) {
			timevalp = (struct timeval *)CMSG_DATA(cmsgp);
			dev->timestamp.seconds = timevalp->tv_sec;
			dev->timestamp.nanoseconds = timevalp->tv_usec * 1000;
			dev->attributes |= ISC_SOCKEVENTATTR_TIMESTAMP;
			goto next;
		}
#endif

	next:
		cmsgp = CMSG_NXTHDR(msg, cmsgp);
	}
#endif /* USE_CMSG */

#endif /* ISC_NET_BSD44MSGHDR */

}

/*
 * 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,
		  WSABUF *iov, size_t *write_countp)
{
	unsigned int iovcount;
	isc_buffer_t *buffer;
	isc_region_t used;
	size_t write_count;
	size_t skip_count;

#ifndef USE_CMSG
	UNUSED(cmsg);
#endif

Andreas Gustafsson's avatar
Andreas Gustafsson committed
710
	memset(msg, 0, sizeof(*msg));
Danny Mayer's avatar
Danny Mayer committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

	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
Danny Mayer's avatar
Danny Mayer committed
756
						   + skip_count);
Danny Mayer's avatar
Danny Mayer committed
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
			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;

#ifdef ISC_NET_BSD44MSGHDR
	msg->msg_control = NULL;
	msg->msg_controllen = 0;
	msg->msg_flags = 0;
775
#if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIPV6)
Danny Mayer's avatar
Danny Mayer committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
	if ((sock->type == isc_sockettype_udp)
	    && ((dev->attributes & ISC_SOCKEVENTATTR_PKTINFO) != 0)) {
		struct cmsghdr *cmsgp;
		struct in6_pktinfo *pktinfop;

		socket_log(sock, NULL, TRACE,
			   isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_SENDTODATA,
			   "sendto pktinfo data, ifindex %u",
			   dev->pktinfo.ipi6_ifindex);

		msg->msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
		msg->msg_control = (void *)cmsg;

		cmsgp = (struct cmsghdr *)cmsg;
		cmsgp->cmsg_level = IPPROTO_IPV6;
		cmsgp->cmsg_type = IPV6_PKTINFO;
		cmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
		pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
		memcpy(pktinfop, &dev->pktinfo, sizeof(struct in6_pktinfo));
	}
796
#endif /* USE_CMSG && ISC_PLATFORM_HAVEIPV6 */
Danny Mayer's avatar
Danny Mayer committed
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
#endif /* ISC_NET_BSD44MSGHDR */

	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,
		  WSABUF *iov, size_t *read_countp)
{
	unsigned int iovcount;
	isc_buffer_t *buffer;
	isc_region_t available;
	size_t read_count;

#ifndef USE_CMSG
	UNUSED(cmsg);
#endif

Andreas Gustafsson's avatar
Andreas Gustafsson committed
829
	memset(msg, 0, sizeof(struct msghdr));
Danny Mayer's avatar
Danny Mayer committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

	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);
#ifdef ISC_NET_RECVOVERFLOW
		/* If needed, steal one iovec for overflow detection. */
		maxiov--;
#endif
	} 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
856 857 858 859 860
	} else {
		/*
		 * Multibuffer I/O.
		 * Skip empty buffers.
		 */
Danny Mayer's avatar
Danny Mayer committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
		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.
	 */
#ifdef ISC_NET_RECVOVERFLOW
	if (sock->type == isc_sockettype_udp) {
		iov[iovcount].iov_base = (void *)(&sock->overflow);
		iov[iovcount].iov_len = 1;
		iovcount++;
	}
#endif

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

#ifdef ISC_NET_BSD44MSGHDR
	msg->msg_control = NULL;
	msg->msg_controllen = 0;
	msg->msg_flags = 0;
#if defined(USE_CMSG)
	if (sock->type == isc_sockettype_udp) {
		msg->msg_control = cmsg;
		msg->msg_controllen = CMSG_BUF_SIZE;
	}
#endif /* USE_CMSG */
#endif /* ISC_NET_BSD44MSGHDR */

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

static void
set_dev_address(isc_sockaddr_t *address, isc_socket_t *sock,
		isc_socketevent_t *dev)
{
	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,
		     isc_taskaction_t action, const void *arg)
{
	isc_socketevent_t *ev;

	ev = (isc_socketevent_t *)isc_event_allocate(sock->manager->mctx,
						     sock, eventtype,
						     action, arg,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
940
						     sizeof(*ev));
Danny Mayer's avatar
Danny Mayer committed
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963

	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;

	printf("MSGHDR %p, Socket #: %d\n", msg, sock->fd);
	printf("\tname %p, namelen %d\n", msg->msg_name, msg->msg_namelen);
	printf("\tiov %p, iovlen %d\n", msg->msg_iov, msg->msg_iovlen);
964
	for (i = 0; i < (unsigned int)msg->msg_iovlen; i++)
Danny Mayer's avatar
Danny Mayer committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
		printf("\t\t%d\tbase %p, len %d\n", i,
		       msg->msg_iov[i].buf,
		       msg->msg_iov[i].len);
#ifdef ISC_NET_BSD44MSGHDR
	printf("\tcontrol %p, controllen %d\n", msg->msg_control,
	       msg->msg_controllen);
#endif
}
#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
doio_recv(isc_socket_t *sock, isc_socketevent_t *dev) {
	int cc;
	WSABUF iov[MAXSCATTERGATHER_RECV];
	size_t read_count;
	size_t actual_count;
	struct msghdr msghdr;
	isc_buffer_t *buffer;
988
	int recv_errno;
Danny Mayer's avatar
Danny Mayer committed
989 990 991 992 993
#if USE_CMSG
	char cmsg[CMSG_BUF_SIZE];
#else
	char *cmsg = NULL;
#endif
994
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
995 996 997 998 999 1000 1001 1002

	build_msghdr_recv(sock, dev, &msghdr, cmsg, iov, &read_count);

#if defined(ISC_SOCKET_DEBUG)
	dump_msg(&msghdr,sock);
#endif

	cc = internal_recvmsg(sock->fd, &msghdr, 0);
1003
	recv_errno = WSAGetLastError();
Danny Mayer's avatar
Danny Mayer committed
1004 1005

	if (cc < 0) {
1006
		if (SOFT_ERROR(recv_errno))
Danny Mayer's avatar
Danny Mayer committed
1007 1008
			return (DOIO_SOFT);

1009 1010
		if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
			isc__strerror(recv_errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1011 1012 1013
			socket_log(sock, NULL, IOEVENT,
				   isc_msgcat, ISC_MSGSET_SOCKET,
				   ISC_MSG_DOIORECV, 
1014 1015 1016
				  "doio_recv: recvmsg(%d) %d bytes, err %d/%s",
				   sock->fd, cc, recv_errno, strbuf);
		}
Danny Mayer's avatar
Danny Mayer committed
1017 1018

#define SOFT_OR_HARD(_system, _isc) \
1019
	if (recv_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1020 1021 1022 1023 1024 1025 1026
		if (sock->connected) { \
			dev->result = _isc; \
			return (DOIO_HARD); \
		} \
		return (DOIO_SOFT); \
	}
#define ALWAYS_HARD(_system, _isc) \
1027
	if (recv_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1028 1029 1030 1031
		dev->result = _isc; \
		return (DOIO_HARD); \
	}

1032 1033 1034 1035 1036 1037 1038 1039
		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);
		SOFT_OR_HARD(WSAEDISCON, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETDOWN, ISC_R_NETDOWN);
		ALWAYS_HARD(WSAENOBUFS, ISC_R_NORESOURCES);
Danny Mayer's avatar
Danny Mayer committed
1040 1041 1042 1043

#undef SOFT_OR_HARD
#undef ALWAYS_HARD

1044
		dev->result = isc__errno2result(recv_errno);
Danny Mayer's avatar
Danny Mayer committed
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 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
		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);

	if (sock->type == isc_sockettype_udp)
		dev->address.length = msghdr.msg_namelen;

	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

	/*
	 * If there are control messages attached, run through them and pull
	 * out the interesting bits.
	 */
	if (sock->type == isc_sockettype_udp)
		process_cmsg(sock, &msghdr, dev);

	/*
	 * 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.
	 */
	if (((size_t)cc != read_count) && (dev->n < dev->minimum))
		return (DOIO_SOFT);

	/*
	 * Full reads are posted, or partials if partials are ok.
	 */
	dev->result = ISC_R_SUCCESS;
	return (DOIO_SUCCESS);
}

/*
 * 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
doio_send(isc_socket_t *sock, isc_socketevent_t *dev) {
	int cc;
	WSABUF iov[MAXSCATTERGATHER_SEND];
	size_t write_count;
	struct msghdr msghdr;
	char addrbuf[ISC_SOCKADDR_FORMATSIZE];
#if USE_CMSG
	char cmsg[CMSG_BUF_SIZE];
#else
	char *cmsg = NULL;
#endif
1144 1145 1146
	int attempts = 0;
	int send_errno;
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
1147 1148 1149

	build_msghdr_send(sock, dev, &msghdr, cmsg, iov, &write_count);

1150
resend:
Danny Mayer's avatar
Danny Mayer committed
1151
	cc = internal_sendmsg(sock->fd, &msghdr, 0);
1152
	send_errno = WSAGetLastError();
Danny Mayer's avatar
Danny Mayer committed
1153 1154 1155 1156 1157

	/*
	 * Check for error or block condition.
	 */
	if (cc < 0) {
1158 1159 1160 1161
		if (send_errno == WSAEINTR && ++attempts < NRETRIES)
			goto resend;

		if (SOFT_ERROR(send_errno))
Danny Mayer's avatar
Danny Mayer committed
1162 1163 1164
			return (DOIO_SOFT);

#define SOFT_OR_HARD(_system, _isc) \
1165
	if (send_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1166 1167 1168 1169 1170 1171 1172
		if (sock->connected) { \
			dev->result = _isc; \
			return (DOIO_HARD); \
		} \
		return (DOIO_SOFT); \
	}
#define ALWAYS_HARD(_system, _isc) \
1173
	if (send_errno == _system) { \
Danny Mayer's avatar
Danny Mayer committed
1174 1175 1176 1177
		dev->result = _isc; \
		return (DOIO_HARD); \
	}

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
		SOFT_OR_HARD(WSAEACCES, ISC_R_NOPERM);
		SOFT_OR_HARD(WSAEAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
		SOFT_OR_HARD(WSAECONNREFUSED, ISC_R_CONNREFUSED);
		SOFT_OR_HARD(WSAECONNRESET, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETRESET, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAEDISCON, ISC_R_CONNECTIONRESET);
		SOFT_OR_HARD(WSAENETDOWN, ISC_R_NETDOWN);
		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);
Danny Mayer's avatar
Danny Mayer committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
		ALWAYS_HARD(EPERM, ISC_R_HOSTUNREACH);
		ALWAYS_HARD(EPIPE, ISC_R_NOTCONNECTED);

#undef SOFT_OR_HARD
#undef ALWAYS_HARD

		/*
		 * The other error types depend on whether or not the
		 * socket is UDP or TCP.  If it is UDP, some errors
		 * that we expect to be fatal under TCP are merely
		 * annoying, and are really soft errors.
		 *
		 * However, these soft errors are still returned as
		 * a status.
		 */
		isc_sockaddr_format(&dev->address, addrbuf, sizeof(addrbuf));
1206 1207 1208 1209
		isc__strerror(send_errno, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_send: %s: %s",
				 addrbuf, strbuf);
		dev->result = isc__errno2result(send_errno);
Danny Mayer's avatar
Danny Mayer committed
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 1248 1249 1250 1251
		return (DOIO_HARD);
	}

	if (cc == 0)
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "internal_send: send() %s 0",
				 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
						ISC_MSG_RETURNED, "returned"));

	/*
	 * If we write less than we expected, update counters, poke.
	 */
	dev->n += cc;
	if ((size_t)cc != write_count)
		return (DOIO_SOFT);

	/*
	 * Exactly what we wanted to write.  We're done with this
	 * entry.  Post its completion event.
	 */
	dev->result = ISC_R_SUCCESS;
	return (DOIO_SUCCESS);
}

/*
 * Kill.
 *
 * Caller must ensure that the socket is not locked and no external
 * references exist.
 */
static void
destroy(isc_socket_t **sockp) {
	isc_socket_t *sock = *sockp;
	isc_socketmgr_t *manager = sock->manager;

	socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET,
		   ISC_MSG_DESTROYING, "destroying");

	INSIST(ISC_LIST_EMPTY(sock->accept_list));
	INSIST(ISC_LIST_EMPTY(sock->recv_list));
	INSIST(ISC_LIST_EMPTY(sock->send_list));
	INSIST(sock->connect_ev == NULL);
1252
	REQUIRE(sock->fd >= 0 && sock->fd < FD_SETSIZE);
Danny Mayer's avatar
Danny Mayer committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

	LOCK(&manager->lock);

	/*
	 * No one has this socket open, so the watcher doesn't have to be
	 * poked, and the socket doesn't have to be locked.
	 */
	manager->fds[sock->fd] = NULL;
	manager->fdstate[sock->fd] = CLOSE_PENDING;
	select_poke(manager, sock->fd, SELECT_POKE_CLOSE);
	ISC_LIST_UNLINK(manager->socklist, sock, link);

#ifdef ISC_PLATFORM_USETHREADS
	if (ISC_LIST_EMPTY(manager->socklist))
		SIGNAL(&manager->shutdown_ok);
#endif /* ISC_PLATFORM_USETHREADS */

	/*
	 * XXX should reset manager->maxfd here
	 */

	UNLOCK(&manager->lock);

	free_socket(sockp);
}

static isc_result_t
allocate_socket(isc_socketmgr_t *manager, isc_sockettype_t type,
		isc_socket_t **socketp)
{
	isc_socket_t *sock;
	isc_result_t ret;

Andreas Gustafsson's avatar
Andreas Gustafsson committed
1286
	sock = isc_mem_get(manager->mctx, sizeof(*sock));
Danny Mayer's avatar
Danny Mayer committed
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

	if (sock == NULL)
		return (ISC_R_NOMEMORY);

	ret = ISC_R_UNEXPECTED;

	sock->magic = 0;
	sock->references = 0;

	sock->manager = manager;
	sock->type = type;
	sock->fd = -1;

	ISC_LINK_INIT(sock, link);

	/*
	 * set up list of readers and writers to be initially empty
	 */
	ISC_LIST_INIT(sock->recv_list);
	ISC_LIST_INIT(sock->send_list);
	ISC_LIST_INIT(sock->accept_list);
	sock->connect_ev = NULL;
	sock->pending_recv = 0;
	sock->pending_send = 0;
	sock->pending_accept = 0;
	sock->listener = 0;
	sock->connected = 0;
	sock->connecting = 0;
	sock->bound = 0;

	/*
	 * initialize the lock
	 */
	if (isc_mutex_init(&sock->lock) != ISC_R_SUCCESS) {
		sock->magic = 0;
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "isc_mutex_init() %s",
				 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
						ISC_MSG_FAILED, "failed"));
		ret = ISC_R_UNEXPECTED;
		goto error;
	}

	/*
	 * Initialize readable and writable events
	 */
	ISC_EVENT_INIT(&sock->readable_ev, sizeof(intev_t),
		       ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTR,
		       NULL, sock, sock, NULL, NULL);
	ISC_EVENT_INIT(&sock->writable_ev, sizeof(intev_t),
		       ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTW,
		       NULL, sock, sock, NULL, NULL);

	sock->magic = SOCKET_MAGIC;
	*socketp = sock;

	return (ISC_R_SUCCESS);

 error: /* socket allocated */

	return (ret);
}

/*
 * This event requires that the various lists be empty, that the reference
 * count be 1, and that the magic number is valid.  The other socket bits,
 * like the lock, must be initialized as well.  The fd associated must be
 * marked as closed, by setting it to -1 on close, or this routine will
 * also close the socket.
 */
static void
free_socket(isc_socket_t **socketp) {
	isc_socket_t *sock = *socketp;

	INSIST(sock->references == 0);
	INSIST(VALID_SOCKET(sock));
	INSIST(!sock->connecting);
	INSIST(!sock->pending_recv);
	INSIST(!sock->pending_send);
	INSIST(!sock->pending_accept);
	INSIST(ISC_LIST_EMPTY(sock->recv_list));
	INSIST(ISC_LIST_EMPTY(sock->send_list));
	INSIST(ISC_LIST_EMPTY(sock->accept_list));
	INSIST(!ISC_LINK_LINKED(sock, link));

	sock->magic = 0;

	DESTROYLOCK(&sock->lock);

Andreas Gustafsson's avatar
Andreas Gustafsson committed
1376
	isc_mem_put(sock->manager->mctx, sock, sizeof(*sock));
Danny Mayer's avatar
Danny Mayer committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388

	*socketp = NULL;
}

/*
 * Create a new 'type' socket managed by 'manager'.  Events
 * will be posted to 'task' and when dispatched 'action' will be
 * called with 'arg' as the arg value.  The new socket is returned
 * in 'socketp'.
 */
isc_result_t
isc_socket_create(isc_socketmgr_t *manager, int pf, isc_sockettype_t type,
1389
		  isc_socket_t **socketp) {
Danny Mayer's avatar
Danny Mayer committed
1390 1391 1392 1393 1394
	isc_socket_t *sock = NULL;
	isc_result_t ret;
#if defined(USE_CMSG) || defined(SO_BSDCOMPAT)
	int on = 1;
#endif
1395 1396
	int socket_errno;
	char strbuf[ISC_STRERRORSIZE];
Danny Mayer's avatar
Danny Mayer committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413

	REQUIRE(VALID_MANAGER(manager));
	REQUIRE(socketp != NULL && *socketp == NULL);

	ret = allocate_socket(manager, type, &sock);
	if (ret != ISC_R_SUCCESS)
		return (ret);

	sock->pf = pf;
	switch (type) {
	case isc_sockettype_udp:
		sock->fd = socket(pf, SOCK_DGRAM, IPPROTO_UDP);
		break;
	case isc_sockettype_tcp:
		sock->fd = socket(pf, SOCK_STREAM, IPPROTO_TCP);
		break;
	}
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

	if (sock->fd >= FD_SETSIZE) {
		(void)closesocket(sock->fd);
		isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL,
			      ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
			       isc_msgcat, ISC_MSGSET_SOCKET,
			       ISC_MSG_TOOMANYFDS,
			       "%s: too many open file descriptors", "socket");
		free_socket(&sock);
		return (ISC_R_NORESOURCES);
	}
	
Danny Mayer's avatar
Danny Mayer committed
1426
	if (sock->fd < 0) {
1427
		socket_errno = WSAGetLastError();
Danny Mayer's avatar
Danny Mayer committed
1428 1429
		free_socket(&sock);

1430 1431 1432
		switch (socket_errno) {
		case WSAEMFILE:
		case WSAENOBUFS:
Danny Mayer's avatar
Danny Mayer committed
1433 1434
			return (ISC_R_NORESOURCES);

1435 1436 1437
		case WSAEPROTONOSUPPORT:
		case WSAEPFNOSUPPORT:
		case WSAEAFNOSUPPORT:
Danny Mayer's avatar
Danny Mayer committed
1438 1439 1440
			return (ISC_R_FAMILYNOSUPPORT);

		default:
1441
			isc__strerror(socket_errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1442 1443 1444 1445 1446 1447
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "socket() %s: %s",
					 isc_msgcat_get(isc_msgcat,
							ISC_MSGSET_GENERAL,
							ISC_MSG_FAILED,
							"failed"),
1448
					 strbuf);
Danny Mayer's avatar
Danny Mayer committed
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
			return (ISC_R_UNEXPECTED);
		}
	}

	if (make_nonblock(sock->fd) != ISC_R_SUCCESS) {
		free_socket(&sock);
		return (ISC_R_UNEXPECTED);
	}

#ifdef SO_BSDCOMPAT
	if (setsockopt(sock->fd, SOL_SOCKET, SO_BSDCOMPAT,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1460
		       (void *)&on, sizeof(on)) < 0) {
1461 1462
		socket_errno = WSAGetLastError();
		isc__strerror(socket_errno, strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1463 1464 1465 1466 1467
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "setsockopt(%d, SO_BSDCOMPAT) %s: %s",
				 sock->fd,
				 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
						ISC_MSG_FAILED, "failed"),
1468
				 strbuf);
Danny Mayer's avatar
Danny Mayer committed
1469 1470 1471 1472 1473 1474 1475 1476 1477
		/* Press on... */
	}
#endif

#if defined(USE_CMSG)
	if (type == isc_sockettype_udp) {

#if defined(SO_TIMESTAMP)
		if (setsockopt(sock->fd, SOL_SOCKET, SO_TIMESTAMP,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1478
			       (void *)&on, sizeof(on)) < 0
1479 1480
		    && WSAGetLastError() != WSAENOPROTOOPT) {
			isc__strerror(WSAGetLastError(), strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1481 1482 1483 1484 1485 1486 1487
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "setsockopt(%d, SO_TIMESTAMP) %s: %s",
					 sock->fd, 
					 isc_msgcat_get(isc_msgcat,
							ISC_MSGSET_GENERAL,
							ISC_MSG_FAILED,
							"failed"),
1488
					 strbuf);
Danny Mayer's avatar
Danny Mayer committed
1489 1490 1491 1492 1493 1494 1495 1496 1497
			/* Press on... */
		}
#endif /* SO_TIMESTAMP */

#if defined(ISC_PLATFORM_HAVEIPV6)
#ifdef IPV6_RECVPKTINFO
		/* 2292bis */
		if ((pf == AF_INET6)
		    && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1498
				   (void *)&on, sizeof(on)) < 0)) {
1499
			isc__strerror(WSAGetLastError(), strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1500 1501 1502 1503 1504 1505 1506
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "setsockopt(%d, IPV6_RECVPKTINFO) "
					 "%s: %s", sock->fd,
					 isc_msgcat_get(isc_msgcat,
							ISC_MSGSET_GENERAL,
							ISC_MSG_FAILED,
							"failed"),
1507
					 strbuf);
Danny Mayer's avatar
Danny Mayer committed
1508 1509 1510 1511 1512
		}
#else
		/* 2292 */
		if ((pf == AF_INET6)
		    && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_PKTINFO,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1513
				   (void *)&on, sizeof(on)) < 0)) {
1514
			isc__strerror(WSAGetLaastError(), strbuf, sizeof(strbuf));
Danny Mayer's avatar
Danny Mayer committed
1515 1516 1517 1518 1519 1520 1521
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "setsockopt(%d, IPV6_PKTINFO) %s: %s",
					 sock->fd,
					 isc_msgcat_get(isc_msgcat,
							ISC_MSGSET_GENERAL,
							ISC_MSG_FAILED,
							"failed"),
1522
					 strbuf);
Danny Mayer's avatar
Danny Mayer committed
1523 1524 1525 1526 1527 1528 1529
		}
#endif /* IPV6_RECVPKTINFO */
#ifdef IPV6_USE_MIN_MTU        /*2292bis, not too common yet*/
		/* use minimum MTU */
		if (pf == AF_INET6) {
			(void)setsockopt(sock->fd, IPPROTO_IPV6,
					 IPV6_USE_MIN_MTU,
Andreas Gustafsson's avatar
Andreas Gustafsson committed
1530
					 (void *)&on, sizeof(on));
Danny Mayer's avatar
Danny Mayer committed
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579