xref: /freebsd/contrib/bsnmp/snmpd/trans_inet.c (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
1 /*
2  * Copyright (c) 2018
3  *	Hartmut Brandt.
4  *	All rights reserved.
5  *
6  * Author: Harti Brandt <harti@freebsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $Begemot: bsnmp/snmpd/trans_udp.c,v 1.5 2005/10/04 08:46:56 brandt_h Exp $
30  *
31  * Internet transport
32  */
33 
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/types.h>
37 
38 #include <assert.h>
39 #include <errno.h>
40 #include <netdb.h>
41 #include <stdbool.h>
42 #include <stddef.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <syslog.h>
46 #include <unistd.h>
47 
48 #include <stdio.h>
49 
50 #include <arpa/inet.h>
51 
52 #include "asn1.h"
53 #include "snmp.h"
54 #include "snmpmod.h"
55 
56 #include "snmpd.h"
57 
58 #define	SNMPTREE_TYPES
59 #define	SNMPENUM_FUNCS
60 #include "tree.h"
61 #include "oid.h"
62 
63 extern const struct transport_def inet_trans;
64 
65 struct inet_port;
66 struct inet_port_params;
67 struct port_sock;
68 
69 typedef int create_func(struct inet_port *, struct inet_port_params *);
70 typedef void input_func(int, void *);
71 typedef int activate_func(struct inet_port *);
72 typedef void deactivate_func(struct inet_port *);
73 typedef void parse_ctrl_func(struct port_sock *, const struct msghdr *);
74 typedef void setsrc_func(struct port_sock *, struct msghdr *);
75 
76 static create_func ipv4_create;
77 static input_func ipv4_input;
78 static activate_func ipv4_activate;
79 static deactivate_func ipv4_deactivate;
80 static parse_ctrl_func ipv4_parse_ctrl;
81 static setsrc_func ipv4_setsrc;
82 
83 static create_func ipv6_create;
84 static input_func ipv6_input;
85 static activate_func ipv6_activate;
86 static deactivate_func ipv6_deactivate;
87 static parse_ctrl_func ipv6_parse_ctrl;
88 static setsrc_func ipv6_setsrc;
89 
90 static create_func ipv6z_create;
91 
92 static create_func dns_create;
93 static activate_func dns_activate;
94 static deactivate_func dns_deactivate;
95 
96 struct port_sock {
97 	/* common input stuff; must be first */
98 	struct port_input input;
99 
100 	/** link field */
101 	TAILQ_ENTRY(port_sock) link;
102 
103 	/** pointer to parent */
104 	struct inet_port *port;
105 
106 	/** bind address */
107 	struct sockaddr_storage bind_addr;
108 
109 	/** reply destination */
110 	struct sockaddr_storage ret_dest;
111 
112 	/** need to set source address in reply; set for INADDR_ANY */
113 	bool set_ret_source;
114 
115 	/** address of the receive interface */
116 	union {
117 		/** IPv4 case */
118 		struct in_addr	a4;
119 
120 		/** IPv6 case */
121 		struct in6_pktinfo a6;
122 	} ret_source;
123 
124 	/** parse control message */
125 	parse_ctrl_func *parse_ctrl;
126 
127 	/** set source address for a send() */
128 	setsrc_func *setsrc;
129 };
130 static_assert(offsetof(struct port_sock, input) == 0,
131     "input not first in port_sock");
132 
133 /**
134  * Table row for the inet ports.
135  *
136  * When actived each row can have one or several open sockets. For ipv6,
137  * ipv4 and ipv6z addresses it is always one, for dns addresses more than
138  * one socket can be open.
139  */
140 struct inet_port {
141 	/** common i/o port stuff (must be first) */
142 	struct tport tport;
143 
144 	/** transport protocol */
145 	enum BegemotSnmpdTransportProto proto;
146 
147 	/** row status */
148 	enum RowStatus row_status;
149 
150 	/** socket list */
151 	TAILQ_HEAD(, port_sock) socks;
152 
153 	/** value for InetAddressType::dns */
154 	char *dns_addr;
155 
156 	/** port number in dns case; network byte order */
157 	uint16_t dns_port;
158 
159 	/** create a port */
160 	create_func *create;
161 
162 	/** activate a port */
163 	activate_func *activate;
164 
165 	/** deactivate port */
166 	deactivate_func *deactivate;
167 };
168 static_assert(offsetof(struct inet_port, tport) == 0,
169     "tport not first in inet_port");
170 
171 /** to be used in bind_addr field */
172 #define	AF_DNS	AF_VENDOR00
173 
174 /** registered transport */
175 static struct transport *my_trans;
176 
177 /** set operation */
178 enum {
179 	SET_CREATED,
180 	SET_ACTIVATED,
181 	SET_DEACTIVATE,
182 	SET_DESTROY,
183 };
184 
185 /** length of the control data buffer */
186 static const size_t RECV_CBUF_SIZE =
187     MAX(CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) +
188 	CMSG_SPACE(sizeof(struct in_addr)),
189 	CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX)) +
190 	CMSG_SPACE(sizeof(struct in6_pktinfo)));
191 
192 /** length of the control data buffer */
193 static const size_t XMIT_CBUF_SIZE =
194     MAX(CMSG_SPACE(sizeof(struct in_addr)),
195 	CMSG_SPACE(sizeof(struct in6_pktinfo)));
196 
197 /**
198  * Start the transport. This registers the transport with the
199  * transport table.
200  *
201  * \return SNMP error code
202  */
203 static int
204 inet_start(void)
205 {
206 	return (trans_register(&inet_trans, &my_trans));
207 }
208 
209 /**
210  * Stop the transport. This tries to unregister the transport which
211  * in turn fails if the list of ports is not empty.
212  *
213  * \return SNMP error code
214  */
215 static int
216 inet_stop(int force __unused)
217 {
218 	if (my_trans != NULL)
219 		if (trans_unregister(my_trans) != 0)
220 			return (SNMP_ERR_GENERR);
221 	return (SNMP_ERR_NOERROR);
222 }
223 
224 /**
225  * Deactivate SNMP port.
226  *
227  * \param tp	port to close
228  */
229 static void
230 deactivate_port(struct inet_port *p)
231 {
232 	p->deactivate(p);
233 }
234 
235 /*
236  * This function activates a port. For ports opened via the config files
237  * this is called just before entering the event loop. For ports create
238  * during runtime this is called when the RowStatus is set to Active or
239  * as second step for CreateAndGo.
240  *
241  * \param tp	transport port
242  *
243  * \return SNMP error code
244  */
245 static int
246 inet_activate(struct tport *tp)
247 {
248 	struct inet_port *port = (struct inet_port *)tp;
249 
250 	return (port->activate(port));
251 }
252 
253 /*
254  * Close the SNMP port if it is open and destroy it.
255  *
256  * \param tp	port to close
257  */
258 static void
259 inet_destroy_port(struct tport *tp)
260 {
261 	struct inet_port *port = (struct inet_port *)tp;
262 
263 	deactivate_port(port);
264 
265 	trans_remove_port(tp);
266 
267 	free(port->dns_addr);
268 	free(port);
269 }
270 
271 /**
272  * If the input struct has no buffer allocated yet, do it now. If allocation
273  * fails, read the data into a local buffer and drop it.
274  *
275  * \param pi	input struct
276  *
277  * \return -1 if allocation fails, 0 otherwise
278  */
279 static int
280 inet_alloc_buf(struct port_input *pi)
281 {
282 	char drop_buf[2000];
283 
284 	if (pi->buf == NULL) {
285 		if ((pi->buf = buf_alloc(0)) == NULL) {
286 			(void)recvfrom(pi->fd, drop_buf, sizeof(drop_buf),
287 			    0, NULL, NULL);
288 			return (-1);
289 		}
290 		pi->buflen = buf_size(0);
291 	}
292 	return (0);
293 }
294 
295 /**
296  * Read message into input buffer. Get also the source address and any
297  * control data that is available. If the message is truncated, increment
298  * corresponding statistics.
299  *
300  * \param pi	input object
301  * \param msg	message object to fill
302  * \param cbuf	control data buffer
303  *
304  * \return -1 when something goes wrong, 0 othersise
305  */
306 static int
307 inet_read_msg(struct port_input *pi, struct msghdr *msg, char *cbuf)
308 {
309 	struct iovec iov[1];
310 
311 	iov[0].iov_base = pi->buf;
312 	iov[0].iov_len = pi->buflen;
313 
314 	msg->msg_name = pi->peer;
315 	msg->msg_namelen = pi->peerlen;
316 	msg->msg_iov = iov;
317 	msg->msg_iovlen = 1;
318 	msg->msg_control = cbuf;
319 	msg->msg_controllen = RECV_CBUF_SIZE;
320 	msg->msg_flags = 0;
321 
322 	memset(cbuf, 0, RECV_CBUF_SIZE);
323 
324 	const ssize_t len = recvmsg(pi->fd, msg, 0);
325 
326 	if (len == -1 || len == 0)
327 		/* receive error */
328 		return (-1);
329 
330 	if (msg->msg_flags & MSG_TRUNC) {
331 		/* truncated - drop */
332 		snmpd_stats.silentDrops++;
333 		snmpd_stats.inTooLong++;
334 		return (-1);
335 	}
336 
337 	pi->length = (size_t)len;
338 
339 	return (0);
340 }
341 
342 /*
343  * Input available on socket.
344  *
345  * \param tp	transport port
346  * \param pi	input struct
347  *
348  * \return number of bytes received
349  */
350 static ssize_t
351 inet_recv(struct tport *tp, struct port_input *pi)
352 {
353 	struct inet_port *port = __containerof(tp, struct inet_port, tport);
354 	struct port_sock *sock = __containerof(pi, struct port_sock, input);
355 
356 	assert(port->proto == BegemotSnmpdTransportProto_udp);
357 
358 	if (inet_alloc_buf(pi) == -1)
359 		return (-1);
360 
361 	char cbuf[RECV_CBUF_SIZE];
362 	struct msghdr msg;
363 
364 	if (inet_read_msg(pi, &msg, cbuf) == -1)
365 		return (-1);
366 
367 	sock->parse_ctrl(sock, &msg);
368 
369 	return (0);
370 }
371 
372 /*
373  * Send message.
374  *
375  * \param tp		port
376  * \param buf		data to send
377  * \param len		number of bytes to send
378  * \param addr		destination address
379  * \param addlen	destination address length
380  *
381  * \return number of bytes sent
382  */
383 static ssize_t
384 inet_send2(struct tport *tp, const u_char *buf, size_t len,
385     struct port_input *pi)
386 {
387 	struct inet_port *p = __containerof(tp, struct inet_port, tport);
388 	struct port_sock *s = (pi == NULL) ?  TAILQ_FIRST(&p->socks) :
389 	    __containerof(pi, struct port_sock, input);
390 
391 	struct iovec iov;
392 
393 	iov.iov_base = __DECONST(void*, buf);
394 	iov.iov_len = len;
395 
396 	struct msghdr msg;
397 
398 	msg.msg_flags = 0;
399 	msg.msg_iov = &iov;
400 	msg.msg_iovlen = 1;
401 	msg.msg_name = (void *)pi->peer;
402 	msg.msg_namelen = pi->peerlen;
403 
404 	msg.msg_control = NULL;
405 	msg.msg_controllen = 0;
406 
407 	char cbuf[XMIT_CBUF_SIZE];
408 	if (s->set_ret_source) {
409 		msg.msg_control = cbuf;
410 		s->setsrc(s, &msg);
411 	}
412 
413 	return (sendmsg(s->input.fd, &msg, 0));
414 }
415 
416 /** exported to daemon */
417 const struct transport_def inet_trans = {
418 	"inet",
419 	OIDX_begemotSnmpdTransInet,
420 	inet_start,
421 	inet_stop,
422 	inet_destroy_port,
423 	inet_activate,
424 	NULL,
425 	inet_recv,
426 	inet_send2,
427 };
428 
429 struct inet_port_params {
430 	/** index oid */
431 	struct asn_oid index;
432 
433 	/** internet address type */
434 	enum InetAddressType type;
435 
436 	/** internet address */
437 	u_char *addr;
438 
439 	/** length of address */
440 	size_t addr_len;
441 
442 	/** port number */
443 	uint32_t port;
444 
445 	/** protocol */
446 	enum BegemotSnmpdTransportProto proto;
447 };
448 
449 /**
450  * IPv4 creation stuff. Parse the index, fill socket address and creates
451  * a port_sock.
452  *
453  * \param port		the port to create
454  * \param params	parameters from the SNMP SET
455  *
456  * \return SNMP error
457  */
458 static int
459 ipv4_create(struct inet_port *port, struct inet_port_params *params)
460 {
461 
462 	if (params->addr_len != 4)
463 		return (SNMP_ERR_INCONS_VALUE);
464 
465 	struct port_sock *sock = calloc(1, sizeof(struct port_sock));
466 	if (sock == NULL)
467 		return (SNMP_ERR_GENERR);
468 
469 	snmpd_input_init(&sock->input);
470 
471 	TAILQ_INSERT_HEAD(&port->socks, sock, link);
472 
473 	struct sockaddr_in *sin =
474 	    (struct sockaddr_in *)&sock->bind_addr;
475 
476 	sin->sin_len = sizeof(struct sockaddr_in);
477 	sin->sin_family = AF_INET;
478 	sin->sin_port = htons(params->port);
479 	memcpy(&sin->sin_addr, params->addr, 4); /* network byte order */
480 
481 	sock->port = port;
482 
483 	return (SNMP_ERR_NOERROR);
484 }
485 
486 /*
487  * An IPv4 inet port is ready. Delegate to the generic code to read the data
488  * and react.
489  *
490  * \param fd	file descriptor that is ready
491  * \param udata	inet_port pointer
492  */
493 static void
494 ipv4_input(int fd __unused, void *udata)
495 {
496 	struct port_sock *sock = udata;
497 
498 	sock->input.peerlen = sizeof(struct sockaddr_in);
499 	snmpd_input(&sock->input, &sock->port->tport);
500 }
501 
502 /**
503  * Activate an IPv4 socket.
504  *
505  * \param sock	thhe socket to activate
506  *
507  * \return error code
508  */
509 static int
510 ipv4_activate_sock(struct port_sock *sock)
511 {
512 	if ((sock->input.fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
513 		syslog(LOG_ERR, "creating UDP4 socket: %m");
514 		return (SNMP_ERR_RES_UNAVAIL);
515 	}
516 
517 	const struct sockaddr_in *sin =
518 	    (const struct sockaddr_in *)&sock->bind_addr;
519 
520 	if (sin->sin_addr.s_addr == INADDR_ANY) {
521 		/* need to know from which address to return */
522 		static const int on = 1;
523 
524 		if (setsockopt(sock->input.fd, IPPROTO_IP, IP_RECVDSTADDR, &on,
525 		    sizeof(on)) == -1) {
526 			syslog(LOG_ERR, "setsockopt(IP_RECVDSTADDR): %m");
527 			(void)close(sock->input.fd);
528 			sock->input.fd = -1;
529 			return (SNMP_ERR_GENERR);
530 		}
531 		sock->set_ret_source = true;
532 	}
533 
534 	if (bind(sock->input.fd, (const struct sockaddr *)sin, sizeof(*sin))) {
535 		if (errno == EADDRNOTAVAIL) {
536 			(void)close(sock->input.fd);
537 			sock->input.fd = -1;
538 			return (SNMP_ERR_INCONS_NAME);
539 		}
540 		syslog(LOG_ERR, "bind: %s:%u %m", inet_ntoa(sin->sin_addr),
541 		    ntohs(sin->sin_port));
542 		(void)close(sock->input.fd);
543 		sock->input.fd = -1;
544 		return (SNMP_ERR_GENERR);
545 	}
546 
547 	if ((sock->input.id = fd_select(sock->input.fd, ipv4_input,
548 	    sock, NULL)) == NULL) {
549 		(void)close(sock->input.fd);
550 		sock->input.fd = -1;
551 		return (SNMP_ERR_GENERR);
552 	}
553 	sock->input.peer = (struct sockaddr *)&sock->ret_dest;
554 
555 	sock->parse_ctrl = ipv4_parse_ctrl;
556 	sock->setsrc = ipv4_setsrc;
557 
558 	return (SNMP_ERR_NOERROR);
559 }
560 
561 /**
562  * Open an IPv4 socket. Make the socket, bind it and put it on the select
563  * list. The socket struct has already been created during creation.
564  *
565  * \param p	inet port
566  *
567  * \return SNMP error code
568  */
569 static int
570 ipv4_activate(struct inet_port *p)
571 {
572 	struct port_sock *sock = TAILQ_FIRST(&p->socks);
573 	assert(sock);
574 	assert(!TAILQ_NEXT(sock, link));
575 
576 	const int ret = ipv4_activate_sock(sock);
577 	if (ret == SNMP_ERR_NOERROR)
578 		p->row_status = RowStatus_active;
579 
580 	return (ret);
581 }
582 
583 /**
584  * Close an IPv4 socket. Keep the sock object.
585  *
586  * \param p	inet port
587  */
588 static void
589 ipv4_deactivate(struct inet_port *p)
590 {
591 	struct port_sock *sock = TAILQ_FIRST(&p->socks);
592 	assert(sock);
593 	assert(!TAILQ_NEXT(sock, link));
594 
595 	snmpd_input_close(&sock->input);
596 
597 	p->row_status = RowStatus_notInService;
598 }
599 
600 /**
601  * Parse the control data received with a UDPv4 packet. This may contain
602  * credentials (for a local connection) and the address of the interface
603  * the message was received on. If there are credentials set the priv flag
604  * if the effective UID is zero.
605  *
606  * \param sock	the sock object
607  * \param msg	the received message
608  */
609 static void
610 ipv4_parse_ctrl(struct port_sock *sock, const struct msghdr *msg)
611 {
612 	struct sockcred *cred = NULL;
613 
614 	for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
615 	    cmsg = CMSG_NXTHDR(msg, cmsg)) {
616 
617 		if (cmsg->cmsg_level == IPPROTO_IP &&
618 		    cmsg->cmsg_type == IP_RECVDSTADDR) {
619 			memcpy(&sock->ret_source.a4, CMSG_DATA(cmsg),
620 			    sizeof(struct in_addr));
621 
622 		} else if (cmsg->cmsg_level == SOL_SOCKET &&
623 		    cmsg->cmsg_type == SCM_CREDS) {
624 			cred = (struct sockcred *)(void *)CMSG_DATA(cmsg);
625 		}
626 	}
627 
628 	sock->input.priv = 0;
629 	if (sock->input.cred && cred)
630 		/* remote end has sent credentials */
631 		sock->input.priv = (cred->sc_euid == 0);
632 }
633 
634 /**
635  * Set the source address option for IPv4 sockets.
636  *
637  * \param sock	socket object
638  * \param msg	message
639  */
640 static void
641 ipv4_setsrc(struct port_sock *sock, struct msghdr *msg)
642 {
643 	struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
644 
645 	/* select outgoing interface by setting source address */
646 	cmsg->cmsg_level = IPPROTO_IP;
647 	cmsg->cmsg_type = IP_SENDSRCADDR;
648 	cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
649 	memcpy(CMSG_DATA(cmsg), &sock->ret_source.a4,
650 	    sizeof(struct in_addr));
651 
652 	msg->msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
653 }
654 
655 /**
656  * Common part of IPv6 creation. This is used by both ipv6_create() and
657  * ipv6z_create().
658  *
659  * \param port		the table row
660  * \param params	creation parameters
661  * \param scope_id	scope_id (0 or from index)
662  *
663  * \return SNMP_ERR_NOERROR if port has been created, error code otherwise
664  */
665 static int
666 ipv6_create_common(struct inet_port *port, struct inet_port_params *params,
667     u_int scope_id)
668 {
669 	struct port_sock *sock = calloc(1, sizeof(struct port_sock));
670 
671 	if (sock == NULL)
672 		return (SNMP_ERR_GENERR);
673 
674 	struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&sock->bind_addr;
675 
676 	sin->sin6_len = sizeof(struct sockaddr_in6);
677 	sin->sin6_family = AF_INET6;
678 	sin->sin6_port = htons(params->port);
679 	sin->sin6_flowinfo = 0;
680 	sin->sin6_scope_id = scope_id;
681 
682 	memcpy(sin->sin6_addr.s6_addr, params->addr, 16);
683 
684 	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr) && scope_id == 0) {
685 		char buf[INET6_ADDRSTRLEN];
686 		syslog(LOG_INFO, "%s: link local address used without scope "
687 		    "index: %s", __func__, inet_ntop(AF_INET6,
688 		    &sin->sin6_addr, buf, sizeof(buf)));
689 		free(sock);
690 		return (SNMP_ERR_NO_CREATION);
691 	}
692 
693 	sock->port = port;
694 
695 	snmpd_input_init(&sock->input);
696 	TAILQ_INSERT_HEAD(&port->socks, sock, link);
697 
698 	return (SNMP_ERR_NOERROR);
699 }
700 
701 /**
702  * IPv6 creation stuff. Parse the index, fill socket address and creates
703  * a port_sock.
704  *
705  * \param port		the port to create
706  * \param params	parameters from the SNMP SET
707  *
708  * \return SNMP error
709  */
710 static int
711 ipv6_create(struct inet_port *port, struct inet_port_params *params)
712 {
713 	if (params->addr_len != 16)
714 		return (SNMP_ERR_INCONS_VALUE);
715 
716 	const int ret = ipv6_create_common(port, params, 0);
717 	if (ret != SNMP_ERR_NOERROR)
718 		return (ret);
719 
720 	return (SNMP_ERR_NOERROR);
721 }
722 
723 /*
724  * An IPv6 inet port is ready. Delegate to the generic code to read the data
725  * and react.
726  *
727  * \param fd	file descriptor that is ready
728  * \param udata	inet_port pointer
729  */
730 static void
731 ipv6_input(int fd __unused, void *udata)
732 {
733 	struct port_sock *sock = udata;
734 
735 	sock->input.peerlen = sizeof(struct sockaddr_in6);
736 	snmpd_input(&sock->input, &sock->port->tport);
737 }
738 
739 /**
740  * Activate an IPv6 socket.
741  *
742  * \param sock	thhe socket to activate
743  *
744  * \return error code
745  */
746 static int
747 ipv6_activate_sock(struct port_sock *sock)
748 {
749 	if ((sock->input.fd = socket(PF_INET6, SOCK_DGRAM, 0)) == -1) {
750 		syslog(LOG_ERR, "creating UDP6 socket: %m");
751 		return (SNMP_ERR_RES_UNAVAIL);
752 	}
753 
754 	const struct sockaddr_in6 *sin =
755 	    (const struct sockaddr_in6 *)&sock->bind_addr;
756 
757 	if (memcmp(&sin->sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0) {
758 		/* need to know from which address to return */
759 		static const int on = 1;
760 
761 		if (setsockopt(sock->input.fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
762 		    &on, sizeof(on)) == -1) {
763 			syslog(LOG_ERR, "setsockopt(IP6_PKTINFO): %m");
764 			(void)close(sock->input.fd);
765 			sock->input.fd = -1;
766 			return (SNMP_ERR_GENERR);
767 		}
768 		sock->set_ret_source = true;
769 	}
770 
771 	if (bind(sock->input.fd, (const struct sockaddr *)sin, sizeof(*sin))) {
772 		if (community != COMM_INITIALIZE && errno == EADDRNOTAVAIL) {
773 			(void)close(sock->input.fd);
774 			sock->input.fd = -1;
775 			return (SNMP_ERR_INCONS_NAME);
776 		}
777 		char buf[INET6_ADDRSTRLEN];
778 		syslog(LOG_ERR, "bind: %s:%u:%u %m", inet_ntop(AF_INET6,
779 		    &sin->sin6_addr, buf, sizeof(buf)), sin->sin6_scope_id,
780 		    ntohs(sin->sin6_port));
781 		(void)close(sock->input.fd);
782 		sock->input.fd = -1;
783 		return (SNMP_ERR_GENERR);
784 	}
785 	if ((sock->input.id = fd_select(sock->input.fd, ipv6_input,
786 	    sock, NULL)) == NULL) {
787 		(void)close(sock->input.fd);
788 		sock->input.fd = -1;
789 		return (SNMP_ERR_GENERR);
790 	}
791 	sock->input.peer = (struct sockaddr *)&sock->ret_dest;
792 
793 	sock->parse_ctrl = ipv6_parse_ctrl;
794 	sock->setsrc = ipv6_setsrc;
795 
796 	return (SNMP_ERR_NOERROR);
797 }
798 
799 /**
800  * Open an IPv6 socket.
801  *
802  * \param port	inet port
803  *
804  * \return SNMP error code
805  */
806 static int
807 ipv6_activate(struct inet_port *p)
808 {
809 	struct port_sock *sock = TAILQ_FIRST(&p->socks);
810 	assert(sock);
811 
812 	const int ret = ipv6_activate_sock(sock);
813 
814 	if (ret == SNMP_ERR_NOERROR)
815 		p->row_status = RowStatus_active;
816 	return (ret);
817 }
818 
819 /**
820  * Close an IPv6 socket. Keep the sock object.
821  *
822  * \param p	inet port
823  */
824 static void
825 ipv6_deactivate(struct inet_port *p)
826 {
827 	struct port_sock *sock = TAILQ_FIRST(&p->socks);
828 	assert(sock);
829 	assert(!TAILQ_NEXT(sock, link));
830 
831 	snmpd_input_close(&sock->input);
832 
833 	p->row_status = RowStatus_notInService;
834 }
835 
836 /**
837  * IPv6 specific part of message processing. The control data may contain
838  * credentials and packet info that contains the destination address of
839  * the packet.
840  *
841  * \param sock	the sock object
842  * \param msg	the received message
843  */
844 static void
845 ipv6_parse_ctrl(struct port_sock *sock, const struct msghdr *msg)
846 {
847 	struct sockcred *cred = NULL;
848 
849 	for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
850 	    cmsg = CMSG_NXTHDR(msg, cmsg)) {
851 
852 		if (cmsg->cmsg_level == IPPROTO_IPV6 &&
853 		    cmsg->cmsg_type == IPV6_PKTINFO) {
854 			const struct in6_pktinfo *info =
855 			    (const struct in6_pktinfo *)(const void *)
856 			    CMSG_DATA(cmsg);
857 			sock->ret_source.a6.ipi6_addr = info->ipi6_addr;
858 			sock->ret_source.a6.ipi6_ifindex =
859 			    !IN6_IS_ADDR_LINKLOCAL(&info->ipi6_addr) ? 0:
860 			    info->ipi6_ifindex;
861 		} else if (cmsg->cmsg_level == SOL_SOCKET &&
862 		    cmsg->cmsg_type == SCM_CREDS) {
863 			cred = (struct sockcred *)(void *)CMSG_DATA(cmsg);
864 		}
865 	}
866 
867 	sock->input.priv = 0;
868 	if (sock->input.cred && cred)
869 		/* remote end has sent credentials */
870 		sock->input.priv = (cred->sc_euid == 0);
871 }
872 
873 /**
874  * Set the source address option for IPv4 sockets.
875  *
876  * \param sock	socket object
877  * \param msg	message
878  */
879 static void
880 ipv6_setsrc(struct port_sock *sock, struct msghdr *msg)
881 {
882 	struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
883 
884 	/* select outgoing interface by setting source address */
885 	cmsg->cmsg_level = IPPROTO_IPV6;
886 	cmsg->cmsg_type = IPV6_PKTINFO;
887 	cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
888 	memcpy(CMSG_DATA(cmsg), &sock->ret_source.a6,
889 	    sizeof(struct in6_pktinfo));
890 
891 	msg->msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
892 }
893 
894 /**
895  * IPv6z creation stuff. Parse the index, fill socket address and creates
896  * a port_sock.
897  *
898  * \param port		the port to create
899  * \param params	parameters from the SNMP SET
900  *
901  * \return SNMP error
902  */
903 static int
904 ipv6z_create(struct inet_port *port, struct inet_port_params *params)
905 {
906 	if (params->addr_len != 20)
907 		return (SNMP_ERR_INCONS_VALUE);
908 
909 	u_int scope_id = 0;
910 	for (u_int i = 16; i < 20; i++) {
911 		scope_id <<= 8;
912 		scope_id |= params->addr[i];
913 	}
914 
915 	const int ret = ipv6_create_common(port, params, scope_id);
916 	if (ret != SNMP_ERR_NOERROR)
917 		return (ret);
918 
919 	return (SNMP_ERR_NOERROR);
920 }
921 
922 /**
923  * DNS name creation stuff. Parse the index and save the string.
924  * This does not create a socket struct.
925  *
926  * \param port		the port to create
927  * \param params	parameters from the SNMP SET
928  *
929  * \return SNMP error
930  */
931 static int
932 dns_create(struct inet_port *port, struct inet_port_params *params)
933 {
934 	if (params->addr_len > 64)
935 		return (SNMP_ERR_INCONS_VALUE);
936 
937 	if (strnlen(params->addr, params->addr_len) !=
938 	    params->addr_len)
939 		return (SNMP_ERR_INCONS_VALUE);
940 
941 	if ((port->dns_addr = realloc(params->addr,
942 	    params->addr_len + 1)) == NULL)
943 		return (SNMP_ERR_GENERR);
944 
945 	port->dns_addr[params->addr_len] = '\0';
946 	params->addr = NULL;
947 
948 	port->dns_port = htons(params->port);
949 
950 	return (SNMP_ERR_NOERROR);
951 }
952 
953 /**
954  * Open sockets. This loops through all the addresses returned by getaddrinfo
955  * and opens a socket for each of them.
956  *
957  * \param port	inet port
958  *
959  * \return SNMP error code
960  */
961 static int
962 dns_activate(struct inet_port *port)
963 {
964 	struct addrinfo hints;
965 	memset(&hints, 0, sizeof(hints));
966 	hints.ai_family = AF_UNSPEC;
967 	hints.ai_socktype = SOCK_DGRAM;		// XXX udp-only
968 	hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE | AI_NUMERICSERV;
969 
970 	char portbuf[8];
971 	sprintf(portbuf, "%hu", ntohs(port->dns_port));
972 
973 	struct addrinfo *res0;
974 	int error = getaddrinfo(port->dns_addr[0] == '\0'
975 	    ? NULL : port->dns_addr,
976 	    portbuf, &hints, &res0);
977 
978 	if (error) {
979 		syslog(LOG_ERR, "cannot resolve address '%s': %s",
980 		    port->dns_addr, gai_strerror(error));
981 		return (SNMP_ERR_GENERR);
982 	}
983 
984 	for (struct addrinfo *res = res0; res != NULL; res = res->ai_next) {
985 		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
986 			continue;
987 
988 		struct port_sock *sock = calloc(1, sizeof(struct port_sock));
989 		if (sock == NULL)
990 			return (SNMP_ERR_GENERR);
991 
992 		snmpd_input_init(&sock->input);
993 		sock->port = port;
994 
995 		int ret = SNMP_ERR_NOERROR;
996 
997 		if (res->ai_family == AF_INET) {
998 			*(struct sockaddr_in *)&sock->bind_addr =
999 			    *(struct sockaddr_in *)(void *)res->ai_addr;
1000 			ret = ipv4_activate_sock(sock);
1001 		} else {
1002 			*(struct sockaddr_in6 *)&sock->bind_addr =
1003 			    *(struct sockaddr_in6 *)(void *)res->ai_addr;
1004 			ret = ipv6_activate_sock(sock);
1005 		}
1006 
1007 		if (ret != SNMP_ERR_NOERROR)
1008 			free(sock);
1009 		else
1010 			TAILQ_INSERT_HEAD(&port->socks, sock, link);
1011 	}
1012 
1013 	if (!TAILQ_EMPTY(&port->socks))
1014 		port->row_status = RowStatus_active;
1015 
1016 	freeaddrinfo(res0);
1017 	return (SNMP_ERR_GENERR);
1018 }
1019 
1020 /**
1021  * Deactive the socket. Close all open sockets and delete all sock objects.
1022  *
1023  * \param port	inet port
1024  */
1025 static void
1026 dns_deactivate(struct inet_port *port)
1027 {
1028 	while (!TAILQ_EMPTY(&port->socks)) {
1029 		struct port_sock *sock = TAILQ_FIRST(&port->socks);
1030 		TAILQ_REMOVE(&port->socks, sock, link);
1031 		snmpd_input_close(&sock->input);
1032 		free(sock);
1033 	}
1034 	port->row_status = RowStatus_notInService;
1035 }
1036 
1037 static int
1038 inet_create(struct inet_port_params *params, struct inet_port **pp)
1039 {
1040 	int err = SNMP_ERR_NOERROR;
1041 	struct inet_port *port = NULL;
1042 
1043 	if (params->port > 0xffff) {
1044 		err = SNMP_ERR_NO_CREATION;
1045 		goto fail;
1046 	}
1047 
1048 	if ((port = malloc(sizeof(*port))) == NULL) {
1049 		err =  SNMP_ERR_GENERR;
1050 		goto fail;
1051 	}
1052 	memset(port, 0, sizeof(*port));
1053 	TAILQ_INIT(&port->socks);
1054 
1055 	port->proto = params->proto;
1056 	port->tport.index = params->index;
1057 
1058 	switch (params->type) {
1059 
1060 	  case InetAddressType_ipv4:
1061 		port->create = ipv4_create;
1062 		port->activate = ipv4_activate;
1063 		port->deactivate = ipv4_deactivate;
1064 		break;
1065 
1066 	  case InetAddressType_ipv6:
1067 		port->create = ipv6_create;
1068 		port->activate = ipv6_activate;
1069 		port->deactivate = ipv6_deactivate;
1070 		break;
1071 
1072 	  case InetAddressType_ipv6z:
1073 		port->create = ipv6z_create;
1074 		port->activate = ipv6_activate;
1075 		port->deactivate = ipv6_deactivate;
1076 		break;
1077 
1078 	  case InetAddressType_dns:
1079 		port->create = dns_create;
1080 		port->activate = dns_activate;
1081 		port->deactivate = dns_deactivate;
1082 		break;
1083 
1084 	  default:
1085 		err = SNMP_ERR_NO_CREATION;
1086 		goto fail;
1087 	}
1088 
1089 	if ((err = port->create(port, params)) != SNMP_ERR_NOERROR)
1090 		goto fail;
1091 
1092 	*pp = port;
1093 	trans_insert_port(my_trans, &port->tport);
1094 	return (err);
1095 
1096 fail:
1097 	free(port->dns_addr);
1098 	free(port);
1099 	return (err);
1100 }
1101 
1102 static int
1103 create_and_go(struct snmp_context *ctx, struct inet_port_params *params)
1104 {
1105 	int err;
1106 	struct inet_port *port;
1107 
1108 	if ((err = inet_create(params, &port)) != SNMP_ERR_NOERROR)
1109 		return (err);
1110 
1111 	port->row_status = RowStatus_createAndGo;
1112 	ctx->scratch->ptr1 = port;
1113 
1114 	if (community == COMM_INITIALIZE)
1115 		return (err);
1116 
1117 	return (inet_activate(&port->tport));
1118 }
1119 
1120 static int
1121 create_and_wait(struct snmp_context *ctx, struct inet_port_params *params)
1122 {
1123 	int err;
1124 	struct inet_port *port;
1125 
1126 	if ((err = inet_create(params, &port)) != SNMP_ERR_NOERROR)
1127 		return (err);
1128 
1129 	port->row_status = RowStatus_createAndWait;
1130 	ctx->scratch->ptr1 = port;
1131 
1132 	return (err);
1133 }
1134 
1135 /**
1136  * This is called to set a RowStatus value in the port table during
1137  * SET processing.
1138  *
1139  * When this is called during initialization time and the RowStatus is set
1140  * to CreateAndGo, the port is actually not activated. This is done when
1141  * the main code calls the init() for all ports later.
1142  */
1143 static int
1144 inet_port_set(struct snmp_context *ctx, struct inet_port *port,
1145     struct inet_port_params *params, enum RowStatus nstatus)
1146 {
1147 	switch (nstatus) {
1148 
1149 	  case RowStatus_createAndGo:
1150 		if (port != NULL)
1151 			return (SNMP_ERR_INCONS_VALUE);
1152 		ctx->scratch->int1 = SET_CREATED;
1153 		return (create_and_go(ctx, params));
1154 
1155 	  case RowStatus_createAndWait:
1156 		if (port != NULL)
1157 			return (SNMP_ERR_INCONS_VALUE);
1158 		ctx->scratch->int1 = SET_CREATED;
1159 		return (create_and_wait(ctx, params));
1160 
1161 	  case RowStatus_active:
1162 		if (port == NULL)
1163 			return (SNMP_ERR_INCONS_VALUE);
1164 
1165 		switch (port->row_status) {
1166 
1167 		  case RowStatus_notReady:
1168 			/* this can not happend */
1169 			abort();
1170 
1171 		  case RowStatus_notInService:
1172 			ctx->scratch->int1 = SET_ACTIVATED;
1173 			return (inet_activate(&port->tport));
1174 
1175 		  case RowStatus_active:
1176 			return (SNMP_ERR_NOERROR);
1177 
1178 		  case RowStatus_createAndGo:
1179 		  case RowStatus_createAndWait:
1180 		  case RowStatus_destroy:
1181 			abort();
1182 		}
1183 		break;
1184 
1185 	  case RowStatus_notInService:
1186 		if (port == NULL)
1187 			return (SNMP_ERR_INCONS_VALUE);
1188 
1189 		switch (port->row_status) {
1190 
1191 		  case RowStatus_notReady:
1192 			/* this can not happend */
1193 			abort();
1194 
1195 		  case RowStatus_notInService:
1196 			return (SNMP_ERR_NOERROR);
1197 
1198 		  case RowStatus_active:
1199 			/* this is done during commit */
1200 			ctx->scratch->int1 = SET_DEACTIVATE;
1201 			return (SNMP_ERR_NOERROR);
1202 
1203 		  case RowStatus_createAndGo:
1204 		  case RowStatus_createAndWait:
1205 		  case RowStatus_destroy:
1206 			abort();
1207 		}
1208 		break;
1209 
1210 	  case RowStatus_destroy:
1211 		/* this is done during commit */
1212 		ctx->scratch->int1 = SET_DESTROY;
1213 		return (SNMP_ERR_NOERROR);
1214 
1215 	  case RowStatus_notReady:
1216 		return (SNMP_ERR_WRONG_VALUE);
1217 	}
1218 	abort();
1219 }
1220 
1221 /*
1222  * Port table
1223  */
1224 int
1225 op_snmp_trans_inet(struct snmp_context *ctx, struct snmp_value *value,
1226     u_int sub, u_int iidx __unused, enum snmp_op op)
1227 {
1228 	asn_subid_t which = value->var.subs[sub - 1];
1229 	struct inet_port *port;
1230 	struct inet_port_params params;
1231 	int ret;
1232 
1233 	switch (op) {
1234 
1235 	  case SNMP_OP_GETNEXT:
1236 		if ((port = (struct inet_port *)trans_next_port(my_trans,
1237 		    &value->var, sub)) == NULL)
1238 			return (SNMP_ERR_NOSUCHNAME);
1239 		index_append(&value->var, sub, &port->tport.index);
1240 		goto fetch;
1241 
1242 	  case SNMP_OP_GET:
1243 		if ((port = (struct inet_port *)trans_find_port(my_trans,
1244 		    &value->var, sub)) == NULL)
1245 			return (SNMP_ERR_NOSUCHNAME);
1246 		goto fetch;
1247 
1248 	  case SNMP_OP_SET:
1249 		port = (struct inet_port *)trans_find_port(my_trans,
1250 		    &value->var, sub);
1251 
1252 		if (which != LEAF_begemotSnmpdTransInetStatus)
1253 			abort();
1254 		if (!isok_RowStatus(value->v.integer))
1255 			return (SNMP_ERR_WRONG_VALUE);
1256 
1257 		if (index_decode(&value->var, sub, iidx, &params.type,
1258 		    &params.addr, &params.addr_len, &params.port,
1259 		    &params.proto))
1260 			return (SNMP_ERR_NO_CREATION);
1261 
1262 		asn_slice_oid(&params.index, &value->var, sub, value->var.len);
1263 
1264 		ret = inet_port_set(ctx, port, &params,
1265 		    (enum RowStatus)value->v.integer);
1266 
1267 		free(params.addr);
1268 		return (ret);
1269 
1270 	  case SNMP_OP_ROLLBACK:
1271 		if ((port = (struct inet_port *)trans_find_port(my_trans,
1272 		    &value->var, sub)) == NULL)
1273 			/* cannot happen */
1274 			abort();
1275 
1276 		switch (ctx->scratch->int1) {
1277 
1278 		  case SET_CREATED:
1279 			/* newly created */
1280 			assert(port != NULL);
1281 			inet_destroy_port(&port->tport);
1282 			return (SNMP_ERR_NOERROR);
1283 
1284 		  case SET_DESTROY:
1285 			/* do it now */
1286 			assert(port != NULL);
1287 			return (SNMP_ERR_NOERROR);
1288 
1289 		  case SET_ACTIVATED:
1290 			deactivate_port(port);
1291 			return (SNMP_ERR_NOERROR);
1292 
1293 		  case SET_DEACTIVATE:
1294 			return (SNMP_ERR_NOERROR);
1295 		}
1296 		abort();
1297 
1298 	  case SNMP_OP_COMMIT:
1299 		if ((port = (struct inet_port *)trans_find_port(my_trans,
1300 		    &value->var, sub)) == NULL)
1301 			/* cannot happen */
1302 			abort();
1303 
1304 		switch (ctx->scratch->int1) {
1305 
1306 		  case SET_CREATED:
1307 			/* newly created */
1308 			assert(port != NULL);
1309 			return (SNMP_ERR_NOERROR);
1310 
1311 		  case SET_DESTROY:
1312 			/* do it now */
1313 			assert(port != NULL);
1314 			inet_destroy_port(&port->tport);
1315 			return (SNMP_ERR_NOERROR);
1316 
1317 		  case SET_ACTIVATED:
1318 			return (SNMP_ERR_NOERROR);
1319 
1320 		  case SET_DEACTIVATE:
1321 			deactivate_port(port);
1322 			return (SNMP_ERR_NOERROR);
1323 		}
1324 		abort();
1325 	}
1326 	abort();
1327 
1328   fetch:
1329 	switch (which) {
1330 
1331 	  case LEAF_begemotSnmpdTransInetStatus:
1332 		value->v.integer = port->row_status;
1333 		break;
1334 
1335 	  default:
1336 		abort();
1337 	}
1338 
1339 	return (SNMP_ERR_NOERROR);
1340 }
1341