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: 84ceedd69dfb6fed073d355e0950a215c4846b5b $
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: 84ceedd69dfb6fed073d355e0950a215c4846b5b $")
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 memset(old_state, 0, sizeof(old_state));
384 } else {
385 old_tries = old->tries;
386 memcpy(old_state, old->state, sizeof(old_state));
387 }
388
390
391 if (timed_out > 0) RWDEBUG("Cleaning up %"PRIu64" timed out state entries", timed_out);
392
393 /*
394 * Now free the unlinked entries.
395 *
396 * We do it here as freeing may involve significantly more
397 * work than just freeing the data.
398 *
399 * If there's request data that was persisted it will now
400 * be freed also, and it may have complex destructors associated
401 * with it.
402 */
403 while ((entry = fr_dlist_head(&to_free)) != NULL) {
404 fr_dlist_remove(&to_free, entry);
405 talloc_free(entry);
406 }
407
408 /*
409 * Have to do this post-cleanup, else we end up returning with
410 * a list full of entries to free with none of them being
411 * freed which is bad...
412 */
413 if (too_many) {
414 RERROR("Failed inserting state entry - At maximum ongoing session limit (%u)",
415 state->max_sessions);
416 PTHREAD_MUTEX_LOCK(&state->mutex); /* Caller expects this to be locked */
417 return NULL;
418 }
419
420 /*
421 * Allocation doesn't need to occur inside the critical region
422 * and would add significantly to contention.
423 */
424 if (!old) {
425 MEM(entry = talloc_zero(NULL, fr_state_entry_t));
426 talloc_set_destructor(entry, _state_entry_free);
427 /* tree->used_sessions incremented above */
428 /*
429 * Reuse the old state entry cleaning up any memory associated
430 * with it.
431 */
432 } else {
434 talloc_free_children(old);
435 memset(old, 0, sizeof(*old));
436 entry = old;
437 }
438
439 entry->state_tree = state;
440
442
443 entry->id = state->id++;
444
445 /*
446 * Limit the lifetime of this entry based on how long the
447 * server takes to process a request. Doing it this way
448 * isn't perfect, but it's reasonable, and it's one less
449 * thing for an administrator to configure.
450 */
451 entry->cleanup = fr_time_add(now, state->timeout);
452
453 /*
454 * Some modules create their own magic
455 * state attributes. If a state value already exists
456 * int the reply, we use that in preference to the
457 * old state.
458 */
459 vp = fr_pair_find_by_da(reply_list, NULL, state->da);
460 if (vp) {
461 if (DEBUG_ENABLED && (vp->vp_length > sizeof(entry->state))) {
462 WARN("State too long, will be truncated. Expected <= %zd bytes, got %zu bytes",
463 sizeof(entry->state), vp->vp_length);
464 }
465
466 /*
467 * Assume our own State first.
468 */
469 if (vp->vp_length == sizeof(entry->state)) {
470 memcpy(entry->state, vp->vp_octets, sizeof(entry->state));
471
472 /*
473 * Too big? Get the MD5 hash, in order
474 * to depend on the entire contents of State.
475 */
476 } else if (vp->vp_length > sizeof(entry->state)) {
477 fr_md5_calc(entry->state, vp->vp_octets, vp->vp_length);
478
479 /*
480 * Too small? Use the whole thing, and
481 * set the rest of my_entry.state to zero.
482 */
483 } else {
484 memcpy(entry->state, vp->vp_octets, vp->vp_length);
485 memset(&entry->state[vp->vp_length], 0, sizeof(entry->state) - vp->vp_length);
486 }
487 } else {
488 /*
489 * Base the new state on the old state if we had one.
490 */
491 if (old) {
492 memcpy(entry->state, old_state, sizeof(entry->state));
493 entry->tries = old_tries + 1;
494 /*
495 * 16 octets of randomness should be enough to
496 * have a globally unique state.
497 */
498 } else {
499 for (i = 0; i < sizeof(entry->state) / sizeof(x); i++) {
500 x = fr_rand();
501 memcpy(entry->state + (i * 4), &x, sizeof(x));
502 }
503 }
504
505 entry->state_comp.tries = entry->tries + 1;
506
507 entry->state_comp.tx = entry->state_comp.tries ^ entry->tries;
508
509 entry->state_comp.vx_0 = entry->state_comp.r_0 ^
510 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 24) & 0xff);
511 entry->state_comp.vx_1 = entry->state_comp.r_0 ^
512 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 16) & 0xff);
513 entry->state_comp.vx_2 = entry->state_comp.r_0 ^
514 ((((uint32_t) HEXIFY(RADIUSD_VERSION)) >> 8) & 0xff);
515 entry->state_comp.vx_3 = entry->state_comp.r_0 ^
516 (((uint32_t) HEXIFY(RADIUSD_VERSION)) & 0xff);
517
518 /*
519 * Allow a portion of the State attribute to be set,
520 * this is useful for debugging purposes.
521 */
522 entry->state_comp.server_id = state->server_id;
523
524 MEM(vp = fr_pair_afrom_da(request->reply_ctx, state->da));
525 fr_pair_value_memdup(vp, entry->state, sizeof(entry->state), false);
526 fr_pair_append(reply_list, vp);
527 }
528
529 DEBUG4("State ID %" PRIu64 " created, value 0x%pH, expires %pV",
530 entry->id, fr_box_octets(entry->state, sizeof(entry->state)),
532
533 PTHREAD_MUTEX_LOCK(&state->mutex);
534
535 /*
536 * XOR the server hash with four bytes of random data.
537 * We XOR is again before resolving, to ensure state lookups
538 * only succeed in the virtual server that created the state
539 * value.
540 */
541 *((uint32_t *)(&entry->state_comp.context_id)) ^= state->context_id;
542
543 if (!fr_rb_insert(state->tree, entry)) {
544 RERROR("Failed inserting state entry - Insertion into state tree failed");
545 fr_pair_delete_by_da(reply_list, state->da);
546 talloc_free(entry);
547 return NULL;
548 }
549
550 /*
551 * Link it to the end of the list, which is implicitly
552 * ordered by cleanup time.
553 */
554 fr_dlist_insert_tail(&state->to_expire, entry);
555
556 return entry;
557}
558
559/** Find the entry based on the State attribute and remove it from the state tree
560 *
561 */
563{
564 fr_state_entry_t *entry, my_entry;
565
566 /*
567 * Assume our own State first.
568 */
569 if (vb->vb_length == sizeof(my_entry.state)) {
570 memcpy(my_entry.state, vb->vb_octets, sizeof(my_entry.state));
571
572 /*
573 * Too big? Get the MD5 hash, in order
574 * to depend on the entire contents of State.
575 */
576 } else if (vb->vb_length > sizeof(my_entry.state)) {
577 fr_md5_calc(my_entry.state, vb->vb_octets, vb->vb_length);
578
579 /*
580 * Too small? Use the whole thing, and
581 * set the rest of my_entry.state to zero.
582 */
583 } else {
584 memcpy(my_entry.state, vb->vb_octets, vb->vb_length);
585 memset(&my_entry.state[vb->vb_length], 0, sizeof(my_entry.state) - vb->vb_length);
586 }
587
588 /*
589 * Make it unique for different virtual servers handling the same request
590 */
591 my_entry.state_comp.context_id ^= state->context_id;
592
593 entry = fr_rb_remove(state->tree, &my_entry);
594 if (entry) {
595 (void) talloc_get_type_abort(entry, fr_state_entry_t);
596 fr_dlist_remove(&state->to_expire, entry);
597 }
598
599 return entry;
600}
601
602/** Called when sending an Access-Accept/Access-Reject to discard state information
603 *
604 */
606{
607 fr_state_entry_t *entry;
608 fr_pair_t *vp;
609
610 vp = fr_pair_find_by_da(&request->request_pairs, NULL, state->da);
611 if (!vp) return;
612
613 PTHREAD_MUTEX_LOCK(&state->mutex);
614 entry = state_entry_find_and_unlink(state, &vp->data);
615 if (!entry) {
617 return;
618 }
620
621 /*
622 * If fr_state_to_request was never called, this ensures
623 * the state owned by entry is freed, otherwise this is
624 * mostly a NOOP, other than freeing the memory held by
625 * the entry.
626 */
627 TALLOC_FREE(entry);
628
629 /*
630 * If fr_state_to_request was called, then the request
631 * holds the existing state data. We need to destroy it,
632 * and return the request to the state it was in when
633 * it was first allocated, just in case a user does something
634 * stupid like add more session-state attributes
635 * in one of the later sections.
636 */
637 talloc_free(request_state_replace(request, NULL));
638
639 RDEBUG3("%s - discarded", state->da->name);
640
641 return;
642}
643
644/** Copy a pointer to the head of the list of state fr_pair_ts (and their ctx) into the request
645 *
646 * @note Does not copy the actual fr_pair_ts. The fr_pair_ts and their context
647 * are transferred between state entries as the conversation progresses.
648 *
649 * @note Called with the mutex free.
650 *
651 * @param[in] state tree to lookup state in.
652 * @param[in] request to restore state for.
653 * @return
654 * - 2 if the state attribute didn't match any known states.
655 * - 1 if no state attribute existed.
656 * - 0 on success (state restored)
657 * - -1 if a state entry has already been thawed by a another request.
658 */
660{
661 fr_state_entry_t *entry;
662 fr_pair_t *vp;
663
664 /*
665 * No State, don't do anything.
666 */
667 vp = fr_pair_find_by_da(&request->request_pairs, NULL, state->da);
668 if (!vp) {
669 RDEBUG3("No request.%s attribute, can't restore session-state", state->da->name);
670 if (request->seq_start == 0) request->seq_start = request->number; /* Need check for fake requests */
671 return 1;
672 }
673
674 PTHREAD_MUTEX_LOCK(&state->mutex);
675 entry = state_entry_find_and_unlink(state, &vp->data);
676 if (!entry) {
678 RDEBUG2("No state entry matching request.%pP found", vp);
679 return 2;
680 }
682
683 /* Probably impossible in the current code */
684 if (unlikely(entry->thawed != NULL)) {
685 RERROR("State entry has already been thawed by a request %"PRIu64, entry->thawed->number);
686 return -2;
687 }
688
689 /*
690 * Discard any existing session state, and replace it
691 * with the cached one.
692 */
693 fr_assert(entry->ctx);
694 talloc_free(request_state_replace(request, entry->ctx));
695 entry->ctx = NULL;
696
697 request->seq_start = entry->seq_start;
698
699 /*
700 * Associate old state with the request
701 *
702 * If the request is freed, it's freed immediately.
703 *
704 * Otherwise, if there's another round, we reuse
705 * the state entry and insert it back into the
706 * tree.
707 */
708 request_data_add(request, state, 0, entry, true, true, false);
709 request_data_restore(request, &entry->data);
710
711 entry->thawed = request;
712
713 if (!fr_pair_list_empty(&request->session_state_pairs)) {
714 RDEBUG2("Restored session-state");
715 log_request_pair_list(L_DBG_LVL_2, request, NULL, &request->session_state_pairs, "session-state.");
716 }
717
718 RDEBUG3("%s - restored", state->da->name);
719
720 /*
721 * Set sequence so that we can prioritize ongoing multi-packet sessions.
722 */
723 request->async->sequence = entry->tries;
724 REQUEST_VERIFY(request);
725 return 0;
726}
727
728
729/** Transfer ownership of the state fr_pair_ts and ctx, back to a state entry
730 *
731 * Put request->session_state_pairs into the State attribute. Put the State attribute
732 * into the vps list. Delete the original entry, if it exists
733 *
734 * Also creates a new state entry.
735 */
737{
738 fr_state_entry_t *entry, *old;
740 fr_pair_t *state_ctx;
741
742 old = request_data_get(request, state, 0);
744 request_data_by_persistance(&data, request, true);
745
746 if (fr_pair_list_empty(&request->session_state_pairs) && fr_dlist_empty(&data)) return 0;
747
748 if (!fr_pair_list_empty(&request->session_state_pairs)) {
749 RDEBUG2("Saving session-state");
750 log_request_pair_list(L_DBG_LVL_2, request, NULL, &request->session_state_pairs, "session-state.");
751
752#ifdef WITH_VERIFY_PTR
753 /*
754 * Double check all the session state pairs
755 * are parented correctly, else we'll get
756 * memory errors when we restore.
757 */
758 fr_pair_list_verify(__FILE__, __LINE__, request->session_state_ctx, &request->session_state_pairs);
759#endif
760 }
761
762 MEM(state_ctx = request_state_replace(request, NULL));
763 PTHREAD_MUTEX_LOCK(&state->mutex);
764
765 /*
766 * Reuses old if possible
767 */
768 entry = state_entry_create(state, request, &request->reply_pairs, old);
769 if (!entry) {
771 RERROR("Creating state entry failed");
772
773 talloc_free(request_state_replace(request, state_ctx));
774 request_data_restore(request, &data); /* Put it back again */
775 return -1;
776 }
777
778 fr_assert(entry->ctx == NULL);
779 fr_assert(request->session_state_ctx);
780
781 entry->seq_start = request->seq_start;
782 entry->ctx = state_ctx;
783 fr_dlist_move(&entry->data, &data);
785
786 RDEBUG3("%s - saved", state->da->name);
787 REQUEST_VERIFY(request);
788
789 return 0;
790}
791
792/** Free any subrequest request data if the dlist head is freed
793 *
794 */
795static int _free_child_data(state_child_entry_t *child_entry)
796{
797 fr_dlist_talloc_free(&child_entry->data);
798 talloc_free(child_entry->ctx); /* Free the child's session_state_ctx if we own it */
799
800 return 0;
801}
802
803/** Store subrequest's session-state list and persistable request data in its parent
804 *
805 * @param[in] child The child request to retrieve state from.
806 * @param[in] unique_ptr A parent may have multiple subrequests spawned
807 * by different modules. This identifies the module
808 * or other facility that spawned the subrequest.
809 * @param[in] unique_int Further identification.
810 */
811void fr_state_store_in_parent(request_t *child, void const *unique_ptr, int unique_int)
812{
813 state_child_entry_t *child_entry;
814 request_t *request = child; /* Stupid logging */
815
816 if (!fr_cond_assert_msg(child->parent,
817 "Child request must have request->parent set when storing state")) return;
818
819 RDEBUG3("Storing subrequest state in request %s", child->parent->name);
820
821 if ((request_data_by_persistance_count(request, true) > 0) ||
822 !fr_pair_list_empty(&request->session_state_pairs)) {
823 MEM(child_entry = talloc_zero(request->parent->session_state_ctx, state_child_entry_t));
824 request_data_list_init(&child_entry->data);
825 talloc_set_destructor(child_entry, _free_child_data);
826
827 child_entry->ctx = request_state_replace(child, NULL);
828
829 /*
830 * Pull everything out of the child,
831 * add it to our temporary list head...
832 *
833 * request_data_add allocs persistable
834 * request dta in the session_state_ctx
835 * which is why we don't need to copy or
836 * reparent any of this.
837 */
838 request_data_by_persistance(&child_entry->data, request, true);
839
840 /*
841 * ...and add the request_data from
842 * the child back into the parent.
843 */
844 request_data_talloc_add(request->parent, unique_ptr, unique_int,
845 state_child_entry_t, child_entry, true, false, true);
846 }
847}
848
849/** Restore subrequest data from a parent request
850 *
851 * @param[in] child The child request to restore state to.
852 * @param[in] unique_ptr A parent may have multiple subrequests spawned
853 * by different modules. This identifies the module
854 * or other facility that spawned the subrequest.
855 * @param[in] unique_int Further identification.
856 */
857void fr_state_restore_to_child(request_t *child, void const *unique_ptr, int unique_int)
858{
859 state_child_entry_t *child_entry;
860 request_t *request = child; /* Stupid logging */
861
862 if (!fr_cond_assert_msg(child->parent,
863 "Child request must have request->parent set when restoring state")) return;
864
865
866 child_entry = request_data_get(child->parent, unique_ptr, unique_int);
867 if (!child_entry) {
868 RDEBUG3("No child state found in parent %s", child->parent->name);
869 return;
870 }
871
872 /*
873 * Shouldn't really be possible unless
874 * there's a logic bug in this API.
875 */
876 if (!fr_cond_assert_msg(!child_entry->thawed,
877 "Child state entry already thawed by %s - %p",
878 child_entry->thawed->name, child_entry->thawed)) return;
879
880 RDEBUG3("Restoring subrequest state from request %s", child->parent->name);
881
882 /*
883 * If we can restore from the parent, do so
884 */
885 fr_assert_msg(child_entry->ctx, "session child entry missing ctx");
886 talloc_free(request_state_replace(child, child_entry->ctx));
887 child_entry->ctx = NULL; /* No longer owns the ctx */
888 child_entry->thawed = child;
889
890 request_data_restore(child, &child_entry->data); /* Put all the request data back */
891
892 talloc_free(child_entry);
893}
894
895/** Remove state from a child
896 *
897 * This is useful for modules like EAP, where we keep a persistent eap_session
898 * but may call multiple EAP method modules during negotiation, and need to
899 * discard the state between each module call.
900 *
901 * @param[in] parent Holding the child's state.
902 * @param[in] unique_ptr A parent may have multiple subrequests spawned
903 * by different modules. This identifies the module
904 * or other facility that spawned the subrequest.
905 * @param[in] unique_int Further identification.
906 */
907void fr_state_discard_child(request_t *parent, void const *unique_ptr, int unique_int)
908{
909 state_child_entry_t *child_entry;
910 request_t *request = parent; /* Stupid logging */
911
912 child_entry = request_data_get(parent, unique_ptr, unique_int);
913 if (!child_entry) {
914 RDEBUG3("No child state found in parent %s", parent->name);
915 return;
916 }
917
918 talloc_free(child_entry);
919}
920
921/** Return number of entries created
922 *
923 */
925{
926 return state->id;
927}
928
929/** Return number of entries that timed out
930 *
931 */
933{
934 return state->timed_out;
935}
936
937/** Return number of entries we're currently tracking
938 *
939 */
941{
942 return fr_rb_num_elements(state->tree);
943}
#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:290
#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:2945
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:697
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:1351
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:1695
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:287
#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:511
#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:907
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:605
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:736
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:659
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:940
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:924
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:562
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:932
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:795
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:857
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:811
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:1288
#define fr_box_time_delta(_val)
Definition value.h:362
#define fr_box_octets(_val, _len)
Definition value.h:307