The FreeRADIUS server $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
Loading...
Searching...
No Matches
state.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: 714b0c54ab2b2eb0d725a0519599389a6c124532 $
19 *
20 * @brief Multi-packet state handling
21 * @file src/lib/server/state.c
22 *
23 * @ingroup AVP
24 *
25 * For each round of a multi-round authentication method such as EAP,
26 * or a 2FA method such as OTP, a state entry will be created. The state
27 * entry holds data that should be available during the complete lifecycle
28 * of the authentication attempt.
29 *
30 * When a request is complete, #fr_request_to_state is called to transfer
31 * ownership of the state fr_pair_ts and state_ctx (which the fr_pair_ts
32 * are allocated in) to a #fr_state_entry_t. This #fr_state_entry_t holds the
33 * value of the State attribute, that will be send out in the response.
34 *
35 * When the next request is received, #fr_state_to_request is called to transfer
36 * the fr_pair_ts and state ctx to the new request.
37 *
38 * The ownership of the state_ctx and state fr_pair_ts is transferred as below:
39 *
40 * @verbatim
41 request -> state_entry -> request -> state_entry -> request -> free()
42 \-> reply \-> reply \-> access-reject/access-accept
43 * @endverbatim
44 *
45 * @copyright 2014 The FreeRADIUS server project
46 */
47RCSID("$Id: 714b0c54ab2b2eb0d725a0519599389a6c124532 $")
48
49#include <freeradius-devel/server/request.h>
50#include <freeradius-devel/server/request_data.h>
51#include <freeradius-devel/server/state.h>
52
53#include <freeradius-devel/io/listen.h>
54
55#include <freeradius-devel/util/debug.h>
56#include <freeradius-devel/util/md5.h>
57#include <freeradius-devel/util/rand.h>
58
59/** Holds a state value, and associated fr_pair_ts and data
60 *
61 */
62typedef struct {
63 uint64_t id; //!< State number within state heap.
64 fr_rb_node_t node; //!< Entry in the state rbtree.
65 union {
66 /** Server ID components
67 *
68 * State values should be unique to a given server
69 */
70 struct state_comp {
71 uint8_t tries; //!< Number of rounds so far in this state sequence.
72 uint8_t tx; //!< Bits changed in the tries counter for this round.
73 uint8_t r_0; //!< Random component.
74 uint8_t server_id; //!< Configured server ID. Used for debugging
75 //!< to locate authentication sessions originating
76 //!< from a particular backend authentication server.
77
78 uint32_t context_id; //!< Hash of the current virtual server, xor'd with
79 //!< r1, r2, r3, r4 after the original state value
80 //!< is sent, but before the state entry is inserted
81 //!< into the tree. The receiving virtual server
82 //!< xor's its hash with the received state before
83 //!< performing the lookup. This means one virtual
84 //!< server can't act on a state entry generated by
85 //!< another, even though the state tree is global
86 //!< to all virtual servers.
87
88 uint8_t vx_0; //!< Random component.
89 uint8_t r_5; //!< Random component.
90 uint8_t vx_1; //!< Random component.
91 uint8_t r_6; //!< Random component.
92
93 uint8_t vx_2; //!< Random component.
94 uint8_t vx_3; //!< Random component.
95 uint8_t r_8; //!< Random component.
96 uint8_t r_9; //!< Random component.
97 } state_comp;
98
99 uint8_t state[sizeof(struct state_comp)]; //!< State value in binary.
100 };
101
102 uint64_t seq_start; //!< Number of first request in this sequence.
103 fr_time_t cleanup; //!< When this entry should be cleaned up.
104
105 /*
106 * Should only even be in one at a time
107 */
108 union {
109 fr_dlist_t expire_entry; //!< Entry in the list of things to expire.
110 fr_dlist_t free_entry; //!< Entry in the list of things to free.
111 };
112
113 int tries;
114
115 fr_pair_t *ctx; //!< for all session specific data.
116
117 fr_dlist_head_t data; //!< Persistable request data, also parented by ctx.
118
119 request_t *thawed; //!< The request that thawed this entry.
120
121 fr_state_tree_t *state_tree; //!< Tree this entry belongs to.
123
124/** A child of a fr_state_entry_t
125 *
126 * Children are tracked using the request data of parents.
127 *
128 * request data is added with identifiers that uniquely identify the
129 * subrequest it should be restored to.
130 *
131 * In this way a top level fr_state_entry_t can hold the session
132 * information for multiple children, and the children may hold
133 * state_child_entry_ts for grandchildren.
134 */
135typedef struct {
136 fr_pair_t *ctx; //!< for all session specific data.
137
138 fr_dlist_head_t data; //!< Persistable request data, also parented by ctx.
139
140 request_t *thawed; //!< The request that thawed this entry.
142
144 uint64_t id; //!< Next ID to assign.
145 uint64_t timed_out; //!< Number of states that were cleaned up due to
146 //!< timeout.
147 uint32_t max_sessions; //!< Maximum number of sessions we track.
148 uint32_t used_sessions; //!< How many sessions are currently in progress.
149 fr_rb_tree_t *tree; //!< rbtree used to lookup state value.
150 fr_dlist_head_t to_expire; //!< Linked list of entries to free.
151
152 fr_time_delta_t timeout; //!< How long to wait before cleaning up state entries.
153
154 bool thread_safe; //!< Whether we lock the tree whilst modifying it.
155 pthread_mutex_t mutex; //!< Synchronisation mutex.
156
157 uint8_t server_id; //!< ID to use for load balancing.
158 uint32_t context_id; //!< ID binding state values to a context such
159 ///< as a virtual server.
160
161 fr_dict_attr_t const *da; //!< State attribute used.
162};
163
164#define PTHREAD_MUTEX_LOCK if (state->thread_safe) pthread_mutex_lock
165#define PTHREAD_MUTEX_UNLOCK if (state->thread_safe) pthread_mutex_unlock
166
167static void state_entry_unlink(fr_state_tree_t *state, fr_state_entry_t *entry);
168
169/** Compare two fr_state_entry_t based on their state value i.e. the value of the attribute
170 *
171 */
172static int8_t state_entry_cmp(void const *one, void const *two)
173{
174 fr_state_entry_t const *a = one, *b = two;
175 int ret;
176
177 ret = memcmp(a->state, b->state, sizeof(a->state));
178 return CMP(ret, 0);
179}
180
181/** Free the state tree
182 *
183 */
185{
186 fr_state_entry_t *entry;
187
188 if (state->thread_safe) pthread_mutex_destroy(&state->mutex);
189
190 DEBUG4("Freeing state tree %p", state);
191
192 while ((entry = fr_dlist_head(&state->to_expire))) {
193 DEBUG4("Freeing state entry %p (%"PRIu64")", entry, entry->id);
194 state_entry_unlink(state, entry);
195 talloc_free(entry);
196 }
197
198 /*
199 * Free the rbtree
200 */
201 talloc_free(state->tree);
202
203 return 0;
204}
205
206/** Initialise a new state tree
207 *
208 * @param[in] ctx to link the lifecycle of the state tree to.
209 * @param[in] da Attribute used to store and retrieve state from.
210 * @param[in] thread_safe Whether we should mutex protect the state tree.
211 * @param[in] max_sessions we track state for.
212 * @param[in] timeout How long to wait before cleaning up entries.
213 * @param[in] server_id ID byte to use in load-balancing operations.
214 * @param[in] context_id Specifies a unique ctx id to prevent states being
215 * used in contexts for which they weren't intended.
216 * @return
217 * - A new state tree.
218 * - NULL on failure.
219 */
220fr_state_tree_t *fr_state_tree_init(TALLOC_CTX *ctx, fr_dict_attr_t const *da, bool thread_safe,
221 uint32_t max_sessions, fr_time_delta_t timeout,
222 uint8_t server_id, uint32_t context_id)
223{
224 fr_state_tree_t *state;
225
226 state = talloc_zero(NULL, fr_state_tree_t);
227 if (!state) return 0;
228
229 state->max_sessions = max_sessions;
230 state->timeout = timeout;
231
232 /*
233 * Create a break in the contexts.
234 * We still want this to be freed at the same time
235 * as the parent, but we also need it to be thread
236 * safe, and multiple threads could be using the
237 * tree.
238 */
239 talloc_link_ctx(ctx, state);
240
241 if (thread_safe && (pthread_mutex_init(&state->mutex, NULL) != 0)) {
242 talloc_free(state);
243 return NULL;
244 }
245
246 fr_dlist_talloc_init(&state->to_expire, fr_state_entry_t, free_entry);
247
248 /*
249 * We need to do controlled freeing of the
250 * rbtree, so that all the state entries
251 * are freed before it's destroyed. Hence
252 * it being parented from the NULL ctx.
253 */
255 if (!state->tree) {
256 talloc_free(state);
257 return NULL;
258 }
259 talloc_set_destructor(state, _state_tree_free);
260
261 state->da = da; /* Remember which attribute we use to load/store state */
262 state->server_id = server_id;
263 state->context_id = context_id;
264 state->thread_safe = thread_safe;
265
266 return state;
267}
268
269/** Unlink an entry and remove if from the tree
270 *
271 */
272static inline CC_HINT(always_inline)
274{
275 /*
276 * Check the memory is still valid
277 */
278 (void) talloc_get_type_abort(entry, fr_state_entry_t);
279
280 fr_dlist_remove(&state->to_expire, entry);
281 fr_rb_delete(state->tree, entry);
282
283 DEBUG4("State ID %" PRIu64 " unlinked", entry->id);
284}
285
286/** Frees any data associated with a state
287 *
288 */
290{
291#ifdef WITH_VERIFY_PTR
292 fr_dcursor_t cursor;
293 fr_pair_t *vp;
294
295 /*
296 * Verify all state attributes are parented
297 * by the state context.
298 */
299 if (entry->ctx) {
300 for (vp = fr_pair_dcursor_init(&cursor, &entry->ctx->children);
301 vp;
302 vp = fr_dcursor_next(&cursor)) {
303 fr_assert(entry->ctx == talloc_parent(vp));
304 }
305 }
306
307 /*
308 * Ensure any request data is parented by us
309 * so we know it'll be cleaned up.
310 */
311 (void)fr_cond_assert(request_data_verify_parent(entry->ctx, &entry->data));
312#endif
313
314 /*
315 * Should also free any state attributes
316 */
317 if (entry->ctx) TALLOC_FREE(entry->ctx);
318
319 DEBUG4("State ID %" PRIu64 " freed", entry->id);
320
321 entry->state_tree->used_sessions--;
322
323 return 0;
324}
325
326/** Create a new state entry
327 *
328 * @note Called with the mutex held.
329 */
331 fr_pair_list_t *reply_list, fr_state_entry_t *old)
332{
333 size_t i;
334 uint32_t x;
335 fr_time_t now = fr_time();
336 fr_pair_t *vp;
337 fr_state_entry_t *entry, *next;
338
339 uint8_t old_state[sizeof(old->state)];
340 int old_tries = 0;
341 uint64_t timed_out = 0;
342 bool too_many = false;
343 fr_dlist_head_t to_free;
344
345 /*
346 * Shouldn't be in any lists if it's being reused
347 */
348 fr_assert(!old ||
349 (!fr_dlist_entry_in_list(&old->expire_entry) &&
351
352 fr_dlist_init(&to_free, fr_state_entry_t, free_entry);
353
354 /*
355 * Clean up expired entries
356 */
357 for (entry = fr_dlist_head(&state->to_expire);
358 entry != NULL;
359 entry = next) {
360 (void)talloc_get_type_abort(entry, fr_state_entry_t); /* Allow examination */
361 next = fr_dlist_next(&state->to_expire, entry); /* Advance *before* potential unlinking */
362
363 if (entry == old) continue;
364
365 /*
366 * Too old, we can delete it.
367 */
368 if (fr_time_lt(entry->cleanup, now)) {
369 state_entry_unlink(state, entry);
370 fr_dlist_insert_tail(&to_free, entry);
371 timed_out++;
372 continue;
373 }
374
375 break;
376 }
377
378 state->timed_out += timed_out;
379
380 if (!old) {
381 too_many = (state->used_sessions == (uint32_t) state->max_sessions);
382 if (!too_many) state->used_sessions++; /* preemptively increment whilst we hold the mutex */
383 } else {
384 old_tries = old->tries;
385 memcpy(old_state, old->state, sizeof(old_state));
386 }
387
389
390 if (timed_out > 0) RWDEBUG("Cleaning up %"PRIu64" timed out state entries", timed_out);
391
392 /*
393 * Now free the unlinked entries.
394 *
395 * We do it here as freeing may involve significantly more
396 * work than just freeing the data.
397 *
398 * If there's request data that was persisted it will now
399 * be freed also, and it may have complex destructors associated
400 * with it.
401 */
402 while ((entry = fr_dlist_head(&to_free)) != NULL) {
403 fr_dlist_remove(&to_free, entry);
404 talloc_free(entry);
405 }
406
407 /*
408 * Have to do this post-cleanup, else we end up returning with
409 * a list full of entries to free with none of them being
410 * freed which is bad...
411 */
412 if (too_many) {
413 RERROR("Failed inserting state entry - At maximum ongoing session limit (%u)",
414 state->max_sessions);
415 PTHREAD_MUTEX_LOCK(&state->mutex); /* Caller expects this to be locked */
416 return NULL;
417 }
418
419 /*
420 * Allocation doesn't need to occur inside the critical region
421 * and would add significantly to contention.
422 */
423 if (!old) {
424 MEM(entry = talloc_zero(NULL, fr_state_entry_t));
425 talloc_set_destructor(entry, _state_entry_free);
426 /* tree->used_sessions incremented above */
427 /*
428 * Reuse the old state entry cleaning up any memory associated
429 * with it.
430 */
431 } else {
433 talloc_free_children(old);
434 memset(old, 0, sizeof(*old));
435 entry = old;
436 }
437
438 entry->state_tree = state;
439
441
442 entry->id = state->id++;
443
444 /*
445 * Limit the lifetime of this entry based on how long the
446 * server takes to process a request. Doing it this way
447 * isn't perfect, but it's reasonable, and it's one less
448 * thing for an administrator to configure.
449 */
450 entry->cleanup = fr_time_add(now, state->timeout);
451
452 /*
453 * Some modules create their own magic
454 * state attributes. If a state value already exists
455 * int the reply, we use that in preference to the
456 * old state.
457 */
458 vp = fr_pair_find_by_da(reply_list, NULL, state->da);
459 if (vp) {
460 if (DEBUG_ENABLED && (vp->vp_length > sizeof(entry->state))) {
461 WARN("State too long, will be truncated. Expected <= %zd bytes, got %zu bytes",
462 sizeof(entry->state), vp->vp_length);
463 }
464
465 /*
466 * Assume our own State first.
467 */
468 if (vp->vp_length == sizeof(entry->state)) {
469 memcpy(entry->state, vp->vp_octets, sizeof(entry->state));
470
471 /*
472 * Too big? Get the MD5 hash, in order
473 * to depend on the entire contents of State.
474 */
475 } else if (vp->vp_length > sizeof(entry->state)) {
476 fr_md5_calc(entry->state, vp->vp_octets, vp->vp_length);
477
478 /*
479 * Too small? Use the whole thing, and
480 * set the rest of my_entry.state to zero.
481 */
482 } else {
483 memcpy(entry->state, vp->vp_octets, vp->vp_length);
484 memset(&entry->state[vp->vp_length], 0, sizeof(entry->state) - vp->vp_length);
485 }
486 } else {
487 /*
488 * Base the new state on the old state if we had one.
489 */
490 if (old) {
491 memcpy(entry->state, old_state, sizeof(entry->state));
492 entry->tries = old_tries + 1;
493 /*
494 * 16 octets of randomness should be enough to
495 * have a globally unique state.
496 */
497 } else {
498 for (i = 0; i < sizeof(entry->state) / sizeof(x); i++) {
499 x = fr_rand();
500 memcpy(entry->state + (i * 4), &x, sizeof(x));
501 }
502 }
503
504 entry->state_comp.tries = entry->tries + 1;
505
506 entry->state_comp.tx = entry->state_comp.tries ^ entry->tries;
507
508 entry->state_comp.vx_0 = entry->state_comp.r_0 ^
509 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 24) & 0xff);
510 entry->state_comp.vx_1 = entry->state_comp.r_0 ^
511 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 16) & 0xff);
512 entry->state_comp.vx_2 = entry->state_comp.r_0 ^
513 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 8) & 0xff);
514 entry->state_comp.vx_3 = entry->state_comp.r_0 ^
515 (((uint32_t) HEXIFY(RADIUSD_VERSION)) & 0xff);
516
517 /*
518 * Allow a portion of the State attribute to be set,
519 * this is useful for debugging purposes.
520 */
521 entry->state_comp.server_id = state->server_id;
522
523 MEM(vp = fr_pair_afrom_da(request->reply_ctx, state->da));
524 fr_pair_value_memdup(vp, entry->state, sizeof(entry->state), false);
525 fr_pair_append(reply_list, vp);
526 }
527
528 DEBUG4("State ID %" PRIu64 " created, value 0x%pH, expires %pV",
529 entry->id, fr_box_octets(entry->state, sizeof(entry->state)),
531
532 PTHREAD_MUTEX_LOCK(&state->mutex);
533
534 /*
535 * XOR the server hash with four bytes of random data.
536 * We XOR is again before resolving, to ensure state lookups
537 * only succeed in the virtual server that created the state
538 * value.
539 */
540 *((uint32_t *)(&entry->state_comp.context_id)) ^= state->context_id;
541
542 if (!fr_rb_insert(state->tree, entry)) {
543 RERROR("Failed inserting state entry - Insertion into state tree failed");
544 fr_pair_delete_by_da(reply_list, state->da);
545 talloc_free(entry);
546 return NULL;
547 }
548
549 /*
550 * Link it to the end of the list, which is implicitly
551 * ordered by cleanup time.
552 */
553 fr_dlist_insert_tail(&state->to_expire, entry);
554
555 return entry;
556}
557
558/** Find the entry based on the State attribute and remove it from the state tree
559 *
560 */
562{
563 fr_state_entry_t *entry, my_entry;
564
565 /*
566 * Assume our own State first.
567 */
568 if (vb->vb_length == sizeof(my_entry.state)) {
569 memcpy(my_entry.state, vb->vb_octets, sizeof(my_entry.state));
570
571 /*
572 * Too big? Get the MD5 hash, in order
573 * to depend on the entire contents of State.
574 */
575 } else if (vb->vb_length > sizeof(my_entry.state)) {
576 fr_md5_calc(my_entry.state, vb->vb_octets, vb->vb_length);
577
578 /*
579 * Too small? Use the whole thing, and
580 * set the rest of my_entry.state to zero.
581 */
582 } else {
583 memcpy(my_entry.state, vb->vb_octets, vb->vb_length);
584 memset(&my_entry.state[vb->vb_length], 0, sizeof(my_entry.state) - vb->vb_length);
585 }
586
587 /*
588 * Make it unique for different virtual servers handling the same request
589 */
590 my_entry.state_comp.context_id ^= state->context_id;
591
592 entry = fr_rb_remove(state->tree, &my_entry);
593 if (entry) {
594 (void) talloc_get_type_abort(entry, fr_state_entry_t);
595 fr_dlist_remove(&state->to_expire, entry);
596 }
597
598 return entry;
599}
600
601/** Called when sending an Access-Accept/Access-Reject to discard state information
602 *
603 */
605{
606 fr_state_entry_t *entry;
607 fr_pair_t *vp;
608
609 vp = fr_pair_find_by_da(&request->request_pairs, NULL, state->da);
610 if (!vp) return;
611
612 PTHREAD_MUTEX_LOCK(&state->mutex);
613 entry = state_entry_find_and_unlink(state, &vp->data);
614 if (!entry) {
616 return;
617 }
619
620 /*
621 * If fr_state_to_request was never called, this ensures
622 * the state owned by entry is freed, otherwise this is
623 * mostly a NOOP, other than freeing the memory held by
624 * the entry.
625 */
626 TALLOC_FREE(entry);
627
628 /*
629 * If fr_state_to_request was called, then the request
630 * holds the existing state data. We need to destroy it,
631 * and return the request to the state it was in when
632 * it was first allocated, just in case a user does something
633 * stupid like add more session-state attributes
634 * in one of the later sections.
635 */
636 talloc_free(request_state_replace(request, NULL));
637
638 RDEBUG3("%s - discarded", state->da->name);
639
640 return;
641}
642
643/** Copy a pointer to the head of the list of state fr_pair_ts (and their ctx) into the request
644 *
645 * @note Does not copy the actual fr_pair_ts. The fr_pair_ts and their context
646 * are transferred between state entries as the conversation progresses.
647 *
648 * @note Called with the mutex free.
649 *
650 * @param[in] state tree to lookup state in.
651 * @param[in] request to restore state for.
652 * @return
653 * - 2 if the state attribute didn't match any known states.
654 * - 1 if no state attribute existed.
655 * - 0 on success (state restored)
656 * - -1 if a state entry has already been thawed by a another request.
657 */
659{
660 fr_state_entry_t *entry;
661 fr_pair_t *vp;
662
663 /*
664 * No State, don't do anything.
665 */
666 vp = fr_pair_find_by_da(&request->request_pairs, NULL, state->da);
667 if (!vp) {
668 RDEBUG3("No request.%s attribute, can't restore session-state", state->da->name);
669 if (request->seq_start == 0) request->seq_start = request->number; /* Need check for fake requests */
670 return 1;
671 }
672
673 PTHREAD_MUTEX_LOCK(&state->mutex);
674 entry = state_entry_find_and_unlink(state, &vp->data);
675 if (!entry) {
677 RDEBUG2("No state entry matching request.%pP found", vp);
678 return 2;
679 }
681
682 /* Probably impossible in the current code */
683 if (unlikely(entry->thawed != NULL)) {
684 RERROR("State entry has already been thawed by a request %"PRIu64, entry->thawed->number);
685 return -2;
686 }
687
688 /*
689 * Discard any existing session state, and replace it
690 * with the cached one.
691 */
692 fr_assert(entry->ctx);
693 talloc_free(request_state_replace(request, entry->ctx));
694 entry->ctx = NULL;
695
696 request->seq_start = entry->seq_start;
697
698 /*
699 * Associate old state with the request
700 *
701 * If the request is freed, it's freed immediately.
702 *
703 * Otherwise, if there's another round, we reuse
704 * the state entry and insert it back into the
705 * tree.
706 */
707 request_data_add(request, state, 0, entry, true, true, false);
708 request_data_restore(request, &entry->data);
709
710 entry->thawed = request;
711
712 if (!fr_pair_list_empty(&request->session_state_pairs)) {
713 RDEBUG2("Restored session-state");
714 log_request_pair_list(L_DBG_LVL_2, request, NULL, &request->session_state_pairs, "session-state.");
715 }
716
717 RDEBUG3("%s - restored", state->da->name);
718
719 /*
720 * Set sequence so that we can prioritize ongoing multi-packet sessions.
721 */
722 request->async->sequence = entry->tries;
723 REQUEST_VERIFY(request);
724 return 0;
725}
726
727
728/** Transfer ownership of the state fr_pair_ts and ctx, back to a state entry
729 *
730 * Put request->session_state_pairs into the State attribute. Put the State attribute
731 * into the vps list. Delete the original entry, if it exists
732 *
733 * Also creates a new state entry.
734 */
736{
737 fr_state_entry_t *entry, *old;
739 fr_pair_t *state_ctx;
740
741 old = request_data_get(request, state, 0);
743 request_data_by_persistance(&data, request, true);
744
745 if (fr_pair_list_empty(&request->session_state_pairs) && fr_dlist_empty(&data)) return 0;
746
747 if (!fr_pair_list_empty(&request->session_state_pairs)) {
748 RDEBUG2("Saving session-state");
749 log_request_pair_list(L_DBG_LVL_2, request, NULL, &request->session_state_pairs, "session-state.");
750
751#ifdef WITH_VERIFY_PTR
752 /*
753 * Double check all the session state pairs
754 * are parented correctly, else we'll get
755 * memory errors when we restore.
756 */
757 fr_pair_list_verify(__FILE__, __LINE__, request->session_state_ctx, &request->session_state_pairs);
758#endif
759 }
760
761 MEM(state_ctx = request_state_replace(request, NULL));
762 PTHREAD_MUTEX_LOCK(&state->mutex);
763
764 /*
765 * Reuses old if possible
766 */
767 entry = state_entry_create(state, request, &request->reply_pairs, old);
768 if (!entry) {
770 RERROR("Creating state entry failed");
771
772 talloc_free(request_state_replace(request, state_ctx));
773 request_data_restore(request, &data); /* Put it back again */
774 return -1;
775 }
776
777 fr_assert(entry->ctx == NULL);
778 fr_assert(request->session_state_ctx);
779
780 entry->seq_start = request->seq_start;
781 entry->ctx = state_ctx;
782 fr_dlist_move(&entry->data, &data);
784
785 RDEBUG3("%s - saved", state->da->name);
786 REQUEST_VERIFY(request);
787
788 return 0;
789}
790
791/** Free any subrequest request data if the dlist head is freed
792 *
793 */
794static int _free_child_data(state_child_entry_t *child_entry)
795{
796 fr_dlist_talloc_free(&child_entry->data);
797 talloc_free(child_entry->ctx); /* Free the child's session_state_ctx if we own it */
798
799 return 0;
800}
801
802/** Store subrequest's session-state list and persistable request data in its parent
803 *
804 * @param[in] child The child request to retrieve state from.
805 * @param[in] unique_ptr A parent may have multiple subrequests spawned
806 * by different modules. This identifies the module
807 * or other facility that spawned the subrequest.
808 * @param[in] unique_int Further identification.
809 */
810void fr_state_store_in_parent(request_t *child, void const *unique_ptr, int unique_int)
811{
812 state_child_entry_t *child_entry;
813 request_t *request = child; /* Stupid logging */
814
815 if (!fr_cond_assert_msg(child->parent,
816 "Child request must have request->parent set when storing state")) return;
817
818 RDEBUG3("Storing subrequest state in request %s", child->parent->name);
819
820 if ((request_data_by_persistance_count(request, true) > 0) ||
821 !fr_pair_list_empty(&request->session_state_pairs)) {
822 MEM(child_entry = talloc_zero(request->parent->session_state_ctx, state_child_entry_t));
823 request_data_list_init(&child_entry->data);
824 talloc_set_destructor(child_entry, _free_child_data);
825
826 child_entry->ctx = request_state_replace(child, NULL);
827
828 /*
829 * Pull everything out of the child,
830 * add it to our temporary list head...
831 *
832 * request_data_add allocs persistable
833 * request dta in the session_state_ctx
834 * which is why we don't need to copy or
835 * reparent any of this.
836 */
837 request_data_by_persistance(&child_entry->data, request, true);
838
839 /*
840 * ...and add the request_data from
841 * the child back into the parent.
842 */
843 request_data_talloc_add(request->parent, unique_ptr, unique_int,
844 state_child_entry_t, child_entry, true, false, true);
845 }
846}
847
848/** Restore subrequest data from a parent request
849 *
850 * @param[in] child The child request to restore state to.
851 * @param[in] unique_ptr A parent may have multiple subrequests spawned
852 * by different modules. This identifies the module
853 * or other facility that spawned the subrequest.
854 * @param[in] unique_int Further identification.
855 */
856void fr_state_restore_to_child(request_t *child, void const *unique_ptr, int unique_int)
857{
858 state_child_entry_t *child_entry;
859 request_t *request = child; /* Stupid logging */
860
861 if (!fr_cond_assert_msg(child->parent,
862 "Child request must have request->parent set when restoring state")) return;
863
864
865 child_entry = request_data_get(child->parent, unique_ptr, unique_int);
866 if (!child_entry) {
867 RDEBUG3("No child state found in parent %s", child->parent->name);
868 return;
869 }
870
871 /*
872 * Shouldn't really be possible unless
873 * there's a logic bug in this API.
874 */
875 if (!fr_cond_assert_msg(!child_entry->thawed,
876 "Child state entry already thawed by %s - %p",
877 child_entry->thawed->name, child_entry->thawed)) return;
878
879 RDEBUG3("Restoring subrequest state from request %s", child->parent->name);
880
881 /*
882 * If we can restore from the parent, do so
883 */
884 fr_assert_msg(child_entry->ctx, "session child entry missing ctx");
885 talloc_free(request_state_replace(child, child_entry->ctx));
886 child_entry->ctx = NULL; /* No longer owns the ctx */
887 child_entry->thawed = child;
888
889 request_data_restore(child, &child_entry->data); /* Put all the request data back */
890
891 talloc_free(child_entry);
892}
893
894/** Remove state from a child
895 *
896 * This is useful for modules like EAP, where we keep a persistent eap_session
897 * but may call multiple EAP method modules during negotiation, and need to
898 * discard the state between each module call.
899 *
900 * @param[in] parent Holding the child's state.
901 * @param[in] unique_ptr A parent may have multiple subrequests spawned
902 * by different modules. This identifies the module
903 * or other facility that spawned the subrequest.
904 * @param[in] unique_int Further identification.
905 */
906void fr_state_discard_child(request_t *parent, void const *unique_ptr, int unique_int)
907{
908 state_child_entry_t *child_entry;
909 request_t *request = parent; /* Stupid logging */
910
911 child_entry = request_data_get(parent, unique_ptr, unique_int);
912 if (!child_entry) {
913 RDEBUG3("No child state found in parent %s", parent->name);
914 return;
915 }
916
917 talloc_free(child_entry);
918}
919
920/** Return number of entries created
921 *
922 */
924{
925 return state->id;
926}
927
928/** Return number of entries that timed out
929 *
930 */
932{
933 return state->timed_out;
934}
935
936/** Return number of entries we're currently tracking
937 *
938 */
940{
941 return fr_rb_num_elements(state->tree);
942}
#define HEXIFY(b1)
Definition build.h:190
#define RCSID(id)
Definition build.h:485
#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:112
#define unlikely(_x)
Definition build.h:383
static void * fr_dcursor_next(fr_dcursor_t *cursor)
Advanced the cursor to the next item.
Definition dcursor.h:288
#define fr_cond_assert(_x)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:139
#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:210
#define fr_cond_assert_msg(_x, _fmt,...)
Calls panic_action ifndef NDEBUG, else logs error and evaluates to value of _x.
Definition debug.h:156
#define MEM(x)
Definition debug.h:36
#define fr_dlist_init(_head, _type, _field)
Initialise the head structure of a doubly linked list.
Definition dlist.h:260
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:486
static void * fr_dlist_remove(fr_dlist_head_t *list_head, void *ptr)
Remove an item from the list.
Definition dlist.h:638
static bool fr_dlist_entry_in_list(fr_dlist_t const *entry)
Check if a list entry is part of a list.
Definition dlist.h:163
static void fr_dlist_talloc_free(fr_dlist_head_t *head)
Free all items in a doubly linked list (with talloc)
Definition dlist.h:908
static bool fr_dlist_empty(fr_dlist_head_t const *list_head)
Check whether a list has any items.
Definition dlist.h:501
static int fr_dlist_insert_tail(fr_dlist_head_t *list_head, void *ptr)
Insert an item into the tail of a list.
Definition dlist.h:378
static int fr_dlist_move(fr_dlist_head_t *list_dst, fr_dlist_head_t *list_src)
Merge two lists, inserting the source at the tail of the destination.
Definition dlist.h:763
#define fr_dlist_talloc_init(_head, _type, _field)
Initialise the head structure of a doubly linked list.
Definition dlist.h:275
static void * fr_dlist_next(fr_dlist_head_t const *list_head, void const *ptr)
Get the next item in a list.
Definition dlist.h:555
Head of a doubly linked list.
Definition dlist.h:51
Entry in a doubly linked list.
Definition dlist.h:41
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:828
#define RWDEBUG(fmt,...)
Definition log.h:361
#define RDEBUG3(fmt,...)
Definition log.h:343
#define RERROR(fmt,...)
Definition log.h:298
#define DEBUG4(_fmt,...)
Definition log.h:267
#define DEBUG_ENABLED
True if global debug level 1 messages are enabled.
Definition log.h:257
talloc_free(reap)
@ L_DBG_LVL_2
2nd highest priority debug messages (-xx | -X).
Definition log.h:71
unsigned int uint32_t
void fr_md5_calc(uint8_t out[static MD5_DIGEST_LENGTH], uint8_t const *in, size_t inlen)
Perform a single digest operation on a single input buffer.
unsigned char uint8_t
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:2937
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:695
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:1347
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:1691
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:285
#define fr_assert(_expr)
Definition rad_assert.h:38
#define RDEBUG2(fmt,...)
Definition radclient.h:54
#define WARN(fmt,...)
Definition radclient.h:47
uint32_t fr_rand(void)
Return a 32-bit random number.
Definition rand.c:105
uint32_t fr_rb_num_elements(fr_rb_tree_t *tree)
Return how many nodes there are in a tree.
Definition rb.c:781
void * fr_rb_remove(fr_rb_tree_t *tree, void const *data)
Remove an entry from the tree, without freeing the data.
Definition rb.c:695
bool fr_rb_insert(fr_rb_tree_t *tree, void const *data)
Insert data into a tree.
Definition rb.c:626
bool fr_rb_delete(fr_rb_tree_t *tree, void const *data)
Remove node and free data (if a free function was specified)
Definition rb.c:741
#define fr_rb_inline_talloc_alloc(_ctx, _type, _field, _data_cmp, _data_free)
Allocs a red black that verifies elements are of a specific talloc type.
Definition rb.h:246
static bool fr_rb_node_inline_in_tree(fr_rb_node_t const *node)
Check to see if an item is in a tree by examining its inline fr_rb_node_t.
Definition rb.h:314
The main red black tree structure.
Definition rb.h:73
fr_pair_t * request_state_replace(request_t *request, fr_pair_t *new_state)
Replace the session_state_ctx with a new one.
Definition request.c:504
#define REQUEST_VERIFY(_x)
Definition request.h:305
int request_data_by_persistance_count(request_t *request, bool persist)
Return how many request data entries exist of a given persistence.
int request_data_by_persistance(fr_dlist_head_t *out, request_t *request, bool persist)
Loop over all the request data, pulling out ones matching persist state.
void request_data_list_init(fr_dlist_head_t *data)
void request_data_restore(request_t *request, fr_dlist_head_t *in)
Add request data back to a request.
void * request_data_get(request_t *request, void const *unique_ptr, int unique_int)
Get opaque data from a request.
#define request_data_talloc_add(_request, _unique_ptr, _unique_int, _type, _opaque, _free_on_replace, _free_on_parent, _persist)
Add opaque data to a request_t.
#define request_data_add(_request, _unique_ptr, _unique_int, _opaque, _free_on_replace, _free_on_parent, _persist)
Add opaque data to a request_t.
uint64_t id
State number within state heap.
Definition state.c:63
void fr_state_discard_child(request_t *parent, void const *unique_ptr, int unique_int)
Remove state from a child.
Definition state.c:906
fr_state_tree_t * fr_state_tree_init(TALLOC_CTX *ctx, fr_dict_attr_t const *da, bool thread_safe, uint32_t max_sessions, fr_time_delta_t timeout, uint8_t server_id, uint32_t context_id)
Initialise a new state tree.
Definition state.c:220
uint64_t seq_start
Number of first request in this sequence.
Definition state.c:102
fr_dlist_head_t data
Persistable request data, also parented by ctx.
Definition state.c:117
void fr_state_discard(fr_state_tree_t *state, request_t *request)
Called when sending an Access-Accept/Access-Reject to discard state information.
Definition state.c:604
uint32_t max_sessions
Maximum number of sessions we track.
Definition state.c:147
#define PTHREAD_MUTEX_UNLOCK
Definition state.c:165
#define PTHREAD_MUTEX_LOCK
Definition state.c:164
int fr_request_to_state(fr_state_tree_t *state, request_t *request)
Transfer ownership of the state fr_pair_ts and ctx, back to a state entry.
Definition state.c:735
uint8_t server_id
ID to use for load balancing.
Definition state.c:157
fr_dict_attr_t const * da
State attribute used.
Definition state.c:161
int fr_state_to_request(fr_state_tree_t *state, request_t *request)
Copy a pointer to the head of the list of state fr_pair_ts (and their ctx) into the request.
Definition state.c:658
fr_dlist_head_t data
Persistable request data, also parented by ctx.
Definition state.c:138
fr_rb_node_t node
Entry in the state rbtree.
Definition state.c:64
request_t * thawed
The request that thawed this entry.
Definition state.c:140
fr_time_t cleanup
When this entry should be cleaned up.
Definition state.c:103
static int _state_tree_free(fr_state_tree_t *state)
Free the state tree.
Definition state.c:184
static int _state_entry_free(fr_state_entry_t *entry)
Frees any data associated with a state.
Definition state.c:289
static int8_t state_entry_cmp(void const *one, void const *two)
Compare two fr_state_entry_t based on their state value i.e.
Definition state.c:172
fr_pair_t * ctx
for all session specific data.
Definition state.c:115
pthread_mutex_t mutex
Synchronisation mutex.
Definition state.c:155
fr_pair_t * ctx
for all session specific data.
Definition state.c:136
static void state_entry_unlink(fr_state_tree_t *state, fr_state_entry_t *entry)
Unlink an entry and remove if from the tree.
Definition state.c:273
fr_rb_tree_t * tree
rbtree used to lookup state value.
Definition state.c:149
uint64_t fr_state_entries_tracked(fr_state_tree_t *state)
Return number of entries we're currently tracking.
Definition state.c:939
fr_dlist_head_t to_expire
Linked list of entries to free.
Definition state.c:150
uint64_t fr_state_entries_created(fr_state_tree_t *state)
Return number of entries created.
Definition state.c:923
static fr_state_entry_t * state_entry_find_and_unlink(fr_state_tree_t *state, fr_value_box_t const *vb)
Find the entry based on the State attribute and remove it from the state tree.
Definition state.c:561
bool thread_safe
Whether we lock the tree whilst modifying it.
Definition state.c:154
uint64_t fr_state_entries_timeout(fr_state_tree_t *state)
Return number of entries that timed out.
Definition state.c:931
static int _free_child_data(state_child_entry_t *child_entry)
Free any subrequest request data if the dlist head is freed.
Definition state.c:794
fr_time_delta_t timeout
How long to wait before cleaning up state entries.
Definition state.c:152
void fr_state_restore_to_child(request_t *child, void const *unique_ptr, int unique_int)
Restore subrequest data from a parent request.
Definition state.c:856
uint64_t timed_out
Number of states that were cleaned up due to timeout.
Definition state.c:145
uint64_t id
Next ID to assign.
Definition state.c:144
fr_state_tree_t * state_tree
Tree this entry belongs to.
Definition state.c:121
request_t * thawed
The request that thawed this entry.
Definition state.c:119
uint32_t used_sessions
How many sessions are currently in progress.
Definition state.c:148
uint32_t context_id
ID binding state values to a context such as a virtual server.
Definition state.c:158
void fr_state_store_in_parent(request_t *child, void const *unique_ptr, int unique_int)
Store subrequest's session-state list and persistable request data in its parent.
Definition state.c:810
Holds a state value, and associated fr_pair_ts and data.
Definition state.c:62
A child of a fr_state_entry_t.
Definition state.c:135
fr_pair_t * vp
#define fr_time()
Allow us to arbitrarily manipulate time.
Definition state_test.c:8
static void state_entry_create(void)
Test functions that read from dbuffs.
Definition state_test.c:15
Stores an attribute, a value and various bits of other data.
Definition pair.h:68
int talloc_link_ctx(TALLOC_CTX *parent, TALLOC_CTX *child)
Link two different parent and child contexts, so the child is freed before the parent.
Definition talloc.c:167
#define fr_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:196
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
#define fr_time_lt(_a, _b)
Definition time.h:239
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
bool fr_pair_list_empty(fr_pair_list_t const *list)
Is a valuepair list empty.
#define fr_pair_dcursor_init(_cursor, _list)
Initialises a special dcursor with callbacks that will maintain the attr sublists correctly.
Definition pair.h:591
static fr_slen_t parent
Definition pair.h:845
static fr_slen_t data
Definition value.h:1274
#define fr_box_time_delta(_val)
Definition value.h:354
#define fr_box_octets(_val, _len)
Definition value.h:299