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