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