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