The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
bio.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 (at
5 * 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: 277afb1ba176f210c1f734eca17e0fd74c6ab460 $
19 * @file src/modules/rlm_radius/bio.c
20 * @brief RADIUS BIO transport
21 *
22 * @copyright 2017 Network RADIUS SAS
23 * @copyright 2020 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
24 */
25
26#include <freeradius-devel/io/application.h>
27#include <freeradius-devel/io/listen.h>
28#include <freeradius-devel/io/pair.h>
29#include <freeradius-devel/server/connection.h>
30#include <freeradius-devel/unlang/function.h>
31#include <freeradius-devel/unlang/load_balance_priv.h>
32#include <freeradius-devel/unlang/subrequest.h>
33#include <freeradius-devel/util/heap.h>
34#include <freeradius-devel/util/rb_expire.h>
35
36
37//#include "rlm_radius.h"
38#include "track.h"
39
40typedef enum : uint8_t {
41 LIMIT_PORTS_NONE = 0, //!< Source port not restricted
42 LIMIT_PORTS_STATIC, //!< Limited source ports for static home servers
43 LIMIT_PORTS_DYNAMIC //!< Limited source ports for dynamic home servers
45
46typedef struct {
47 char const *module_name; //!< the module that opened the connection
48 rlm_radius_t const *inst; //!< our instance
49 fr_event_list_t *el; //!< Event list.
50 trunk_t *trunk; //!< trunk handler
51 fr_bio_fd_config_t fd_config; //!< for threads or sockets
52 fr_bio_fd_info_t const *fd_info; //!< status of the FD.
53 fr_radius_ctx_t radius_ctx; //!< for signing packets
54 bio_limit_ports_t limit_source_ports; //!< What type of port limit is in use.
55 bool dynamic; //!< is this a dynamic home server.
56#ifdef WITH_TLS
57 SSL_CTX *ssl_ctx; //!< TLS context for this thread, NULL if we don't use TLS.
58#endif
60
61typedef struct {
62 bio_handle_ctx_t ctx; //!< common struct for home servers and BIO handles
63
64 struct {
65 fr_bio_t *fd; //!< writing
66 uint32_t id; //!< for replication
67 fr_rb_expire_t expires; //!< for proxying / client sending
68 } bio;
69
73
75
76/** Track the handle, which is tightly correlated with the FD
77 *
78 */
79typedef struct bio_handle_s {
80 bio_handle_ctx_t ctx; //!< common struct for home servers and BIO handles
81
82 int fd; //!< File descriptor.
83
84 bool eof; //!< The BIO chain is at EOF, see bio_eof().
85
86 bool radius_1_1; //!< RADIUS/1.1 has been negotiated for this connection
87
88 bool write_blocked; //!< A stream write blocked, and has not yet resumed. See
89 ///< bio_write_blocked() and bio_write_resume().
90
91 struct {
92 fr_bio_t *main; //!< what we use for IO
93 fr_bio_t *fd; //!< raw FD
94 fr_bio_t *mem; //!< memory wrappers for stream sockets
95#ifdef WITH_TLS
96 fr_bio_tls_t *tls; //!< TLS BIO.
97#endif
98 } bio;
99
101
102 uint8_t last_id; //!< Used when replicating to ensure IDs are distributed
103 ///< evenly.
104
105 uint32_t max_packet_size; //!< Our max packet size. may be different from the parent.
106
107 uint8_t *buffer; //!< Receive buffer.
108 size_t buflen; //!< Receive buffer length.
109
110 radius_track_t *tt; //!< RADIUS ID tracking structure.
111
112 fr_time_t last_reply; //!< When we last received a reply.
113 fr_time_t last_sent; //!< last time we wrote a request.
114 fr_time_t first_unanswered; //!< When the current run of unanswered requests started. Zero
115 ///< when no request is waiting for a reply since last_reply.
116 uint32_t timeouts; //!< Requests which timed out without a reply since the last reply.
117 ///< Compared with `response_timeouts`.
118
119 fr_timer_list_t *tl; //!< Timers for this connection
120
121 fr_timer_t *zombie_ev; //!< Zombie timeout. Only used when `status_check = no`.
122 unlang_t const *instruction; //!< Instruction which triggered the start of the zombie period.
123
124 bool status_checking; //!< whether we're doing status checks
125 bio_request_t *status_u; //!< for sending status check packets
127
128#ifdef WITH_TLS
129 request_t *conn_request; //!< owns the TLS bio, and runs the handshake. This is
130 ///< separate from status_request.
131 struct bio_handle_s **p_self; //!< Tells the handle when the worker frees conn_request.
132 ///< parented from conn_request.
133 bool tls_starting; //!< Are we inside of fr_bio_tls_connect() ?
134 bool tls_started; //!< The connection request has run, and the TLS start is scheduled.
135 fr_timer_t *tls_ev; //!< Starts the TLS connection.
136 fr_timer_t *tls_failed_ev; //!< Signals the connection after the TLS connection failed.
137#endif
138
139 trunk_connection_t *tconn; //!< The trunk connection. Set by thread_conn_notify(), so it
140 ///< is NULL until the trunk has started to use the connection.
141 trunk_connection_event_t notify_on; //!< The events which the trunk last asked for.
143
144/** Is the connection at EOF?
145 *
146 * Either the whole BIO chain is at EOF, or the fd is at EOF.
147 */
148static inline CC_HINT(always_inline) bool bio_at_eof(bio_handle_t const *h)
149{
150 return h->eof || h->ctx.fd_info->eof;
151}
152
153
154/** Connect request_t to local tracking structure
155 *
156 */
159 rlm_rcode_t rcode; //!< from the transport
160
161 uint32_t priority; //!< copied from request->async->priority
162 fr_time_t recv_time; //!< copied from request->async->recv_time
163
164 uint32_t num_replies; //!< number of reply packets, sent is in retry.count
165
166 bool status_check; //!< is this packet a status check?
167 bool proxied; //!< is this request being proxied
168
169 fr_pair_list_t extra; //!< VPs for debugging, like Proxy-State.
170
171 uint8_t code; //!< Packet code.
172 uint8_t id; //!< Last ID assigned to this packet.
173 uint32_t token; //!< Last Token assigned to this packet. Only for RADIUS/1.1.
174 uint8_t *packet; //!< Packet we write to the network.
175 size_t packet_len; //!< Length of the packet.
176 size_t partial; //!< partially sent data
177
178 fr_time_t last_written; //!< when the last whole packet was last written.
179 ///< Suppresses fast / duplicate NAS retransmissions
180
181 radius_track_entry_t *rr; //!< ID tracking, resend count, etc.
182 fr_timer_t *ev; //!< timer for retransmissions
183 fr_retry_t retry; //!< retransmission timers
184};
185
186typedef struct {
187 bio_handle_ctx_t ctx; //!< for copying to bio_handle_t
188
190
192 connection_t *connections[]; //!< for tracking outbound connections
194
195/*
196 * Due to RFC 3539 requirements that a proxy doesn't do retransmits itself, the proxy is just a "wire",
197 * and retransmits when the NAS retransmits. However, many NASes ignore the RFC 5080 Section 2.2.1
198 * requirements on retransmissions, and send packets very quickly.
199 *
200 * We therefore limit retransmissions on the proxy to no more than once per second.
201 */
202#define DUP_INTERVAL fr_time_delta_from_sec(1)
203
204
205/** Turn a reply code into a module rcode;
206 *
207 */
223
225 UNUSED int flags, void *uctx);
226
228
229static fr_radius_decode_fail_t decode(TALLOC_CTX *ctx, fr_pair_list_t *reply, uint8_t *response_code,
231 uint8_t const request_authenticator[static RADIUS_AUTH_VECTOR_LENGTH],
232 uint8_t *data, size_t data_len);
233
235
237
239 trunk_connection_event_t notify_on, void *uctx);
240
241static int _bio_request_free(bio_request_t *u);
242
243static fr_cmp_ret_t home_server_cmp(void const *one, void const *two);
244
245#ifndef NDEBUG
246/** Log additional information about a tracking entry
247 *
248 * @param[in] te Tracking entry we're logging information for.
249 * @param[in] log destination.
250 * @param[in] log_type Type of log message.
251 * @param[in] file the logging request was made in.
252 * @param[in] line logging request was made on.
253 */
254static void bio_tracking_entry_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line,
256{
258
259 if (!te->request) return; /* Free entry */
260
261 request = talloc_get_type_abort(te->request, request_t);
262
263 fr_log(log, log_type, file, line, "request %s, allocated %s:%d", request->name,
264 request->alloc_file, request->alloc_line);
265
266 trunk_request_state_log(log, log_type, file, line, talloc_get_type_abort(te->uctx, trunk_request_t));
267}
268#endif
269
270/** Clear out any connection specific resources from a udp request
271 *
272 */
274{
275 TALLOC_FREE(u->packet);
277
278 /*
279 * Can have packet put no u->rr
280 * if this is part of a pre-trunk status check.
281 */
282 if (u->rr) radius_track_entry_release(&u->rr);
283
285}
286
287/** Reset a status_check packet, ready to reuse
288 *
289 */
291{
292 fr_assert(u->status_check == true);
293
294 h->status_checking = false;
295 u->num_replies = 0; /* Reset */
296 u->retry.start = fr_time_wrap(0);
297
299
301}
302
303/*
304 * Status-Server checks. Manually build the packet, and
305 * all of its associated glue.
306 */
308{
309 bio_request_t *u;
311 fr_pair_t *vp;
312 rlm_radius_t const *inst = h->ctx.inst;
313
315
317 MEM(u = talloc_zero(request, bio_request_t));
318 talloc_set_destructor(u, _bio_request_free);
319
320 h->status_u = u;
321
324
325 /*
326 * Status checks are prioritized over any other packet
327 */
328 u->priority = ~(uint32_t) 0;
329 u->status_check = true;
330
331 /*
332 * Allocate outside of the free list.
333 * There appears to be an issue where
334 * the thread destructor runs too
335 * early, and frees the freelist's
336 * head before the module destructor
337 * runs.
338 */
339 request->async = talloc_zero(request, fr_async_t);
340 request->async->request = request;
343
344 request->packet = fr_packet_alloc(request, false);
345 request->reply = fr_packet_alloc(request, false);
346
347 /*
348 * Create the VPs, and ignore any errors creating them.
349 */
350 if (map_list_num_elements(&inst->status_check_map) > 0) {
351 map_t *map = NULL;
352
353 while ((map = map_list_next(&inst->status_check_map, map))) {
354 (void) map_to_request(request, map, map_to_vp, NULL);
355 }
356 } else {
357 /*
358 * Ensure that there's a NAS-Identifier with a value.
359 *
360 * Arguably if there's no status-check map, then the request_pairs are empty. But
361 * whatever...
362 */
363 if (!fr_pair_find_by_da(&request->request_pairs, NULL, attr_nas_identifier)) {
365 fr_pair_value_strdup(vp, "status check - are you alive?", false);
366 }
367 }
368
369 /*
370 * Always add an Event-Timestamp, and update its value every time we send a packet.
371 *
372 * The retry code will later update the timestamp, too, but updating it here means that the debug
373 * output doesn't show a zero-value Event-Timstamp.
374 */
375 vp = fr_pair_find_by_da(&request->request_pairs, NULL, attr_event_timestamp);
376 if (!vp) {
378 }
379 vp->vp_date = fr_time_to_unix_time(fr_time());
380
381 /*
382 * Initialize the request IO ctx. Note that we don't set
383 * destructors.
384 */
385 u->code = inst->status_check;
386 request->packet->code = u->code;
387
388 DEBUG3("%s - Status check packet type will be %s", h->ctx.module_name, fr_radius_packet_name[u->code]);
389 log_request_proto_pair_list(L_DBG_LVL_3, request, NULL, &request->request_pairs, NULL);
390}
391
392/** Connection errored
393 *
394 * We were signalled by the event loop that a fatal error occurred on this connection.
395 *
396 * @param[in] el The event list signalling.
397 * @param[in] fd that errored.
398 * @param[in] flags El flags.
399 * @param[in] fd_errno The nature of the error.
400 * @param[in] uctx The trunk connection handle (tconn).
401 */
402static void conn_init_error(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, void *uctx)
403{
404 connection_t *conn = talloc_get_type_abort(uctx, connection_t);
405 bio_handle_t *h;
406
407 /*
408 * Connection must be in the connecting state when this fires
409 */
411
412 h = talloc_get_type_abort(conn->h, bio_handle_t);
413
414 ERROR("%s - Connection %s failed: %s", h->ctx.module_name, h->ctx.fd_info->name, fr_syserror(fd_errno));
415
417}
418
419/** Status check timer when opening the connection for the first time.
420 *
421 * Setup retries, or fail the connection.
422 */
423static void conn_init_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
424{
425 connection_t *conn = talloc_get_type_abort(uctx, connection_t);
426 bio_handle_t *h;
427 bio_request_t *u;
428
429 /*
430 * Connection must be in the connecting state when this fires
431 */
433
434 h = talloc_get_type_abort(conn->h, bio_handle_t);
435 u = h->status_u;
436
437 /*
438 * We're only interested in contiguous, good, replies.
439 */
440 u->num_replies = 0;
441
442 switch (fr_retry_next(&u->retry, now)) {
443 case FR_RETRY_MRD:
444 DEBUG("%s - Reached maximum_retransmit_duration (%pVs > %pVs), failing status checks",
447 goto fail;
448
449 case FR_RETRY_MRC:
450 DEBUG("%s - Reached maximum_retransmit_count (%u > %u), failing status checks",
452 fail:
454 return;
455
457 if (fr_event_fd_insert(h, NULL, conn->el, h->fd, NULL, conn_init_writable,
458 conn_init_error, conn) < 0) {
459 PERROR("%s - Failed inserting FD event", h->ctx.module_name);
461 }
462 return;
463 }
464
465 fr_assert(0);
466}
467
468/** Perform the next step of init and negotiation.
469 *
470 */
471static void conn_init_next(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
472{
473 connection_t *conn = talloc_get_type_abort(uctx, connection_t);
474 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
475 bio_request_t *u = h->status_u;
476
477 /*
478 * The previous status check was answered, so start the retries again. Unlike conn_init_timeout(),
479 * we do not reset u->num_replies, as we want contiguous good replies.
480 */
482
483 if (fr_event_fd_insert(h, NULL, conn->el, h->fd, NULL, conn_init_writable, conn_init_error, conn) < 0) {
484 PERROR("%s - Failed inserting FD event", h->ctx.module_name);
486 }
487}
488
489/** Read the connection during the init and negotiation stage.
490 *
491 */
492static void conn_init_readable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
493{
494 connection_t *conn = talloc_get_type_abort(uctx, connection_t);
495 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
496 trunk_t *trunk = h->ctx.trunk;
497 rlm_radius_t const *inst = h->ctx.inst;
498 bio_request_t *u = h->status_u;
499 ssize_t slen;
501 uint8_t code = 0;
502
504 slen = fr_bio_read(h->bio.main, NULL, h->buffer, h->buflen);
505 if (slen == 0) {
506 if (bio_at_eof(h)) goto failed;
507 return;
508 }
509
510 /*
511 * We're done reading, return.
512 */
513 if (slen == fr_bio_error(IO_WOULD_BLOCK)) return;
514
515 if (slen < 0) {
516 switch (errno) {
517 case ECONNREFUSED:
518 ERROR("%s - Failed reading response from socket: there is no server listening on outgoing connection %s",
519 h->ctx.module_name, h->ctx.fd_info->name);
520 break;
521
522 default:
523 ERROR("%s - Failed reading response from socket: %s",
524 h->ctx.module_name, fr_syserror(errno));
525 break;
526 }
527
528 failed:
530 return;
531 }
532
533 /*
534 * Where we just return in this function, we're letting
535 * the response timer take care of progressing the
536 * connection attempt.
537 */
538 fr_assert(slen >= RADIUS_HEADER_LENGTH); /* checked in verify */
539
540 if (!u->packet) {
541 ERROR("%s - Received response to expired status check packet",
542 h->ctx.module_name);
543 return;
544 }
545
546 /*
547 * Just manually do the Token checks for RADIUS/1.1.
548 */
549 if (h->radius_1_1) {
550 if (u->token != fr_nbo_to_uint32(h->buffer + 4)) {
551 ERROR("%s - Received response with incorrect or expired Token. Expected %u, got %u",
553 return;
554 }
555
556 } else if (u->id != h->buffer[1]) {
557 ERROR("%s - Received response with incorrect or expired ID. Expected %u, got %u",
558 h->ctx.module_name, u->id, h->buffer[1]);
559 return;
560 }
561
562 if (decode(h, &reply, &code,
564 h->buffer, slen) != FR_RADIUS_FAIL_NONE) {
566 return;
567 }
568
569 fr_pair_list_free(&reply); /* FIXME - Do something with these... */
570
571 /*
572 * Process the error, and count this as a success.
573 * This is usually used for dynamic configuration
574 * on startup.
575 */
577
578 /*
579 * Last trunk event was a failure, be more careful about
580 * bringing up the connection (require multiple responses).
581 */
582 if ((fr_time_gt(trunk->last_failed, fr_time_wrap(0)) && (fr_time_gt(trunk->last_failed, trunk->last_connected))) &&
583 (u->num_replies < inst->num_answers_to_alive)) {
584 /*
585 * Leave the timer in place. This timer is BOTH when we
586 * give up on the current status check, AND when we send
587 * the next status check.
588 */
589 DEBUG("%s - Received %u / %u replies for status check, on connection - %s",
590 h->ctx.module_name, u->num_replies, inst->num_answers_to_alive, h->ctx.fd_info->name);
591 DEBUG("%s - Next status check packet will be in %pVs",
593
594 /*
595 * Set the timer for the next retransmit.
596 */
597 if (fr_timer_at(h, h->tl, &u->ev, u->retry.next, false, conn_init_next, conn) < 0) {
599 }
600 return;
601 }
602
603 /*
604 * It's alive!
605 */
606 status_check_reset(h, u);
607
608 DEBUG("%s - Connection open - %s", h->ctx.module_name, h->ctx.fd_info->name);
609
611}
612
613/** Send initial negotiation.
614 *
615 */
616static void conn_init_writable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
617{
618 connection_t *conn = talloc_get_type_abort(uctx, connection_t);
619 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
620 bio_request_t *u = h->status_u;
621 ssize_t slen;
622
623 if (fr_time_eq(u->retry.start, fr_time_wrap(0))) {
624 u->token = fr_rand();
625 u->id = u->token & 0xff; /* We don't care what the value is here */
626 h->status_checking = true; /* Ensure this is valid */
628
629 /*
630 * Status checks can never be retransmitted
631 * So increment the ID here.
632 */
633 } else {
635 u->token++;
636 u->id = u->token & 0xff;
637 }
638
639 DEBUG("%s - Sending %s ID %d over connection %s",
641
642 if (encode(h, h->status_request, u, u->id) < 0) {
643 fail:
645 return;
646 }
647 DEBUG3("Encoded packet");
648 HEXDUMP3(u->packet, u->packet_len, NULL);
649
650 fr_assert(u->packet != NULL);
652
653 slen = fr_bio_write(h->bio.main, NULL, u->packet, u->packet_len);
654
655 if (slen == fr_bio_error(IO_WOULD_BLOCK)) goto blocked;
656
657 if (slen < 0) {
658 ERROR("%s - Failed sending %s ID %d length %zu over connection %s: %s",
660 goto fail;
661 }
662
663 /*
664 * @todo - handle partial packets and blocked writes.
665 */
666 if ((size_t)slen < u->packet_len) {
667 blocked:
668 ERROR("%s - Failed sending %s ID %d length %zu over connection %s: writing is blocked",
670 goto fail;
671 }
672
673 /*
674 * Switch to waiting on read and insert the event
675 * for the response timeout.
676 */
677 if (fr_event_fd_insert(h, NULL, conn->el, h->fd, conn_init_readable, NULL, conn_init_error, conn) < 0) {
678 PERROR("%s - Failed inserting FD event", h->ctx.module_name);
679 goto fail;
680 }
681
682 DEBUG("%s - %s request. Expecting response within %pVs",
683 h->ctx.module_name, (u->retry.count == 1) ? "Originated" : "Retransmitted",
685
686 if (fr_timer_at(h, h->tl, &u->ev, u->retry.next, false, conn_init_timeout, conn) < 0) {
687 PERROR("%s - Failed inserting timer event", h->ctx.module_name);
688 goto fail;
689 }
690}
691
692/** Pause the connection when a stream BIO is blocked on write
693 *
694 * @return
695 * - 1 for "writes are blocked".
696 */
698{
699 bio_handle_t *h = bio->uctx;
700
701 /*
702 * @todo - the FD BIO runs the write_blocked callbacks only when the FD BIO changes from "not
703 * blocked" to "blocked". If the FD BIO is already flagged as blocked, then a write which
704 * returns IO_WOULD_BLOCK doesn't run the callback, and h->write_blocked stays false. That
705 * shouldn't happen, but there's no test for it.
706 *
707 * The solution is likely to hoist the `write_blocked` flag into a public flag in fr_bio_t. That
708 * lets us get rid of `h->write_blocked`. i.e. having multiple different flags for the same
709 * state is a source of issues.
710 */
711 h->write_blocked = true;
712
713 /*
714 * The trunk has not started to use the connection, e.g. the TCP connect or the TLS handshake is
715 * still running. The BIOs track their own blocked state.
716 */
717 if (!h->tconn) return 1;
718
719 DEBUG("%s - Writing is blocked on connection %s", h->ctx.module_name, h->ctx.fd_info->name);
720
721 /*
722 * Don't requeue the pending requests at this point. Partial writes will be signaled once
723 * mod_write() checks the status of the connection.
724 */
726 thread_conn_notify(h->tconn, h->conn, h->conn->el, h->notify_on, NULL);
727
728 return 1;
729}
730
731/** Resume the connection when a stream BIO can write again.
732 *
733 * @return
734 * - 1 for "writes can resume".
735 */
737{
738 bio_handle_t *h = bio->uctx;
739
740 h->write_blocked = false;
741
742 if (!h->tconn) return 1;
743
744 DEBUG("%s - Writing is resumed on connection %s", h->ctx.module_name, h->ctx.fd_info->name);
745
747
748 /*
749 * bio_write_blocked() registered conn_writable_flush() as the write handler.
750 * The fd is almost always writable, so the handler would run in a loop. Register the events
751 * which the trunk wants.
752 */
753 thread_conn_notify(h->tconn, h->conn, h->conn->el, h->notify_on, NULL);
754
755 return 1;
756}
757
758#ifdef WITH_TLS
759/** Start the TLS connection
760 *
761 * The TLS bio needs to run the interpreter on the connection request. When the request is added to the
762 * worker, the worker runs the request function. Which is this one.
763
764 * fr_bio_tls_connect() runs the interpreter on the connection request. The interpreter asserts that the
765 * request is not in the runnable heap of the worker, and the worker adds a new request to the heap. The
766 * worker has therefore to run the request once, before the TLS connection can start. conn_request_hold() adds
767 * the timer which calls this function, and the timer runs only after the worker has finished with the request.
768 */
769static void conn_tls_start(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
770{
771 bio_handle_t *h = talloc_get_type_abort(uctx, bio_handle_t);
772 int rcode;
773
774 /*
775 * From fr_bio_tls_connect() until the "connected" callback, the TLS BIO owns the FD events. The
776 * fd bio connect and the TLS handshake both happen after fr_bio_tls_connect().
777 */
778 h->tls_starting = true;
779 rcode = fr_bio_tls_connect(h->bio.tls);
780 h->tls_starting = false;
781
782 if (rcode < 0) {
783 PERROR("%s - Failed starting the TLS connection", h->ctx.module_name);
785 }
786}
787
788/** Tell the handle that the worker freed the connection request
789 *
790 * The request outlives the handle, so the worker frees the tracker after the handle.
791 *
792 * The request associated witht the connection is detached, which means that the worker owns the request. The
793 * handle frees the request by cancelling it. However, when the server shuts down, the worker frees the
794 * request while the handle still exists. We therefore have to disassociate the pointers, otherwise the
795 * handle keeps a reference to the freed request, TLS BIO, and the timer.
796 */
797static inline void bio_handle_detach(bio_handle_t *h)
798{
799 if (h->p_self) *h->p_self = NULL;
800 h->p_self = NULL;
801}
802
803/** The worker freed the connection request, which also freed the TLS bio.
804 *
805 */
806static int _bio_handle_self_free(bio_handle_t **p_h)
807{
808 bio_handle_t *h = *p_h;
809
810 if (!h) return 0;
811
812 /*
813 * The timers use the TLS bio, which is gone.
814 */
815 FR_TIMER_DELETE(&h->tls_ev);
816 FR_TIMER_DELETE(&h->tls_failed_ev);
817
818 h->bio.tls = NULL;
819 h->conn_request = NULL;
820 h->p_self = NULL;
821
822 return 0;
823}
824
825/** The bottom frame of the connection request
826 *
827 * The worker runs a request which has no frames, and the interpreter asserts that the stack is not empty. This
828 * frame is the bottom of the stack. The TLS code pushes its own frame above this frame, once the TCP connection
829 * is open.
830 *
831 * The worker has finished with the request as soon as this frame yields. The function therefore asks for the
832 * TLS connection to start from an event, instead of starting the TLS connection here, as the TLS connection
833 * runs the interpreter on the request.
834 */
835static unlang_action_t conn_request_hold(UNUSED request_t *request, void *uctx)
836{
837 bio_handle_t *h = talloc_get_type_abort(uctx, bio_handle_t);
838
839 if (h->tls_started) return UNLANG_ACTION_YIELD;
840
841 h->tls_started = true;
842
843 if (fr_timer_in(h, h->tl, &h->tls_ev, fr_time_delta_wrap(0), false, conn_tls_start, h) < 0) {
844 PERROR("%s - Failed adding a timer to start the TLS connection", h->ctx.module_name);
846 }
847
848 return UNLANG_ACTION_YIELD;
849}
850
851/** Allocate the request that owns the TLS bio.
852 *
853 * The code in src/lib/tls uses a request to handle the BIO and the TLS handshake. The TLS handshake runs the
854 * various unlang sessions for `verify certificate`, etc.
855 *
856 * This request is only used to manage the TLS state machine. The status check request is needed for UDP,
857 * and is therefore independent.
858 *
859 * The request is detached, which allows it to be managed by the worker. When the request is cancelled, it's
860 * stack is unwound, and the request is freed. As a result, the request is not owned by the handle.
861 *
862 * @param[in] h the connection handle. The fd bio MUST be allocated.
863 * @return
864 * - 0 on success.
865 * - -1 on failure.
866 */
867static int conn_request_alloc(bio_handle_t *h)
868{
870 unlang_interpret_t *intp;
871 static uint64_t number = 0;
872
873 fr_assert(h->bio.fd);
874 fr_assert(!h->conn_request);
875
877 if (!intp) {
878 ERROR("%s - No interpreter for the TLS connection request", h->ctx.module_name);
879 return -1;
880 }
881
882 MEM(request = request_local_alloc_internal(intp, &(request_init_args_t) { .detachable = true }));
883
884 MEM(request->packet = fr_packet_alloc(request, false));
885 MEM(request->reply = fr_packet_alloc(request, false));
886
887 /*
888 * The home server is the destination. The socket names it in log messages and in the
889 * session-state list.
890 */
891 request->packet->socket = h->ctx.fd_info->socket;
892
893 request->number = number++;
895 MEM(request->name = talloc_typed_asprintf(request, "%s TLS %" PRIu64, h->ctx.module_name, request->number));
896
898
899 if (unlang_function_push(request, conn_request_hold, conn_request_hold, NULL, FR_SIGNAL_NONE,
901 fail:
903 return -1;
904 }
905
906 /*
907 * Push the request onto the interpreter "runnable" queue. The worker is now responsible for the
908 * request.
909 */
911
912 /*
913 * Remove the `max_request_time` timer, which is automatically added by the worker. Instead,
914 * the request lives as long as the connection is up. Which could be a long time.
915 *
916 * When the connection is closed, the request is freed.
917 */
918 TALLOC_FREE(request->timeout);
919
920 h->conn_request = request;
921
922 MEM(h->p_self = talloc_zero(request, bio_handle_t *));
923 *h->p_self = h;
924 talloc_set_destructor(h->p_self, _bio_handle_self_free);
925
926 return 0;
927}
928
929/** Callback to signal that the TLS connection is open.
930 *
931 */
932static void bio_tls_connected(fr_bio_t *bio)
933{
934 bio_handle_t *h = bio->uctx;
935 fr_tls_connection_t *tls_conn = fr_bio_tls_conn(h->bio.tls);
936
937 /*
938 * Now that TLS negotiation is finished, set the local RADIUS/1.1, and allocate the tracking
939 * structure which uses the RADIUS/1.1 Tokens.
940 */
941 if (tls_conn->tls_session->alpn_id == FR_RADIUS_ALPN_RADIUS_1_1) {
942 h->radius_1_1 = true;
944 }
945 MEM(h->tt = radius_track_alloc(h, h->radius_1_1));
946
947 /*
948 * If we're doing status checks, then we want at least one positive response before signalling
949 * that the connection is open. The status check code is the same as for a socket without TLS.
950 *
951 * Insert an FD event to read from the socket, because the TLS BIO deleted its own "connection
952 * setup" FD events before calling this function.
953 */
954 if (h->ctx.inst->status_check) {
955 DEBUG("%s - TLS handshake finished - %s", h->ctx.module_name, h->ctx.fd_info->name);
956
958
959 if (fr_event_fd_insert(h, NULL, h->conn->el, h->fd, NULL,
961 PERROR("%s - Failed inserting FD event", h->ctx.module_name);
963 }
964 return;
965 }
966
967 DEBUG("%s - TLS connection open - %s", h->ctx.module_name, h->ctx.fd_info->name);
968
970}
971
972/** Tell the connection that the TLS connection failed
973 *
974 * The timer runs bio_tls_failed() later, outside of the TLS code.
975 */
976static void conn_tls_failed(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
977{
978 bio_handle_t *h = talloc_get_type_abort(uctx, bio_handle_t);
979
981}
982
983/** Something in TLS failed.
984 *
985 * The TLS bio calls this function from inside of a read or a write. The TLS connection also calls this
986 * function from inside of the connection frame, which the worker runs for the connection request.
987 *
988 * Don't free the BIO, and don't signal the connection from here. Signalling the connection runs
989 * conn_close(), which frees the handle, the TLS bio, and the TLS connection, while the TLS code is still
990 * running and uses the TLS connection. Instead, run the signal from a timer. The timer is a
991 * child of the handle, so freeing the handle stops the timer.
992 *
993 * @todo - using a timer seems to be annoying and problematic. We need a better way.
994 */
995static void bio_tls_failed(fr_bio_t *bio)
996{
997 bio_handle_t *h = bio->uctx;
998 fr_tls_connection_t *tls_conn = fr_bio_tls_conn(h->bio.tls);
999
1000 if (tls_conn->failed == TLS_CONNECTION_FAIL_SYSCALL) {
1001 ERROR("%s - TLS connection failed - %s - %s", h->ctx.module_name, h->ctx.fd_info->name,
1002 fr_syserror(tls_conn->error));
1003 } else {
1004 ERROR("%s - TLS connection failed - %s - %s", h->ctx.module_name, h->ctx.fd_info->name,
1005 fr_table_str_by_value(fr_tls_connection_fail_table, tls_conn->failed, "<INVALID>"));
1006 }
1007
1008 /*
1009 * conn_init() is still running, and returns CONNECTION_STATE_FAILED when fr_bio_tls_connect()
1010 * fails. Signalling the connection from here would make the connection code handle the same
1011 * failure twice.
1012 */
1013 if (h->tls_starting) return;
1014
1015 if (fr_timer_armed(h->tls_failed_ev)) return;
1016
1017 if (fr_timer_in(h, h->tl, &h->tls_failed_ev, fr_time_delta_wrap(0), false, conn_tls_failed, h) < 0) {
1018 PERROR("%s - Failed adding a timer to signal the failed TLS connection", h->ctx.module_name);
1019
1020 /*
1021 * We have no other way to update the connection. A connection which never reconnects is worse
1022 * than the risk of this signal.
1023 */
1025 }
1026}
1027
1028/** Allocate the TLS bio
1029 *
1030 * @param[in] h the connection handle. The fd bio MUST be allocated.
1031 * @return
1032 * - 0 on success.
1033 * - -1 on failure.
1034 */
1035static int conn_tls_alloc(bio_handle_t *h)
1036{
1037 fr_tls_connection_t *tls_conn;
1038
1039 if (conn_request_alloc(h) < 0) return -1;
1040
1041 h->bio.tls = fr_bio_tls_alloc(h->conn_request, h->bio.fd, h->ctx.ssl_ctx, true, false);
1042 if (!h->bio.tls) {
1043 /*
1044 * _bio_handle_free() expects that a connection request has a TLS bio. Without a TLS bio
1045 * nothing owns the request, so cancel the request here. The worker unwinds and frees
1046 * the request.
1047 */
1048 bio_handle_detach(h);
1049 unlang_interpret_signal(h->conn_request, FR_SIGNAL_CANCEL);
1050 h->conn_request = NULL;
1051 return -1;
1052 }
1053
1054 ((fr_bio_t *) h->bio.tls)->uctx = h;
1056 .connected = bio_tls_connected,
1057 .failed = bio_tls_failed,
1058 });
1059
1060 tls_conn = fr_bio_tls_conn(h->bio.tls);
1061 tls_conn->name = talloc_typed_asprintf(tls_conn, "%s %s",
1062 (h->ctx.fd_config.socket_type == SOCK_DGRAM) ? "DTLS" : "TLS",
1063 h->ctx.fd_info->name);
1064
1065 return 0;
1066}
1067#endif
1068
1069/** Free a connection handle, closing associated resources
1070 *
1071 */
1073{
1074 fr_assert(h != NULL);
1075
1076 fr_assert(h->fd >= 0);
1077
1079
1080#ifdef WITH_TLS
1081 /*
1082 * Parenting goes "connection request" -> TLS bio -> TLS connection. The TLS BIO also points to
1083 * the FD BIO. The TLS bio MUST therefore be freed before the the FD bio.
1084 *
1085 * Freeing the TLS bio sends any TLS close_notify, deletes the fd events, and cancels the request.
1086 * The interpreter then cleans it up, and frees everything.
1087 *
1088 * If the handle is being freed, then cancel the request. The request is allocated from the
1089 * interpreter ctx. The worker will clean up the request after it's cancelled.
1090 */
1091 h->tconn = NULL;
1092
1093 if (h->conn_request) {
1094 fr_assert(h->bio.tls);
1095
1096 /*
1097 * Before closing, forcibly write a TLS close_notify. But first delete the FD events, so
1098 * if there are any errors writing to the socket (IO error, or IO_WOULD_BLOCK), those are
1099 * ignored, and the close_notify is discarded.
1100 */
1101 (void) fr_event_fd_delete(h->conn->el, h->fd, FR_EVENT_FILTER_IO);
1102 fr_bio_tls_close_send(h->bio.tls);
1103
1104 /*
1105 * We're about to free the handle, so but the BIO sticks around until the interpreter
1106 * unwinds the cancelled request. Remove the callbacks so that they don't try to access
1107 * the freed handle.
1108 */
1109 fr_bio_cb_set((fr_bio_t *) h->bio.tls, NULL);
1110
1111 bio_handle_detach(h);
1112
1113 unlang_interpret_signal(h->conn_request, FR_SIGNAL_CANCEL);
1114 h->bio.tls = NULL;
1115 h->conn_request = NULL;
1116 }
1117#endif
1118
1119 /*
1120 * The connection code will take care of deleting the FD from the event loop.
1121 */
1122
1123 DEBUG("%s - Connection closed - %s", h->ctx.module_name, h->ctx.fd_info->name);
1124
1125 return 0;
1126}
1127
1128/** Replication is write-only, so the socket never reads.
1129 *
1130 * A stream socket has to be connected before this function runs, as shutdown() on a socket which is not
1131 * connected fails with ENOTCONN.
1132 *
1133 * @return
1134 * - 0 on success, or when the module is not replicating.
1135 * - -1 on failure.
1136 */
1138{
1139 if ((h->ctx.inst->mode != RLM_RADIUS_MODE_REPLICATE) &&
1141
1143
1144 if (fr_bio_fd_write_only(h->bio.fd) < 0) {
1145 PERROR("%s - Failed setting socket to write-only", h->ctx.module_name);
1146 return -1;
1147 }
1148
1149 return 0;
1150}
1151
1152static void bio_connected(fr_bio_t *bio)
1153{
1154 bio_handle_t *h = bio->uctx;
1155
1156 if (conn_write_only(h) < 0) {
1158 return;
1159 }
1160
1161 DEBUG("%s - Connection open - %s", h->ctx.module_name, h->ctx.fd_info->name);
1162
1164}
1165
1166static void bio_error(fr_bio_t *bio)
1167{
1168 bio_handle_t *h = bio->uctx;
1169
1170 DEBUG("%s - Connection failed - %s - %s", h->ctx.module_name, h->ctx.fd_info->name,
1172
1174}
1175
1176/** The BIO chain is at EOF, and has no more data for us.
1177 *
1178 * For TLS, the peer sent us a close_notify alert. The fd BIO may not have seen EOF, as the peer can send
1179 * a close_notify and keep the TCP connection open.
1180 */
1181static void bio_eof(fr_bio_t *bio)
1182{
1183 bio_handle_t *h = bio->uctx;
1184
1185 h->eof = true;
1186}
1187
1188static fr_bio_verify_action_t rlm_radius_verify(UNUSED fr_bio_t *bio, void *verify_ctx, UNUSED void *packet_ctx, const void *data, size_t *size)
1189{
1191 size_t in_buffer = *size;
1192 bio_handle_t *h = verify_ctx;
1193 uint8_t const *hdr = data;
1194 size_t want;
1195
1196 if (in_buffer < 20) {
1197 *size = RADIUS_HEADER_LENGTH;
1199 }
1200
1201 /*
1202 * Packet is too large, discard it.
1203 */
1204 want = fr_nbo_to_uint16(hdr + 2);
1205 if (want > h->ctx.inst->max_packet_size) {
1206 ERROR("%s - Connection %s received too long packet", h->ctx.module_name, h->ctx.fd_info->name);
1208 }
1209
1210 /*
1211 * Not a full packet, we want more data.
1212 */
1213 if (want > *size) {
1214 *size = want;
1216 }
1217
1218#ifndef WITH_TLS
1219#define REQUIRE_MA(_h) (((_h)->ctx.inst->require_message_authenticator == FR_RADIUS_REQUIRE_MA_YES) || *(_h)->ctx.inst->received_message_authenticator)
1220#else
1221#define REQUIRE_MA(_h) (!(_h)->bio.tls && (((_h)->ctx.inst->require_message_authenticator == FR_RADIUS_REQUIRE_MA_YES) || *(_h)->ctx.inst->received_message_authenticator))
1222#endif
1223 /*
1224 * See if we need to discard the packet.
1225 *
1226 * @todo - rate limit these messages, and find a way to associate them with a request, or even
1227 * the logging destination of the module.
1228 */
1229 if (!fr_radius_ok(data, size, h->ctx.inst->max_attributes, REQUIRE_MA(h), h->radius_1_1, &failure)) {
1230 if (*size) return FR_BIO_VERIFY_DISCARD;
1231
1232 PERROR("%s - Connection %s received bad packet", h->ctx.module_name, h->ctx.fd_info->name);
1233
1234 if (failure == FR_RADIUS_FAIL_MA_MISSING) {
1236 ERROR("We are configured with 'require_message_authenticator = true'");
1237 } else {
1238 ERROR("We previously received a packet from this client which included a Message-Authenticator attribute");
1239 }
1240 }
1241
1242 if (h->ctx.fd_config.socket_type == SOCK_DGRAM) return FR_BIO_VERIFY_DISCARD;
1243
1245 }
1246
1247 /*
1248 * @todo - check if the reply is allowed. Bad replies are discarded later, but it might be worth
1249 * checking them here.
1250 */
1251
1252 /*
1253 * On input, *size is how much data we have. On output, *size is how much data we want.
1254 */
1255 return (in_buffer >= *size) ? FR_BIO_VERIFY_OK : FR_BIO_VERIFY_WANT_MORE;
1256}
1257
1258
1259/** Initialise a new outbound connection
1260 *
1261 * @param[out] h_out Where to write the new file descriptor.
1262 * @param[in] conn to initialise.
1263 * @param[in] uctx A #bio_handle_ctx_t
1264 */
1265CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
1266static connection_state_t conn_init(void **h_out, connection_t *conn, void *uctx)
1267{
1268 int fd;
1269 bio_handle_t *h;
1270 bio_handle_ctx_t *ctx = uctx; /* thread or home server */
1271 connection_t **to_save = NULL;
1272 fr_bio_t *next;
1273 size_t write_size;
1274
1275 MEM(h = talloc_zero(conn, bio_handle_t));
1276 h->ctx = *ctx;
1277 h->conn = conn;
1279
1280 MEM(h->tl = fr_timer_list_lst_alloc(h, h->ctx.el->tl));
1281
1282 MEM(h->buffer = talloc_array(h, uint8_t, h->max_packet_size));
1283 h->buflen = h->max_packet_size;
1284
1285 h->bio.fd = fr_bio_fd_alloc(h, &h->ctx.fd_config, 0);
1286 if (!h->bio.fd) {
1287 PERROR("%s - failed opening socket", h->ctx.module_name);
1288 fail:
1289 talloc_free(h);
1291 }
1292
1293 h->bio.fd->uctx = h;
1294 h->ctx.fd_info = fr_bio_fd_info(h->bio.fd);
1295
1296 fd = h->ctx.fd_info->socket.fd;
1297 fr_assert(fd >= 0);
1298
1299 /*
1300 * We are proxying to multiple home servers, but using a limited port range. We must track the
1301 * source port for each home server, so that conn_close() can mark the source port as unused.
1302 * fr_bio_fd_alloc() has picked the source port from the range, and has saved the port in the
1303 * fd_info.
1304 */
1305 switch (ctx->limit_source_ports) {
1306 case LIMIT_PORTS_NONE:
1307 break;
1308
1309 /*
1310 * Dynamic home servers store source port usage in the home_server_t
1311 */
1313 {
1314 home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
1315 int slot;
1316
1317 fr_assert(h->ctx.fd_info->socket.inet.src_port >= h->ctx.fd_config.src_port_start);
1318 fr_assert(h->ctx.fd_info->socket.inet.src_port <= h->ctx.fd_config.src_port_end);
1319
1320 slot = h->ctx.fd_info->socket.inet.src_port - h->ctx.fd_config.src_port_start;
1321 fr_assert(slot < home->num_ports);
1322
1323 if (home->connections[slot]) {
1324 ERROR("%s - Failed opening socket to home server %pV:%u - source port %u is already in use",
1326 h->ctx.fd_info->socket.inet.src_port);
1327 goto fail;
1328 }
1329
1330 to_save = &home->connections[slot];
1331 }
1332 break;
1333
1334 /*
1335 * Static home servers store source port usage in bio_thread_t
1336 */
1337 case LIMIT_PORTS_STATIC:
1338 {
1339 bio_thread_t *thread = talloc_get_type_abort(ctx, bio_thread_t);
1340 int slot;
1341
1342 fr_assert(h->ctx.fd_info->socket.inet.src_port >= h->ctx.fd_config.src_port_start);
1343 fr_assert(h->ctx.fd_info->socket.inet.src_port <= h->ctx.fd_config.src_port_end);
1344
1345 slot = h->ctx.fd_info->socket.inet.src_port - h->ctx.fd_config.src_port_start;
1346 fr_assert(slot < thread->num_ports);
1347
1348 if (thread->connections[slot]) {
1349 ERROR("%s - Failed opening socket to home server %pV:%u - source port %u is already in use",
1351 h->ctx.fd_info->socket.inet.src_port);
1352 goto fail;
1353 }
1354
1355 to_save = &thread->connections[slot];
1356 }
1357 break;
1358 }
1359
1360 /*
1361 * Set the destructor now, so that every failure below frees the TLS bio and the connection
1362 * request.
1363 */
1364 h->fd = fd;
1365 talloc_set_destructor(h, _bio_handle_free);
1366
1367 /*
1368 * Create a memory BIO for stream sockets. We want to return only complete packets, and not
1369 * partial packets.
1370 *
1371 * @todo - maybe we want to have a fr_bio_verify_t which is independent of fr_bio_mem_t. That
1372 * way we don't need a memory BIO for UDP sockets, but we can still add a verification layer for
1373 * UDP sockets?
1374 */
1375 next = h->bio.fd;
1376
1377#ifdef WITH_TLS
1378 /*
1379 * For TLS, the path goes mem -> TLS -> FD. The memory BIO sees the decrypted application data,
1380 * and can then run its validation callbacks.
1381 */
1382 if (h->ctx.ssl_ctx) {
1383 if (conn_tls_alloc(h) < 0) {
1384 PERROR("%s - Failed allocating the TLS bio", h->ctx.module_name);
1385 goto fail;
1386 }
1387
1388 next = (fr_bio_t *) h->bio.tls;
1389 } else
1390#endif
1391 /*
1392 * Always allocate the tracking table for bare TCP and UDP.
1393 */
1394 MEM(h->tt = radius_track_alloc(h, false));
1395
1396 /*
1397 * A plain stream socket can accept only part of a packet, so the memory BIO needs a write buffer to
1398 * keep the rest of the packet. conn_writable_flush() flushes the buffer. The TLS BIO keeps its own
1399 * pending data, so a TLS connection does not need a write buffer.
1400 */
1401 write_size = 0;
1402#ifdef WITH_TLS
1403 if (!h->bio.tls)
1404#endif
1405 if (h->ctx.fd_config.socket_type == SOCK_STREAM) write_size = h->ctx.inst->max_packet_size * 4;
1406
1407 h->bio.mem = fr_bio_mem_alloc(h, (h->ctx.fd_config.socket_type == SOCK_DGRAM) ? 0 : h->ctx.inst->max_packet_size * 4,
1408 write_size, next);
1409 if (!h->bio.mem) {
1410 PERROR("%s - Failed allocating memory buffer - ", h->ctx.module_name);
1411 goto fail;
1412 }
1413
1414 if (fr_bio_mem_set_verify(h->bio.mem, rlm_radius_verify, h, (h->ctx.fd_config.socket_type == SOCK_DGRAM)) < 0) {
1415 PERROR("%s - Failed setting validation callback - ", h->ctx.module_name);
1416 goto fail;
1417 }
1418
1419 /*
1420 * Set the BIO read function to be the memory BIO, which will then call the packet verification
1421 * routine.
1422 */
1423 h->bio.main = h->bio.mem;
1424 h->bio.mem->uctx = h;
1426 .eof = bio_eof,
1427 /*
1428 * Datagram sockets drop packets instead of blocking.
1429 */
1430 .write_blocked = (h->ctx.fd_config.socket_type == SOCK_STREAM) ? bio_write_blocked : NULL,
1431 });
1432
1433#ifdef WITH_TLS
1434 /*
1435 * The TLS BIO owns the FD events until the bio_tls_connected() is called.
1436 *
1437 * The fd bio connect and TLS handshakes all happen after fr_bio_tls_connect().
1438 */
1439 if (h->bio.tls) {
1440 /*
1441 * The connection request starts the TLS connection, see conn_request_hold().
1442 */
1443 *h_out = h;
1444
1445 if (to_save) *to_save = conn;
1446
1448 }
1449#endif
1450
1451 /*
1452 * Allocate the status check packet now, because a stream socket can be in the CONNECTING state.
1453 */
1455
1456 /*
1457 * If the socket isn't connected, then do that first.
1458 */
1460 int rcode;
1461
1463
1464 /*
1465 * We don't pass timeouts here because the trunk has it's own connection timeouts.
1466 */
1467 rcode = fr_bio_fd_connect_full(h->bio.fd, conn->el, bio_connected, bio_error, NULL, NULL);
1468 if (rcode < 0) goto fail;
1469
1470 if (rcode == 0) {
1471 *h_out = h;
1473 }
1474
1475 fr_assert(rcode == 1);
1476
1477 /*
1478 * Don't return 'h' to the caller when we free it.
1479 */
1480 if (conn_write_only(h) < 0) goto fail;
1481
1482 *h_out = h;
1483
1484 DEBUG("%s - Connection open - %s", h->ctx.module_name, h->ctx.fd_info->name);
1485
1487 }
1488
1489 /*
1490 * The socket is connected.
1491 */
1492 if (conn_write_only(h) < 0) goto fail;
1493
1494 /*
1495 * If we're doing status checks, then we want at least
1496 * one positive response before signalling that the
1497 * connection is open.
1498 *
1499 * To do this we install special I/O handlers that
1500 * only signal the connection as open once we get a
1501 * status-check response.
1502 */
1503 if (h->ctx.inst->status_check) {
1504 /*
1505 * Start status checking.
1506 *
1507 * If we've had no recent failures we need exactly
1508 * one response to bring the connection online,
1509 * otherwise we need inst->num_answers_to_alive
1510 */
1511 if (fr_event_fd_insert(h, NULL, conn->el, h->fd, NULL,
1512 conn_init_writable, conn_init_error, conn) < 0) goto fail;
1513
1514 /*
1515 * If we're not doing status-checks, signal the connection
1516 * as open as soon as it becomes writable.
1517 */
1518 } else {
1519 DEBUG("%s - Connection open - %s", h->ctx.module_name, h->ctx.fd_info->name);
1520 connection_signal_on_fd(conn, fd);
1521 }
1522
1523 *h_out = h;
1524
1525 if (to_save) *to_save = conn;
1526
1528}
1529
1530/** Shutdown/close a file descriptor
1531 *
1532 */
1533static void conn_close(UNUSED fr_event_list_t *el, void *handle, void *uctx)
1534{
1535 bio_handle_t *h = talloc_get_type_abort(handle, bio_handle_t);
1536
1537 /*
1538 * There's tracking entries still allocated
1539 * this is bad, they should have all been
1540 * released.
1541 */
1542 if (h->tt && (h->tt->num_requests != 0)) {
1543#ifndef NDEBUG
1545#endif
1546 fr_assert_fail("%u tracking entries still allocated at conn close", h->tt->num_requests);
1547 }
1548
1549 /*
1550 * We have opened a limited number of outbound source ports. This means that when we close a
1551 * port, we have to mark it unused.
1552 */
1553 switch (h->ctx.limit_source_ports) {
1554 case LIMIT_PORTS_NONE:
1555 break;
1556
1558 {
1559 int offset;
1560 home_server_t *home = talloc_get_type_abort(uctx, home_server_t);
1561
1562 fr_assert(h->ctx.fd_info->socket.inet.src_port >= h->ctx.fd_config.src_port_start);
1563 fr_assert(h->ctx.fd_info->socket.inet.src_port <= h->ctx.fd_config.src_port_end);
1564
1565 offset = h->ctx.fd_info->socket.inet.src_port - h->ctx.fd_config.src_port_start;
1566 fr_assert(offset < home->num_ports);
1567
1568 fr_assert(home->connections[offset] == h->conn);
1569
1570 home->connections[offset] = NULL;
1571 }
1572 break;
1573
1574 case LIMIT_PORTS_STATIC:
1575 {
1576 int offset;
1577 bio_thread_t *thread = talloc_get_type_abort(uctx, bio_thread_t);
1578
1579 fr_assert(h->ctx.fd_info->socket.inet.src_port >= h->ctx.fd_config.src_port_start);
1580 fr_assert(h->ctx.fd_info->socket.inet.src_port <= h->ctx.fd_config.src_port_end);
1581
1582 offset = h->ctx.fd_info->socket.inet.src_port - h->ctx.fd_config.src_port_start;
1583 fr_assert(offset < thread->num_ports);
1584
1585 fr_assert(thread->connections[offset] == h->conn);
1586
1587 thread->connections[offset] = NULL;
1588 }
1589 break;
1590 }
1591
1592 DEBUG4("Freeing handle %p", handle);
1593
1594 talloc_free(h);
1595}
1596
1597/** Connection failed
1598 *
1599 * @param[in] handle of connection that failed.
1600 * @param[in] state the connection was in when it failed.
1601 * @param[in] uctx UNUSED.
1602 */
1603static connection_state_t conn_failed(void *handle, connection_state_t state, UNUSED void *uctx)
1604{
1605 switch (state) {
1606 /*
1607 * If the connection was connected when it failed,
1608 * we need to handle any outstanding packets and
1609 * timer events before reconnecting.
1610 */
1612 {
1613 bio_handle_t *h = talloc_get_type_abort(handle, bio_handle_t); /* h only available if connected */
1614
1615 /*
1616 * Reset the Status-Server checks.
1617 */
1618 if (h->status_u) FR_TIMER_DISARM(h->status_u->ev);
1619 break;
1620
1621 default:
1622 break;
1623 }
1624 }
1625
1626 return CONNECTION_STATE_INIT;
1627}
1628
1629CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
1631 connection_conf_t const *conf,
1632 char const *log_prefix, void *uctx)
1633{
1634 connection_t *conn;
1635 bio_handle_ctx_t *ctx = uctx; /* thread or home server */
1636
1637 conn = connection_alloc(tconn, el,
1639 .init = conn_init,
1640 .close = conn_close,
1641 .failed = conn_failed
1642 },
1643 conf,
1644 log_prefix,
1645 uctx);
1646 if (!conn) {
1647 PERROR("%s - Failed allocating state handler for new connection", ctx->inst->name);
1648 return NULL;
1649 }
1650 ctx->trunk = tconn->trunk;
1651 ctx->module_name = log_prefix;
1652
1653 return conn;
1654}
1655
1656/** Read and discard data
1657 *
1658 */
1659static void conn_discard(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
1660{
1661 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
1662 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
1663 uint8_t buffer[4096];
1664 ssize_t slen;
1665
1666 while ((slen = fr_bio_read(h->bio.main, NULL, buffer, sizeof(buffer))) > 0);
1667
1668 if (slen < 0) {
1669 switch (errno) {
1670 case EBADF:
1671 case ECONNRESET:
1672 case ENOTCONN:
1673 case ETIMEDOUT:
1674 ERROR("%s - Failed draining socket: %s", h->ctx.module_name, fr_syserror(errno));
1676 break;
1677
1678 default:
1679 break;
1680 }
1681 }
1682}
1683
1684/** Connection errored
1685 *
1686 * We were signalled by the event loop that a fatal error occurred on this connection.
1687 *
1688 * @param[in] el The event list signalling.
1689 * @param[in] fd that errored.
1690 * @param[in] flags El flags.
1691 * @param[in] fd_errno The nature of the error.
1692 * @param[in] uctx The trunk connection handle (tconn).
1693 */
1694static void conn_error(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, void *uctx)
1695{
1696 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
1697 connection_t *conn = tconn->conn;
1698 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
1699
1700 if (fd_errno) ERROR("%s - Connection %s failed: %s", h->ctx.module_name, h->ctx.fd_info->name, fr_syserror(fd_errno));
1701
1703}
1704
1705/** The fd is writable, and the connection is blocked on write
1706 *
1707 */
1708CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
1709static void conn_writable_flush(fr_event_list_t *el, int fd, int flags, void *uctx)
1710{
1711 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
1712 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
1713 ssize_t slen;
1714
1715 /*
1716 * Write "no packet" with a size, which signals the BIOs to flush their buffers.
1717 *
1718 * The write returns the actual amount of data which was flushed, even though we don't care about
1719 * that. All we care is that _some_ data was written on success. If only partial data is
1720 * written, then the BIO returns "would block".
1721 */
1722 slen = fr_bio_write(h->bio.main, NULL, NULL, SIZE_MAX);
1723 if (slen == fr_bio_error(IO_WOULD_BLOCK)) return;
1724
1725 if (slen < 0) {
1726 ERROR("%s - Failed writing pending data on connection %s: %s", h->ctx.module_name,
1727 h->ctx.fd_info->name, fr_strerror());
1729 return;
1730 }
1731
1732 bio_write_resume(h->bio.main);
1733
1734 trunk_connection_callback_writable(el, fd, flags, uctx);
1735}
1736
1737CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
1740 trunk_connection_event_t notify_on, UNUSED void *uctx)
1741{
1742 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
1743 fr_event_fd_cb_t read_fn = NULL;
1744 fr_event_fd_cb_t write_fn = NULL;
1745
1746 h->tconn = tconn;
1747 h->notify_on = notify_on;
1748
1749 switch (notify_on) {
1750 /*
1751 * We may have sent multiple requests to the
1752 * other end, so it might be sending us multiple
1753 * replies. We want to drain the socket, instead
1754 * of letting the packets sit in the UDP receive
1755 * queue.
1756 */
1758 read_fn = conn_discard;
1759 break;
1760
1763 break;
1764
1767 break;
1768
1772 break;
1773
1774 }
1775
1776 /*
1777 * A blocked connection has data which has to reach the fd before the trunk code writes packets.
1778 */
1779 if (h->write_blocked) write_fn = conn_writable_flush;
1780
1781 /*
1782 * Over-ride read for replication.
1783 */
1785 if (read_fn) read_fn = conn_discard;
1786 }
1787
1788 if (fr_event_fd_insert(h, NULL, el, h->fd,
1789 read_fn,
1790 write_fn,
1791 conn_error,
1792 tconn) < 0) {
1793 PERROR("%s - Failed inserting FD event", h->ctx.module_name);
1794
1795 /*
1796 * May free the connection!
1797 */
1799 }
1800}
1801
1802/*
1803 * Return negative numbers to put 'a' at the top of the heap.
1804 * Return positive numbers to put 'b' at the top of the heap.
1805 *
1806 * We want the value with the lowest timestamp to be prioritized at
1807 * the top of the heap.
1808 */
1809static fr_cmp_ret_t request_prioritise(void const *one, void const *two)
1810{
1811 bio_request_t const *a = one;
1812 bio_request_t const *b = two;
1813 fr_cmp_ret_t ret;
1814
1815 /*
1816 * Prioritise status check packets
1817 */
1819 if (ret != 0) return ret;
1820
1821 /*
1822 * Larger priority is more important.
1823 */
1824 ret = CMP_PREFER_LARGER(a->priority, b->priority);
1825 if (ret != 0) return ret;
1826
1827 /*
1828 * Smaller timestamp (i.e. earlier) is more important.
1829 */
1830 return fr_time_cmp(a->recv_time, b->recv_time);
1831}
1832
1833/** Decode response packet data, extracting relevant information and validating the packet
1834 *
1835 * @param[in] ctx to allocate pairs in.
1836 * @param[out] reply Pointer to head of pair list to add reply attributes to.
1837 * @param[out] response_code The type of response packet.
1838 * @param[in] h connection handle.
1839 * @param[in] request the request.
1840 * @param[in] u UDP request.
1841 * @param[in] request_authenticator from the original request.
1842 * @param[in] data to decode.
1843 * @param[in] data_len Length of input data.
1844 * @return
1845 * - FR_RADIUS_FAIL_NONE on success.
1846 * - FR_RADIUS_FAIL_* on failure.
1847 */
1848static fr_radius_decode_fail_t decode(TALLOC_CTX *ctx, fr_pair_list_t *reply, uint8_t *response_code,
1850 uint8_t const request_authenticator[static RADIUS_AUTH_VECTOR_LENGTH],
1851 uint8_t *data, size_t data_len)
1852{
1854 uint8_t code;
1855 fr_radius_decode_ctx_t decode_ctx;
1856
1857 *response_code = 0; /* Initialise to keep the rest of the code happy */
1858
1859 RHEXDUMP3(data, data_len, "Read packet");
1860
1861 decode_ctx = (fr_radius_decode_ctx_t) {
1862 .common = &h->ctx.radius_ctx,
1863 .request_code = u->code,
1864 .request_authenticator = request_authenticator,
1865 .tmp_ctx = talloc(ctx, uint8_t),
1866 .end = data + data_len,
1867 .verify = true,
1868 .require_message_authenticator = REQUIRE_MA(h),
1869 .radius_1_1 = h->radius_1_1,
1870 };
1871
1872 if (fr_radius_decode(ctx, reply, data, data_len, &decode_ctx) < 0) {
1873 talloc_free(decode_ctx.tmp_ctx);
1874 RPEDEBUG("Failed reading packet");
1875 return decode_ctx.reason;
1876 }
1877 talloc_free(decode_ctx.tmp_ctx);
1878
1879 code = data[0];
1880
1881 RDEBUG("Received %s ID %d length %zu reply packet on connection %s",
1882 fr_radius_packet_name[code], data[1], data_len, h->ctx.fd_info->name);
1884
1885 /*
1886 * This code is for BlastRADIUS mitigation.
1887 *
1888 * The scenario where this applies is where we send Message-Authenticator
1889 * but the home server doesn't support it or require it, in which case
1890 * the response can be manipulated by an attacker.
1891 */
1892 if ((u->code == FR_RADIUS_CODE_ACCESS_REQUEST) &&
1893#ifdef WITH_TLS
1894 !h->bio.tls &&
1895#endif
1896
1897 (inst->require_message_authenticator == FR_RADIUS_REQUIRE_MA_AUTO) &&
1898 !*(inst->received_message_authenticator) &&
1901 RINFO("Packet contained a valid Message-Authenticator. Setting \"require_message_authenticator = yes\"");
1902 *(inst->received_message_authenticator) = true;
1903 }
1904
1905 *response_code = code;
1906
1907 /*
1908 * Record the fact we've seen a response
1909 */
1910 u->num_replies++;
1911
1912 /*
1913 * Fixup retry times
1914 */
1915 if (fr_time_gt(u->retry.start, h->tconn->mrs_time)) h->tconn->mrs_time = u->retry.start;
1916
1917 /*
1918 * Sample the round trip time from the start of the retransmission timer to the reply.
1919 */
1920 if (!u->status_check && (inst->mode != RLM_RADIUS_MODE_REPLICATE)) {
1922 }
1923
1924 return FR_RADIUS_FAIL_NONE;
1925}
1926
1928{
1929 ssize_t packet_len;
1931 rlm_radius_t const *inst = h->ctx.inst;
1932
1933 fr_assert(inst->allowed[u->code]);
1934 fr_assert(!u->packet);
1935
1936 u->packet_len = inst->max_packet_size;
1937 u->packet = h->buffer;
1938
1939 /*
1940 * We should have at minimum 64-byte packets, so don't
1941 * bother doing run-time checks here.
1942 */
1944
1946 .common = &h->ctx.radius_ctx,
1947 .rand_ctx = (fr_fast_rand_t) {
1948 .a = fr_rand(),
1949 .b = fr_rand(),
1950 },
1951 .code = u->code,
1952 .id = id,
1953 .token = u->token,
1954 .radius_1_1 = h->radius_1_1,
1955 .add_proxy_state = u->proxied,
1956 };
1957
1958 /*
1959 * RADIUS/1.1 needs a secure transport.
1960 */
1962
1963 /*
1964 * If we're sending a status check packet, update any
1965 * necessary timestamps. Also, don't add Proxy-State, as
1966 * we're originating the packet.
1967 */
1968 if (u->status_check) {
1969 fr_pair_t *vp;
1970
1971 vp = fr_pair_find_by_da(&request->request_pairs, NULL, attr_event_timestamp);
1972 if (vp) vp->vp_date = fr_time_to_unix_time(u->retry.updated);
1973
1974 encode_ctx.add_proxy_state = false;
1975 }
1976
1977 /*
1978 * Encode it, leaving room for Proxy-State if necessary.
1979 */
1980 packet_len = fr_radius_encode(&FR_DBUFF_TMP(u->packet, u->packet_len),
1981 &request->request_pairs, &encode_ctx);
1982 if (packet_len < 0) {
1983 RPERROR("Failed encoding packet");
1984 u->packet = NULL;
1985 return -1;
1986 }
1987
1988 /*
1989 * The encoded packet should NOT over-run the input buffer.
1990 */
1991 fr_assert((size_t) packet_len <= u->packet_len);
1992
1993 /*
1994 * Add Proxy-State to the "extra" list. It has been added
1995 * to the encoded packet by `fr_radius_encode`.
1996 *
1997 * We need to add it here, and NOT in
1998 * request->request_pairs, because multiple modules
1999 * may be sending the packets at the same time.
2000 */
2001 if (encode_ctx.add_proxy_state) {
2002 fr_pair_t *vp;
2003
2005 fr_pair_value_memdup(vp, (uint8_t const *) &inst->common_ctx.proxy_state, sizeof(inst->common_ctx.proxy_state), false);
2006 fr_pair_append(&u->extra, vp);
2007 }
2008
2009 /*
2010 * Update our version of the packet length.
2011 */
2012 u->packet_len = packet_len;
2013
2014 /*
2015 * Now that we're done mangling the packet, sign it. RADIUS/1.1 packets are not signed.
2016 */
2017 if (!h->radius_1_1 &&
2018 (fr_radius_sign(u->packet, NULL, (uint8_t const *) h->ctx.radius_ctx.secret,
2019 h->ctx.radius_ctx.secret_length) < 0)) {
2020 RPERROR("Failed signing packet");
2021 u->packet = NULL;
2022 return -1;
2023 }
2024
2025 MEM(u->packet = talloc_memdup(u, h->buffer, packet_len));
2026
2027 return 0;
2028}
2029
2030
2031/** Revive a connection after "revive_interval"
2032 *
2033 */
2034static void revive_timeout(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
2035{
2036 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
2037 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2038
2039 INFO("%s - Reviving connection %s", h->ctx.module_name, h->ctx.fd_info->name);
2041}
2042
2043/** Mark a connection dead after "zombie_interval"
2044 *
2045 */
2046static void zombie_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
2047{
2048 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
2049 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2050
2051 /*
2052 * check_for_zombie() sets the timer only when there are no status checks.
2053 */
2055
2056 INFO("%s - No replies during 'zombie_period', marking connection %s as dead", h->ctx.module_name, h->ctx.fd_info->name);
2057
2058 /*
2059 * Don't use this connection, and re-queue its requests onto other connections.
2060 *
2061 * RFC 6613 Section 2.6.1 forbids retransmitting a request over a different TCP connection while the
2062 * first connection is open. So for stream sockets, we only requeue pending packets.
2063 */
2065 (h->ctx.fd_config.socket_type == SOCK_STREAM) ?
2067
2068 if (!h->ctx.dynamic) {
2069 /*
2070 * Force the instruction to immediately fail until the revive interval has expired.
2071 *
2072 * We use the main interpreter event loop here, so that the timer outlives the connection.
2073 */
2074 unlang_interpret_force_result(h->instruction, &(unlang_result_t){.rcode = RLM_MODULE_FAIL},
2075 h->ctx.el->tl,
2077
2078 /*
2079 * Mark the connection as active, so when the module forced result times out, the
2080 * requests will be sent again. Also reset `first_unanswered`, otherwise one lost
2081 * request after `revive_interval` would mark the connection as zombie again.
2082 */
2085 return;
2086 }
2087
2088 /*
2089 * Revive the connection after a time.
2090 */
2091 if (fr_timer_at(h, h->tl, &h->zombie_ev,
2092 fr_time_add(now, h->ctx.inst->revive_interval), false,
2093 revive_timeout, tconn) < 0) {
2094 ERROR("Failed inserting revive timeout for connection");
2096 }
2097}
2098
2099
2100static void status_check_enqueue(trunk_connection_t *tconn, bio_handle_t *h, bool init);
2101
2102/** We timed out, without getting a status check reply.
2103 *
2104 */
2105static void status_check_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
2106{
2107 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
2108 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2109 bio_request_t *u = h->status_u;
2110
2111 if (h->ctx.fd_info->state != FR_BIO_FD_STATE_OPEN) return;
2112
2113 /*
2114 * Remove the status check which got no reply. Freeing the old request also releases the ID.
2115 */
2116 if (u->treq) {
2118 u->treq = NULL;
2119 }
2120
2121 /*
2122 * We are only interested in contiguous, good, replies.
2123 */
2124 u->num_replies = 0;
2125
2126 switch (fr_retry_next(&u->retry, now)) {
2127 case FR_RETRY_MRD:
2128 DEBUG("%s - Reached maximum_retransmit_duration (%pVs > %pVs), failing status checks",
2132 return;
2133
2134 case FR_RETRY_MRC:
2135 DEBUG("%s - Reached maximum_retransmit_count (%u > %u), failing status checks",
2136 h->ctx.module_name, u->retry.count, u->retry.config->mrc);
2138 return;
2139
2140 case FR_RETRY_CONTINUE:
2141 status_check_enqueue(tconn, h, false);
2142 return;
2143 }
2144
2145 fr_assert(0);
2146}
2147
2148
2149/** Queue a status check packet on an open connection, and wait for the reply
2150 *
2151 * The caller has already set up the retry state of the status check. The timer runs when the
2152 * status check gets no reply before u->retry.next.
2153 */
2155{
2156 bio_request_t *u = h->status_u;
2157
2158 u->treq = NULL;
2159
2161
2162 /*
2163 * Queue up the status check packet. It will be sent when the connection is writable.
2164 */
2165 if (trunk_request_enqueue_on_conn(&u->treq, tconn, h->status_request, u, u, true) != TRUNK_ENQUEUE_OK) {
2167 return;
2168 }
2169
2170 if (fr_timer_at(h, h->tl, &u->ev, u->retry.next, false, status_check_timeout, tconn) < 0) {
2172 }
2173}
2174
2175/** Decide whether a request timeout marks the connection as zombie
2176 *
2177 * This function is called by do_retry() when a request reaches `max_rtx_duration` or `max_rtx_count`. That
2178 * call is skipped when:
2179 *
2180 * 1. The request has no connection.
2181 * 2. The module is in replicate mode.
2182 * 3. The request is not in the `TRUNK_REQUEST_STATE_SENT` state.
2183 *
2184 * In the third case, the home server had no chance to reply, because the module did not write the
2185 * whole packet.
2186 *
2187 * The connection becomes zombie only when all of the following conditions are true:
2188 *
2189 * 1. The connection is open. A connection that is connecting or closing cannot send or receive
2190 * status checks.
2191 * 2. The connection has not received a valid reply since the request was first sent.
2192 * 3. A run of unanswered requests exists, *and* the run started at least `zombie_period` ago.
2193 * 4. At least `response_timeouts` requests in a row have timed out, without receiving a reply between the
2194 * timeouts.
2195 *
2196 * An open connection that is already zombie, or that is running status checks, stays zombie.
2197 *
2198 * When the connection becomes zombie, teh connectin is marked as inactive.
2199 *
2200 * The value of `status_check` decides how the zombie state ends:
2201 *
2202 * - With `status_check = no`, a timer is started with `zombie_period`. When the timer fires,
2203 * `zombie_timeout()` marks the connection as dead. As noted above, receiving a reply during this period
2204 * marks the connection as `alive` again.
2205 * - With `status_check = yes`, the function queues a status check on the connection. The connection leaves
2206 * the zombie state after `num_answers_to_alive` replies. If a status check reaches `max_rtx_duration` or
2207 * `max_rtx_count`, the connection is dead, and is reconnected.
2208 *
2209 * @param[in] request the request that timed out. The function reads the unlang instruction from the
2210 * request when `status_check = no`.
2211 * @param[in] tconn the trunk connection to check.
2212 * @param[in] now the current time, or zero if the function must read the clock.
2213 * @param[in] last_sent when the request was first sent (`retry->start`). This is not the time of the
2214 * last write in `h->last_sent`.
2215 * @return
2216 * - true if the connection is zombie.
2217 * - false if the connection is not zombie.
2218 */
2220{
2221 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2222 /*
2223 * We're replicating, and don't care about the health of
2224 * the home server, and this function should not be called.
2225 */
2227
2228 /*
2229 * Only an open connection can become zombie. A connection which is connecting or closing
2230 * cannot send or receive the status checks, and the zombie timer would run on a connection
2231 * which is about to be freed.
2232 */
2233 if (h->ctx.fd_info->state != FR_BIO_FD_STATE_OPEN) return false;
2234
2235 /*
2236 * If we're status checking OR already zombie, don't go to zombie
2237 */
2238 if (h->status_checking || fr_timer_armed(h->zombie_ev)) return true;
2239
2240 if (fr_time_eq(now, fr_time_wrap(0))) now = fr_time();
2241
2242 /*
2243 * We received a reply since this packet was sent, the connection isn't zombie.
2244 *
2245 * Or, there was no unanswered request, the connection isn't zombie.
2246 *
2247 * Or, the run of unanswered requests didn't reach zombie_period, the connection isn't zombie.
2248 */
2249 if (fr_time_gteq(h->last_reply, last_sent)) return false;
2250
2251 /*
2252 * Count every timeout which has no reply since the request was sent. The counter is not reset
2253 * when the connection goes idle, because the last request to time out makes the connection idle.
2254 */
2255 h->timeouts++;
2256
2257 if (fr_time_eq(h->first_unanswered, fr_time_wrap(0))) return false;
2258
2259 if (fr_time_gt(fr_time_add(h->first_unanswered, h->ctx.inst->zombie_period), now)) return false;
2260
2261 /*
2262 * The home server has to miss "response_timeouts" requests in a row.
2263 */
2264 if (h->timeouts < h->ctx.inst->response_timeouts) return false;
2265
2266 h->timeouts = 0;
2267
2268 /*
2269 * Stop using it for new requests.
2270 */
2271 WARN("%s - Entering Zombie state - connection %s", h->ctx.module_name, h->ctx.fd_info->name);
2273
2274 if (h->ctx.inst->status_check) {
2275 h->status_checking = true;
2276
2277 /*
2278 * Queue up the status check packet. It will be sent
2279 * when the connection is writable.
2280 */
2281 status_check_enqueue(tconn, h, true);
2282 } else {
2283 /*
2284 * Capture the instruction which started the zombie period.
2285 */
2287
2288 if (fr_timer_at(h, h->tl, &h->zombie_ev, fr_time_add(now, h->ctx.inst->zombie_period),
2289 false, zombie_timeout, tconn) < 0) {
2290 ERROR("Failed inserting zombie timeout for connection");
2292 }
2293 }
2294
2295 return true;
2296}
2297
2299{
2300 bio_handle_t *h;
2301
2302 if (!u->treq) {
2303 RDEBUG("Request is queued and waiting for a connection - suppressing retransmission");
2304 return;
2305 }
2306
2307 /*
2308 * Only a request which was written to the connection can be retransmitted. A request in the
2309 * backlog has no connection, and request_mux() writes the other requests.
2310 */
2311 if (u->treq->state != TRUNK_REQUEST_STATE_SENT) {
2312 RDEBUG("Request has not been sent - suppressing retransmission");
2313 return;
2314 }
2315
2316 h = talloc_get_type_abort(u->treq->tconn->conn->h, bio_handle_t);
2317
2318 if (h->ctx.fd_config.socket_type != SOCK_DGRAM) {
2319 RDEBUG("Using stream sockets - suppressing retransmission");
2320 return;
2321 }
2322
2323 /*
2324 * Arguably this should never happen for UDP sockets.
2325 */
2326 if (h->ctx.fd_info->write_blocked) {
2327 RDEBUG("IO is blocked - suppressing retransmission");
2328 return;
2329 }
2330
2331 /*
2332 * We are doing synchronous proxying, retransmit
2333 * the current request on the same connection.
2334 *
2335 * If it's zombie, we still resend it. If the
2336 * connection is dead, then a callback will move
2337 * this request to a new connection.
2338 */
2339 mod_write(request, u->treq, h);
2340}
2341
2342static void do_retry(rlm_radius_t const *inst, bio_request_t *u, request_t *request, fr_retry_t const *retry);
2343
2344/** Handle module retries.
2345 *
2346 */
2347static void mod_retry(module_ctx_t const *mctx, request_t *request, fr_retry_t const *retry)
2348{
2349 bio_request_t *u = talloc_get_type_abort(mctx->rctx, bio_request_t);
2350 rlm_radius_t const *inst = talloc_get_type_abort(mctx->mi->data, rlm_radius_t);
2351
2352 do_retry(inst, u, request, retry);
2353}
2354
2355static void do_retry(rlm_radius_t const *inst, bio_request_t *u, request_t *request, fr_retry_t const *retry)
2356{
2357 trunk_request_t *treq;
2358 trunk_connection_t *tconn;
2359 fr_time_t now;
2360 bool was_sent;
2361
2362 if (!u->treq) {
2363 RDEBUG("Packet was cancelled by the connection handler - ignoring retry");
2364 return;
2365 }
2366
2367 treq = talloc_get_type_abort(u->treq, trunk_request_t);
2368
2369 fr_assert(request == treq->request);
2370 fr_assert(treq->preq); /* Must still have a protocol request */
2371 fr_assert(treq->preq == u);
2372
2373 tconn = treq->tconn;
2374 now = retry->updated;
2375
2376 switch (retry->state) {
2377 case FR_RETRY_CONTINUE:
2378 u->retry = *retry;
2379
2380 switch (treq->state) {
2383 fr_assert(0);
2384 break;
2385
2387 RDEBUG("Packet is still in the backlog queue to be sent - suppressing retransmission");
2388 return;
2389
2391 RDEBUG("Packet is still in the pending queue to be sent - suppressing retransmission");
2392 return;
2393
2395 RDEBUG("Packet was partially written, as IO is blocked - suppressing retransmission");
2396 return;
2397
2399 fr_assert(tconn);
2400
2401 mod_dup(request, u);
2402 return;
2403
2411 fr_assert(0);
2412 break;
2413 }
2414 break;
2415
2416 case FR_RETRY_MRD:
2417 REDEBUG("Reached maximum_retransmit_duration (%pVs > %pVs), failing request",
2419 break;
2420
2421 case FR_RETRY_MRC:
2422 REDEBUG("Reached maximum_retransmit_count (%u > %u), failing request",
2423 retry->count, retry->config->mrc);
2424 break;
2425 }
2426
2428
2429 /*
2430 * The state has to be read before trunk_request_signal_fail() changes it.
2431 */
2432 was_sent = (treq->state == TRUNK_REQUEST_STATE_SENT);
2433
2435
2436 /*
2437 * We don't do zombie stuff!
2438 */
2439 if (!tconn || (inst->mode == RLM_RADIUS_MODE_REPLICATE)) return;
2440
2441 /*
2442 * If we didn't do a full write, then the home server
2443 * isn't down, and we don't do the zombie checks.
2444 */
2445 if (!was_sent) return;
2446
2447 /*
2448 * Sample the round trip time from the start of the retransmission timer to the timeout.
2449 * The request is not a status check, because status checks do not use do_retry().
2450 */
2451 fr_rtt_update(&tconn->rtt, fr_time_sub(now, retry->start));
2452
2453 check_for_zombie(request, tconn, now, retry->start);
2454}
2455
2456/** Requeue packets if the connection is blocked on write.
2457 *
2458 * bio_write_blocked() makes the connection inactive, and this function moves pending (but unwritten) requests
2459 * out of the queue, to other connections.
2460 *
2461 * Requests in the partial state stay on this connection.
2462 *
2463 * Requests in the sent state stay on this connection, because they're waiting for a response.
2464 *
2465 * @param[in] tconn the trunk connection which was just written to.
2466 */
2468{
2469 bio_handle_t *h;
2470 uint64_t moved;
2471
2472 /*
2473 * If the handle is being reconnected, it's inactive, and we don't need to do anything.
2474 */
2476
2477 h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2478 if (!h->write_blocked) return;
2479
2481 if (!moved) return;
2482
2483 DEBUG("%s - Moved %" PRIu64 " pending request(s) off of blocked connection %s",
2484 h->ctx.module_name, moved, h->ctx.fd_info->name);
2485}
2486
2487CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
2489 trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
2490{
2491 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
2492 trunk_request_t *treq;
2494
2495 if (unlikely(trunk_connection_pop_request(&treq, tconn) < 0)) return;
2496
2497 /*
2498 * No more requests to send
2499 */
2500 if (!treq) return;
2501
2502 request = treq->request;
2503
2504 mod_write(request, treq, h);
2505
2507}
2508
2510{
2511 rlm_radius_t const *inst = h->ctx.inst;
2512 bio_request_t *u;
2513 char const *action;
2514 uint8_t const *packet;
2515 size_t packet_len;
2516 ssize_t slen;
2517
2518 u = treq->preq;
2519
2520 fr_assert((treq->state == TRUNK_REQUEST_STATE_PENDING) ||
2521 (treq->state == TRUNK_REQUEST_STATE_PARTIAL) ||
2522 ((u->retry.count > 0) && (treq->state == TRUNK_REQUEST_STATE_SENT)));
2523
2525
2526 /*
2527 * If it's a partial packet, then write the partial bit.
2528 */
2529 if (u->partial) {
2530 fr_assert(u->partial < u->packet_len);
2531 packet = u->packet + u->partial;
2532 packet_len = u->packet_len - u->partial;
2533 goto do_write;
2534 }
2535
2536 /*
2537 * No previous packet, OR can't retransmit the
2538 * existing one. Oh well.
2539 *
2540 * Note that if we can't retransmit the previous
2541 * packet, then u->rr MUST already have been
2542 * deleted in the request_cancel() function
2543 * or request_release_conn() function when
2544 * the REQUEUE signal was received.
2545 */
2546 if (!u->packet) {
2547 fr_assert(!u->rr);
2548
2549 if (unlikely(radius_track_entry_reserve(&u->rr, treq, h->tt, request, u->code, treq) < 0)) {
2550#ifndef NDEBUG
2551 radius_track_state_log(&default_log, L_ERR, __FILE__, __LINE__,
2553#endif
2554 fr_assert_fail("Tracking entry allocation failed: %s", fr_strerror());
2556 return;
2557 }
2558 fr_assert(u->rr);
2559 u->id = u->rr->id;
2560 if (h->radius_1_1) u->token = u->rr->token;
2561
2562 RDEBUG("Sending %s ID %d length %zu over connection %s",
2564
2565 if (encode(h, request, u, u->id) < 0) {
2566 /*
2567 * Need to do this because request_conn_release
2568 * may not be called.
2569 */
2572 return;
2573 }
2574 RHEXDUMP3(u->packet, u->packet_len, "Encoded packet");
2575
2576 /*
2577 * Remember the authentication vector, which now has the
2578 * packet signature.
2579 */
2581 } else {
2582 RDEBUG("Retransmitting %s ID %d length %zu over connection %s",
2584 }
2585
2586 /*
2587 * @todo - When logging Message-Authenticator, don't print its' value.
2588 */
2589 log_request_proto_pair_list(L_DBG_LVL_2, request, NULL, &request->request_pairs, NULL);
2591
2592 packet = u->packet;
2593 packet_len = u->packet_len;
2594
2595do_write:
2596 fr_assert(packet != NULL);
2597 fr_assert(packet_len >= RADIUS_HEADER_LENGTH);
2598
2599 slen = fr_bio_write(h->bio.main, NULL, packet, packet_len);
2600
2601 /*
2602 * Can't write anything, requeue it on a different socket.
2603 */
2604 if (slen == fr_bio_error(IO_WOULD_BLOCK)) goto requeue;
2605
2606 if (slen < 0) {
2607 switch (errno) {
2608 /*
2609 * There is an error in the request.
2610 */
2611 case EMSGSIZE: /* Packet size exceeds max size allowed on socket */
2612 ERROR("%s - Failed sending data over connection %s: %s",
2613 h->ctx.module_name, h->ctx.fd_info->name, fr_syserror(errno));
2615 break;
2616
2617 /*
2618 * There is an error in the connection. The reconnection will re-queue any pending or
2619 * sent requests, so we don't have to do any cleanup.
2620 */
2621 default:
2622 ERROR("%s - Failed sending data over connection %s: %s",
2623 h->ctx.module_name, h->ctx.fd_info->name, fr_syserror(errno));
2625 break;
2626 }
2627
2628 return;
2629 }
2630
2631 /*
2632 * No data to send, ignore the write for partials, but otherwise requeue it.
2633 */
2634 if (slen == 0) {
2635 if (u->partial) return;
2636
2637 /*
2638 * We didn't get a "blocked" error, but we didn't write any data. And the socket is
2639 * unconnected. This means we just discard the packet.
2640 */
2642 ERROR("%s - Failed sending %s ID %d length %zu over connection %s: Destination network is down or unreachable",
2645 return;
2646 }
2647
2648 requeue:
2649 RWARN("%s - Failed sending data over connection %s: sent zero bytes",
2650 h->ctx.module_name, h->ctx.fd_info->name);
2652 return;
2653 }
2654
2655 /*
2656 * Stream BIOs can write partial packets. The request stays in the partial state until all of
2657 * the packet has been written.
2658 */
2659 fr_assert((size_t) slen <= packet_len);
2660 u->partial += slen;
2661 if (u->partial < u->packet_len) {
2663 return;
2664 }
2665
2666 /*
2667 * For retransmissions.
2668 */
2669 u->partial = 0;
2670 u->last_written = fr_time();
2671
2672 /*
2673 * Don't print anything extra for replication.
2674 */
2675 if (inst->mode == RLM_RADIUS_MODE_REPLICATE) {
2676 u->rcode = RLM_MODULE_OK;
2678 return;
2679 }
2680
2681 /*
2682 * A request which is not already in the SENT state is a new packet from request_mux(), and we
2683 * signal the trunk that it was written.
2684 *
2685 * A request which is in the SENT state is a retransmission, and we don't signal the trunk.
2686 */
2687 if (treq->state == TRUNK_REQUEST_STATE_SENT) {
2688 action = "Retransmitted";
2689
2690 } else {
2692
2693 if (u->retry.count > 1) {
2694 action = "Retransmitted";
2695 } else {
2696 action = u->proxied ? "Proxied" : "Originated";
2697 }
2698 }
2699
2701
2702 /*
2703 * A status check is sent only while the connection is already zombie, so a status check does not
2704 * start a run of unanswered requests. The write of a retransmission counts, because the home server
2705 * has still not answered.
2706 */
2707 if (!u->status_check) {
2708 fr_time_t write_time = fr_time();
2709 fr_time_delta_t timeout = inst->retry[u->code].mrd;
2710
2711 /*
2712 * "no timeout" means "use zombie_period".
2713 */
2714 if (!fr_time_delta_ispos(timeout)) timeout = inst->zombie_period;
2715
2716 /*
2717 * If we haven't already set first_unanswered, or we're just starting a run of writes
2718 * after a long delay of no packets. Set the first_unanswered to now.
2719 */
2721 fr_time_delta_gt(fr_time_sub(write_time, h->last_sent), timeout)) {
2722 h->first_unanswered = write_time;
2723
2724 /*
2725 * Timeouts from the earlier run do not count towards "response_timeouts".
2726 */
2727 h->timeouts = 0;
2728 }
2729
2730 h->last_sent = write_time;
2731 }
2732
2733 if (!u->proxied) {
2734 RDEBUG("%s request. Expecting response within %pVs", action,
2736
2737 } else {
2738 /*
2739 * If the packet doesn't get a response, then bio_request_free() will notice, and look
2740 * for zombie connections.
2741 */
2742 RDEBUG("%s request. Relying on NAS to perform more retransmissions", action);
2743 }
2744
2745 /*
2746 * We don't retransmit over TCP.
2747 */
2748 if (h->ctx.fd_config.socket_type != SOCK_DGRAM) return;
2749
2750 /*
2751 * If we only send one datagram packet, then don't bother saving it.
2752 */
2753 if (u->retry.config && u->retry.config->mrc == 1) {
2754 u->packet = NULL;
2755 return;
2756 }
2757
2758 MEM(u->packet = talloc_memdup(u, u->packet, u->packet_len));
2759}
2760
2761/** Deal with Protocol-Error replies, and possible negotiation
2762 *
2763 */
2765{
2766 bool error_601 = false;
2767 uint32_t response_length = 0;
2768 uint8_t const *attr, *end;
2769
2770 end = h->buffer + fr_nbo_to_uint16(h->buffer + 2);
2771
2772 for (attr = h->buffer + RADIUS_HEADER_LENGTH;
2773 attr < end;
2774 attr += attr[1]) {
2775 /*
2776 * Error-Cause = Response-Too-Big
2777 */
2778 if ((attr[0] == attr_error_cause->attr) && (attr[1] == 6)) {
2779 uint32_t error;
2780
2781 error = fr_nbo_to_uint32(attr + 2);
2782 if (error == 601) error_601 = true;
2783 continue;
2784 }
2785
2786 /*
2787 * The other end wants us to increase our Response-Length
2788 */
2789 if ((attr[0] == attr_extended_attribute_1->attr) &&
2790 (attr[1] == 7) &&
2791 (attr[2] == attr_response_length->attr)) {
2792 response_length = fr_nbo_to_uint32(attr + 3);
2793 continue;
2794 }
2795
2796 /*
2797 * Protocol-Error packets MUST contain an
2798 * Original-Packet-Code attribute.
2799 *
2800 * The attribute containing the
2801 * Original-Packet-Code is an extended
2802 * attribute.
2803 */
2804 if (attr[0] != attr_extended_attribute_1->attr) continue;
2805
2806 /*
2807 * ATTR + LEN + EXT-Attr + uint32
2808 */
2809 if (attr[1] != 7) continue;
2810
2811 /*
2812 * See if there's an Original-Packet-Code.
2813 */
2814 if (attr[2] != (uint8_t)attr_original_packet_code->attr) continue;
2815
2816 /*
2817 * Has to be an 8-bit number.
2818 */
2819 if ((attr[3] != 0) ||
2820 (attr[4] != 0) ||
2821 (attr[5] != 0)) {
2823 return;
2824 }
2825
2826 /*
2827 * The value has to match. We don't
2828 * currently multiplex different codes
2829 * with the same IDs on connections. So
2830 * this check is just for RFC compliance,
2831 * and for sanity.
2832 */
2833 if (attr[6] != u->code) {
2835 return;
2836 }
2837 }
2838
2839 /*
2840 * Error-Cause = Response-Too-Big
2841 *
2842 * The other end says it needs more room to send it's response
2843 *
2844 * Limit it to reasonable values.
2845 */
2846 if (error_601 && response_length && (response_length > h->buflen)) {
2847 if (response_length < 4096) response_length = 4096;
2848 if (response_length > 65535) response_length = 65535;
2849
2850 DEBUG("%s - Increasing buffer size to %u for connection %s", h->ctx.module_name, response_length, h->ctx.fd_info->name);
2851
2852 /*
2853 * Make sure to copy the packet over!
2854 */
2855 MEM(h->buffer = talloc_realloc_size(h, h->buffer, response_length));
2856 h->buflen = response_length;
2857 }
2858
2859 /*
2860 * fail - something went wrong internally, or with the connection.
2861 * invalid - wrong response to packet
2862 * handled - best remaining alternative :(
2863 *
2864 * i.e. if the response is NOT accept, reject, whatever,
2865 * then we shouldn't allow the caller to do any more
2866 * processing of this packet. There was a protocol
2867 * error, and the response is valid, but not useful for
2868 * anything.
2869 */
2871}
2872
2873
2874/** Send the next status check, after the previous status check got a reply
2875 *
2876 */
2878{
2879 trunk_connection_t *tconn = talloc_get_type_abort(uctx, trunk_connection_t);
2880 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2881
2882 /*
2883 * Status checks are sent only on an open connection.
2884 */
2885 if (h->ctx.fd_info->state != FR_BIO_FD_STATE_OPEN) return;
2886
2887 /*
2888 * The previous status check was answered, so start the retries again.
2889 */
2890 status_check_enqueue(tconn, h, true);
2891}
2892
2893/** Deal with replies replies to status checks and possible negotiation
2894 *
2895 */
2897{
2898 bio_handle_t *h = talloc_get_type_abort(tconn->conn->h, bio_handle_t);
2899 rlm_radius_t const *inst = h->ctx.inst;
2900
2901 fr_assert(u == h->status_u);
2902
2903 /*
2904 * @todo - do other negotiation and signaling.
2905 */
2907
2908 if (u->num_replies < inst->num_answers_to_alive) {
2909 DEBUG("Received %u / %u replies for status check, on connection - %s",
2910 u->num_replies, inst->num_answers_to_alive, h->ctx.fd_info->name);
2911 DEBUG("Next status check packet will be in %pVs", fr_box_time_delta(fr_time_sub(u->retry.next, now)));
2912
2913 /*
2914 * Set the timer for the next status check.
2915 */
2916 if (fr_timer_at(h, h->tl, &u->ev, u->retry.next, false, status_check_next, tconn) < 0) {
2918 }
2919 return;
2920 }
2921
2922 DEBUG("Received enough replies to status check, marking connection as active - %s", h->ctx.fd_info->name);
2923
2924 /*
2925 * Reset retry interval and retransmission counters
2926 * also frees u->ev.
2927 */
2928 status_check_reset(h, u);
2930}
2931
2932CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
2934{
2935 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
2936
2937 DEBUG3("%s - Reading data for connection %s", h->ctx.module_name, h->ctx.fd_info->name);
2938
2939 while (true) {
2940 ssize_t slen;
2941
2942 trunk_request_t *treq;
2944 bio_request_t *u;
2947 uint8_t code = 0;
2949 fr_pair_t *vp;
2950
2951 fr_time_t now;
2952
2954
2955 /*
2956 * Drain the socket of all packets. If we're busy, this
2957 * saves a round through the event loop. If we're not
2958 * busy, a few extra system calls don't matter.
2959 */
2960 slen = fr_bio_read(h->bio.main, NULL, h->buffer, h->buflen);
2961 if (slen == 0) {
2963 return;
2964 }
2965
2966 /*
2967 * We're done reading, return.
2968 */
2969 if (slen == fr_bio_error(IO_WOULD_BLOCK)) return;
2970
2971 if (slen < 0) {
2972 ERROR("%s - Failed reading response from socket: %s",
2973 h->ctx.module_name, fr_syserror(errno));
2975 return;
2976 }
2977
2978 fr_assert(slen >= RADIUS_HEADER_LENGTH); /* checked in verify */
2979
2980 /*
2981 * Note that we don't care about packet codes. All
2982 * packet codes share the same ID space.
2983 */
2984 rr = radius_track_entry_find(h->tt, h->buffer[1], h->buffer + 4);
2985 if (!rr) {
2986 WARN("%s - Ignoring reply with %s that arrived too late",
2988 continue;
2989 }
2990
2991 treq = talloc_get_type_abort(rr->uctx, trunk_request_t);
2992 request = treq->request;
2993 fr_assert(request != NULL);
2994 u = talloc_get_type_abort(treq->rctx, bio_request_t);
2995 fr_assert(u == treq->preq);
2996
2997 /*
2998 * Decode the incoming packet.
2999 */
3000 reason = decode(request->reply_ctx, &reply, &code, h, request, u, rr->vector, h->buffer, (size_t)slen);
3001 if (reason != FR_RADIUS_FAIL_NONE) continue;
3002
3003 /*
3004 * Only valid packets are processed
3005 * Otherwise an attacker could perform
3006 * a DoS attack against the proxying servers
3007 * by sending fake responses for upstream
3008 * servers.
3009 */
3010 h->last_reply = now = fr_time();
3012 h->timeouts = 0;
3013
3014 /*
3015 * If we got a reply during the zombie period mark the
3016 * connection as active and remove the timer.
3017 */
3021 }
3022
3023 /*
3024 * Status-Server can have any reply code, we don't care
3025 * what it is. So long as it's signed properly, we
3026 * accept it. This flexibility is because we don't
3027 * expose Status-Server to the admins. It's only used by
3028 * this module for internal signalling.
3029 */
3030 if (u == h->status_u) {
3031 fr_pair_list_free(&reply); /* Probably want to pass this to status_check_reply? */
3033 status_check_reply(tconn, u, now);
3034 continue;
3035 }
3036
3037 /*
3038 * Handle any state changes, etc. needed by receiving a
3039 * Protocol-Error reply packet.
3040 *
3041 * Protocol-Error is permitted as a reply to any
3042 * packet.
3043 */
3044 switch (code) {
3047
3048 /*
3049 * The attributes which the home server sent are in the "reply" list. They are
3050 * added to request->reply_pairs at the end of this function. Original-Packet-Code
3051 * is a child of Extended-Attribute-1, so we need the nested versions of the pair
3052 * functions.
3053 */
3055 if (!vp) {
3056 if (!h->radius_1_1) RWDEBUG("Protocol-Error response is missing Original-Packet-Code");
3057 } else {
3059 }
3060
3062 if (!vp) {
3064 vp->vp_uint32 = FR_ERROR_CAUSE_VALUE_PROXY_PROCESSING_ERROR;
3066 }
3067 break;
3068
3069 default:
3070 break;
3071 }
3072
3073 /*
3074 * Mark up the request as being an Access-Challenge, if
3075 * required.
3076 *
3077 * We don't do this for other packet types, because the
3078 * ok/fail nature of the module return code will
3079 * automatically result in it the parent request
3080 * returning an ok/fail packet code.
3081 */
3083 vp = fr_pair_find_by_da(&request->reply_pairs, NULL, attr_packet_type);
3084 if (!vp) {
3087 fr_pair_append(&request->reply_pairs, vp);
3088 }
3089
3090 /*
3091 * If the Access-Request got a challenge, AND the request doesn't have State, AND
3092 * the challenge does have State, THEN try to load-balance future packets to the
3093 * same destination.
3094 */
3095 if (h->ctx.inst->track_load_balance &&
3096 !fr_pair_find_by_da(&request->request_pairs, NULL, attr_state) &&
3099 }
3100 }
3101
3102 /*
3103 * Delete Proxy-State attributes from the reply.
3104 */
3106
3107 /*
3108 * If the reply has Message-Authenticator, then over-ride its value with all zeros, so
3109 * that we don't confuse anyone reading the debug output.
3110 */
3111 if ((vp = fr_pair_find_by_da(&reply, NULL, attr_message_authenticator)) != NULL) {
3112 (void) fr_pair_value_memdup(vp, (uint8_t const *) "", 1, false);
3113 }
3114
3115 treq->request->reply->code = code;
3116
3117 /*
3118 * protocol_error_reply() has already set u->rcode, which is FAIL when the
3119 * Original-Packet-Code is wrong.
3120 */
3122 fr_pair_list_append(&request->reply_pairs, &reply);
3124 }
3125}
3126
3127/*
3128 * This is the same as request_mux(), except that we immediately mark the request as complete.
3129 */
3130CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
3132 trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
3133{
3134 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
3135 trunk_request_t *treq;
3136
3137 if (unlikely(trunk_connection_pop_request(&treq, tconn) < 0)) return;
3138
3139 /*
3140 * No more requests to send
3141 */
3142 if (!treq) return;
3143
3144 /*
3145 * Write the request, and change to the next state.
3146 */
3147 mod_write(treq->request, treq, h);
3148
3150}
3151
3152CC_NO_UBSAN(function) /* UBSAN: false positive - public vs private connection_t trips --fsanitize=function*/
3154{
3155 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
3156
3157 DEBUG3("%s - Reading data for connection %s", h->ctx.module_name, h->ctx.fd_info->name);
3158
3159 while (true) {
3160 ssize_t slen;
3161
3162 trunk_request_t *treq;
3164 bio_request_t *u;
3167 uint8_t code = 0;
3169
3170 fr_time_t now;
3171
3173
3174 /*
3175 * Drain the socket of all packets. If we're busy, this
3176 * saves a round through the event loop. If we're not
3177 * busy, a few extra system calls don't matter.
3178 */
3179 slen = fr_bio_read(h->bio.main, NULL, h->buffer, h->buflen);
3180 if (slen == 0) {
3182 return;
3183 }
3184
3185 /*
3186 * We're done reading, return.
3187 */
3188 if (slen == fr_bio_error(IO_WOULD_BLOCK)) return;
3189
3190 if (slen < 0) {
3191 ERROR("%s - Failed reading response from socket: %s",
3192 h->ctx.module_name, fr_syserror(errno));
3194 return;
3195 }
3196
3197 fr_assert(slen >= RADIUS_HEADER_LENGTH); /* checked in verify */
3198
3199 /*
3200 * We only pay attention to Protocol-Error replies.
3201 *
3202 * All other packets are discarded.
3203 */
3205 continue;
3206 }
3207
3208 /*
3209 * Note that we don't care about packet codes. All
3210 * packet codes share the same ID space.
3211 */
3212 rr = radius_track_entry_find(h->tt, h->buffer[1], h->buffer + 4);
3213 if (!rr) {
3214 WARN("%s - Ignoring reply with %s that arrived too late",
3216 continue;
3217 }
3218
3219 treq = talloc_get_type_abort(rr->uctx, trunk_request_t);
3220 request = treq->request;
3221 fr_assert(request != NULL);
3222 u = talloc_get_type_abort(treq->rctx, bio_request_t);
3223 fr_assert(u == treq->preq);
3224
3225 /*
3226 * Decode the incoming packet
3227 */
3228 reason = decode(request->reply_ctx, &reply, &code, h, request, u, rr->vector, h->buffer, (size_t)slen);
3229 if (reason != FR_RADIUS_FAIL_NONE) continue;
3230
3231 /*
3232 * Only valid packets are processed
3233 * Otherwise an attacker could perform
3234 * a DoS attack against the proxying servers
3235 * by sending fake responses for upstream
3236 * servers.
3237 */
3238 h->last_reply = now = fr_time();
3239
3240 /*
3241 * Status-Server can have any reply code, we don't care
3242 * what it is. So long as it's signed properly, we
3243 * accept it. This flexibility is because we don't
3244 * expose Status-Server to the admins. It's only used by
3245 * this module for internal signalling.
3246 */
3247 if (u == h->status_u) {
3248 fr_pair_list_free(&reply); /* Probably want to pass this to status_check_reply? */
3250 status_check_reply(tconn, u, now);
3251 continue;
3252 }
3253
3254 /*
3255 * Handle any state changes, etc. needed by receiving a
3256 * Protocol-Error reply packet.
3257 *
3258 * Protocol-Error is also permitted as a reply to any
3259 * packet.
3260 */
3262 }
3263}
3264
3265
3266/** Remove the request from any tracking structures
3267 *
3268 * Frees encoded packets if the request is being moved to a new connection
3269 */
3270static void request_cancel(UNUSED connection_t *conn, void *preq_to_reset,
3271 trunk_cancel_reason_t reason, UNUSED void *uctx)
3272{
3273 bio_request_t *u = preq_to_reset;
3274
3275 /*
3276 * Request has been requeued on the same
3277 * connection due to timeout or DUP signal. We
3278 * keep the same packet to avoid re-encoding it.
3279 */
3280 if (reason == TRUNK_CANCEL_REASON_REQUEUE) {
3281 /*
3282 * Delete the request_timeout
3283 *
3284 * Note: There might not be a request timeout
3285 * set in the case where the request was
3286 * queued for sendmmsg but never actually
3287 * sent.
3288 */
3289 FR_TIMER_DISARM(u->ev);
3290 }
3291
3292 /*
3293 * Other cancellations are dealt with by
3294 * request_conn_release as the request is removed
3295 * from the trunk.
3296 */
3297}
3298
3299/** Clear out anything associated with the handle from the request
3300 *
3301 */
3302static void request_conn_release(connection_t *conn, void *preq_to_reset, UNUSED void *uctx)
3303{
3304 bio_request_t *u = preq_to_reset;
3305 bio_handle_t *h = talloc_get_type_abort(conn->h, bio_handle_t);
3306
3307 FR_TIMER_DISARM(u->ev);
3309
3310 if (h->ctx.inst->mode == RLM_RADIUS_MODE_REPLICATE) return;
3311
3312 /*
3313 * Status checks have their own counts and release in status_check_reset()
3314 */
3315 if (!u->status_check) u->num_replies = 0;
3316}
3317
3318/** Write out a canned failure
3319 *
3320 */
3321static void request_fail(request_t *request, NDEBUG_UNUSED void *preq, void *rctx,
3322 NDEBUG_UNUSED trunk_request_state_t state, UNUSED void *uctx)
3323{
3324 bio_request_t *u = talloc_get_type_abort(rctx, bio_request_t);
3325
3326 fr_assert(u == preq);
3327
3328 fr_assert(!u->rr && !u->packet && fr_pair_list_empty(&u->extra) && !fr_timer_armed(u->ev)); /* Dealt with by request_conn_release */
3329
3331
3332 /*
3333 * The trunk frees the status check treq after this callback. Clear the pointer so that
3334 * _bio_request_free() does not look at a freed treq.
3335 */
3336 if (u->status_check) {
3337 u->treq = NULL;
3338 return;
3339 }
3340
3342 u->treq = NULL;
3343
3345}
3346
3347/** Response has already been written to the rctx at this point
3348 *
3349 */
3350static void request_complete(request_t *request, NDEBUG_UNUSED void *preq, void *rctx, UNUSED void *uctx)
3351{
3352 bio_request_t *u = talloc_get_type_abort(rctx, bio_request_t);
3353
3354 fr_assert(u == preq);
3355
3356 fr_assert(!u->rr && !u->packet && fr_pair_list_empty(&u->extra) && !fr_timer_armed(u->ev)); /* Dealt with by request_conn_release */
3357
3358 /*
3359 * The trunk frees the status check treq after this callback. Clear the pointer so that
3360 * _bio_request_free() does not look at a freed treq.
3361 */
3362 if (u->status_check) {
3363 u->treq = NULL;
3364 return;
3365 }
3366
3367 u->treq = NULL;
3368
3370}
3371
3372/** Resume execution of the request, returning the rcode set during trunk execution
3373 *
3374 */
3376{
3377 bio_request_t *u = talloc_get_type_abort(mctx->rctx, bio_request_t);
3378 rlm_rcode_t rcode = u->rcode;
3379
3380 talloc_free(u);
3381
3382 RETURN_UNLANG_RCODE(rcode);
3383}
3384
3385static void do_signal(rlm_radius_t const *inst, bio_request_t *u, request_t *request, fr_signal_t action);
3386
3387static void mod_signal(module_ctx_t const *mctx, request_t *request, fr_signal_t action)
3388{
3390
3391 bio_request_t *u = talloc_get_type_abort(mctx->rctx, bio_request_t);
3392
3393 do_signal(inst, u, request, action);
3394}
3395
3397{
3398 /*
3399 * We received a duplicate packet, but we're not doing
3400 * synchronous proxying. Ignore the dup, and rely on the
3401 * IO submodule to time it's own retransmissions.
3402 */
3403 if ((action == FR_SIGNAL_DUP) && (inst->mode != RLM_RADIUS_MODE_PROXY)) return;
3404
3405 switch (action) {
3406 /*
3407 * The request is being cancelled, tell the
3408 * trunk so it can clean up the treq.
3409 */
3410 case FR_SIGNAL_CANCEL:
3411 if (u->treq) {
3413 u->treq = NULL;
3414 }
3415 return;
3416
3417 /*
3418 * Requeue the request on the same connection
3419 * causing a "retransmission" if the request
3420 * has already been sent out.
3421 *
3422 * mod_dup() checks u->treq and complains if necessary.
3423 */
3424 case FR_SIGNAL_DUP:
3425 /*
3426 * The check is here and not in mod_dup(), because the retry timer also calls mod_dup().
3427 */
3428 if (fr_time_gt(u->last_written, fr_time_wrap(0)) &&
3430 RDEBUG("Duplicate packet received %pVs after the last write - suppressing retransmission",
3432 return;
3433 }
3434
3435 mod_dup(request, u);
3436 return;
3437
3438 default:
3439 return;
3440 }
3441}
3442
3443/** Free a bio_request_t
3444 *
3445 * Allows us to set break points for debugging.
3446 */
3448{
3449 if (!u->treq) return 0;
3450
3451#ifndef NDEBUG
3452 {
3453 trunk_request_t *treq;
3454 treq = talloc_get_type_abort(u->treq, trunk_request_t);
3455 fr_assert(treq->preq == u);
3456 }
3457#endif
3458
3459 fr_assert_msg(!fr_timer_armed(u->ev), "bio_request_t freed with active timer");
3460
3462
3463 fr_assert(u->rr == NULL);
3464
3465 return 0;
3466}
3467
3468static int mod_enqueue(bio_request_t **p_u, fr_retry_config_t const **p_retry_config,
3469 rlm_radius_t const *inst, trunk_t *trunk, request_t *request)
3470{
3471 bio_request_t *u;
3472 trunk_request_t *treq;
3474
3475 fr_assert(request->packet->code > 0);
3476 fr_assert(request->packet->code < FR_RADIUS_CODE_MAX);
3477
3478 /*
3479 * Do any necessary RADIUS level fixups
3480 * - check Proxy-State
3481 * - do CHAP-Challenge fixups
3482 */
3483 if (radius_fixups(inst, request) < 0) return -1;
3484
3485 treq = trunk_request_alloc(trunk, request);
3486 if (!treq) {
3487 REDEBUG("Failed allocating handler for request");
3488 return -1;
3489 }
3490
3491 MEM(u = talloc_zero(request, bio_request_t));
3492 talloc_set_destructor(u, _bio_request_free);
3493
3494 /*
3495 * Can't use compound literal - const issues.
3496 */
3497 u->code = request->packet->code;
3498 u->priority = request->priority;
3499 u->recv_time = request->async->recv_time;
3501
3502 u->retry.count = 1;
3503
3505
3506 switch(trunk_request_enqueue(&treq, trunk, request, u, u)) {
3507 case TRUNK_ENQUEUE_OK:
3509 break;
3510
3512 REDEBUG("Unable to queue packet - connections at maximum capacity");
3513 fail:
3514 fr_assert(!u->rr && !u->packet); /* Should not have been fed to the muxer */
3515 trunk_request_free(&treq); /* Return to the free list */
3516 talloc_free(u);
3517 return -1;
3518
3520 REDEBUG("All destinations are down - cannot send packet");
3521 goto fail;
3522
3523 case TRUNK_ENQUEUE_FAIL:
3524 REDEBUG("Unable to queue packet");
3525 goto fail;
3526 }
3527
3528 u->treq = treq; /* Remember for signalling purposes */
3529 fr_assert(treq->rctx == u);
3530
3531 /*
3532 * Figure out if we're originating the packet or proxying it. And also figure out if we have to
3533 * retry.
3534 */
3535 switch (inst->mode) {
3537 case RLM_RADIUS_MODE_UNCONNECTED_REPLICATE: /* unconnected sockets are UDP, and bypass the trunk */
3538 REDEBUG("Internal sanity check failed - connection trunking cannot be used for replication");
3539 return -1;
3540
3541 /*
3542 * We originate this packet if it was taken from the detail module, which doesn't have a
3543 * real client. @todo - do a better check here.
3544 *
3545 * We originate this packet if the parent request is not compatible with this one
3546 * (i.e. it's from a different protocol).
3547 *
3548 * We originate the packet if the parent is from the same dictionary, but has a different
3549 * packet code. This lets us receive Accounting-Request, and originate
3550 * Disconnect-Request.
3551 */
3554 if (!request->parent) {
3555 u->proxied = (request->client && request->client->cs != NULL);
3556
3557 } else if (!fr_dict_compatible(request->parent->proto_dict, request->proto_dict)) {
3558 u->proxied = false;
3559
3560 } else {
3561 u->proxied = (request->parent->packet->code == request->packet->code);
3562 }
3563
3565
3566 /*
3567 * All proxied and client packets have at a timer, generally at least max_rtx_duration.
3568 */
3570 retry_config = &inst->retry[u->code];
3571 break;
3572
3573 /*
3574 * Replicated packets do not wait for a response, so they have no timer.
3575 */
3577 retry_config = NULL;
3578 break;
3579
3580 default:
3581 fr_assert(0);
3582 return -1;
3583 }
3584
3585 /*
3586 * The event loop will take care of demux && sending the
3587 * packet, along with any retransmissions.
3588 */
3589 *p_u = u;
3590 *p_retry_config = retry_config;
3591
3592 return 1;
3593}
3594
3595static void home_server_free(void *data)
3596{
3597 home_server_t *home = data;
3598
3599 talloc_free(home);
3600}
3601
3604 .connection_notify = thread_conn_notify,
3605 .request_prioritise = request_prioritise,
3606 .request_mux = request_mux,
3607 .request_demux = request_demux,
3608 .request_conn_release = request_conn_release,
3609 .request_complete = request_complete,
3610 .request_fail = request_fail,
3611 .request_cancel = request_cancel,
3612};
3613
3616 .connection_notify = thread_conn_notify,
3617 .request_prioritise = request_prioritise,
3618 .request_mux = request_replicate_mux,
3619 .request_demux = request_replicate_demux,
3620 .request_conn_release = request_conn_release,
3621 .request_complete = request_complete,
3622 .request_fail = request_fail,
3623 .request_cancel = request_cancel,
3624};
3625
3626/** Instantiate thread data for the submodule.
3627 *
3628 */
3630{
3631 rlm_radius_t *inst = talloc_get_type_abort(mctx->mi->data, rlm_radius_t);
3632 bio_thread_t *thread = talloc_get_type_abort(mctx->thread, bio_thread_t);
3633 bool delay_start = false;
3634
3635 thread->ctx.el = mctx->el;
3636 thread->ctx.inst = inst;
3637 thread->ctx.fd_config = inst->fd_config;
3638 thread->ctx.radius_ctx = inst->common_ctx;
3639
3640#ifdef WITH_TLS
3641 /*
3642 * SSL_CTX cannot be shared across threads, so each worker thread allocates its own.
3643 */
3644 if (inst->tls_conf) {
3645 thread->ctx.ssl_ctx = fr_tls_ctx_alloc(inst->tls_conf, true);
3646 if (!thread->ctx.ssl_ctx) {
3647 PERROR("%s - failed allocating TLS context", inst->name);
3648 return -1;
3649 }
3650 }
3651#endif
3652
3653 switch (inst->mode) {
3656 inst->home_server_lifetime);
3658
3659 default:
3660 /*
3661 * Assign each thread a portion of the available source port range.
3662 */
3663 if (thread->ctx.fd_config.src_port_start) {
3664 uint16_t range = inst->fd_config.src_port_end - inst->fd_config.src_port_start + 1;
3665 thread->num_ports = range / main_config->max_workers;
3666 thread->ctx.fd_config.src_port_start = inst->fd_config.src_port_start + (thread->num_ports * fr_schedule_worker_id());
3667 thread->ctx.fd_config.src_port_end = inst->fd_config.src_port_start + (thread->num_ports * (fr_schedule_worker_id() +1)) - 1;
3668 if (inst->mode != RLM_RADIUS_MODE_XLAT_PROXY) {
3669 thread->connections = talloc_zero_array(thread, connection_t *, thread->num_ports);
3671 }
3672 }
3673
3674 /*
3675 * @todo - we are called for threads which do NOT have an interpreter set up. e.g. the
3676 * coordinator thread. This is likely wrong.
3677 *
3678 * For now, work around it.
3679 */
3680#ifdef WITH_TLS
3681 if (thread->ctx.ssl_ctx && !unlang_interpret_get_thread_default()) delay_start = true;
3682#endif
3683
3684 thread->ctx.trunk = trunk_alloc(thread, mctx->el, &io_funcs,
3685 &inst->trunk_conf, inst->name, thread, delay_start, inst->trigger_args);
3686 if (!thread->ctx.trunk) return -1;
3687 return 0;
3688
3690 /*
3691 * Replication trunks use a different set of functions.
3692 */
3693 thread->ctx.trunk = trunk_alloc(thread, mctx->el, &io_replicate_funcs,
3694 &inst->trunk_conf, inst->name, thread, false, inst->trigger_args);
3695 if (!thread->ctx.trunk) return -1;
3696 return 0;
3697
3699 break;
3700 }
3701
3702 /*
3703 * If we have a port range, allocate the source port based
3704 * on the range start, plus the thread ID. This means
3705 * that we can avoid "hunt and peck" attempts to open up
3706 * the source port.
3707 */
3708 if (thread->ctx.fd_config.src_port_start) {
3710 }
3711
3712 /*
3713 * Allocate an unconnected socket for replication.
3714 */
3715 thread->bio.fd = fr_bio_fd_alloc(thread, &thread->ctx.fd_config, 0);
3716 if (!thread->bio.fd) {
3717 PERROR("%s - failed opening socket", inst->name);
3718 return -1;
3719 }
3720
3721 thread->bio.fd->uctx = thread;
3722 thread->ctx.fd_info = fr_bio_fd_info(thread->bio.fd);
3723 fr_assert(thread->ctx.fd_info != NULL);
3724
3725 (void) fr_bio_fd_write_only(thread->bio.fd);
3726
3727 DEBUG("%s - Opened unconnected replication socket %s", inst->name, thread->ctx.fd_info->name);
3728 return 0;
3729}
3730
3731/** Free thread data for the submodule.
3732 *
3733 */
3735{
3736#ifdef WITH_TLS
3737 bio_thread_t *thread = talloc_get_type_abort(mctx->thread, bio_thread_t);
3738
3739 if (thread->ctx.ssl_ctx) SSL_CTX_free(thread->ctx.ssl_ctx);
3740#else
3741 (void) mctx;
3742#endif
3743
3744 return 0;
3745}
3746
3748 { .required = true, .single = true, .type = FR_TYPE_COMBO_IP_ADDR },
3749 { .required = true, .single = true, .type = FR_TYPE_UINT16 },
3750 { .required = true, .single = true, .type = FR_TYPE_STRING },
3752};
3753
3754/*
3755 * %replicate.sendto.ipaddr(ipaddr, port, secret)
3756 */
3758 xlat_ctx_t const *xctx,
3759 request_t *request, fr_value_box_list_t *args)
3760{
3761 bio_thread_t *thread = talloc_get_type_abort(xctx->mctx->thread, bio_thread_t);
3762 fr_value_box_t *ipaddr, *port, *secret;
3763 ssize_t packet_len;
3764 uint8_t buffer[4096];
3765 fr_radius_ctx_t radius_ctx;
3768
3769 XLAT_ARGS(args, &ipaddr, &port, &secret);
3770
3771 /*
3772 * Can't change IP address families.
3773 */
3774 if (ipaddr->vb_ip.af != thread->ctx.fd_info->socket.af) {
3775 RPERROR("Invalid destination IP address family in %pV", ipaddr);
3776 return XLAT_ACTION_FAIL;
3777 }
3778
3779 /*
3780 * This shouldn't happen, but what the heck.
3781 */
3782 if (!FR_RADIUS_PACKET_CODE_VALID(request->packet->code)) {
3783 REDEBUG("Cannot replicate packet code %u, it is not a RADIUS packet code", request->packet->code);
3784 return XLAT_ACTION_FAIL;
3785 }
3786
3787 /*
3788 * Warn if we're not replicating accounting data. It likely won't wokr/
3789 */
3790 if (request->packet->code != FR_RADIUS_CODE_ACCOUNTING_REQUEST) {
3791 RWDEBUG("Replication of packets other then Accounting-Request will likely not do what you want.");
3792 }
3793
3794 /*
3795 * Set up various context things.
3796 */
3797 radius_ctx = (fr_radius_ctx_t) {
3798 .secret = secret->vb_strvalue,
3799 .secret_length = secret->vb_length,
3800 .proxy_state = 0,
3801 };
3802
3804 .common = &radius_ctx,
3805 .rand_ctx = (fr_fast_rand_t) {
3806 .a = fr_rand(),
3807 .b = fr_rand(),
3808 },
3809 .code = request->packet->code,
3810 .id = thread->bio.id++ & 0xff,
3811 .add_proxy_state = false,
3812 };
3813
3814 /*
3815 * Encode the entire packet.
3816 */
3817 packet_len = fr_radius_encode(&FR_DBUFF_TMP(buffer, sizeof(buffer)),
3818 &request->request_pairs, &encode_ctx);
3819 if (packet_len < 0) {
3820 RPERROR("Failed encoding replicated packet");
3821 return XLAT_ACTION_FAIL;
3822 }
3823
3824 /*
3825 * Sign it.
3826 */
3827 if (fr_radius_sign(buffer, NULL, (uint8_t const *) radius_ctx.secret, radius_ctx.secret_length) < 0) {
3828 RPERROR("Failed signing replicated packet");
3829 return XLAT_ACTION_FAIL;
3830 }
3831
3832 /*
3833 * Prepare destination address.
3834 */
3835 addr = (fr_bio_fd_packet_ctx_t) {
3836 .socket = thread->ctx.fd_info->socket,
3837 };
3838 addr.socket.inet.dst_ipaddr = ipaddr->vb_ip;
3839 addr.socket.inet.dst_port = port->vb_uint16;
3840
3841 RDEBUG("Replicating packet to %pV:%u", ipaddr, port->vb_uint16);
3842
3843 /*
3844 * We either send it, or fail.
3845 */
3846 packet_len = fr_bio_write(thread->bio.fd, &addr, buffer, packet_len);
3847 if (packet_len < 0) {
3848 RPERROR("Failed replicating packet to %pV:%u", ipaddr, port->vb_uint16);
3849 return XLAT_ACTION_FAIL;
3850 }
3851
3852 /*
3853 * No return value.
3854 */
3855 return XLAT_ACTION_DONE;
3856}
3857
3858// **********************************************************************
3859
3860/** Dynamic home server code
3861 *
3862 */
3863
3864static fr_cmp_ret_t home_server_cmp(void const *one, void const *two)
3865{
3866 home_server_t const *a = one;
3867 home_server_t const *b = two;
3868 fr_cmp_ret_t rcode;
3869
3871 if (rcode != 0) return rcode;
3872
3874}
3875
3877 xlat_ctx_t const *xctx,
3878 request_t *request, UNUSED fr_value_box_list_t *in)
3879{
3880 bio_request_t *u = talloc_get_type_abort(xctx->rctx, bio_request_t);
3881 fr_value_box_t *dst;
3882
3883 if (u->rcode == RLM_MODULE_FAIL) return XLAT_ACTION_FAIL;
3884
3886 dst->vb_uint32 = request->reply->code;
3887
3888 fr_dcursor_append(out, dst);
3889
3890 return XLAT_ACTION_DONE;
3891}
3892
3894{
3895 rlm_radius_t const *inst = talloc_get_type_abort(xctx->mctx->mi->data, rlm_radius_t);
3896 bio_request_t *u = talloc_get_type_abort(xctx->rctx, bio_request_t);
3897
3898 do_signal(inst, u, request, action);
3899}
3900
3901/*
3902 * @todo - change this to mod_retry
3903 */
3904static void xlat_sendto_retry(xlat_ctx_t const *xctx, request_t *request, fr_retry_t const *retry)
3905{
3906 rlm_radius_t const *inst = talloc_get_type_abort(xctx->mctx->mi->data, rlm_radius_t);
3907 bio_request_t *u = talloc_get_type_abort(xctx->rctx, bio_request_t);
3908
3909 do_retry(inst, u, request, retry);
3910}
3911
3912/*
3913 * %proxy.sendto.ipaddr(ipaddr, port, secret)
3914 */
3916 xlat_ctx_t const *xctx,
3917 request_t *request, fr_value_box_list_t *args)
3918{
3919 rlm_radius_t const *inst = talloc_get_type_abort(xctx->mctx->mi->data, rlm_radius_t);
3920 bio_thread_t *thread = talloc_get_type_abort(xctx->mctx->thread, bio_thread_t);
3921 fr_value_box_t *ipaddr, *port, *secret;
3922 home_server_t *home;
3923 bio_request_t *u = NULL;
3924 fr_retry_config_t const *retry_config = NULL;
3925 int rcode;
3926 xlat_action_t action;
3927
3928 XLAT_ARGS(args, &ipaddr, &port, &secret);
3929
3930 /*
3931 * The packet code indexes tables which have FR_RADIUS_CODE_MAX entries.
3932 */
3933 if (!FR_RADIUS_PACKET_CODE_VALID(request->packet->code)) {
3934 REDEBUG("Cannot proxy packet code %u, it is not a RADIUS packet code", request->packet->code);
3935 return XLAT_ACTION_FAIL;
3936 }
3937
3938 /*
3939 * Can't change IP address families.
3940 */
3941 if (ipaddr->vb_ip.af != thread->ctx.fd_config.src_ipaddr.af) {
3942 RDEBUG("Invalid destination IP address family in %pV", ipaddr);
3943 return XLAT_ACTION_DONE;
3944 }
3945
3946 fr_rb_find((void **)&home, &thread->bio.expires.tree, &(home_server_t) {
3947 .ctx = {
3948 .fd_config = (fr_bio_fd_config_t) {
3949 .dst_ipaddr = ipaddr->vb_ip,
3950 .dst_port = port->vb_uint16,
3951 },
3952 },
3953 });
3954 if (!home) {
3955 /*
3956 * Track which connections are made to this home server from which open ports.
3957 */
3958 MEM(home = (home_server_t *) talloc_zero_array(thread, uint8_t, sizeof(home_server_t) + sizeof(connection_t *) * thread->num_ports));
3959 talloc_set_type(home, home_server_t);
3960
3961 *home = (home_server_t) {
3962 .ctx = (bio_handle_ctx_t) {
3964 .module_name = inst->name,
3965 .inst = inst,
3966 .limit_source_ports = (thread->num_ports > 0) ? LIMIT_PORTS_DYNAMIC : LIMIT_PORTS_NONE,
3967 .dynamic = true,
3968#ifdef WITH_TLS
3969 .ssl_ctx = thread->ctx.ssl_ctx, /* DTLS to dynamic destinations uses the thread context */
3970#endif
3971 },
3972 .num_ports = thread->num_ports,
3973 };
3974
3975 /*
3976 * Copy the home server configuration from the thread configuration. Then update it with
3977 * the needs of the home server.
3978 */
3979 home->ctx.fd_config = thread->ctx.fd_config;
3980 home->ctx.fd_config.type = FR_BIO_FD_CONNECTED;
3981 home->ctx.fd_config.dst_ipaddr = ipaddr->vb_ip;
3982 home->ctx.fd_config.dst_port = port->vb_uint16;
3983
3984 home->ctx.radius_ctx = (fr_radius_ctx_t) {
3985 .secret = talloc_strdup(home, secret->vb_strvalue),
3986 .secret_length = secret->vb_length,
3987 .proxy_state = inst->common_ctx.proxy_state,
3988 };
3989
3990 /*
3991 * Allocate the trunk and start it up.
3992 */
3993 home->ctx.trunk = trunk_alloc(home, unlang_interpret_event_list(request), &io_funcs,
3994 &inst->trunk_conf, inst->name, home, false, inst->trigger_args);
3995 if (!home->ctx.trunk) {
3996 fail:
3997 talloc_free(home);
3998 return XLAT_ACTION_FAIL;
3999 }
4000
4001 if (!fr_rb_expire_insert(&thread->bio.expires, home, fr_time())) goto fail;
4002 } else {
4003 fr_rb_expire_t *expire = &thread->bio.expires;
4004 fr_time_t now = fr_time();
4005 home_server_t *old;
4006
4007 /*
4008 * We can't change secrets on the fly. The home
4009 * server has to expire first, and then the
4010 * secret can be changed.
4011 */
4012 if ((home->ctx.radius_ctx.secret_length != secret->vb_length) ||
4013 (strcmp(home->ctx.radius_ctx.secret, secret->vb_strvalue) != 0)) {
4014 RWDEBUG("The new secret is not the same as the old secret: Ignoring the new one");
4015 }
4016
4017 fr_rb_expire_update(expire, home, now);
4018
4019 while ((old = fr_dlist_head(&expire->head)) != NULL) {
4020 (void) talloc_get_type_abort(old, home_server_t);
4021
4022 fr_assert(old->ctx.trunk);
4023
4024 /*
4025 * Don't delete the home server we're about to use.
4026 */
4027 if (old == home) break;
4028
4029 /*
4030 * It still has a request allocated, do nothing.
4031 */
4032 if (old->ctx.trunk->req_alloc) break;
4033
4034 /*
4035 * Not yet time to expire.
4036 */
4037 if (fr_time_gt(old->expire.when, now)) break;
4038
4039 fr_dlist_remove(&expire->head, old);
4040 fr_rb_delete(&expire->tree, old);
4041 }
4042 }
4043
4044 /*
4045 * Enqueue the packet on the per-home-server trunk.
4046 */
4047 rcode = mod_enqueue(&u, &retry_config, inst, home->ctx.trunk, request);
4048 if (rcode == 0) return XLAT_ACTION_DONE;
4049
4050 if (rcode < 0) {
4051 REDEBUG("Failed enqueuing packet");
4052 return XLAT_ACTION_FAIL;
4053 }
4054 fr_assert(u != NULL);
4055 fr_assert(retry_config != NULL);
4056
4057 /*
4058 * Start the retry.
4059 *
4060 * @todo - change unlang_xlat_timeout_add() to unlang_xlat_retry_add().
4061 */
4062 fr_retry_init(&u->retry, fr_time(), retry_config);
4063
4066 u, retry_config);
4067
4068 /*
4069 * The xlat is not yielding, so xlat_sendto_signal() will never be called. Remove the request
4070 * from the trunk.
4071 */
4072 if ((action == XLAT_ACTION_FAIL) && u->treq) {
4074 }
4075
4076 return action;
4077}
unlang_action_t
Returned by unlang_op_t calls, determine the next action of the interpreter.
Definition action.h:35
@ UNLANG_ACTION_FAIL
Encountered an unexpected error.
Definition action.h:36
@ UNLANG_ACTION_YIELD
Temporarily pause execution until an event occurs.
Definition action.h:42
static int const char char buffer[256]
Definition acutest.h:641
int const char * file
Definition acutest.h:855
va_list args
Definition acutest.h:923
void int line
Definition acutest.h:810
static ssize_t fr_bio_write(fr_bio_t *bio, void *packet_ctx, void const *buffer, size_t size)
Write raw data to a bio.
Definition base.h:184
static ssize_t fr_bio_read(fr_bio_t *bio, void *packet_ctx, void *buffer, size_t size)
Read raw data from a bio.
Definition base.h:161
void * uctx
user ctx, caller can manually set it.
Definition base.h:114
#define fr_bio_error(_x)
Definition base.h:200
static int packet_ctx
the tests pass only the address of packet_ctx
static uint8_t request[4]
static uint8_t reply[4]
#define NDEBUG_UNUSED
Definition build.h:426
#define FALL_THROUGH
clang 10 doesn't recognised the FALL-THROUGH comment anymore
Definition build.h:422
#define CC_NO_UBSAN(_sanitize)
Definition build.h:540
#define CMP_PREFER_LARGER(_a, _b)
Evaluates to -1 for a > b, and +1 for a < b.
Definition build.h:126
#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:130
#define unlikely(_x)
Definition build.h:492
#define UNUSED
Definition build.h:415
fr_cmp_ret_t
Result of an ordering comparison.
Definition build.h:113
#define FR_DBUFF_TMP(_start, _len_or_end)
Creates a compound literal to pass into functions which accept a dbuff.
Definition dbuff.h:556
static int fr_dcursor_append(fr_dcursor_t *cursor, void *v)
Insert a single item at the end of the list.
Definition dcursor.h:406
#define fr_assert_msg(_x, _msg,...)
Calls panic_action ifndef NDEBUG, else logs error and causes the server to exit immediately with code...
Definition debug.h:248
#define fr_assert_fail(_msg,...)
Calls panic_action ifndef NDEBUG, else logs error.
Definition debug.h:254
#define MEM(x)
Definition debug.h:38
@ FR_RADIUS_CODE_ACCESS_CHALLENGE
RFC2865 - Access-Challenge.
Definition defs.h:43
@ FR_RADIUS_CODE_ACCESS_REQUEST
RFC2865 - Access-Request.
Definition defs.h:33
@ FR_RADIUS_CODE_MAX
Maximum possible protocol code.
Definition defs.h:53
@ FR_RADIUS_CODE_DISCONNECT_ACK
RFC3575/RFC5176 - Disconnect-Ack (positive)
Definition defs.h:47
@ FR_RADIUS_CODE_STATUS_SERVER
RFC2865/RFC5997 - Status Server (request)
Definition defs.h:44
@ FR_RADIUS_CODE_ACCESS_ACCEPT
RFC2865 - Access-Accept.
Definition defs.h:34
@ FR_RADIUS_CODE_ACCOUNTING_RESPONSE
RFC2866 - Accounting-Response.
Definition defs.h:37
@ FR_RADIUS_CODE_COA_NAK
RFC3575/RFC5176 - CoA-Nak (not willing to perform)
Definition defs.h:51
@ FR_RADIUS_CODE_COA_ACK
RFC3575/RFC5176 - CoA-Ack (positive)
Definition defs.h:50
@ FR_RADIUS_CODE_DISCONNECT_NAK
RFC3575/RFC5176 - Disconnect-Nak (not willing to perform)
Definition defs.h:48
@ FR_RADIUS_CODE_PROTOCOL_ERROR
RFC7930 - Protocol-Error (generic NAK)
Definition defs.h:52
@ FR_RADIUS_CODE_ACCOUNTING_REQUEST
RFC2866 - Accounting-Request.
Definition defs.h:36
@ FR_RADIUS_CODE_ACCESS_REJECT
RFC2865 - Access-Reject.
Definition defs.h:35
static fr_dict_attr_t const * attr_packet_type
Definition dhcpclient.c:88
#define ERROR(fmt,...)
Definition dhcpclient.c:40
int main(int argc, char **argv)
Definition dhcpclient.c:530
#define DEBUG(fmt,...)
Definition dhcpclient.c:38
bool fr_dict_compatible(fr_dict_t const *dict1, fr_dict_t const *dict2)
See if two dictionaries have the same end parent.
Definition dict_util.c:2956
static void * fr_dlist_head(fr_dlist_head_t const *list_head)
Return the HEAD item of a list or NULL if the list is empty.
Definition dlist.h:468
static void * fr_dlist_remove(fr_dlist_head_t *list_head, void *ptr)
Remove an item from the list.
Definition dlist.h:620
#define fr_event_fd_insert(...)
Definition event.h:251
void(* fr_event_fd_cb_t)(fr_event_list_t *el, int fd, int flags, void *uctx)
Called when an IO event occurs on a file descriptor.
Definition event.h:154
@ FR_EVENT_FILTER_IO
Combined filter for read/write functions/.
Definition event.h:87
int fr_bio_fd_connect_full(fr_bio_t *bio, fr_event_list_t *el, fr_bio_callback_t connected_cb, fr_bio_callback_t error_cb, fr_time_delta_t *timeout, fr_bio_callback_t timeout_cb)
Finalize a connect()
Definition fd.c:1349
fr_bio_t * fr_bio_fd_alloc(TALLOC_CTX *ctx, fr_bio_fd_config_t const *cfg, size_t offset)
Allocate a FD bio.
Definition fd.c:1116
fr_bio_fd_info_t const * fr_bio_fd_info(fr_bio_t *bio)
Returns a pointer to the bio-specific information.
Definition fd.c:1446
int fr_bio_fd_write_only(fr_bio_t *bio)
Mark up a bio as write-only.
Definition fd.c:1493
fr_socket_t socket
as connected socket
Definition fd.h:145
char const * name
printable name of this BIO
Definition fd.h:150
uint16_t src_port
our port
Definition fd.h:104
bool eof
are we at EOF?
Definition fd.h:154
fr_bio_fd_type_t type
type of the socket
Definition fd.h:147
fr_bio_fd_state_t state
connecting, open, closed, etc.
Definition fd.h:148
uint16_t src_port_start
limit source port ranges for client BIOs
Definition fd.h:107
int connect_errno
from connect() or other APIs
Definition fd.h:156
fr_ipaddr_t dst_ipaddr
their IP address
Definition fd.h:102
@ FR_BIO_FD_CONNECTED
connected client sockets (UDP or TCP)
Definition fd.h:63
@ FR_BIO_FD_UNCONNECTED
unconnected UDP / datagram, but also allowed
Definition fd.h:60
uint16_t src_port_end
limit source port ranges for client BIOs
Definition fd.h:108
int socket_type
SOCK_STREAM or SOCK_DGRAM.
Definition fd.h:95
uint16_t dst_port
their port
Definition fd.h:105
@ FR_BIO_FD_STATE_CONNECTING
Definition fd.h:55
@ FR_BIO_FD_STATE_OPEN
error states must be before this
Definition fd.h:54
fr_socket_t socket
socket information, including FD.
Definition fd.h:47
bool write_blocked
did we block on write?
Definition fd.h:153
fr_ipaddr_t src_ipaddr
our IP address
Definition fd.h:101
Configuration for sockets.
Definition fd.h:92
Run-time status of the socket.
Definition fd.h:144
Per-packet context.
Definition fd.h:46
#define unlang_function_push(_request, _func, _repeat, _signal, _sigmask, _top_frame, _uctx)
Push a generic function onto the unlang stack.
Definition function.h:181
talloc_free(hp)
fr_cmp_ret_t fr_ipaddr_cmp(fr_ipaddr_t const *a, fr_ipaddr_t const *b)
Compare two ip addresses.
Definition inet.c:1353
int af
Address family.
Definition inet.h:64
void unlang_interpret_set(request_t *request, unlang_interpret_t *intp)
Set a specific interpreter for a request.
Definition interpret.c:2759
void unlang_interpret_mark_runnable(request_t *request)
Mark a request as resumable.
Definition interpret.c:2022
unlang_interpret_t * unlang_interpret_get_thread_default(void)
Get the default interpreter for this thread.
Definition interpret.c:2801
unlang_t const * unlang_interpret_instruction(request_t *request)
Get the current instruction.
Definition interpret.c:327
void unlang_interpret_signal(request_t *request, fr_signal_t action)
Send a signal (usually stop) to a request.
Definition interpret.c:1794
int unlang_interpret_force_result(unlang_t const *instruction, unlang_result_t *p_result, fr_timer_list_t *tl, fr_time_delta_t expire)
Set (or clear) a forced result.
Definition interpret.c:350
fr_event_list_t * unlang_interpret_event_list(request_t *request)
Get the event list for the current interpreter.
Definition interpret.c:2778
#define UNLANG_TOP_FRAME
Definition interpret.h:36
el_self ties the lifetime of the event list to the interpreter
void fr_bio_cb_set(fr_bio_t *bio, fr_bio_cb_funcs_t const *cb)
Definition base.c:260
void fr_bio_tls_close_send(fr_bio_tls_t *my)
Send a TLS close_notify alert to the peer.
Definition tls.c:1041
fr_tls_connection_t * fr_bio_tls_conn(fr_bio_tls_t *my)
The TLS connection, so the caller can set conn->name
Definition tls.c:1167
int fr_bio_tls_connect(fr_bio_tls_t *my)
Take the connection through every state which comes before application data.
Definition tls.c:1262
fr_bio_tls_t * fr_bio_tls_alloc(request_t *request, fr_bio_t *next, SSL_CTX *ssl_ctx, bool client, bool client_cert)
Allocate a TLS bio.
Definition tls.c:1115
HIDDEN fr_dict_attr_t const * attr_eap_message
Definition base.c:94
void log_request_proto_pair_list(fr_log_lvl_t lvl, request_t *request, fr_pair_t const *parent, fr_pair_list_t const *vps, char const *prefix)
Print a list of protocol fr_pair_ts.
Definition log.c:905
void log_request_pair_list(fr_log_lvl_t lvl, request_t *request, fr_pair_t const *parent, fr_pair_list_t const *vps, char const *prefix)
Print a fr_pair_list_t.
Definition log.c:831
#define PERROR(_fmt,...)
Definition log.h:233
#define DEBUG3(_fmt,...)
Definition log.h:271
#define RWDEBUG(fmt,...)
Definition log.h:378
#define RWARN(fmt,...)
Definition log.h:314
#define DEBUG4(_fmt,...)
Definition log.h:272
#define RPERROR(fmt,...)
Definition log.h:319
#define RINFO(fmt,...)
Definition log.h:313
#define RPEDEBUG(fmt,...)
Definition log.h:393
#define HEXDUMP3(_data, _len, _fmt,...)
Definition log.h:742
#define RHEXDUMP3(_data, _len, _fmt,...)
Definition log.h:724
int map_to_vp(TALLOC_CTX *ctx, fr_pair_list_t *out, request_t *request, map_t const *map, UNUSED void *uctx)
Convert a map to a fr_pair_t.
Definition map.c:1566
int map_to_request(request_t *request, map_t const *map, radius_map_getvalue_t func, void *ctx)
Convert map_t to fr_pair_t (s) and add them to a request_t.
Definition map.c:1846
#define fr_time()
Definition event.c:61
int fr_event_fd_delete(fr_event_list_t *el, int fd, fr_event_filter_t filter)
Remove a file descriptor from the event loop.
Definition event.c:1244
Stores all information relating to an event list.
Definition event.c:415
fr_log_t default_log
Definition log.c:308
#define fr_log(_log, _lvl, _file, _line, _fmt,...)
Definition log.h:172
@ L_DBG_LVL_3
3rd highest priority debug messages (-xxx | -Xx).
Definition log.h:69
@ L_DBG_LVL_2
2nd highest priority debug messages (-xx | -X).
Definition log.h:68
fr_log_type_t
Definition log.h:51
@ L_ERR
Error message.
Definition log.h:53
fr_packet_t * fr_packet_alloc(TALLOC_CTX *ctx, bool new_vector)
Allocate a new fr_packet_t.
Definition packet.c:38
Minimal data structure to use the new code.
Definition listen.h:80
int unlang_load_balance_persist(request_t *request)
Persist the current load-balance selection.
main_config_t const * main_config
Main server configuration.
Definition main_config.c:56
uint32_t max_workers
for the scheduler
fr_bio_t * fr_bio_mem_alloc(TALLOC_CTX *ctx, size_t read_size, size_t write_size, fr_bio_t *next)
Allocate a memory buffer bio.
Definition mem.c:686
int fr_bio_mem_set_verify(fr_bio_t *bio, fr_bio_verify_t verify, void *verify_ctx, bool datagram)
Set the verification function for memory bios.
Definition mem.c:863
fr_bio_verify_action_t
Status returned by the verification callback.
Definition mem.h:32
@ FR_BIO_VERIFY_ERROR_CLOSE
fatal error, the bio should be closed.
Definition mem.h:36
@ FR_BIO_VERIFY_DISCARD
the packet should be discarded
Definition mem.h:34
@ FR_BIO_VERIFY_OK
packet is OK
Definition mem.h:33
@ FR_BIO_VERIFY_WANT_MORE
not enough data for one packet
Definition mem.h:35
unsigned short uint16_t
@ FR_TYPE_STRING
String of printable characters.
@ FR_TYPE_UINT16
16 Bit unsigned integer.
@ FR_TYPE_UINT32
32 Bit unsigned integer.
@ FR_TYPE_COMBO_IP_ADDR
IPv4 or IPv6 address depending on length.
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
bool fr_radius_ok(uint8_t const *packet, size_t *packet_len_p, uint32_t max_attributes, bool require_message_authenticator, bool radius_1_1, decode_fail_t *reason)
module_instance_t const * mi
Instance of the module being instantiated.
Definition module_ctx.h:42
void * thread
Thread specific instance data.
Definition module_ctx.h:43
void * rctx
Resume ctx that a module previously set.
Definition module_ctx.h:45
fr_event_list_t * el
Event list to register any IO handlers and timers against.
Definition module_ctx.h:68
void * thread
Thread instance data.
Definition module_ctx.h:67
module_instance_t const * mi
Instance of the module being instantiated.
Definition module_ctx.h:64
Temporary structure to hold arguments for module calls.
Definition module_ctx.h:41
Temporary structure to hold arguments for thread_instantiation calls.
Definition module_ctx.h:63
bool radius_1_1
RADIUS/1.1 has been negotiated for this connection.
Definition bio.c:86
static int mod_enqueue(bio_request_t **p_u, fr_retry_config_t const **p_retry_config, rlm_radius_t const *inst, trunk_t *trunk, request_t *request)
Definition bio.c:3468
fr_bio_fd_config_t fd_config
for threads or sockets
Definition bio.c:51
uint32_t token
Last Token assigned to this packet. Only for RADIUS/1.1.
Definition bio.c:173
int num_ports
Definition bio.c:191
static void do_retry(rlm_radius_t const *inst, bio_request_t *u, request_t *request, fr_retry_t const *retry)
Definition bio.c:2355
fr_timer_t * ev
timer for retransmissions
Definition bio.c:182
static void status_check_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
We timed out, without getting a status check reply.
Definition bio.c:2105
static void request_replicate_mux(UNUSED fr_event_list_t *el, trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
Definition bio.c:3131
static void conn_init_error(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, void *uctx)
Connection errored.
Definition bio.c:402
size_t buflen
Receive buffer length.
Definition bio.c:108
static void request_demux(UNUSED fr_event_list_t *el, trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
Definition bio.c:2933
radius_track_t * tt
RADIUS ID tracking structure.
Definition bio.c:110
static void conn_discard(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Read and discard data.
Definition bio.c:1659
uint8_t id
Last ID assigned to this packet.
Definition bio.c:172
static void request_replicate_demux(UNUSED fr_event_list_t *el, trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
Definition bio.c:3153
static void do_signal(rlm_radius_t const *inst, bio_request_t *u, request_t *request, fr_signal_t action)
Definition bio.c:3396
trunk_connection_event_t notify_on
The events which the trunk last asked for.
Definition bio.c:141
bool dynamic
is this a dynamic home server.
Definition bio.c:55
bool status_checking
whether we're doing status checks
Definition bio.c:124
static void bio_connected(fr_bio_t *bio)
Definition bio.c:1152
uint32_t num_replies
number of reply packets, sent is in retry.count
Definition bio.c:164
static const trunk_io_funcs_t io_funcs
Definition bio.c:3602
static void conn_close(UNUSED fr_event_list_t *el, void *handle, void *uctx)
Shutdown/close a file descriptor.
Definition bio.c:1533
uint32_t priority
copied from request->async->priority
Definition bio.c:161
trunk_connection_t * tconn
The trunk connection.
Definition bio.c:139
static rlm_rcode_t radius_code_to_rcode[FR_RADIUS_CODE_MAX]
Turn a reply code into a module rcode;.
Definition bio.c:208
static bool bio_at_eof(bio_handle_t const *h)
Is the connection at EOF?
Definition bio.c:148
static void conn_error(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, void *uctx)
Connection errored.
Definition bio.c:1694
char const * module_name
the module that opened the connection
Definition bio.c:47
fr_bio_fd_info_t const * fd_info
status of the FD.
Definition bio.c:52
connection_t * connections[]
for tracking outbound connections
Definition bio.c:192
static void bio_eof(fr_bio_t *bio)
The BIO chain is at EOF, and has no more data for us.
Definition bio.c:1181
uint8_t * buffer
Receive buffer.
Definition bio.c:107
static void mod_retry(module_ctx_t const *mctx, request_t *request, fr_retry_t const *retry)
Handle module retries.
Definition bio.c:2347
static fr_radius_decode_fail_t decode(TALLOC_CTX *ctx, fr_pair_list_t *reply, uint8_t *response_code, bio_handle_t *h, request_t *request, bio_request_t *u, uint8_t const request_authenticator[static RADIUS_AUTH_VECTOR_LENGTH], uint8_t *data, size_t data_len)
Decode response packet data, extracting relevant information and validating the packet.
Definition bio.c:1848
static int encode(bio_handle_t *h, request_t *request, bio_request_t *u, uint8_t id)
Definition bio.c:1927
fr_time_t last_written
when the last whole packet was last written.
Definition bio.c:178
static void request_conn_release(connection_t *conn, void *preq_to_reset, UNUSED void *uctx)
Clear out anything associated with the handle from the request.
Definition bio.c:3302
bio_handle_ctx_t ctx
common struct for home servers and BIO handles
Definition bio.c:62
static fr_bio_verify_action_t rlm_radius_verify(UNUSED fr_bio_t *bio, void *verify_ctx, UNUSED void *packet_ctx, const void *data, size_t *size)
Definition bio.c:1188
static void mod_write(request_t *request, trunk_request_t *treq, bio_handle_t *h)
Definition bio.c:2509
#define REQUIRE_MA(_h)
fr_pair_list_t extra
VPs for debugging, like Proxy-State.
Definition bio.c:169
bool proxied
is this request being proxied
Definition bio.c:167
uint32_t timeouts
Requests which timed out without a reply since the last reply.
Definition bio.c:116
bool write_blocked
A stream write blocked, and has not yet resumed.
Definition bio.c:88
bool eof
The BIO chain is at EOF, see bio_eof().
Definition bio.c:84
bio_limit_ports_t
Definition bio.c:40
@ LIMIT_PORTS_DYNAMIC
Limited source ports for dynamic home servers.
Definition bio.c:43
@ LIMIT_PORTS_NONE
Source port not restricted.
Definition bio.c:41
@ LIMIT_PORTS_STATIC
Limited source ports for static home servers.
Definition bio.c:42
static fr_cmp_ret_t request_prioritise(void const *one, void const *two)
Definition bio.c:1809
static void bio_tracking_entry_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line, radius_track_entry_t *te)
Log additional information about a tracking entry.
Definition bio.c:254
static xlat_action_t xlat_radius_replicate(UNUSED TALLOC_CTX *ctx, UNUSED fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *args)
Definition bio.c:3757
fr_time_t first_unanswered
When the current run of unanswered requests started.
Definition bio.c:114
radius_track_entry_t * rr
ID tracking, resend count, etc.
Definition bio.c:181
fr_time_t last_reply
When we last received a reply.
Definition bio.c:112
size_t packet_len
Length of the packet.
Definition bio.c:175
static int _bio_handle_free(bio_handle_t *h)
Free a connection handle, closing associated resources.
Definition bio.c:1072
static void conn_writable_flush(fr_event_list_t *el, int fd, int flags, void *uctx)
The fd is writable, and the connection is blocked on write.
Definition bio.c:1709
size_t partial
partially sent data
Definition bio.c:176
fr_event_list_t * el
Event list.
Definition bio.c:49
static int bio_write_blocked(fr_bio_t *bio)
Pause the connection when a stream BIO is blocked on write.
Definition bio.c:697
static void request_cancel(UNUSED connection_t *conn, void *preq_to_reset, trunk_cancel_reason_t reason, UNUSED void *uctx)
Remove the request from any tracking structures.
Definition bio.c:3270
static void home_server_free(void *data)
Definition bio.c:3595
int num_ports
Definition bio.c:70
static void protocol_error_reply(bio_request_t *u, bio_handle_t *h)
Deal with Protocol-Error replies, and possible negotiation.
Definition bio.c:2764
static void status_check_reset(bio_handle_t *h, bio_request_t *u)
Reset a status_check packet, ready to reuse.
Definition bio.c:290
static const trunk_io_funcs_t io_replicate_funcs
Definition bio.c:3614
static void request_fail(request_t *request, NDEBUG_UNUSED void *preq, void *rctx, NDEBUG_UNUSED trunk_request_state_t state, UNUSED void *uctx)
Write out a canned failure.
Definition bio.c:3321
fr_time_t recv_time
copied from request->async->recv_time
Definition bio.c:162
fr_retry_t retry
retransmission timers
Definition bio.c:183
fr_timer_t * zombie_ev
Zombie timeout. Only used when status_check = no.
Definition bio.c:121
static void conn_init_writable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Send initial negotiation.
Definition bio.c:616
static xlat_action_t xlat_radius_client(UNUSED TALLOC_CTX *ctx, UNUSED fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, fr_value_box_list_t *args)
Definition bio.c:3915
struct bio_handle_s bio_handle_t
Track the handle, which is tightly correlated with the FD.
rlm_rcode_t rcode
from the transport
Definition bio.c:159
static void thread_conn_notify(trunk_connection_t *tconn, connection_t *conn, fr_event_list_t *el, trunk_connection_event_t notify_on, void *uctx)
struct bio_handle_s::@227 bio
static void status_check_alloc(bio_handle_t *h)
Definition bio.c:307
static void status_check_reply(trunk_connection_t *tconn, bio_request_t *u, fr_time_t now)
Deal with replies replies to status checks and possible negotiation.
Definition bio.c:2896
trunk_t * trunk
trunk handler
Definition bio.c:50
fr_timer_list_t * tl
Timers for this connection.
Definition bio.c:119
bio_handle_ctx_t ctx
for copying to bio_handle_t
Definition bio.c:187
static int mod_thread_instantiate(module_thread_inst_ctx_t const *mctx)
Instantiate thread data for the submodule.
Definition bio.c:3629
static void bio_error(fr_bio_t *bio)
Definition bio.c:1166
static bool check_for_zombie(request_t *request, trunk_connection_t *tconn, fr_time_t now, fr_time_t last_sent)
Decide whether a request timeout marks the connection as zombie.
Definition bio.c:2219
unlang_t const * instruction
Instruction which triggered the start of the zombie period.
Definition bio.c:122
static void mod_signal(module_ctx_t const *mctx, request_t *request, fr_signal_t action)
Definition bio.c:3387
#define DUP_INTERVAL
Definition bio.c:202
static void conn_init_next(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
Perform the next step of init and negotiation.
Definition bio.c:471
request_t * status_request
Definition bio.c:126
static int _bio_request_free(bio_request_t *u)
Free a bio_request_t.
Definition bio.c:3447
static unlang_action_t mod_resume(unlang_result_t *p_result, module_ctx_t const *mctx, UNUSED request_t *request)
Resume execution of the request, returning the rcode set during trunk execution.
Definition bio.c:3375
static connection_t * thread_conn_alloc(trunk_connection_t *tconn, fr_event_list_t *el, connection_conf_t const *conf, char const *log_prefix, void *uctx)
Definition bio.c:1630
static int conn_write_only(bio_handle_t *h)
Replication is write-only, so the socket never reads.
Definition bio.c:1137
bio_request_t * status_u
for sending status check packets
Definition bio.c:125
static void xlat_sendto_retry(xlat_ctx_t const *xctx, request_t *request, fr_retry_t const *retry)
Definition bio.c:3904
static void bio_request_reset(bio_request_t *u)
Clear out any connection specific resources from a udp request.
Definition bio.c:273
struct bio_thread_t::@226 bio
trunk_request_t * treq
Definition bio.c:158
static void status_check_enqueue(trunk_connection_t *tconn, bio_handle_t *h, bool init)
Queue a status check packet on an open connection, and wait for the reply.
Definition bio.c:2154
static void mux_requeue_if_blocked(trunk_connection_t *tconn)
Requeue packets if the connection is blocked on write.
Definition bio.c:2467
fr_time_t last_sent
last time we wrote a request.
Definition bio.c:113
uint32_t max_packet_size
Our max packet size. may be different from the parent.
Definition bio.c:105
static xlat_action_t xlat_sendto_resume(TALLOC_CTX *ctx, fr_dcursor_t *out, xlat_ctx_t const *xctx, request_t *request, UNUSED fr_value_box_list_t *in)
Definition bio.c:3876
static void status_check_next(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
Send the next status check, after the previous status check got a reply.
Definition bio.c:2877
rlm_radius_t const * inst
our instance
Definition bio.c:48
static connection_state_t conn_init(void **h_out, connection_t *conn, void *uctx)
Initialise a new outbound connection.
Definition bio.c:1266
static void conn_init_readable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Read the connection during the init and negotiation stage.
Definition bio.c:492
connection_t ** connections
Definition bio.c:71
bio_handle_ctx_t ctx
common struct for home servers and BIO handles
Definition bio.c:80
fr_rb_expire_node_t expire
Definition bio.c:189
static void revive_timeout(UNUSED fr_timer_list_t *tl, UNUSED fr_time_t now, void *uctx)
Revive a connection after "revive_interval".
Definition bio.c:2034
uint8_t last_id
Used when replicating to ensure IDs are distributed evenly.
Definition bio.c:102
uint8_t * packet
Packet we write to the network.
Definition bio.c:174
static void conn_init_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
Status check timer when opening the connection for the first time.
Definition bio.c:423
static connection_state_t conn_failed(void *handle, connection_state_t state, UNUSED void *uctx)
Connection failed.
Definition bio.c:1603
bio_limit_ports_t limit_source_ports
What type of port limit is in use.
Definition bio.c:54
fr_radius_ctx_t radius_ctx
for signing packets
Definition bio.c:53
static void mod_dup(request_t *request, bio_request_t *u)
Definition bio.c:2298
static int mod_thread_detach(module_thread_inst_ctx_t const *mctx)
Free thread data for the submodule.
Definition bio.c:3734
uint8_t code
Packet code.
Definition bio.c:171
connection_t * conn
Definition bio.c:100
static void request_mux(UNUSED fr_event_list_t *el, trunk_connection_t *tconn, connection_t *conn, UNUSED void *uctx)
Definition bio.c:2488
static fr_cmp_ret_t home_server_cmp(void const *one, void const *two)
Dynamic home server code.
Definition bio.c:3864
int fd
File descriptor.
Definition bio.c:82
static void request_complete(request_t *request, NDEBUG_UNUSED void *preq, void *rctx, UNUSED void *uctx)
Response has already been written to the rctx at this point.
Definition bio.c:3350
bool status_check
is this packet a status check?
Definition bio.c:166
static xlat_arg_parser_t const xlat_radius_send_args[]
Definition bio.c:3747
static void xlat_sendto_signal(xlat_ctx_t const *xctx, request_t *request, fr_signal_t action)
Definition bio.c:3893
static void zombie_timeout(UNUSED fr_timer_list_t *tl, fr_time_t now, void *uctx)
Mark a connection dead after "zombie_interval".
Definition bio.c:2046
static int bio_write_resume(fr_bio_t *bio)
Resume the connection when a stream BIO can write again.
Definition bio.c:736
Track the handle, which is tightly correlated with the FD.
Definition bio.c:79
Connect request_t to local tracking structure.
Definition bio.c:157
static uint16_t fr_nbo_to_uint16(uint8_t const data[static sizeof(uint16_t)])
Read an unsigned 16bit integer from wire format (big endian)
Definition nbo.h:146
static uint32_t fr_nbo_to_uint32(uint8_t const data[static sizeof(uint32_t)])
Read an unsigned 32bit integer from wire format (big endian)
Definition nbo.h:167
#define RADIUS_HEADER_LENGTH
Definition net.h:80
#define RADIUS_AUTH_VECTOR_LENGTH
Definition net.h:89
int fr_pair_delete_by_da_nested(fr_pair_list_t *list, fr_dict_attr_t const *da)
Delete matching pairs from the specified list, and prune any empty branches.
Definition pair.c:1674
int fr_pair_value_memdup(fr_pair_t *vp, uint8_t const *src, size_t len, bool tainted)
Copy data into an "octets" data type.
Definition pair.c:2906
fr_pair_t * fr_pair_find_by_da_nested(fr_pair_list_t const *list, fr_dict_attr_t const *da)
Find a pair with a matching fr_dict_attr_t, by walking the nested fr_dict_attr_t tree.
Definition pair.c:791
int fr_pair_value_strdup(fr_pair_t *vp, char const *src, bool tainted)
Copy data into an "string" data type.
Definition pair.c:2607
fr_pair_t * fr_pair_find_by_da(fr_pair_list_t const *list, fr_pair_t const *prev, fr_dict_attr_t const *da)
Find the first pair with a matching da.
Definition pair.c:716
int fr_pair_append(fr_pair_list_t *list, fr_pair_t *to_add)
Add a VP to the end of the list.
Definition pair.c:1306
int fr_pair_delete_by_da(fr_pair_list_t *list, fr_dict_attr_t const *da)
Delete matching pairs from the specified list.
Definition pair.c:1650
fr_pair_t * fr_pair_afrom_da(TALLOC_CTX *ctx, fr_dict_attr_t const *da)
Dynamically allocate a new attribute and assign a fr_dict_attr_t.
Definition pair.c:284
void fr_pair_list_init(fr_pair_list_t *list)
Initialise a pair list header.
Definition pair.c:47
static fr_internal_encode_ctx_t encode_ctx
static fr_dict_attr_t const * attr_state
static fr_dict_attr_t const * attr_error_cause
ssize_t fr_radius_decode(TALLOC_CTX *ctx, fr_pair_list_t *out, uint8_t *packet, size_t packet_len, fr_radius_decode_ctx_t *decode_ctx)
Definition base.c:1229
int fr_radius_sign(uint8_t *packet, uint8_t const *vector, uint8_t const *secret, size_t secret_len)
Sign a previously encoded packet.
Definition base.c:365
ssize_t fr_radius_encode(fr_dbuff_t *dbuff, fr_pair_list_t *vps, fr_radius_encode_ctx_t *packet_ctx)
Definition base.c:1047
char const * fr_radius_packet_name[FR_RADIUS_CODE_MAX]
Definition base.c:119
#define fr_assert(_expr)
Definition rad_assert.h:37
static char * secret
#define REDEBUG(fmt,...)
#define RDEBUG(fmt,...)
#define WARN(fmt,...)
static fr_dict_attr_t const * attr_proxy_state
Definition radclient.c:127
static fr_dict_attr_t const * attr_message_authenticator
Definition radclient.c:128
#define INFO(fmt,...)
Definition radict.c:67
bool secure_transport
for TLS
Definition radius.h:130
#define RADIUS_AUTH_VECTOR_OFFSET
Definition radius.h:33
char const * secret
Definition radius.h:127
fr_radius_decode_fail_t
Failure reasons.
Definition radius.h:89
@ FR_RADIUS_FAIL_NONE
Definition radius.h:90
@ FR_RADIUS_FAIL_MA_MISSING
Definition radius.h:108
size_t secret_length
Definition radius.h:128
#define FR_RADIUS_PACKET_CODE_VALID(_x)
Definition radius.h:51
fr_radius_ctx_t const * common
Definition radius.h:162
@ FR_RADIUS_REQUIRE_MA_YES
Require Message-Authenticator.
Definition radius.h:63
@ FR_RADIUS_REQUIRE_MA_AUTO
Only require Message-Authenticator if we've previously received a packet from this client with Messag...
Definition radius.h:64
fr_radius_decode_fail_t reason
reason for decode failure
Definition radius.h:169
TALLOC_CTX * tmp_ctx
for temporary things cleaned up during decoding
Definition radius.h:166
static fr_dict_t const * dict_radius
Definition radsniff.c:93
static rs_t * conf
Definition radsniff.c:52
static fr_dict_attr_t const * attr_extended_attribute_1
Definition radsnmp.c:110
uint32_t fr_rand(void)
Return a 32-bit random number.
Definition rand.c:128
Smaller fast random number generator.
Definition rand.h:54
int fr_rb_find(void **found, fr_rb_tree_t const *tree, void const *data)
Find an element in the tree, returning the data, not the node.
Definition rb.c:586
int 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:767
bool fr_rb_expire_insert(fr_rb_expire_t *expire, void *data, fr_time_t now)
Attempt to find current data in the tree, if it does not exist insert it.
Definition rb_expire.c:39
void fr_rb_expire_update(fr_rb_expire_t *expire, void *data, fr_time_t now)
Definition rb_expire.c:57
#define fr_rb_expire_inline_talloc_init(_expire, _type, _field, _data_cmp, _data_free, _lifetime)
Definition rb_expire.h:50
fr_dlist_head_t head
Definition rb_expire.h:35
fr_rb_tree_t tree
Definition rb_expire.h:34
dlist for expiring old entries
Definition rb_expire.h:44
rlm_rcode_t
Return codes indicating the result of the module call.
Definition rcode.h:44
@ RLM_MODULE_OK
The module is OK, continue.
Definition rcode.h:49
@ RLM_MODULE_FAIL
Module failed, don't reply.
Definition rcode.h:48
@ RLM_MODULE_REJECT
Immediately reject the request.
Definition rcode.h:47
@ RLM_MODULE_UPDATED
OK (pairs modified).
Definition rcode.h:55
@ RLM_MODULE_HANDLED
The module handled the request, so stop.
Definition rcode.h:50
#define RETURN_UNLANG_RCODE(_rcode)
Definition rcode.h:67
#define request_local_alloc_internal(_ctx, _args)
Allocate a new internal request outside of the request pool.
Definition request.h:344
#define request_local_alloc_external(_ctx, _args)
Allocate a new external request outside of the request pool.
Definition request.h:336
Optional arguments for initialising requests.
Definition request.h:288
static int radius_fixups(rlm_radius_t const *inst, request_t *request)
Do any RADIUS-layer fixups for proxying.
Definition rlm_radius.c:619
static fr_dict_attr_t const * attr_nas_identifier
Definition rlm_radius.c:278
static fr_dict_attr_t const * attr_original_packet_code
Definition rlm_radius.c:279
static fr_dict_attr_t const * attr_event_timestamp
Definition rlm_radius.c:272
static fr_dict_attr_t const * attr_response_length
Definition rlm_radius.c:281
fr_radius_require_ma_t require_message_authenticator
Require Message-Authenticator in responses.
Definition rlm_radius.h:87
fr_time_delta_t revive_interval
Definition rlm_radius.h:68
bool track_load_balance
do we track load-balance state
Definition rlm_radius.h:89
fr_retry_config_t retry[FR_RADIUS_CODE_MAX]
Definition rlm_radius.h:99
char const * name
Definition rlm_radius.h:63
uint32_t status_check
code of status-check type
Definition rlm_radius.h:92
rlm_radius_mode_t mode
proxy, client, etc.
Definition rlm_radius.h:83
@ RLM_RADIUS_MODE_XLAT_PROXY
radius.sendto.ipaddr(), but we do look for a reply.
Definition rlm_radius.h:54
@ RLM_RADIUS_MODE_INVALID
Definition rlm_radius.h:49
@ RLM_RADIUS_MODE_PROXY
we proxy to one home server
Definition rlm_radius.h:50
@ RLM_RADIUS_MODE_REPLICATE
to a particular destination
Definition rlm_radius.h:52
@ RLM_RADIUS_MODE_UNCONNECTED_REPLICATE
radius.sendto.ipaddr(), but we don't look for a reply
Definition rlm_radius.h:53
@ RLM_RADIUS_MODE_CLIENT
we are a client to one home server
Definition rlm_radius.h:51
uint32_t max_packet_size
Maximum packet size.
Definition rlm_radius.h:78
uint32_t max_attributes
Maximum number of attributes to decode in response.
Definition rlm_radius.h:85
uint32_t response_timeouts
Requests in a row which have to time out before the connection is zombie.
Definition rlm_radius.h:67
fr_time_delta_t zombie_period
Definition rlm_radius.h:66
static char const * name
static conf_parser_t retry_config[]
Definition rlm_tacacs.c:38
static void fr_rtt_update(fr_rtt_t *r, fr_time_delta_t t)
Update the smoothed round trip time and the variation with a new sample.
Definition rtt.h:96
int fr_schedule_worker_id(void)
Return the worker id for the current thread.
Definition schedule.c:111
void connection_signal_reconnect(connection_t *conn, connection_reason_t reason)
Asynchronously signal the connection should be reconnected.
int connection_signal_on_fd(connection_t *conn, int fd)
Setup the connection to change states to connected or failed based on I/O events.
connection_t * connection_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, connection_funcs_t const *funcs, connection_conf_t const *conf, char const *log_prefix, void const *uctx)
Allocate a new connection.
void connection_signal_connected(connection_t *conn)
Asynchronously signal that the connection is open.
@ CONNECTION_FAILED
Connection is being reconnected because it failed.
Definition connection.h:89
connection_state_t
Definition connection.h:47
@ CONNECTION_STATE_FAILED
Connection has failed.
Definition connection.h:56
@ CONNECTION_STATE_CONNECTED
File descriptor is open (ready for writing).
Definition connection.h:54
@ CONNECTION_STATE_INIT
Init state, sets up connection.
Definition connection.h:51
@ CONNECTION_STATE_CONNECTING
Waiting for connection to establish.
Definition connection.h:52
Holds a complete set of functions for a connection.
Definition connection.h:199
void * data
Module's instance data.
Definition module.h:297
#define pair_append_request(_attr, _da)
Allocate and append a fr_pair_t to the request list.
Definition pair.h:37
#define FR_SIGNAL_ALLOW(_signals)
Signal mask which blocks every signal except the ones in _signals.
Definition signal.h:58
fr_signal_t
Signals that can be generated/processed by request signal handlers.
Definition signal.h:38
@ FR_SIGNAL_DUP
A duplicate request was received.
Definition signal.h:44
@ FR_SIGNAL_NONE
No signals.
Definition signal.h:39
@ FR_SIGNAL_CANCEL
Request has been cancelled.
Definition signal.h:40
init
Enter the EAP-IDENTITY state.
eap_aka_sim_process_conf_t * inst
fr_pair_t * vp
Definition log.h:93
Value pair map.
Definition map.h:77
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
int unlang_subrequest_child_push_and_detach(request_t *request)
Add a child request to the runnable queue.
Definition subrequest.c:503
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:804
char * talloc_typed_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Call talloc vasprintf, setting the type on the new chunk correctly.
Definition talloc.c:621
#define talloc_get_type_abort_const
Definition talloc.h:117
static int talloc_const_free(void const *ptr)
Free const'd memory.
Definition talloc.h:289
#define talloc_strdup(_ctx, _str)
Definition talloc.h:149
#define fr_time_gteq(_a, _b)
Definition time.h:238
#define fr_time_delta_lt(_a, _b)
Definition time.h:285
#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
static fr_cmp_ret_t fr_time_cmp(fr_time_t a, fr_time_t b)
Compare two fr_time_t values.
Definition time.h:934
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_gt(_a, _b)
Definition time.h:237
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
static fr_unix_time_t fr_time_to_unix_time(fr_time_t when)
Convert an fr_time_t (internal time) to our version of unix time (wallclock time)
Definition time.h:706
#define fr_time_delta_gt(_a, _b)
Definition time.h:283
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
fr_timer_list_t * fr_timer_list_lst_alloc(TALLOC_CTX *ctx, fr_timer_list_t *parent)
Allocate a new lst based timer list.
Definition timer.c:1413
An event timer list.
Definition timer.c:65
A timer event.
Definition timer.c:100
#define FR_TIMER_DELETE(_ev_p)
Definition timer.h:105
#define FR_TIMER_DELETE_RETURN(_ev_p)
Definition timer.h:112
#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:124
#define fr_timer_at(...)
Definition timer.h:81
void radius_track_state_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line, radius_track_t *tt, radius_track_log_extra_t extra)
Print out the state of every tracking entry.
Definition track.c:381
int radius_track_entry_update(radius_track_entry_t *te, uint8_t const *vector)
Update a tracking entry with the authentication vector.
Definition track.c:271
radius_track_t * radius_track_alloc(TALLOC_CTX *ctx, bool radius_1_1)
Create an radius_track_t.
Definition track.c:52
radius_track_entry_t * radius_track_entry_find(radius_track_t *tt, uint8_t packet_id, uint8_t const *vector)
Find a tracking entry from a request authenticator.
Definition track.c:344
#define radius_track_entry_release(_te)
Definition track.h:104
void * uctx
Result/resumption context.
Definition track.h:48
uint8_t id
our ID
Definition track.h:51
unsigned int num_requests
number of requests in the allocation
Definition track.h:70
#define radius_track_entry_reserve(_te_out, _ctx, _tt, _request, _code, _uctx)
Definition track.h:96
request_t * request
as always...
Definition track.h:46
Track one request to a response.
Definition track.h:37
void trunk_connection_callback_readable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Standard I/O read function.
Definition trunk.c:4204
void trunk_connection_callback_writable(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Standard I/O write function.
Definition trunk.c:4221
void trunk_request_signal_partial(trunk_request_t *treq)
Signal a partial write.
Definition trunk.c:2150
void trunk_request_signal_fail(trunk_request_t *treq)
Signal that a trunk request failed.
Definition trunk.c:2269
trunk_request_t * trunk_request_alloc(trunk_t *trunk, request_t *request)
(Pre-)Allocate a new trunk request
Definition trunk.c:2615
uint64_t trunk_connection_requests_requeue(trunk_connection_t *tconn, int states, uint64_t max, bool fail_bound)
Move requests off of a connection and requeue elsewhere.
Definition trunk.c:2131
trunk_enqueue_t trunk_request_enqueue_on_conn(trunk_request_t **treq_out, trunk_connection_t *tconn, request_t *request, void *preq, void *rctx, bool ignore_limits)
Enqueue additional requests on a specific connection.
Definition trunk.c:2884
trunk_enqueue_t trunk_request_enqueue(trunk_request_t **treq_out, trunk_t *trunk, request_t *request, void *preq, void *rctx)
Enqueue a request that needs data written to the trunk.
Definition trunk.c:2730
trunk_enqueue_t trunk_request_requeue(trunk_request_t *treq)
Re-enqueue a request on the same connection.
Definition trunk.c:2819
int trunk_connection_pop_request(trunk_request_t **treq_out, trunk_connection_t *tconn)
Pop a request off a connection's pending queue.
Definition trunk.c:4073
void trunk_request_signal_cancel(trunk_request_t *treq)
Cancel a trunk request.
Definition trunk.c:2289
trunk_t * trunk_alloc(TALLOC_CTX *ctx, fr_event_list_t *el, trunk_io_funcs_t const *funcs, trunk_conf_t const *conf, char const *log_prefix, void const *uctx, bool delay_start, fr_pair_list_t *trigger_args)
Allocate a new collection of connections.
Definition trunk.c:5407
void trunk_request_free(trunk_request_t **treq_to_free)
If the trunk request is freed then update the target requests.
Definition trunk.c:2459
void trunk_connection_signal_active(trunk_connection_t *tconn)
Signal a trunk connection is no longer full.
Definition trunk.c:4150
void trunk_connection_signal_inactive(trunk_connection_t *tconn)
Signal a trunk connection cannot accept more requests.
Definition trunk.c:4127
void trunk_request_signal_sent(trunk_request_t *treq)
Signal that the request was written to a connection successfully.
Definition trunk.c:2171
void trunk_request_signal_complete(trunk_request_t *treq)
Signal that a trunk request is complete.
Definition trunk.c:2215
void trunk_connection_signal_reconnect(trunk_connection_t *tconn, connection_reason_t reason)
Signal a trunk connection is no longer viable.
Definition trunk.c:4189
void trunk_request_state_log(fr_log_t const *log, fr_log_type_t log_type, char const *file, int line, trunk_request_t const *treq)
Definition trunk.c:2985
bool trunk_connection_in_state(trunk_connection_t *tconn, int state)
Returns true if the trunk connection is in one of the specified states.
Definition trunk.c:4237
Associates request queues with a connection.
Definition trunk.c:137
Wraps a normal request.
Definition trunk.c:99
Main trunk management handle.
Definition trunk.c:219
trunk_connection_event_t
What type of I/O events the trunk connection is currently interested in receiving.
Definition trunk.h:82
@ TRUNK_CONN_EVENT_BOTH
Trunk should be notified if a connection is readable or writable.
Definition trunk.h:89
@ TRUNK_CONN_EVENT_WRITE
Trunk should be notified if a connection is writable.
Definition trunk.h:87
@ TRUNK_CONN_EVENT_NONE
Don't notify the trunk on connection state changes.
Definition trunk.h:83
@ TRUNK_CONN_EVENT_READ
Trunk should be notified if a connection is readable.
Definition trunk.h:85
#define TRUNK_REQUEST_STATE_ALL
All request states.
Definition trunk.h:222
@ TRUNK_CONN_INACTIVE
Connection is inactive and can't accept any more requests.
Definition trunk.h:106
trunk_connection_alloc_t connection_alloc
Allocate a new connection_t.
Definition trunk.h:778
@ TRUNK_ENQUEUE_DST_UNAVAILABLE
Destination is down.
Definition trunk.h:180
@ TRUNK_ENQUEUE_FAIL
General internal sanity check failure.
Definition trunk.h:181
@ TRUNK_ENQUEUE_OK
Operation was successful.
Definition trunk.h:177
@ TRUNK_ENQUEUE_NO_CAPACITY
At maximum number of connections, and no connection has capacity.
Definition trunk.h:178
@ TRUNK_ENQUEUE_IN_BACKLOG
Request should be enqueued in backlog.
Definition trunk.h:176
trunk_request_state_t
Used for sanity checks and to simplify freeing.
Definition trunk.h:188
@ TRUNK_REQUEST_STATE_PARTIAL
Some of the request was written to the socket, more of it should be written later.
Definition trunk.h:197
@ TRUNK_REQUEST_STATE_REAPABLE
Request has been written, needs to persist, but we are not currently waiting for any response.
Definition trunk.h:200
@ TRUNK_REQUEST_STATE_UNASSIGNED
Transition state - Request currently not assigned to any connection.
Definition trunk.h:192
@ TRUNK_REQUEST_STATE_INIT
Initial state.
Definition trunk.h:189
@ TRUNK_REQUEST_STATE_CANCEL_SENT
We've informed the remote server that the request has been cancelled.
Definition trunk.h:212
@ TRUNK_REQUEST_STATE_COMPLETE
The request is complete.
Definition trunk.h:209
@ TRUNK_REQUEST_STATE_FAILED
The request failed.
Definition trunk.h:210
@ TRUNK_REQUEST_STATE_CANCEL
A request on a particular socket was cancel.
Definition trunk.h:211
@ TRUNK_REQUEST_STATE_CANCEL_PARTIAL
We partially wrote a cancellation request.
Definition trunk.h:214
@ TRUNK_REQUEST_STATE_BACKLOG
In the backlog.
Definition trunk.h:194
@ TRUNK_REQUEST_STATE_CANCEL_COMPLETE
Remote server has acknowledged our cancellation.
Definition trunk.h:215
@ TRUNK_REQUEST_STATE_PENDING
In the queue of a connection and is pending writing.
Definition trunk.h:195
@ TRUNK_REQUEST_STATE_SENT
Was written to a socket. Waiting for a response.
Definition trunk.h:199
trunk_cancel_reason_t
Reasons for a request being cancelled.
Definition trunk.h:56
@ TRUNK_CANCEL_REASON_REQUEUE
A previously sent request is being requeued.
Definition trunk.h:60
I/O functions to pass to trunk_alloc.
Definition trunk.h:777
static fr_event_list_t * el
xlat_action_t unlang_xlat_yield_to_retry(request_t *request, xlat_func_t resume, fr_unlang_xlat_retry_t retry, xlat_func_signal_t signal, fr_signal_t sigmask, void *rctx, fr_retry_config_t const *retry_cfg)
Yield a request back to the interpreter, with retries.
Definition xlat.c:663
xlat_action_t
Definition xlat.h:37
@ XLAT_ACTION_FAIL
An xlat function failed.
Definition xlat.h:44
@ XLAT_ACTION_DONE
We're done evaluating this level of nesting.
Definition xlat.h:43
#define XLAT_ARGS(_list,...)
Populate local variables with value boxes from the input list.
Definition xlat.h:373
unsigned int required
Argument must be present, and non-empty.
Definition xlat.h:136
#define XLAT_ARG_PARSER_TERMINATOR
Definition xlat.h:160
Definition for a single argument consumed by an xlat function.
Definition xlat.h:135
A node in a graph of unlang_op_t (s) that we execute.
bool fr_pair_list_empty(fr_pair_list_t const *list)
Is a valuepair list empty.
void fr_pair_list_free(fr_pair_list_t *list)
Free memory used by a valuepair list.
void fr_pair_list_append(fr_pair_list_t *dst, fr_pair_list_t *src)
Appends a list of fr_pair_t from a temporary list to a destination list.
fr_retry_state_t fr_retry_next(fr_retry_t *r, fr_time_t now)
Initialize a retransmission counter.
Definition retry.c:110
void fr_retry_init(fr_retry_t *r, fr_time_t now, fr_retry_config_t const *config)
Initialize a retransmission counter.
Definition retry.c:36
fr_time_t start
when we started the retransmission
Definition retry.h:53
fr_time_delta_t rt
retransmit interval
Definition retry.h:57
uint32_t mrc
Maximum retransmission count.
Definition retry.h:36
fr_retry_config_t const * config
master configuration
Definition retry.h:52
fr_retry_state_t state
so callers can see what state it's in.
Definition retry.h:60
uint32_t count
number of sent packets
Definition retry.h:58
fr_time_delta_t mrd
Maximum retransmission duration.
Definition retry.h:35
fr_time_t updated
last update, really a cached "now".
Definition retry.h:56
@ FR_RETRY_MRC
reached maximum retransmission count
Definition retry.h:47
@ FR_RETRY_CONTINUE
Definition retry.h:46
@ FR_RETRY_MRD
reached maximum retransmission duration
Definition retry.h:48
fr_time_t next
when the next timer should be set
Definition retry.h:55
int af
AF_INET, AF_INET6, or AF_UNIX.
Definition socket.h:83
int fd
File descriptor if this is a live socket.
Definition socket.h:86
char const * fr_strerror(void)
Get the last library error.
Definition strerror.c:558
#define fr_value_box_alloc(_ctx, _type, _enumv)
Allocate a value box of a specific type.
Definition value.h:668
static fr_sbuff_err_t char size_t fr_sbuff_t * in
Definition value.h:1061
#define fr_box_ipaddr(_val)
Definition value.h:348
static fr_slen_t data
Definition value.h:1366
static fr_sbuff_err_t char ** out
Definition value.h:1061
#define fr_box_time_delta(_val)
Definition value.h:397
int nonnull(2, 5))
void * rctx
Resume context.
Definition xlat_ctx.h:54
module_ctx_t const * mctx
Synthesised module calling ctx.
Definition xlat_ctx.h:52
An xlat calling ctx.
Definition xlat_ctx.h:49