The FreeRADIUS server $Id: f3670dba8951ca10eb4948feb3dc3db9423a334f $
Loading...
Searching...
No Matches
master.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: bdecedb78c9e09405bd88c140e129535b50dfb68 $
19 * @file io/master.c
20 * @brief Master IO handler
21 *
22 * @copyright 2018 Alan DeKok (aland@freeradius.org)
23 */
24#include <freeradius-devel/io/listen.h>
25#include <freeradius-devel/io/master.h>
26
27
28#include <freeradius-devel/util/debug.h>
29
30#include <freeradius-devel/util/syserror.h>
31
32typedef struct {
33 fr_event_list_t *el; //!< event list, for the master socket.
34 fr_network_t *nr; //!< network for the master socket
35
36 fr_trie_t *trie; //!< trie of clients
37 fr_heap_t *pending_clients; //!< heap of pending clients
38 fr_heap_t *alive_clients; //!< heap of active dynamic clients
39
40 fr_listen_t *listen; //!< The master IO path
41 fr_listen_t *child; //!< The child (app_io) IO path
42 fr_schedule_t *sc; //!< the scheduler
43
44 // @todo - count num_nak_clients, and num_nak_connections, too
45 uint32_t num_connections; //!< number of dynamic connections
46 uint32_t num_pending_packets; //!< number of pending packets
47 uint64_t client_id; //!< Unique client identifier.
48
49 struct {
50 fr_rate_limit_t accept_failed;
51 fr_rate_limit_t alloc_failed;
52 fr_rate_limit_t bad_type;
53 fr_rate_limit_t conn_alloc_failed;
54 fr_rate_limit_t max_connections;
55 fr_rate_limit_t queue_full;
56 fr_rate_limit_t repeat_nak;
57 fr_rate_limit_t too_many_pending;
58 fr_rate_limit_t tracking_failed;
59 fr_rate_limit_t unknown_client;
60 } rate_limit;
62
63/** A saved packet
64 *
65 */
74
75
76/** Client states
77 *
78 */
79typedef enum {
81 PR_CLIENT_STATIC, //!< static / global clients
82 PR_CLIENT_NAK, //!< negative cache entry
83 PR_CLIENT_DYNAMIC, //!< dynamically defined client
84 PR_CLIENT_CONNECTED, //!< dynamically defined client in a connected socket
85 PR_CLIENT_PENDING, //!< dynamic client pending definition
87
88/*
89 * Dynamic clients are run through the normal src/process/foo state machine.
90 *
91 * request->async->packet_ctx is an fr_io_track_t
92 *
93 * track->dynamic is set to a non-zero value.
94 *
95 * The dynamic client code returns a buffer of 1 byte for a NAK.
96 *
97 * If the client creation is successful, then it does talloc(NULL, fr_client_t),
98 * fills out the structure, and sends the pointer in the buffer (8 bytes).
99 *
100 * This code will take over ownership of the structure, and
101 * create the dynamic client.
102 */
103
105
106/** Client definitions for master IO
107 *
108 */
110 fr_io_connection_t *connection; //!< parent connection
111 fr_io_client_state_t state; //!< state of this client
112 fr_ipaddr_t src_ipaddr; //!< packets come from this address
113 fr_ipaddr_t network; //!< network for dynamic clients
114 fr_client_t *radclient; //!< old-style definition of this client
115
116 int packets; //!< number of packets using this client
117 fr_heap_index_t pending_id; //!< for pending clients
118 fr_heap_index_t alive_id; //!< for all clients
119
120 bool use_connected; //!< does this client allow connected sub-sockets?
121 bool ready_to_delete; //!< are we ready to delete this client?
122 bool in_trie; //!< is the client in the trie?
123
124 fr_io_instance_t const *inst; //!< parent instance for master IO handler
126 fr_timer_t *ev; //!< when we clean up the client
127 fr_rb_tree_t *table; //!< tracking table for packets
128
129 fr_heap_t *pending; //!< pending packets for this client
130 fr_hash_table_t *addresses; //!< list of src/dst addresses used by this client
131
132 pthread_mutex_t mutex; //!< for parent / child signaling
133 fr_hash_table_t *ht; //!< for tracking connected sockets
134};
135
136/** Track a connection
137 *
138 * This structure contains information about the connection,
139 * a pointer to the library instance so that we can clean up on exit,
140 * and the listener.
141 *
142 * It also points to a client structure which is for this connection,
143 * and only this connection.
144 *
145 * Finally, a pointer to the parent client, so that the child can
146 * tell the parent it's alive, and the parent can push packets to the
147 * child.
148 */
150 char const *name; //!< taken from proto_FOO_TRANSPORT
151 int packets; //!< number of packets using this connection
152 fr_io_address_t *address; //!< full information about the connection.
153 fr_listen_t *listen; //!< master listener for this socket
154 fr_listen_t *child; //!< child listener (app_io) for this socket
155 fr_io_client_t *client; //!< our local client (pending or connected).
156 fr_io_client_t *parent; //!< points to the parent client.
157 module_instance_t *mi; //!< for submodule
158
159 bool dead; //!< roundabout way to get the network side to close a socket
160 bool paused; //!< event filter doesn't like resuming something that isn't paused
161 bool in_parent_hash; //!< for tracking thread issues
162 fr_event_list_t *el; //!< event list for this connection
163 fr_network_t *nr; //!< network for this connection
164};
165
168 { 0 }
169};
170
173 { 0 }
174};
175
176static int track_free(fr_io_track_t *track)
177{
178 FR_TIMER_DELETE_RETURN(&track->ev);
179 talloc_free_children(track);
180
181 fr_assert(track->client->packets > 0);
182 track->client->packets--;
183
184 return 0;
185}
186
188{
189 fr_assert(track->client->table != NULL);
190
191 /*
192 * If the tree is being freed, then we don't try to remove ourselves from it. Doing so would
193 * free this node, and therefore corrupt the tree.
194 *
195 * The talloc code will take care of cleaning up the children and events when this chunk is
196 * freed.
197 */
198 if (track->client->table->being_freed) return 0;
199
200 fr_assert(fr_rb_find(track->client->table, track) != NULL);
201
202 if (!fr_rb_delete(track->client->table, track)) {
203 fr_assert(0);
204 }
205
206 return track_free(track);
207}
208
209/*
210 * Return negative numbers to put 'one' at the top of the heap.
211 * Return positive numbers to put 'two' at the top of the heap.
212 */
213static int8_t pending_packet_cmp(void const *one, void const *two)
214{
217 int ret;
218
219 /*
220 * Higher priority elements are larger than lower
221 * priority elements. So if "a" is larger than "b", we
222 * wish to prefer "a".
223 */
224 ret = CMP_PREFER_LARGER(a->priority, b->priority);
225 if (ret != 0) return ret;
226
227 /*
228 * Smaller numbers mean packets were received earlier.
229 * We want to process packets in time order. So if "a"
230 * is smaller than "b", we wish to prefer "a".
231 *
232 * After that, it doesn't really matter what order the
233 * packets go in. Since we'll never have two identical
234 * "recv_time" values, the code should never get here.
235 */
237}
238
239/*
240 * Order clients in the pending_clients heap, based on the
241 * packets that they contain.
242 */
243static int8_t pending_client_cmp(void const *one, void const *two)
244{
245 fr_io_pending_packet_t const *a;
246 fr_io_pending_packet_t const *b;
247
250
251 a = fr_heap_peek(c1->pending);
252 b = fr_heap_peek(c2->pending);
253
254 fr_assert(a != NULL);
255 fr_assert(b != NULL);
256
257 return pending_packet_cmp(a, b);
258}
259
260
261static int8_t address_cmp(void const *one, void const *two)
262{
265 int8_t ret;
266
267 CMP_RETURN(a, b, socket.inet.src_port);
268 CMP_RETURN(a, b, socket.inet.dst_port);
269 CMP_RETURN(a, b, socket.inet.ifindex);
270
271 ret = fr_ipaddr_cmp(&a->socket.inet.src_ipaddr, &b->socket.inet.src_ipaddr);
272 if (ret != 0) return ret;
273
274 return fr_ipaddr_cmp(&a->socket.inet.dst_ipaddr, &b->socket.inet.dst_ipaddr);
275}
276
277static uint32_t connection_hash(void const *ctx)
278{
281
282 hash = fr_hash(&c->address->socket.inet.src_ipaddr, sizeof(c->address->socket.inet.src_ipaddr));
283 hash = fr_hash_update(&c->address->socket.inet.src_port, sizeof(c->address->socket.inet.src_port), hash);
284
285 hash = fr_hash_update(&c->address->socket.inet.ifindex, sizeof(c->address->socket.inet.ifindex), hash);
286
287 hash = fr_hash_update(&c->address->socket.inet.dst_ipaddr, sizeof(c->address->socket.inet.dst_ipaddr), hash);
288 return fr_hash_update(&c->address->socket.inet.dst_port, sizeof(c->address->socket.inet.dst_port), hash);
289}
290
291static int8_t connection_cmp(void const *one, void const *two)
292{
295
296 return address_cmp(a->address, b->address);
297}
298
299
300static int8_t track_cmp(void const *one, void const *two)
301{
304 int ret;
305
306 fr_assert(a->client != NULL);
307 fr_assert(b->client != NULL);
308 fr_assert(a->client == b->client); /* tables are per-client */
309
312
313 /*
314 * Unconnected sockets must check src/dst ip/port.
315 */
316 ret = address_cmp(a->address, b->address);
317 if (ret != 0) return ret;
318
319 /*
320 * Call the per-protocol comparison function.
321 */
324 a->client->radclient,
325 a->packet, b->packet);
326 return CMP(ret, 0);
327}
328
329
330static int8_t track_connected_cmp(void const *one, void const *two)
331{
334 int ret;
335
336 fr_assert(a->client != NULL);
337 fr_assert(b->client != NULL);
338
341 fr_assert(a->client == b->client);
343
344 /*
345 * Note that we pass the connection "client", as
346 * we may do negotiation specific to this connection.
347 */
351 a->packet, b->packet);
352 return CMP(ret, 0);
353}
354
355
357{
358 fr_io_client_t *client;
359 fr_io_pending_packet_t *pending;
360
361 client = fr_heap_pop(&thread->pending_clients);
362 if (!client) {
363 fr_assert(thread->num_pending_packets == 0);
364
365 /*
366 * 99% of the time we don't have pending clients.
367 * So we might as well free this, so that the
368 * caller doesn't keep checking us for every packet.
369 */
371 thread->pending_clients = NULL;
372 return NULL;
373 }
374
375 pending = fr_heap_pop(&client->pending);
376 fr_assert(pending != NULL);
377
378 /*
379 * If the client has more packets pending, add it back to
380 * the heap.
381 */
382 if (fr_heap_num_elements(client->pending) > 0) {
383 if (fr_heap_insert(&thread->pending_clients, client) < 0) {
384 fr_assert(0 == 1);
385 }
386 }
387
388 fr_assert(thread->num_pending_packets > 0);
389 thread->num_pending_packets--;
390
391 return pending;
392}
393
394static fr_client_t *radclient_clone(TALLOC_CTX *ctx, fr_client_t const *parent)
395{
396 fr_client_t *c;
397
398 if (!parent) return NULL;
399
400 c = talloc_zero(ctx, fr_client_t);
401 if (!c) return NULL;
402
403 /*
404 * Do NOT set ipaddr or src_ipaddr. The caller MUST do this!
405 */
406
407#define DUP_FIELD(_x) do { if (parent->_x) {c->_x = talloc_strdup(c, parent->_x); if (!c->_x) {goto error;}}} while (0)
408#define COPY_FIELD(_x) c->_x = parent->_x
409
410 DUP_FIELD(longname);
411 DUP_FIELD(shortname);
413 DUP_FIELD(nas_type);
414 DUP_FIELD(server);
415
416 COPY_FIELD(require_message_authenticator);
417 COPY_FIELD(require_message_authenticator_is_set);
418#ifdef NAS_VIOLATES_RFC
419 COPY_FIELD(allow_vulnerable_clients);
420#endif
421 COPY_FIELD(limit_proxy_state);
422 COPY_FIELD(limit_proxy_state_is_set);
423 COPY_FIELD(received_message_authenticator);
424 COPY_FIELD(first_packet_no_proxy_state);
425 /* dynamic MUST be false */
426 COPY_FIELD(server_cs);
427 COPY_FIELD(cs);
428 COPY_FIELD(proto);
429 COPY_FIELD(active);
430
431 COPY_FIELD(use_connected);
432
433#ifdef WITH_TLS
434 COPY_FIELD(tls_required);
435#endif
436
437 c->ipaddr = parent->ipaddr;
438 c->src_ipaddr = parent->src_ipaddr;
439
440 return c;
441
442 /*
443 * @todo - fill in other fields, too!
444 */
445
446error:
447 talloc_free(c);
448 return NULL;
449}
450#undef COPY_FIELD
451#undef DUP_FIELD
452
453
454/** Count the number of connections used by active clients.
455 *
456 * Unfortunately, we also count NAK'd connections, too, even if they
457 * are closed. The alternative is to walk through all connections
458 * for each client, which would be a long time.
459 */
460static int count_connections(UNUSED uint8_t const *key, UNUSED size_t keylen, void *data, void *ctx)
461{
462 fr_io_client_t *client = talloc_get_type_abort(data, fr_io_client_t);
463 int connections;
464
465 pthread_mutex_lock(&client->mutex);
466
467 if (!client->ht) {
468 pthread_mutex_unlock(&client->mutex);
469 return 0;
470 }
471
472 connections = fr_hash_table_num_elements(client->ht);
473 pthread_mutex_unlock(&client->mutex);
474
475 /*
476 * Don't check "use_connected". Pending dynamic clients get an entry in the connection tracking
477 * table before the client is defined, and therefore before "use_connected" is set. As a result,
478 * we can't check the value of "use_connected" until much later.
479 */
480
481 *((uint32_t *) ctx) += connections;
482
483 return 0;
484}
485
486
487static int _client_free(fr_io_client_t *client)
488{
489 /*
490 * The mutex is initialized whenever the connection tracking table is created, which can happen
491 * for pending clients which do not (yet) have "use_connected" set. Since the mutex creation is
492 * conditional on the existence of the connection tracking table, we make the mutex deletion
493 * conditional on the existence of the tracking table.
494 */
495 if (client->ht) (void) pthread_mutex_destroy(&client->mutex);
496
497 TALLOC_FREE(client->pending);
498
499 return 0;
500}
501
503{
504 size_t num;
505
506 fr_assert(!client->connection);
507
508 if (!client->pending) return;
509
510 num = fr_heap_num_elements(client->pending);
511
512 fr_assert(client->thread->num_pending_packets >= num);
513 client->thread->num_pending_packets -= num;
514
515 TALLOC_FREE(client->pending);
516}
517
518
519static int connection_free(fr_io_connection_t *connection)
520{
521 /*
522 * This is it's own talloc context, as there are
523 * thousands of packets associated with it.
524 */
525 TALLOC_FREE(connection->client);
526
527 return 0;
528}
529
530/** Create a new connection.
531 *
532 * Called ONLY from the master socket.
533 */
535 fr_io_thread_t *thread,
536 fr_io_client_t *client, int fd,
537 fr_io_address_t *address,
539{
540 int ret;
541 fr_io_connection_t *connection;
542 module_instance_t *mi = NULL;
543 fr_listen_t *li;
544 fr_client_t *radclient;
545
546
547 /*
548 * Reload the app_io module as a "new" library. This
549 * causes the link count for the library to be correct.
550 * It also allocates a new instance data for it, too.
551 * Passing CONF_SECTION of NULL ensures that there's no
552 * config for it, as we'll just clone it's contents from
553 * the original. It also means that detach should be
554 * called when the instance data is freed.
555 */
556 if (!nak) {
557 CONF_SECTION *cs;
558 char *inst_name;
559
560 if (inst->max_connections || client->radclient->limit.max_connections) {
561 uint32_t max_connections = inst->max_connections ? inst->max_connections : client->radclient->limit.max_connections;
562
563 /*
564 * We've hit the connection limit. Walk
565 * over all clients with connections, and
566 * count the number of connections used.
567 */
568 if (thread->num_connections >= max_connections) {
569 thread->num_connections = 0;
570
571 (void) fr_trie_walk(thread->trie, &thread->num_connections, count_connections);
572
573 if ((thread->num_connections + 1) >= max_connections) {
574 RATE_LIMIT_LOCAL(&thread->rate_limit.max_connections, INFO,
575 "proto_%s - Ignoring connection from client %s - 'max_connections' limit reached.",
576 inst->app->common.name, client->radclient->shortname);
577 if (fd >= 0) close(fd);
578 return NULL;
579 }
580 }
581 }
582
583 /*
584 * Add a client module into a sublist
585 */
586 inst_name = talloc_asprintf(NULL, "%"PRIu64, thread->client_id++);
587 mi = module_instance_copy(inst->clients, inst->submodule, inst_name);
588 talloc_free(inst_name);
589
590 cs = cf_section_dup(mi, NULL, inst->submodule->conf,
591 cf_section_name1(inst->submodule->conf),
592 cf_section_name2(inst->submodule->conf), false);
593
594 /*
595 * Clear the "dynamic_clients" flag, so that the child instantiate routines don't check
596 * the network allow / deny list when instantiating child connections.
597 *
598 * This is a short-term and minimal hack to get the problem fixed. A longer term
599 * solution would be to update fr_master_io_network() so that it sets caches the trie
600 * _and_ the dynamic client flag in connection data structure. Which then means that the
601 * mod_network_get() API could also go away.
602 *
603 * But doing that involves more rearchitecture and code changes, which we're avoiding at
604 * this time.
605 */
606 cf_pair_replace_or_add(cs, "dynamic_clients", "no");
607
608 if (module_instance_conf_parse(mi, cs) < 0) {
609 cf_log_err(inst->server_cs, "Failed parsing module config");
610 goto cleanup;
611 }
612
613 /* Thread local module lists never run bootstrap */
614 if (module_instantiate(mi) < 0) {
615 cf_log_err(inst->server_cs, "Failed instantiating module");
616 goto cleanup;
617 }
618
619 if (module_thread_instantiate(mi, mi, thread->el) < 0) {
620 cf_log_err(inst->server_cs, "Failed instantiating module");
621 goto cleanup;
622 }
623
624 /*
625 * FIXME - Instantiate the new module?!
626 */
627 fr_assert(mi != NULL);
628 } else {
629 mi = talloc_init_const("nak");
630 }
631
632 MEM(connection = talloc_zero(mi, fr_io_connection_t));
633 MEM(connection->address = talloc_memdup(connection, address, sizeof(*address)));
634 (void) talloc_set_name_const(connection->address, "fr_io_address_t");
635
636 connection->parent = client;
637 connection->mi = mi;
638
639 MEM(connection->client = talloc_named(NULL, sizeof(fr_io_client_t), "fr_io_client_t"));
640 memset(connection->client, 0, sizeof(*connection->client));
641
642 MEM(connection->client->radclient = radclient = radclient_clone(connection->client, client->radclient));
643
644 talloc_set_destructor(connection->client, _client_free);
645 talloc_set_destructor(connection, connection_free);
646
649 connection->client->connection = connection;
650
651 /*
652 * Create the packet tracking table for this client.
653 *
654 * #todo - unify the code with static clients?
655 */
656 if (inst->app_io->track_duplicates) {
657 MEM(connection->client->table = fr_rb_inline_talloc_alloc(client, fr_io_track_t, node,
658 track_connected_cmp, NULL));
659 }
660
661 /*
662 * Set this radclient to be dynamic, and active.
663 */
664 radclient->dynamic = true;
665 radclient->active = true;
666
667 /*
668 * address->socket.inet.client points to a "static" client. We want
669 * to clean up everything associated with the connection
670 * when it closes. So we need to point to our own copy
671 * of the client here.
672 */
673 connection->address->radclient = connection->client->radclient;
674 connection->client->inst = inst;
675 connection->client->thread = thread;
676
677 /*
678 * Create a heap for packets which are pending for this
679 * client.
680 */
681 MEM(connection->client->pending = fr_heap_alloc(connection->client, pending_packet_cmp,
682 fr_io_pending_packet_t, heap_id, 0));
683
684 /*
685 * Clients for connected sockets are always a /32 or /128.
686 */
687 connection->client->src_ipaddr = address->socket.inet.src_ipaddr;
688 connection->client->network = address->socket.inet.src_ipaddr;
689
690 /*
691 * Don't initialize mutex or hash table.
692 * Connections cannot spawn other connections.
693 */
694
695 /*
696 * If this client state is pending, then the connection
697 * state is pending, too. That allows NAT gateways to be
698 * defined dynamically, AND for them to have multiple
699 * connections, each with a different client. This
700 * allows for different shared secrets to be used for
701 * different connections. Once the client gets defined
702 * for this connection, it will be either "connected" or
703 * not. If connected, then the parent client remains
704 * PENDING. Otherwise, the parent client is moved to
705 * DYNAMIC
706 *
707 * If this client state is static or dynamic,
708 * then we're just using connected sockets behind
709 * that client. The connections here all use the
710 * same shared secret, but they use different
711 * sockets, so they allow for sharing of IO
712 * across CPUs / threads.
713 */
714 switch (client->state) {
716 connection->client->state = PR_CLIENT_PENDING;
717
718 /*
719 * Needed for rlm_radius, which refuses to proxy packets
720 * that define a dynamic client.
721 */
722 radclient->active = false;
723 break;
724
725 case PR_CLIENT_STATIC:
727 connection->client->state = PR_CLIENT_CONNECTED;
728 break;
729
731 case PR_CLIENT_NAK:
733 fr_assert(0 == 1);
734 goto cleanup;
735 }
736
737 if (!nak) {
738 /*
739 * Get the child listener.
740 */
741 MEM(li = connection->child = talloc(connection, fr_listen_t));
742 memcpy(li, thread->listen, sizeof(*li));
743
744 /*
745 * Glue in the actual app_io
746 */
747 li->connected = true;
748 li->app_io = thread->child->app_io;
749 li->cs = inst->app_io_conf;
750 li->thread_instance = connection;
751 li->app_io_instance = mi->data;
753
754 /*
755 * Create writable thread instance data.
756 */
757 connection->child->thread_instance = talloc_zero_array(NULL, uint8_t,
758 inst->app_io->common.thread_inst_size);
759 talloc_set_destructor(connection->child, fr_io_listen_free);
760 talloc_set_name(connection->child->thread_instance, "proto_%s_thread_t",
761 inst->app_io->common.name);
762
763 /*
764 * This is "const", and the user can't
765 * touch it. So we just reuse the same
766 * configuration everywhere.
767 */
768 connection->child->app_io_instance = inst->app_io_instance;
769
770 /*
771 * Create the listener, based on our listener.
772 */
773 MEM(li = connection->listen = talloc(connection, fr_listen_t));
774
775 /*
776 * Note that our instance is effectively 'const'.
777 *
778 * i.e. we can't add things to it. Instead, we have to
779 * put all variable data into the connection.
780 */
781 memcpy(li, thread->listen, sizeof(*li));
782
783 /*
784 * Glue in the connection to the listener.
785 */
787
788 li->connected = true;
789 li->thread_instance = connection;
790 li->cs = inst->app_io_conf;
793
794 /*
795 * Instantiate the child, and open the socket.
796 */
797 fr_assert(inst->app_io->connection_set != NULL);
798
799 if (inst->app_io->connection_set(connection->child, connection->address) < 0) {
800 DEBUG("proto_%s - Failed setting connection for socket.", inst->app->common.name);
801 goto cleanup;
802 }
803
804 /*
805 * UDP sockets: open a new socket, and then
806 * connect it to the client. This emulates the
807 * behavior of accept().
808 *
809 * Note that there is a small window between the
810 * bind() and connect() where UDP packets for the
811 * wildcard socket can get received by this
812 * socket. We hope that this time frame is as
813 * small as possible.
814 *
815 * i.e. we ignore the problem, and don't
816 * currently check dst ip/port for UDP packets
817 * received on connected sockets.
818 */
819 if (fd < 0) {
820 socklen_t salen;
821 struct sockaddr_storage src;
822
823 if (fr_ipaddr_to_sockaddr(&src, &salen,
824 &connection->address->socket.inet.src_ipaddr,
825 connection->address->socket.inet.src_port) < 0) {
826 DEBUG("proto_%s - Failed getting IP address", inst->app->common.name);
827 talloc_free(mi);
828 return NULL;
829 }
830
831 if (inst->app_io->open(connection->child) < 0) {
832 DEBUG("proto_%s - Failed opening connected socket.", inst->app->common.name);
833 talloc_free(mi);
834 return NULL;
835 }
836
837 fd = connection->child->fd;
838
839 if (connect(fd, (struct sockaddr *) &src, salen) < 0) {
840 ERROR("proto_%s - Failed in connect: %s", inst->app->common.name, fr_syserror(errno));
841 goto cleanup;
842 }
843 } else {
844 connection->child->fd = fd;
845 }
846
847 /*
848 * Set the new FD, and get the module to set it's connection name.
849 */
850 if (inst->app_io->fd_set(connection->child, fd) < 0) {
851 DEBUG3("Failed setting FD to %s", inst->app_io->common.name);
852 goto cleanup;
853 }
854
855 li->fd = fd;
856
857 if (!inst->app_io->get_name) {
858 connection->name = fr_asprintf(connection, "proto_%s from client %pV port "
859 "%u to server %pV port %u",
860 inst->app->common.name,
861 fr_box_ipaddr(connection->address->socket.inet.src_ipaddr),
862 connection->address->socket.inet.src_port,
863 fr_box_ipaddr(connection->address->socket.inet.dst_ipaddr),
864 connection->address->socket.inet.dst_port);
865 } else {
866 connection->name = inst->app_io->get_name(connection->child);
867 }
868
869 /*
870 * Set the names for the listeners.
871 */
872 connection->listen->name = connection->name;
873 connection->child->name = connection->name;
874 }
875
876 /*
877 * If the parent client is still PENDING, lazily create the hash table that tracks its child
878 * connections. We need this so that fr_io_connection_allow() can later find any sibling
879 * connections, and add them to the scheduler once the dynamic client is defined.
880 */
881 if ((client->state == PR_CLIENT_PENDING) && !client->ht) {
882 (void) pthread_mutex_init(&client->mutex, NULL);
883 MEM(client->ht = fr_hash_table_alloc(client, connection_hash, connection_cmp, NULL));
884 }
885
886 /*
887 * Add the connection to the set of connections for this client. Capture the pre-insert size so
888 * we can tell whether this is the first connection (which runs the dynamic-client verification)
889 * or a later connection (which is deferred until the first connection is verified).
890 */
891 pthread_mutex_lock(&client->mutex);
892 if (client->ht) {
893 size_t pre_size = fr_hash_table_num_elements(client->ht);
894
895 if (nak) (void) fr_hash_table_delete(client->ht, nak);
896 ret = fr_hash_table_insert(client->ht, connection);
897 client->ready_to_delete = false;
898 connection->in_parent_hash = true;
899
900 if (!ret) {
901 pthread_mutex_unlock(&client->mutex);
902 ERROR("proto_%s - Failed inserting connection into tracking table. "
903 "Closing it, and discarding all packets for connection %s.",
904 inst->app_io->common.name, connection->name);
905 goto cleanup;
906 }
907
908 /*
909 * The first connection for a PENDING parent runs the dynamic client definition. All
910 * later connections will be scheduled by fr_io_connection_allow(), once the parent is
911 * defined (or not). nak placeholders are never scheduled, so they don't count.
912 */
913 if (!nak && (client->state == PR_CLIENT_PENDING) && (pre_size > 0)) {
914 pthread_mutex_unlock(&client->mutex);
915 DEBUG("proto_%s - deferring scheduling of connection %s until parent client %pV is defined",
916 inst->app_io->common.name, connection->name, fr_box_ipaddr(client->src_ipaddr));
917 thread->num_connections++;
918 return connection;
919 }
920 }
921 pthread_mutex_unlock(&client->mutex);
922
923 /*
924 * It's a NAK client. Set the state to NAK, and don't
925 * add it to the scheduler.
926 */
927 if (nak) {
928 INFO("proto_%s - Verification failed for packet from dynamic client %pV - adding IP address to the NAK cache",
929 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
930
931 connection->name = talloc_strdup(connection, nak->name);
932 connection->client->state = PR_CLIENT_NAK;
933 connection->el = nak->el;
934 return connection;
935 }
936
937 DEBUG("proto_%s - starting connection %s", inst->app_io->common.name, connection->name);
938 connection->nr = fr_schedule_listen_add(thread->sc, connection->listen);
939 if (!connection->nr) {
940 ERROR("proto_%s - Failed inserting connection into scheduler. "
941 "Closing it, and diuscarding all packets for connection %s.",
942 inst->app_io->common.name, connection->name);
943 pthread_mutex_lock(&client->mutex);
944 if (client->ht) (void) fr_hash_table_delete(client->ht, connection);
945 pthread_mutex_unlock(&client->mutex);
946
947 cleanup:
948 if (fd >= 0) close(fd);
949 talloc_free(mi);
950 return NULL;
951 }
952
953 /*
954 * We have one more connection. Note that we do
955 * NOT decrement this counter when a connection
956 * closes, as the close is done in a child
957 * thread. Instead, we just let counter hit the
958 * limit, and then walk over the clients to reset
959 * the count.
960 */
961 thread->num_connections++;
962
963 return connection;
964}
965
966
967/*
968 * And here we go into the rabbit hole...
969 *
970 * @todo future - have a similar structure
971 * fr_io_connection_io, which will duplicate some code,
972 * but may make things simpler?
973 */
974static void get_inst(fr_listen_t *li, fr_io_instance_t const **inst, fr_io_thread_t **thread,
975 fr_io_connection_t **connection, fr_listen_t **child)
976{
977 if (!li->connected) {
978 *inst = li->app_io_instance;
979 if (thread) *thread = li->thread_instance;
980 *connection = NULL;
981 if (child) *child = ((fr_io_thread_t *)li->thread_instance)->child;
982
983 } else {
984 fr_assert(connection != NULL);
985
986 *connection = li->thread_instance;
987 *inst = (*connection)->client->inst;
988 if (thread) *thread = NULL;
989 if (child) *child = (*connection)->child;
990 }
991}
992
993
994static fr_client_t *radclient_alloc(TALLOC_CTX *ctx, int ipproto, fr_io_address_t *address)
995{
996 fr_client_t *radclient;
997 char *shortname;
998
999 MEM(radclient = talloc_zero(ctx, fr_client_t));
1000
1001 fr_value_box_aprint(radclient, &shortname, fr_box_ipaddr(address->socket.inet.src_ipaddr), NULL);
1002 radclient->longname = radclient->shortname = shortname;
1003
1004 radclient->secret = radclient->nas_type = talloc_strdup(radclient, "");
1005
1006 radclient->ipaddr = address->socket.inet.src_ipaddr;
1007
1008 radclient->src_ipaddr = address->socket.inet.dst_ipaddr;
1009
1010 radclient->proto = ipproto;
1011 radclient->dynamic = true;
1012
1013 return radclient;
1014}
1015
1016/*
1017 * Remove a client from the list of "live" clients.
1018 *
1019 * This function is only used for the "main" socket. Clients
1020 * from connections do not use it.
1021 */
1023{
1024 talloc_get_type_abort(client, fr_io_client_t);
1025
1026 fr_assert(client->in_trie);
1027 fr_assert(!client->connection);
1028 fr_assert(client->thread);
1029
1030 if (client->pending) client_pending_free(client);
1031
1032 (void) fr_trie_remove_by_key(client->thread->trie, &client->src_ipaddr.addr, client->src_ipaddr.prefix);
1033
1034 if (client->thread->alive_clients) {
1036 (void) fr_heap_extract(&client->thread->alive_clients, client);
1037 }
1038
1039 /*
1040 * The mutex/ht pair is initialized either for use_connected
1041 * clients (in client_alloc) or for PENDING clients with
1042 * deferred sibling connections (in fr_io_connection_alloc).
1043 * The ht pointer is the canonical signal that the mutex
1044 * was initialized.
1045 */
1046 if (client->ht) (void) pthread_mutex_destroy(&client->mutex);
1047
1048 return 0;
1049}
1050
1051/** Allocate a dynamic client.
1052 *
1053 */
1054static fr_io_client_t *client_alloc(TALLOC_CTX *ctx, fr_io_client_state_t state,
1055 fr_io_instance_t const *inst, fr_io_thread_t *thread, fr_client_t *radclient,
1056 fr_ipaddr_t const *network)
1057{
1058 fr_io_client_t *client;
1059
1060 /*
1061 * Create our own local client. This client
1062 * holds our state which really shouldn't go into
1063 * fr_client_t.
1064 *
1065 * Note that we create a new top-level talloc
1066 * context for this client, as there may be tens
1067 * of thousands of packets associated with this
1068 * client. And we want to avoid problems with
1069 * O(N) issues in talloc.
1070 */
1071 MEM(client = talloc_named(ctx, sizeof(fr_io_client_t), "fr_io_client_t"));
1072 memset(client, 0, sizeof(*client));
1073
1074 client->state = state;
1075 client->src_ipaddr = radclient->ipaddr;
1076 client->radclient = radclient;
1077 client->inst = inst;
1078 client->thread = thread;
1079
1080 if (network) {
1081 client->network = *network;
1082 } else {
1083 client->network = client->src_ipaddr;
1084 }
1085
1086 /*
1087 * At this point, this variable can only be true
1088 * for STATIC clients. PENDING clients may set
1089 * it to true later, after they've been defined.
1090 */
1091 client->use_connected = radclient->use_connected;
1092
1093 /*
1094 * Create the pending heap for pending clients.
1095 */
1096 if (state == PR_CLIENT_PENDING) {
1097 MEM(client->pending = fr_heap_alloc(client, pending_packet_cmp,
1098 fr_io_pending_packet_t, heap_id, 0));
1099 }
1100
1101 /*
1102 * Create the packet tracking table for this client.
1103 */
1104 if (inst->app_io->track_duplicates) {
1105 fr_assert(inst->app_io->track_compare != NULL);
1106 MEM(client->table = fr_rb_inline_talloc_alloc(client, fr_io_track_t, node, track_cmp, NULL));
1107 }
1108
1109 /*
1110 * Allow connected sockets to be set on a
1111 * per-client basis.
1112 */
1113 if (client->use_connected) {
1114 fr_assert(client->state == PR_CLIENT_STATIC);
1115
1116 (void) pthread_mutex_init(&client->mutex, NULL);
1117 MEM(client->ht = fr_hash_table_alloc(client, connection_hash, connection_cmp, NULL));
1118 }
1119
1120 /*
1121 * Add the newly defined client to the trie of
1122 * allowed clients.
1123 */
1124 if (fr_trie_insert_by_key(thread->trie, &client->src_ipaddr.addr, client->src_ipaddr.prefix, client)) {
1125 ERROR("proto_%s - Failed inserting client %s into tracking table. Discarding client, and all packets for it.",
1126 inst->app_io->common.name, client->radclient->shortname);
1127 if (client->ht) (void) pthread_mutex_destroy(&client->mutex);
1128 talloc_free(client);
1129 return NULL;
1130 }
1131
1132 client->in_trie = true;
1133
1134 /*
1135 * It's a static client. Don't insert it into the list of alive clients, as those are only for
1136 * dynamic clients.
1137 */
1138 if (state == PR_CLIENT_STATIC) return client;
1139
1140 fr_assert(thread->alive_clients != NULL);
1141
1142 /*
1143 * Track the live clients so that we can clean
1144 * them up.
1145 */
1146 (void) fr_heap_insert(&thread->alive_clients, client);
1148
1149 /*
1150 * Now that we've inserted it into the heap and
1151 * incremented the numbers, set the destructor
1152 * function.
1153 */
1154 talloc_set_destructor(client, _client_live_free);
1155
1156 return client;
1157}
1158
1159
1161 fr_io_address_t *address,
1162 uint8_t const *packet, size_t packet_len,
1163 fr_time_t recv_time, bool *is_dup)
1164{
1165 size_t len;
1166 fr_io_track_t *track, *old;
1167
1168 *is_dup = false;
1169
1170 /*
1171 * Allocate a new tracking structure. Most of the time
1172 * there are no duplicates, so this is fine.
1173 */
1174 if (client->connection) {
1175 MEM(track = talloc_zero_pooled_object(client->table, fr_io_track_t, 1, sizeof(*track) + 64));
1176 track->address = client->connection->address;
1177 } else {
1178 fr_io_address_t *my_address;
1179
1180 MEM(track = talloc_zero_pooled_object(client->table, fr_io_track_t, 1, sizeof(*track) + sizeof(*track->address) + 64));
1181 MEM(track->address = my_address = talloc(track, fr_io_address_t));
1182
1183 *my_address = *address;
1184 my_address->radclient = client->radclient;
1185 }
1186
1187 track->li = li;
1188 track->client = client;
1189
1190 track->timestamp = recv_time;
1191 track->packets = 1;
1192
1193 /*
1194 * We're not tracking duplicates, so just return the
1195 * tracking entry. This tracks src/dst IP/port, client,
1196 * receive time, etc.
1197 */
1198 if (!client->inst->app_io->track_duplicates) {
1199 client->packets++;
1200 talloc_set_destructor(track, track_free);
1201 return track;
1202 }
1203
1204 /*
1205 * We are checking for duplicates, see if there is a dup
1206 * already in the tree.
1207 */
1208 track->packet = client->inst->app_io->track_create(client->inst->app_io_instance,
1209 client->thread->child->thread_instance,
1210 client->radclient,
1211 track, packet, packet_len);
1212 if (!track->packet) {
1213 talloc_free(track);
1214 return NULL;
1215 }
1216
1217 /*
1218 * No existing duplicate. Return the new tracking entry.
1219 */
1220 old = fr_rb_find(client->table, track);
1221 if (!old) goto do_insert;
1222
1223 fr_assert(old->client == client);
1224
1225 /*
1226 * It cannot be both in the free list and in the tracking table.
1227 *
1228 * 2020-08-17, this assertion fails randomly in travis.
1229 * Which means that "track" was in the free list, *and*
1230 * in the rbtree.
1231 */
1232 fr_assert(old != track);
1233
1234 /*
1235 * The new packet has the same dedup fields as the old
1236 * one, BUT it may be a conflicting packet. Check for
1237 * that via a simple memcmp().
1238 *
1239 * It's an exact duplicate. Drop the new one and
1240 * use the old one.
1241 *
1242 * If there's a cached reply, the caller will take care
1243 * of sending it to the network layer.
1244 */
1245 len = talloc_array_length(old->packet);
1246 if ((len == talloc_array_length(track->packet)) &&
1247 (memcmp(old->packet, track->packet, len) == 0)) {
1248 fr_assert(old != track);
1249
1250 /*
1251 * Ignore duplicates while the client is
1252 * still pending.
1253 */
1254 if (client->state == PR_CLIENT_PENDING) {
1255 DEBUG("Ignoring duplicate packet while client %s is still pending dynamic definition",
1256 client->radclient->shortname);
1257 talloc_free(track);
1258 return NULL;
1259 }
1260
1261 *is_dup = true;
1262 old->packets++;
1263 talloc_free(track);
1264
1265 /*
1266 * Retransmits can sit in the outbound queue for
1267 * a while. We don't want to time out this
1268 * struct while the packet is in the outbound
1269 * queue.
1270 */
1271 FR_TIMER_DISARM(old->ev);
1272 return old;
1273 }
1274
1275 /*
1276 * Else it's a conflicting packet. Which is OK if we
1277 * already have a reply. We just delete the old entry,
1278 * and insert the new one.
1279 *
1280 * If there's no reply, then the old request is still
1281 * "live". Delete the old one from the tracking tree,
1282 * and return the new one.
1283 */
1284 if (old->reply_len || old->do_not_respond) {
1285 talloc_free(old);
1286
1287 } else {
1288 fr_assert(client == old->client);
1289
1290 if (!fr_rb_delete(client->table, old)) {
1291 fr_assert(0);
1292 }
1293 FR_TIMER_DELETE(&old->ev);
1294
1295 talloc_set_destructor(old, track_free);
1296
1297 old->discard = true; /* don't send any reply, there's nowhere for it to go */
1298 }
1299
1300do_insert:
1301 if (!fr_rb_insert(client->table, track)) {
1302 fr_assert(0);
1303 }
1304
1305 client->packets++;
1306 talloc_set_destructor(track, track_dedup_free);
1307 return track;
1308}
1309
1310
1312{
1313 fr_io_track_t *track = pending->track;
1314
1315 /*
1316 * Note that we don't check timestamps, replies, etc. If
1317 * a packet is pending, then any conflicting packet gets
1318 * the "pending" entry marked as such, and a new entry
1319 * added. Any duplicate packet gets suppressed. And
1320 * because the packets are pending, track->reply MUST be
1321 * NULL.
1322 */
1323 fr_assert(track->packets > 0);
1324 track->packets--;
1325
1326 /*
1327 * No more packets using this tracking entry,
1328 * delete it.
1329 */
1330 if (track->packets == 0) talloc_free(track);
1331
1332 return 0;
1333}
1334
1336 uint8_t const *buffer, size_t packet_len,
1337 fr_io_track_t *track,
1338 int priority)
1339{
1340 fr_io_pending_packet_t *pending;
1341
1342 MEM(pending = talloc_zero(client->pending, fr_io_pending_packet_t));
1343
1344 MEM(pending->buffer = talloc_memdup(pending, buffer, packet_len));
1345 pending->buffer_len = packet_len;
1346 pending->priority = priority;
1347 pending->track = track;
1348 pending->recv_time = track->timestamp; /* there can only be one */
1349
1350 talloc_set_destructor(pending, pending_free);
1351
1352 /*
1353 * Insert the pending packet for this client. If it
1354 * fails, silently discard the packet.
1355 */
1356 if (fr_heap_insert(&client->pending, pending) < 0) {
1357 talloc_free(pending);
1358 return NULL;
1359 }
1360
1361 /*
1362 * We only track pending packets for the
1363 * main socket. For connected sockets,
1364 * we pause the FD, so the number of
1365 * pending packets will always be small.
1366 */
1367 if (!connection) client->thread->num_pending_packets++;
1368
1369 return pending;
1370}
1371
1372
1373/*
1374 * Order clients in the alive_clients heap, based on their IP
1375 * address.
1376 *
1377 * This function is only used for the "main" socket. Clients
1378 * from connections do not use it.
1379 */
1380static int8_t alive_client_cmp(void const *one, void const *two)
1381{
1384
1385 return fr_ipaddr_cmp(&a->src_ipaddr, &b->src_ipaddr);
1386}
1387
1388/** Implement 99% of the read routines.
1389 *
1390 * The app_io->read does the transport-specific data read.
1391 */
1392static ssize_t mod_read(fr_listen_t *li, void **packet_ctx, fr_time_t *recv_time_p,
1393 uint8_t *buffer, size_t buffer_len, size_t *leftover)
1394{
1395 fr_io_instance_t const *inst;
1396 fr_io_thread_t *thread;
1397 ssize_t packet_len = -1;
1398 fr_time_t recv_time = fr_time_wrap(0);
1399 fr_io_client_t *client;
1400 fr_io_address_t address;
1401 fr_io_connection_t my_connection, *connection;
1402 fr_io_pending_packet_t *pending = NULL;
1403 fr_io_track_t *track;
1404 fr_listen_t *child;
1405 int value, accept_fd = -1;
1406 uint32_t priority = PRIORITY_NORMAL;
1407
1408/** Log that we ignore clients in debug mode, or when it's enabled for a listener
1409 */
1410#define LOG_IGNORED_CLIENTS(_inst) ((_inst)->log_ignored_clients || fr_debug_lvl >= 1)
1411
1412 get_inst(li, &inst, &thread, &connection, &child);
1413
1414 track = NULL;
1415
1416 /*
1417 * There was data left over from the previous read, go
1418 * get the rest of it now. We MUST do this instead of
1419 * popping a pending packet, because the leftover bytes
1420 * are already in the output buffer.
1421 */
1422 if (*leftover) goto do_read;
1423
1424redo:
1425 /*
1426 * Read one pending packet. The packet may be pending
1427 * because of dynamic client definitions, or because it's
1428 * for a connected UDP socket, and was sent over by the
1429 * "master" UDP socket.
1430 */
1431 if (connection) {
1432 /*
1433 * The connection is dead. Tell the network side
1434 * to close it.
1435 */
1436 if (connection->dead) {
1437 DEBUG("Dead connection %s", connection->name);
1438 return -1;
1439 }
1440
1441 pending = fr_heap_pop(&connection->client->pending);
1442
1443 } else if (thread->pending_clients) {
1444 pending = pending_packet_pop(thread);
1445
1446 } else {
1447 pending = NULL;
1448 }
1449
1450 if (pending) {
1451 fr_assert(buffer_len >= pending->buffer_len);
1452 track = pending->track;
1453
1454 /*
1455 * Clear the destructor as we now own the
1456 * tracking entry.
1457 */
1458 talloc_set_destructor(pending, NULL);
1459
1460 /*
1461 * We received a conflicting packet while this
1462 * packet was pending. Discard this entry and
1463 * try to get another one.
1464 *
1465 * Note that the pending heap is *simple*. We
1466 * just track priority and recv_time. This means
1467 * it's fast, but also that it's hard to look up
1468 * random packets in the pending heap.
1469 */
1470 if (fr_time_neq(pending->recv_time, track->timestamp)) {
1471 DEBUG3("Discarding old packet");
1472 TALLOC_FREE(pending);
1473 goto redo;
1474 }
1475
1476 /*
1477 * We have a valid packet. Copy it over to the
1478 * caller, and return.
1479 */
1480 *packet_ctx = track;
1481 *leftover = 0;
1482 recv_time = *recv_time_p = pending->recv_time;
1483 client = track->client;
1484
1485 memcpy(buffer, pending->buffer, pending->buffer_len);
1486 packet_len = pending->buffer_len;
1487
1488 /*
1489 * Shouldn't be necessary, but what the heck...
1490 */
1491 memcpy(&address, track->address, sizeof(address));
1492 TALLOC_FREE(pending);
1493
1494 /*
1495 * Skip over all kinds of logic to find /
1496 * allocate the client, when we don't need to do
1497 * it any more.
1498 */
1499 goto have_client;
1500
1501 } else if (!connection && (inst->ipproto == IPPROTO_TCP)) {
1502 struct sockaddr_storage saremote;
1503 socklen_t salen;
1504
1505 salen = sizeof(saremote);
1506
1507 /*
1508 * We're a TCP socket but are NOT connected. We
1509 * must be the master socket. Accept the new
1510 * connection, and figure out src/dst IP/port.
1511 */
1512 accept_fd = accept(child->fd,
1513 (struct sockaddr *) &saremote, &salen);
1514
1515 /*
1516 * Couldn't open a NEW socket, but THIS ONE is
1517 * OK. So don't return -1.
1518 */
1519 if (accept_fd < 0) {
1520 RATE_LIMIT_LOCAL(&thread->rate_limit.accept_failed,
1521 INFO, "proto_%s - failed to accept new socket: %s",
1522 inst->app->common.name, fr_syserror(errno));
1523 return 0;
1524 }
1525
1526 /*
1527 * Set the new descriptor to be non-blocking.
1528 */
1529 (void) fr_nonblock(accept_fd);
1530
1531#ifdef STATIC_ANALYZER
1532 saremote.ss_family = AF_INET; /* static analyzer doesn't know that accept() initializes this */
1533#endif
1534
1535 /*
1536 * Get IP addresses only if we have IP addresses.
1537 */
1538 if ((saremote.ss_family == AF_INET) || (saremote.ss_family == AF_INET6)) {
1539 memset(&address.socket, 0, sizeof(address.socket));
1540 (void) fr_ipaddr_from_sockaddr(&address.socket.inet.src_ipaddr, &address.socket.inet.src_port,
1541 &saremote, salen);
1542 salen = sizeof(saremote);
1543
1544 /*
1545 * @todo - only if the local listen address is "*".
1546 */
1547 (void) getsockname(accept_fd, (struct sockaddr *) &saremote, &salen);
1548 (void) fr_ipaddr_from_sockaddr(&address.socket.inet.dst_ipaddr, &address.socket.inet.dst_port,
1549 &saremote, salen);
1550 address.socket.type = (inst->ipproto == IPPROTO_TCP) ? SOCK_STREAM : SOCK_DGRAM;
1551 address.socket.fd = accept_fd;
1552 }
1553
1554 } else {
1555 fr_io_address_t *local_address;
1556
1557 /*
1558 * We're either not a TCP socket, or we are a
1559 * connected TCP socket. Just read it.
1560 */
1561do_read:
1562 local_address = &address;
1563
1564 /*
1565 * @todo - For connected TCP sockets which are
1566 * dynamically defined, the app_io read()
1567 * function should stop reading the socket if the
1568 * server is busy. That change puts TCP
1569 * backpressure on the client.
1570 *
1571 * @todo TLS - for TLS and dynamic sockets, do
1572 * the SSL setup here, but have a structure which
1573 * describes the TLS data and run THAT through
1574 * the dynamic client definition, instead of
1575 * using normal packets. Or, rely on the app_io
1576 * read() function to do all TLS work? Given
1577 * that some protocols have "starttls" beginning
1578 * after a clear-text exchange, it's likely best
1579 * to have yet another layer of trampoline
1580 * functions which do all of the TLS work.
1581 */
1582 packet_len = inst->app_io->read(child, (void **) &local_address, &recv_time,
1583 buffer, buffer_len, leftover);
1584 if (packet_len <= 0) {
1585 return packet_len;
1586 }
1587
1588 /*
1589 * Not allowed? Discard it. The priority()
1590 * function has done any complaining, if
1591 * necessary.
1592 */
1593 if (inst->app->priority) {
1594 value = inst->app->priority(inst->app_instance, buffer, packet_len);
1595 if (value <= 0) {
1596 static fr_rate_limit_t bad_type;
1597
1598 /*
1599 * @todo - unix sockets. We need to use
1600 * the "name" of the socket, in the
1601 * listener?
1602 */
1604 RATE_LIMIT_LOCAL(thread ? &thread->rate_limit.bad_type : &bad_type, INFO,
1605 "proto_%s - ignoring packet from IP %pV. It is not configured as 'type = ...'",
1606 inst->app_io->common.name, fr_box_ipaddr(address.socket.inet.src_ipaddr));
1607 }
1608 return 0;
1609 }
1610 priority = value;
1611 }
1612
1613 /*
1614 * If the connection is pending, pause reading of
1615 * more packets. If mod_write() accepts the
1616 * connection, it will resume reading.
1617 * Otherwise, it will close the socket without
1618 * resuming it.
1619 */
1620 if (connection &&
1621 (connection->client->state == PR_CLIENT_PENDING)) {
1622 fr_assert(!connection->paused);
1623
1624 connection->paused = true;
1625 (void) fr_event_filter_update(connection->el,
1626 child->fd,
1628 }
1629 }
1630
1631 /*
1632 * Look up the client, unless we already have one (for a
1633 * connected socket).
1634 */
1635 if (!connection) {
1636 client = fr_trie_lookup_by_key(thread->trie,
1637 &address.socket.inet.src_ipaddr.addr, address.socket.inet.src_ipaddr.prefix);
1638 fr_assert(!client || !client->connection);
1639
1640 /*
1641 * Verify the cached client is the most specific match.
1642 * A broader subnet may have been cached first, shadowing
1643 * a more specific client definition.
1644 */
1645 if (client && (client->state == PR_CLIENT_STATIC)) {
1646 fr_client_t *radclient;
1647
1648 radclient = inst->app_io->client_find(thread->child,
1649 &address.socket.inet.src_ipaddr, inst->ipproto);
1650 if (radclient && (radclient->ipaddr.prefix > client->src_ipaddr.prefix)) {
1651 client = NULL;
1652 }
1653 }
1654
1655 } else {
1656 client = connection->client;
1657
1658 /*
1659 * We don't care what the read function says
1660 * about address. We have it already.
1661 */
1662 address = *connection->address;
1663 }
1664
1665 /*
1666 * Negative cache entry. Drop the packet.
1667 */
1668 if (client && client->state == PR_CLIENT_NAK) {
1669 if (accept_fd >= 0) close(accept_fd);
1670 return 0;
1671 }
1672
1673 /*
1674 * If there's no client, try to pull one from the global
1675 * / static client list. Or if dynamic clients are
1676 * allowed, try to define a dynamic client.
1677 */
1678 if (!client) {
1679 fr_client_t *radclient = NULL;
1681 fr_ipaddr_t const *network = NULL;
1682 char const *error;
1683
1684 /*
1685 * We MUST be the master socket.
1686 */
1687 fr_assert(!connection);
1688
1689 radclient = inst->app_io->client_find(thread->child, &address.socket.inet.src_ipaddr, inst->ipproto);
1690 if (radclient) {
1691 state = PR_CLIENT_STATIC;
1692
1693 /*
1694 * Make our own copy that we can modify it.
1695 */
1696 MEM(radclient = radclient_clone(thread, radclient));
1697 radclient->active = true;
1698
1699 } else if (inst->dynamic_clients) {
1700 if (inst->max_clients && (fr_heap_num_elements(thread->alive_clients) >= inst->max_clients)) {
1701 error = "Too many dynamic clients have been defined";
1702 goto ignore;
1703 }
1704
1705 /*
1706 * Look up the allowed networks.
1707 */
1708 network = fr_trie_lookup_by_key(inst->networks, &address.socket.inet.src_ipaddr.addr,
1709 address.socket.inet.src_ipaddr.prefix);
1710 if (!network) {
1711 error = "Address is outside of the the 'allow' network range";
1712 goto ignore;
1713 }
1714
1715 /*
1716 * It exists, but it's a "deny" rule, ignore it.
1717 */
1718 if (network->af == AF_UNSPEC) {
1719 error = "Address is forbidden by the 'deny' network range";
1720 goto ignore;
1721 }
1722
1723 /*
1724 * Allocate our local radclient as a
1725 * placeholder for the dynamic client.
1726 */
1727 radclient = radclient_alloc(thread, inst->ipproto, &address);
1728 state = PR_CLIENT_PENDING;
1729
1730 } else {
1731 char const *msg;
1732
1733 error = "No matching 'client' definition was found";
1734
1735 ignore:
1736 if (accept_fd < 0) {
1737 msg = "packet";
1738 } else {
1739 msg = "connection attempt";
1740 close(accept_fd);
1741 }
1742
1744 static fr_rate_limit_t unknown_client;
1745 RATE_LIMIT_LOCAL(thread ? &thread->rate_limit.unknown_client : &unknown_client,
1746 ERROR, "proto_%s - Ignoring %s from IP address %pV - %s",
1747 inst->app_io->common.name, msg, fr_box_ipaddr(address.socket.inet.src_ipaddr),
1748 error);
1749 }
1750
1751 return 0;
1752 }
1753
1754 MEM(client = client_alloc(thread, state, inst, thread, radclient, network));
1755
1756 /*
1757 * Parent the dynamic client radclient off the client - it
1758 * is the client which gets freed by the dynamic client timers.
1759 */
1760 if (state == PR_CLIENT_PENDING) talloc_steal(client, radclient);
1761 }
1762
1763have_client:
1764 fr_assert(client->state != PR_CLIENT_INVALID);
1765 fr_assert(client->state != PR_CLIENT_NAK);
1766
1767 /*
1768 * We've accepted a new connection. Go allocate it, and
1769 * let it read from the socket.
1770 */
1771 if (accept_fd >= 0) {
1772 connection = fr_io_connection_alloc(inst, thread, client, accept_fd, &address, NULL);
1773 if (!connection) {
1774 static fr_rate_limit_t alloc_failed;
1775
1776 RATE_LIMIT_LOCAL(thread ? &thread->rate_limit.conn_alloc_failed : &alloc_failed,
1777 ERROR, "Failed to allocate connection from client %s", client->radclient->shortname);
1778 return -1;
1779 }
1780
1781 /*
1782 * The parent is in use - ensure the cleanup timer is disarmed.
1783 */
1784 if (fr_timer_armed(connection->parent->ev)) {
1785 FR_TIMER_DISARM_RETURN(connection->parent->ev);
1786 connection->parent->ready_to_delete = false;
1787 }
1788
1789 return 0;
1790 }
1791
1792 /*
1793 * No connected sockets, OR we are the connected socket.
1794 *
1795 * Track this packet and return it if necessary.
1796 */
1797 if (connection || !client->use_connected) {
1798 fr_io_track_t *to_free = NULL;
1799
1800 /*
1801 * Add the packet to the tracking table, if it's
1802 * not already there. Pending packets will be in
1803 * the tracking table, but won't be counted as
1804 * "live" packets.
1805 */
1806 if (!track) {
1807 static fr_rate_limit_t tracking_failed;
1808 bool is_dup = false;
1809
1810 track = fr_io_track_add(li, client, &address, buffer, packet_len, recv_time, &is_dup);
1811 if (!track) {
1812 RATE_LIMIT_LOCAL(thread ? &thread->rate_limit.tracking_failed : &tracking_failed,
1813 ERROR, "Failed tracking packet from client %s - discarding it",
1814 client->radclient->shortname);
1815 return 0;
1816 }
1817
1818 /*
1819 * If there's a cached reply, just send that and don't do anything else.
1820 */
1821 if (is_dup) {
1822 fr_network_t *nr;
1823
1824 if (track->do_not_respond) {
1825 DEBUG("Ignoring retransmit from client %s - we are not responding to this request", client->radclient->shortname);
1826 return 0;
1827 }
1828
1829 if (track->discard) {
1830 DEBUG("Ignoring transmit from client %s - we previously received a newer / conflicting packet", client->radclient->shortname);
1831 return 0;
1832 }
1833
1834 if (!track->reply) {
1835 fr_assert(!track->finished);
1836 DEBUG("Ignoring retransmit from client %s - we are still processing the request", client->radclient->shortname);
1837 return 0;
1838 }
1839
1840 if (connection) {
1841 nr = connection->nr;
1842 } else {
1843 nr = thread->nr;
1844 }
1845
1846 /*
1847 * @todo - mark things up so that we know to keep 'track' around
1848 * until the packet is actually written to the network. OR, add
1849 * a network API so that the talloc_free() function can remove
1850 * the packet from the queue of packets to be retransmitted.
1851 *
1852 * Perhaps via having fr_network_listen_write() return a pointer
1853 * to the localized message, and then caching that in the tracking
1854 * structure.
1855 */
1856 DEBUG("Sending duplicate reply to client %s", client->radclient->shortname);
1857 fr_network_listen_write(nr, li, track->reply, track->reply_len,
1858 track, track->timestamp);
1859 return 0;
1860 }
1861
1862 /*
1863 * Got to free this if we don't process the packet.
1864 */
1865 to_free = track;
1866 }
1867
1868 /*
1869 * This is a pending dynamic client. See if we
1870 * have to either run the dynamic client code to
1871 * define the client, OR to push the packet onto
1872 * the pending queue for this client.
1873 */
1874 if (client->state == PR_CLIENT_PENDING) {
1875 /*
1876 * Track pending packets for the master
1877 * socket. Connected sockets are paused
1878 * as soon as they are defined, so we
1879 * won't be reading any more packets from
1880 * them.
1881 *
1882 * Since we don't have pending packets
1883 * for connected sockets, we don't need
1884 * to track pending packets.
1885 */
1886 if (!connection && inst->max_pending_packets && (thread->num_pending_packets >= inst->max_pending_packets)) {
1887 RATE_LIMIT_LOCAL(&thread->rate_limit.too_many_pending,
1888 ERROR, "Too many pending dynamic client packets for listener - discarding packet from %pV",
1889 fr_box_ipaddr(client->src_ipaddr));
1890
1891 discard:
1892 talloc_free(to_free);
1893 return 0;
1894 }
1895
1896 /*
1897 * Allocate the pending packet structure.
1898 */
1899 pending = fr_io_pending_alloc(connection, client, buffer, packet_len,
1900 track, priority);
1901 if (!pending) {
1902 static fr_rate_limit_t alloc_failed;
1903 RATE_LIMIT_LOCAL(thread ? &thread->rate_limit.alloc_failed : &alloc_failed,
1904 ERROR, "proto_%s - Failed allocating space for dynamic client %pV - discarding packet",
1905 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
1906 goto discard;
1907 }
1908
1909 if (fr_heap_num_elements(client->pending) > 1) {
1910 DEBUG("Verification is still pending for dynamic client %pV - queuing additional packet(s)",
1911 fr_box_ipaddr(client->src_ipaddr));
1912 return 0;
1913 }
1914
1915 /*
1916 * Tell this packet that it's defining a
1917 * dynamic client.
1918 */
1919 track->dynamic = recv_time;
1920
1921 INFO("proto_%s - Verification started for packet from dynamic client %pV - queuing new packets",
1922 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
1923 }
1924
1925 /*
1926 * Remove all cleanup timers for the client /
1927 * connection. It's still in use, so we don't
1928 * want to clean it up.
1929 */
1930 if (fr_timer_armed(client->ev)) {
1931 FR_TIMER_DISARM_RETURN(client->ev);
1932 client->ready_to_delete = false;
1933 }
1934
1935 /*
1936 * Remove cleanup timers for the connection parent.
1937 */
1938 if (connection && fr_timer_armed(connection->parent->ev)) {
1939 FR_TIMER_DISARM_RETURN(connection->parent->ev);
1940 connection->parent->ready_to_delete = false;
1941 }
1942
1943 /*
1944 * Return the packet.
1945 */
1946 *recv_time_p = track->timestamp;
1947 *packet_ctx = track;
1948 return packet_len;
1949 }
1950
1951 /*
1952 *
1953 */
1954 fr_assert(!pending);
1955
1956 /*
1957 * This must be the main UDP socket which creates
1958 * connections.
1959 */
1960 fr_assert(inst->ipproto == IPPROTO_UDP);
1961
1962 /*
1963 * We're using connected sockets, but this socket isn't
1964 * connected. It must be the master socket. The master
1965 * can either be STATIC, DYNAMIC, or PENDING. Whatever
1966 * the state, the child socket will take care of handling
1967 * the packet. e.g. dynamic clients, etc.
1968 */
1969 {
1970 bool nak = false;
1971
1972 my_connection.address = &address;
1973
1974 pthread_mutex_lock(&client->mutex);
1975 connection = fr_hash_table_find(client->ht, &my_connection);
1976 if (connection) nak = (connection->client->state == PR_CLIENT_NAK);
1977 pthread_mutex_unlock(&client->mutex);
1978
1979 /*
1980 * The connection is in NAK state, ignore packets
1981 * for it.
1982 */
1983 if (nak) {
1984 RATE_LIMIT_LOCAL(&thread->rate_limit.repeat_nak, ERROR, "proto_%s - Discarding repeated packet from NAK'd dynamic client %pV",
1985 inst->app_io->common.name, fr_box_ipaddr(address.socket.inet.src_ipaddr));
1986
1987 DEBUG("Discarding packet to NAKed connection %s", connection->name);
1988 return 0;
1989 }
1990 }
1991
1992 /*
1993 * No existing connection, create one.
1994 */
1995 if (!connection) {
1996 connection = fr_io_connection_alloc(inst, thread, client, -1, &address, NULL);
1997 if (!connection) {
1998 RATE_LIMIT_LOCAL(&thread->rate_limit.conn_alloc_failed,
1999 ERROR, "Failed to allocate connection from client %s. Discarding packet.", client->radclient->shortname);
2000 return 0;
2001 }
2002 }
2003
2004 DEBUG("Sending packet to connection %s", connection->name);
2005
2006 /*
2007 * Inject the packet into the connected socket. It will
2008 * process the packet as if it came in from the network.
2009 *
2010 * @todo future - after creating the connection, put the
2011 * current packet into connection->pending, instead of
2012 * inject?, and then call fr_network_listen_read() from
2013 * the child's instantiation routine???
2014 *
2015 * @todo TCP - for ACCEPT sockets, we don't have a
2016 * packet, so don't do this. Instead, the connection
2017 * will take care of figuring out what to do.
2018 *
2019 * We don't need "to_free" after this, as it will be
2020 * tracked in the connected socket.
2021 */
2022 if (fr_network_listen_inject(connection->nr, connection->listen,
2023 buffer, packet_len, recv_time) < 0) {
2024 RATE_LIMIT_LOCAL(&thread->rate_limit.queue_full, PERROR,
2025 "proto_%s - Discarding packet from dynamic client %pV - cannot push packet to connected socket",
2026 inst->app_io->common.name, fr_box_ipaddr(address.socket.inet.src_ipaddr));
2027 /*
2028 * Don't return an error, because that will cause the listener to close its socket.
2029 */
2030 }
2031
2032 return 0;
2033}
2034
2035/** Inject a packet to a connection.
2036 *
2037 * Always called in the context of the network.
2038 */
2039static int mod_inject(fr_listen_t *li, uint8_t const *buffer, size_t buffer_len, fr_time_t recv_time)
2040{
2041 fr_io_instance_t const *inst;
2042 int priority;
2043 bool is_dup = false;
2044 fr_io_connection_t *connection;
2045 fr_io_pending_packet_t *pending;
2046 fr_io_track_t *track;
2047
2048 get_inst(li, &inst, NULL, &connection, NULL);
2049
2050 if (!connection) {
2051 DEBUG2("Received injected packet for an unconnected socket.");
2052 return -1;
2053 }
2054
2055 if (inst->app->priority) {
2056 priority = inst->app->priority(inst->app_instance, buffer, buffer_len);
2057 if (priority <= 0) {
2058 return -1;
2059 }
2060 } else {
2061 priority = PRIORITY_NORMAL;
2062 }
2063
2064 /*
2065 * Track this packet, because that's what mod_read expects.
2066 */
2067 track = fr_io_track_add(li, connection->client, connection->address,
2068 buffer, buffer_len, recv_time, &is_dup);
2069 if (!track) {
2070 DEBUG2("Failed injecting packet to tracking table");
2071 return -1;
2072 }
2073
2074 talloc_get_type_abort(track, fr_io_track_t);
2075
2076 /*
2077 * @todo future - what to do with duplicates?
2078 */
2079 fr_assert(!is_dup);
2080
2081 /*
2082 * Remember to restore this packet later.
2083 */
2084 pending = fr_io_pending_alloc(connection, connection->client, buffer, buffer_len,
2085 track, priority);
2086 if (!pending) {
2087 DEBUG2("Failed injecting packet due to allocation error");
2088 return -1;
2089 }
2090
2091 return 0;
2092}
2093
2094/** Open a new listener
2095 *
2096 */
2097static int mod_open(fr_listen_t *li)
2098{
2099 fr_io_thread_t *thread;
2100 fr_io_instance_t const *inst;
2101
2102 thread = li->thread_instance;
2103 inst = li->app_io_instance;
2104
2105 if (inst->app_io->open(thread->child) < 0) return -1;
2106
2107 li->fd = thread->child->fd; /* copy this back up */
2108
2109 /*
2110 * Set the name of the socket.
2111 */
2112 if (!li->app_io->get_name) {
2113 li->name = li->app_io->common.name;
2114 } else {
2115 li->name = li->app_io->get_name(li);
2116 }
2117
2118 /*
2119 * Note that we're opening a child socket, so we don't
2120 * put it into the list of global listeners.
2121 */
2122
2123 return 0;
2124}
2125
2126
2127/** Set the event list for a new socket
2128 *
2129 * @param[in] li the listener
2130 * @param[in] el the event list
2131 * @param[in] nr context from the network side
2132 */
2134{
2135 fr_io_instance_t const *inst;
2136 fr_io_connection_t *connection;
2137 fr_io_thread_t *thread;
2138 fr_listen_t *child;
2139
2140 get_inst(li, &inst, &thread, &connection, &child);
2141
2142 /*
2143 * We're not doing IO, so there are no timers for
2144 * cleaning up packets, dynamic clients, or connections.
2145 */
2146 if (!inst->submodule) return;
2147
2148 if (inst->app_io->event_list_set) {
2149 inst->app_io->event_list_set(child, el, nr);
2150 }
2151
2152 /*
2153 * Set event list and network side for this socket.
2154 */
2155 if (!connection) {
2156 thread->el = el;
2157 thread->nr = nr;
2158
2159 } else {
2160 connection->el = el;
2161 connection->nr = nr;
2162 }
2163}
2164
2165
2166static void client_expiry_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
2167{
2168 fr_io_client_t *client = talloc_get_type_abort(uctx, fr_io_client_t);
2169 fr_io_instance_t const *inst;
2170 fr_io_connection_t *connection;
2171 fr_time_delta_t delay;
2172 int connections;
2173
2174 /*
2175 * No event list? We don't need to expire the client.
2176 */
2177 if (!tl) return;
2178
2179 // @todo - print out what we plan on doing next
2180 connection = client->connection;
2181 inst = client->inst;
2182
2183 fr_assert(client->state != PR_CLIENT_STATIC);
2184
2185 /*
2186 * Called from the read or write functions with
2187 * now==0, to signal that we have to *set* the timer.
2188 */
2189 if (fr_time_eq(now, fr_time_wrap(0))) {
2190 /*
2191 * The timer is already set, don't do anything.
2192 */
2193 if (fr_timer_armed(client->ev)) return;
2194
2195 switch (client->state) {
2197 fr_assert(connection != NULL);
2198 delay = inst->idle_timeout;
2200 (fr_time_delta_lt(client->radclient->limit.idle_timeout, inst->idle_timeout))) {
2201 delay = client->radclient->limit.idle_timeout;
2202 }
2203 break;
2204
2205 case PR_CLIENT_DYNAMIC:
2206 delay = inst->dynamic_timeout;
2207 break;
2208
2209 case PR_CLIENT_NAK:
2210 delay = inst->nak_lifetime;
2211 break;
2212
2213 default:
2214 fr_assert(0 == 1);
2215 return;
2216 }
2217
2218 DEBUG("TIMER - setting idle timeout to %pVs for connection from client %s", fr_box_time_delta(delay), client->radclient->shortname);
2219
2220 goto reset_timer;
2221 }
2222
2223 /*
2224 * It's a negative cache entry. Just delete it.
2225 */
2226 if (client->state == PR_CLIENT_NAK) {
2227 INFO("proto_%s - Expiring NAK'd dynamic client %pV - permitting new packets to be verified",
2228 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
2229
2230 delete_client:
2231 fr_assert(client->packets == 0);
2232
2233 /*
2234 * It's a connected socket. Remove it from the
2235 * parents list of connections, and delete it.
2236 */
2237 if (connection) {
2238 pthread_mutex_lock(&connection->parent->mutex);
2239 if (connection->in_parent_hash) {
2240 connection->in_parent_hash = false;
2241 (void) fr_hash_table_delete(connection->parent->ht, connection);
2242 }
2243 pthread_mutex_unlock(&connection->parent->mutex);
2244
2245 /*
2246 * Mark the connection as dead, and tell
2247 * the network side to stop reading from
2248 * it.
2249 */
2250 connection->dead = true;
2251 fr_network_listen_read(connection->nr, connection->listen);
2252 return;
2253 }
2254
2255 talloc_free(client);
2256 return;
2257 }
2258
2259 DEBUG2("TIMER - checking status of dynamic client %s %pV", client->radclient->shortname, fr_box_ipaddr(client->src_ipaddr));
2260
2261 /*
2262 * It's a dynamically defined client. If no one is using
2263 * it, clean it up after an idle timeout.
2264 */
2265 if ((client->state == PR_CLIENT_DYNAMIC) ||
2266 (client->state == PR_CLIENT_CONNECTED)) {
2267 if (client->packets > 0) {
2268 client->ready_to_delete = false;
2269 return;
2270 }
2271
2272 /*
2273 * No packets, check / set idle timeout.
2274 */
2275 goto idle_timeout;
2276 }
2277
2278 /*
2279 * The client is pending definition. It's either a
2280 * dynamic client which has timed out, OR it's a
2281 * "place-holder" client for connected sockets.
2282 */
2283 fr_assert(client->state == PR_CLIENT_PENDING);
2284
2285 /*
2286 * This is a dynamic client pending definition.
2287 * But it's taken too long to define, so we just
2288 * delete the client, and all packets for it. A
2289 * new packet will cause the dynamic definition
2290 * to be run again.
2291 */
2292 if (!client->use_connected) {
2293 if (!client->packets) {
2294 DEBUG("proto_%s - No packets are using unconnected socket", inst->app_io->common.name);
2295 goto delete_client;
2296 }
2297
2298 /*
2299 * Tell the writer to NOT dynamically define the
2300 * client. We've run into a problem. Then,
2301 * return. The writer will take care of calling
2302 * us again when it notices that a PENDING client
2303 * is ready to delete.
2304 *
2305 * TBH... that shouldn't happen? We should rely
2306 * on the write to do this all of the time...
2307 */
2308 client->ready_to_delete = true;
2309 return;
2310 }
2311
2312 fr_assert(!connection);
2313
2314 /*
2315 * Find out how many connections are using this
2316 * client.
2317 */
2318 pthread_mutex_lock(&client->mutex);
2319 fr_assert(client->ht != NULL);
2320 connections = fr_hash_table_num_elements(client->ht);
2321 pthread_mutex_unlock(&client->mutex);
2322
2323 /*
2324 * No connections are using this client. If
2325 * we've passed the idle timeout, then just
2326 * delete it. Otherwise, set an idle timeout (as
2327 * above);
2328 */
2329 if (!connections) {
2330idle_timeout:
2331 /*
2332 * We didn't receive any packets during the
2333 * idle_timeout, just delete it.
2334 */
2335 if (client->ready_to_delete) {
2336 if (connection) {
2337 DEBUG("proto_%s - idle timeout for connection %s", inst->app_io->common.name, connection->name);
2338 } else {
2339 DEBUG("proto_%s - idle timeout for client %s", inst->app_io->common.name, client->radclient->shortname);
2340 }
2341 goto delete_client;
2342 }
2343
2344 /*
2345 * No packets and no idle timeout set, go set
2346 * idle timeut.
2347 */
2348 client->ready_to_delete = true;
2349 delay = client->state == PR_CLIENT_DYNAMIC ? inst->dynamic_timeout : inst->idle_timeout;
2350 goto reset_timer;
2351 }
2352
2353 /*
2354 * There are live sub-connections. Poll again after a
2355 * long period of time. Once all of the connections are
2356 * closed, we can then delete this client.
2357 *
2358 * @todo - maybe just leave it? we want to be able to
2359 * clean up this client after a while tho... especially
2360 * if the total number of clients is limited.
2361 */
2362 client->ready_to_delete = false;
2363 delay = inst->check_interval;
2364
2365reset_timer:
2366 if (fr_timer_in(client, tl, &client->ev,
2367 delay, false, client_expiry_timer, client) < 0) {
2368 ERROR("proto_%s - Failed adding timeout for dynamic client %s. It will be permanent!",
2369 inst->app_io->common.name, client->radclient->shortname);
2370 return;
2371 }
2372
2373 return;
2374}
2375
2376
2377/*
2378 * Expire cached packets after cleanup_delay time
2379 */
2380static void packet_expiry_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
2381{
2382 fr_io_track_t *track = talloc_get_type_abort(uctx, fr_io_track_t);
2383 fr_io_client_t *client = track->client;
2384 fr_io_instance_t const *inst = client->inst;
2385
2386 /*
2387 * Insert the timer if requested.
2388 *
2389 * On duplicates this also extends the expiry timer.
2390 */
2391 if (fr_time_eq(now, fr_time_wrap(0)) && !track->discard && inst->app_io->track_duplicates) {
2392 fr_assert(fr_time_delta_ispos(inst->cleanup_delay));
2393 fr_assert(track->do_not_respond || track->reply_len);
2394
2395 track->expires = fr_time_add(fr_time(), inst->cleanup_delay);
2396
2397 /*
2398 * if the timer succeeds, then "track"
2399 * will be cleaned up when the timer
2400 * fires.
2401 */
2402 if (fr_timer_at(track, tl, &track->ev,
2403 track->expires,
2404 false, packet_expiry_timer, track) == 0) {
2405 DEBUG("proto_%s - cleaning up request in %.6fs", inst->app_io->common.name,
2406 fr_time_delta_unwrap(inst->cleanup_delay) / (double)NSEC);
2407 return;
2408 }
2409
2410 DEBUG("proto_%s - Failed adding cleanup_delay for packet. Discarding packet immediately",
2411 inst->app_io->common.name);
2412 }
2413
2414 /*
2415 * So that all cleanup paths can come here, not just the
2416 * timeout ones.
2417 */
2418 if (fr_time_neq(now, fr_time_wrap(0))) {
2419 DEBUG2("TIMER - proto_%s - cleanup delay", inst->app_io->common.name);
2420 } else {
2421 DEBUG2("proto_%s - cleaning up", inst->app_io->common.name);
2422 }
2423
2424 /*
2425 * Delete the tracking entry.
2426 */
2427 talloc_free(track);
2428
2429 /*
2430 * The client isn't dynamic, stop here.
2431 */
2432 if (client->state == PR_CLIENT_STATIC) return;
2433
2434 fr_assert(client->state != PR_CLIENT_NAK);
2435 fr_assert(client->state != PR_CLIENT_PENDING);
2436
2437 /*
2438 * If necessary, call the client expiry timer to clean up
2439 * the client.
2440 */
2441 if (client->packets == 0) {
2442 client_expiry_timer(tl, now, client);
2443 }
2444}
2445
2446static void update_client(fr_io_client_t *client, fr_client_t *radclient)
2447{
2448
2449 /*
2450 * The new client is mostly OK. Copy the various fields
2451 * over.
2452 */
2453#define COPY_FIELD(_dest, _x) _dest->radclient->_x = radclient->_x
2454#define DUP_FIELD(_dest, _x) _dest->radclient->_x = talloc_strdup(_dest->radclient, radclient->_x)
2455
2456 /*
2457 * Only these two fields are set. Other strings in
2458 * radclient are copies of these ones.
2459 */
2462
2463 DUP_FIELD(client, longname);
2464 DUP_FIELD(client, shortname);
2465 DUP_FIELD(client, secret);
2466 DUP_FIELD(client, nas_type);
2467
2468 COPY_FIELD(client, ipaddr);
2469 COPY_FIELD(client, src_ipaddr);
2470 COPY_FIELD(client, require_message_authenticator);
2471 COPY_FIELD(client, require_message_authenticator_is_set);
2472#ifdef NAS_VIOLATES_RFC
2473 COPY_FIELD(client, allow_vulnerable_clients);
2474#endif
2475 COPY_FIELD(client, limit_proxy_state);
2476 COPY_FIELD(client, limit_proxy_state_is_set);
2477 COPY_FIELD(client, use_connected);
2478 COPY_FIELD(client, cs);
2479}
2480
2481/** Tear down any deferred sibling connections under a pending parent.
2482 *
2483 * This function is Cclled from mod_write() when the first connection dynamic-client verification fails (NAK
2484 * or hard reject). Any other connections that were inserted into parent->ht are then freed.
2485 *
2486 * Walk parent->ht, find every deferred sibling, remove it from the hash table, close the socket, and frees
2487 * its module instance (which cascades to the connection itself). The first connection (the one whose
2488 * verification just failed) is identified by conn->nr != NULL and is left alone, as the caller already owns
2489 * its cleanup.
2490 *
2491 * Uses a find-one-then-restart loop rather than iterate-while-deleting, since the deferred sibling count is
2492 * small and the cost is irrelevant on the failure path.
2493 */
2495{
2496 if (!parent->ht) return;
2497
2498 while (true) {
2499 fr_hash_iter_t iter;
2500 fr_io_connection_t *target = NULL;
2501 fr_io_connection_t *conn;
2502
2503 pthread_mutex_lock(&parent->mutex);
2504 for (conn = fr_hash_table_iter_init(parent->ht, &iter);
2505 conn != NULL;
2506 conn = fr_hash_table_iter_next(parent->ht, &iter)) {
2507 if (conn->nr != NULL) continue; /* first child, owned by caller */
2508 if (conn->client->state != PR_CLIENT_PENDING) continue; /* already NAK or promoted */
2509 target = conn;
2510 break;
2511 }
2512 if (target && target->in_parent_hash) {
2513 target->in_parent_hash = false;
2514 (void) fr_hash_table_delete(parent->ht, target);
2515 }
2516 pthread_mutex_unlock(&parent->mutex);
2517
2518 if (!target) break;
2519
2520 DEBUG("proto_%s - cleaning up deferred connection %s after verification failure",
2521 target->client->inst->app_io->common.name, target->name);
2522
2523 if (target->child) {
2524 if (target->client->inst->app_io->close) {
2525 (void) target->client->inst->app_io->close(target->child);
2526 } else if (target->child->fd >= 0) {
2527 close(target->child->fd);
2528 }
2529 }
2530
2531 talloc_free(target->mi);
2532 }
2533}
2534
2535/** Promote a pending dynamic-client parent and all of its child connections.
2536 *
2537 * When multiple TCP connections from the same source IP arrive while the parent client is still
2538 * PR_CLIENT_PENDING, only the first connection is added to the scheduler. Later connection are inserted
2539 * into the parent's hash table, but their fr_schedule_listen_add() call is deferred to this function. When
2540 * the first connection verification completes successfully, every other connection is finished and
2541 * scheduled.
2542 *
2543 * This function:
2544 *
2545 * * Promotes the parent itself to PR_CLIENT_DYNAMIC and re-parents the cs.
2546 *
2547 * * Walks the parent's hash table of connections. For the first connection (already in the scheduler with
2548 * connection->nr set), it resumes reads if the connection was paused. For every later connection,
2549 * (connection->nr == NULL), it copies the verified radclient definition onto the connection and then calls
2550 * fr_schedule_listen_add() to add the connection to the scheduler.
2551 *
2552 * @param parent the parent client whose state and child connections to promote
2553 * @param radclient the verified radclient (typically the calling child's radclient)
2554 */
2556{
2557 fr_hash_iter_t iter;
2558 fr_io_connection_t *conn;
2559 fr_schedule_t *sc = parent->thread->sc;
2560
2561 /*
2562 * Promote the parent itself. Only the first connection to reach here does the work; later
2563 * connections will already see the parent as PR_CLIENT_DYNAMIC.
2564 */
2565 if (parent->state == PR_CLIENT_PENDING) {
2566 parent->radclient->active = true;
2567 parent->state = PR_CLIENT_DYNAMIC;
2568
2569 update_client(parent, radclient);
2570
2571 /*
2572 * Re-parent the conf section used to build this
2573 * client so its lifetime is linked to the parent
2574 * client.
2575 */
2576 talloc_steal(parent->radclient, parent->radclient->cs);
2577 } else {
2579 }
2580
2581 /*
2582 * Walk every child connection of this parent and promote the pending ones. The calling
2583 * connection is itself in parent->ht, so its per-child work is also done here.
2584 */
2585 pthread_mutex_lock(&parent->mutex);
2586 if (parent->ht) {
2587 for (conn = fr_hash_table_iter_init(parent->ht, &iter);
2588 conn != NULL;
2589 conn = fr_hash_table_iter_next(parent->ht, &iter)) {
2590 fr_io_client_t *child = conn->client;
2591
2592 if (child->state != PR_CLIENT_PENDING) continue;
2593
2594 /*
2595 * Connections can't spawn new connections.
2596 */
2597 child->use_connected = child->radclient->use_connected = false;
2598
2599 if (conn->nr == NULL) {
2600 /*
2601 * Deferred connection: its radclient was cloned from the parent's
2602 * placeholder before verification, so copy the now-verified fields onto
2603 * it before adding it to the scheduler.
2604 */
2605 update_client(child, radclient);
2606
2607 child->state = PR_CLIENT_DYNAMIC;
2608 child->radclient->active = true;
2609
2610 DEBUG("proto_%s - scheduling deferred connection %s",
2611 child->inst->app_io->common.name, conn->name);
2612
2613 conn->nr = fr_schedule_listen_add(sc, conn->listen);
2614 if (!conn->nr) {
2615 ERROR("proto_%s - Failed scheduling deferred connection %s",
2616 child->inst->app_io->common.name, conn->name);
2617 /*
2618 * Leave the entry in the hash table; the usual connection
2619 * cleanup path will eventually remove it.
2620 */
2621 }
2622 } else {
2623 /*
2624 * The first connection is already scheduled. Resume reads if it was
2625 * paused, while waiting on verification.
2626 */
2627 if (conn->paused) {
2628 conn->paused = false;
2629 (void) fr_event_filter_update(conn->el, conn->child->fd,
2631 }
2632
2633 child->state = PR_CLIENT_DYNAMIC;
2634 child->radclient->active = true;
2635 }
2636 }
2637 }
2638 pthread_mutex_unlock(&parent->mutex);
2639}
2640
2641static ssize_t mod_write(fr_listen_t *li, void *packet_ctx, fr_time_t request_time,
2642 uint8_t *buffer, size_t buffer_len, size_t written)
2643{
2644 fr_io_instance_t const *inst;
2645 fr_io_thread_t *thread;
2646 fr_io_connection_t *connection;
2647 fr_io_track_t *track = talloc_get_type_abort(packet_ctx, fr_io_track_t);
2648 fr_io_client_t *client;
2649 fr_client_t *radclient;
2650 fr_listen_t *child;
2652 char const *name;
2653
2654 get_inst(li, &inst, &thread, &connection, &child);
2655
2656 client = track->client;
2657 if (connection) {
2658 el = connection->el;
2659 name = connection->name;
2660 } else {
2661 el = thread->el;
2662 name = li->name;
2663 }
2664
2665 DEBUG3("Processing reply for %s", name);
2666
2667 /*
2668 * A fully defined client means that we just send the reply.
2669 */
2670 if (client->state != PR_CLIENT_PENDING) {
2671 ssize_t packet_len;
2672
2673 track->finished = true;
2674
2675 /*
2676 * The request received a conflicting packet, so we
2677 * discard this one.
2678 */
2679 if (fr_time_neq(track->timestamp, request_time) || track->discard) {
2680 fr_assert(track->packets > 0);
2681 track->packets--;
2682 DEBUG3("Suppressing reply as we have a newer / conflicing packet from the same source");
2683 track->discard = true;
2684 goto setup_timer;
2685 }
2686
2687 /*
2688 * We have a NAK packet, or the request has timed
2689 * out, or it was discarded due to a conflicting
2690 * packet. We don't respond, but we do cache the
2691 * "do not respond" reply for a period of time.
2692 */
2693 if ((buffer_len == 1) || track->do_not_respond) {
2694 DEBUG3("Not sending response to request - it is marked as 'do not respond'");
2695 track->do_not_respond = true;
2696 goto setup_timer;
2697 }
2698
2699 /*
2700 * We have a real packet, write it to the network
2701 * via the underlying transport write.
2702 */
2703 packet_len = inst->app_io->write(child, track, request_time,
2704 buffer, buffer_len, written);
2705 if (packet_len <= 0) {
2706 ERROR("Failed writing the reply - not sending any response on %s", name);
2707 track->discard = true;
2708 packet_expiry_timer(el->tl, fr_time_wrap(0), track);
2709 return packet_len;
2710 }
2711
2712 /*
2713 * Only a partial write. The network code will
2714 * take care of calling us again, and we will set
2715 * the expiry timer at that point.
2716 */
2717 if ((size_t) packet_len < buffer_len) {
2718 DEBUG3("Partial write (%zd < %zu)", packet_len, buffer_len);
2719 return packet_len;
2720 }
2721
2722 /*
2723 * We're not tracking duplicates, so just expire
2724 * the packet now.
2725 */
2726 if (!inst->app_io->track_duplicates) {
2727 DEBUG3("Not tracking duplicates - expiring the request");
2728 goto setup_timer;
2729 }
2730
2731 /*
2732 * Cache the reply packet if we're doing dedup.
2733 *
2734 * On resend duplicate reply, the reply is
2735 * already filled out. So we don't do that twice.
2736 */
2737 if (!track->reply) {
2738 DEBUG3("Caching reply");
2739 MEM(track->reply = talloc_memdup(track, buffer, buffer_len));
2740 track->reply_len = buffer_len;
2741 }
2742
2743 /*
2744 * Set the timer to expire the packet.
2745 *
2746 * On dedup this also extends the timer.
2747 */
2748 setup_timer:
2749 packet_expiry_timer(el->tl, fr_time_wrap(0), track);
2750 return buffer_len;
2751 }
2752
2753 /*
2754 * The client is pending, so we MUST have dynamic clients.
2755 *
2756 * If there's a connected socket and no dynamic clients, then the
2757 * client state is set to CONNECTED when the client is created.
2758 */
2759 fr_assert(inst->dynamic_clients);
2760 fr_assert(client->pending != NULL);
2761
2762 /*
2763 * The request failed trying to define the dynamic
2764 * client. Discard the client and all pending packets.
2765 */
2766 if ((buffer_len == 1) && (*buffer == true)) {
2767 DEBUG("Request failed trying to define a new client. Discarding client and pending packets.");
2768
2769 if (!connection) {
2770 talloc_free(client);
2771 return buffer_len;
2772 }
2773
2774 /*
2775 * Free pending packets and tracking table.
2776 * The table is parented by connection->parent, so won't
2777 * be auto-freed when connection->client is freed.
2778 */
2779 TALLOC_FREE(client->pending);
2780 if (client->table) TALLOC_FREE(client->table);
2781
2782 /*
2783 * Remove from parent's hash table so new packets won't
2784 * be routed to this connection.
2785 */
2786 pthread_mutex_lock(&connection->parent->mutex);
2787 if (connection->in_parent_hash) {
2788 connection->in_parent_hash = false;
2789 (void) fr_hash_table_delete(connection->parent->ht, connection);
2790 }
2791 pthread_mutex_unlock(&connection->parent->mutex);
2792
2793 /*
2794 * Tear down any sibling connections that were
2795 * deferred waiting on this verification.
2796 */
2797 fr_io_connection_deny(connection->parent);
2798
2799 /*
2800 * Mark the connection as dead, then trigger the
2801 * standard cleanup path via fr_network_listen_read().
2802 * This calls mod_read(), which sees connection->dead,
2803 * returns -1, and the network layer closes the
2804 * connection through its normal error handling.
2805 */
2806 connection->dead = true;
2807 fr_network_listen_read(connection->nr, connection->listen);
2808
2809 return buffer_len;
2810 }
2811
2812 /*
2813 * The dynamic client was NOT defined. Set it's state to
2814 * NAK, delete all pending packets, and close the
2815 * tracking table.
2816 */
2817 if (buffer_len == 1) {
2818 INFO("proto_%s - Verification failed for packet from dynamic client %pV - adding IP address to the NAK cache",
2819 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
2820
2821 client->state = PR_CLIENT_NAK;
2822 if (!connection) {
2823 client_pending_free(client);
2824 } else {
2825 TALLOC_FREE(client->pending);
2826 }
2827 if (client->table) TALLOC_FREE(client->table);
2828 fr_assert(client->packets == 0);
2829
2830 /*
2831 * Tear down any sibling connections that were
2832 * deferred waiting on this verification. Only
2833 * relevant for the connection case — the !connection
2834 * path never has deferred siblings.
2835 */
2836 if (connection) fr_io_connection_deny(connection->parent);
2837
2838 /*
2839 * If we're a connected UDP socket, allocate a
2840 * new connection which is the place-holder for
2841 * the NAK. We will reject packets from from the
2842 * src/dst IP/port.
2843 *
2844 * The timer will take care of deleting the NAK
2845 * connection (which doesn't have any FDs
2846 * associated with it). The network side will
2847 * call mod_close() when the original connection
2848 * is done, which will then free that connection,
2849 * too.
2850 */
2851 if (connection && (inst->ipproto == IPPROTO_UDP)) {
2852 MEM(connection = fr_io_connection_alloc(inst, thread, client, -1, connection->address, connection));
2853 client_expiry_timer(el->tl, fr_time_wrap(0), connection->client);
2854
2855 errno = ECONNREFUSED;
2856 return -1;
2857 }
2858
2859 /*
2860 * For connected TCP sockets, we just call the
2861 * expiry timer, which will close and free the
2862 * connection.
2863 */
2864 client_expiry_timer(el->tl, fr_time_wrap(0), client);
2865 return buffer_len;
2866 }
2867
2868 fr_assert(buffer_len == sizeof(radclient));
2869
2870 memcpy(&radclient, buffer, sizeof(radclient));
2871
2872 if (!connection) {
2873 fr_ipaddr_t ipaddr;
2874
2875 /*
2876 * Check the encapsulating network against the
2877 * address that the user wants to use, but only
2878 * for unconnected sockets.
2879 */
2880 if (client->network.af != radclient->ipaddr.af) {
2881 DEBUG("Client IP address %pV IP family does not match the source network %pV of the packet.",
2882 fr_box_ipaddr(radclient->ipaddr), fr_box_ipaddr(client->network));
2883 goto error;
2884 }
2885
2886 /*
2887 * Network prefix is more restrictive than the one given
2888 * by the client... that's bad.
2889 */
2890 if (client->network.prefix > radclient->ipaddr.prefix) {
2891 DEBUG("Client IP address %pV is not within the prefix with the defined network %pV",
2892 fr_box_ipaddr(radclient->ipaddr), fr_box_ipaddr(client->network));
2893 goto error;
2894 }
2895
2896 ipaddr = radclient->ipaddr;
2897 fr_ipaddr_mask(&ipaddr, client->network.prefix);
2898 if (fr_ipaddr_cmp(&ipaddr, &client->network) != 0) {
2899 DEBUG("Client IP address %pV is not within the defined network %pV.",
2900 fr_box_ipaddr(radclient->ipaddr), fr_box_ipaddr(client->network));
2901 goto error;
2902 }
2903
2904 /*
2905 * We can't define dynamic clients as networks (for now).
2906 *
2907 * @todo - If we did allow it, we would have to remove
2908 * this client from the trie, update it's IP address, and
2909 * re-add it. We can PROBABLY do this if this client
2910 * isn't already connected, AND radclient->use_connected
2911 * is true. But that's for later...
2912 */
2913 if (((radclient->ipaddr.af == AF_INET) &&
2914 (radclient->ipaddr.prefix != 32)) ||
2915 ((radclient->ipaddr.af == AF_INET6) &&
2916 (radclient->ipaddr.prefix != 128))) {
2917 ERROR("Cannot define a dynamic client as a network");
2918
2919 error:
2920 talloc_free(radclient);
2921
2922 /*
2923 * Remove the pending client from the trie.
2924 */
2925 fr_assert(!connection);
2926 talloc_free(client);
2927 return buffer_len;
2928 }
2929 }
2930
2931 update_client(client, radclient);
2932
2933 // @todo - fill in other fields?
2934
2935 talloc_free(radclient);
2936
2937 radclient = client->radclient; /* laziness */
2938 radclient->server_cs = inst->server_cs;
2939 radclient->server = cf_section_name2(inst->server_cs);
2940
2941 /*
2942 * This is a connected socket, and it's just been
2943 * allowed. Go poke the network side to read from the
2944 * socket.
2945 */
2946 if (connection) {
2947 fr_assert(connection != NULL);
2948 fr_assert(connection->client == client);
2949 fr_assert(client->connection != NULL);
2950
2951 /*
2952 * Promote the parent and every sibling connection.
2953 * This also promotes the current child.
2954 */
2955 fr_io_connection_allow(connection->parent, radclient);
2956
2957 INFO("proto_%s - Verification succeeded for packet from dynamic client %pV - processing queued packets",
2958 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr));
2959 goto finish;
2960 } else {
2961 /*
2962 * Re-parent the conf section used to build this client
2963 * so its lifetime is linked to the client
2964 */
2965 talloc_steal(radclient, radclient->cs);
2966 }
2967
2968 fr_assert(connection == NULL);
2969 fr_assert(client->use_connected == false); /* we weren't sure until now */
2970
2971 /*
2972 * Disallow unsupported configurations.
2973 */
2974 if (radclient->use_connected && !inst->app_io->connection_set) {
2975 DEBUG("proto_%s - cannot use connected sockets as underlying 'transport = %s' does not support it.",
2976 inst->app_io->common.name, inst->submodule->module->exported->name);
2977 goto error;
2978 }
2979
2980
2981 /*
2982 * Dynamic clients can spawn new connections.
2983 */
2984 client->use_connected = radclient->use_connected;
2985
2986 /*
2987 * The admin has defined a client which uses connected
2988 * sockets. Go spawn it
2989 */
2990 if (client->use_connected) {
2991 fr_assert(connection == NULL);
2992
2993
2994 /*
2995 * Leave the state as PENDING. Each connection
2996 * will then cause a dynamic client to be
2997 * defined.
2998 */
2999 (void) pthread_mutex_init(&client->mutex, NULL);
3000 MEM(client->ht = fr_hash_table_alloc(client, connection_hash, connection_cmp, NULL));
3001
3002 } else {
3003 /*
3004 * The client has been allowed.
3005 */
3006 client->state = PR_CLIENT_DYNAMIC;
3007 client->radclient->active = true;
3008
3009 INFO("proto_%s - Verification succeeded for packet from dynamic client %pV - processing %d queued packets",
3010 inst->app_io->common.name, fr_box_ipaddr(client->src_ipaddr),
3011 fr_heap_num_elements(client->pending));
3012 }
3013
3014 /*
3015 * Add this client to the master socket, so that
3016 * mod_read() will see the pending client, pop the
3017 * pending packet, and process it.
3018 *
3019 */
3020 if (!thread->pending_clients) {
3022 fr_io_client_t, pending_id, 0));
3023 }
3024
3026 (void) fr_heap_insert(&thread->pending_clients, client);
3027
3028finish:
3029 /*
3030 * Maybe we defined the client, but the original packet
3031 * timed out, so there's nothing more to do. In that case, set up the expiry timers.
3032 */
3033 if (client->packets == 0) {
3034 client_expiry_timer(el->tl, fr_time_wrap(0), client);
3035 }
3036
3037 /*
3038 * If there are pending packets (and there should be at
3039 * least one), tell the network socket to call our read()
3040 * function again.
3041 */
3042 if (fr_heap_num_elements(client->pending) > 0) {
3043 if (connection) {
3044 fr_network_listen_read(connection->nr, connection->listen);
3045 } else {
3046 fr_network_listen_read(thread->nr, thread->listen);
3047 }
3048 }
3049
3050 return buffer_len;
3051}
3052
3053/** Close the socket.
3054 *
3055 */
3056static int mod_close(fr_listen_t *li)
3057{
3058 fr_io_instance_t const *inst;
3059 fr_io_connection_t *connection;
3060 fr_listen_t *child;
3061
3062 get_inst(li, &inst, NULL, &connection, &child);
3063
3064 if (inst->app_io->close) {
3065 int ret;
3066
3067 ret = inst->app_io->close(child);
3068 if (ret < 0) return ret;
3069 } else {
3070 close(child->fd);
3071// child->fd = -1;
3072 }
3073
3074 if (!connection) return 0;
3075
3076 /*
3077 * We allocated this, so we're responsible for closing
3078 * it.
3079 */
3080 DEBUG("Closing connection %s", connection->name);
3081 if (connection->client->pending) {
3082 TALLOC_FREE(connection->client->pending); /* for any pending packets */
3083 }
3084
3085 /*
3086 * Remove connection from parent hash table
3087 */
3088 pthread_mutex_lock(&connection->parent->mutex);
3089 if (connection->in_parent_hash) {
3090 connection->in_parent_hash = false;
3091 (void) fr_hash_table_delete(connection->parent->ht, connection);
3092 }
3093
3094 /*
3095 * If this is a dynamic client, and the parent has no more connections
3096 * set up the timer to expire the dynamic client.
3097 */
3098 if ((connection->parent->state == PR_CLIENT_DYNAMIC) &&
3099 ((!connection->parent->ht) || (fr_hash_table_num_elements(connection->parent->ht) == 0))) {
3100 client_expiry_timer(connection->el->tl, fr_time_wrap(0), connection->parent);
3101 }
3102 pthread_mutex_unlock(&connection->parent->mutex);
3103
3104 talloc_free(connection->mi);
3105
3106 return 0;
3107}
3108
3109static int mod_instantiate(module_inst_ctx_t const *mctx)
3110{
3111 fr_io_instance_t *inst = mctx->mi->data;
3112 CONF_SECTION *conf = mctx->mi->conf;
3113
3114 inst->mi = mctx->mi;
3115 inst->app_io = (fr_app_io_t const *) inst->submodule->exported;
3116 inst->app_io_conf = inst->submodule->conf;
3117 inst->app_io_instance = inst->submodule->data;
3118
3119 /*
3120 * If we're not tracking duplicates then we don't need a
3121 * cleanup delay.
3122 *
3123 * If we are tracking duplicates, then we must have a non-zero cleanup delay.
3124 */
3125 if (!inst->app_io->track_duplicates) {
3126 inst->cleanup_delay = fr_time_delta_wrap(0);
3127
3128 } else {
3129 FR_TIME_DELTA_BOUND_CHECK("cleanup_delay", inst->cleanup_delay, >=, fr_time_delta_from_sec(1));
3130
3131 if (!inst->app_io->track_create) {
3132 cf_log_err(inst->app_io_conf, "Internal error: 'track_duplicates' is set, but there is no 'track create' function");
3133 return -1;
3134 }
3135 }
3136
3137 /*
3138 * Get various information after bootstrapping the
3139 * application IO module.
3140 */
3141 if (inst->app_io->network_get) {
3142 inst->app_io->network_get(&inst->ipproto, &inst->dynamic_clients, &inst->networks, inst->app_io_instance);
3143 }
3144
3145 if ((inst->ipproto == IPPROTO_TCP) && !inst->app_io->connection_set) {
3146 cf_log_err(inst->app_io_conf, "Missing 'connection set' API for proto_%s", inst->app_io->common.name);
3147 return -1;
3148 }
3149
3150 /*
3151 * Ensure that the dynamic client sections exist
3152 */
3153 if (inst->dynamic_clients) {
3155
3156 if (!cf_section_find(server, "new", "client")) {
3157 cf_log_err(conf, "Cannot use 'dynamic_clients = yes' as the virtual server has no 'new client { ... }' section defined.");
3158 return -1;
3159 }
3160
3161 if (!cf_section_find(server, "add", "client")) {
3162 cf_log_warn(conf, "No 'add client { ... }' section was defined.");
3163 }
3164
3165 if (!cf_section_find(server, "deny", "client")) {
3166 cf_log_warn(conf, "No 'deny client { ... }' section was defined.");
3167 }
3168 }
3169
3170 /*
3171 * Create a list of client modules.
3172 *
3173 * FIXME - Probably only want to do this for connected sockets?
3174 *
3175 * FIXME - We probably want write protect enabled?
3176 */
3177 inst->clients = module_list_alloc(inst, &module_list_type_thread_local, "clients", false);
3179
3180 return 0;
3181}
3182
3183
3184static char const *mod_name(fr_listen_t *li)
3185{
3186 fr_io_thread_t *thread;
3187 fr_io_connection_t *connection;
3188 fr_listen_t *child;
3189 fr_io_instance_t const *inst;
3190
3191 get_inst(li, &inst, &thread, &connection, &child);
3192
3193 fr_assert(child != NULL);
3194 return child->app_io->get_name(child);
3195}
3196
3197/** Create a trie from arrays of allow / deny IP addresses
3198 *
3199 * @param ctx the talloc ctx
3200 * @param af the address family to allow
3201 * @param allow the array of IPs / networks to allow. MUST be talloc'd
3202 * @param deny the array of IPs / networks to deny. MAY be NULL, MUST be talloc'd
3203 * @return
3204 * - fr_trie_t on success
3205 * - NULL on error
3206 */
3207fr_trie_t *fr_master_io_network(TALLOC_CTX *ctx, int af, fr_ipaddr_t *allow, fr_ipaddr_t *deny)
3208{
3209 fr_trie_t *trie;
3210 size_t i, num;
3211
3212 MEM(trie = fr_trie_alloc(ctx, NULL, NULL));
3213
3214 num = talloc_array_length(allow);
3215 fr_assert(num > 0);
3216
3217 for (i = 0; i < num; i++) {
3218 fr_ipaddr_t *network;
3219
3220 /*
3221 * Can't add v4 networks to a v6 socket, or vice versa.
3222 */
3223 if (allow[i].af != af) {
3224 fr_strerror_printf("Address family in entry %zd - 'allow = %pV' "
3225 "does not match 'ipaddr'", i + 1, fr_box_ipaddr(allow[i]));
3226 talloc_free(trie);
3227 return NULL;
3228 }
3229
3230 /*
3231 * Duplicates are bad.
3232 */
3233 network = fr_trie_match_by_key(trie,
3234 &allow[i].addr, allow[i].prefix);
3235 if (network) {
3236 fr_strerror_printf("Cannot add duplicate entry 'allow = %pV'",
3237 fr_box_ipaddr(allow[i]));
3238 talloc_free(trie);
3239 return NULL;
3240 }
3241
3242 /*
3243 * Look for overlapping entries.
3244 * i.e. the networks MUST be disjoint.
3245 *
3246 * Note that this catches 192.168.1/24
3247 * followed by 192.168/16, but NOT the
3248 * other way around. The best fix is
3249 * likely to add a flag to
3250 * fr_trie_alloc() saying "we can only
3251 * have terminal fr_trie_user_t nodes"
3252 */
3253 network = fr_trie_lookup_by_key(trie,
3254 &allow[i].addr, allow[i].prefix);
3255 if (network && (network->prefix <= allow[i].prefix)) {
3256 fr_strerror_printf("Cannot add overlapping entry 'allow = %pV'", fr_box_ipaddr(allow[i]));
3257 fr_strerror_const("Entry is completely enclosed inside of a previously defined network.");
3258 talloc_free(trie);
3259 return NULL;
3260 }
3261
3262 /*
3263 * Insert the network into the trie.
3264 * Lookups will return the fr_ipaddr_t of
3265 * the network.
3266 */
3267 if (fr_trie_insert_by_key(trie,
3268 &allow[i].addr, allow[i].prefix,
3269 &allow[i]) < 0) {
3270 fr_strerror_printf("Failed adding 'allow = %pV' to tracking table", fr_box_ipaddr(allow[i]));
3271 talloc_free(trie);
3272 return NULL;
3273 }
3274 }
3275
3276 /*
3277 * And now check denied networks.
3278 */
3279 num = talloc_array_length(deny);
3280 if (!num) return trie;
3281
3282 /*
3283 * Since the default is to deny, you can only add
3284 * a "deny" inside of a previous "allow".
3285 */
3286 for (i = 0; i < num; i++) {
3287 fr_ipaddr_t *network;
3288
3289 /*
3290 * Can't add v4 networks to a v6 socket, or vice versa.
3291 */
3292 if (deny[i].af != af) {
3293 fr_strerror_printf("Address family in entry %zd - 'deny = %pV' "
3294 "does not match 'ipaddr'", i + 1, fr_box_ipaddr(deny[i]));
3295 talloc_free(trie);
3296 return NULL;
3297 }
3298
3299 /*
3300 * Duplicates are bad.
3301 */
3302 network = fr_trie_match_by_key(trie,
3303 &deny[i].addr, deny[i].prefix);
3304 if (network) {
3305 fr_strerror_printf("Cannot add duplicate entry 'deny = %pV'", fr_box_ipaddr(deny[i]));
3306 talloc_free(trie);
3307 return NULL;
3308 }
3309
3310 /*
3311 * A "deny" can only be within a previous "allow".
3312 */
3313 network = fr_trie_lookup_by_key(trie,
3314 &deny[i].addr, deny[i].prefix);
3315 if (!network) {
3316 fr_strerror_printf("The network in entry %zd - 'deny = %pV' is not "
3317 "contained within a previous 'allow'", i + 1, fr_box_ipaddr(deny[i]));
3318 talloc_free(trie);
3319 return NULL;
3320 }
3321
3322 /*
3323 * We hack the AF in "deny" rules. If
3324 * the lookup gets AF_UNSPEC, then we're
3325 * adding a "deny" inside of a "deny".
3326 */
3327 if (network->af != af) {
3328 fr_strerror_printf("The network in entry %zd - 'deny = %pV' is overlaps "
3329 "with another 'deny' rule", i + 1, fr_box_ipaddr(deny[i]));
3330 talloc_free(trie);
3331 return NULL;
3332 }
3333
3334 /*
3335 * Insert the network into the trie.
3336 * Lookups will return the fr_ipaddr_t of
3337 * the network.
3338 */
3339 if (fr_trie_insert_by_key(trie,
3340 &deny[i].addr, deny[i].prefix,
3341 &deny[i]) < 0) {
3342 fr_strerror_printf("Failed adding 'deny = %pV' to tracking table", fr_box_ipaddr(deny[i]));
3343 talloc_free(trie);
3344 return NULL;
3345 }
3346
3347 /*
3348 * Hack it to make it a deny rule.
3349 */
3350 deny[i].af = AF_UNSPEC;
3351 }
3352
3353 return trie;
3354}
3355
3356
3358{
3359 if (!li->thread_instance) return 0;
3360
3362 return 0;
3363}
3364
3366 size_t default_message_size, size_t num_messages)
3367{
3368 fr_listen_t *li, *child;
3369 fr_io_thread_t *thread;
3370
3371 /*
3372 * No IO paths, so we don't initialize them.
3373 */
3374 if (!inst->app_io) {
3375 fr_assert(!inst->dynamic_clients);
3376 return 0;
3377 }
3378
3379 if (!inst->app_io->common.thread_inst_size) {
3380 fr_strerror_const("IO modules MUST set 'thread_inst_size' when using the master IO handler.");
3381 return -1;
3382 }
3383
3384 /*
3385 * Build the #fr_listen_t. This describes the complete
3386 * path data takes from the socket to the decoder and
3387 * back again.
3388 */
3389 MEM(li = talloc_zero(NULL, fr_listen_t));
3390 talloc_set_destructor(li, fr_io_listen_free);
3391
3392 /*
3393 * The first listener is the one for the application
3394 * (e.g. RADIUS). However, we mangle the IO path to
3395 * point to the master IO handler. That allows all of
3396 * the high-level work (dynamic client checking,
3397 * connected sockets, etc.) to be handled by the master
3398 * IO handler.
3399 *
3400 * This listener is then passed to the network code,
3401 * which calls our trampoline functions to do the actual
3402 * work.
3403 */
3404 li->app = inst->app;
3405 li->app_instance = inst->app_instance;
3406 li->server_cs = inst->server_cs;
3407
3408 /*
3409 * Set configurable parameters for message ring buffer.
3410 */
3411 li->default_message_size = default_message_size;
3412 li->num_messages = num_messages;
3413
3414 /*
3415 * Per-socket data lives here.
3416 */
3417 thread = talloc_zero(NULL, fr_io_thread_t);
3418 thread->listen = li;
3419 thread->sc = sc;
3420
3421 /*
3422 * Create the trie of clients for this socket.
3423 */
3424 MEM(thread->trie = fr_trie_alloc(thread, NULL, NULL));
3425
3426 if (inst->dynamic_clients) {
3428 fr_io_client_t, alive_id, 0));
3429 }
3430
3431 /*
3432 * Set the listener to call our master trampoline function.
3433 */
3434 li->cs = inst->app_io_conf;
3435 li->app_io = &fr_master_app_io;
3436 li->thread_instance = thread;
3437 li->app_io_instance = inst;
3438 li->track_duplicates = inst->app_io->track_duplicates;
3439 if (inst->app_io->hexdump_set) inst->app_io->hexdump_set(li, inst->app_io_instance);
3440
3441 /*
3442 * The child listener points to the *actual* IO path.
3443 *
3444 * We need to create a complete listener here (e.g.
3445 * RADIUS + RADIUS_UDP), because the underlying IO
3446 * functions expect to get passed a full listener.
3447 *
3448 * Once the network side calls us, we will call the child
3449 * listener to do the actual IO.
3450 */
3451 child = thread->child = talloc_zero(li, fr_listen_t);
3452 memcpy(child, li, sizeof(*child));
3453
3454 /*
3455 * Reset these fields to point to the IO instance data.
3456 */
3457 child->app_io = inst->app_io;
3458 child->track_duplicates = inst->app_io->track_duplicates;
3459
3460 if (child->app_io->common.thread_inst_size > 0) {
3461 child->thread_instance = talloc_zero_array(NULL, uint8_t,
3462 inst->app_io->common.thread_inst_size);
3463 talloc_set_destructor(child, fr_io_listen_free);
3464
3465 talloc_set_name(child->thread_instance, "proto_%s_thread_t",
3466 inst->app_io->common.name);
3467
3468 /*
3469 * This is "const", and the user can't
3470 * touch it. So we just reuse the same
3471 * configuration everywhere.
3472 */
3473 child->app_io_instance = inst->app_io_instance;
3474
3475 } else {
3476 child->thread_instance = inst->app_io_instance;
3477 child->app_io_instance = child->thread_instance;
3478 }
3479
3480 /*
3481 * Don't call connection_set() for the main socket. It's
3482 * not connected. Instead, tell the IO path to open the
3483 * socket for us.
3484 */
3485 if (inst->app_io->open(child) < 0) {
3486 talloc_free(li);
3487 return -1;
3488 }
3489
3490 li->fd = child->fd; /* copy this back up */
3491
3492 if (!child->app_io->get_name) {
3493 child->name = child->app_io->common.name;
3494 } else {
3495 child->name = child->app_io->get_name(child);
3496 }
3497 li->name = child->name;
3498
3499 /*
3500 * Record which socket we opened.
3501 */
3502 if (child->app_io_addr) {
3503 fr_listen_t *other;
3504
3505 other = listen_find_any(thread->child);
3506 if (other) {
3507 cf_log_err(other->cs, "Already opened socket %s", other->name);
3508 cf_log_err(li->cs, "Failed opening duplicate socket - cannot use the same configuration for two different listen sections");
3509
3510 talloc_free(li);
3511 return -1;
3512 }
3513
3514 (void) listen_record(child);
3515 }
3516
3517 /*
3518 * Add the socket to the scheduler, where it might end up
3519 * in a different thread.
3520 */
3521 if (!fr_schedule_listen_add(sc, li)) {
3522 talloc_free(li);
3523 return -1;
3524 }
3525
3526 return 0;
3527}
3528
3529/*
3530 * Used to create a tracking structure for fr_network_sendto_worker()
3531 */
3532fr_io_track_t *fr_master_io_track_alloc(fr_listen_t *li, fr_client_t *radclient, fr_ipaddr_t const *src_ipaddr, int src_port,
3533 fr_ipaddr_t const *dst_ipaddr, int dst_port)
3534{
3535 fr_io_instance_t const *inst;
3536 fr_io_thread_t *thread;
3537 fr_io_connection_t *connection;
3538 fr_listen_t *child;
3539 fr_io_track_t *track;
3540 fr_io_client_t *client;
3541 fr_io_address_t *address;
3542 fr_listen_t *parent = talloc_parent(li);
3543
3544 (void) talloc_get_type_abort(parent, fr_listen_t);
3545
3546 get_inst(parent, &inst, &thread, &connection, &child);
3547
3548 fr_assert(child == li);
3549
3550 if (unlikely(!thread)) return NULL;
3551 fr_assert(thread->trie != NULL);
3552
3553 client = fr_trie_lookup_by_key(thread->trie, &src_ipaddr->addr, src_ipaddr->prefix);
3554 if (!client) {
3555 MEM(client = client_alloc(thread, PR_CLIENT_STATIC, inst, thread, radclient, NULL));
3556 }
3557
3558 MEM(track = talloc_zero_pooled_object(client->table, fr_io_track_t, 1, sizeof(*track) + sizeof(*track->address) + 64));
3559 MEM(track->address = address = talloc_zero(track, fr_io_address_t));
3560
3561 track->li = li;
3562 track->client = client;
3563
3564 address->socket.inet.src_port = src_port;
3565 address->socket.inet.dst_port = dst_port;
3566
3567 address->socket.inet.src_ipaddr = *src_ipaddr;
3568 address->socket.inet.dst_ipaddr = *dst_ipaddr;
3569 address->radclient = radclient;
3570
3571 return track;
3572}
3573
3574
3576 .common = {
3577 .magic = MODULE_MAGIC_INIT,
3578 .name = "radius_master_io",
3579
3581 },
3582 .default_message_size = 4096,
3583 .track_duplicates = true,
3584
3585 .read = mod_read,
3586 .write = mod_write,
3587 .inject = mod_inject,
3588
3589 .open = mod_open,
3590 .close = mod_close,
3591 .event_list_set = mod_event_list_set,
3592 .get_name = mod_name,
3593};
static int const char char buffer[256]
Definition acutest.h:576
log_entry msg
Definition acutest.h:794
fr_io_close_t close
Close the transport.
Definition app_io.h:60
module_t common
Common fields to all loadable modules.
Definition app_io.h:34
fr_io_track_create_t track_create
create a tracking structure
Definition app_io.h:64
bool track_duplicates
track duplicate packets
Definition app_io.h:41
fr_io_name_t get_name
get the socket name
Definition app_io.h:70
fr_io_track_cmp_t track_compare
compare two tracking structures
Definition app_io.h:65
Public structure describing an I/O path for a protocol.
Definition app_io.h:33
#define CMP_PREFER_SMALLER(_a, _b)
Evaluates to +1 for a > b, and -1 for a < b.
Definition build.h:105
#define CMP_PREFER_LARGER(_a, _b)
Evaluates to -1 for a > b, and +1 for a < b.
Definition build.h:109
#define CMP_RETURN(_a, _b, _field)
Return if the comparison is not 0 (is unequal)
Definition build.h:122
#define CMP(_a, _b)
Same as CMP_PREFER_SMALLER use when you don't really care about ordering, you just want an ordering.
Definition build.h:113
#define unlikely(_x)
Definition build.h:407
#define UNUSED
Definition build.h:336
#define FR_TIME_DELTA_BOUND_CHECK(_name, _var, _op, _bound)
Definition cf_parse.h:540
A section grouping multiple CONF_PAIR.
Definition cf_priv.h:106
int cf_pair_replace_or_add(CONF_SECTION *cs, char const *ref, char const *value)
Definition cf_util.c:2597
char const * cf_section_name2(CONF_SECTION const *cs)
Return the second identifier of a CONF_SECTION.
Definition cf_util.c:1359
char const * cf_section_name1(CONF_SECTION const *cs)
Return the first identifier of a CONF_SECTION.
Definition cf_util.c:1345
CONF_SECTION * cf_section_find(CONF_SECTION const *cs, char const *name1, char const *name2)
Find a CONF_SECTION with name1 and optionally name2.
Definition cf_util.c:1201
CONF_SECTION * cf_item_to_section(CONF_ITEM const *ci)
Cast a CONF_ITEM to a CONF_SECTION.
Definition cf_util.c:692
CONF_SECTION * cf_section_dup(TALLOC_CTX *ctx, CONF_SECTION *parent, CONF_SECTION const *cs, char const *name1, char const *name2, bool copy_meta)
Duplicate a configuration section.
Definition cf_util.c:1032
#define cf_log_err(_cf, _fmt,...)
Definition cf_util.h:345
#define cf_parent(_cf)
Definition cf_util.h:118
#define cf_log_warn(_cf, _fmt,...)
Definition cf_util.h:346
#define PRIORITY_NORMAL
Definition channel.h:153
#define MEM(x)
Definition debug.h:36
#define ERROR(fmt,...)
Definition dhcpclient.c:40
#define DEBUG(fmt,...)
Definition dhcpclient.c:38
Test enumeration values.
Definition dict_test.h:92
#define MODULE_MAGIC_INIT
Stop people using different module/library/server versions together.
Definition dl_module.h:63
@ FR_EVENT_FILTER_IO
Combined filter for read/write functions/.
Definition event.h:83
#define fr_event_filter_update(...)
Definition event.h:239
#define FR_EVENT_RESUME(_s, _f)
Re-add the filter for a func from kevent.
Definition event.h:131
#define FR_EVENT_SUSPEND(_s, _f)
Temporarily remove the filter for a func from kevent.
Definition event.h:115
Callbacks for the FR_EVENT_FILTER_IO filter.
Definition event.h:188
Structure describing a modification to a filter's state.
Definition event.h:96
void * fr_hash_table_iter_next(fr_hash_table_t *ht, fr_hash_iter_t *iter)
Iterate over entries in a hash table.
Definition hash.c:649
void * fr_hash_table_find(fr_hash_table_t *ht, void const *data)
Find data in a hash table.
Definition hash.c:450
void * fr_hash_table_iter_init(fr_hash_table_t *ht, fr_hash_iter_t *iter)
Initialise an iterator.
Definition hash.c:704
uint32_t fr_hash_update(void const *data, size_t size, uint32_t hash)
Definition hash.c:881
uint32_t fr_hash(void const *data, size_t size)
Definition hash.c:847
bool fr_hash_table_insert(fr_hash_table_t *ht, void const *data)
Insert data into a hash table.
Definition hash.c:489
bool fr_hash_table_delete(fr_hash_table_t *ht, void const *data)
Remove and free data (if a free function was specified)
Definition hash.c:617
uint32_t fr_hash_table_num_elements(fr_hash_table_t *ht)
Definition hash.c:633
#define fr_hash_table_alloc(_ctx, _hash_node, _cmp_node, _free_node)
Definition hash.h:61
Stores the state of the current iteration operation.
Definition hash.h:41
int fr_heap_insert(fr_heap_t **hp, void *data)
Insert a new element into the heap.
Definition heap.c:146
void * fr_heap_pop(fr_heap_t **hp)
Remove a node from the heap.
Definition heap.c:325
int fr_heap_extract(fr_heap_t **hp, void *data)
Remove a node from the heap.
Definition heap.c:239
unsigned int fr_heap_index_t
Definition heap.h:80
static void * fr_heap_peek(fr_heap_t *h)
Return the item from the top of the heap but don't pop it.
Definition heap.h:136
#define fr_heap_alloc(_ctx, _cmp, _type, _field, _init)
Creates a heap that can be used with non-talloced elements.
Definition heap.h:100
static bool fr_heap_entry_inserted(fr_heap_index_t heap_idx)
Check if an entry is inserted into a heap.
Definition heap.h:124
static unsigned int fr_heap_num_elements(fr_heap_t *h)
Return the number of elements in the heap.
Definition heap.h:179
#define FR_HEAP_INDEX_INVALID
Definition heap.h:83
The main heap structure.
Definition heap.h:66
talloc_free(hp)
int fr_ipaddr_from_sockaddr(fr_ipaddr_t *ipaddr, uint16_t *port, struct sockaddr_storage const *sa, socklen_t salen)
Convert sockaddr to our internal ip address representation.
Definition inet.c:1448
int fr_ipaddr_to_sockaddr(struct sockaddr_storage *sa, socklen_t *salen, fr_ipaddr_t const *ipaddr, uint16_t port)
Convert our internal ip address representation to a sockaddr.
Definition inet.c:1399
int8_t fr_ipaddr_cmp(fr_ipaddr_t const *a, fr_ipaddr_t const *b)
Compare two ip addresses.
Definition inet.c:1353
void fr_ipaddr_mask(fr_ipaddr_t *addr, uint8_t prefix)
Zeroes out the host portion of an fr_ipaddr_t.
Definition inet.c:218
uint8_t prefix
Prefix length - Between 0-32 for IPv4 and 0-128 for IPv6.
Definition inet.h:68
int af
Address family.
Definition inet.h:63
union fr_ipaddr_t::@137 addr
IPv4/6 prefix.
fr_socket_t socket
src/dst ip and port.
Definition base.h:336
fr_client_t const * radclient
old-style client definition
Definition base.h:338
size_t num_messages
for the message ring buffer
Definition listen.h:57
CONF_SECTION * cs
of this listener
Definition listen.h:41
char const * name
printable name for this socket - set by open
Definition listen.h:29
bool track_duplicates
do we track duplicate packets?
Definition listen.h:45
fr_socket_t * app_io_addr
for tracking duplicate sockets
Definition listen.h:36
void const * app_instance
Definition listen.h:39
size_t default_message_size
copied from app_io, but may be changed
Definition listen.h:56
bool connected
is this for a connected socket?
Definition listen.h:44
fr_app_t const * app
Definition listen.h:38
void const * app_io_instance
I/O path configuration context.
Definition listen.h:33
CONF_SECTION * server_cs
CONF_SECTION of the server.
Definition listen.h:42
void * thread_instance
thread / socket context
Definition listen.h:34
int fd
file descriptor for this socket - set by open
Definition listen.h:28
fr_app_io_t const * app_io
I/O path functions.
Definition listen.h:32
int fr_network_listen_inject(fr_network_t *nr, fr_listen_t *li, uint8_t const *packet, size_t packet_len, fr_time_t recv_time)
Inject a packet for a listener to read.
Definition network.c:405
void fr_network_listen_read(fr_network_t *nr, fr_listen_t *li)
Signal the network to read from a listener.
Definition network.c:331
void fr_network_listen_write(fr_network_t *nr, fr_listen_t *li, uint8_t const *packet, size_t packet_len, void *packet_ctx, fr_time_t request_time)
Inject a packet for a listener to write.
Definition network.c:357
char const * server
Name of the virtual server client is associated with.
Definition client.h:133
fr_ipaddr_t ipaddr
IPv4/IPv6 address of the host.
Definition client.h:83
char const * secret
Secret PSK.
Definition client.h:90
bool active
for dynamic clients
Definition client.h:120
fr_ipaddr_t src_ipaddr
IPv4/IPv6 address to send responses from (family must match ipaddr).
Definition client.h:84
char const * nas_type
Type of client (arbitrary).
Definition client.h:131
int proto
Protocol number.
Definition client.h:147
CONF_SECTION * cs
CONF_SECTION that was parsed to generate the client.
Definition client.h:138
bool dynamic
Whether the client was dynamically defined.
Definition client.h:119
char const * longname
Client identifier.
Definition client.h:87
fr_socket_limit_t limit
Connections per client (TCP clients only).
Definition client.h:148
char const * shortname
Client nickname.
Definition client.h:88
bool use_connected
do we use connected sockets for this client
Definition client.h:121
CONF_SECTION * server_cs
Virtual server that the client is associated with.
Definition client.h:134
Describes a host allowed to send packets to the server.
Definition client.h:80
#define PERROR(_fmt,...)
Definition log.h:228
#define DEBUG3(_fmt,...)
Definition log.h:266
#define RATE_LIMIT_LOCAL(_entry, _log, _fmt,...)
Rate limit messages using a local limiting entry.
Definition log.h:581
Track when a log message was last repeated.
Definition log.h:559
#define fr_time()
Definition event.c:60
Stores all information relating to an event list.
Definition event.c:377
fr_listen_t * child
The child (app_io) IO path.
Definition master.c:41
fr_network_t * nr
network for this connection
Definition master.c:163
static void fr_io_connection_allow(fr_io_client_t *parent, fr_client_t *radclient)
Promote a pending dynamic-client parent and all of its child connections.
Definition master.c:2555
static fr_io_track_t * fr_io_track_add(fr_listen_t const *li, fr_io_client_t *client, fr_io_address_t *address, uint8_t const *packet, size_t packet_len, fr_time_t recv_time, bool *is_dup)
Definition master.c:1160
static int8_t alive_client_cmp(void const *one, void const *two)
Definition master.c:1380
bool in_trie
is the client in the trie?
Definition master.c:122
static fr_io_pending_packet_t * fr_io_pending_alloc(fr_io_connection_t *connection, fr_io_client_t *client, uint8_t const *buffer, size_t packet_len, fr_io_track_t *track, int priority)
Definition master.c:1335
bool paused
event filter doesn't like resuming something that isn't paused
Definition master.c:160
bool in_parent_hash
for tracking thread issues
Definition master.c:161
static fr_client_t * radclient_clone(TALLOC_CTX *ctx, fr_client_t const *parent)
Definition master.c:394
static ssize_t mod_read(fr_listen_t *li, void **packet_ctx, fr_time_t *recv_time_p, uint8_t *buffer, size_t buffer_len, size_t *leftover)
Implement 99% of the read routines.
Definition master.c:1392
int packets
number of packets using this connection
Definition master.c:151
uint32_t num_pending_packets
number of pending packets
Definition master.c:46
#define DUP_FIELD(_x)
static int track_dedup_free(fr_io_track_t *track)
Definition master.c:187
fr_rb_tree_t * table
tracking table for packets
Definition master.c:127
fr_time_t recv_time
Definition master.c:69
static int8_t pending_packet_cmp(void const *one, void const *two)
Definition master.c:213
fr_heap_t * pending_clients
heap of pending clients
Definition master.c:37
bool ready_to_delete
are we ready to delete this client?
Definition master.c:121
static int _client_live_free(fr_io_client_t *client)
Definition master.c:1022
fr_heap_index_t pending_id
for pending clients
Definition master.c:117
static int pending_free(fr_io_pending_packet_t *pending)
Definition master.c:1311
bool use_connected
does this client allow connected sub-sockets?
Definition master.c:120
fr_io_client_t * client
our local client (pending or connected).
Definition master.c:155
static int track_free(fr_io_track_t *track)
Definition master.c:176
fr_app_io_t fr_master_app_io
Definition master.c:3575
static void packet_expiry_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
Definition master.c:2380
fr_listen_t * listen
The master IO path.
Definition master.c:40
static int8_t pending_client_cmp(void const *one, void const *two)
Definition master.c:243
fr_io_track_t * fr_master_io_track_alloc(fr_listen_t *li, fr_client_t *radclient, fr_ipaddr_t const *src_ipaddr, int src_port, fr_ipaddr_t const *dst_ipaddr, int dst_port)
Definition master.c:3532
fr_io_address_t * address
full information about the connection.
Definition master.c:152
static int8_t address_cmp(void const *one, void const *two)
Definition master.c:261
fr_listen_t * child
child listener (app_io) for this socket
Definition master.c:154
fr_listen_t * listen
master listener for this socket
Definition master.c:153
fr_timer_t * ev
when we clean up the client
Definition master.c:126
fr_network_t * nr
network for the master socket
Definition master.c:34
fr_trie_t * fr_master_io_network(TALLOC_CTX *ctx, int af, fr_ipaddr_t *allow, fr_ipaddr_t *deny)
Create a trie from arrays of allow / deny IP addresses.
Definition master.c:3207
static fr_io_pending_packet_t * pending_packet_pop(fr_io_thread_t *thread)
Definition master.c:356
static void update_client(fr_io_client_t *client, fr_client_t *radclient)
Definition master.c:2446
fr_ipaddr_t network
network for dynamic clients
Definition master.c:113
static void mod_event_list_set(fr_listen_t *li, fr_event_list_t *el, void *nr)
Set the event list for a new socket.
Definition master.c:2133
static int mod_open(fr_listen_t *li)
Open a new listener.
Definition master.c:2097
pthread_mutex_t mutex
for parent / child signaling
Definition master.c:132
fr_heap_index_t heap_id
Definition master.c:67
static fr_io_client_t * client_alloc(TALLOC_CTX *ctx, fr_io_client_state_t state, fr_io_instance_t const *inst, fr_io_thread_t *thread, fr_client_t *radclient, fr_ipaddr_t const *network)
Allocate a dynamic client.
Definition master.c:1054
fr_io_instance_t const * inst
parent instance for master IO handler
Definition master.c:124
#define LOG_IGNORED_CLIENTS(_inst)
#define COPY_FIELD(_x)
static void fr_io_connection_deny(fr_io_client_t *parent)
Tear down any deferred sibling connections under a pending parent.
Definition master.c:2494
fr_trie_t * trie
trie of clients
Definition master.c:36
static void client_expiry_timer(fr_timer_list_t *tl, fr_time_t now, void *uctx)
Definition master.c:2166
fr_io_client_state_t
Client states.
Definition master.c:79
@ PR_CLIENT_DYNAMIC
dynamically defined client
Definition master.c:83
@ PR_CLIENT_CONNECTED
dynamically defined client in a connected socket
Definition master.c:84
@ PR_CLIENT_PENDING
dynamic client pending definition
Definition master.c:85
@ PR_CLIENT_INVALID
Definition master.c:80
@ PR_CLIENT_NAK
negative cache entry
Definition master.c:82
@ PR_CLIENT_STATIC
static / global clients
Definition master.c:81
static void get_inst(fr_listen_t *li, fr_io_instance_t const **inst, fr_io_thread_t **thread, fr_io_connection_t **connection, fr_listen_t **child)
Definition master.c:974
static fr_event_update_t pause_read[]
Definition master.c:166
static int8_t track_connected_cmp(void const *one, void const *two)
Definition master.c:330
fr_heap_t * alive_clients
heap of active dynamic clients
Definition master.c:38
fr_schedule_t * sc
the scheduler
Definition master.c:42
static fr_io_connection_t * fr_io_connection_alloc(fr_io_instance_t const *inst, fr_io_thread_t *thread, fr_io_client_t *client, int fd, fr_io_address_t *address, fr_io_connection_t *nak)
Create a new connection.
Definition master.c:534
fr_hash_table_t * addresses
list of src/dst addresses used by this client
Definition master.c:130
int fr_master_io_listen(fr_io_instance_t *inst, fr_schedule_t *sc, size_t default_message_size, size_t num_messages)
Definition master.c:3365
static int connection_free(fr_io_connection_t *connection)
Definition master.c:519
struct fr_io_thread_t::@38 rate_limit
int fr_io_listen_free(fr_listen_t *li)
Definition master.c:3357
char const * name
taken from proto_FOO_TRANSPORT
Definition master.c:150
fr_heap_index_t alive_id
for all clients
Definition master.c:118
fr_event_list_t * el
event list for this connection
Definition master.c:162
fr_io_client_state_t state
state of this client
Definition master.c:111
int packets
number of packets using this client
Definition master.c:116
static ssize_t mod_write(fr_listen_t *li, void *packet_ctx, fr_time_t request_time, uint8_t *buffer, size_t buffer_len, size_t written)
Definition master.c:2641
bool dead
roundabout way to get the network side to close a socket
Definition master.c:159
fr_event_list_t * el
event list, for the master socket.
Definition master.c:33
uint64_t client_id
Unique client identifier.
Definition master.c:47
fr_io_thread_t * thread
Definition master.c:125
static char const * mod_name(fr_listen_t *li)
Definition master.c:3184
module_instance_t * mi
for submodule
Definition master.c:157
static int _client_free(fr_io_client_t *client)
Definition master.c:487
static int mod_close(fr_listen_t *li)
Close the socket.
Definition master.c:3056
static uint32_t connection_hash(void const *ctx)
Definition master.c:277
fr_io_connection_t * connection
parent connection
Definition master.c:110
fr_heap_t * pending
pending packets for this client
Definition master.c:129
static int count_connections(UNUSED uint8_t const *key, UNUSED size_t keylen, void *data, void *ctx)
Count the number of connections used by active clients.
Definition master.c:460
static int8_t connection_cmp(void const *one, void const *two)
Definition master.c:291
static int8_t track_cmp(void const *one, void const *two)
Definition master.c:300
fr_hash_table_t * ht
for tracking connected sockets
Definition master.c:133
static int mod_instantiate(module_inst_ctx_t const *mctx)
Definition master.c:3109
fr_io_track_t * track
Definition master.c:70
fr_client_t * radclient
old-style definition of this client
Definition master.c:114
fr_ipaddr_t src_ipaddr
packets come from this address
Definition master.c:112
static fr_event_update_t resume_read[]
Definition master.c:171
static void client_pending_free(fr_io_client_t *client)
Definition master.c:502
uint32_t num_connections
number of dynamic connections
Definition master.c:45
fr_io_client_t * parent
points to the parent client.
Definition master.c:156
static fr_client_t * radclient_alloc(TALLOC_CTX *ctx, int ipproto, fr_io_address_t *address)
Definition master.c:994
static int mod_inject(fr_listen_t *li, uint8_t const *buffer, size_t buffer_len, fr_time_t recv_time)
Inject a packet to a connection.
Definition master.c:2039
Client definitions for master IO.
Definition master.c:109
Track a connection.
Definition master.c:149
A saved packet.
Definition master.c:66
fr_timer_t * ev
when we clean up this tracking entry
Definition master.h:43
uint8_t * reply
reply packet (if any)
Definition master.h:47
int packets
number of packets using this entry
Definition master.h:46
fr_time_t dynamic
timestamp for packet doing dynamic client definition
Definition master.h:54
void * app_io_instance
Easy access to the app_io instance.
Definition master.h:106
fr_app_io_t const * app_io
Easy access to the app_io handle.
Definition master.h:105
fr_io_address_t const * address
of this packet.. shared between multiple packets
Definition master.h:55
bool do_not_respond
don't respond
Definition master.h:51
fr_listen_t const * li
listener associated with this tracking structure
Definition master.h:42
bool discard
whether or not we discard the packet
Definition master.h:50
fr_time_t timestamp
when this packet was received
Definition master.h:44
bool finished
are we finished the request?
Definition master.h:52
uint8_t * packet
really a tracking structure, not a packet
Definition master.h:57
size_t reply_len
length of reply, or 1 for "do not reply"
Definition master.h:48
fr_io_client_t * client
client handling this packet.
Definition master.h:56
fr_time_t expires
when this packet expires
Definition master.h:45
The master IO instance.
Definition master.h:73
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
int fr_nonblock(UNUSED int fd)
Definition misc.c:293
module_instance_t * mi
Instance of the module being instantiated.
Definition module_ctx.h:51
Temporary structure to hold arguments for instantiation calls.
Definition module_ctx.h:50
char * fr_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Special version of asprintf which implements custom format specifiers.
Definition print.c:883
#define fr_assert(_expr)
Definition rad_assert.h:37
static int ipproto
static char * secret
#define DEBUG2(fmt,...)
#define INFO(fmt,...)
Definition radict.c:63
static bool cleanup
Definition radsniff.c:59
static rs_t * conf
Definition radsniff.c:52
void * fr_rb_find(fr_rb_tree_t const *tree, void const *data)
Find an element in the tree, returning the data, not the node.
Definition rb.c:577
bool fr_rb_insert(fr_rb_tree_t *tree, void const *data)
Insert data into a tree.
Definition rb.c:626
bool fr_rb_delete(fr_rb_tree_t *tree, void const *data)
Remove node and free data (if a free function was specified)
Definition rb.c:741
#define fr_rb_inline_talloc_alloc(_ctx, _type, _field, _data_cmp, _data_free)
Allocs a red black that verifies elements are of a specific talloc type.
Definition rb.h:244
bool being_freed
Prevent double frees in talloc_destructor.
Definition rb.h:94
The main red black tree structure.
Definition rb.h:71
static unsigned int hash(char const *username, unsigned int tablesize)
Definition rlm_passwd.c:132
static char const * name
fr_network_t * fr_schedule_listen_add(fr_schedule_t *sc, fr_listen_t *li)
Add a fr_listen_t to a scheduler.
Definition schedule.c:730
The scheduler.
Definition schedule.c:76
CONF_SECTION * conf
Module's instance configuration.
Definition module.h:351
void * data
Module's instance data.
Definition module.h:293
module_instantiate_t instantiate
Callback to allow the module to register any per-instance resources like sockets and file handles.
Definition module.h:227
@ MODULE_INSTANCE_BOOTSTRAPPED
Module instance has been bootstrapped, but not yet instantiated.
Definition module.h:266
size_t thread_inst_size
Size of the module's thread-specific instance data.
Definition module.h:246
Module instance data.
Definition module.h:287
fr_time_delta_t idle_timeout
Definition socket.h:38
uint32_t max_connections
Definition socket.h:33
static const uchar sc[16]
Definition smbdes.c:115
module_list_type_t const module_list_type_thread_local
Callbacks for a thread local list.
Definition module.c:587
void module_list_mask_set(module_list_t *ml, module_instance_state_t mask)
Set a new bootstrap/instantiate state for a list.
Definition module.c:1876
module_instance_t * module_instance_copy(module_list_t *dst, module_instance_t const *src, char const *inst_name)
Duplicate a module instance, placing it in a new module list.
Definition module.c:1575
module_list_t * module_list_alloc(TALLOC_CTX *ctx, module_list_type_t const *type, char const *name, bool write_protect)
Allocate a new module list.
Definition module.c:1898
int module_thread_instantiate(TALLOC_CTX *ctx, module_instance_t *mi, fr_event_list_t *el)
Allocate thread-local instance data for a module.
Definition module.c:1082
int module_instantiate(module_instance_t *instance)
Manually complete module setup by calling its instantiate function.
Definition module.c:1224
int module_instance_conf_parse(module_instance_t *mi, CONF_SECTION *conf)
Covert a CONF_SECTION into parsed module instance data.
Definition module.c:763
eap_aka_sim_process_conf_t * inst
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
#define talloc_get_type_abort_const
Definition talloc.h:117
#define talloc_zero_pooled_object(_ctx, _type, _num_subobjects, _total_subobjects_size)
Definition talloc.h:208
static int talloc_const_free(void const *ptr)
Free const'd memory.
Definition talloc.h:288
static TALLOC_CTX * talloc_init_const(char const *name)
Allocate a top level chunk with a constant name.
Definition talloc.h:127
#define talloc_asprintf
Definition talloc.h:151
#define talloc_strdup(_ctx, _str)
Definition talloc.h:149
static int64_t fr_time_delta_unwrap(fr_time_delta_t time)
Definition time.h:154
#define fr_time_delta_lt(_a, _b)
Definition time.h:285
static int64_t fr_time_unwrap(fr_time_t time)
Definition time.h:146
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:590
#define fr_time_delta_wrap(_time)
Definition time.h:152
#define fr_time_wrap(_time)
Definition time.h:145
#define fr_time_delta_ispos(_a)
Definition time.h:290
#define fr_time_eq(_a, _b)
Definition time.h:241
#define NSEC
Definition time.h:379
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_neq(_a, _b)
Definition time.h:242
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
An event timer list.
Definition timer.c:49
A timer event.
Definition timer.c:83
#define FR_TIMER_DISARM_RETURN(_ev)
Definition timer.h:98
#define FR_TIMER_DELETE(_ev_p)
Definition timer.h:103
#define FR_TIMER_DELETE_RETURN(_ev_p)
Definition timer.h:110
#define fr_timer_in(...)
Definition timer.h:87
#define FR_TIMER_DISARM(_ev)
Definition timer.h:91
static bool fr_timer_armed(fr_timer_t *ev)
Definition timer.h:120
#define fr_timer_at(...)
Definition timer.h:81
void * fr_trie_remove_by_key(fr_trie_t *ft, void const *key, size_t keylen)
Remove a key and return the associated user ctx.
Definition trie.c:2157
fr_trie_t * fr_trie_alloc(TALLOC_CTX *ctx, fr_trie_key_t get_key, fr_free_t free_data)
Allocate a trie.
Definition trie.c:741
int fr_trie_walk(fr_trie_t *ft, void *ctx, fr_trie_walk_t callback)
Definition trie.c:2610
void * fr_trie_lookup_by_key(fr_trie_t const *ft, void const *key, size_t keylen)
Lookup a key in a trie and return user ctx, if any.
Definition trie.c:1265
void * fr_trie_match_by_key(fr_trie_t const *ft, void const *key, size_t keylen)
Match a key and length in a trie and return user ctx, if any.
Definition trie.c:1289
int fr_trie_insert_by_key(fr_trie_t *ft, void const *key, size_t keylen, void const *data)
Insert a key and user ctx into a trie.
Definition trie.c:1878
static fr_event_list_t * el
static fr_slen_t parent
Definition pair.h:858
int fd
File descriptor if this is a live socket.
Definition socket.h:78
int type
SOCK_STREAM, SOCK_DGRAM, etc.
Definition socket.h:76
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition strerror.h:64
#define fr_strerror_const(_msg)
Definition strerror.h:223
static fr_slen_t fr_value_box_aprint(TALLOC_CTX *ctx, char **out, fr_value_box_t const *data, fr_sbuff_escape_rules_t const *e_rules) 1(fr_value_box_print
#define fr_box_ipaddr(_val)
Definition value.h:317
static fr_slen_t data
Definition value.h:1340
#define fr_box_time_delta(_val)
Definition value.h:366
bool listen_record(fr_listen_t *li)
Record that we're listening on a particular IP / port.
fr_listen_t * listen_find_any(fr_listen_t *li)
See if another global listener is using a particular IP / port.