Home | History | Annotate | Line # | Download | only in npf
npf_conn.c revision 1.25
      1   1.1     rmind /*-
      2  1.15     rmind  * Copyright (c) 2014-2015 Mindaugas Rasiukevicius <rmind at netbsd org>
      3   1.1     rmind  * Copyright (c) 2010-2014 The NetBSD Foundation, Inc.
      4   1.1     rmind  * All rights reserved.
      5   1.1     rmind  *
      6   1.1     rmind  * This material is based upon work partially supported by The
      7   1.1     rmind  * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
      8   1.1     rmind  *
      9   1.1     rmind  * Redistribution and use in source and binary forms, with or without
     10   1.1     rmind  * modification, are permitted provided that the following conditions
     11   1.1     rmind  * are met:
     12   1.1     rmind  * 1. Redistributions of source code must retain the above copyright
     13   1.1     rmind  *    notice, this list of conditions and the following disclaimer.
     14   1.1     rmind  * 2. Redistributions in binary form must reproduce the above copyright
     15   1.1     rmind  *    notice, this list of conditions and the following disclaimer in the
     16   1.1     rmind  *    documentation and/or other materials provided with the distribution.
     17   1.1     rmind  *
     18   1.1     rmind  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     19   1.1     rmind  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     20   1.1     rmind  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     21   1.1     rmind  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     22   1.1     rmind  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     23   1.1     rmind  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     24   1.1     rmind  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     25   1.1     rmind  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     26   1.1     rmind  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     27   1.1     rmind  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     28   1.1     rmind  * POSSIBILITY OF SUCH DAMAGE.
     29   1.1     rmind  */
     30   1.1     rmind 
     31   1.1     rmind /*
     32   1.1     rmind  * NPF connection tracking for stateful filtering and translation.
     33   1.1     rmind  *
     34   1.1     rmind  * Overview
     35   1.1     rmind  *
     36   1.1     rmind  *	Connection direction is identified by the direction of its first
     37   1.1     rmind  *	packet.  Packets can be incoming or outgoing with respect to an
     38   1.1     rmind  *	interface.  To describe the packet in the context of connection
     39   1.1     rmind  *	direction we will use the terms "forwards stream" and "backwards
     40   1.1     rmind  *	stream".  All connections have two keys and thus two entries:
     41   1.1     rmind  *
     42   1.1     rmind  *		npf_conn_t::c_forw_entry for the forwards stream and
     43   1.1     rmind  *		npf_conn_t::c_back_entry for the backwards stream.
     44   1.1     rmind  *
     45   1.1     rmind  *	The keys are formed from the 5-tuple (source/destination address,
     46   1.1     rmind  *	source/destination port and the protocol).  Additional matching
     47   1.1     rmind  *	is performed for the interface (a common behaviour is equivalent
     48   1.1     rmind  *	to the 6-tuple lookup including the interface ID).  Note that the
     49   1.1     rmind  *	key may be formed using translated values in a case of NAT.
     50   1.1     rmind  *
     51   1.1     rmind  *	Connections can serve two purposes: for the implicit passing or
     52   1.1     rmind  *	to accommodate the dynamic NAT.  Connections for the former purpose
     53   1.1     rmind  *	are created by the rules with "stateful" attribute and are used for
     54   1.1     rmind  *	stateful filtering.  Such connections indicate that the packet of
     55   1.1     rmind  *	the backwards stream should be passed without inspection of the
     56   1.1     rmind  *	ruleset.  The other purpose is to associate a dynamic NAT mechanism
     57   1.1     rmind  *	with a connection.  Such connections are created by the NAT policies
     58   1.1     rmind  *	and they have a relationship with NAT translation structure via
     59   1.1     rmind  *	npf_conn_t::c_nat.  A single connection can serve both purposes,
     60   1.1     rmind  *	which is a common case.
     61   1.1     rmind  *
     62   1.1     rmind  * Connection life-cycle
     63   1.1     rmind  *
     64   1.1     rmind  *	Connections are established when a packet matches said rule or
     65   1.1     rmind  *	NAT policy.  Both keys of the established connection are inserted
     66   1.1     rmind  *	into the connection database.  A garbage collection thread
     67   1.1     rmind  *	periodically scans all connections and depending on connection
     68   1.1     rmind  *	properties (e.g. last activity time, protocol) removes connection
     69   1.1     rmind  *	entries and expires the actual connections.
     70   1.1     rmind  *
     71   1.1     rmind  *	Each connection has a reference count.  The reference is acquired
     72   1.1     rmind  *	on lookup and should be released by the caller.  It guarantees that
     73   1.1     rmind  *	the connection will not be destroyed, although it may be expired.
     74   1.1     rmind  *
     75   1.1     rmind  * Synchronisation
     76   1.1     rmind  *
     77   1.1     rmind  *	Connection database is accessed in a lock-less manner by the main
     78   1.1     rmind  *	routines: npf_conn_inspect() and npf_conn_establish().  Since they
     79   1.1     rmind  *	are always called from a software interrupt, the database is
     80   1.1     rmind  *	protected using passive serialisation.  The main place which can
     81   1.1     rmind  *	destroy a connection is npf_conn_worker().  The database itself
     82   1.1     rmind  *	can be replaced and destroyed in npf_conn_reload().
     83   1.1     rmind  *
     84   1.1     rmind  * ALG support
     85   1.1     rmind  *
     86   1.1     rmind  *	Application-level gateways (ALGs) can override generic connection
     87   1.1     rmind  *	inspection (npf_alg_conn() call in npf_conn_inspect() function) by
     88   1.1     rmind  *	performing their own lookup using different key.  Recursive call
     89   1.1     rmind  *	to npf_conn_inspect() is not allowed.  The ALGs ought to use the
     90   1.1     rmind  *	npf_conn_lookup() function for this purpose.
     91   1.1     rmind  *
     92   1.1     rmind  * Lock order
     93   1.1     rmind  *
     94   1.6     rmind  *	npf_config_lock ->
     95   1.6     rmind  *		conn_lock ->
     96   1.6     rmind  *			npf_conn_t::c_lock
     97   1.1     rmind  */
     98   1.1     rmind 
     99  1.22  christos #ifdef _KERNEL
    100   1.1     rmind #include <sys/cdefs.h>
    101  1.25     rmind __KERNEL_RCSID(0, "$NetBSD: npf_conn.c,v 1.25 2018/09/29 14:41:36 rmind Exp $");
    102   1.1     rmind 
    103   1.1     rmind #include <sys/param.h>
    104   1.1     rmind #include <sys/types.h>
    105   1.1     rmind 
    106   1.1     rmind #include <netinet/in.h>
    107   1.1     rmind #include <netinet/tcp.h>
    108   1.1     rmind 
    109   1.1     rmind #include <sys/atomic.h>
    110   1.1     rmind #include <sys/condvar.h>
    111   1.1     rmind #include <sys/kmem.h>
    112   1.1     rmind #include <sys/kthread.h>
    113   1.1     rmind #include <sys/mutex.h>
    114   1.1     rmind #include <net/pfil.h>
    115   1.1     rmind #include <sys/pool.h>
    116   1.1     rmind #include <sys/queue.h>
    117   1.1     rmind #include <sys/systm.h>
    118  1.22  christos #endif
    119   1.1     rmind 
    120   1.1     rmind #define __NPF_CONN_PRIVATE
    121   1.1     rmind #include "npf_conn.h"
    122   1.1     rmind #include "npf_impl.h"
    123   1.1     rmind 
    124   1.1     rmind /*
    125   1.1     rmind  * Connection flags: PFIL_IN and PFIL_OUT values are reserved for direction.
    126   1.1     rmind  */
    127   1.1     rmind CTASSERT(PFIL_ALL == (0x001 | 0x002));
    128   1.1     rmind #define	CONN_ACTIVE	0x004	/* visible on inspection */
    129   1.1     rmind #define	CONN_PASS	0x008	/* perform implicit passing */
    130   1.1     rmind #define	CONN_EXPIRE	0x010	/* explicitly expire */
    131   1.1     rmind #define	CONN_REMOVED	0x020	/* "forw/back" entries removed */
    132   1.1     rmind 
    133   1.6     rmind enum { CONN_TRACKING_OFF, CONN_TRACKING_ON };
    134   1.1     rmind 
    135  1.22  christos static void	npf_conn_destroy(npf_t *, npf_conn_t *);
    136  1.25     rmind static nvlist_t *npf_conn_export(npf_t *, const npf_conn_t *);
    137   1.1     rmind 
    138   1.1     rmind /*
    139   1.1     rmind  * npf_conn_sys{init,fini}: initialise/destroy connection tracking.
    140   1.1     rmind  */
    141   1.1     rmind 
    142   1.1     rmind void
    143  1.22  christos npf_conn_init(npf_t *npf, int flags)
    144   1.1     rmind {
    145  1.22  christos 	npf->conn_cache = pool_cache_init(sizeof(npf_conn_t), coherency_unit,
    146   1.1     rmind 	    0, 0, "npfconpl", NULL, IPL_NET, NULL, NULL, NULL);
    147  1.22  christos 	mutex_init(&npf->conn_lock, MUTEX_DEFAULT, IPL_NONE);
    148  1.22  christos 	npf->conn_tracking = CONN_TRACKING_OFF;
    149  1.22  christos 	npf->conn_db = npf_conndb_create();
    150   1.1     rmind 
    151  1.22  christos 	if ((flags & NPF_NO_GC) == 0) {
    152  1.22  christos 		npf_worker_register(npf, npf_conn_worker);
    153  1.22  christos 	}
    154   1.1     rmind }
    155   1.1     rmind 
    156   1.1     rmind void
    157  1.22  christos npf_conn_fini(npf_t *npf)
    158   1.1     rmind {
    159   1.6     rmind 	/* Note: the caller should have flushed the connections. */
    160  1.22  christos 	KASSERT(npf->conn_tracking == CONN_TRACKING_OFF);
    161  1.22  christos 	npf_worker_unregister(npf, npf_conn_worker);
    162   1.1     rmind 
    163  1.22  christos 	npf_conndb_destroy(npf->conn_db);
    164  1.22  christos 	pool_cache_destroy(npf->conn_cache);
    165  1.22  christos 	mutex_destroy(&npf->conn_lock);
    166   1.1     rmind }
    167   1.1     rmind 
    168   1.1     rmind /*
    169   1.6     rmind  * npf_conn_load: perform the load by flushing the current connection
    170   1.6     rmind  * database and replacing it with the new one or just destroying.
    171   1.1     rmind  *
    172   1.6     rmind  * => The caller must disable the connection tracking and ensure that
    173   1.6     rmind  *    there are no connection database lookups or references in-flight.
    174   1.1     rmind  */
    175   1.6     rmind void
    176  1.22  christos npf_conn_load(npf_t *npf, npf_conndb_t *ndb, bool track)
    177   1.1     rmind {
    178   1.6     rmind 	npf_conndb_t *odb = NULL;
    179   1.1     rmind 
    180  1.22  christos 	KASSERT(npf_config_locked_p(npf));
    181   1.1     rmind 
    182   1.1     rmind 	/*
    183   1.6     rmind 	 * The connection database is in the quiescent state.
    184   1.6     rmind 	 * Prevent G/C thread from running and install a new database.
    185   1.1     rmind 	 */
    186  1.22  christos 	mutex_enter(&npf->conn_lock);
    187   1.6     rmind 	if (ndb) {
    188  1.22  christos 		KASSERT(npf->conn_tracking == CONN_TRACKING_OFF);
    189  1.22  christos 		odb = npf->conn_db;
    190  1.22  christos 		npf->conn_db = ndb;
    191   1.6     rmind 		membar_sync();
    192   1.6     rmind 	}
    193   1.6     rmind 	if (track) {
    194   1.6     rmind 		/* After this point lookups start flying in. */
    195  1.22  christos 		npf->conn_tracking = CONN_TRACKING_ON;
    196   1.1     rmind 	}
    197  1.22  christos 	mutex_exit(&npf->conn_lock);
    198   1.1     rmind 
    199   1.1     rmind 	if (odb) {
    200   1.6     rmind 		/*
    201   1.6     rmind 		 * Flush all, no sync since the caller did it for us.
    202   1.6     rmind 		 * Also, release the pool cache memory.
    203   1.6     rmind 		 */
    204  1.22  christos 		npf_conn_gc(npf, odb, true, false);
    205   1.1     rmind 		npf_conndb_destroy(odb);
    206  1.22  christos 		pool_cache_invalidate(npf->conn_cache);
    207   1.1     rmind 	}
    208   1.1     rmind }
    209   1.1     rmind 
    210   1.1     rmind /*
    211   1.1     rmind  * npf_conn_tracking: enable/disable connection tracking.
    212   1.1     rmind  */
    213   1.1     rmind void
    214  1.22  christos npf_conn_tracking(npf_t *npf, bool track)
    215   1.1     rmind {
    216  1.22  christos 	KASSERT(npf_config_locked_p(npf));
    217  1.22  christos 	npf->conn_tracking = track ? CONN_TRACKING_ON : CONN_TRACKING_OFF;
    218   1.1     rmind }
    219   1.1     rmind 
    220   1.6     rmind static inline bool
    221   1.1     rmind npf_conn_trackable_p(const npf_cache_t *npc)
    222   1.1     rmind {
    223  1.22  christos 	const npf_t *npf = npc->npc_ctx;
    224  1.22  christos 
    225   1.1     rmind 	/*
    226   1.1     rmind 	 * Check if connection tracking is on.  Also, if layer 3 and 4 are
    227   1.1     rmind 	 * not cached - protocol is not supported or packet is invalid.
    228   1.1     rmind 	 */
    229  1.22  christos 	if (npf->conn_tracking != CONN_TRACKING_ON) {
    230   1.1     rmind 		return false;
    231   1.1     rmind 	}
    232   1.1     rmind 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    233   1.1     rmind 		return false;
    234   1.1     rmind 	}
    235   1.1     rmind 	return true;
    236   1.1     rmind }
    237   1.1     rmind 
    238  1.18  christos static uint32_t
    239  1.20  christos connkey_setkey(npf_connkey_t *key, uint16_t proto, const void *ipv,
    240  1.22  christos     const uint16_t *id, unsigned alen, bool forw)
    241  1.18  christos {
    242  1.20  christos 	uint32_t isrc, idst, *k = key->ck_key;
    243  1.18  christos 	const npf_addr_t * const *ips = ipv;
    244  1.22  christos 
    245  1.18  christos 	if (__predict_true(forw)) {
    246  1.18  christos 		isrc = NPF_SRC, idst = NPF_DST;
    247  1.18  christos 	} else {
    248  1.18  christos 		isrc = NPF_DST, idst = NPF_SRC;
    249  1.18  christos 	}
    250  1.18  christos 
    251  1.18  christos 	/*
    252  1.18  christos 	 * Construct a key formed out of 32-bit integers.  The key layout:
    253  1.18  christos 	 *
    254  1.18  christos 	 * Field: | proto  |  alen  | src-id | dst-id | src-addr | dst-addr |
    255  1.18  christos 	 *        +--------+--------+--------+--------+----------+----------+
    256  1.18  christos 	 * Bits:  |   16   |   16   |   16   |   16   |  32-128  |  32-128  |
    257  1.18  christos 	 *
    258  1.18  christos 	 * The source and destination are inverted if they key is for the
    259  1.18  christos 	 * backwards stream (forw == false).  The address length depends
    260  1.18  christos 	 * on the 'alen' field; it is a length in bytes, either 4 or 16.
    261  1.18  christos 	 */
    262  1.18  christos 
    263  1.20  christos 	k[0] = ((uint32_t)proto << 16) | (alen & 0xffff);
    264  1.20  christos 	k[1] = ((uint32_t)id[isrc] << 16) | id[idst];
    265  1.18  christos 
    266  1.18  christos 	if (__predict_true(alen == sizeof(in_addr_t))) {
    267  1.22  christos 		k[2] = ips[isrc]->word32[0];
    268  1.22  christos 		k[3] = ips[idst]->word32[0];
    269  1.18  christos 		return 4 * sizeof(uint32_t);
    270  1.18  christos 	} else {
    271  1.18  christos 		const u_int nwords = alen >> 2;
    272  1.20  christos 		memcpy(&k[2], ips[isrc], alen);
    273  1.20  christos 		memcpy(&k[2 + nwords], ips[idst], alen);
    274  1.18  christos 		return (2 + (nwords * 2)) * sizeof(uint32_t);
    275  1.18  christos 	}
    276  1.18  christos }
    277  1.18  christos 
    278  1.20  christos static void
    279  1.20  christos connkey_getkey(const npf_connkey_t *key, uint16_t *proto, npf_addr_t *ips,
    280  1.20  christos     uint16_t *id, uint16_t *alen)
    281  1.20  christos {
    282  1.20  christos 	const uint32_t *k = key->ck_key;
    283  1.20  christos 
    284  1.20  christos 	*proto = k[0] >> 16;
    285  1.20  christos 	*alen = k[0] & 0xffff;
    286  1.20  christos 	id[NPF_SRC] = k[1] >> 16;
    287  1.20  christos 	id[NPF_DST] = k[1] & 0xffff;
    288  1.20  christos 
    289  1.20  christos 	switch (*alen) {
    290  1.20  christos 	case sizeof(struct in6_addr):
    291  1.20  christos 	case sizeof(struct in_addr):
    292  1.20  christos 		memcpy(&ips[NPF_SRC], &k[2], *alen);
    293  1.20  christos 		memcpy(&ips[NPF_DST], &k[2 + ((unsigned)*alen >> 2)], *alen);
    294  1.20  christos 		return;
    295  1.20  christos 	default:
    296  1.20  christos 		KASSERT(0);
    297  1.20  christos 	}
    298  1.20  christos }
    299  1.20  christos 
    300   1.1     rmind /*
    301   1.1     rmind  * npf_conn_conkey: construct a key for the connection lookup.
    302   1.8     rmind  *
    303   1.8     rmind  * => Returns the key length in bytes or zero on failure.
    304   1.1     rmind  */
    305   1.8     rmind unsigned
    306   1.1     rmind npf_conn_conkey(const npf_cache_t *npc, npf_connkey_t *key, const bool forw)
    307   1.1     rmind {
    308  1.22  christos 	const u_int proto = npc->npc_proto;
    309  1.22  christos 	const u_int alen = npc->npc_alen;
    310   1.1     rmind 	const struct tcphdr *th;
    311   1.1     rmind 	const struct udphdr *uh;
    312   1.1     rmind 	uint16_t id[2];
    313   1.1     rmind 
    314  1.22  christos 	switch (proto) {
    315   1.1     rmind 	case IPPROTO_TCP:
    316   1.1     rmind 		KASSERT(npf_iscached(npc, NPC_TCP));
    317   1.1     rmind 		th = npc->npc_l4.tcp;
    318   1.1     rmind 		id[NPF_SRC] = th->th_sport;
    319   1.1     rmind 		id[NPF_DST] = th->th_dport;
    320   1.1     rmind 		break;
    321   1.1     rmind 	case IPPROTO_UDP:
    322   1.1     rmind 		KASSERT(npf_iscached(npc, NPC_UDP));
    323   1.1     rmind 		uh = npc->npc_l4.udp;
    324   1.1     rmind 		id[NPF_SRC] = uh->uh_sport;
    325   1.1     rmind 		id[NPF_DST] = uh->uh_dport;
    326   1.1     rmind 		break;
    327   1.1     rmind 	case IPPROTO_ICMP:
    328   1.1     rmind 		if (npf_iscached(npc, NPC_ICMP_ID)) {
    329   1.1     rmind 			const struct icmp *ic = npc->npc_l4.icmp;
    330   1.1     rmind 			id[NPF_SRC] = ic->icmp_id;
    331   1.1     rmind 			id[NPF_DST] = ic->icmp_id;
    332   1.1     rmind 			break;
    333   1.1     rmind 		}
    334   1.8     rmind 		return 0;
    335   1.1     rmind 	case IPPROTO_ICMPV6:
    336   1.1     rmind 		if (npf_iscached(npc, NPC_ICMP_ID)) {
    337   1.1     rmind 			const struct icmp6_hdr *ic6 = npc->npc_l4.icmp6;
    338   1.1     rmind 			id[NPF_SRC] = ic6->icmp6_id;
    339   1.1     rmind 			id[NPF_DST] = ic6->icmp6_id;
    340   1.1     rmind 			break;
    341   1.1     rmind 		}
    342   1.8     rmind 		return 0;
    343   1.1     rmind 	default:
    344   1.1     rmind 		/* Unsupported protocol. */
    345   1.8     rmind 		return 0;
    346   1.1     rmind 	}
    347  1.22  christos 	return connkey_setkey(key, proto, npc->npc_ips, id, alen, forw);
    348   1.1     rmind }
    349   1.1     rmind 
    350   1.3  christos static __inline void
    351   1.1     rmind connkey_set_addr(npf_connkey_t *key, const npf_addr_t *naddr, const int di)
    352   1.1     rmind {
    353   1.1     rmind 	const u_int alen = key->ck_key[0] & 0xffff;
    354   1.1     rmind 	uint32_t *addr = &key->ck_key[2 + ((alen >> 2) * di)];
    355   1.1     rmind 
    356   1.1     rmind 	KASSERT(alen > 0);
    357   1.1     rmind 	memcpy(addr, naddr, alen);
    358   1.1     rmind }
    359   1.1     rmind 
    360   1.3  christos static __inline void
    361   1.1     rmind connkey_set_id(npf_connkey_t *key, const uint16_t id, const int di)
    362   1.1     rmind {
    363   1.1     rmind 	const uint32_t oid = key->ck_key[1];
    364   1.1     rmind 	const u_int shift = 16 * !di;
    365   1.1     rmind 	const uint32_t mask = 0xffff0000 >> shift;
    366   1.1     rmind 
    367   1.1     rmind 	key->ck_key[1] = ((uint32_t)id << shift) | (oid & mask);
    368   1.1     rmind }
    369   1.1     rmind 
    370  1.22  christos static inline void
    371  1.22  christos conn_update_atime(npf_conn_t *con)
    372  1.22  christos {
    373  1.22  christos 	struct timespec tsnow;
    374  1.22  christos 
    375  1.22  christos 	getnanouptime(&tsnow);
    376  1.22  christos 	con->c_atime = tsnow.tv_sec;
    377  1.22  christos }
    378  1.22  christos 
    379   1.1     rmind /*
    380  1.18  christos  * npf_conn_ok: check if the connection is active, and has the right direction.
    381  1.18  christos  */
    382  1.18  christos static bool
    383  1.22  christos npf_conn_ok(const npf_conn_t *con, const int di, bool forw)
    384  1.18  christos {
    385  1.22  christos 	const uint32_t flags = con->c_flags;
    386  1.18  christos 
    387  1.18  christos 	/* Check if connection is active and not expired. */
    388  1.18  christos 	bool ok = (flags & (CONN_ACTIVE | CONN_EXPIRE)) == CONN_ACTIVE;
    389  1.18  christos 	if (__predict_false(!ok)) {
    390  1.18  christos 		return false;
    391  1.18  christos 	}
    392  1.18  christos 
    393  1.18  christos 	/* Check if the direction is consistent */
    394  1.22  christos 	bool pforw = (flags & PFIL_ALL) == (unsigned)di;
    395  1.18  christos 	if (__predict_false(forw != pforw)) {
    396  1.18  christos 		return false;
    397  1.18  christos 	}
    398  1.18  christos 	return true;
    399  1.18  christos }
    400  1.18  christos 
    401  1.18  christos /*
    402   1.1     rmind  * npf_conn_lookup: lookup if there is an established connection.
    403   1.1     rmind  *
    404   1.1     rmind  * => If found, we will hold a reference for the caller.
    405   1.1     rmind  */
    406   1.1     rmind npf_conn_t *
    407   1.4     rmind npf_conn_lookup(const npf_cache_t *npc, const int di, bool *forw)
    408   1.1     rmind {
    409  1.22  christos 	npf_t *npf = npc->npc_ctx;
    410   1.4     rmind 	const nbuf_t *nbuf = npc->npc_nbuf;
    411   1.1     rmind 	npf_conn_t *con;
    412   1.1     rmind 	npf_connkey_t key;
    413  1.18  christos 	u_int cifid;
    414   1.1     rmind 
    415   1.1     rmind 	/* Construct a key and lookup for a connection in the store. */
    416   1.1     rmind 	if (!npf_conn_conkey(npc, &key, true)) {
    417   1.1     rmind 		return NULL;
    418   1.1     rmind 	}
    419  1.22  christos 	con = npf_conndb_lookup(npf->conn_db, &key, forw);
    420   1.1     rmind 	if (con == NULL) {
    421   1.1     rmind 		return NULL;
    422   1.1     rmind 	}
    423   1.1     rmind 	KASSERT(npc->npc_proto == con->c_proto);
    424   1.1     rmind 
    425   1.1     rmind 	/* Check if connection is active and not expired. */
    426  1.18  christos 	if (!npf_conn_ok(con, di, *forw)) {
    427   1.1     rmind 		atomic_dec_uint(&con->c_refcnt);
    428   1.1     rmind 		return NULL;
    429   1.1     rmind 	}
    430   1.1     rmind 
    431   1.1     rmind 	/*
    432   1.1     rmind 	 * Match the interface and the direction of the connection entry
    433   1.1     rmind 	 * and the packet.
    434   1.1     rmind 	 */
    435   1.1     rmind 	cifid = con->c_ifid;
    436   1.1     rmind 	if (__predict_false(cifid && cifid != nbuf->nb_ifid)) {
    437   1.1     rmind 		atomic_dec_uint(&con->c_refcnt);
    438   1.1     rmind 		return NULL;
    439   1.1     rmind 	}
    440   1.1     rmind 
    441   1.1     rmind 	/* Update the last activity time. */
    442  1.22  christos 	conn_update_atime(con);
    443   1.1     rmind 	return con;
    444   1.1     rmind }
    445   1.1     rmind 
    446   1.1     rmind /*
    447   1.1     rmind  * npf_conn_inspect: lookup a connection and inspecting the protocol data.
    448   1.1     rmind  *
    449   1.1     rmind  * => If found, we will hold a reference for the caller.
    450   1.1     rmind  */
    451   1.1     rmind npf_conn_t *
    452   1.4     rmind npf_conn_inspect(npf_cache_t *npc, const int di, int *error)
    453   1.1     rmind {
    454   1.4     rmind 	nbuf_t *nbuf = npc->npc_nbuf;
    455   1.1     rmind 	npf_conn_t *con;
    456   1.1     rmind 	bool forw, ok;
    457   1.1     rmind 
    458   1.1     rmind 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    459   1.1     rmind 	if (!npf_conn_trackable_p(npc)) {
    460   1.1     rmind 		return NULL;
    461   1.1     rmind 	}
    462   1.1     rmind 
    463   1.1     rmind 	/* Query ALG which may lookup connection for us. */
    464   1.4     rmind 	if ((con = npf_alg_conn(npc, di)) != NULL) {
    465   1.1     rmind 		/* Note: reference is held. */
    466   1.1     rmind 		return con;
    467   1.1     rmind 	}
    468   1.1     rmind 	if (nbuf_head_mbuf(nbuf) == NULL) {
    469   1.1     rmind 		*error = ENOMEM;
    470   1.1     rmind 		return NULL;
    471   1.1     rmind 	}
    472   1.1     rmind 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    473   1.1     rmind 
    474   1.1     rmind 	/* Main lookup of the connection. */
    475   1.4     rmind 	if ((con = npf_conn_lookup(npc, di, &forw)) == NULL) {
    476   1.1     rmind 		return NULL;
    477   1.1     rmind 	}
    478   1.1     rmind 
    479   1.1     rmind 	/* Inspect the protocol data and handle state changes. */
    480   1.1     rmind 	mutex_enter(&con->c_lock);
    481   1.4     rmind 	ok = npf_state_inspect(npc, &con->c_state, forw);
    482   1.1     rmind 	mutex_exit(&con->c_lock);
    483   1.1     rmind 
    484  1.17     rmind 	/* If invalid state: let the rules deal with it. */
    485   1.1     rmind 	if (__predict_false(!ok)) {
    486   1.1     rmind 		npf_conn_release(con);
    487  1.22  christos 		npf_stats_inc(npc->npc_ctx, NPF_STAT_INVALID_STATE);
    488  1.17     rmind 		return NULL;
    489  1.17     rmind 	}
    490  1.17     rmind 
    491  1.17     rmind 	/*
    492  1.17     rmind 	 * If this is multi-end state, then specially tag the packet
    493  1.17     rmind 	 * so it will be just passed-through on other interfaces.
    494  1.17     rmind 	 */
    495  1.17     rmind 	if (con->c_ifid == 0 && nbuf_add_tag(nbuf, NPF_NTAG_PASS) != 0) {
    496  1.17     rmind 		npf_conn_release(con);
    497  1.17     rmind 		*error = ENOMEM;
    498  1.17     rmind 		return NULL;
    499   1.1     rmind 	}
    500   1.1     rmind 	return con;
    501   1.1     rmind }
    502   1.1     rmind 
    503   1.1     rmind /*
    504   1.1     rmind  * npf_conn_establish: create a new connection, insert into the global list.
    505   1.1     rmind  *
    506   1.1     rmind  * => Connection is created with the reference held for the caller.
    507   1.1     rmind  * => Connection will be activated on the first reference release.
    508   1.1     rmind  */
    509   1.1     rmind npf_conn_t *
    510   1.4     rmind npf_conn_establish(npf_cache_t *npc, int di, bool per_if)
    511   1.1     rmind {
    512  1.22  christos 	npf_t *npf = npc->npc_ctx;
    513   1.4     rmind 	const nbuf_t *nbuf = npc->npc_nbuf;
    514   1.1     rmind 	npf_conn_t *con;
    515  1.15     rmind 	int error = 0;
    516   1.1     rmind 
    517   1.1     rmind 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    518   1.1     rmind 
    519   1.1     rmind 	if (!npf_conn_trackable_p(npc)) {
    520   1.1     rmind 		return NULL;
    521   1.1     rmind 	}
    522   1.1     rmind 
    523   1.1     rmind 	/* Allocate and initialise the new connection. */
    524  1.22  christos 	con = pool_cache_get(npf->conn_cache, PR_NOWAIT);
    525   1.1     rmind 	if (__predict_false(!con)) {
    526  1.22  christos 		npf_worker_signal(npf);
    527   1.1     rmind 		return NULL;
    528   1.1     rmind 	}
    529   1.1     rmind 	NPF_PRINTF(("NPF: create conn %p\n", con));
    530  1.22  christos 	npf_stats_inc(npf, NPF_STAT_CONN_CREATE);
    531   1.1     rmind 
    532   1.1     rmind 	mutex_init(&con->c_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    533   1.1     rmind 	con->c_flags = (di & PFIL_ALL);
    534  1.15     rmind 	con->c_refcnt = 0;
    535   1.1     rmind 	con->c_rproc = NULL;
    536   1.1     rmind 	con->c_nat = NULL;
    537   1.1     rmind 
    538  1.15     rmind 	/* Initialize the protocol state. */
    539   1.4     rmind 	if (!npf_state_init(npc, &con->c_state)) {
    540  1.22  christos 		npf_conn_destroy(npf, con);
    541  1.15     rmind 		return NULL;
    542   1.1     rmind 	}
    543   1.1     rmind 
    544   1.1     rmind 	KASSERT(npf_iscached(npc, NPC_IP46));
    545   1.1     rmind 	npf_connkey_t *fw = &con->c_forw_entry;
    546   1.1     rmind 	npf_connkey_t *bk = &con->c_back_entry;
    547   1.1     rmind 
    548   1.1     rmind 	/*
    549   1.1     rmind 	 * Construct "forwards" and "backwards" keys.  Also, set the
    550   1.1     rmind 	 * interface ID for this connection (unless it is global).
    551   1.1     rmind 	 */
    552  1.15     rmind 	if (!npf_conn_conkey(npc, fw, true) ||
    553  1.15     rmind 	    !npf_conn_conkey(npc, bk, false)) {
    554  1.22  christos 		npf_conn_destroy(npf, con);
    555  1.15     rmind 		return NULL;
    556   1.1     rmind 	}
    557   1.1     rmind 	fw->ck_backptr = bk->ck_backptr = con;
    558   1.1     rmind 	con->c_ifid = per_if ? nbuf->nb_ifid : 0;
    559   1.1     rmind 	con->c_proto = npc->npc_proto;
    560   1.1     rmind 
    561  1.15     rmind 	/*
    562  1.15     rmind 	 * Set last activity time for a new connection and acquire
    563  1.15     rmind 	 * a reference for the caller before we make it visible.
    564  1.15     rmind 	 */
    565  1.22  christos 	conn_update_atime(con);
    566  1.15     rmind 	con->c_refcnt = 1;
    567   1.1     rmind 
    568   1.1     rmind 	/*
    569   1.1     rmind 	 * Insert both keys (entries representing directions) of the
    570  1.15     rmind 	 * connection.  At this point it becomes visible, but we activate
    571  1.15     rmind 	 * the connection later.
    572   1.1     rmind 	 */
    573  1.15     rmind 	mutex_enter(&con->c_lock);
    574  1.22  christos 	if (!npf_conndb_insert(npf->conn_db, fw, con)) {
    575  1.15     rmind 		error = EISCONN;
    576   1.1     rmind 		goto err;
    577   1.1     rmind 	}
    578  1.22  christos 	if (!npf_conndb_insert(npf->conn_db, bk, con)) {
    579  1.15     rmind 		npf_conn_t *ret __diagused;
    580  1.22  christos 		ret = npf_conndb_remove(npf->conn_db, fw);
    581  1.15     rmind 		KASSERT(ret == con);
    582  1.15     rmind 		error = EISCONN;
    583  1.15     rmind 		goto err;
    584  1.15     rmind 	}
    585  1.15     rmind err:
    586  1.15     rmind 	/*
    587  1.15     rmind 	 * If we have hit the duplicate: mark the connection as expired
    588  1.15     rmind 	 * and let the G/C thread to take care of it.  We cannot do it
    589  1.15     rmind 	 * here since there might be references acquired already.
    590  1.15     rmind 	 */
    591  1.15     rmind 	if (error) {
    592  1.16     rmind 		atomic_or_uint(&con->c_flags, CONN_REMOVED | CONN_EXPIRE);
    593  1.16     rmind 		atomic_dec_uint(&con->c_refcnt);
    594  1.22  christos 		npf_stats_inc(npf, NPF_STAT_RACE_CONN);
    595  1.15     rmind 	} else {
    596  1.15     rmind 		NPF_PRINTF(("NPF: establish conn %p\n", con));
    597   1.1     rmind 	}
    598   1.1     rmind 
    599   1.1     rmind 	/* Finally, insert into the connection list. */
    600  1.22  christos 	npf_conndb_enqueue(npf->conn_db, con);
    601  1.15     rmind 	mutex_exit(&con->c_lock);
    602  1.15     rmind 
    603  1.15     rmind 	return error ? NULL : con;
    604   1.1     rmind }
    605   1.1     rmind 
    606   1.1     rmind static void
    607  1.22  christos npf_conn_destroy(npf_t *npf, npf_conn_t *con)
    608   1.1     rmind {
    609  1.15     rmind 	KASSERT(con->c_refcnt == 0);
    610  1.15     rmind 
    611   1.1     rmind 	if (con->c_nat) {
    612   1.1     rmind 		/* Release any NAT structures. */
    613   1.1     rmind 		npf_nat_destroy(con->c_nat);
    614   1.1     rmind 	}
    615   1.1     rmind 	if (con->c_rproc) {
    616   1.1     rmind 		/* Release the rule procedure. */
    617   1.1     rmind 		npf_rproc_release(con->c_rproc);
    618   1.1     rmind 	}
    619   1.1     rmind 
    620   1.1     rmind 	/* Destroy the state. */
    621   1.1     rmind 	npf_state_destroy(&con->c_state);
    622   1.1     rmind 	mutex_destroy(&con->c_lock);
    623   1.1     rmind 
    624   1.1     rmind 	/* Free the structure, increase the counter. */
    625  1.22  christos 	pool_cache_put(npf->conn_cache, con);
    626  1.22  christos 	npf_stats_inc(npf, NPF_STAT_CONN_DESTROY);
    627   1.1     rmind 	NPF_PRINTF(("NPF: conn %p destroyed\n", con));
    628   1.1     rmind }
    629   1.1     rmind 
    630   1.1     rmind /*
    631   1.1     rmind  * npf_conn_setnat: associate NAT entry with the connection, update and
    632   1.1     rmind  * re-insert connection entry using the translation values.
    633  1.16     rmind  *
    634  1.16     rmind  * => The caller must be holding a reference.
    635   1.1     rmind  */
    636   1.1     rmind int
    637   1.1     rmind npf_conn_setnat(const npf_cache_t *npc, npf_conn_t *con,
    638   1.1     rmind     npf_nat_t *nt, u_int ntype)
    639   1.1     rmind {
    640   1.1     rmind 	static const u_int nat_type_dimap[] = {
    641   1.1     rmind 		[NPF_NATOUT] = NPF_DST,
    642   1.1     rmind 		[NPF_NATIN] = NPF_SRC,
    643   1.1     rmind 	};
    644  1.22  christos 	npf_t *npf = npc->npc_ctx;
    645   1.1     rmind 	npf_connkey_t key, *bk;
    646   1.2     rmind 	npf_conn_t *ret __diagused;
    647   1.1     rmind 	npf_addr_t *taddr;
    648   1.1     rmind 	in_port_t tport;
    649   1.1     rmind 	u_int tidx;
    650   1.1     rmind 
    651   1.1     rmind 	KASSERT(con->c_refcnt > 0);
    652   1.1     rmind 
    653   1.1     rmind 	npf_nat_gettrans(nt, &taddr, &tport);
    654   1.1     rmind 	KASSERT(ntype == NPF_NATOUT || ntype == NPF_NATIN);
    655   1.1     rmind 	tidx = nat_type_dimap[ntype];
    656   1.1     rmind 
    657   1.1     rmind 	/* Construct a "backwards" key. */
    658   1.1     rmind 	if (!npf_conn_conkey(npc, &key, false)) {
    659   1.1     rmind 		return EINVAL;
    660   1.1     rmind 	}
    661   1.1     rmind 
    662   1.1     rmind 	/* Acquire the lock and check for the races. */
    663   1.1     rmind 	mutex_enter(&con->c_lock);
    664   1.1     rmind 	if (__predict_false(con->c_flags & CONN_EXPIRE)) {
    665   1.1     rmind 		/* The connection got expired. */
    666   1.1     rmind 		mutex_exit(&con->c_lock);
    667   1.1     rmind 		return EINVAL;
    668   1.1     rmind 	}
    669  1.15     rmind 	KASSERT((con->c_flags & CONN_REMOVED) == 0);
    670  1.15     rmind 
    671   1.1     rmind 	if (__predict_false(con->c_nat != NULL)) {
    672   1.1     rmind 		/* Race with a duplicate packet. */
    673   1.1     rmind 		mutex_exit(&con->c_lock);
    674  1.22  christos 		npf_stats_inc(npc->npc_ctx, NPF_STAT_RACE_NAT);
    675   1.1     rmind 		return EISCONN;
    676   1.1     rmind 	}
    677   1.1     rmind 
    678   1.1     rmind 	/* Remove the "backwards" entry. */
    679  1.22  christos 	ret = npf_conndb_remove(npf->conn_db, &con->c_back_entry);
    680   1.1     rmind 	KASSERT(ret == con);
    681   1.1     rmind 
    682   1.1     rmind 	/* Set the source/destination IDs to the translation values. */
    683   1.1     rmind 	bk = &con->c_back_entry;
    684   1.1     rmind 	connkey_set_addr(bk, taddr, tidx);
    685   1.1     rmind 	if (tport) {
    686   1.1     rmind 		connkey_set_id(bk, tport, tidx);
    687   1.1     rmind 	}
    688   1.1     rmind 
    689   1.1     rmind 	/* Finally, re-insert the "backwards" entry. */
    690  1.22  christos 	if (!npf_conndb_insert(npf->conn_db, bk, con)) {
    691   1.1     rmind 		/*
    692   1.1     rmind 		 * Race: we have hit the duplicate, remove the "forwards"
    693   1.1     rmind 		 * entry and expire our connection; it is no longer valid.
    694   1.1     rmind 		 */
    695  1.22  christos 		ret = npf_conndb_remove(npf->conn_db, &con->c_forw_entry);
    696  1.15     rmind 		KASSERT(ret == con);
    697  1.15     rmind 
    698   1.1     rmind 		atomic_or_uint(&con->c_flags, CONN_REMOVED | CONN_EXPIRE);
    699   1.1     rmind 		mutex_exit(&con->c_lock);
    700   1.1     rmind 
    701  1.22  christos 		npf_stats_inc(npc->npc_ctx, NPF_STAT_RACE_NAT);
    702   1.1     rmind 		return EISCONN;
    703   1.1     rmind 	}
    704   1.1     rmind 
    705   1.1     rmind 	/* Associate the NAT entry and release the lock. */
    706   1.1     rmind 	con->c_nat = nt;
    707   1.1     rmind 	mutex_exit(&con->c_lock);
    708   1.1     rmind 	return 0;
    709   1.1     rmind }
    710   1.1     rmind 
    711   1.1     rmind /*
    712   1.1     rmind  * npf_conn_expire: explicitly mark connection as expired.
    713   1.1     rmind  */
    714   1.1     rmind void
    715   1.1     rmind npf_conn_expire(npf_conn_t *con)
    716   1.1     rmind {
    717   1.1     rmind 	/* KASSERT(con->c_refcnt > 0); XXX: npf_nat_freepolicy() */
    718   1.1     rmind 	atomic_or_uint(&con->c_flags, CONN_EXPIRE);
    719   1.1     rmind }
    720   1.1     rmind 
    721   1.1     rmind /*
    722   1.1     rmind  * npf_conn_pass: return true if connection is "pass" one, otherwise false.
    723   1.1     rmind  */
    724   1.1     rmind bool
    725  1.23  christos npf_conn_pass(const npf_conn_t *con, npf_match_info_t *mi, npf_rproc_t **rp)
    726   1.1     rmind {
    727   1.1     rmind 	KASSERT(con->c_refcnt > 0);
    728   1.1     rmind 	if (__predict_true(con->c_flags & CONN_PASS)) {
    729  1.24     rmind 		mi->mi_rid = con->c_rid;
    730  1.24     rmind 		mi->mi_retfl = con->c_retfl;
    731   1.1     rmind 		*rp = con->c_rproc;
    732   1.1     rmind 		return true;
    733   1.1     rmind 	}
    734   1.1     rmind 	return false;
    735   1.1     rmind }
    736   1.1     rmind 
    737   1.1     rmind /*
    738   1.1     rmind  * npf_conn_setpass: mark connection as a "pass" one and associate the
    739   1.1     rmind  * rule procedure with it.
    740   1.1     rmind  */
    741   1.1     rmind void
    742  1.23  christos npf_conn_setpass(npf_conn_t *con, const npf_match_info_t *mi, npf_rproc_t *rp)
    743   1.1     rmind {
    744   1.1     rmind 	KASSERT((con->c_flags & CONN_ACTIVE) == 0);
    745   1.1     rmind 	KASSERT(con->c_refcnt > 0);
    746   1.1     rmind 	KASSERT(con->c_rproc == NULL);
    747   1.1     rmind 
    748   1.1     rmind 	/*
    749   1.1     rmind 	 * No need for atomic since the connection is not yet active.
    750   1.1     rmind 	 * If rproc is set, the caller transfers its reference to us,
    751   1.1     rmind 	 * which will be released on npf_conn_destroy().
    752   1.1     rmind 	 */
    753  1.14     rmind 	atomic_or_uint(&con->c_flags, CONN_PASS);
    754   1.1     rmind 	con->c_rproc = rp;
    755  1.24     rmind 	if (rp) {
    756  1.24     rmind 		con->c_rid = mi->mi_rid;
    757  1.24     rmind 		con->c_retfl = mi->mi_retfl;
    758  1.24     rmind 	}
    759   1.1     rmind }
    760   1.1     rmind 
    761   1.1     rmind /*
    762   1.1     rmind  * npf_conn_release: release a reference, which might allow G/C thread
    763   1.1     rmind  * to destroy this connection.
    764   1.1     rmind  */
    765   1.1     rmind void
    766   1.1     rmind npf_conn_release(npf_conn_t *con)
    767   1.1     rmind {
    768   1.1     rmind 	if ((con->c_flags & (CONN_ACTIVE | CONN_EXPIRE)) == 0) {
    769   1.1     rmind 		/* Activate: after this, connection is globally visible. */
    770  1.14     rmind 		atomic_or_uint(&con->c_flags, CONN_ACTIVE);
    771   1.1     rmind 	}
    772   1.1     rmind 	KASSERT(con->c_refcnt > 0);
    773   1.1     rmind 	atomic_dec_uint(&con->c_refcnt);
    774   1.1     rmind }
    775   1.1     rmind 
    776   1.1     rmind /*
    777  1.13     rmind  * npf_conn_getnat: return associated NAT data entry and indicate
    778   1.1     rmind  * whether it is a "forwards" or "backwards" stream.
    779   1.1     rmind  */
    780   1.1     rmind npf_nat_t *
    781  1.13     rmind npf_conn_getnat(npf_conn_t *con, const int di, bool *forw)
    782   1.1     rmind {
    783   1.1     rmind 	KASSERT(con->c_refcnt > 0);
    784  1.22  christos 	*forw = (con->c_flags & PFIL_ALL) == (u_int)di;
    785   1.1     rmind 	return con->c_nat;
    786   1.1     rmind }
    787   1.1     rmind 
    788   1.1     rmind /*
    789   1.1     rmind  * npf_conn_expired: criterion to check if connection is expired.
    790   1.1     rmind  */
    791   1.1     rmind static inline bool
    792  1.22  christos npf_conn_expired(const npf_conn_t *con, uint64_t tsnow)
    793   1.1     rmind {
    794   1.1     rmind 	const int etime = npf_state_etime(&con->c_state, con->c_proto);
    795  1.22  christos 	int elapsed;
    796   1.1     rmind 
    797   1.1     rmind 	if (__predict_false(con->c_flags & CONN_EXPIRE)) {
    798   1.1     rmind 		/* Explicitly marked to be expired. */
    799   1.1     rmind 		return true;
    800   1.1     rmind 	}
    801  1.22  christos 
    802  1.22  christos 	/*
    803  1.22  christos 	 * Note: another thread may update 'atime' and it might
    804  1.22  christos 	 * become greater than 'now'.
    805  1.22  christos 	 */
    806  1.22  christos 	elapsed = (int64_t)tsnow - con->c_atime;
    807  1.22  christos 	return elapsed > etime;
    808   1.1     rmind }
    809   1.1     rmind 
    810   1.1     rmind /*
    811   1.6     rmind  * npf_conn_gc: garbage collect the expired connections.
    812   1.6     rmind  *
    813   1.6     rmind  * => Must run in a single-threaded manner.
    814   1.6     rmind  * => If it is a flush request, then destroy all connections.
    815   1.6     rmind  * => If 'sync' is true, then perform passive serialisation.
    816   1.1     rmind  */
    817   1.7     rmind void
    818  1.22  christos npf_conn_gc(npf_t *npf, npf_conndb_t *cd, bool flush, bool sync)
    819   1.1     rmind {
    820   1.1     rmind 	npf_conn_t *con, *prev, *gclist = NULL;
    821   1.1     rmind 	struct timespec tsnow;
    822   1.1     rmind 
    823   1.1     rmind 	getnanouptime(&tsnow);
    824   1.1     rmind 
    825   1.1     rmind 	/*
    826   1.1     rmind 	 * Scan all connections and check them for expiration.
    827   1.1     rmind 	 */
    828   1.1     rmind 	prev = NULL;
    829   1.1     rmind 	con = npf_conndb_getlist(cd);
    830   1.1     rmind 	while (con) {
    831   1.1     rmind 		npf_conn_t *next = con->c_next;
    832   1.1     rmind 
    833   1.1     rmind 		/* Expired?  Flushing all? */
    834  1.22  christos 		if (!npf_conn_expired(con, tsnow.tv_sec) && !flush) {
    835   1.1     rmind 			prev = con;
    836   1.1     rmind 			con = next;
    837   1.1     rmind 			continue;
    838   1.1     rmind 		}
    839   1.1     rmind 
    840   1.1     rmind 		/* Remove both entries of the connection. */
    841   1.1     rmind 		mutex_enter(&con->c_lock);
    842   1.1     rmind 		if ((con->c_flags & CONN_REMOVED) == 0) {
    843   1.1     rmind 			npf_conn_t *ret __diagused;
    844   1.1     rmind 
    845   1.1     rmind 			ret = npf_conndb_remove(cd, &con->c_forw_entry);
    846   1.1     rmind 			KASSERT(ret == con);
    847   1.1     rmind 			ret = npf_conndb_remove(cd, &con->c_back_entry);
    848   1.1     rmind 			KASSERT(ret == con);
    849   1.1     rmind 		}
    850   1.1     rmind 
    851   1.1     rmind 		/* Flag the removal and expiration. */
    852   1.1     rmind 		atomic_or_uint(&con->c_flags, CONN_REMOVED | CONN_EXPIRE);
    853   1.1     rmind 		mutex_exit(&con->c_lock);
    854   1.1     rmind 
    855   1.1     rmind 		/* Move to the G/C list. */
    856   1.1     rmind 		npf_conndb_dequeue(cd, con, prev);
    857   1.1     rmind 		con->c_next = gclist;
    858   1.1     rmind 		gclist = con;
    859   1.1     rmind 
    860   1.1     rmind 		/* Next.. */
    861   1.1     rmind 		con = next;
    862   1.1     rmind 	}
    863   1.1     rmind 	npf_conndb_settail(cd, prev);
    864   1.6     rmind 
    865   1.6     rmind 	/*
    866   1.6     rmind 	 * Ensure it is safe to destroy the connections.
    867   1.6     rmind 	 * Note: drop the conn_lock (see the lock order).
    868   1.6     rmind 	 */
    869   1.6     rmind 	if (sync) {
    870  1.22  christos 		mutex_exit(&npf->conn_lock);
    871   1.6     rmind 		if (gclist) {
    872  1.22  christos 			npf_config_enter(npf);
    873  1.22  christos 			npf_config_sync(npf);
    874  1.22  christos 			npf_config_exit(npf);
    875   1.6     rmind 		}
    876   1.1     rmind 	}
    877   1.1     rmind 
    878   1.1     rmind 	/*
    879   1.1     rmind 	 * Garbage collect all expired connections.
    880   1.1     rmind 	 * May need to wait for the references to drain.
    881   1.1     rmind 	 */
    882   1.1     rmind 	con = gclist;
    883   1.1     rmind 	while (con) {
    884   1.1     rmind 		npf_conn_t *next = con->c_next;
    885   1.1     rmind 
    886   1.1     rmind 		/*
    887   1.1     rmind 		 * Destroy only if removed and no references.
    888   1.1     rmind 		 * Otherwise, wait for a tiny moment.
    889   1.1     rmind 		 */
    890   1.1     rmind 		if (__predict_false(con->c_refcnt)) {
    891   1.1     rmind 			kpause("npfcongc", false, 1, NULL);
    892   1.1     rmind 			continue;
    893   1.1     rmind 		}
    894  1.22  christos 		npf_conn_destroy(npf, con);
    895   1.1     rmind 		con = next;
    896   1.1     rmind 	}
    897   1.1     rmind }
    898   1.1     rmind 
    899   1.6     rmind /*
    900   1.6     rmind  * npf_conn_worker: G/C to run from a worker thread.
    901   1.6     rmind  */
    902  1.22  christos void
    903  1.22  christos npf_conn_worker(npf_t *npf)
    904   1.1     rmind {
    905  1.22  christos 	mutex_enter(&npf->conn_lock);
    906   1.6     rmind 	/* Note: the conn_lock will be released (sync == true). */
    907  1.22  christos 	npf_conn_gc(npf, npf->conn_db, false, true);
    908   1.1     rmind }
    909   1.1     rmind 
    910   1.1     rmind /*
    911  1.10     rmind  * npf_conndb_export: construct a list of connections prepared for saving.
    912   1.1     rmind  * Note: this is expected to be an expensive operation.
    913   1.1     rmind  */
    914   1.1     rmind int
    915  1.25     rmind npf_conndb_export(npf_t *npf, nvlist_t *npf_dict)
    916   1.1     rmind {
    917   1.1     rmind 	npf_conn_t *con, *prev;
    918   1.1     rmind 
    919   1.1     rmind 	/*
    920   1.1     rmind 	 * Note: acquire conn_lock to prevent from the database
    921   1.1     rmind 	 * destruction and G/C thread.
    922   1.1     rmind 	 */
    923  1.22  christos 	mutex_enter(&npf->conn_lock);
    924  1.22  christos 	if (npf->conn_tracking != CONN_TRACKING_ON) {
    925  1.22  christos 		mutex_exit(&npf->conn_lock);
    926   1.1     rmind 		return 0;
    927   1.1     rmind 	}
    928   1.1     rmind 	prev = NULL;
    929  1.22  christos 	con = npf_conndb_getlist(npf->conn_db);
    930   1.1     rmind 	while (con) {
    931   1.1     rmind 		npf_conn_t *next = con->c_next;
    932  1.25     rmind 		nvlist_t *cdict;
    933   1.1     rmind 
    934  1.22  christos 		if ((cdict = npf_conn_export(npf, con)) != NULL) {
    935  1.25     rmind 			nvlist_append_nvlist_array(npf_dict, "conn-list", cdict);
    936  1.25     rmind 			nvlist_destroy(cdict);
    937   1.1     rmind 		}
    938   1.1     rmind 		prev = con;
    939   1.1     rmind 		con = next;
    940   1.1     rmind 	}
    941  1.22  christos 	npf_conndb_settail(npf->conn_db, prev);
    942  1.22  christos 	mutex_exit(&npf->conn_lock);
    943   1.5     joerg 	return 0;
    944   1.1     rmind }
    945   1.1     rmind 
    946  1.25     rmind static nvlist_t *
    947  1.20  christos npf_connkey_export(const npf_connkey_t *key)
    948  1.20  christos {
    949  1.20  christos 	uint16_t id[2], alen, proto;
    950  1.20  christos 	npf_addr_t ips[2];
    951  1.25     rmind 	nvlist_t *kdict;
    952  1.20  christos 
    953  1.25     rmind 	kdict = nvlist_create(0);
    954  1.20  christos 	connkey_getkey(key, &proto, ips, id, &alen);
    955  1.25     rmind 	nvlist_add_number(kdict, "proto", proto);
    956  1.25     rmind 	nvlist_add_number(kdict, "sport", id[NPF_SRC]);
    957  1.25     rmind 	nvlist_add_number(kdict, "dport", id[NPF_DST]);
    958  1.25     rmind 	nvlist_add_binary(kdict, "saddr", &ips[NPF_SRC], alen);
    959  1.25     rmind 	nvlist_add_binary(kdict, "daddr", &ips[NPF_DST], alen);
    960  1.20  christos 	return kdict;
    961  1.20  christos }
    962  1.20  christos 
    963   1.1     rmind /*
    964  1.10     rmind  * npf_conn_export: serialise a single connection.
    965  1.10     rmind  */
    966  1.25     rmind static nvlist_t *
    967  1.22  christos npf_conn_export(npf_t *npf, const npf_conn_t *con)
    968  1.10     rmind {
    969  1.25     rmind 	nvlist_t *cdict, *kdict;
    970  1.10     rmind 
    971  1.10     rmind 	if ((con->c_flags & (CONN_ACTIVE|CONN_EXPIRE)) != CONN_ACTIVE) {
    972  1.10     rmind 		return NULL;
    973  1.10     rmind 	}
    974  1.25     rmind 	cdict = nvlist_create(0);
    975  1.25     rmind 	nvlist_add_number(cdict, "flags", con->c_flags);
    976  1.25     rmind 	nvlist_add_number(cdict, "proto", con->c_proto);
    977  1.10     rmind 	if (con->c_ifid) {
    978  1.22  christos 		const char *ifname = npf_ifmap_getname(npf, con->c_ifid);
    979  1.25     rmind 		nvlist_add_string(cdict, "ifname", ifname);
    980  1.10     rmind 	}
    981  1.25     rmind 	nvlist_add_binary(cdict, "state", &con->c_state, sizeof(npf_state_t));
    982  1.10     rmind 
    983  1.20  christos 	kdict = npf_connkey_export(&con->c_forw_entry);
    984  1.25     rmind 	nvlist_move_nvlist(cdict, "forw-key", kdict);
    985  1.10     rmind 
    986  1.20  christos 	kdict = npf_connkey_export(&con->c_back_entry);
    987  1.25     rmind 	nvlist_move_nvlist(cdict, "back-key", kdict);
    988  1.10     rmind 
    989  1.10     rmind 	if (con->c_nat) {
    990  1.10     rmind 		npf_nat_export(cdict, con->c_nat);
    991  1.10     rmind 	}
    992  1.10     rmind 	return cdict;
    993  1.10     rmind }
    994  1.10     rmind 
    995  1.18  christos static uint32_t
    996  1.25     rmind npf_connkey_import(const nvlist_t *kdict, npf_connkey_t *key)
    997  1.18  christos {
    998  1.18  christos 	npf_addr_t const * ips[2];
    999  1.25     rmind 	uint16_t proto, id[2];
   1000  1.25     rmind 	size_t alen1, alen2;
   1001  1.18  christos 
   1002  1.25     rmind 	proto = dnvlist_get_number(kdict, "proto", 0);
   1003  1.25     rmind 	id[NPF_SRC] = dnvlist_get_number(kdict, "sport", 0);
   1004  1.25     rmind 	id[NPF_DST] = dnvlist_get_number(kdict, "dport", 0);
   1005  1.25     rmind 	ips[NPF_SRC] = dnvlist_get_binary(kdict, "saddr", &alen1, NULL, 0);
   1006  1.25     rmind 	ips[NPF_DST] = dnvlist_get_binary(kdict, "daddr", &alen2, NULL, 0);
   1007  1.25     rmind 	if (__predict_false(alen1 == 0 || alen1 != alen2)) {
   1008  1.20  christos 		return 0;
   1009  1.25     rmind 	}
   1010  1.25     rmind 	return connkey_setkey(key, proto, ips, id, alen1, true);
   1011  1.18  christos }
   1012  1.18  christos 
   1013  1.10     rmind /*
   1014   1.6     rmind  * npf_conn_import: fully reconstruct a single connection from a
   1015  1.25     rmind  * nvlist and insert into the given database.
   1016   1.1     rmind  */
   1017   1.1     rmind int
   1018  1.25     rmind npf_conn_import(npf_t *npf, npf_conndb_t *cd, const nvlist_t *cdict,
   1019   1.6     rmind     npf_ruleset_t *natlist)
   1020   1.1     rmind {
   1021   1.1     rmind 	npf_conn_t *con;
   1022   1.1     rmind 	npf_connkey_t *fw, *bk;
   1023  1.25     rmind 	const nvlist_t *nat, *conkey;
   1024  1.10     rmind 	const char *ifname;
   1025  1.25     rmind 	const void *state;
   1026  1.25     rmind 	size_t len;
   1027   1.1     rmind 
   1028   1.1     rmind 	/* Allocate a connection and initialise it (clear first). */
   1029  1.22  christos 	con = pool_cache_get(npf->conn_cache, PR_WAITOK);
   1030   1.1     rmind 	memset(con, 0, sizeof(npf_conn_t));
   1031   1.1     rmind 	mutex_init(&con->c_lock, MUTEX_DEFAULT, IPL_SOFTNET);
   1032  1.22  christos 	npf_stats_inc(npf, NPF_STAT_CONN_CREATE);
   1033   1.1     rmind 
   1034  1.25     rmind 	con->c_proto = dnvlist_get_number(cdict, "proto", 0);
   1035  1.25     rmind 	con->c_flags = dnvlist_get_number(cdict, "flags", 0);
   1036   1.1     rmind 	con->c_flags &= PFIL_ALL | CONN_ACTIVE | CONN_PASS;
   1037  1.22  christos 	conn_update_atime(con);
   1038   1.1     rmind 
   1039  1.25     rmind 	ifname = dnvlist_get_string(cdict, "ifname", NULL);
   1040  1.25     rmind 	if (ifname && (con->c_ifid = npf_ifmap_register(npf, ifname)) == 0) {
   1041  1.10     rmind 		goto err;
   1042  1.10     rmind 	}
   1043  1.10     rmind 
   1044  1.25     rmind 	state = dnvlist_get_binary(cdict, "state", &len, NULL, 0);
   1045  1.25     rmind 	if (!state || len != sizeof(npf_state_t)) {
   1046   1.1     rmind 		goto err;
   1047   1.1     rmind 	}
   1048  1.25     rmind 	memcpy(&con->c_state, state, sizeof(npf_state_t));
   1049   1.1     rmind 
   1050  1.11     rmind 	/* Reconstruct NAT association, if any. */
   1051  1.25     rmind 	if ((nat = dnvlist_get_nvlist(cdict, "nat", NULL)) != NULL &&
   1052  1.25     rmind 	    (con->c_nat = npf_nat_import(npf, nat, natlist, con)) == NULL) {
   1053  1.11     rmind 		goto err;
   1054  1.11     rmind 	}
   1055   1.1     rmind 
   1056   1.1     rmind 	/*
   1057   1.1     rmind 	 * Fetch and copy the keys for each direction.
   1058   1.1     rmind 	 */
   1059  1.25     rmind 	conkey = dnvlist_get_nvlist(cdict, "forw-key", NULL);
   1060  1.20  christos 	fw = &con->c_forw_entry;
   1061  1.25     rmind 	if (conkey == NULL || !npf_connkey_import(conkey, fw)) {
   1062   1.1     rmind 		goto err;
   1063   1.1     rmind 	}
   1064  1.25     rmind 	conkey = dnvlist_get_nvlist(cdict, "back-key", NULL);
   1065  1.20  christos 	bk = &con->c_back_entry;
   1066  1.25     rmind 	if (conkey == NULL || !npf_connkey_import(conkey, bk)) {
   1067   1.1     rmind 		goto err;
   1068   1.1     rmind 	}
   1069   1.1     rmind 	fw->ck_backptr = bk->ck_backptr = con;
   1070   1.1     rmind 
   1071   1.1     rmind 	/* Insert the entries and the connection itself. */
   1072   1.1     rmind 	if (!npf_conndb_insert(cd, fw, con)) {
   1073   1.1     rmind 		goto err;
   1074   1.1     rmind 	}
   1075   1.1     rmind 	if (!npf_conndb_insert(cd, bk, con)) {
   1076   1.1     rmind 		npf_conndb_remove(cd, fw);
   1077   1.1     rmind 		goto err;
   1078   1.1     rmind 	}
   1079  1.12     rmind 
   1080  1.12     rmind 	NPF_PRINTF(("NPF: imported conn %p\n", con));
   1081   1.1     rmind 	npf_conndb_enqueue(cd, con);
   1082   1.1     rmind 	return 0;
   1083   1.1     rmind err:
   1084  1.22  christos 	npf_conn_destroy(npf, con);
   1085   1.1     rmind 	return EINVAL;
   1086   1.1     rmind }
   1087   1.1     rmind 
   1088  1.20  christos int
   1089  1.25     rmind npf_conn_find(npf_t *npf, const nvlist_t *idict, nvlist_t **odict)
   1090  1.20  christos {
   1091  1.25     rmind 	const nvlist_t *kdict;
   1092  1.20  christos 	npf_connkey_t key;
   1093  1.20  christos 	npf_conn_t *con;
   1094  1.20  christos 	uint16_t dir;
   1095  1.20  christos 	bool forw;
   1096  1.20  christos 
   1097  1.25     rmind 	kdict = dnvlist_get_nvlist(idict, "key", NULL);
   1098  1.25     rmind 	if (!kdict || !npf_connkey_import(kdict, &key)) {
   1099  1.20  christos 		return EINVAL;
   1100  1.25     rmind 	}
   1101  1.25     rmind 	dir = dnvlist_get_number(idict, "direction", 0);
   1102  1.22  christos 	con = npf_conndb_lookup(npf->conn_db, &key, &forw);
   1103  1.20  christos 	if (con == NULL) {
   1104  1.20  christos 		return ESRCH;
   1105  1.20  christos 	}
   1106  1.20  christos 	if (!npf_conn_ok(con, dir, true)) {
   1107  1.20  christos 		atomic_dec_uint(&con->c_refcnt);
   1108  1.20  christos 		return ESRCH;
   1109  1.20  christos 	}
   1110  1.22  christos 	*odict = npf_conn_export(npf, con);
   1111  1.20  christos 	atomic_dec_uint(&con->c_refcnt);
   1112  1.25     rmind 	return *odict ? 0 : ENOSPC;
   1113  1.20  christos }
   1114  1.20  christos 
   1115   1.1     rmind #if defined(DDB) || defined(_NPF_TESTING)
   1116   1.1     rmind 
   1117   1.1     rmind void
   1118   1.1     rmind npf_conn_print(const npf_conn_t *con)
   1119   1.1     rmind {
   1120   1.1     rmind 	const u_int alen = NPF_CONN_GETALEN(&con->c_forw_entry);
   1121   1.1     rmind 	const uint32_t *fkey = con->c_forw_entry.ck_key;
   1122   1.1     rmind 	const uint32_t *bkey = con->c_back_entry.ck_key;
   1123   1.1     rmind 	const u_int proto = con->c_proto;
   1124  1.22  christos 	struct timespec tspnow;
   1125   1.1     rmind 	const void *src, *dst;
   1126   1.1     rmind 	int etime;
   1127   1.1     rmind 
   1128  1.22  christos 	getnanouptime(&tspnow);
   1129   1.1     rmind 	etime = npf_state_etime(&con->c_state, proto);
   1130   1.1     rmind 
   1131  1.22  christos 	printf("%p:\n\tproto %d flags 0x%x tsdiff %ld etime %d\n", con,
   1132  1.22  christos 	    proto, con->c_flags, (long)(tspnow.tv_sec - con->c_atime), etime);
   1133   1.1     rmind 
   1134   1.1     rmind 	src = &fkey[2], dst = &fkey[2 + (alen >> 2)];
   1135   1.1     rmind 	printf("\tforw %s:%d", npf_addr_dump(src, alen), ntohs(fkey[1] >> 16));
   1136   1.1     rmind 	printf("-> %s:%d\n", npf_addr_dump(dst, alen), ntohs(fkey[1] & 0xffff));
   1137   1.1     rmind 
   1138   1.1     rmind 	src = &bkey[2], dst = &bkey[2 + (alen >> 2)];
   1139   1.1     rmind 	printf("\tback %s:%d", npf_addr_dump(src, alen), ntohs(bkey[1] >> 16));
   1140   1.1     rmind 	printf("-> %s:%d\n", npf_addr_dump(dst, alen), ntohs(bkey[1] & 0xffff));
   1141   1.1     rmind 
   1142   1.1     rmind 	npf_state_dump(&con->c_state);
   1143   1.1     rmind 	if (con->c_nat) {
   1144   1.1     rmind 		npf_nat_dump(con->c_nat);
   1145   1.1     rmind 	}
   1146   1.1     rmind }
   1147   1.1     rmind 
   1148   1.1     rmind #endif
   1149