All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
process.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: d6113a2d69fdf67fc1986664a34d6511452c722a $
19  *
20  * @file process.c
21  * @brief Defines the state machines that control how requests are processed.
22  *
23  * @copyright 2012 The FreeRADIUS server project
24  * @copyright 2012 Alan DeKok <aland@deployingradius.com>
25  */
26 
27 RCSID("$Id: d6113a2d69fdf67fc1986664a34d6511452c722a $")
28 
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
33 
34 #include <freeradius-devel/rad_assert.h>
35 
36 #ifdef WITH_DETAIL
37 #include <freeradius-devel/detail.h>
38 #endif
39 
40 #include <signal.h>
41 #include <fcntl.h>
42 
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
45 #endif
46 
47 extern pid_t radius_pid;
49 
50 static bool spawn_workers = false;
51 static bool just_started = true;
52 time_t fr_start_time = (time_t)-1;
53 static rbtree_t *pl = NULL;
54 static fr_event_list_t *el = NULL;
55 
57  /* Currently we do not run a second event loop for modules. */
58  return el;
59 }
60 
61 static char const *action_codes[] = {
62  "INVALID",
63  "run",
64  "done",
65  "dup",
66  "timer",
67 #ifdef WITH_PROXY
68  "proxy-reply"
69 #endif
70 };
71 
72 #ifdef DEBUG_STATE_MACHINE
73 # define TRACE_STATE_MACHINE \
74 if (rad_debug_lvl) do { \
75  struct timeval debug_tv; \
76  gettimeofday(&debug_tv, NULL); \
77  debug_tv.tv_sec -= fr_start_time; \
78  printf("(%u) %d.%06d ********\tSTATE %s action %s live M-%s C-%s\t********\n",\
79  request->number, (int) debug_tv.tv_sec, (int) debug_tv.tv_usec, \
80  __FUNCTION__, action_codes[action], master_state_names[request->master_state], \
81  child_state_names[request->child_state]); \
82 } while (0)
83 
84 static char const *master_state_names[REQUEST_MASTER_NUM_STATES] = {
85  "?",
86  "active",
87  "stop-processing",
88  "counted"
89 };
90 
91 static char const *child_state_names[REQUEST_CHILD_NUM_STATES] = {
92  "?",
93  "queued",
94  "running",
95  "proxied",
96  "reject-delay",
97  "cleanup-delay",
98  "done"
99 };
100 
101 #else
102 # define TRACE_STATE_MACHINE {}
103 #endif
104 
105 static NEVER_RETURNS void _rad_panic(char const *file, unsigned int line, char const *msg)
106 {
107  ERROR("%s[%u]: %s", file, line, msg);
108  fr_exit_now(1);
109 }
110 
111 #define rad_panic(x) _rad_panic(__FILE__, __LINE__, x)
112 
113 /** Declare a state in the state machine
114  *
115  * Expands to the start of a function definition for a given state.
116  *
117  * @param _x the name of the state.
118  */
119 #define STATE_MACHINE_DECL(_x) static void _x(REQUEST *request, int action)
120 
121 static void request_timer(void *ctx, struct timeval *now);
122 
123 /** Insert #REQUEST back into the event heap, to continue executing at a future time
124  *
125  * @param file the state machine timer call occurred in.
126  * @param line the state machine timer call occurred on.
127  * @param request to set add the timer event for.
128  * @param when the event should fine.
129  * @param action to perform when we resume processing the request.
130  */
131 static inline void state_machine_timer(char const *file, int line, REQUEST *request,
132  struct timeval *when, fr_state_action_t action)
133 {
134  request->timer_action = action;
135  if (!fr_event_insert(el, request_timer, request, when, &request->ev)) {
136  _rad_panic(file, line, "Failed to insert event");
137  }
138 }
139 
140 /** @copybrief state_machine_timer
141  *
142  * @param _x the action to perform when we resume processing the request.
143  */
144 #define STATE_MACHINE_TIMER(_x) state_machine_timer(__FILE__, __LINE__, request, &when, _x)
145 
146 /*
147  * We need a different VERIFY_REQUEST macro in process.c
148  * To avoid the race conditions with the master thread
149  * checking the REQUEST whilst it's being worked on by
150  * the child.
151  */
152 #if defined(WITH_VERIFY_PTR) && defined(HAVE_PTHREAD_H)
153 # undef VERIFY_REQUEST
154 # define VERIFY_REQUEST(_x) if (pthread_equal(pthread_self(), _x->child_pid) != 0) verify_request(__FILE__, __LINE__, _x)
155 #endif
156 
157 /**
158  * @section request_timeline
159  *
160  * Time sequence of a request
161  * @code
162  *
163  * RQ-----------------P=============================Y-J-C
164  * ::::::::::::::::::::::::::::::::::::::::::::::::::::::::M
165  * @endcode
166  *
167  * - R: received. Duplicate detection is done, and request is
168  * cached.
169  *
170  * - Q: Request is placed onto a queue for child threads to pick up.
171  * If there are no child threads, the request goes immediately
172  * to P.
173  *
174  * - P: Processing the request through the modules.
175  *
176  * - Y: Reply is ready. Rejects MAY be delayed here. All other
177  * replies are sent immediately.
178  *
179  * - J: Reject is sent "response_delay" after the reply is ready.
180  *
181  * - C: For Access-Requests, After "cleanup_delay", the request is
182  * deleted. Accounting-Request packets go directly from Y to C.
183  *
184  * - M: Max request time. If the request hits this timer, it is
185  * forcibly stopped.
186  *
187  * Other considerations include duplicate and conflicting
188  * packets. When a dupicate packet is received, it is ignored
189  * until we've reached Y, as no response is ready. If the reply
190  * is a reject, duplicates are ignored until J, when we're ready
191  * to send the reply. In between the reply being sent (Y or J),
192  * and C, the server responds to duplicates by sending the cached
193  * reply.
194  *
195  * Conflicting packets are sent in 2 situations.
196  *
197  * The first is in between R and Y. In that case, we consider
198  * it as a hint that we're taking too long, and the NAS has given
199  * up on the request. We then behave just as if the M timer was
200  * reached, and we discard the current request. This allows us
201  * to process the new one.
202  *
203  * The second case is when we're at Y, but we haven't yet
204  * finished processing the request. This is a race condition in
205  * the threading code (avoiding locks is faster). It means that
206  * a thread has actually encoded and sent the reply, and that the
207  * NAS has responded with a new packet. The server can then
208  * safely mark the current request as "OK to delete", and behaves
209  * just as if the M timer was reached. This usually happens only
210  * in high-load situations.
211  *
212  * Duplicate packets are sent when the NAS thinks we're taking
213  * too long, and wants a reply. From R-Y, duplicates are
214  * ignored. From Y-J (for Access-Rejects), duplicates are also
215  * ignored. From Y-C, duplicates get a duplicate reply. *And*,
216  * they cause the "cleanup_delay" time to be extended. This
217  * extension means that we're more likely to send a duplicate
218  * reply (if we have one), or to suppress processing the packet
219  * twice if we didn't reply to it.
220  *
221  * All functions in this file should be thread-safe, and should
222  * assume thet the REQUEST structure is being accessed
223  * simultaneously by the main thread, and by the child worker
224  * threads. This means that timers, etc. cannot be updated in
225  * the child thread.
226  *
227  * Instead, the master thread periodically calls request->process
228  * with action TIMER. It's up to the individual functions to
229  * determine how to handle that. They need to check if they're
230  * being called from a child thread or the master, and then do
231  * different things based on that.
232  */
233 #ifdef WITH_PROXY
235 static TALLOC_CTX *proxy_ctx = NULL;
236 #endif
237 
238 #ifdef HAVE_PTHREAD_H
239 # ifdef WITH_PROXY
240 static pthread_mutex_t proxy_mutex;
241 static bool proxy_no_new_sockets = false;
242 # endif
243 
244 # define PTHREAD_MUTEX_LOCK if (spawn_workers) pthread_mutex_lock
245 # define PTHREAD_MUTEX_UNLOCK if (spawn_workers) pthread_mutex_unlock
246 
247 static pthread_t NO_SUCH_CHILD_PID;
248 # define NO_CHILD_THREAD request->child_pid = NO_SUCH_CHILD_PID
249 
250 #else
251 /*
252  * This is easier than ifdef's throughout the code.
253  */
254 # define PTHREAD_MUTEX_LOCK(_x)
255 # define PTHREAD_MUTEX_UNLOCK(_x)
256 # define NO_CHILD_THREAD
257 #endif
258 
259 #ifdef HAVE_PTHREAD_H
260 static bool we_are_master(void)
261 {
262  if (spawn_workers &&
263  (pthread_equal(pthread_self(), NO_SUCH_CHILD_PID) == 0)) {
264  return false;
265  }
266 
267  return true;
268 }
269 
270 /*
271  * Assertions are debug checks.
272  */
273 # ifndef NDEBUG
274 # define ASSERT_MASTER if (!we_are_master()) rad_panic("We are not master")
275 # endif
276 #else
277 
278 /*
279  * No threads: we're always master.
280  */
281 # define we_are_master(_x) (1)
282 #endif /* HAVE_PTHREAD_H */
283 
284 #ifndef ASSERT_MASTER
285 # define ASSERT_MASTER
286 #endif
287 
288 /*
289  * Make state transitions simpler.
290  */
291 #define FINAL_STATE(_x) NO_CHILD_THREAD; request->component = "<" #_x ">"; request->module = ""; request->child_state = _x
292 
293 
294 static int event_new_fd(rad_listen_t *this);
295 
296 /*
297  * We need mutexes around the event FD list *only* in certain
298  * cases.
299  */
300 #if defined (HAVE_PTHREAD_H) && (defined(WITH_PROXY) || defined(WITH_TCP))
301 static rad_listen_t *new_listeners = NULL;
302 
303 static pthread_mutex_t fd_mutex;
304 # define FD_MUTEX_LOCK if (spawn_workers) pthread_mutex_lock
305 # define FD_MUTEX_UNLOCK if (spawn_workers) pthread_mutex_unlock
306 
308 {
309  /*
310  * Just do it ourselves.
311  */
312  if (we_are_master()) {
313  event_new_fd(this);
314  return;
315  }
316 
317  FD_MUTEX_LOCK(&fd_mutex);
318 
319  /*
320  * If it's already in the list, don't add it again.
321  */
322  if (this->next) {
323  FD_MUTEX_UNLOCK(&fd_mutex);
324  return;
325  }
326 
327  /*
328  * Otherwise, add it to the list
329  */
330  this->next = new_listeners;
331  new_listeners = this;
332  FD_MUTEX_UNLOCK(&fd_mutex);
334 }
335 #else
337 {
338  /*
339  * No threads. Just insert it.
340  */
341  event_new_fd(this);
342 }
343 /*
344  * This is easier than ifdef's throughout the code.
345  */
346 # define FD_MUTEX_LOCK(_x)
347 # define FD_MUTEX_UNLOCK(_x)
348 #endif
349 
350 static int request_num_counter = 1;
351 #ifdef WITH_PROXY
352 static int request_will_proxy(REQUEST *request) CC_HINT(nonnull);
353 static int request_proxy(REQUEST *request, int retransmit) CC_HINT(nonnull);
355 
360 
364 
365 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply) CC_HINT(nonnull (1));
366 static void remove_from_proxy_hash(REQUEST *request) CC_HINT(nonnull);
367 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank) CC_HINT(nonnull);
368 static int insert_into_proxy_hash(REQUEST *request) CC_HINT(nonnull);
369 #endif
370 
371 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
372  RADCLIENT *client, RAD_REQUEST_FUNP fun);
373 static int request_pre_handler(REQUEST *request, UNUSED int action) CC_HINT(nonnull);
374 
375 #ifdef WITH_COA
376 static void request_coa_originate(REQUEST *request) CC_HINT(nonnull);
380 static void coa_separate(REQUEST *request) CC_HINT(nonnull);
381 # define COA_SEPARATE if (request->coa) coa_separate(request->coa);
382 #else
383 # define COA_SEPARATE
384 #endif
385 
386 #define CHECK_FOR_STOP do { if (request->master_state == REQUEST_STOP_PROCESSING) {request_done(request, FR_ACTION_DONE);return;}} while (0)
387 
388 #undef USEC
389 #define USEC (1000000)
390 
391 #define INSERT_EVENT(_function, _ctx) if (!fr_event_insert(el, _function, _ctx, &((_ctx)->when), &((_ctx)->ev))) { _rad_panic(__FILE__, __LINE__, "Failed to insert event"); }
392 
393 static void tv_add(struct timeval *tv, int usec_delay)
394 {
395  if (usec_delay >= USEC) {
396  tv->tv_sec += usec_delay / USEC;
397  usec_delay %= USEC;
398  }
399  tv->tv_usec += usec_delay;
400 
401  if (tv->tv_usec >= USEC) {
402  tv->tv_sec += tv->tv_usec / USEC;
403  tv->tv_usec %= USEC;
404  }
405 }
406 
407 /***********************************************************************
408  *
409  * Start of RADIUS server state machine.
410  *
411  ***********************************************************************/
412 
413 static struct timeval *request_response_window(REQUEST *request)
414 {
415  VERIFY_REQUEST(request);
416 
417  if (request->client) {
418  /*
419  * The client hasn't set the response window. Return
420  * either the home server one, if set, or the global one.
421  */
422  if (!timerisset(&request->client->response_window)) {
423  return &request->home_server->response_window;
424  }
425 
426  if (timercmp(&request->client->response_window,
427  &request->home_server->response_window, <)) {
428  return &request->client->response_window;
429  }
430  }
431 
432  rad_assert(request->home_server != NULL);
433  return &request->home_server->response_window;
434 }
435 
436 /*
437  * Determine initial request processing delay.
438  */
439 static int request_init_delay(REQUEST *request)
440 {
441  struct timeval half_response_window;
442 
443  VERIFY_REQUEST(request);
444 
445  /* Allow client response window to lower initial delay */
446  if (timerisset(&request->client->response_window)) {
447  half_response_window.tv_sec = request->client->response_window.tv_sec >> 1;
448  half_response_window.tv_usec =
449  ((request->client->response_window.tv_sec & 1) * USEC +
450  request->client->response_window.tv_usec) >> 1;
451  if (timercmp(&half_response_window, &request->root->init_delay, <))
452  return (int)half_response_window.tv_sec * USEC +
453  (int)half_response_window.tv_usec;
454  }
455 
456  return (int)request->root->init_delay.tv_sec * USEC +
457  (int)request->root->init_delay.tv_usec;
458 }
459 
460 /*
461  * Callback for ALL timer events related to the request.
462  */
463 static void request_timer(void *ctx, UNUSED struct timeval *now)
464 {
465  REQUEST *request = talloc_get_type_abort(ctx, REQUEST);
466  int action;
467 
468  action = request->timer_action;
469 
471 
472  request->process(request, action);
473 }
474 
475 /*
476  * Wrapper for talloc pools. If there's no parent, just free the
477  * request. If there is a parent, free the parent INSTEAD of the
478  * request.
479  */
480 static void request_free(REQUEST *request)
481 {
482  void *ptr;
483 
484  rad_assert(request->ev == NULL);
485  rad_assert(!request->in_request_hash);
486  rad_assert(!request->in_proxy_hash);
487 
488  if ((request->options & RAD_REQUEST_OPTION_CTX) == 0) {
489  talloc_free(request);
490  return;
491  }
492 
493  ptr = talloc_parent(request);
494  rad_assert(ptr != NULL);
495  talloc_free(ptr);
496 }
497 
498 
499 #ifdef WITH_PROXY
500 static void proxy_reply_too_late(REQUEST *request)
501 {
502  char buffer[INET6_ADDRSTRLEN];
503 
504  RDEBUG2("Reply from home server %s port %d - ID: %d arrived too late. "
505  "Try increasing 'retry_delay' or 'max_request_time'",
506  inet_ntop(request->proxy->dst_ipaddr.af,
507  &request->proxy->dst_ipaddr.ipaddr,
508  buffer, sizeof(buffer)),
509  request->proxy->dst_port, request->proxy->id);
510 }
511 #endif
512 
513 
514 /** Mark a request DONE and clean it up.
515  *
516  * When a request is DONE, it can have ties to a number of other
517  * portions of the server. The request hash, proxy hash, events,
518  * child threads, etc. This function takes care of either cleaning
519  * up the request, or managing the timers to wait for the ties to be
520  * removed.
521  *
522  * \dot
523  * digraph done {
524  * done -> done [ label = "still running" ];
525  * }
526  * \enddot
527  */
528 static void request_done(REQUEST *request, int action)
529 {
530  struct timeval now, when;
531 
532  VERIFY_REQUEST(request);
533 
535 
536  /*
537  * Force this no matter what.
538  */
539  request->process = request_done;
540 
541 #ifdef WITH_DETAIL
542  /*
543  * Tell the detail listener that we're done.
544  */
545  if (request->listener &&
546  (request->listener->type == RAD_LISTEN_DETAIL) &&
547  (request->simul_max != 1)) {
548  request->simul_max = 1;
549  request->listener->send(request->listener,
550  request);
551  }
552 #endif
553 
554 #ifdef HAVE_PTHREAD_H
555  /*
556  * If called from a child thread, mark ourselves as done,
557  * and wait for the master thread timer to clean us up.
558  */
559  if (!we_are_master()) {
561  return;
562  }
563 #endif
564 
565  /*
566  * Mark the request as STOP.
567  */
569 
570 #ifdef WITH_COA
571  /*
572  * Move the CoA request to its own handler.
573  */
574  if (request->coa) {
575  coa_separate(request->coa);
576  } else if (request->parent && (request->parent->coa == request)) {
577  coa_separate(request);
578  }
579 #endif
580 
581  /*
582  * It doesn't hurt to send duplicate replies. All other
583  * signals are ignored, as the request will be cleaned up
584  * soon anyways.
585  */
586  switch (action) {
587  case FR_ACTION_DUP:
588 #ifdef WITH_DETAIL
589  rad_assert(request->listener != NULL);
590 #endif
591  if (request->reply->code != 0) {
592  request->listener->send(request->listener, request);
593  return;
594  } else {
595  RDEBUG("No reply. Ignoring retransmit");
596  }
597  break;
598 
599  /*
600  * Mark the request as done.
601  */
602  case FR_ACTION_DONE:
603 #ifdef HAVE_PTHREAD_H
604  /*
605  * If the child is still running, leave it alone.
606  */
607  if (spawn_workers && (request->child_state <= REQUEST_RUNNING)) {
608  break;
609  }
610 #endif
611 
612 #ifdef DEBUG_STATE_MACHINE
613  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
614  request->number, __FUNCTION__,
615  child_state_names[request->child_state],
616  child_state_names[REQUEST_DONE]);
617 #endif
618  request->child_state = REQUEST_DONE;
619  break;
620 
621  /*
622  * Called when the child is taking too long to
623  * finish. We've already marked it "please
624  * stop", so we don't complain any more.
625  */
626  case FR_ACTION_TIMER:
627  break;
628 
629 #ifdef WITH_PROXY
631  proxy_reply_too_late(request);
632  break;
633 #endif
634 
635  default:
636  break;
637  }
638 
639  /*
640  * Remove it from the request hash.
641  */
642  if (request->in_request_hash) {
643  if (!rbtree_deletebydata(pl, &request->packet)) {
644  rad_assert(0 == 1);
645  }
646  request->in_request_hash = false;
647  }
648 
649 #ifdef WITH_PROXY
650  /*
651  * Wait for the proxy ID to expire. This allows us to
652  * avoid re-use of proxy IDs for a while.
653  */
654  if (request->in_proxy_hash) {
655  rad_assert(request->proxy != NULL);
656 
657  fr_event_now(el, &now);
658  when = request->proxy->timestamp;
659 
660 #ifdef WITH_COA
661  if (((request->proxy->code == PW_CODE_COA_REQUEST) ||
662  (request->proxy->code == PW_CODE_DISCONNECT_REQUEST)) &&
663  (request->packet->code != request->proxy->code)) {
664  when.tv_sec += request->home_server->coa_mrd;
665  } else
666 #endif
667  timeradd(&when, request_response_window(request), &when);
668 
669  /*
670  * We haven't received all responses, AND there's still
671  * time to wait. Do so.
672  */
673  if ((request->num_proxied_requests > request->num_proxied_responses) &&
674 #ifdef WITH_TCP
675  (request->home_server->proto != IPPROTO_TCP) &&
676 #endif
677  timercmp(&now, &when, <)) {
678  RDEBUG("Waiting for more responses from the home server");
679  goto wait_some_more;
680  }
681 
682  /*
683  * Time to remove it.
684  */
685  remove_from_proxy_hash(request);
686  }
687 #endif
688 
689 #ifdef HAVE_PTHREAD_H
690  /*
691  * If there's no children, we can mark the request as done.
692  */
693  if (!spawn_workers) request->child_state = REQUEST_DONE;
694 #endif
695 
696  /*
697  * If the child is still running, wait for it to be finished.
698  */
699  if (request->child_state <= REQUEST_RUNNING) {
700  gettimeofday(&now, NULL);
701 #ifdef WITH_PROXY
702  wait_some_more:
703 #endif
704  when = now;
705  if (request->delay < (USEC / 3)) request->delay = USEC / 3;
706  tv_add(&when, request->delay);
707  request->delay += request->delay >> 1;
708  if (request->delay > (10 * USEC)) request->delay = 10 * USEC;
709 
711  return;
712  }
713 
714 #ifdef HAVE_PTHREAD_H
715  rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
716 #endif
717 
718  /*
719  * @todo: do final states for TCP sockets, too?
720  */
721  request_stats_final(request);
722 #ifdef WITH_TCP
723  if (request->listener) {
724  request->listener->count--;
725 
726  /*
727  * If we're the last one, remove the listener now.
728  */
729  if ((request->listener->count == 0) &&
730  (request->listener->status >= RAD_LISTEN_STATUS_FROZEN)) {
731  event_new_fd(request->listener);
732  }
733  }
734 #endif
735 
736  if (request->packet) {
737  RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
738  request->packet->id,
739  (unsigned int) (request->timestamp.tv_sec - fr_start_time));
740  } /* else don't print anything */
741 
743  fr_event_delete(el, &request->ev);
744  request_free(request);
745 }
746 
747 
748 static void request_cleanup_delay_init(REQUEST *request)
749 {
750  struct timeval now, when;
751 
752  VERIFY_REQUEST(request);
753 
754  /*
755  * Do cleanup delay ONLY for RADIUS packets from a real
756  * client. Everything else just gets cleaned up
757  * immediately.
758  */
759  if (request->packet->dst_port == 0) goto done;
760 
761  /*
762  * Accounting packets shouldn't be retransmitted. They
763  * should always be updated with Acct-Delay-Time.
764  */
765 #ifdef WITH_ACCOUNTING
766  if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) goto done;
767 #endif
768 
769 #ifdef WITH_DHCP
770  if (request->listener->type == RAD_LISTEN_DHCP) goto done;
771 #endif
772 
773 #ifdef WITH_VMPS
774  if (request->listener->type == RAD_LISTEN_VQP) goto done;
775 #endif
776 
777  if (!request->root->cleanup_delay) goto done;
778 
779  gettimeofday(&now, NULL);
780 
781  rad_assert(request->reply->timestamp.tv_sec != 0);
782  when = request->reply->timestamp;
783 
784  request->delay = request->root->cleanup_delay;
785  when.tv_sec += request->delay;
786 
787  /*
788  * Set timer for when we need to clean it up.
789  */
790  if (timercmp(&when, &now, >)) {
791 #ifdef DEBUG_STATE_MACHINE
792  if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
793 #endif
794  request->process = request_cleanup_delay;
795 
796  if (!we_are_master()) {
798  return;
799  }
800 
801  /*
802  * Update this if we can, otherwise let the timers pick it up.
803  */
805 #ifdef HAVE_PTHREAD_H
806  rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
807 #endif
809  return;
810  }
811 
812  /*
813  * Otherwise just clean it up.
814  */
815 done:
816  request_done(request, FR_ACTION_DONE);
817 }
818 
819 
820 /*
821  * Enforce max_request_time.
822  */
823 static bool request_max_time(REQUEST *request)
824 {
825  struct timeval now, when;
826  rad_assert(request->magic == REQUEST_MAGIC);
827 #ifdef DEBUG_STATE_MACHINE
828  int action = FR_ACTION_TIMER;
829 #endif
830 
831  VERIFY_REQUEST(request);
832 
835 
836  /*
837  * The child thread has acknowledged it's done.
838  * Transition to the DONE state.
839  *
840  * If the request was marked STOP, then the "check for
841  * stop" macro already took care of it.
842  */
843  if (request->child_state == REQUEST_DONE) {
844  done:
845  request_done(request, FR_ACTION_DONE);
846  return true;
847  }
848 
849  /*
850  * The request is still running. Enforce max_request_time.
851  */
852  fr_event_now(el, &now);
853  when = request->packet->timestamp;
854  when.tv_sec += request->root->max_request_time;
855 
856  /*
857  * Taking too long: tell it to die.
858  */
859  if (timercmp(&now, &when, >=)) {
860 #ifdef HAVE_PTHREAD_H
861  /*
862  * If there's a child thread processing it,
863  * complain.
864  */
865  if (spawn_workers &&
866  (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0)) {
867  ERROR("Unresponsive child for request %u, in component %s module %s",
868  request->number,
869  request->component ? request->component : "<core>",
870  request->module ? request->module : "<core>");
871  exec_trigger(request, NULL, "server.thread.unresponsive", true);
872  }
873 #endif
874  /*
875  * Tell the request that it's done.
876  */
877  goto done;
878  }
879 
880  /*
881  * Sleep for some more. We HOPE that the child will
882  * become responsive at some point in the future. We do
883  * this by adding 50% to the current timer.
884  */
885  when = now;
886  tv_add(&when, request->delay);
887  request->delay += request->delay >> 1;
889  return false;
890 }
891 
892 static void request_queue_or_run(REQUEST *request,
893  fr_request_process_t process)
894 {
895 #ifdef DEBUG_STATE_MACHINE
896  int action = FR_ACTION_TIMER;
897 #endif
898 
899  VERIFY_REQUEST(request);
900 
902 
903  /*
904  * Do this here so that fewer other functions need to do
905  * it.
906  */
907  if (request->master_state == REQUEST_STOP_PROCESSING) {
908 #ifdef DEBUG_STATE_MACHINE
909  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s M-%s causes C-%s-> C-%s\t********\n",
910  request->number, __FUNCTION__,
911  master_state_names[request->master_state],
912  child_state_names[request->child_state],
913  child_state_names[REQUEST_DONE]);
914 #endif
915  request_done(request, FR_ACTION_DONE);
916  return;
917  }
918 
919  request->process = process;
920 
921  if (we_are_master()) {
922  struct timeval when;
923 
924  /*
925  * (re) set the initial delay.
926  */
927  request->delay = request_init_delay(request);
928  if (request->delay > USEC) request->delay = USEC;
929  gettimeofday(&when, NULL);
930  tv_add(&when, request->delay);
931  request->delay += request->delay >> 1;
932 
934 
935 #ifdef HAVE_PTHREAD_H
936  if (spawn_workers) {
937  /*
938  * A child thread will eventually pick it up.
939  */
940  if (request_enqueue(request)) return;
941 
942  /*
943  * Otherwise we're not going to do anything with
944  * it...
945  */
946  request_done(request, FR_ACTION_DONE);
947  return;
948  }
949 #endif
950  }
951 
952  request->child_state = REQUEST_RUNNING;
953  request->process(request, FR_ACTION_RUN);
954 
955 #ifdef WNOHANG
956  /*
957  * Requests that care about child process exit
958  * codes have already either called
959  * rad_waitpid(), or they've given up.
960  */
961  while (waitpid(-1, NULL, WNOHANG) > 0);
962 #endif
963 }
964 
965 
966 static void request_dup(REQUEST *request)
967 {
968  ERROR("(%u) Ignoring duplicate packet from "
969  "client %s port %d - ID: %u due to unfinished request "
970  "in component %s module %s",
971  request->number, request->client->shortname,
972  request->packet->src_port,request->packet->id,
973  request->component, request->module);
974 }
975 
976 
977 /** Sit on a request until it's time to clean it up.
978  *
979  * A NAS may not see a response from the server. When the NAS
980  * retransmits, we want to be able to send a cached reply back. The
981  * alternative is to re-process the packet, which does bad things for
982  * EAP, among others.
983  *
984  * IF we do see a NAS retransmit, we extend the cleanup delay,
985  * because the NAS might miss our cached reply.
986  *
987  * Otherwise, once we reach cleanup_delay, we transition to DONE.
988  *
989  * \dot
990  * digraph cleanup_delay {
991  * cleanup_delay;
992  * send_reply [ label = "send_reply\nincrease cleanup delay" ];
993  *
994  * cleanup_delay -> send_reply [ label = "DUP" ];
995  * send_reply -> cleanup_delay;
996  * cleanup_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
997  * cleanup_delay -> cleanup_delay [ label = "TIMER < timeout" ];
998  * cleanup_delay -> done [ label = "TIMER >= timeout" ];
999  * }
1000  * \enddot
1001  */
1002 static void request_cleanup_delay(REQUEST *request, int action)
1003 {
1004  struct timeval when, now;
1005 
1006  VERIFY_REQUEST(request);
1007 
1009  ASSERT_MASTER;
1010  COA_SEPARATE;
1012 
1013  switch (action) {
1014  case FR_ACTION_DUP:
1015  if (request->reply->code != 0) {
1016  request->listener->send(request->listener, request);
1017  } else {
1018  RDEBUG("No reply. Ignoring retransmit");
1019  }
1020 
1021  /*
1022  * Double the cleanup_delay to catch retransmits.
1023  */
1024  when = request->reply->timestamp;
1025  request->delay += request->delay;
1026  when.tv_sec += request->delay;
1027 
1029  break;
1030 
1031 #ifdef WITH_PROXY
1032  case FR_ACTION_PROXY_REPLY:
1033  proxy_reply_too_late(request);
1034  break;
1035 #endif
1036 
1037  case FR_ACTION_TIMER:
1038  fr_event_now(el, &now);
1039 
1040  rad_assert(request->root->cleanup_delay > 0);
1041 
1042  when = request->reply->timestamp;
1043  when.tv_sec += request->root->cleanup_delay;
1044 
1045  if (timercmp(&when, &now, >)) {
1046 #ifdef DEBUG_STATE_MACHINE
1047  if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_cleanup_delay");
1048 #endif
1050  return;
1051  } /* else it's time to clean up */
1052 
1053  request_done(request, REQUEST_DONE);
1054  break;
1055 
1056  default:
1057  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1058  break;
1059  }
1060 }
1061 
1062 
1063 /** Sit on a request until it's time to respond to it.
1064  *
1065  * For security reasons, rejects (and maybe some other) packets are
1066  * delayed for a while before we respond. This delay means that
1067  * badly behaved NASes don't hammer the server with authentication
1068  * attempts.
1069  *
1070  * Otherwise, once we reach response_delay, we send the reply, and
1071  * transition to cleanup_delay.
1072  *
1073  * \dot
1074  * digraph response_delay {
1075  * response_delay -> proxy_reply_too_late [ label = "PROXY_REPLY", arrowhead = "none" ];
1076  * response_delay -> response_delay [ label = "DUP, TIMER < timeout" ];
1077  * response_delay -> send_reply [ label = "TIMER >= timeout" ];
1078  * send_reply -> cleanup_delay;
1079  * }
1080  * \enddot
1081  */
1082 static void request_response_delay(REQUEST *request, int action)
1083 {
1084  struct timeval when, now;
1085 
1086  VERIFY_REQUEST(request);
1087 
1089  ASSERT_MASTER;
1090  COA_SEPARATE;
1092 
1093  switch (action) {
1094  case FR_ACTION_DUP:
1095  ERROR("(%u) Discarding duplicate request from "
1096  "client %s port %d - ID: %u due to delayed response",
1097  request->number, request->client->shortname,
1098  request->packet->src_port,request->packet->id);
1099  break;
1100 
1101 #ifdef WITH_PROXY
1102  case FR_ACTION_PROXY_REPLY:
1103  proxy_reply_too_late(request);
1104  break;
1105 #endif
1106 
1107  case FR_ACTION_TIMER:
1108  fr_event_now(el, &now);
1109 
1110  /*
1111  * See if it's time to send the reply. If not,
1112  * we wait some more.
1113  */
1114  when = request->reply->timestamp;
1115 
1116  tv_add(&when, request->response_delay.tv_sec * USEC);
1117  tv_add(&when, request->response_delay.tv_usec);
1118 
1119  if (timercmp(&when, &now, >)) {
1120 #ifdef DEBUG_STATE_MACHINE
1121  if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_response_delay");
1122 #endif
1124  return;
1125  } /* else it's time to send the reject */
1126 
1127  RDEBUG2("Sending delayed response");
1128  request->listener->debug(request, request->reply, false);
1129  request->listener->send(request->listener, request);
1130 
1131  /*
1132  * Clean up the request.
1133  */
1134  request_cleanup_delay_init(request);
1135  break;
1136 
1137  default:
1138  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1139  break;
1140  }
1141 }
1142 
1143 
1144 extern fr_log_t debug_log;
1145 
1146 static int request_pre_handler(REQUEST *request, UNUSED int action)
1147 {
1148  int rcode;
1149 
1150  VERIFY_REQUEST(request);
1151 
1153 
1154  if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
1155 
1156  /*
1157  * Don't decode the packet if it's an internal "fake"
1158  * request. Instead, just return so that the caller can
1159  * process it.
1160  */
1161  if (request->packet->dst_port == 0) {
1162  request->username = fr_pair_find_by_num(request->packet->vps, 0, PW_USER_NAME, TAG_ANY);
1163  request->password = fr_pair_find_by_num(request->packet->vps, 0, PW_USER_PASSWORD, TAG_ANY);
1164  return 1;
1165  }
1166 
1167  if (!request->packet->vps) { /* FIXME: check for correct state */
1168  rcode = request->listener->decode(request->listener, request);
1169 
1170 #ifdef WITH_UNLANG
1171  if (debug_condition) {
1172  /*
1173  * Ignore parse errors.
1174  */
1175  if (radius_evaluate_cond(request, RLM_MODULE_OK, 0, debug_condition)) {
1176  request->log.lvl = L_DBG_LVL_2;
1177  request->log.func = vradlog_request;
1178  request->log.output = &debug_log;
1179  }
1180  }
1181 #endif
1182 
1183  request->listener->debug(request, request->packet, true);
1184  } else {
1185  rcode = 0;
1186  }
1187 
1188  if (rcode < 0) {
1189  RATE_LIMIT(INFO("Dropping packet without response because of error: %s", fr_strerror()));
1190  request->reply->offset = -2; /* bad authenticator */
1191  return 0;
1192  }
1193 
1194  if (!request->username) {
1195  request->username = fr_pair_find_by_num(request->packet->vps, 0, PW_USER_NAME, TAG_ANY);
1196  }
1197 
1198  return 1;
1199 }
1200 
1201 
1202 /** Do the final processing of a request before we reply to the NAS.
1203  *
1204  * Various cleanups, suppress responses, copy Proxy-State, and set
1205  * response_delay or cleanup_delay;
1206  */
1207 static void request_finish(REQUEST *request, int action)
1208 {
1209  VALUE_PAIR *vp;
1210 
1211  VERIFY_REQUEST(request);
1212 
1215 
1216  (void) action; /* -Wunused */
1217 
1218 #ifdef WITH_COA
1219  /*
1220  * Don't do post-auth if we're a CoA request originated
1221  * from an Access-Request. See request_alloc_coa() for
1222  * details.
1223  */
1224  if ((request->options & RAD_REQUEST_OPTION_COA) != 0) goto done;
1225 #endif
1226 
1227  /*
1228  * Override the response code if a control:Response-Packet-Type attribute is present.
1229  */
1230  vp = fr_pair_find_by_num(request->config, 0, PW_RESPONSE_PACKET_TYPE, TAG_ANY);
1231  if (vp) {
1232  if (vp->vp_integer == 256) {
1233  RDEBUG2("Not responding to request");
1234  request->reply->code = 0;
1235  } else {
1236  request->reply->code = vp->vp_integer;
1237  }
1238  }
1239  /*
1240  * Catch Auth-Type := Reject BEFORE proxying the packet.
1241  */
1242  else if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
1243  if (request->reply->code == 0) {
1244  vp = fr_pair_find_by_num(request->config, 0, PW_AUTH_TYPE, TAG_ANY);
1245  if (!vp || (vp->vp_integer != 5)) {
1246  RDEBUG2("There was no response configured: "
1247  "rejecting request");
1248  }
1249 
1250  request->reply->code = PW_CODE_ACCESS_REJECT;
1251  }
1252  }
1253 
1254  /*
1255  * Copy Proxy-State from the request to the reply.
1256  */
1257  vp = fr_pair_list_copy_by_num(request->reply, request->packet->vps, 0, PW_PROXY_STATE, TAG_ANY);
1258  if (vp) fr_pair_add(&request->reply->vps, vp);
1259 
1260  switch (request->reply->code) {
1261  case PW_CODE_ACCESS_ACCEPT:
1262  rad_postauth(request);
1263  break;
1265  fr_pair_delete_by_num(&request->config, 0, PW_POST_AUTH_TYPE, TAG_ANY);
1266  vp = pair_make_config("Post-Auth-Type", "Challenge", T_OP_SET);
1267  if (vp) rad_postauth(request);
1268  break;
1269  default:
1270  break;
1271  }
1272 
1273  /*
1274  * Run rejected packets through
1275  *
1276  * Post-Auth-Type = Reject
1277  *
1278  * We do this separately so ACK and challenge can change the code
1279  * to reject if a module returns reject.
1280  */
1281  if (request->reply->code == PW_CODE_ACCESS_REJECT) {
1282  fr_pair_delete_by_num(&request->config, 0, PW_POST_AUTH_TYPE, TAG_ANY);
1283  vp = pair_make_config("Post-Auth-Type", "Reject", T_OP_SET);
1284  if (vp) rad_postauth(request);
1285  }
1286 
1287 #ifdef WITH_COA
1288  /*
1289  * Maybe originate a CoA request.
1290  */
1291  if ((action == FR_ACTION_RUN) && !request->proxy && request->coa) {
1292  request_coa_originate(request);
1293  }
1294 #endif
1295 
1296  /*
1297  * Clean up. These are no longer needed.
1298  */
1299  gettimeofday(&request->reply->timestamp, NULL);
1300 
1301  /*
1302  * Fake packets get marked as "done", and have the
1303  * proxy-reply section deal with the reply attributes.
1304  * We therefore don't free the reply attributes.
1305  */
1306  if (request->packet->dst_port == 0) {
1307  RDEBUG("Finished internally proxied request.");
1309  return;
1310  }
1311 
1312 #ifdef WITH_DETAIL
1313  /*
1314  * Always send the reply to the detail listener.
1315  */
1316  if (request->listener->type == RAD_LISTEN_DETAIL) {
1317  request->simul_max = 1;
1318 
1319  /*
1320  * But only print the reply if there is one.
1321  */
1322  if (request->reply->code != 0) {
1323  request->listener->debug(request, request->reply, false);
1324  }
1325 
1326  request->listener->send(request->listener, request);
1327  goto done;
1328  }
1329 #endif
1330 
1331  /*
1332  * Ignore all "do not respond" packets.
1333  * Except for the detail ones, which need to ping
1334  * the detail file reader so that it will retransmit.
1335  */
1336  if (!request->reply->code) {
1337  RDEBUG("Not sending reply to client.");
1338  goto done;
1339  }
1340 
1341  /*
1342  * If it's not in the request hash, we MIGHT not want to
1343  * send a reply.
1344  *
1345  * If duplicate packets are allowed, then then only
1346  * reason to NOT be in the request hash is because we
1347  * don't want to send a reply.
1348  *
1349  * FIXME: this is crap. The rest of the state handling
1350  * should use a different field so that we don't have two
1351  * meanings for it.
1352  *
1353  * Otherwise duplicates are forbidden, and the request is
1354  * SUPPOSED to avoid the request hash.
1355  *
1356  * In that case, we need to send a reply.
1357  */
1358  if (!request->in_request_hash &&
1359  !request->listener->nodup) {
1360  RDEBUG("Suppressing reply to client.");
1361  goto done;
1362  }
1363 
1364  /*
1365  * See if we need to delay an Access-Reject packet.
1366  */
1367  if ((request->reply->code == PW_CODE_ACCESS_REJECT) &&
1368  (request->root->reject_delay.tv_sec > 0)) {
1369  request->response_delay = request->root->reject_delay;
1370 
1371  vp = fr_pair_find_by_num(request->reply->vps, 0, PW_FREERADIUS_RESPONSE_DELAY, TAG_ANY);
1372  if (vp) {
1373  if (vp->vp_integer <= 10) {
1374  request->response_delay.tv_sec = vp->vp_integer;
1375  } else {
1376  request->response_delay.tv_sec = 10;
1377  }
1378  request->response_delay.tv_usec = 0;
1379  } else {
1380  vp = fr_pair_find_by_num(request->reply->vps, 0, PW_FREERADIUS_RESPONSE_DELAY_USEC, TAG_ANY);
1381  if (vp) {
1382  if (vp->vp_integer <= 10 * USEC) {
1383  request->response_delay.tv_sec = vp->vp_integer / USEC;
1384  request->response_delay.tv_usec = vp->vp_integer % USEC;
1385  } else {
1386  request->response_delay.tv_sec = 10;
1387  request->response_delay.tv_usec = 0;
1388  }
1389  }
1390  }
1391 
1392 #ifdef WITH_PROXY
1393  /*
1394  * If we timed out a proxy packet, don't delay
1395  * the reject any more.
1396  */
1397  if (request->proxy && !request->proxy_reply) {
1398  request->response_delay.tv_sec = 0;
1399  request->response_delay.tv_usec = 0;
1400  }
1401 #endif
1402  }
1403 
1404  /*
1405  * Send the reply.
1406  */
1407  if ((request->response_delay.tv_sec == 0) &&
1408  (request->response_delay.tv_usec == 0)) {
1409 
1410  /*
1411  * Don't print a reply if there's none to send.
1412  */
1413  if (request->reply->code != 0) {
1414  request->listener->debug(request, request->reply, false);
1415  request->listener->send(request->listener, request);
1416  }
1417 
1418  done:
1419  RDEBUG2("Finished request");
1420  request_cleanup_delay_init(request);
1421 
1422  } else {
1423  /*
1424  * Encode and sign it here, so that the master
1425  * thread can just send the encoded data, which
1426  * means it does less work.
1427  */
1428  RDEBUG2("Delaying response for %d.%06d seconds",
1429  (int) request->response_delay.tv_sec, (int) request->response_delay.tv_usec);
1430  request->listener->encode(request->listener, request);
1431  request->process = request_response_delay;
1432 
1434  }
1435 }
1436 
1437 /** Process a request from a client.
1438  *
1439  * The outcome might be that the request is proxied.
1440  *
1441  * \dot
1442  * digraph running {
1443  * running -> running [ label = "TIMER < max_request_time" ];
1444  * running -> done [ label = "TIMER >= max_request_time" ];
1445  * running -> proxy [ label = "proxied" ];
1446  * running -> dup [ label = "DUP", arrowhead = "none" ];
1447  * }
1448  * \enddot
1449  */
1450 static void request_running(REQUEST *request, int action)
1451 {
1452  int ret;
1453 
1454  VERIFY_REQUEST(request);
1455 
1458 
1459  switch (action) {
1460  case FR_ACTION_TIMER:
1461  COA_SEPARATE;
1462  (void) request_max_time(request);
1463  break;
1464 
1465  case FR_ACTION_DUP:
1466  request_dup(request);
1467  break;
1468 
1469  case FR_ACTION_RUN:
1470  if (!request_pre_handler(request, action)) {
1471 #ifdef DEBUG_STATE_MACHINE
1472  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s failed in pre-handler C-%s -> C-%s\t********\n",
1473  request->number, __FUNCTION__,
1474  child_state_names[request->child_state],
1475  child_state_names[REQUEST_DONE]);
1476 #endif
1477  FINAL_STATE(REQUEST_DONE);
1478  break;
1479  }
1480 
1481  rad_assert(request->handle != NULL);
1482  ret = request->handle(request);
1483  if (ret < 0) {
1484  RWDEBUG("State function returned error (%i): %s", ret, fr_strerror());
1485  }
1486 
1487 #ifdef WITH_PROXY
1488  /*
1489  * We may need to send a proxied request.
1490  */
1491  if ((action == FR_ACTION_RUN) &&
1492  request_will_proxy(request)) {
1493 #ifdef DEBUG_STATE_MACHINE
1494  if (rad_debug_lvl) printf("(%u) ********\tWill Proxy\t********\n", request->number);
1495 #endif
1496  /*
1497  * If this fails, it
1498  * takes care of setting
1499  * up the post proxy fail
1500  * handler.
1501  */
1502  if (request_proxy(request, 0) < 0) goto req_finished;
1503  } else
1504 #endif
1505  {
1506 #ifdef DEBUG_STATE_MACHINE
1507  if (rad_debug_lvl) printf("(%u) ********\tFinished\t********\n", request->number);
1508 #endif
1509 
1510 #ifdef WITH_PROXY
1511  req_finished:
1512 #endif
1513  request_finish(request, action);
1514  }
1515  break;
1516 
1517  default:
1518  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
1519  break;
1520  }
1521 }
1522 
1523 int request_receive(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1524  RADCLIENT *client, RAD_REQUEST_FUNP fun)
1525 {
1526  uint32_t count;
1527  RADIUS_PACKET **packet_p;
1528  REQUEST *request = NULL;
1529  struct timeval now;
1530  listen_socket_t *sock = NULL;
1531 
1532  VERIFY_PACKET(packet);
1533 
1534  /*
1535  * Set the last packet received.
1536  */
1537  now = packet->timestamp;
1538  rad_assert(packet->timestamp.tv_sec != 0);
1539 
1540 #ifdef WITH_ACCOUNTING
1541  if (listener->type != RAD_LISTEN_DETAIL)
1542 #endif
1543  {
1544  sock = listener->data;
1545  sock->last_packet = now.tv_sec;
1546 
1547 #ifdef WITH_TCP
1548  packet->proto = sock->proto;
1549 #endif
1550  }
1551 
1552  /*
1553  * Skip everything if required.
1554  */
1555  if (listener->nodup) goto skip_dup;
1556 
1557  packet_p = rbtree_finddata(pl, &packet);
1558  if (packet_p) {
1559  rad_child_state_t child_state;
1560 
1561  request = fr_packet2myptr(REQUEST, packet, packet_p);
1562  rad_assert(request->in_request_hash);
1563  child_state = request->child_state;
1564 
1565  /*
1566  * Same src/dst ip/port, length, and
1567  * authentication vector: must be a duplicate.
1568  */
1569  if ((request->packet->data_len == packet->data_len) &&
1570  (memcmp(request->packet->vector, packet->vector,
1571  sizeof(packet->vector)) == 0)) {
1572 
1573 #ifdef WITH_STATS
1574  switch (packet->code) {
1576  FR_STATS_INC(auth, total_dup_requests);
1577  break;
1578 
1579 #ifdef WITH_ACCOUNTING
1581  FR_STATS_INC(acct, total_dup_requests);
1582  break;
1583 #endif
1584 #ifdef WITH_COA
1585  case PW_CODE_COA_REQUEST:
1586  FR_STATS_INC(coa, total_dup_requests);
1587  break;
1588 
1590  FR_STATS_INC(dsc, total_dup_requests);
1591  break;
1592 #endif
1593 
1594  default:
1595  break;
1596  }
1597 #endif /* WITH_STATS */
1598 
1599  /*
1600  * Tell the state machine that there's a
1601  * duplicate request.
1602  */
1603  request->process(request, FR_ACTION_DUP);
1604  return 0; /* duplicate of live request */
1605  }
1606 
1607  /*
1608  * Mark the request as done ASAP, and before we
1609  * log anything. The child may stop processing
1610  * the request just as we're logging the
1611  * complaint.
1612  */
1613  request_done(request, FR_ACTION_DONE);
1614  request = NULL;
1615 
1616  /*
1617  * It's a new request, not a duplicate. If the
1618  * old one is done, then we can clean it up.
1619  */
1620  if (child_state <= REQUEST_RUNNING) {
1621  /*
1622  * The request is still QUEUED or RUNNING. That's a problem.
1623  */
1624  ERROR("Received conflicting packet from "
1625  "client %s port %d - ID: %u due to "
1626  "unfinished request. Giving up on old request.",
1627  client->shortname,
1628  packet->src_port, packet->id);
1629  }
1630 
1631  /*
1632  * Mark the old request as done. If there's no
1633  * child, the request will be cleaned up
1634  * immediately. If there is a child, we'll set a
1635  * timer to go clean up the request.
1636  */
1637  } /* else the new packet is unique */
1638 
1639  /*
1640  * Quench maximum number of outstanding requests.
1641  */
1642  if (main_config.max_requests &&
1643  ((count = rbtree_num_elements(pl)) > main_config.max_requests)) {
1644  RATE_LIMIT(ERROR("Dropping request (%d is too many): from client %s port %d - ID: %d", count,
1645  client->shortname,
1646  packet->src_port, packet->id);
1647  WARN("Please check the configuration file.\n"
1648  "\tThe value for 'max_requests' is probably set too low.\n"));
1649 
1650  exec_trigger(NULL, NULL, "server.max_requests", true);
1651  return 0;
1652  }
1653 
1654 skip_dup:
1655  /*
1656  * Rate-limit the incoming packets
1657  */
1658  if (sock && sock->max_rate) {
1659  uint32_t pps;
1660 
1661  pps = rad_pps(&sock->rate_pps_old, &sock->rate_pps_now, &sock->rate_time, &now);
1662  if (pps > sock->max_rate) {
1663  DEBUG("Dropping request due to rate limiting");
1664  return 0;
1665  }
1666  sock->rate_pps_now++;
1667  }
1668 
1669  /*
1670  * Allocate a pool for the request.
1671  */
1672  if (!ctx) {
1673  ctx = talloc_pool(NULL, main_config.talloc_pool_size);
1674  if (!ctx) return 0;
1675  talloc_set_name_const(ctx, "request_receive_pool");
1676 
1677  /*
1678  * The packet is still allocated from a different
1679  * context, but oh well.
1680  */
1681  (void) talloc_steal(ctx, packet);
1682  }
1683 
1684  request = request_setup(ctx, listener, packet, client, fun);
1685  if (!request) {
1686  talloc_free(ctx);
1687  return 1;
1688  }
1689 
1690  /*
1691  * Mark it as a "real" request with a context.
1692  */
1693  request->options |= RAD_REQUEST_OPTION_CTX;
1694 
1695  /*
1696  * Remember the request in the list.
1697  */
1698  if (!listener->nodup) {
1699  if (!rbtree_insert(pl, &request->packet)) {
1700  RERROR("Failed to insert request in the list of live requests: discarding it");
1701  request_done(request, FR_ACTION_DONE);
1702  return 1;
1703  }
1704 
1705  request->in_request_hash = true;
1706  }
1707 
1708  /*
1709  * Process it. Send a response, and free it.
1710  */
1711  if (listener->synchronous) {
1712 #ifdef WITH_DETAIL
1713  rad_assert(listener->type != RAD_LISTEN_DETAIL);
1714 #endif
1715 
1716  request->listener->decode(request->listener, request);
1717  request->username = fr_pair_find_by_num(request->packet->vps, 0, PW_USER_NAME, TAG_ANY);
1718  request->password = fr_pair_find_by_num(request->packet->vps, 0, PW_USER_PASSWORD, TAG_ANY);
1719 
1720  if (fun(request) < 0) REDEBUG("Error processing request: %s", fr_strerror());
1721 
1722  if (request->reply->code != 0) {
1723  request->listener->send(request->listener, request);
1724  } else {
1725  RDEBUG("Not sending reply");
1726  }
1727 
1728  /*
1729  * Don't do delayed reject. Oh well.
1730  */
1731  request_free(request);
1732  return 1;
1733  }
1734 
1735  /*
1736  * Otherwise, insert it into the state machine.
1737  * The child threads will take care of processing it.
1738  */
1740 
1741  return 1;
1742 }
1743 
1744 
1745 static REQUEST *request_setup(TALLOC_CTX *ctx, rad_listen_t *listener, RADIUS_PACKET *packet,
1746  RADCLIENT *client, RAD_REQUEST_FUNP fun)
1747 {
1748  REQUEST *request;
1749 
1750  /*
1751  * Create and initialize the new request.
1752  */
1753  request = request_alloc(ctx);
1754  if (!request) {
1755  ERROR("No memory");
1756  return NULL;
1757  }
1758  request->reply = fr_radius_alloc(request, false);
1759  if (!request->reply) {
1760  ERROR("No memory");
1761  talloc_free(request);
1762  return NULL;
1763  }
1764 
1765  request->listener = listener;
1766  request->client = client;
1767  request->packet = talloc_steal(request, packet);
1768  request->number = request_num_counter++;
1769  request->priority = listener->type;
1770  if (request->priority >= RAD_LISTEN_MAX) {
1771  request->priority = RAD_LISTEN_AUTH;
1772  }
1773 
1774  request->master_state = REQUEST_ACTIVE;
1775  request->child_state = REQUEST_RUNNING;
1776 #ifdef DEBUG_STATE_MACHINE
1777  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n",
1778  request->number, __FUNCTION__,
1779  child_state_names[request->child_state],
1780  child_state_names[REQUEST_RUNNING]);
1781 #endif
1782  request->handle = fun;
1784 
1785 #ifdef WITH_STATS
1786  request->listener->stats.last_packet = request->packet->timestamp.tv_sec;
1787  if (packet->code == PW_CODE_ACCESS_REQUEST) {
1788  request->client->auth.last_packet = request->packet->timestamp.tv_sec;
1789  radius_auth_stats.last_packet = request->packet->timestamp.tv_sec;
1790 #ifdef WITH_ACCOUNTING
1791  } else if (packet->code == PW_CODE_ACCOUNTING_REQUEST) {
1792  request->client->acct.last_packet = request->packet->timestamp.tv_sec;
1793  radius_acct_stats.last_packet = request->packet->timestamp.tv_sec;
1794 #endif
1795  }
1796 #endif /* WITH_STATS */
1797 
1798  /*
1799  * Status-Server packets go to the head of the queue.
1800  */
1801  if (request->packet->code == PW_CODE_STATUS_SERVER) request->priority = 0;
1802 
1803  /*
1804  * Set virtual server identity
1805  */
1806  if (client->server) {
1807  request->server = client->server;
1808  } else if (listener->server) {
1809  request->server = listener->server;
1810  } else {
1811  request->server = NULL;
1812  }
1813 
1814  request->root = &main_config;
1815 #ifdef WITH_TCP
1816  request->listener->count++;
1817 #endif
1818 
1819  /*
1820  * The request passes many of our sanity checks.
1821  * From here on in, if anything goes wrong, we
1822  * send a reject message, instead of dropping the
1823  * packet.
1824  */
1825 
1826  /*
1827  * Build the reply template from the request.
1828  */
1829 
1830  request->reply->sockfd = request->packet->sockfd;
1831  request->reply->dst_ipaddr = request->packet->src_ipaddr;
1832  request->reply->src_ipaddr = request->packet->dst_ipaddr;
1833  request->reply->dst_port = request->packet->src_port;
1834  request->reply->src_port = request->packet->dst_port;
1835  request->reply->if_index = request->packet->if_index;
1836  request->reply->id = request->packet->id;
1837  request->reply->code = 0; /* UNKNOWN code */
1838  memcpy(request->reply->vector, request->packet->vector,
1839  sizeof(request->reply->vector));
1840  request->reply->vps = NULL;
1841  request->reply->data = NULL;
1842  request->reply->data_len = 0;
1843 
1844  return request;
1845 }
1846 
1847 #ifdef WITH_TCP
1848 /***********************************************************************
1849  *
1850  * TCP Handlers.
1851  *
1852  ***********************************************************************/
1853 
1854 /*
1855  * Timer function for all TCP sockets.
1856  */
1857 static void tcp_socket_timer(void *ctx, struct timeval *now)
1858 {
1859  rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
1860  listen_socket_t *sock = listener->data;
1861  struct timeval end;
1862  char buffer[256];
1863  fr_socket_limit_t *limit;
1864 
1865  ASSERT_MASTER;
1866 
1867  if (listener->status != RAD_LISTEN_STATUS_KNOWN) return;
1868 
1869  fr_event_now(el, now);
1870 
1871  switch (listener->type) {
1872 #ifdef WITH_PROXY
1873  case RAD_LISTEN_PROXY:
1874  limit = &sock->home->limit;
1875  break;
1876 #endif
1877 
1878  case RAD_LISTEN_AUTH:
1879 #ifdef WITH_ACCOUNTING
1880  case RAD_LISTEN_ACCT:
1881 #endif
1882  limit = &sock->limit;
1883  break;
1884 
1885  default:
1886  return;
1887  }
1888 
1889  /*
1890  * If we enforce a lifetime, do it now.
1891  */
1892  if (limit->lifetime > 0) {
1893  end.tv_sec = sock->opened + limit->lifetime;
1894  end.tv_usec = 0;
1895 
1896  if (timercmp(&end, now, <=)) {
1897  listener->print(listener, buffer, sizeof(buffer));
1898  DEBUG("Reached maximum lifetime on socket %s", buffer);
1899 
1900  do_close:
1901 
1902 #ifdef WITH_PROXY
1903  /*
1904  * Proxy sockets get frozen, so that we don't use
1905  * them for new requests. But we do keep them
1906  * open to listen for replies to requests we had
1907  * previously sent.
1908  */
1909  if (listener->type == RAD_LISTEN_PROXY) {
1910  PTHREAD_MUTEX_LOCK(&proxy_mutex);
1911  if (!fr_packet_list_socket_freeze(proxy_list,
1912  listener->fd)) {
1913  ERROR("Fatal error freezing socket: %s", fr_strerror());
1914  fr_exit(1);
1915  }
1916  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
1917  }
1918 #endif
1919 
1920  /*
1921  * Mark the socket as "don't use if at all possible".
1922  */
1923  listener->status = RAD_LISTEN_STATUS_FROZEN;
1924  event_new_fd(listener);
1925  return;
1926  }
1927  } else {
1928  end = *now;
1929  end.tv_sec += 3600;
1930  }
1931 
1932  /*
1933  * Enforce an idle timeout.
1934  */
1935  if (limit->idle_timeout > 0) {
1936  struct timeval idle;
1937 
1938  rad_assert(sock->last_packet != 0);
1939  idle.tv_sec = sock->last_packet + limit->idle_timeout;
1940  idle.tv_usec = 0;
1941 
1942  if (timercmp(&idle, now, <=)) {
1943  listener->print(listener, buffer, sizeof(buffer));
1944  DEBUG("Reached idle timeout on socket %s", buffer);
1945  goto do_close;
1946  }
1947 
1948  /*
1949  * Enforce the minimum of idle timeout or lifetime.
1950  */
1951  if (timercmp(&idle, &end, <)) {
1952  end = idle;
1953  }
1954  }
1955 
1956  /*
1957  * Wake up at t + 0.5s. The code above checks if the timers
1958  * are <= t. This addition gives us a bit of leeway.
1959  */
1960  end.tv_usec = USEC / 2;
1961 
1962  ASSERT_MASTER;
1963  if (!fr_event_insert(el, tcp_socket_timer, listener, &end, &sock->ev)) {
1964  rad_panic("Failed to insert event");
1965  }
1966 }
1967 
1968 
1969 #ifdef WITH_PROXY
1970 /*
1971  * Add +/- 2s of jitter, as suggested in RFC 3539
1972  * and in RFC 5080.
1973  */
1974 static void add_jitter(struct timeval *when)
1975 {
1976  uint32_t jitter;
1977 
1978  when->tv_sec -= 2;
1979 
1980  jitter = fr_rand();
1981  jitter ^= (jitter >> 10);
1982  jitter &= ((1 << 22) - 1); /* 22 bits of 1 */
1983 
1984  /*
1985  * Add in ~ (4 * USEC) of jitter.
1986  */
1987  tv_add(when, jitter);
1988 }
1989 
1990 /*
1991  * Called by socket_del to remove requests with this socket
1992  */
1993 static int eol_proxy_listener(void *ctx, void *data)
1994 {
1995  rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
1996  RADIUS_PACKET **proxy_p = data;
1997  REQUEST *request;
1998 
1999  request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2000  if (request->proxy_listener != this) return 0;
2001 
2002  /*
2003  * The normal "remove_from_proxy_hash" tries to grab the
2004  * proxy mutex. We already have it held, so grabbing it
2005  * again will cause a deadlock. Instead, call the "no
2006  * lock" version of the function.
2007  */
2008  rad_assert(request->in_proxy_hash == true);
2009  remove_from_proxy_hash_nl(request, false);
2010 
2011  /*
2012  * Don't mark it as DONE. The client can retransmit, and
2013  * the packet SHOULD be re-proxied somewhere else.
2014  *
2015  * Return "2" means that the rbtree code will remove it
2016  * from the tree, and we don't need to do it ourselves.
2017  */
2018  return 2;
2019 }
2020 #endif /* WITH_PROXY */
2021 
2022 static int eol_listener(void *ctx, void *data)
2023 {
2024  rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
2025  RADIUS_PACKET **packet_p = data;
2026  REQUEST *request;
2027 
2028  request = fr_packet2myptr(REQUEST, packet, packet_p);
2029  if (request->listener != this) return 0;
2030 
2032  request->process = request_done;
2033 
2034  return 0;
2035 }
2036 #endif /* WITH_TCP */
2037 
2038 #ifdef WITH_PROXY
2039 /***********************************************************************
2040  *
2041  * Proxy handlers for the state machine.
2042  *
2043  ***********************************************************************/
2044 
2045 /*
2046  * Called with the proxy mutex held
2047  */
2048 static void remove_from_proxy_hash_nl(REQUEST *request, bool yank)
2049 {
2050  VERIFY_REQUEST(request);
2051 
2052  if (!request->in_proxy_hash) return;
2053 
2054  fr_packet_list_id_free(proxy_list, request->proxy, yank);
2055  request->in_proxy_hash = false;
2056 
2057  /*
2058  * On the FIRST reply, decrement the count of outstanding
2059  * requests. Note that this is NOT the count of sent
2060  * packets, but whether or not the home server has
2061  * responded at all.
2062  */
2063  if (request->home_server &&
2064  request->home_server->currently_outstanding) {
2065  request->home_server->currently_outstanding--;
2066 
2067  /*
2068  * If we're NOT sending it packets, AND it's been
2069  * a while since we got a response, then we don't
2070  * know if it's alive or dead.
2071  */
2072  if ((request->home_server->currently_outstanding == 0) &&
2073  (request->home_server->state == HOME_STATE_ALIVE)) {
2074  struct timeval when, now;
2075 
2076  when.tv_sec = request->home_server->last_packet_recv ;
2077  when.tv_usec = 0;
2078 
2079  timeradd(&when, request_response_window(request), &when);
2080  gettimeofday(&now, NULL);
2081 
2082  /*
2083  * last_packet + response_window
2084  *
2085  * We *administratively* mark the home
2086  * server as "unknown" state, because we
2087  * haven't seen a packet for a while.
2088  */
2089  if (timercmp(&now, &when, >)) {
2090  request->home_server->state = HOME_STATE_UNKNOWN;
2091  request->home_server->last_packet_sent = 0;
2092  request->home_server->last_packet_recv = 0;
2093  }
2094  }
2095  }
2096 
2097 #ifdef WITH_TCP
2098  rad_assert(request->proxy_listener != NULL);
2099  request->proxy_listener->count--;
2100 #endif
2101  request->proxy_listener = NULL;
2102 
2103  /*
2104  * Got from YES in hash, to NO, not in hash while we hold
2105  * the mutex. This guarantees that when another thread
2106  * grabs the mutex, the "not in hash" flag is correct.
2107  */
2108 }
2109 
2110 static void remove_from_proxy_hash(REQUEST *request)
2111 {
2112  VERIFY_REQUEST(request);
2113 
2114  /*
2115  * Check this without grabbing the mutex because it's a
2116  * lot faster that way.
2117  */
2118  if (!request->in_proxy_hash) return;
2119 
2120  /*
2121  * The "not in hash" flag is definitive. However, if the
2122  * flag says that it IS in the hash, there might still be
2123  * a race condition where it isn't.
2124  */
2125  PTHREAD_MUTEX_LOCK(&proxy_mutex);
2126 
2127  if (!request->in_proxy_hash) {
2128  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2129  return;
2130  }
2131 
2132  remove_from_proxy_hash_nl(request, true);
2133 
2134  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2135 }
2136 
2137 static int insert_into_proxy_hash(REQUEST *request)
2138 {
2139  char buffer[INET6_ADDRSTRLEN];
2140  int tries;
2141  bool success = false;
2142  void *proxy_listener;
2143 
2144  VERIFY_REQUEST(request);
2145 
2146  rad_assert(request->proxy != NULL);
2147  rad_assert(request->home_server != NULL);
2148  rad_assert(proxy_list != NULL);
2149 
2150 
2151  PTHREAD_MUTEX_LOCK(&proxy_mutex);
2152  proxy_listener = NULL;
2153  request->num_proxied_requests = 1;
2154  request->num_proxied_responses = 0;
2155 
2156  for (tries = 0; tries < 2; tries++) {
2157  rad_listen_t *this;
2158  listen_socket_t *sock;
2159 
2160  RDEBUG3("proxy: Trying to allocate ID (%d/2)", tries);
2161  success = fr_packet_list_id_alloc(proxy_list,
2162  request->home_server->proto,
2163  &request->proxy, &proxy_listener);
2164  if (success) break;
2165 
2166  if (tries > 0) continue; /* try opening new socket only once */
2167 
2168 #ifdef HAVE_PTHREAD_H
2169  if (proxy_no_new_sockets) break;
2170 #endif
2171 
2172  RDEBUG3("proxy: Trying to open a new listener to the home server");
2173  this = proxy_new_listener(proxy_ctx, request->home_server, 0);
2174  if (!this) {
2175  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2176  goto fail;
2177  }
2178 
2179  request->proxy->src_port = 0; /* Use any new socket */
2180  proxy_listener = this;
2181 
2182  sock = this->data;
2183  if (!fr_packet_list_socket_add(proxy_list, this->fd,
2184  sock->proto,
2185  &sock->other_ipaddr, sock->other_port,
2186  this)) {
2187 
2188 #ifdef HAVE_PTHREAD_H
2189  proxy_no_new_sockets = true;
2190 #endif
2191  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2192 
2193  /*
2194  * This is bad. However, the
2195  * packet list now supports 256
2196  * open sockets, which should
2197  * minimize this problem.
2198  */
2199  ERROR("Failed adding proxy socket: %s",
2200  fr_strerror());
2201  goto fail;
2202  }
2203 
2204  /*
2205  * Add it to the event loop. Ensure that we have
2206  * only one mutex locked at a time.
2207  */
2208  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2209  radius_update_listener(this);
2210  PTHREAD_MUTEX_LOCK(&proxy_mutex);
2211  }
2212 
2213  if (!proxy_listener || !success) {
2214  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2215  REDEBUG2("proxy: Failed allocating Id for proxied request");
2216  fail:
2217  request->proxy_listener = NULL;
2218  request->in_proxy_hash = false;
2219  return 0;
2220  }
2221 
2222  rad_assert(request->proxy->id >= 0);
2223 
2224  request->proxy_listener = proxy_listener;
2225  request->in_proxy_hash = true;
2226  RDEBUG3("proxy: request is now in proxy hash");
2227 
2228  /*
2229  * Keep track of maximum outstanding requests to a
2230  * particular home server. 'max_outstanding' is
2231  * enforced in home_server_ldb(), in realms.c.
2232  */
2233  request->home_server->currently_outstanding++;
2234 
2235 #ifdef WITH_TCP
2236  request->proxy_listener->count++;
2237 #endif
2238 
2239  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2240 
2241  RDEBUG3("proxy: allocating destination %s port %d - Id %d",
2242  inet_ntop(request->proxy->dst_ipaddr.af, &request->proxy->dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2243  request->proxy->dst_port,
2244  request->proxy->id);
2245 
2246  return 1;
2247 }
2248 
2249 static int process_proxy_reply(REQUEST *request, RADIUS_PACKET *reply)
2250 {
2251  int rcode;
2252  int post_proxy_type = 0;
2253  VALUE_PAIR *vp;
2254 
2255  VERIFY_REQUEST(request);
2256 
2257  /*
2258  * There may be a proxy reply, but it may be too late.
2259  */
2260  if (!request->home_server->server && !request->proxy_listener) return 0;
2261 
2262  /*
2263  * Delete any reply we had accumulated until now.
2264  */
2265  RDEBUG2("Clearing existing &reply: attributes");
2266  fr_pair_list_free(&request->reply->vps);
2267 
2268  /*
2269  * Run the packet through the post-proxy stage,
2270  * BEFORE playing games with the attributes.
2271  */
2272  vp = fr_pair_find_by_num(request->config, 0, PW_POST_PROXY_TYPE, TAG_ANY);
2273  if (vp) {
2274  post_proxy_type = vp->vp_integer;
2275  /*
2276  * If we have a proxy_reply, and it was a reject, or a NAK
2277  * setup Post-Proxy <type>.
2278  *
2279  * If the <type> doesn't have a section, then the Post-Proxy
2280  * section is ignored.
2281  */
2282  } else if (reply) {
2283  fr_dict_enum_t *dval = NULL;
2284  fr_dict_attr_t const *da = fr_dict_attr_by_num(NULL, 0, PW_POST_PROXY_TYPE);
2285 
2286  switch (reply->code) {
2287  case PW_CODE_ACCESS_REJECT:
2288  dval = fr_dict_enum_by_name(NULL, da, "Reject");
2289  if (dval) post_proxy_type = dval->value;
2290  break;
2291 
2293  dval = fr_dict_enum_by_name(NULL, da, fr_packet_codes[reply->code]);
2294  if (dval) post_proxy_type = dval->value;
2295  break;
2296 
2297  case PW_CODE_COA_NAK:
2298  dval = fr_dict_enum_by_name(NULL, da, fr_packet_codes[reply->code]);
2299  if (dval) post_proxy_type = dval->value;
2300  break;
2301 
2302  default:
2303  break;
2304  }
2305 
2306  /*
2307  * Create config:Post-Proxy-Type
2308  */
2309  if (dval) {
2310  vp = radius_pair_create(request, &request->config, PW_POST_PROXY_TYPE, 0);
2311  vp->vp_integer = dval->value;
2312  }
2313  }
2314 
2315  if (post_proxy_type > 0) RDEBUG2("Found Post-Proxy-Type %s",
2316  fr_dict_enum_name_by_da(NULL, vp->da, post_proxy_type));
2317 
2318  if (reply) {
2319  VERIFY_PACKET(reply);
2320 
2321  /*
2322  * Decode the packet if required.
2323  */
2324  if (request->proxy_listener) {
2325  rcode = request->proxy_listener->decode(request->proxy_listener, request);
2326  request->proxy_listener->debug(request, reply, true);
2327 
2328  /*
2329  * Pro-actively remove it from the proxy hash.
2330  * This is later than in 2.1.x, but it means that
2331  * the replies are authenticated before being
2332  * removed from the hash.
2333  */
2334  if ((rcode == 0) &&
2335  (request->num_proxied_requests <= request->num_proxied_responses)) {
2336  remove_from_proxy_hash(request);
2337  }
2338  } else {
2339  rad_assert(!request->in_proxy_hash);
2340  }
2341  } else if (request->in_proxy_hash) {
2342  remove_from_proxy_hash(request);
2343  }
2344 
2345  if (request->home_pool && request->home_pool->virtual_server) {
2346  char const *old_server = request->server;
2347 
2348  request->server = request->home_pool->virtual_server;
2349  RDEBUG2("server %s {", request->server);
2350  RINDENT();
2351  rcode = process_post_proxy(post_proxy_type, request);
2352  REXDENT();
2353  RDEBUG2("}");
2354  request->server = old_server;
2355  } else {
2356  rcode = process_post_proxy(post_proxy_type, request);
2357  }
2358 
2359 #ifdef WITH_COA
2360  if (request->packet->code == request->proxy->code)
2361  /*
2362  * Don't run the next bit if we originated a CoA
2363  * packet, after receiving an Access-Request or
2364  * Accounting-Request.
2365  */
2366 #endif
2367 
2368  /*
2369  * There may NOT be a proxy reply, as we may be
2370  * running Post-Proxy-Type = Fail.
2371  */
2372  if (reply) {
2373  fr_pair_add(&request->reply->vps, fr_pair_list_copy(request->reply, reply->vps));
2374 
2375  /*
2376  * Delete the Proxy-State Attributes from
2377  * the reply. These include Proxy-State
2378  * attributes from us and remote server.
2379  */
2380  fr_pair_delete_by_num(&request->reply->vps, 0, PW_PROXY_STATE, TAG_ANY);
2381  }
2382 
2383  switch (rcode) {
2384  default: /* Don't do anything */
2385  break;
2386  case RLM_MODULE_FAIL:
2387  return 0;
2388 
2389  case RLM_MODULE_HANDLED:
2390  return 0;
2391  }
2392 
2393  return 1;
2394 }
2395 
2396 static void mark_home_server_alive(REQUEST *request, home_server_t *home)
2397 {
2398  char buffer[INET6_ADDRSTRLEN];
2399 
2400  home->state = HOME_STATE_ALIVE;
2401  home->response_timeouts = 0;
2402  exec_trigger(request, home->cs, "home_server.alive", false);
2403  home->currently_outstanding = 0;
2404  home->num_sent_pings = 0;
2405  home->num_received_pings = 0;
2406  gettimeofday(&home->revive_time, NULL);
2407 
2408  fr_event_delete(el, &home->ev);
2409 
2410  RPROXY("Marking home server %s port %d alive",
2411  inet_ntop(request->proxy->dst_ipaddr.af,
2412  &request->proxy->dst_ipaddr.ipaddr,
2413  buffer, sizeof(buffer)),
2414  request->proxy->dst_port);
2415 }
2416 
2417 
2419 {
2420  RADIUS_PACKET **proxy_p;
2421  REQUEST *request;
2422  struct timeval now;
2423  char buffer[INET6_ADDRSTRLEN];
2424 
2425  VERIFY_PACKET(packet);
2426 
2427  PTHREAD_MUTEX_LOCK(&proxy_mutex);
2428  proxy_p = fr_packet_list_find_byreply(proxy_list, packet);
2429 
2430  if (!proxy_p) {
2431  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2432  PROXY("No outstanding request was found for %s packet from host %s port %d - ID %u",
2433  fr_packet_codes[packet->code],
2434  inet_ntop(packet->src_ipaddr.af,
2435  &packet->src_ipaddr.ipaddr,
2436  buffer, sizeof(buffer)),
2437  packet->src_port, packet->id);
2438  return 0;
2439  }
2440 
2441  request = fr_packet2myptr(REQUEST, proxy, proxy_p);
2442  request->num_proxied_responses++; /* needs to be protected by lock */
2443 
2444  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
2445 
2446  /*
2447  * No reply, BUT the current packet fails verification:
2448  * ignore it. This does the MD5 calculations in the
2449  * server core, but I guess we can fix that later.
2450  */
2451  if (!request->proxy_reply &&
2452  (fr_radius_verify(packet, request->proxy,
2453  request->home_server->secret) != 0)) {
2454  DEBUG("Ignoring spoofed proxy reply. Signature is invalid");
2455  return 0;
2456  }
2457 
2458  /*
2459  * The home server sent us a packet which doesn't match
2460  * something we have: ignore it. This is done only to
2461  * catch the case of broken systems.
2462  */
2463  if (request->proxy_reply &&
2464  (memcmp(request->proxy_reply->vector,
2465  packet->vector,
2466  sizeof(request->proxy_reply->vector)) != 0)) {
2467  RDEBUG2("Ignoring conflicting proxy reply");
2468  return 0;
2469  }
2470 
2471  gettimeofday(&now, NULL);
2472 
2473  /*
2474  * Status-Server packets don't count as real packets.
2475  */
2476  if (request->proxy->code != PW_CODE_STATUS_SERVER) {
2477  listen_socket_t *sock = request->proxy_listener->data;
2478 
2479  request->home_server->last_packet_recv = now.tv_sec;
2480  sock->last_packet = now.tv_sec;
2481  }
2482 
2483  /*
2484  * If we have previously seen a reply, ignore the
2485  * duplicate.
2486  */
2487  if (request->proxy_reply) {
2488  RDEBUG2("Discarding duplicate reply from host %s port %d - ID: %d",
2489  inet_ntop(packet->src_ipaddr.af,
2490  &packet->src_ipaddr.ipaddr,
2491  buffer, sizeof(buffer)),
2492  packet->src_port, packet->id);
2493  return 0;
2494  }
2495 
2496  /*
2497  * Call the state machine to do something useful with the
2498  * request.
2499  */
2500  request->proxy_reply = talloc_steal(request, packet);
2501  request->priority = RAD_LISTEN_PROXY;
2502 
2503 #ifdef WITH_STATS
2504  /*
2505  * Update the proxy listener stats here, because only one
2506  * thread accesses that at a time. The home_server and
2507  * main proxy_*_stats structures are updated once the
2508  * request is cleaned up.
2509  */
2510  request->proxy_listener->stats.total_responses++;
2511 
2512  request->home_server->stats.last_packet = packet->timestamp.tv_sec;
2513  request->proxy_listener->stats.last_packet = packet->timestamp.tv_sec;
2514 
2515  switch (request->proxy->code) {
2517  proxy_auth_stats.last_packet = packet->timestamp.tv_sec;
2518 
2519  if (request->proxy_reply->code == PW_CODE_ACCESS_ACCEPT) {
2521 
2522  } else if (request->proxy_reply->code == PW_CODE_ACCESS_REJECT) {
2524 
2525  } else if (request->proxy_reply->code == PW_CODE_ACCESS_CHALLENGE) {
2527  }
2528  break;
2529 
2530 #ifdef WITH_ACCOUNTING
2532  proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2533 
2534  request->proxy_listener->stats.total_responses++;
2535  proxy_acct_stats.last_packet = packet->timestamp.tv_sec;
2536  break;
2537 
2538 #endif
2539 
2540 #ifdef WITH_COA
2541  case PW_CODE_COA_REQUEST:
2542  request->proxy_listener->stats.total_responses++;
2543  proxy_coa_stats.last_packet = packet->timestamp.tv_sec;
2544  break;
2545 
2547  request->proxy_listener->stats.total_responses++;
2548  proxy_dsc_stats.last_packet = packet->timestamp.tv_sec;
2549  break;
2550 
2551 #endif
2552  default:
2553  break;
2554  }
2555 #endif
2556 
2557  /*
2558  * If we hadn't been sending the home server packets for
2559  * a while, just mark it alive. Or, if it was zombie,
2560  * it's now responded, and is therefore alive.
2561  */
2562  if ((request->home_server->state == HOME_STATE_UNKNOWN) ||
2563  (request->home_server->state == HOME_STATE_ZOMBIE)) {
2564  mark_home_server_alive(request, request->home_server);
2565  }
2566 
2567  /*
2568  * Tell the request state machine that we have a proxy
2569  * reply. Depending on the function, this should either
2570  * ignore it, or process it.
2571  */
2572  request->process(request, FR_ACTION_PROXY_REPLY);
2573 
2574  return 1;
2575 }
2576 
2577 
2578 static int setup_post_proxy_fail(REQUEST *request)
2579 {
2580  fr_dict_enum_t const *dval = NULL;
2581  fr_dict_attr_t const *da = fr_dict_attr_by_num(NULL, 0, PW_POST_PROXY_TYPE);
2582  VALUE_PAIR *vp;
2583 
2584  VERIFY_REQUEST(request);
2585 
2586  if (request->proxy->code == PW_CODE_ACCESS_REQUEST) {
2587  dval = fr_dict_enum_by_name(NULL, da, "Fail-Authentication");
2588  } else if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
2589  dval = fr_dict_enum_by_name(NULL, da, "Fail-Accounting");
2590 #ifdef WITH_COA
2591  } else if (request->proxy->code == PW_CODE_COA_REQUEST) {
2592  dval = fr_dict_enum_by_name(NULL, da, "Fail-CoA");
2593 
2594  } else if (request->proxy->code == PW_CODE_DISCONNECT_REQUEST) {
2595  dval = fr_dict_enum_by_name(NULL, da, "Fail-Disconnect");
2596 #endif
2597  } else {
2598  WARN("Unknown packet type in Post-Proxy-Type Fail: ignoring");
2599  return 0;
2600  }
2601 
2602  if (!dval) dval = fr_dict_enum_by_name(NULL, da, "Fail");
2603 
2604  if (!dval) {
2605  fr_pair_delete_by_num(&request->config, 0, PW_POST_PROXY_TYPE, TAG_ANY);
2606  return 0;
2607  }
2608 
2609  vp = fr_pair_find_by_num(request->config, 0, PW_POST_PROXY_TYPE, TAG_ANY);
2610  if (!vp) vp = radius_pair_create(request, &request->config,
2611  PW_POST_PROXY_TYPE, 0);
2612  vp->vp_integer = dval->value;
2613 
2614  return 1;
2615 }
2616 
2617 
2618 /** Process a request after the proxy has timed out.
2619  *
2620  * Run the packet through Post-Proxy-Type Fail
2621  *
2622  * \dot
2623  * digraph proxy_no_reply {
2624  * proxy_no_reply;
2625  *
2626  * proxy_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
2627  * proxy_no_reply -> timer [ label = "TIMER < max_request_time" ];
2628  * proxy_no_reply -> proxy_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
2629  * proxy_no_reply -> process_proxy_reply [ label = "RUN" ];
2630  * proxy_no_reply -> done [ label = "TIMER >= timeout" ];
2631  * }
2632  * \enddot
2633  */
2634 static void proxy_no_reply(REQUEST *request, int action)
2635 {
2636  VERIFY_REQUEST(request);
2637 
2640 
2641  switch (action) {
2642  case FR_ACTION_DUP:
2643  request_dup(request);
2644  break;
2645 
2646  case FR_ACTION_TIMER:
2647  (void) request_max_time(request);
2648  break;
2649 
2650  case FR_ACTION_PROXY_REPLY:
2651  proxy_reply_too_late(request);
2652  break;
2653 
2654  case FR_ACTION_RUN:
2655  if (process_proxy_reply(request, NULL)) {
2656  request->handle(request);
2657  }
2658  request_finish(request, action);
2659  break;
2660 
2661  default:
2662  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2663  break;
2664  }
2665 }
2666 
2667 /** Process the request after receiving a proxy reply.
2668  *
2669  * Throught the post-proxy section, and the through the handler
2670  * function.
2671  *
2672  * \dot
2673  * digraph proxy_running {
2674  * proxy_running;
2675  *
2676  * proxy_running -> dup [ label = "DUP", arrowhead = "none" ];
2677  * proxy_running -> timer [ label = "TIMER < max_request_time" ];
2678  * proxy_running -> process_proxy_reply [ label = "RUN" ];
2679  * proxy_running -> done [ label = "TIMER >= timeout" ];
2680  * }
2681  * \enddot
2682  */
2683 static void proxy_running(REQUEST *request, int action)
2684 {
2685  VERIFY_REQUEST(request);
2686 
2689 
2690  switch (action) {
2691  case FR_ACTION_DUP:
2692  request_dup(request);
2693  break;
2694 
2695  case FR_ACTION_TIMER:
2696  (void) request_max_time(request);
2697  break;
2698 
2699  case FR_ACTION_RUN:
2700  if (process_proxy_reply(request, request->proxy_reply)) {
2701  request->handle(request);
2702  }
2703  request_finish(request, action);
2704  break;
2705 
2706  default: /* duplicate proxy replies are suppressed */
2707  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
2708  break;
2709  }
2710 }
2711 
2712 /** Determine if a #REQUEST needs to be proxied, and perform pre-proxy operations
2713  *
2714  * Whether a request will be proxied is determined by the attributes present
2715  * in request->config. If any of the following attributes are found, the
2716  * request may be proxied.
2717  *
2718  * The key attributes are:
2719  * - PW_PROXY_TO_REALM - Specifies a realm the request should be proxied to.
2720  * - PW_HOME_SERVER_POOL - Specifies a specific home server pool to proxy to.
2721  * - PW_PACKET_DST_IP_ADDRESS - Specifies a specific IPv4 home server to proxy to.
2722  * - PW_PACKET_DST_IPV6_ADDRESS - Specifies a specific IPv6 home server to proxy to.
2723  *
2724  * Certain packet types such as #PW_CODE_STATUS_SERVER will never be proxied.
2725  *
2726  * If request should be proxied, will:
2727  * - Add request:Proxy-State
2728  * - Strip the current username value of its realm (depending on config)
2729  * - Create a CHAP-Challenge from the original request vector, if one doesn't already
2730  * exist.
2731  * - Call the pre-process section in the current server, or in the virtual server
2732  * associated with the home server pool we're proxying to.
2733  *
2734  * @todo A lot of this logic is RADIUS specific, and should be moved out into a protocol
2735  * specific function.
2736  *
2737  * @param request The #REQUEST to evaluate for proxying.
2738  * @return
2739  * - 0 if not proxying.
2740  * - 1 if #REQUEST should be proxied.
2741  * - -1 on failure.
2742  */
2743 static int request_will_proxy(REQUEST *request)
2744 {
2745  int rcode, pre_proxy_type = 0;
2746  char const *realmname = NULL;
2747  VALUE_PAIR *vp, *strippedname;
2748  home_server_t *home;
2749  REALM *realm = NULL;
2750  home_pool_t *pool = NULL;
2751 
2752  VERIFY_REQUEST(request);
2753 
2754  if (!request->root->proxy_requests) return 0;
2755  if (request->packet->dst_port == 0) return 0;
2756  if (request->packet->code == PW_CODE_STATUS_SERVER) return 0;
2757  if (request->in_proxy_hash) return 0;
2758 
2759  /*
2760  * FIXME: for 3.0, allow this only for rejects?
2761  */
2762  if (request->reply->code != 0) return 0;
2763 
2764  vp = fr_pair_find_by_num(request->config, 0, PW_PROXY_TO_REALM, TAG_ANY);
2765  if (vp) {
2766  realm = realm_find2(vp->vp_strvalue);
2767  if (!realm) {
2768  REDEBUG2("Cannot proxy to unknown realm %s",
2769  vp->vp_strvalue);
2770  return 0;
2771  }
2772 
2773  realmname = vp->vp_strvalue;
2774 
2775  /*
2776  * Figure out which pool to use.
2777  */
2778  if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2779  pool = realm->auth_pool;
2780 
2781 #ifdef WITH_ACCOUNTING
2782  } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2783  pool = realm->acct_pool;
2784 #endif
2785 
2786 #ifdef WITH_COA
2787  } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2788  (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2789  pool = realm->coa_pool;
2790 #endif
2791 
2792  } else {
2793  return 0;
2794  }
2795 
2796  } else if ((vp = fr_pair_find_by_num(request->config, 0, PW_HOME_SERVER_POOL, TAG_ANY)) != NULL) {
2797  int pool_type;
2798 
2799  switch (request->packet->code) {
2801  pool_type = HOME_TYPE_AUTH;
2802  break;
2803 
2804 #ifdef WITH_ACCOUNTING
2806  pool_type = HOME_TYPE_ACCT;
2807  break;
2808 #endif
2809 
2810 #ifdef WITH_COA
2811  case PW_CODE_COA_REQUEST:
2813  pool_type = HOME_TYPE_COA;
2814  break;
2815 #endif
2816 
2817  default:
2818  return 0;
2819  }
2820 
2821  pool = home_pool_byname(vp->vp_strvalue, pool_type);
2822 
2823  /*
2824  * Send it directly to a home server (i.e. NAS)
2825  */
2826  } else if (((vp = fr_pair_find_by_num(request->config, 0, PW_PACKET_DST_IP_ADDRESS, TAG_ANY)) != NULL) ||
2827  ((vp = fr_pair_find_by_num(request->config, 0, PW_PACKET_DST_IPV6_ADDRESS, TAG_ANY)) != NULL)) {
2828  uint16_t dst_port;
2829  fr_ipaddr_t dst_ipaddr;
2830 
2831  memset(&dst_ipaddr, 0, sizeof(dst_ipaddr));
2832 
2833  if (vp->da->attr == PW_PACKET_DST_IP_ADDRESS) {
2834  dst_ipaddr.af = AF_INET;
2835  dst_ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
2836  dst_ipaddr.prefix = 32;
2837  } else {
2838  dst_ipaddr.af = AF_INET6;
2839  memcpy(&dst_ipaddr.ipaddr.ip6addr, &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
2840  dst_ipaddr.prefix = 128;
2841  }
2842 
2843  vp = fr_pair_find_by_num(request->config, 0, PW_PACKET_DST_PORT, TAG_ANY);
2844  if (!vp) {
2845  if (request->packet->code == PW_CODE_ACCESS_REQUEST) {
2846  dst_port = PW_AUTH_UDP_PORT;
2847 
2848 #ifdef WITH_ACCOUNTING
2849  } else if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
2850  dst_port = PW_ACCT_UDP_PORT;
2851 #endif
2852 
2853 #ifdef WITH_COA
2854  } else if ((request->packet->code == PW_CODE_COA_REQUEST) ||
2855  (request->packet->code == PW_CODE_DISCONNECT_REQUEST)) {
2856  dst_port = PW_COA_UDP_PORT;
2857 #endif
2858  } else { /* shouldn't happen for RADIUS... */
2859  return 0;
2860  }
2861 
2862  } else {
2863  dst_port = vp->vp_integer;
2864  }
2865 
2866  /*
2867  * Nothing does CoA over TCP.
2868  */
2869  home = home_server_find(&dst_ipaddr, dst_port, IPPROTO_UDP);
2870  if (!home) {
2871  char buffer[INET6_ADDRSTRLEN];
2872 
2873  WARN("No such home server %s port %u",
2874  inet_ntop(dst_ipaddr.af, &dst_ipaddr.ipaddr, buffer, sizeof(buffer)),
2875  (unsigned int) dst_port);
2876  return 0;
2877  }
2878 
2879  /*
2880  * The home server is alive (or may be alive).
2881  * Send the packet to the IP.
2882  */
2883  if (home->state != HOME_STATE_IS_DEAD) goto do_home;
2884 
2885  /*
2886  * The home server is dead. If you wanted
2887  * fail-over, you should have proxied to a pool.
2888  * Sucks to be you.
2889  */
2890 
2891  return 0;
2892 
2893  } else {
2894  return 0;
2895  }
2896 
2897  if (!pool) {
2898  RWDEBUG2("Cancelling proxy as no home pool exists");
2899  return 0;
2900  }
2901 
2902  if (request->listener->synchronous) {
2903  WARN("Cannot proxy a request which is from a 'synchronous' socket");
2904  return 0;
2905  }
2906 
2907  request->home_pool = pool;
2908 
2909  home = home_server_ldb(realmname, pool, request);
2910 
2911  if (!home) {
2912  REDEBUG2("Failed to find live home server: Cancelling proxy");
2913  return 0;
2914  }
2915 
2916 do_home:
2917  home_server_update_request(home, request);
2918 
2919 #ifdef WITH_COA
2920  /*
2921  * Once we've decided to proxy a request, we cannot send
2922  * a CoA packet. So we free up any CoA packet here.
2923  */
2924  if (request->coa) request_done(request->coa, FR_ACTION_DONE);
2925 #endif
2926 
2927  /*
2928  * Remember that we sent the request to a Realm.
2929  */
2930  if (realmname) pair_make_request("Realm", realmname, T_OP_EQ);
2931 
2932  /*
2933  * Strip the name, if told to.
2934  *
2935  * Doing it here catches the case of proxied tunneled
2936  * requests.
2937  */
2938  if (realm && (realm->strip_realm == true) &&
2939  (strippedname = fr_pair_find_by_num(request->proxy->vps, 0, PW_STRIPPED_USER_NAME, TAG_ANY)) != NULL) {
2940  /*
2941  * If there's a Stripped-User-Name attribute in
2942  * the request, then use THAT as the User-Name
2943  * for the proxied request, instead of the
2944  * original name.
2945  *
2946  * This is done by making a copy of the
2947  * Stripped-User-Name attribute, turning it into
2948  * a User-Name attribute, deleting the
2949  * Stripped-User-Name and User-Name attributes
2950  * from the vps list, and making the new
2951  * User-Name the head of the vps list.
2952  */
2953  vp = fr_pair_find_by_num(request->proxy->vps, 0, PW_USER_NAME, TAG_ANY);
2954  if (!vp) {
2955  vp_cursor_t cursor;
2956  vp = radius_pair_create(NULL, NULL,
2957  PW_USER_NAME, 0);
2958  rad_assert(vp != NULL); /* handled by above function */
2959  /* Insert at the START of the list */
2960  /* FIXME: Can't make assumptions about ordering */
2961  fr_cursor_init(&cursor, &vp);
2962  fr_cursor_merge(&cursor, request->proxy->vps);
2963  request->proxy->vps = vp;
2964  }
2965  fr_pair_value_strcpy(vp, strippedname->vp_strvalue);
2966 
2967  /*
2968  * Do NOT delete Stripped-User-Name.
2969  */
2970  }
2971 
2972  /*
2973  * If there is no PW_CHAP_CHALLENGE attribute but
2974  * there is a PW_CHAP_PASSWORD we need to add it
2975  * since we can't use the request authenticator
2976  * anymore - we changed it.
2977  */
2978  if ((request->packet->code == PW_CODE_ACCESS_REQUEST) &&
2979  fr_pair_find_by_num(request->proxy->vps, 0, PW_CHAP_PASSWORD, TAG_ANY) &&
2980  fr_pair_find_by_num(request->proxy->vps, 0, PW_CHAP_CHALLENGE, TAG_ANY) == NULL) {
2981  vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_CHAP_CHALLENGE, 0);
2982  fr_pair_value_memcpy(vp, request->packet->vector, sizeof(request->packet->vector));
2983  }
2984 
2985  /*
2986  * The RFC's say we have to do this, but FreeRADIUS
2987  * doesn't need it.
2988  */
2989  vp = radius_pair_create(request->proxy, &request->proxy->vps, PW_PROXY_STATE, 0);
2990  fr_pair_value_snprintf(vp, "%u", request->packet->id);
2991 
2992  /*
2993  * Should be done BEFORE inserting into proxy hash, as
2994  * pre-proxy may use this information, or change it.
2995  */
2996  request->proxy->code = request->packet->code;
2997 
2998  /*
2999  * Call the pre-proxy routines.
3000  */
3001  vp = fr_pair_find_by_num(request->config, 0, PW_PRE_PROXY_TYPE, TAG_ANY);
3002  if (vp) {
3003  fr_dict_enum_t const *dval = fr_dict_enum_by_da(NULL, vp->da, vp->vp_integer);
3004  /* Must be a validation issue */
3005  rad_assert(dval);
3006  RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
3007  pre_proxy_type = vp->vp_integer;
3008  }
3009 
3010  /*
3011  * home_pool may be NULL when originating CoA packets,
3012  * because they go directly to an IP address.
3013  */
3014  if (request->home_pool && request->home_pool->virtual_server) {
3015  char const *old_server = request->server;
3016 
3017  request->server = request->home_pool->virtual_server;
3018 
3019  RDEBUG2("server %s {", request->server);
3020  RINDENT();
3021  rcode = process_pre_proxy(pre_proxy_type, request);
3022  REXDENT();
3023  RDEBUG2("}");
3024 
3025  request->server = old_server;
3026  } else {
3027  rcode = process_pre_proxy(pre_proxy_type, request);
3028  }
3029 
3030  switch (rcode) {
3031  case RLM_MODULE_FAIL:
3032  case RLM_MODULE_INVALID:
3033  case RLM_MODULE_NOTFOUND:
3034  case RLM_MODULE_USERLOCK:
3035  default:
3036  /* FIXME: debug print failed stuff */
3037  return -1;
3038 
3039  case RLM_MODULE_REJECT:
3040  case RLM_MODULE_HANDLED:
3041  return 0;
3042 
3043  /*
3044  * Only proxy the packet if the pre-proxy code succeeded.
3045  */
3046  case RLM_MODULE_NOOP:
3047  case RLM_MODULE_OK:
3048  case RLM_MODULE_UPDATED:
3049  return 1;
3050  }
3051 }
3052 
3053 static int proxy_to_virtual_server(REQUEST *request)
3054 {
3055  REQUEST *fake;
3056 
3057  if (request->packet->dst_port == 0) {
3058  WARN("Cannot proxy an internal request");
3059  return 0;
3060  }
3061 
3062  DEBUG("Proxying to virtual server %s",
3063  request->home_server->server);
3064 
3065  /*
3066  * Packets to virtual servers don't get
3067  * retransmissions sent to them. And the virtual
3068  * server is run ONLY if we have no child
3069  * threads, or we're running in a child thread.
3070  */
3071  rad_assert(!spawn_workers || !we_are_master());
3072 
3073  fake = request_alloc_fake(request);
3074 
3075  fake->packet->vps = fr_pair_list_copy(fake->packet, request->packet->vps);
3076  talloc_free(request->proxy);
3077 
3078  fake->server = request->home_server->server;
3079  fake->handle = request->handle;
3080  fake->process = NULL; /* should never be run for anything */
3081 
3082  /*
3083  * Run the virtual server.
3084  */
3086 
3087  request->proxy = talloc_steal(request, fake->packet);
3088  fake->packet = NULL;
3089  request->proxy_reply = talloc_steal(request, fake->reply);
3090  fake->reply = NULL;
3091 
3092  talloc_free(fake);
3093 
3094  /*
3095  * No reply code, toss the reply we have,
3096  * and do post-proxy-type Fail.
3097  */
3098  if (!request->proxy_reply->code) {
3099  TALLOC_FREE(request->proxy_reply);
3100  setup_post_proxy_fail(request);
3101  }
3102 
3103  /*
3104  * Do the proxy reply (if any)
3105  */
3106  if (process_proxy_reply(request, request->proxy_reply)) {
3107  request->handle(request);
3108  }
3109 
3110  return -1; /* so we call request_finish */
3111 }
3112 
3113 
3114 static int request_proxy(REQUEST *request, int retransmit)
3115 {
3116  char buffer[INET6_ADDRSTRLEN];
3117 
3118  VERIFY_REQUEST(request);
3119 
3120  rad_assert(request->parent == NULL);
3121  rad_assert(request->home_server != NULL);
3122 
3123  if (request->master_state == REQUEST_STOP_PROCESSING) return 0;
3124 
3125 #ifdef WITH_COA
3126  if (request->coa) {
3127  RWDEBUG("Cannot proxy and originate CoA packets at the same time. Cancelling CoA request");
3128  request_done(request->coa, FR_ACTION_DONE);
3129  }
3130 #endif
3131 
3132  /*
3133  * The request may need sending to a virtual server.
3134  * This code is more than a little screwed up. The rest
3135  * of the state machine doesn't handle parent / child
3136  * relationships well. i.e. if the child request takes
3137  * too long, the core will mark the *parent* as "stop
3138  * processing". And the child will continue without
3139  * knowing anything...
3140  *
3141  * So, we have some horrible hacks to get around that.
3142  */
3143  if (request->home_server->server) return proxy_to_virtual_server(request);
3144 
3145  /*
3146  * We're actually sending a proxied packet. Do that now.
3147  */
3148  if (!request->in_proxy_hash && !insert_into_proxy_hash(request)) {
3149  RPROXY("Failed to insert request into the proxy list");
3150  return -1;
3151  }
3152 
3153  rad_assert(request->proxy->id >= 0);
3154 
3155  if (rad_debug_lvl) {
3156  struct timeval *response_window;
3157 
3158  response_window = request_response_window(request);
3159 
3160 #ifdef WITH_TLS
3161  if (request->home_server->tls) {
3162  RDEBUG2("Proxying request to home server %s port %d (TLS) timeout %d.%06d",
3163  inet_ntop(request->proxy->dst_ipaddr.af,
3164  &request->proxy->dst_ipaddr.ipaddr,
3165  buffer, sizeof(buffer)),
3166  request->proxy->dst_port,
3167  (int) response_window->tv_sec, (int) response_window->tv_usec);
3168  } else
3169 #endif
3170  RDEBUG2("Proxying request to home server %s port %d timeout %d.%06d",
3171  inet_ntop(request->proxy->dst_ipaddr.af,
3172  &request->proxy->dst_ipaddr.ipaddr,
3173  buffer, sizeof(buffer)),
3174  request->proxy->dst_port,
3175  (int) response_window->tv_sec, (int) response_window->tv_usec);
3176 
3177 
3178  }
3179 
3180  gettimeofday(&request->proxy_retransmit, NULL);
3181  if (!retransmit) {
3182  request->proxy->timestamp = request->proxy_retransmit;
3183  }
3184  request->home_server->last_packet_sent = request->proxy_retransmit.tv_sec;
3185 
3186  /*
3187  * Encode the packet before we do anything else.
3188  */
3189  request->proxy_listener->encode(request->proxy_listener, request);
3190  request->proxy_listener->debug(request, request->proxy, false);
3191 
3192  /*
3193  * Set the state function, then the state, no child, and
3194  * send the packet.
3195  *
3196  * The order here is different from other state changes
3197  * due to race conditions with replies from the home
3198  * server.
3199  */
3200  request->process = proxy_wait_for_reply;
3201  request->child_state = REQUEST_PROXIED;
3202  request->component = "<REQUEST_PROXIED>";
3203  request->module = "";
3205 
3206  /*
3207  * And send the packet.
3208  */
3209  request->proxy_listener->send(request->proxy_listener, request);
3210  return 1;
3211 }
3212 
3213 /*
3214  * Proxy the packet as if it was new.
3215  */
3216 static int request_proxy_anew(REQUEST *request)
3217 {
3218  home_server_t *home;
3219 
3220  VERIFY_REQUEST(request);
3221 
3222  /*
3223  * Delete the request from the proxy list.
3224  *
3225  * The packet list code takes care of ensuring that IDs
3226  * aren't reused until all 256 IDs have been used. So
3227  * there's a 1/256 chance of re-using the same ID when
3228  * we're sending to the same home server. Which is
3229  * acceptable.
3230  */
3231  remove_from_proxy_hash(request);
3232 
3233  /*
3234  * Find a live home server for the request.
3235  */
3236  home = home_server_ldb(NULL, request->home_pool, request);
3237  if (!home) {
3238  REDEBUG2("Failed to find live home server for request");
3239  post_proxy_fail:
3240  if (setup_post_proxy_fail(request)) {
3242  } else {
3243  gettimeofday(&request->reply->timestamp, NULL);
3244  request_cleanup_delay_init(request);
3245  }
3246  return 0;
3247  }
3248 
3249 #ifdef WITH_ACCOUNTING
3250  /*
3251  * Update the Acct-Delay-Time attribute.
3252  */
3253  if (request->packet->code == PW_CODE_ACCOUNTING_REQUEST) {
3254  VALUE_PAIR *vp;
3255 
3256  vp = fr_pair_find_by_num(request->proxy->vps, 0, PW_ACCT_DELAY_TIME, TAG_ANY);
3257  if (!vp) vp = radius_pair_create(request->proxy,
3258  &request->proxy->vps,
3259  PW_ACCT_DELAY_TIME, 0);
3260  if (vp) {
3261  struct timeval now;
3262 
3263  gettimeofday(&now, NULL);
3264  vp->vp_integer += now.tv_sec - request->proxy_retransmit.tv_sec;
3265  }
3266  }
3267 #endif
3268 
3269  /*
3270  * May have failed over to a "fallback" virtual server.
3271  * If so, run that instead of doing proxying to a real
3272  * server.
3273  */
3274  if (home->server) {
3275  request->home_server = home;
3276  TALLOC_FREE(request->proxy);
3277 
3278  (void) proxy_to_virtual_server(request);
3279  return 0;
3280  }
3281 
3282  home_server_update_request(home, request);
3283 
3284  if (!insert_into_proxy_hash(request)) {
3285  RPROXY("Failed to insert retransmission into the proxy list");
3286  goto post_proxy_fail;
3287  }
3288 
3289  /*
3290  * Free the old packet, to force re-encoding
3291  */
3292  talloc_free(request->proxy->data);
3293  request->proxy->data = NULL;
3294  request->proxy->data_len = 0;
3295 
3296  if (request_proxy(request, 1) != 1) goto post_proxy_fail;
3297 
3298  return 1;
3299 }
3300 
3301 
3302 /** Ping a home server.
3303  *
3304  */
3305 static void request_ping(REQUEST *request, int action)
3306 {
3307  home_server_t *home = request->home_server;
3308  char buffer[INET6_ADDRSTRLEN];
3309 
3310  VERIFY_REQUEST(request);
3311 
3313  ASSERT_MASTER;
3314 
3315  switch (action) {
3316  case FR_ACTION_TIMER:
3317  ERROR("No response to status check %d ID %u for home server %s port %d",
3318  request->number,
3319  request->proxy->id,
3320  inet_ntop(request->proxy->dst_ipaddr.af,
3321  &request->proxy->dst_ipaddr.ipaddr,
3322  buffer, sizeof(buffer)),
3323  request->proxy->dst_port);
3324  break;
3325 
3326  case FR_ACTION_PROXY_REPLY:
3327  rad_assert(request->in_proxy_hash);
3328 
3329  request->home_server->num_received_pings++;
3330  RPROXY("Received response to status check %d ID %u (%d in current sequence)",
3331  request->number, request->proxy->id, home->num_received_pings);
3332 
3333  /*
3334  * Remove the request from any hashes
3335  */
3336  fr_event_delete(el, &request->ev);
3337  remove_from_proxy_hash(request);
3338 
3339  /*
3340  * The control socket may have marked the home server as
3341  * alive. OR, it may have suddenly started responding to
3342  * requests again. If so, don't re-do the "make alive"
3343  * work.
3344  */
3345  if (home->state == HOME_STATE_ALIVE) break;
3346 
3347  /*
3348  * It's dead, and we haven't received enough ping
3349  * responses to mark it "alive". Wait a bit.
3350  *
3351  * If it's zombie, we mark it alive immediately.
3352  */
3353  if ((home->state == HOME_STATE_IS_DEAD) &&
3354  (home->num_received_pings < home->num_pings_to_alive)) {
3355  return;
3356  }
3357 
3358  /*
3359  * Mark it alive and delete any outstanding
3360  * pings.
3361  */
3362  mark_home_server_alive(request, home);
3363  break;
3364 
3365  default:
3366  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3367  break;
3368  }
3369 
3370  rad_assert(!request->in_request_hash);
3371  rad_assert(request->ev == NULL);
3373  request_done(request, FR_ACTION_DONE);
3374 }
3375 
3376 /*
3377  * Called from start of zombie period, OR after control socket
3378  * marks the home server dead.
3379  */
3380 static void ping_home_server(void *ctx, struct timeval *now)
3381 {
3382  home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3383  REQUEST *request;
3384  VALUE_PAIR *vp;
3385  struct timeval when;
3386 
3387  if ((home->state == HOME_STATE_ALIVE) ||
3388 #ifdef WITH_TCP
3389  (home->proto == IPPROTO_TCP) ||
3390 #endif
3391  (home->ev != NULL)) {
3392  return;
3393  }
3394 
3395  ASSERT_MASTER;
3396 
3397  /*
3398  * We've run out of zombie time. Mark it dead.
3399  */
3400  if (home->state == HOME_STATE_ZOMBIE) {
3401  when = home->zombie_period_start;
3402  when.tv_sec += home->zombie_period;
3403 
3404  if (timercmp(&when, now, <)) {
3405  DEBUG("PING: Zombie period is over for home server %s", home->log_name);
3406  mark_home_server_dead(home, now);
3407  }
3408  }
3409 
3410  /*
3411  * We're not supposed to be pinging it. Just wake up
3412  * when we're supposed to mark it dead.
3413  */
3414  if (home->ping_check == HOME_PING_CHECK_NONE) {
3415  if (home->state == HOME_STATE_ZOMBIE) {
3416  home->when = home->zombie_period_start;
3417  home->when.tv_sec += home->zombie_period;
3419  }
3420 
3421  /*
3422  * Else mark_home_server_dead will set a timer
3423  * for revive_interval.
3424  */
3425  return;
3426  }
3427 
3428  /*
3429  * Skip Status-Server checks if the NAS is retransmitting
3430  * packets. If it responds to one of the normal packets,
3431  * it will be marked "alive".
3432  */
3433  if ((home->last_packet_sent + home->ping_timeout) >= now->tv_sec) goto reset_timer;
3434 
3435  request = request_alloc(NULL);
3436  if (!request) return;
3437  request->number = request_num_counter++;
3439 
3440  request->proxy = fr_radius_alloc(request, true);
3441  rad_assert(request->proxy != NULL);
3442 
3444  request->proxy->code = PW_CODE_STATUS_SERVER;
3445 
3446  fr_pair_make(request->proxy, &request->proxy->vps,
3447  "Message-Authenticator", "0x00", T_OP_SET);
3448 
3449  } else if ((home->type == HOME_TYPE_AUTH) ||
3450  (home->type == HOME_TYPE_AUTH_ACCT)) {
3451  request->proxy->code = PW_CODE_ACCESS_REQUEST;
3452 
3453  fr_pair_make(request->proxy, &request->proxy->vps,
3454  "User-Name", home->ping_user_name, T_OP_SET);
3455  fr_pair_make(request->proxy, &request->proxy->vps,
3456  "User-Password", home->ping_user_password, T_OP_SET);
3457  fr_pair_make(request->proxy, &request->proxy->vps,
3458  "Service-Type", "Authenticate-Only", T_OP_SET);
3459  fr_pair_make(request->proxy, &request->proxy->vps,
3460  "Message-Authenticator", "0x00", T_OP_SET);
3461 
3462 #ifdef WITH_ACCOUNTING
3463  } else if (home->type == HOME_TYPE_ACCT) {
3465 
3466  fr_pair_make(request->proxy, &request->proxy->vps,
3467  "User-Name", home->ping_user_name, T_OP_SET);
3468  fr_pair_make(request->proxy, &request->proxy->vps,
3469  "Acct-Status-Type", "Stop", T_OP_SET);
3470  fr_pair_make(request->proxy, &request->proxy->vps,
3471  "Acct-Session-Id", "00000000", T_OP_SET);
3472  vp = fr_pair_make(request->proxy, &request->proxy->vps,
3473  "Event-Timestamp", "0", T_OP_SET);
3474  vp->vp_date = now->tv_sec;
3475 #endif
3476 
3477  } else {
3478  /*
3479  * Unkown home server type.
3480  */
3481  talloc_free(request);
3482  return;
3483  }
3484 
3485  vp = fr_pair_make(request->proxy, &request->proxy->vps,
3486  "NAS-Identifier", "", T_OP_SET);
3487  if (vp) {
3488  fr_pair_value_snprintf(vp, "Status Check %u. Are you alive?",
3489  home->num_sent_pings);
3490  }
3491 
3492 #ifdef WITH_TCP
3493  request->proxy->proto = home->proto;
3494 #endif
3495  request->proxy->src_ipaddr = home->src_ipaddr;
3496  request->proxy->dst_ipaddr = home->ipaddr;
3497  request->proxy->dst_port = home->port;
3498  request->home_server = home;
3499 #ifdef DEBUG_STATE_MACHINE
3500  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
3501  child_state_names[request->child_state],
3502  child_state_names[REQUEST_DONE]);
3503  if (rad_debug_lvl) printf("(%u) ********\tNEXT-STATE %s -> %s\n", request->number, __FUNCTION__, "request_ping");
3504 #endif
3505 #ifdef HAVE_PTHREAD_H
3506  rad_assert(request->child_pid == NO_SUCH_CHILD_PID);
3507 #endif
3508  request->child_state = REQUEST_PROXIED;
3509  request->process = request_ping;
3510 
3511  rad_assert(request->proxy_listener == NULL);
3512 
3513  if (!insert_into_proxy_hash(request)) {
3514  RPROXY("Failed to insert status check %d into proxy list. Discarding it.",
3515  request->number);
3516 
3517  rad_assert(!request->in_request_hash);
3518  rad_assert(!request->in_proxy_hash);
3519  rad_assert(request->ev == NULL);
3520  talloc_free(request);
3521  return;
3522  }
3523 
3524  /*
3525  * Set up the timer callback.
3526  */
3527  when = *now;
3528  when.tv_sec += home->ping_timeout;
3529 
3530  DEBUG("PING: Waiting %u seconds for response to ping",
3531  home->ping_timeout);
3532 
3534  home->num_sent_pings++;
3535 
3536  rad_assert(request->proxy_listener != NULL);
3537  request->proxy_listener->debug(request, request->proxy, false);
3538  request->proxy_listener->send(request->proxy_listener, request);
3539 
3540 reset_timer:
3541  /*
3542  * Add +/- 2s of jitter, as suggested in RFC 3539
3543  * and in the Issues and Fixes draft.
3544  */
3545  home->when = *now;
3546  home->when.tv_sec += home->ping_interval;
3547 
3548  add_jitter(&home->when);
3549 
3550  DEBUG("PING: Next status packet in %u seconds", home->ping_interval);
3552 }
3553 
3554 static void home_trigger(home_server_t *home, char const *trigger)
3555 {
3556  REQUEST *my_request;
3558 
3559  my_request = talloc_zero(NULL, REQUEST);
3560  my_packet = talloc_zero(my_request, RADIUS_PACKET);
3561  my_request->proxy = my_packet;
3562  my_packet->dst_ipaddr = home->ipaddr;
3563  my_packet->src_ipaddr = home->src_ipaddr;
3564 
3565  exec_trigger(my_request, home->cs, trigger, false);
3566  talloc_free(my_request);
3567 }
3568 
3569 static void mark_home_server_zombie(home_server_t *home, struct timeval *now, struct timeval *response_window)
3570 {
3571  time_t start;
3572  char buffer[INET6_ADDRSTRLEN];
3573 
3574  ASSERT_MASTER;
3575 
3576  rad_assert((home->state == HOME_STATE_ALIVE) ||
3577  (home->state == HOME_STATE_UNKNOWN));
3578 
3579 #ifdef WITH_TCP
3580  if (home->proto == IPPROTO_TCP) {
3581  WARN("Not marking TCP server %s zombie", home->log_name);
3582  return;
3583  }
3584 #endif
3585 
3586  /*
3587  * We've received a real packet recently. Don't mark the
3588  * server as zombie until we've received NO packets for a
3589  * while. The "1/4" of zombie period was chosen rather
3590  * arbitrarily. It's a balance between too short, which
3591  * gives quick fail-over and fail-back, or too long,
3592  * where the proxy still sends packets to an unresponsive
3593  * home server.
3594  */
3595  start = now->tv_sec - ((home->zombie_period + 3) / 4);
3596  if (home->last_packet_recv >= start) {
3597  DEBUG("Received reply from home server %d seconds ago. Might not be zombie.",
3598  (int) (now->tv_sec - home->last_packet_recv));
3599  return;
3600  }
3601 
3602  home->state = HOME_STATE_ZOMBIE;
3603  home_trigger(home, "home_server.zombie");
3604 
3605  /*
3606  * Set the home server to "zombie", as of the time
3607  * calculated above.
3608  */
3609  home->zombie_period_start.tv_sec = start;
3610  home->zombie_period_start.tv_usec = USEC / 2;
3611 
3612  fr_event_delete(el, &home->ev);
3613 
3614  home->num_sent_pings = 0;
3615  home->num_received_pings = 0;
3616 
3617  PROXY("Marking home server %s port %d as zombie (it has not responded in %d.%06d seconds).",
3618  inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3619  buffer, sizeof(buffer)),
3620  home->port, (int) response_window->tv_sec, (int) response_window->tv_usec);
3621 
3622  ping_home_server(home, now);
3623 }
3624 
3625 
3626 void revive_home_server(void *ctx, UNUSED struct timeval *now)
3627 {
3628  home_server_t *home = talloc_get_type_abort(ctx, home_server_t);
3629  char buffer[INET6_ADDRSTRLEN];
3630 
3631 #ifdef WITH_TCP
3632  rad_assert(home->proto != IPPROTO_TCP);
3633 #endif
3634 
3635  home->state = HOME_STATE_ALIVE;
3636  home->response_timeouts = 0;
3637  home_trigger(home, "home_server.alive");
3638  home->currently_outstanding = 0;
3639  gettimeofday(&home->revive_time, NULL);
3640 
3641  /*
3642  * Delete any outstanding events.
3643  */
3644  ASSERT_MASTER;
3645  if (home->ev) fr_event_delete(el, &home->ev);
3646 
3647  PROXY("Marking home server %s port %d alive again... we have no idea if it really is alive or not.",
3648  inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr, buffer, sizeof(buffer)),
3649  home->port);
3650 }
3651 
3652 void mark_home_server_dead(home_server_t *home, struct timeval *when)
3653 {
3654  int previous_state = home->state;
3655  char buffer[INET6_ADDRSTRLEN];
3656 
3657 #ifdef WITH_TCP
3658  if (home->proto == IPPROTO_TCP) {
3659  WARN("Not marking TCP server dead");
3660  return;
3661  }
3662 #endif
3663 
3664  PROXY("Marking home server %s port %d as dead",
3665  inet_ntop(home->ipaddr.af, &home->ipaddr.ipaddr,
3666  buffer, sizeof(buffer)),
3667  home->port);
3668 
3669  home->state = HOME_STATE_IS_DEAD;
3670  home_trigger(home, "home_server.dead");
3671 
3672  if (home->ping_check != HOME_PING_CHECK_NONE) {
3673  /*
3674  * If the control socket marks us dead, start
3675  * pinging. Otherwise, we already started
3676  * pinging when it was marked "zombie".
3677  */
3678  if (previous_state == HOME_STATE_ALIVE) {
3679  struct timeval now;
3680 
3681  gettimeofday(&now, NULL);
3682  ping_home_server(home, &now);
3683  } else {
3684  DEBUG("PING: Already pinging home server %s", home->log_name);
3685  }
3686 
3687  } else {
3688  /*
3689  * Revive it after a fixed period of time. This
3690  * is very, very, bad.
3691  */
3692  home->when = *when;
3693  home->when.tv_sec += home->revive_interval;
3694 
3695  DEBUG("PING: Reviving home server %s in %u seconds", home->log_name, home->revive_interval);
3696  ASSERT_MASTER;
3698  }
3699 }
3700 
3701 /** Wait for a reply after proxying a request.
3702  *
3703  * Retransmit the proxied packet, or time out and go to
3704  * proxy_no_reply. Mark the home server unresponsive, etc.
3705  *
3706  * If we do receive a reply, we transition to proxy_running.
3707  *
3708  * \dot
3709  * digraph proxy_wait_for_reply {
3710  * proxy_wait_for_reply;
3711  *
3712  * proxy_wait_for_reply -> retransmit_proxied_request [ label = "DUP", arrowhead = "none" ];
3713  * proxy_wait_for_reply -> proxy_no_reply [ label = "TIMER >= response_window" ];
3714  * proxy_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
3715  * proxy_wait_for_reply -> proxy_running [ label = "PROXY_REPLY" arrowhead = "none"];
3716  * proxy_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
3717  * }
3718  * \enddot
3719  */
3720 static void proxy_wait_for_reply(REQUEST *request, int action)
3721 {
3722  struct timeval now, when;
3723  struct timeval *response_window = NULL;
3724  home_server_t *home = request->home_server;
3725  char buffer[INET6_ADDRSTRLEN];
3726 
3727  VERIFY_REQUEST(request);
3728 
3731 
3733  rad_assert(request->home_server != NULL);
3734 
3735  gettimeofday(&now, NULL);
3736 
3737  switch (action) {
3738  case FR_ACTION_DUP:
3739  /*
3740  * We have a reply, ignore the retransmit.
3741  */
3742  if (request->proxy_reply) return;
3743 
3744  /*
3745  * The request was proxied to a virtual server.
3746  * Ignore the retransmit.
3747  */
3748  if (request->home_server->server) return;
3749 
3750  /*
3751  * Use a new connection when the home server is
3752  * dead, or when there's no proxy listener, or
3753  * when the listener is failed or dead.
3754  *
3755  * If the listener is known or frozen, use it for
3756  * retransmits.
3757  */
3758  if ((home->state == HOME_STATE_IS_DEAD) ||
3759  !request->proxy_listener ||
3760  (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3761  request_proxy_anew(request);
3762  return;
3763  }
3764 
3765 #ifdef WITH_TCP
3766  /*
3767  * The home server is still alive, but TCP. We
3768  * rely on TCP to get the request and reply back.
3769  * So there's no need to retransmit.
3770  */
3771  if (home->proto == IPPROTO_TCP) {
3772  DEBUG2("Suppressing duplicate proxied request (tcp) to home server %s port %d proto TCP - ID: %d",
3773  inet_ntop(request->proxy->dst_ipaddr.af,
3774  &request->proxy->dst_ipaddr.ipaddr,
3775  buffer, sizeof(buffer)),
3776  request->proxy->dst_port,
3777  request->proxy->id);
3778  return;
3779  }
3780 #endif
3781 
3782  /*
3783  * More than one retransmit a second is stupid,
3784  * and should be suppressed by the proxy.
3785  */
3786  when = request->proxy_retransmit;
3787  when.tv_sec++;
3788 
3789  if (timercmp(&now, &when, <)) {
3790  DEBUG2("Suppressing duplicate proxied request (too fast) to home server %s port %d proto TCP - ID: %d",
3791  inet_ntop(request->proxy->dst_ipaddr.af,
3792  &request->proxy->dst_ipaddr.ipaddr,
3793  buffer, sizeof(buffer)),
3794  request->proxy->dst_port,
3795  request->proxy->id);
3796  return;
3797  }
3798 
3799 #ifdef WITH_ACCOUNTING
3800  /*
3801  * If we update the Acct-Delay-Time, we need to
3802  * get a new ID.
3803  */
3804  if ((request->packet->code == PW_CODE_ACCOUNTING_REQUEST) &&
3805  fr_pair_find_by_num(request->proxy->vps, 0, PW_ACCT_DELAY_TIME, TAG_ANY)) {
3806  request_proxy_anew(request);
3807  return;
3808  }
3809 #endif
3810 
3811  RDEBUG2("Sending duplicate proxied request to home server %s port %d - ID: %d",
3812  inet_ntop(request->proxy->dst_ipaddr.af,
3813  &request->proxy->dst_ipaddr.ipaddr,
3814  buffer, sizeof(buffer)),
3815  request->proxy->dst_port,
3816  request->proxy->id);
3817  request->num_proxied_requests++;
3818 
3819  rad_assert(request->proxy_listener != NULL);
3821  home->last_packet_sent = now.tv_sec;
3822  request->proxy_retransmit = now;
3823  request->proxy_listener->debug(request, request->proxy, false);
3824  request->proxy_listener->send(request->proxy_listener, request);
3825  break;
3826 
3827  case FR_ACTION_TIMER:
3828  response_window = request_response_window(request);
3829 
3830 #ifdef WITH_TCP
3831  if (!request->proxy_listener ||
3832  (request->proxy_listener->status >= RAD_LISTEN_STATUS_EOL)) {
3833  remove_from_proxy_hash(request);
3834 
3835  when = request->packet->timestamp;
3836  when.tv_sec += request->root->max_request_time;
3837 
3838  if (timercmp(&when, &now, >)) {
3839  RDEBUG("Waiting for client retransmission in order to do a proxy retransmit");
3841  return;
3842  }
3843  } else
3844 #endif
3845  {
3846  /*
3847  * Wake up "response_window" time in the future.
3848  * i.e. when MY packet hasn't received a response.
3849  *
3850  * Note that we DO NOT mark the home server as
3851  * zombie if it doesn't respond to us. It may be
3852  * responding to other (better looking) packets.
3853  */
3854  when = request->proxy->timestamp;
3855  timeradd(&when, response_window, &when);
3856 
3857  /*
3858  * Not at the response window. Set the timer for
3859  * that.
3860  */
3861  if (timercmp(&when, &now, >)) {
3862  struct timeval diff;
3863  timersub(&when, &now, &diff);
3864 
3865  RDEBUG("Expecting proxy response no later than %d.%06d seconds from now",
3866  (int) diff.tv_sec, (int) diff.tv_usec);
3868  return;
3869  }
3870  }
3871 
3872  RDEBUG("No proxy response, giving up on request and marking it done");
3873 
3874  /*
3875  * If we haven't received any packets for
3876  * "response_window", then mark the home server
3877  * as zombie.
3878  *
3879  * If the connection is TCP, then another
3880  * "watchdog timer" function takes care of pings,
3881  * etc. So we don't need to do it here.
3882  *
3883  * This check should really be part of a home
3884  * server state machine.
3885  */
3886  if (((home->state == HOME_STATE_ALIVE) ||
3887  (home->state == HOME_STATE_UNKNOWN))
3888 #ifdef WITH_TCP
3889  && (home->proto != IPPROTO_TCP)
3890 #endif
3891  ) {
3892  home->response_timeouts++;
3893  if (home->response_timeouts >= home->max_response_timeouts)
3894  mark_home_server_zombie(home, &now, response_window);
3895  }
3896 
3898  if (home->type == HOME_TYPE_AUTH) {
3901  }
3902 #ifdef WITH_ACCT
3903  else if (home->type == HOME_TYPE_ACCT) {
3906  }
3907 #endif
3908 #ifdef WITH_COA
3909  else if (home->type == HOME_TYPE_COA) {
3911 
3912  if (request->packet->code == PW_CODE_COA_REQUEST) {
3914  } else {
3916  }
3917  }
3918 #endif
3919 
3920  /*
3921  * There was no response within the window. Stop
3922  * the request. If the client retransmitted, it
3923  * may have failed over to another home server.
3924  * But that one may be dead, too.
3925  *
3926  * The extra verbose message if we have a username,
3927  * is extremely useful if the proxy is part of a chain
3928  * and the final home server, is not the one we're
3929  * proxying to.
3930  */
3931  if (request->username) {
3932  RERROR("Failing proxied request for user \"%s\", due to lack of any response from home "
3933  "server %s port %d",
3934  request->username->vp_strvalue,
3935  inet_ntop(request->proxy->dst_ipaddr.af,
3936  &request->proxy->dst_ipaddr.ipaddr,
3937  buffer, sizeof(buffer)),
3938  request->proxy->dst_port);
3939  } else {
3940  RERROR("Failing proxied request, due to lack of any response from home server %s port %d",
3941  inet_ntop(request->proxy->dst_ipaddr.af,
3942  &request->proxy->dst_ipaddr.ipaddr,
3943  buffer, sizeof(buffer)),
3944  request->proxy->dst_port);
3945  }
3946 
3947  if (setup_post_proxy_fail(request)) {
3949  } else {
3950  gettimeofday(&request->reply->timestamp, NULL);
3951  request_cleanup_delay_init(request);
3952  }
3953  break;
3954 
3955  /*
3956  * We received a new reply. Go process it.
3957  */
3958  case FR_ACTION_PROXY_REPLY:
3960  break;
3961 
3962  default:
3963  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
3964  break;
3965  }
3966 }
3967 #endif /* WITH_PROXY */
3968 
3969 
3970 /***********************************************************************
3971  *
3972  * CoA code
3973  *
3974  ***********************************************************************/
3975 #ifdef WITH_COA
3976 static int null_handler(UNUSED REQUEST *request)
3977 {
3978  return 0;
3979 }
3980 
3981 /*
3982  * See if we need to originate a CoA request.
3983  */
3984 static void request_coa_originate(REQUEST *request)
3985 {
3986  int rcode, pre_proxy_type = 0;
3987  VALUE_PAIR *vp;
3988  REQUEST *coa;
3989  fr_ipaddr_t ipaddr;
3990 
3991  VERIFY_REQUEST(request);
3992 
3993  rad_assert(request->coa != NULL);
3994  rad_assert(request->proxy == NULL);
3995  rad_assert(!request->in_proxy_hash);
3996  rad_assert(request->proxy_reply == NULL);
3997 
3998  /*
3999  * Check whether we want to originate one, or cancel one.
4000  */
4001  vp = fr_pair_find_by_num(request->config, 0, PW_SEND_COA_REQUEST, TAG_ANY);
4002  if (!vp) {
4003  vp = fr_pair_find_by_num(request->coa->proxy->vps, 0, PW_SEND_COA_REQUEST, TAG_ANY);
4004  }
4005 
4006  if (vp) {
4007  if (vp->vp_integer == 0) {
4008  fail:
4009  TALLOC_FREE(request->coa);
4010  return;
4011  }
4012  }
4013 
4014  coa = request->coa;
4015 
4016  /*
4017  * src_ipaddr will be set up in proxy_encode.
4018  */
4019  memset(&ipaddr, 0, sizeof(ipaddr));
4020  vp = fr_pair_find_by_num(coa->proxy->vps, 0, PW_PACKET_DST_IP_ADDRESS, TAG_ANY);
4021  if (vp) {
4022  ipaddr.af = AF_INET;
4023  ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
4024  ipaddr.prefix = 32;
4025  } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, 0, PW_PACKET_DST_IPV6_ADDRESS, TAG_ANY)) != NULL) {
4026  ipaddr.af = AF_INET6;
4027  ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
4028  ipaddr.prefix = 128;
4029  } else if ((vp = fr_pair_find_by_num(coa->proxy->vps, 0, PW_HOME_SERVER_POOL, TAG_ANY)) != NULL) {
4030  coa->home_pool = home_pool_byname(vp->vp_strvalue,
4031  HOME_TYPE_COA);
4032  if (!coa->home_pool) {
4033  RWDEBUG2("No such home_server_pool %s",
4034  vp->vp_strvalue);
4035  goto fail;
4036  }
4037 
4038  /*
4039  * Prefer the pool to one server
4040  */
4041  } else if (request->client->coa_pool) {
4042  coa->home_pool = request->client->coa_pool;
4043 
4044  } else if (request->client->coa_server) {
4045  coa->home_server = request->client->coa_server;
4046 
4047  } else {
4048  /*
4049  * If all else fails, send it to the client that
4050  * originated this request.
4051  */
4052  memcpy(&ipaddr, &request->packet->src_ipaddr, sizeof(ipaddr));
4053  }
4054 
4055  /*
4056  * Use the pool, if it exists.
4057  */
4058  if (coa->home_pool) {
4059  coa->home_server = home_server_ldb(NULL, coa->home_pool, coa);
4060  if (!coa->home_server) {
4061  RWDEBUG("No live home server for home_server_pool %s", coa->home_pool->name);
4062  goto fail;
4063  }
4065 
4066  } else if (!coa->home_server) {
4067  uint16_t port = PW_COA_UDP_PORT;
4068  char buffer[INET6_ADDRSTRLEN];
4069 
4070  vp = fr_pair_find_by_num(coa->proxy->vps, 0, PW_PACKET_DST_PORT, TAG_ANY);
4071  if (vp) port = vp->vp_integer;
4072 
4073  coa->home_server = home_server_find(&ipaddr, port, IPPROTO_UDP);
4074  if (!coa->home_server) {
4075  RWDEBUG2("Unknown destination %s:%d for CoA request",
4076  inet_ntop(ipaddr.af, &ipaddr.ipaddr,
4077  buffer, sizeof(buffer)), port);
4078  goto fail;
4079  }
4080  }
4081 
4082  vp = fr_pair_find_by_num(coa->proxy->vps, 0, PW_PACKET_TYPE, TAG_ANY);
4083  if (vp) {
4084  switch (vp->vp_integer) {
4085  case PW_CODE_COA_REQUEST:
4087  coa->proxy->code = vp->vp_integer;
4088  break;
4089 
4090  default:
4091  DEBUG("Cannot set CoA Packet-Type to code %d",
4092  vp->vp_integer);
4093  goto fail;
4094  }
4095  }
4096 
4097  if (!coa->proxy->code) coa->proxy->code = PW_CODE_COA_REQUEST;
4098 
4099  /*
4100  * The rest of the server code assumes that
4101  * request->packet && request->reply exist. Copy them
4102  * from the original request.
4103  */
4104  rad_assert(coa->packet != NULL);
4105  rad_assert(coa->packet->vps == NULL);
4106 
4107  coa->packet = fr_radius_copy(coa, request->packet);
4108  coa->reply = fr_radius_copy(coa, request->reply);
4109 
4110  coa->config = fr_pair_list_copy(coa, request->config);
4111  coa->num_coa_requests = 0;
4112  coa->handle = null_handler;
4113  coa->number = request->number; /* it's associated with the same request */
4114 
4115  /*
4116  * Call the pre-proxy routines.
4117  */
4118  vp = fr_pair_find_by_num(request->config, 0, PW_PRE_PROXY_TYPE, TAG_ANY);
4119  if (vp) {
4120  fr_dict_enum_t const *dval = fr_dict_enum_by_da(NULL, vp->da, vp->vp_integer);
4121  /* Must be a validation issue */
4122  rad_assert(dval);
4123  RDEBUG2("Found Pre-Proxy-Type %s", dval->name);
4124  pre_proxy_type = vp->vp_integer;
4125  }
4126 
4127  if (coa->home_pool && coa->home_pool->virtual_server) {
4128  char const *old_server = coa->server;
4129 
4130  coa->server = coa->home_pool->virtual_server;
4131  RDEBUG2("server %s {", coa->server);
4132  RINDENT();
4133  rcode = process_pre_proxy(pre_proxy_type, coa);
4134  REXDENT();
4135  RDEBUG2("}");
4136  coa->server = old_server;
4137  } else {
4138  rcode = process_pre_proxy(pre_proxy_type, coa);
4139  }
4140  switch (rcode) {
4141  default:
4142  goto fail;
4143 
4144  /*
4145  * Only send the CoA packet if the pre-proxy code succeeded.
4146  */
4147  case RLM_MODULE_NOOP:
4148  case RLM_MODULE_OK:
4149  case RLM_MODULE_UPDATED:
4150  break;
4151  }
4152 
4153  /*
4154  * Source IP / port is set when the proxy socket
4155  * is chosen.
4156  */
4157  coa->proxy->dst_ipaddr = coa->home_server->ipaddr;
4158  coa->proxy->dst_port = coa->home_server->port;
4159 
4160  if (!insert_into_proxy_hash(coa)) {
4161  radlog_request(L_PROXY, 0, coa, "Failed to insert CoA request into proxy list");
4162  goto fail;
4163  }
4164 
4165  /*
4166  * We CANNOT divorce the CoA request from the parent
4167  * request. This function is running in a child thread,
4168  * and we need access to the main event loop in order to
4169  * to add the timers for the CoA packet.
4170  *
4171  * Instead, we wait for the timer on the parent request
4172  * to fire.
4173  */
4174  gettimeofday(&coa->proxy->timestamp, NULL);
4175  coa->packet->timestamp = coa->proxy->timestamp; /* for max_request_time */
4176  coa->home_server->last_packet_sent = coa->proxy->timestamp.tv_sec;
4177  coa->delay = 0; /* need to calculate a new delay */
4178 
4179  /*
4180  * If requested, put a State attribute into the packet,
4181  * and cache the VPS.
4182  */
4183  fr_request_to_state(global_state, coa, NULL, coa->packet);
4184 
4185  /*
4186  * Encode the packet before we do anything else.
4187  */
4188  coa->proxy_listener->encode(coa->proxy_listener, coa);
4189  coa->proxy_listener->debug(coa, coa->proxy, false);
4190 
4191 #ifdef DEBUG_STATE_MACHINE
4192  if (rad_debug_lvl) printf("(%u) ********\tSTATE %s C-%s -> C-%s\t********\n", request->number, __FUNCTION__,
4193  child_state_names[request->child_state],
4194  child_state_names[REQUEST_PROXIED]);
4195 #endif
4196 
4197  /*
4198  * Set the state function, then the state, no child, and
4199  * send the packet.
4200  */
4201  coa->process = coa_wait_for_reply;
4203 
4204 #ifdef HAVE_PTHREAD_H
4205  coa->child_pid = NO_SUCH_CHILD_PID;
4206 #endif
4207 
4208  if (we_are_master()) coa_separate(request->coa);
4209 
4210  /*
4211  * And send the packet.
4212  */
4213  coa->proxy_listener->send(coa->proxy_listener, coa);
4214 }
4215 
4216 
4217 static void coa_retransmit(REQUEST *request)
4218 {
4219  uint32_t delay, frac;
4220  struct timeval now, when, mrd;
4221  char buffer[INET6_ADDRSTRLEN];
4222 
4223  VERIFY_REQUEST(request);
4224 
4225  fr_event_now(el, &now);
4226 
4227  if (request->delay == 0) {
4228  /*
4229  * Implement re-transmit algorithm as per RFC 5080
4230  * Section 2.2.1.
4231  *
4232  * We want IRT + RAND*IRT
4233  * or 0.9 IRT + rand(0,.2) IRT
4234  *
4235  * 2^20 ~ USEC, and we want 2.
4236  * rand(0,0.2) USEC ~ (rand(0,2^21) / 10)
4237  */
4238  delay = (fr_rand() & ((1 << 22) - 1)) / 10;
4239  request->delay = delay * request->home_server->coa_irt;
4240  delay = request->home_server->coa_irt * USEC;
4241  delay -= delay / 10;
4242  delay += request->delay;
4243  request->delay = delay;
4244 
4245  when = request->proxy->timestamp;
4246  tv_add(&when, delay);
4247 
4248  if (timercmp(&when, &now, >)) {
4250  return;
4251  }
4252  }
4253 
4254  /*
4255  * Retransmit CoA request.
4256  */
4257 
4258  /*
4259  * Cap count at MRC, if it is non-zero.
4260  */
4261  if (request->home_server->coa_mrc &&
4262  (request->num_coa_requests >= request->home_server->coa_mrc)) {
4263  RERROR("Failing request - originate-coa ID %u, due to lack of any response from coa server %s port %d",
4264  request->proxy->id,
4265  inet_ntop(request->proxy->dst_ipaddr.af,
4266  &request->proxy->dst_ipaddr.ipaddr,
4267  buffer, sizeof(buffer)),
4268  request->proxy->dst_port);
4269 
4270  if (setup_post_proxy_fail(request)) {
4272  } else {
4273  request_done(request, FR_ACTION_DONE);
4274  }
4275  return;
4276  }
4277 
4278  /*
4279  * RFC 5080 Section 2.2.1
4280  *
4281  * RT = 2*RTprev + RAND*RTprev
4282  * = 1.9 * RTprev + rand(0,.2) * RTprev
4283  * = 1.9 * RTprev + rand(0,1) * (RTprev / 5)
4284  */
4285  delay = fr_rand();
4286  delay ^= (delay >> 16);
4287  delay &= 0xffff;
4288  frac = request->delay / 5;
4289  delay = ((frac >> 16) * delay) + (((frac & 0xffff) * delay) >> 16);
4290 
4291  delay += (2 * request->delay) - (request->delay / 10);
4292 
4293  /*
4294  * Cap delay at MRT, if MRT is non-zero.
4295  */
4296  if (request->home_server->coa_mrt &&
4297  (delay > (request->home_server->coa_mrt * USEC))) {
4298  int mrt_usec = request->home_server->coa_mrt * USEC;
4299 
4300  /*
4301  * delay = MRT + RAND * MRT
4302  * = 0.9 MRT + rand(0,.2) * MRT
4303  */
4304  delay = fr_rand();
4305  delay ^= (delay >> 15);
4306  delay &= 0x1ffff;
4307  delay = ((mrt_usec >> 16) * delay) + (((mrt_usec & 0xffff) * delay) >> 16);
4308  delay += mrt_usec - (mrt_usec / 10);
4309  }
4310 
4311  request->delay = delay;
4312  when = now;
4313  tv_add(&when, request->delay);
4314  mrd = request->proxy->timestamp;
4315  mrd.tv_sec += request->home_server->coa_mrd;
4316 
4317  /*
4318  * Cap duration at MRD.
4319  */
4320  if (timercmp(&mrd, &when, <)) {
4321  when = mrd;
4322  }
4324 
4325  request->num_coa_requests++; /* is NOT reset by code 3 lines above! */
4326 
4328 
4329  RDEBUG2("Sending duplicate CoA request to home server %s port %d - ID: %d",
4330  inet_ntop(request->proxy->dst_ipaddr.af,
4331  &request->proxy->dst_ipaddr.ipaddr,
4332  buffer, sizeof(buffer)),
4333  request->proxy->dst_port,
4334  request->proxy->id);
4335 
4336  request->proxy_listener->send(request->proxy_listener,
4337  request);
4338 }
4339 
4340 
4341 /** Wait for a reply after originating a CoA a request.
4342  *
4343  * Retransmit the proxied packet, or time out and go to
4344  * coa_no_reply. Mark the home server unresponsive, etc.
4345  *
4346  * If we do receive a reply, we transition to coa_running.
4347  *
4348  * \dot
4349  * digraph coa_wait_for_reply {
4350  * coa_wait_for_reply;
4351  *
4352  * coa_wait_for_reply -> coa_no_reply [ label = "TIMER >= response_window" ];
4353  * coa_wait_for_reply -> timer [ label = "TIMER < max_request_time" ];
4354  * coa_wait_for_reply -> coa_running [ label = "PROXY_REPLY" arrowhead = "none"];
4355  * coa_wait_for_reply -> done [ label = "TIMER >= max_request_time" ];
4356  * }
4357  * \enddot
4358  */
4359 static void coa_wait_for_reply(REQUEST *request, int action)
4360 {
4361  VERIFY_REQUEST(request);
4362 
4364  ASSERT_MASTER;
4366 
4367  if (request->parent) coa_separate(request);
4368 
4369  switch (action) {
4370  case FR_ACTION_TIMER:
4371  if (request_max_time(request)) break;
4372 
4373  coa_retransmit(request);
4374  break;
4375 
4376  case FR_ACTION_PROXY_REPLY:
4378  break;
4379 
4380  default:
4381  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4382  break;
4383  }
4384 }
4385 
4386 static void coa_separate(REQUEST *request)
4387 {
4388  VERIFY_REQUEST(request);
4389 #ifdef DEBUG_STATE_MACHINE
4390  int action = FR_ACTION_TIMER;
4391 #endif
4392 
4394  ASSERT_MASTER;
4395 
4396  rad_assert(request->parent != NULL);
4397  rad_assert(request->parent->coa == request);
4398  rad_assert(request->ev == NULL);
4399  rad_assert(!request->in_request_hash);
4400  rad_assert(request->coa == NULL);
4401 
4402  rad_assert(request->proxy_reply || request->proxy_listener);
4403 
4404  (void) talloc_steal(NULL, request);
4405  request->parent->coa = NULL;
4406  request->parent = NULL;
4407 
4408  if (we_are_master()) {
4409  request->delay = 0;
4410  coa_retransmit(request);
4411  }
4412 }
4413 
4414 
4415 /** Process a request after the CoA has timed out.
4416  *
4417  * Run the packet through Post-Proxy-Type Fail
4418  *
4419  * \dot
4420  * digraph coa_no_reply {
4421  * coa_no_reply;
4422  *
4423  * coa_no_reply -> dup [ label = "DUP", arrowhead = "none" ];
4424  * coa_no_reply -> timer [ label = "TIMER < max_request_time" ];
4425  * coa_no_reply -> coa_reply_too_late [ label = "PROXY_REPLY" arrowhead = "none"];
4426  * coa_no_reply -> process_proxy_reply [ label = "RUN" ];
4427  * coa_no_reply -> done [ label = "TIMER >= timeout" ];
4428  * }
4429  * \enddot
4430  */
4431 static void coa_no_reply(REQUEST *request, int action)
4432 {
4433  char buffer[INET6_ADDRSTRLEN];
4434 
4435  VERIFY_REQUEST(request);
4436 
4439 
4440  switch (action) {
4441  case FR_ACTION_TIMER:
4442  (void) request_max_time(request);
4443  break;
4444 
4445  case FR_ACTION_PROXY_REPLY: /* too late! */
4446  RDEBUG2("Reply from CoA server %s port %d - ID: %d arrived too late.",
4447  inet_ntop(request->proxy->src_ipaddr.af,
4448  &request->proxy->src_ipaddr.ipaddr,
4449  buffer, sizeof(buffer)),
4450  request->proxy->dst_port, request->proxy->id);
4451  break;
4452 
4453  case FR_ACTION_RUN:
4454  if (process_proxy_reply(request, NULL)) {
4455  request->handle(request);
4456  }
4457  request_done(request, FR_ACTION_DONE);
4458  break;
4459 
4460  default:
4461  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4462  break;
4463  }
4464 }
4465 
4466 
4467 /** Process the request after receiving a coa reply.
4468  *
4469  * Throught the post-proxy section, and the through the handler
4470  * function.
4471  *
4472  * \dot
4473  * digraph coa_running {
4474  * coa_running;
4475  *
4476  * coa_running -> timer [ label = "TIMER < max_request_time" ];
4477  * coa_running -> process_proxy_reply [ label = "RUN" ];
4478  * coa_running -> done [ label = "TIMER >= timeout" ];
4479  * }
4480  * \enddot
4481  */
4482 static void coa_running(REQUEST *request, int action)
4483 {
4484  VERIFY_REQUEST(request);
4485 
4488 
4489  switch (action) {
4490  case FR_ACTION_TIMER:
4491  (void) request_max_time(request);
4492  break;
4493 
4494  case FR_ACTION_RUN:
4495  if (process_proxy_reply(request, request->proxy_reply)) {
4496  request->handle(request);
4497  }
4498  request_done(request, FR_ACTION_DONE);
4499  break;
4500 
4501  default:
4502  RDEBUG3("%s: Ignoring action %s", __FUNCTION__, action_codes[action]);
4503  break;
4504  }
4505 }
4506 #endif /* WITH_COA */
4507 
4508 /***********************************************************************
4509  *
4510  * End of the State machine. Start of additional helper code.
4511  *
4512  ***********************************************************************/
4513 
4514 /***********************************************************************
4515  *
4516  * Event handlers.
4517  *
4518  ***********************************************************************/
4519 static void event_socket_handler(fr_event_list_t *xel, UNUSED int fd, void *ctx)
4520 {
4521  rad_listen_t *listener = talloc_get_type_abort(ctx, rad_listen_t);
4522 
4523  rad_assert(xel == el);
4524 
4525  if ((listener->fd < 0)
4526 #ifdef WITH_DETAIL
4527 #ifndef WITH_DETAIL_THREAD
4528  && (listener->type != RAD_LISTEN_DETAIL)
4529 #endif
4530 #endif
4531  ) {
4532  char buffer[256];
4533 
4534  listener->print(listener, buffer, sizeof(buffer));
4535  ERROR("FATAL: Asked to read from closed socket: %s",
4536  buffer);
4537 
4538  rad_panic("Socket was closed on us!");
4539  fr_exit_now(1);
4540  }
4541 
4542  listener->recv(listener);
4543 }
4544 
4545 #ifdef WITH_DETAIL
4546 #ifdef WITH_DETAIL_THREAD
4547 #else
4548 /*
4549  * This function is called periodically to see if this detail
4550  * file is available for reading.
4551  */
4552 static void event_poll_detail(void *ctx, struct timeval *now)
4553 {
4554  int delay;
4555  rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4556  struct timeval when;
4557  listen_detail_t *detail = this->data;
4558 
4559  rad_assert(this->type == RAD_LISTEN_DETAIL);
4560 
4561  redo:
4562  event_socket_handler(el, this->fd, this);
4563 
4564  fr_event_now(el, now);
4565  when = *now;
4566 
4567  /*
4568  * Backdoor API to get the delay until the next poll
4569  * time.
4570  */
4571  delay = this->encode(this, NULL);
4572  if (delay == 0) goto redo;
4573 
4574  tv_add(&when, delay);
4575 
4576  ASSERT_MASTER;
4577  if (!fr_event_insert(el, event_poll_detail, this,
4578  &when, &detail->ev)) {
4579  ERROR("Failed creating handler");
4580  fr_exit(1);
4581  }
4582 }
4583 #endif /* WITH_DETAIL_THREAD */
4584 #endif /* WITH_DETAIL */
4585 
4586 static void event_status(struct timeval *wake)
4587 {
4588 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4589  int argval;
4590 #endif
4591 
4592  if (rad_debug_lvl == 0) {
4593  if (just_started) {
4594  INFO("Ready to process requests");
4595  just_started = false;
4596  }
4597  return;
4598  }
4599 
4600  if (!wake) {
4601  INFO("Ready to process requests");
4602 
4603  } else if ((wake->tv_sec != 0) ||
4604  (wake->tv_usec >= 100000)) {
4605  DEBUG("Waking up in %d.%01u seconds.",
4606  (int) wake->tv_sec, (unsigned int) wake->tv_usec / 100000);
4607  }
4608 
4609 
4610  /*
4611  * FIXME: Put this somewhere else, where it isn't called
4612  * all of the time...
4613  */
4614 
4615 #if !defined(HAVE_PTHREAD_H) && defined(WNOHANG)
4616  /*
4617  * If there are no child threads, then there may
4618  * be child processes. In that case, wait for
4619  * their exit status, and throw that exit status
4620  * away. This helps get rid of zxombie children.
4621  */
4622  while (waitpid(-1, &argval, WNOHANG) > 0) {
4623  /* do nothing */
4624  }
4625 #endif
4626 
4627 }
4628 
4629 #ifdef WITH_TCP
4630 static void listener_free_cb(void *ctx, UNUSED struct timeval *now)
4631 {
4632  rad_listen_t *this = talloc_get_type_abort(ctx, rad_listen_t);
4633  char buffer[1024];
4634 
4635  if (this->count > 0) {
4636  struct timeval when;
4637  listen_socket_t *sock = this->data;
4638 
4639  fr_event_now(el, &when);
4640  when.tv_sec += 3;
4641 
4642  ASSERT_MASTER;
4643  if (!fr_event_insert(el, listener_free_cb, this, &when,
4644  &(sock->ev))) {
4645  rad_panic("Failed to insert event");
4646  }
4647 
4648  return;
4649  }
4650 
4651  /*
4652  * It's all free, close the socket.
4653  */
4654 
4655  this->print(this, buffer, sizeof(buffer));
4656  DEBUG("... cleaning up socket %s", buffer);
4657  rad_assert(this->next == NULL);
4658  talloc_free(this);
4659 }
4660 #endif
4661 
4662 #ifdef WITH_PROXY
4663 static int proxy_eol_cb(void *ctx, void *data)
4664 {
4665  struct timeval when;
4666  REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
4667 
4668  if (request->proxy_listener != ctx) return 0;
4669 
4670  /*
4671  * We don't care if it's being processed in a child thread.
4672  */
4673 
4674 #ifdef WITH_ACCOUNTING
4675  /*
4676  * Accounting packets should be deleted immediately.
4677  * They will never be retransmitted by the client.
4678  */
4679  if (request->proxy->code == PW_CODE_ACCOUNTING_REQUEST) {
4680  RDEBUG("Stopping request due to failed connection to home server");
4681  request->master_state = REQUEST_STOP_PROCESSING;
4682  }
4683 #endif
4684 
4685  /*
4686  * Reset the timer to be now, so that the request is
4687  * quickly updated. But spread the requests randomly
4688  * over the next second, so that we don't overload the
4689  * server.
4690  */
4691  fr_event_now(el, &when);
4692  tv_add(&when, fr_rand() % USEC);
4694 
4695  /*
4696  * Don't delete it from the list.
4697  */
4698  return 0;
4699 }
4700 #endif
4701 
4702 static int event_new_fd(rad_listen_t *this)
4703 {
4704  char buffer[1024];
4705 
4706  ASSERT_MASTER;
4707 
4708  if (this->status == RAD_LISTEN_STATUS_KNOWN) return 1;
4709 
4710  this->print(this, buffer, sizeof(buffer));
4711 
4712  if (this->status == RAD_LISTEN_STATUS_INIT) {
4713  listen_socket_t *sock = this->data;
4714 
4715  rad_assert(sock != NULL);
4716  if (just_started) {
4717  DEBUG("Listening on %s", buffer);
4718  } else {
4719  INFO(" ... adding new socket %s", buffer);
4720  }
4721 
4722 #ifdef WITH_PROXY
4723  if (!just_started && (this->type == RAD_LISTEN_PROXY)) {
4724  home_server_t *home;
4725 
4726  home = sock->home;
4727  if (!home || !home->limit.max_connections) {
4728  INFO(" ... adding new socket %s", buffer);
4729  } else {
4730  INFO(" ... adding new socket %s (%u of %u)", buffer,
4732  }
4733 
4734 #endif
4735  }
4736 
4737  switch (this->type) {
4738 #ifdef WITH_DETAIL
4739  /*
4740  * Detail files are always known, and aren't
4741  * put into the socket event loop.
4742  */
4743  case RAD_LISTEN_DETAIL:
4744  this->status = RAD_LISTEN_STATUS_KNOWN;
4745 
4746 #ifndef WITH_DETAIL_THREAD
4747  {
4748  struct timeval now;
4749 
4750  gettimeofday(&now, NULL);
4751  /*
4752  * Set up the first poll interval.
4753  */
4754  event_poll_detail(this, &now);
4755  return 1;
4756  }
4757 #else
4758  break; /* add the FD to the list */
4759 #endif
4760 #endif /* WITH_DETAIL */
4761 
4762 #ifdef WITH_PROXY
4763  /*
4764  * Add it to the list of sockets we can use.
4765  * Server sockets (i.e. auth/acct) are never
4766  * added to the packet list.
4767  */
4768  case RAD_LISTEN_PROXY:
4769 #ifdef WITH_TCP
4770  rad_assert((sock->proto == IPPROTO_UDP) || (sock->home != NULL));
4771 
4772  /*
4773  * Add timers to outgoing child sockets, if necessary.
4774  */
4775  if (sock->proto == IPPROTO_TCP && sock->opened &&
4776  (sock->home->limit.lifetime || sock->home->limit.idle_timeout)) {
4777  struct timeval when;
4778 
4779  when.tv_sec = sock->opened + 1;
4780  when.tv_usec = 0;
4781 
4782  ASSERT_MASTER;
4783  if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4784  &(sock->ev))) {
4785  rad_panic("Failed to insert event");
4786  }
4787  }
4788 #endif
4789  break;
4790 #endif /* WITH_PROXY */
4791 
4792  /*
4793  * FIXME: put idle timers on command sockets.
4794  */
4795 
4796  default:
4797 #ifdef WITH_TCP
4798  /*
4799  * Add timers to incoming child sockets, if necessary.
4800  */
4801  if (sock->proto == IPPROTO_TCP && sock->opened &&
4802  (sock->limit.lifetime || sock->limit.idle_timeout)) {
4803  struct timeval when;
4804 
4805  when.tv_sec = sock->opened + 1;
4806  when.tv_usec = 0;
4807 
4808  ASSERT_MASTER;
4809  if (!fr_event_insert(el, tcp_socket_timer, this, &when,
4810  &(sock->ev))) {
4811  ERROR("Failed adding timer for socket: %s", fr_strerror());
4812  fr_exit(1);
4813  }
4814  }
4815 #endif
4816  break;
4817  } /* switch over listener types */
4818 
4819  /*
4820  * All sockets: add the FD to the event handler.
4821  */
4822  if (!fr_event_fd_insert(el, 0, this->fd,
4823  event_socket_handler, this)) {
4824  ERROR("Failed adding event handler for socket: %s", fr_strerror());
4825  fr_exit(1);
4826  }
4827 
4828  this->status = RAD_LISTEN_STATUS_KNOWN;
4829  return 1;
4830  } /* end of INIT */
4831 
4832 #ifdef WITH_TCP
4833  /*
4834  * The socket has reached a timeout. Try to close it.
4835  */
4836  if (this->status == RAD_LISTEN_STATUS_FROZEN) {
4837  /*
4838  * Requests are still using the socket. Wait for
4839  * them to finish.
4840  */
4841  if (this->count > 0) {
4842  struct timeval when;
4843  listen_socket_t *sock = this->data;
4844 
4845  /*
4846  * Try again to clean up the socket in 30
4847  * seconds.
4848  */
4849  gettimeofday(&when, NULL);
4850  when.tv_sec += 30;
4851 
4852  ASSERT_MASTER;
4853  if (!fr_event_insert(el,
4855  this, &when, &sock->ev)) {
4856  rad_panic("Failed to insert event");
4857  }
4858 
4859  return 1;
4860  }
4861 
4862  fr_event_fd_delete(el, 0, this->fd);
4863  this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4864  }
4865 
4866  /*
4867  * The socket has had a catastrophic error. Close it.
4868  */
4869  if (this->status == RAD_LISTEN_STATUS_EOL) {
4870  /*
4871  * Remove it from the list of live FD's.
4872  */
4873  fr_event_fd_delete(el, 0, this->fd);
4874 
4875 #ifdef WITH_PROXY
4876  /*
4877  * Tell all requests using this socket that the socket is dead.
4878  */
4879  if (this->type == RAD_LISTEN_PROXY) {
4880  PTHREAD_MUTEX_LOCK(&proxy_mutex);
4881  if (!fr_packet_list_socket_freeze(proxy_list,
4882  this->fd)) {
4883  ERROR("Fatal error freezing socket: %s", fr_strerror());
4884  fr_exit(1);
4885  }
4886 
4887  if (this->count > 0) {
4888  fr_packet_list_walk(proxy_list, this, proxy_eol_cb);
4889  }
4890  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4891  }
4892 #endif
4893 
4894  /*
4895  * Requests are still using the socket. Wait for
4896  * them to finish.
4897  */
4898  if (this->count > 0) {
4899  struct timeval when;
4900  listen_socket_t *sock = this->data;
4901 
4902  /*
4903  * Try again to clean up the socket in 30
4904  * seconds.
4905  */
4906  gettimeofday(&when, NULL);
4907  when.tv_sec += 30;
4908 
4909  ASSERT_MASTER;
4910  if (!fr_event_insert(el,
4912  this, &when, &sock->ev)) {
4913  rad_panic("Failed to insert event");
4914  }
4915 
4916  return 1;
4917  }
4918 
4919  /*
4920  * No one is using the socket. We can remove it now.
4921  */
4922  this->status = RAD_LISTEN_STATUS_REMOVE_NOW;
4923  } /* socket is at EOL */
4924 #endif
4925 
4926  /*
4927  * Nuke the socket.
4928  */
4929  if (this->status == RAD_LISTEN_STATUS_REMOVE_NOW) {
4930  int devnull;
4931 #ifdef WITH_TCP
4932  listen_socket_t *sock = this->data;
4933 #endif
4934  struct timeval when;
4935 
4936  /*
4937  * Re-open the socket, pointing it to /dev/null.
4938  * This means that all writes proceed without
4939  * blocking, and all reads return "no data".
4940  *
4941  * This leaves the socket active, so any child
4942  * threads won't go insane. But it means that
4943  * they cannot send or receive any packets.
4944  *
4945  * This is EXTRA work in the normal case, when
4946  * sockets are closed without error. But it lets
4947  * us have one simple processing method for all
4948  * sockets.
4949  */
4950  devnull = open("/dev/null", O_RDWR);
4951  if (devnull < 0) {
4952  ERROR("FATAL failure opening /dev/null: %s",
4953  fr_syserror(errno));
4954  fr_exit(1);
4955  }
4956  if (dup2(devnull, this->fd) < 0) {
4957  ERROR("FATAL failure closing socket: %s",
4958  fr_syserror(errno));
4959  fr_exit(1);
4960  }
4961  close(devnull);
4962 
4963 #ifdef WITH_DETAIL
4964  rad_assert(this->type != RAD_LISTEN_DETAIL);
4965 #endif
4966 
4967 #ifdef WITH_TCP
4968 #ifdef WITH_PROXY
4969  /*
4970  * The socket is dead. Force all proxied packets
4971  * to stop using it. And then remove it from the
4972  * list of outgoing sockets.
4973  */
4974  if (this->type == RAD_LISTEN_PROXY) {
4975  home_server_t *home;
4976 
4977  home = sock->home;
4978  if (!home || !home->limit.max_connections) {
4979  INFO(" ... shutting down socket %s", buffer);
4980  } else {
4981  INFO(" ... shutting down socket %s (%u of %u)", buffer,
4983  }
4984 
4985  PTHREAD_MUTEX_LOCK(&proxy_mutex);
4986  fr_packet_list_walk(proxy_list, this, eol_proxy_listener);
4987 
4988  if (!fr_packet_list_socket_del(proxy_list, this->fd)) {
4989  ERROR("Fatal error removing socket %s: %s",
4990  buffer, fr_strerror());
4991  fr_exit(1);
4992  }
4993  PTHREAD_MUTEX_UNLOCK(&proxy_mutex);
4994  } else
4995 #endif
4996  {
4997  INFO(" ... shutting down socket %s", buffer);
4998 
4999  /*
5000  * EOL all requests using this socket.
5001  */
5003  }
5004 
5005  /*
5006  * No child threads, clean it up now.
5007  */
5008  if (!spawn_workers) {
5009  ASSERT_MASTER;
5010  if (sock->ev) fr_event_delete(el, &sock->ev);
5011  listen_free(&this);
5012  return 1;
5013  }
5014 
5015  /*
5016  * Wait until all requests using this socket are done.
5017  */
5018  gettimeofday(&when, NULL);
5019  when.tv_sec += 3;
5020 
5021  ASSERT_MASTER;
5022  if (!fr_event_insert(el, listener_free_cb, this, &when,
5023  &(sock->ev))) {
5024  rad_panic("Failed to insert event");
5025  }
5026  }
5027 #endif /* WITH_TCP */
5028 
5029  return 1;
5030 }
5031 
5032 /***********************************************************************
5033  *
5034  * Signal handlers.
5035  *
5036  ***********************************************************************/
5037 
5038 static void handle_signal_self(int flag)
5039 {
5040  ASSERT_MASTER;
5041 
5042  if ((flag & (RADIUS_SIGNAL_SELF_EXIT | RADIUS_SIGNAL_SELF_TERM)) != 0) {
5043  if ((flag & RADIUS_SIGNAL_SELF_EXIT) != 0) {
5044  INFO("Signalled to exit");
5045  fr_event_loop_exit(el, 1);
5046  } else {
5047  INFO("Signalled to terminate");
5048  fr_event_loop_exit(el, 2);
5049  }
5050 
5051  return;
5052  } /* else exit/term flags weren't set */
5053 
5054  /*
5055  * Tell the even loop to stop processing.
5056  */
5057  if ((flag & RADIUS_SIGNAL_SELF_HUP) != 0) {
5058  time_t when;
5059  static time_t last_hup = 0;
5060 
5061  when = time(NULL);
5062  if ((int) (when - last_hup) < 5) {
5063  INFO("Ignoring HUP (less than 5s since last one)");
5064  return;
5065  }
5066 
5067  INFO("Received HUP signal");
5068 
5069  last_hup = when;
5070 
5071  exec_trigger(NULL, NULL, "server.signal.hup", true);
5072  fr_event_loop_exit(el, 0x80);
5073  }
5074 
5075 #if defined(WITH_DETAIL) && !defined(WITH_DETAIL_THREAD)
5076  if ((flag & RADIUS_SIGNAL_SELF_DETAIL) != 0) {
5077  rad_listen_t *this;
5078 
5079  /*
5080  * FIXME: O(N) loops suck.
5081  */
5082  for (this = main_config.listen;
5083  this != NULL;
5084  this = this->next) {
5085  struct timeval now;
5086 
5087  if (this->type != RAD_LISTEN_DETAIL) continue;
5088 
5089  /*
5090  * This one didn't send the signal, skip
5091  * it.
5092  */
5093  if (!this->decode(this, NULL)) continue;
5094 
5095  gettimeofday(&now, NULL);
5096  /*
5097  * Go service the interrupt.
5098  */
5099  event_poll_detail(this, &now);
5100  }
5101  }
5102 #endif
5103 
5104 #if defined(WITH_TCP) && defined(WITH_PROXY) && defined(HAVE_PTHREAD_H)
5105  /*
5106  * There are new listeners in the list. Run
5107  * event_new_fd() on them.
5108  */
5109  if ((flag & RADIUS_SIGNAL_SELF_NEW_FD) != 0) {
5110  rad_listen_t *this, *next;
5111 
5112  FD_MUTEX_LOCK(&fd_mutex);
5113 
5114  /*
5115  * FIXME: unlock the mutex before calling
5116  * event_new_fd()?
5117  */
5118  for (this = new_listeners; this != NULL; this = next) {
5119  next = this->next;
5120  this->next = NULL;
5121 
5122  event_new_fd(this);
5123  }
5124 
5125  new_listeners = NULL;
5126  FD_MUTEX_UNLOCK(&fd_mutex);
5127  }
5128 #endif
5129 }
5130 
5131 #ifndef HAVE_PTHREAD_H
5132 void radius_signal_self(int flag)
5133 {
5134  return handle_signal_self(flag);
5135 }
5136 
5137 #else
5138 static int self_pipe[2] = { -1, -1 };
5139 
5140 /*
5141  * Inform ourselves that we received a signal.
5142  */
5143 void radius_signal_self(int flag)
5144 {
5145  ssize_t rcode;
5146  uint8_t buffer[16];
5147 
5148  /*
5149  * The read MUST be non-blocking for this to work.
5150  */
5151  rcode = read(self_pipe[0], buffer, sizeof(buffer));
5152  if (rcode > 0) {
5153  ssize_t i;
5154 
5155  for (i = 0; i < rcode; i++) {
5156  buffer[0] |= buffer[i];
5157  }
5158  } else {
5159  buffer[0] = 0;
5160  }
5161 
5162  buffer[0] |= flag;
5163 
5164  if (write(self_pipe[1], buffer, 1) < 0) fr_exit(0);
5165 }
5166 
5167 
5168 static void event_signal_handler(UNUSED fr_event_list_t *xel,
5169  UNUSED int fd, UNUSED void *ctx)
5170 {
5171  ssize_t i, rcode;
5172  uint8_t buffer[32];
5173 
5174  rcode = read(self_pipe[0], buffer, sizeof(buffer));
5175  if (rcode <= 0) return;
5176 
5177  /*
5178  * Merge pending signals.
5179  */
5180  for (i = 0; i < rcode; i++) {
5181  buffer[0] |= buffer[i];
5182  }
5183 
5184  handle_signal_self(buffer[0]);
5185 }
5186 #endif /* HAVE_PTHREAD_H */
5187 
5188 /***********************************************************************
5189  *
5190  * Bootstrapping code.
5191  *
5192  ***********************************************************************/
5193 
5194 /*
5195  * Externally-visibly functions.
5196  */
5197 int radius_event_init(TALLOC_CTX *ctx) {
5199  if (!el) return 0;
5200 
5201  return 1;
5202 }
5203 
5204 static int packet_entry_cmp(void const *one, void const *two)
5205 {
5206  RADIUS_PACKET const * const *a = one;
5207  RADIUS_PACKET const * const *b = two;
5208 
5209  return fr_packet_cmp(*a, *b);
5210 }
5211 
5212 #ifdef WITH_PROXY
5213 /*
5214  * They haven't defined a proxy listener. Automatically
5215  * add one for them, with the correct address family.
5216  */
5218 {
5219  uint16_t port = 0;
5220  home_server_t home;
5221  listen_socket_t *sock;
5222  rad_listen_t *this;
5223 
5224  memset(&home, 0, sizeof(home));
5225 
5226  /*
5227  * Open a default UDP port
5228  */
5229  home.proto = IPPROTO_UDP;
5230  port = 0;
5231 
5232  /*
5233  * Set the address family.
5234  */
5235  home.src_ipaddr.af = af;
5236  home.ipaddr.af = af;
5237 
5238  /*
5239  * Get the correct listener.
5240  */
5241  this = proxy_new_listener(proxy_ctx, &home, port);
5242  if (!this) {
5243  fr_exit_now(1);
5244  }
5245 
5246  sock = this->data;
5247  if (!fr_packet_list_socket_add(proxy_list, this->fd,
5248  sock->proto,
5249  &sock->other_ipaddr, sock->other_port,
5250  this)) {
5251  ERROR("Failed adding proxy socket");
5252  fr_exit_now(1);
5253  }
5254 
5255  /*
5256  * Insert the FD into list of FDs to listen on.
5257  */
5258  radius_update_listener(this);
5259 }
5260 
5261 /*
5262  * See if we automatically need to open a proxy socket.
5263  */
5264 static void check_proxy(rad_listen_t *head)
5265 {
5266  bool defined_proxy;
5267  bool has_v4, has_v6;
5268  rad_listen_t *this;
5269 
5270  if (check_config) return;
5271  if (!main_config.proxy_requests) return;
5272  if (!head) return;
5273  if (!home_servers_udp) return;
5274 
5275  defined_proxy = has_v4 = has_v6 = false;
5276 
5277  /*
5278  * Figure out if we need to open a proxy socket, and if
5279  * so, which one.
5280  */
5281  for (this = head; this != NULL; this = this->next) {
5282  listen_socket_t *sock;
5283 
5284  switch (this->type) {
5285  case RAD_LISTEN_PROXY:
5286  defined_proxy = true;
5287  break;
5288 
5289  case RAD_LISTEN_AUTH:
5290 #ifdef WITH_ACCT
5291  case RAD_LISTEN_ACCT:
5292 #endif
5293 #ifdef WITH_COA
5294  case RAD_LISTEN_COA:
5295 #endif
5296  sock = this->data;
5297  if (sock->my_ipaddr.af == AF_INET) has_v4 = true;
5298  if (sock->my_ipaddr.af == AF_INET6) has_v6 = true;
5299  break;
5300 
5301  default:
5302  break;
5303  }
5304  }
5305 
5306  /*
5307  * Assume they know what they're doing.
5308  */
5309  if (defined_proxy) return;
5310 
5311  if (has_v4) create_default_proxy_listener(AF_INET);
5312 
5313  if (has_v6) create_default_proxy_listener(AF_INET6);
5314 }
5315 #endif
5316 
5317 int radius_event_start(bool have_children)
5318 {
5319  rad_listen_t *head = NULL;
5320 
5321  if (fr_start_time != (time_t)-1) return 0;
5322 
5323  time(&fr_start_time);
5324 
5325  if (!check_config) {
5326  /*
5327  * radius_event_init() must be called first
5328  */
5329  rad_assert(el);
5330 
5331  pl = rbtree_create(NULL, packet_entry_cmp, NULL, 0);
5332  if (!pl) return 0; /* leak el */
5333  }
5334 
5335  request_num_counter = 0;
5336 
5337 #ifdef WITH_PROXY
5339  /*
5340  * Create the tree for managing proxied requests and
5341  * responses.
5342  */
5343  proxy_list = fr_packet_list_create(1);
5344  if (!proxy_list) return 0;
5345 
5346 #ifdef HAVE_PTHREAD_H
5347  if (pthread_mutex_init(&proxy_mutex, NULL) != 0) {
5348  ERROR("FATAL: Failed to initialize proxy mutex: %s",
5349  fr_syserror(errno));
5350  fr_exit(1);
5351  }
5352 #endif
5353 
5354  /*
5355  * The "init_delay" is set to "response_window".
5356  * Reset it to half of "response_window" in order
5357  * to give the event loop enough time to service
5358  * the event before hitting "response_window".
5359  */
5360  main_config.init_delay.tv_usec += (main_config.init_delay.tv_sec & 0x01) * USEC;
5361  main_config.init_delay.tv_usec >>= 1;
5362  main_config.init_delay.tv_sec >>= 1;
5363 
5364  proxy_ctx = talloc_init("proxy");
5365  }
5366 #endif
5367 
5368  /*
5369  * Move all of the thread calls to this file?
5370  *
5371  * It may be best for the mutexes to be in this file...
5372  */
5373  spawn_workers = have_children;
5374 
5375 #ifdef HAVE_PTHREAD_H
5376  NO_SUCH_CHILD_PID = pthread_self(); /* not a child thread */
5377 #endif
5378 
5379  if (check_config) {
5380  DEBUG("%s: #### Skipping IP addresses and Ports ####",
5381  main_config.name);
5382  return 1;
5383  }
5384 
5385 #ifdef HAVE_PTHREAD_H
5386  /*
5387  * Child threads need a pipe to signal us, as do the
5388  * signal handlers.
5389  */
5390  if (pipe(self_pipe) < 0) {
5391  ERROR("Error opening internal pipe: %s", fr_syserror(errno));
5392  fr_exit(1);
5393  }
5394  if ((fcntl(self_pipe[0], F_SETFL, O_NONBLOCK) < 0) ||
5395  (fcntl(self_pipe[0], F_SETFD, FD_CLOEXEC) < 0)) {
5396  ERROR("Error setting internal flags: %s", fr_syserror(errno));
5397  fr_exit(1);
5398  }
5399  if ((fcntl(self_pipe[1], F_SETFL, O_NONBLOCK) < 0) ||
5400  (fcntl(self_pipe[1], F_SETFD, FD_CLOEXEC) < 0)) {
5401  ERROR("Error setting internal flags: %s", fr_syserror(errno));
5402  fr_exit(1);
5403  }
5404  DEBUG4("Created signal pipe. Read end FD %i, write end FD %i", self_pipe[0], self_pipe[1]);
5405 
5406  if (!fr_event_fd_insert(el, 0, self_pipe[0], event_signal_handler, el)) {
5407  ERROR("Failed creating signal pipe handler: %s", fr_strerror());
5408  fr_exit(1);
5409  }
5410 #endif
5411 
5412  DEBUG("%s: #### Opening IP addresses and Ports ####", main_config.name);
5413 
5414  /*
5415  * The server temporarily switches to an unprivileged
5416  * user very early in the bootstrapping process.
5417  * However, some sockets MAY require privileged access
5418  * (bind to device, or to port < 1024, or to raw
5419  * sockets). Those sockets need to call suid up/down
5420  * themselves around the functions that need a privileged
5421  * uid.
5422  */
5423  if (listen_init(&head, spawn_workers) < 0) {
5424  fr_exit_now(1);
5425  }
5426 
5427  main_config.listen = head;
5428 
5429 #ifdef WITH_PROXY
5430  check_proxy(head);
5431 #endif
5432 
5433  /*
5434  * At this point, no one has any business *ever* going
5435  * back to root uid.
5436  */
5438 
5439  return 1;
5440 }
5441 
5442 
5443 #ifdef WITH_PROXY
5444 static int proxy_delete_cb(UNUSED void *ctx, void *data)
5445 {
5446  REQUEST *request = fr_packet2myptr(REQUEST, proxy, data);
5447 
5448  VERIFY_REQUEST(request);
5449 
5451 
5452 #ifdef HAVE_PTHREAD_H
5453  if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5454 #endif
5455 
5456  /*
5457  * If it's queued we can't delete it from the queue.
5458  *
5459  * Otherwise, it's OK to delete it. Even RUNNING, because
5460  * that will get caught by the check above.
5461  */
5462  if (request->child_state == REQUEST_QUEUED) return 0;
5463 
5464  request->in_proxy_hash = false;
5465 
5466  if (!request->in_request_hash) {
5467  request_done(request, FR_ACTION_DONE);
5468  }
5469 
5470  /*
5471  * Delete it from the list.
5472  */
5473  return 2;
5474 }
5475 #endif
5476 
5477 
5478 static int request_delete_cb(UNUSED void *ctx, void *data)
5479 {
5480  REQUEST *request = fr_packet2myptr(REQUEST, packet, data);
5481 
5482  VERIFY_REQUEST(request);
5483 
5485 
5486  /*
5487  * Not done, or the child thread is still processing it.
5488  */
5489  if (request->child_state < REQUEST_RESPONSE_DELAY) return 0; /* continue */
5490 
5491 #ifdef HAVE_PTHREAD_H
5492  if (pthread_equal(request->child_pid, NO_SUCH_CHILD_PID) == 0) return 0;
5493 #endif
5494 
5495 #ifdef WITH_PROXY
5496  rad_assert(request->in_proxy_hash == false);
5497 #endif
5498 
5499  request->in_request_hash = false;
5500  ASSERT_MASTER;
5501  if (request->ev) fr_event_delete(el, &request->ev);
5502 
5503  if (main_config.memory_report) {
5504  RDEBUG2("Cleaning up request packet ID %u with timestamp +%d",
5505  request->packet->id,
5506  (unsigned int) (request->timestamp.tv_sec - fr_start_time));
5507  }
5508 
5509 #ifdef WITH_COA
5510  if (request->coa) {
5511  rad_assert(!request->coa->in_proxy_hash);
5512  }
5513 #endif
5514 
5515  request_free(request);
5516 
5517  /*
5518  * Delete it from the list, and continue;
5519  */
5520  return 2;
5521 }
5522 
5523 
5525 {
5526  ASSERT_MASTER;
5527 
5528 #ifdef WITH_PROXY
5529  /*
5530  * There are requests in the proxy hash that aren't
5531  * referenced from anywhere else. Remove them first.
5532  */
5533  if (proxy_list) {
5534  fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5535  }
5536 #endif
5537 
5539 
5540  if (spawn_workers) {
5541  /*
5542  * Walk the lists again, ensuring that all
5543  * requests are done.
5544  */
5545  if (main_config.memory_report) {
5546  int num;
5547 
5548 #ifdef WITH_PROXY
5549  if (proxy_list) {
5550  fr_packet_list_walk(proxy_list, NULL, proxy_delete_cb);
5551  num = fr_packet_list_num_elements(proxy_list);
5552  if (num > 0) {
5553  ERROR("Proxy list has %d requests still in it.", num);
5554  }
5555  }
5556 #endif
5557 
5559  num = rbtree_num_elements(pl);
5560  if (num > 0) {
5561  ERROR("Request list has %d requests still in it.", num);
5562  }
5563  }
5564  }
5565 
5566  rbtree_free(pl);
5567  pl = NULL;
5568 
5569 #ifdef WITH_PROXY
5570  fr_packet_list_free(proxy_list);
5571  proxy_list = NULL;
5572 
5573  if (proxy_ctx) talloc_free(proxy_ctx);
5574 #endif
5575 
5576  TALLOC_FREE(el);
5577 
5578  if (debug_condition) talloc_free(debug_condition);
5579 }
5580 
5582 {
5583  if (!el) return 0;
5584 
5585  return fr_event_loop(el);
5586 }
#define USEC
void home_server_update_request(home_server_t *home, REQUEST *request)
Definition: realms.c:2285
void fr_pair_list_free(VALUE_PAIR **)
Free memory used by a valuepair list.
Definition: pair.c:544
static int insert_into_proxy_hash(REQUEST *request)
Definition: process.c:2137
struct timeval reject_delay
How long to wait before sending an Access-Reject.
Definition: radiusd.h:128
fr_state_action_t timer_action
What action to perform when the timer event fires.
Definition: radiusd.h:247
fr_state_action_t
Definition: process.h:37
static void proxy_reply_too_late(REQUEST *request)
Definition: process.c:500
REALM * realm_find2(char const *name)
Definition: realms.c:2201
int sockfd
Socket this packet was read from.
Definition: libradius.h:147
bool in_request_hash
Definition: radiusd.h:278
RAD_LISTEN_TYPE priority
Definition: radiusd.h:276
struct timeval response_delay
How long to wait before sending Access-Rejects.
Definition: radiusd.h:246
2nd highest priority debug messages (-xx | -X).
Definition: log.h:52
fr_ipaddr_t src_ipaddr
Resolved version of src_ipaddr_str.
Definition: realms.h:87
#define pthread_mutex_init(_x, _y)
Definition: rlm_eap.h:75
rad_master_state_t master_state
Set by the master thread to signal the child that's currently working with the request, to do something.
Definition: radiusd.h:259
VALUE_PAIR * config
VALUE_PAIR (s) used to set per request parameters for modules and the