xref: /freebsd/contrib/wpa/src/radius/radius_client.c (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 /*
2  * RADIUS client
3  * Copyright (c) 2002-2015, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 #include <net/if.h>
11 
12 #include "common.h"
13 #include "radius.h"
14 #include "radius_client.h"
15 #include "eloop.h"
16 
17 /* Defaults for RADIUS retransmit values (exponential backoff) */
18 
19 /**
20  * RADIUS_CLIENT_FIRST_WAIT - RADIUS client timeout for first retry in seconds
21  */
22 #define RADIUS_CLIENT_FIRST_WAIT 3
23 
24 /**
25  * RADIUS_CLIENT_MAX_WAIT - RADIUS client maximum retry timeout in seconds
26  */
27 #define RADIUS_CLIENT_MAX_WAIT 120
28 
29 /**
30  * RADIUS_CLIENT_MAX_FAILOVER - RADIUS client maximum retries
31  *
32  * Maximum number of server failovers before the entry is removed from
33  * retransmit list.
34  */
35 #define RADIUS_CLIENT_MAX_FAILOVER 3
36 
37 /**
38  * RADIUS_CLIENT_MAX_ENTRIES - RADIUS client maximum pending messages
39  *
40  * Maximum number of entries in retransmit list (oldest entries will be
41  * removed, if this limit is exceeded).
42  */
43 #define RADIUS_CLIENT_MAX_ENTRIES 30
44 
45 /**
46  * RADIUS_CLIENT_NUM_FAILOVER - RADIUS client failover point
47  *
48  * The number of failed retry attempts after which the RADIUS server will be
49  * changed (if one of more backup servers are configured).
50  */
51 #define RADIUS_CLIENT_NUM_FAILOVER 4
52 
53 
54 /**
55  * struct radius_rx_handler - RADIUS client RX handler
56  *
57  * This data structure is used internally inside the RADIUS client module to
58  * store registered RX handlers. These handlers are registered by calls to
59  * radius_client_register() and unregistered when the RADIUS client is
60  * deinitialized with a call to radius_client_deinit().
61  */
62 struct radius_rx_handler {
63 	/**
64 	 * handler - Received RADIUS message handler
65 	 */
66 	RadiusRxResult (*handler)(struct radius_msg *msg,
67 				  struct radius_msg *req,
68 				  const u8 *shared_secret,
69 				  size_t shared_secret_len,
70 				  void *data);
71 
72 	/**
73 	 * data - Context data for the handler
74 	 */
75 	void *data;
76 };
77 
78 
79 /**
80  * struct radius_msg_list - RADIUS client message retransmit list
81  *
82  * This data structure is used internally inside the RADIUS client module to
83  * store pending RADIUS requests that may still need to be retransmitted.
84  */
85 struct radius_msg_list {
86 	/**
87 	 * addr - STA/client address
88 	 *
89 	 * This is used to find RADIUS messages for the same STA.
90 	 */
91 	u8 addr[ETH_ALEN];
92 
93 	/**
94 	 * msg - RADIUS message
95 	 */
96 	struct radius_msg *msg;
97 
98 	/**
99 	 * msg_type - Message type
100 	 */
101 	RadiusType msg_type;
102 
103 	/**
104 	 * first_try - Time of the first transmission attempt
105 	 */
106 	os_time_t first_try;
107 
108 	/**
109 	 * next_try - Time for the next transmission attempt
110 	 */
111 	os_time_t next_try;
112 
113 	/**
114 	 * attempts - Number of transmission attempts for one server
115 	 */
116 	int attempts;
117 
118 	/**
119 	 * accu_attempts - Number of accumulated attempts
120 	 */
121 	int accu_attempts;
122 
123 	/**
124 	 * next_wait - Next retransmission wait time in seconds
125 	 */
126 	int next_wait;
127 
128 	/**
129 	 * last_attempt - Time of the last transmission attempt
130 	 */
131 	struct os_reltime last_attempt;
132 
133 	/**
134 	 * shared_secret - Shared secret with the target RADIUS server
135 	 */
136 	const u8 *shared_secret;
137 
138 	/**
139 	 * shared_secret_len - shared_secret length in octets
140 	 */
141 	size_t shared_secret_len;
142 
143 	/* TODO: server config with failover to backup server(s) */
144 
145 	/**
146 	 * next - Next message in the list
147 	 */
148 	struct radius_msg_list *next;
149 };
150 
151 
152 /**
153  * struct radius_client_data - Internal RADIUS client data
154  *
155  * This data structure is used internally inside the RADIUS client module.
156  * External users allocate this by calling radius_client_init() and free it by
157  * calling radius_client_deinit(). The pointer to this opaque data is used in
158  * calls to other functions as an identifier for the RADIUS client instance.
159  */
160 struct radius_client_data {
161 	/**
162 	 * ctx - Context pointer for hostapd_logger() callbacks
163 	 */
164 	void *ctx;
165 
166 	/**
167 	 * conf - RADIUS client configuration (list of RADIUS servers to use)
168 	 */
169 	struct hostapd_radius_servers *conf;
170 
171 	/**
172 	 * auth_serv_sock - IPv4 socket for RADIUS authentication messages
173 	 */
174 	int auth_serv_sock;
175 
176 	/**
177 	 * acct_serv_sock - IPv4 socket for RADIUS accounting messages
178 	 */
179 	int acct_serv_sock;
180 
181 	/**
182 	 * auth_serv_sock6 - IPv6 socket for RADIUS authentication messages
183 	 */
184 	int auth_serv_sock6;
185 
186 	/**
187 	 * acct_serv_sock6 - IPv6 socket for RADIUS accounting messages
188 	 */
189 	int acct_serv_sock6;
190 
191 	/**
192 	 * auth_sock - Currently used socket for RADIUS authentication server
193 	 */
194 	int auth_sock;
195 
196 	/**
197 	 * acct_sock - Currently used socket for RADIUS accounting server
198 	 */
199 	int acct_sock;
200 
201 	/**
202 	 * auth_handlers - Authentication message handlers
203 	 */
204 	struct radius_rx_handler *auth_handlers;
205 
206 	/**
207 	 * num_auth_handlers - Number of handlers in auth_handlers
208 	 */
209 	size_t num_auth_handlers;
210 
211 	/**
212 	 * acct_handlers - Accounting message handlers
213 	 */
214 	struct radius_rx_handler *acct_handlers;
215 
216 	/**
217 	 * num_acct_handlers - Number of handlers in acct_handlers
218 	 */
219 	size_t num_acct_handlers;
220 
221 	/**
222 	 * msgs - Pending outgoing RADIUS messages
223 	 */
224 	struct radius_msg_list *msgs;
225 
226 	/**
227 	 * num_msgs - Number of pending messages in the msgs list
228 	 */
229 	size_t num_msgs;
230 
231 	/**
232 	 * next_radius_identifier - Next RADIUS message identifier to use
233 	 */
234 	u8 next_radius_identifier;
235 
236 	/**
237 	 * interim_error_cb - Interim accounting error callback
238 	 */
239 	void (*interim_error_cb)(const u8 *addr, void *ctx);
240 
241 	/**
242 	 * interim_error_cb_ctx - interim_error_cb() context data
243 	 */
244 	void *interim_error_cb_ctx;
245 };
246 
247 
248 static int
249 radius_change_server(struct radius_client_data *radius,
250 		     struct hostapd_radius_server *nserv,
251 		     struct hostapd_radius_server *oserv,
252 		     int sock, int sock6, int auth);
253 static int radius_client_init_acct(struct radius_client_data *radius);
254 static int radius_client_init_auth(struct radius_client_data *radius);
255 static void radius_client_auth_failover(struct radius_client_data *radius);
256 static void radius_client_acct_failover(struct radius_client_data *radius);
257 
258 
259 static void radius_client_msg_free(struct radius_msg_list *req)
260 {
261 	radius_msg_free(req->msg);
262 	os_free(req);
263 }
264 
265 
266 /**
267  * radius_client_register - Register a RADIUS client RX handler
268  * @radius: RADIUS client context from radius_client_init()
269  * @msg_type: RADIUS client type (RADIUS_AUTH or RADIUS_ACCT)
270  * @handler: Handler for received RADIUS messages
271  * @data: Context pointer for handler callbacks
272  * Returns: 0 on success, -1 on failure
273  *
274  * This function is used to register a handler for processing received RADIUS
275  * authentication and accounting messages. The handler() callback function will
276  * be called whenever a RADIUS message is received from the active server.
277  *
278  * There can be multiple registered RADIUS message handlers. The handlers will
279  * be called in order until one of them indicates that it has processed or
280  * queued the message.
281  */
282 int radius_client_register(struct radius_client_data *radius,
283 			   RadiusType msg_type,
284 			   RadiusRxResult (*handler)(struct radius_msg *msg,
285 						     struct radius_msg *req,
286 						     const u8 *shared_secret,
287 						     size_t shared_secret_len,
288 						     void *data),
289 			   void *data)
290 {
291 	struct radius_rx_handler **handlers, *newh;
292 	size_t *num;
293 
294 	if (msg_type == RADIUS_ACCT) {
295 		handlers = &radius->acct_handlers;
296 		num = &radius->num_acct_handlers;
297 	} else {
298 		handlers = &radius->auth_handlers;
299 		num = &radius->num_auth_handlers;
300 	}
301 
302 	newh = os_realloc_array(*handlers, *num + 1,
303 				sizeof(struct radius_rx_handler));
304 	if (newh == NULL)
305 		return -1;
306 
307 	newh[*num].handler = handler;
308 	newh[*num].data = data;
309 	(*num)++;
310 	*handlers = newh;
311 
312 	return 0;
313 }
314 
315 
316 /**
317  * radius_client_set_interim_erro_cb - Register an interim acct error callback
318  * @radius: RADIUS client context from radius_client_init()
319  * @addr: Station address from the failed message
320  * @cb: Handler for interim accounting errors
321  * @ctx: Context pointer for handler callbacks
322  *
323  * This function is used to register a handler for processing failed
324  * transmission attempts of interim accounting update messages.
325  */
326 void radius_client_set_interim_error_cb(struct radius_client_data *radius,
327 					void (*cb)(const u8 *addr, void *ctx),
328 					void *ctx)
329 {
330 	radius->interim_error_cb = cb;
331 	radius->interim_error_cb_ctx = ctx;
332 }
333 
334 
335 /*
336  * Returns >0 if message queue was flushed (i.e., the message that triggered
337  * the error is not available anymore)
338  */
339 static int radius_client_handle_send_error(struct radius_client_data *radius,
340 					   int s, RadiusType msg_type)
341 {
342 #ifndef CONFIG_NATIVE_WINDOWS
343 	int _errno = errno;
344 	wpa_printf(MSG_INFO, "send[RADIUS,s=%d]: %s", s, strerror(errno));
345 	if (_errno == ENOTCONN || _errno == EDESTADDRREQ || _errno == EINVAL ||
346 	    _errno == EBADF || _errno == ENETUNREACH || _errno == EACCES) {
347 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
348 			       HOSTAPD_LEVEL_INFO,
349 			       "Send failed - maybe interface status changed -"
350 			       " try to connect again");
351 		if (msg_type == RADIUS_ACCT ||
352 		    msg_type == RADIUS_ACCT_INTERIM) {
353 			radius_client_init_acct(radius);
354 			return 0;
355 		} else {
356 			radius_client_init_auth(radius);
357 			return 1;
358 		}
359 	}
360 #endif /* CONFIG_NATIVE_WINDOWS */
361 
362 	return 0;
363 }
364 
365 
366 static int radius_client_retransmit(struct radius_client_data *radius,
367 				    struct radius_msg_list *entry,
368 				    os_time_t now)
369 {
370 	struct hostapd_radius_servers *conf = radius->conf;
371 	int s;
372 	struct wpabuf *buf;
373 	size_t prev_num_msgs;
374 	u8 *acct_delay_time;
375 	size_t acct_delay_time_len;
376 	int num_servers;
377 
378 	if (entry->msg_type == RADIUS_ACCT ||
379 	    entry->msg_type == RADIUS_ACCT_INTERIM) {
380 		num_servers = conf->num_acct_servers;
381 		if (radius->acct_sock < 0)
382 			radius_client_init_acct(radius);
383 		if (radius->acct_sock < 0 && conf->num_acct_servers > 1) {
384 			prev_num_msgs = radius->num_msgs;
385 			radius_client_acct_failover(radius);
386 			if (prev_num_msgs != radius->num_msgs)
387 				return 0;
388 		}
389 		s = radius->acct_sock;
390 		if (entry->attempts == 0)
391 			conf->acct_server->requests++;
392 		else {
393 			conf->acct_server->timeouts++;
394 			conf->acct_server->retransmissions++;
395 		}
396 	} else {
397 		num_servers = conf->num_auth_servers;
398 		if (radius->auth_sock < 0)
399 			radius_client_init_auth(radius);
400 		if (radius->auth_sock < 0 && conf->num_auth_servers > 1) {
401 			prev_num_msgs = radius->num_msgs;
402 			radius_client_auth_failover(radius);
403 			if (prev_num_msgs != radius->num_msgs)
404 				return 0;
405 		}
406 		s = radius->auth_sock;
407 		if (entry->attempts == 0)
408 			conf->auth_server->requests++;
409 		else {
410 			conf->auth_server->timeouts++;
411 			conf->auth_server->retransmissions++;
412 		}
413 	}
414 
415 	if (entry->msg_type == RADIUS_ACCT_INTERIM) {
416 		wpa_printf(MSG_DEBUG,
417 			   "RADIUS: Failed to transmit interim accounting update to "
418 			   MACSTR " - drop message and request a new update",
419 			   MAC2STR(entry->addr));
420 		if (radius->interim_error_cb)
421 			radius->interim_error_cb(entry->addr,
422 						 radius->interim_error_cb_ctx);
423 		return 1;
424 	}
425 
426 	if (s < 0) {
427 		wpa_printf(MSG_INFO,
428 			   "RADIUS: No valid socket for retransmission");
429 		return 1;
430 	}
431 
432 	if (entry->msg_type == RADIUS_ACCT &&
433 	    radius_msg_get_attr_ptr(entry->msg, RADIUS_ATTR_ACCT_DELAY_TIME,
434 				    &acct_delay_time, &acct_delay_time_len,
435 				    NULL) == 0 &&
436 	    acct_delay_time_len == 4) {
437 		struct radius_hdr *hdr;
438 		u32 delay_time;
439 
440 		/*
441 		 * Need to assign a new identifier since attribute contents
442 		 * changes.
443 		 */
444 		hdr = radius_msg_get_hdr(entry->msg);
445 		hdr->identifier = radius_client_get_id(radius);
446 
447 		/* Update Acct-Delay-Time to show wait time in queue */
448 		delay_time = now - entry->first_try;
449 		WPA_PUT_BE32(acct_delay_time, delay_time);
450 
451 		wpa_printf(MSG_DEBUG,
452 			   "RADIUS: Updated Acct-Delay-Time to %u for retransmission",
453 			   delay_time);
454 		radius_msg_finish_acct(entry->msg, entry->shared_secret,
455 				       entry->shared_secret_len);
456 		if (radius->conf->msg_dumps)
457 			radius_msg_dump(entry->msg);
458 	}
459 
460 	/* retransmit; remove entry if too many attempts */
461 	if (entry->accu_attempts >= RADIUS_CLIENT_MAX_FAILOVER *
462 	    RADIUS_CLIENT_NUM_FAILOVER * num_servers) {
463 		wpa_printf(MSG_INFO,
464 			   "RADIUS: Removing un-ACKed message due to too many failed retransmit attempts");
465 		return 1;
466 	}
467 
468 	entry->attempts++;
469 	entry->accu_attempts++;
470 	hostapd_logger(radius->ctx, entry->addr, HOSTAPD_MODULE_RADIUS,
471 		       HOSTAPD_LEVEL_DEBUG, "Resending RADIUS message (id=%d)",
472 		       radius_msg_get_hdr(entry->msg)->identifier);
473 
474 	os_get_reltime(&entry->last_attempt);
475 	buf = radius_msg_get_buf(entry->msg);
476 	if (send(s, wpabuf_head(buf), wpabuf_len(buf), 0) < 0) {
477 		if (radius_client_handle_send_error(radius, s, entry->msg_type)
478 		    > 0)
479 			return 0;
480 	}
481 
482 	entry->next_try = now + entry->next_wait;
483 	entry->next_wait *= 2;
484 	if (entry->next_wait > RADIUS_CLIENT_MAX_WAIT)
485 		entry->next_wait = RADIUS_CLIENT_MAX_WAIT;
486 
487 	return 0;
488 }
489 
490 
491 static void radius_client_timer(void *eloop_ctx, void *timeout_ctx)
492 {
493 	struct radius_client_data *radius = eloop_ctx;
494 	struct os_reltime now;
495 	os_time_t first;
496 	struct radius_msg_list *entry, *prev, *tmp;
497 	int auth_failover = 0, acct_failover = 0;
498 	size_t prev_num_msgs;
499 	int s;
500 
501 	entry = radius->msgs;
502 	if (!entry)
503 		return;
504 
505 	os_get_reltime(&now);
506 
507 	while (entry) {
508 		if (now.sec >= entry->next_try) {
509 			s = entry->msg_type == RADIUS_AUTH ? radius->auth_sock :
510 				radius->acct_sock;
511 			if (entry->attempts >= RADIUS_CLIENT_NUM_FAILOVER ||
512 			    (s < 0 && entry->attempts > 0)) {
513 				if (entry->msg_type == RADIUS_ACCT ||
514 				    entry->msg_type == RADIUS_ACCT_INTERIM)
515 					acct_failover++;
516 				else
517 					auth_failover++;
518 			}
519 		}
520 		entry = entry->next;
521 	}
522 
523 	if (auth_failover)
524 		radius_client_auth_failover(radius);
525 
526 	if (acct_failover)
527 		radius_client_acct_failover(radius);
528 
529 	entry = radius->msgs;
530 	first = 0;
531 
532 	prev = NULL;
533 	while (entry) {
534 		prev_num_msgs = radius->num_msgs;
535 		if (now.sec >= entry->next_try &&
536 		    radius_client_retransmit(radius, entry, now.sec)) {
537 			if (prev)
538 				prev->next = entry->next;
539 			else
540 				radius->msgs = entry->next;
541 
542 			tmp = entry;
543 			entry = entry->next;
544 			radius_client_msg_free(tmp);
545 			radius->num_msgs--;
546 			continue;
547 		}
548 
549 		if (prev_num_msgs != radius->num_msgs) {
550 			wpa_printf(MSG_DEBUG,
551 				   "RADIUS: Message removed from queue - restart from beginning");
552 			entry = radius->msgs;
553 			prev = NULL;
554 			continue;
555 		}
556 
557 		if (first == 0 || entry->next_try < first)
558 			first = entry->next_try;
559 
560 		prev = entry;
561 		entry = entry->next;
562 	}
563 
564 	if (radius->msgs) {
565 		if (first < now.sec)
566 			first = now.sec;
567 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
568 		eloop_register_timeout(first - now.sec, 0,
569 				       radius_client_timer, radius, NULL);
570 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
571 			       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client "
572 			       "retransmit in %ld seconds",
573 			       (long int) (first - now.sec));
574 	}
575 }
576 
577 
578 static void radius_client_auth_failover(struct radius_client_data *radius)
579 {
580 	struct hostapd_radius_servers *conf = radius->conf;
581 	struct hostapd_radius_server *next, *old;
582 	struct radius_msg_list *entry;
583 	char abuf[50];
584 
585 	old = conf->auth_server;
586 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
587 		       HOSTAPD_LEVEL_NOTICE,
588 		       "No response from Authentication server %s:%d - failover",
589 		       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
590 		       old->port);
591 
592 	for (entry = radius->msgs; entry; entry = entry->next) {
593 		if (entry->msg_type == RADIUS_AUTH)
594 			old->timeouts++;
595 	}
596 
597 	next = old + 1;
598 	if (next > &(conf->auth_servers[conf->num_auth_servers - 1]))
599 		next = conf->auth_servers;
600 	conf->auth_server = next;
601 	radius_change_server(radius, next, old,
602 			     radius->auth_serv_sock,
603 			     radius->auth_serv_sock6, 1);
604 }
605 
606 
607 static void radius_client_acct_failover(struct radius_client_data *radius)
608 {
609 	struct hostapd_radius_servers *conf = radius->conf;
610 	struct hostapd_radius_server *next, *old;
611 	struct radius_msg_list *entry;
612 	char abuf[50];
613 
614 	old = conf->acct_server;
615 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
616 		       HOSTAPD_LEVEL_NOTICE,
617 		       "No response from Accounting server %s:%d - failover",
618 		       hostapd_ip_txt(&old->addr, abuf, sizeof(abuf)),
619 		       old->port);
620 
621 	for (entry = radius->msgs; entry; entry = entry->next) {
622 		if (entry->msg_type == RADIUS_ACCT ||
623 		    entry->msg_type == RADIUS_ACCT_INTERIM)
624 			old->timeouts++;
625 	}
626 
627 	next = old + 1;
628 	if (next > &conf->acct_servers[conf->num_acct_servers - 1])
629 		next = conf->acct_servers;
630 	conf->acct_server = next;
631 	radius_change_server(radius, next, old,
632 			     radius->acct_serv_sock,
633 			     radius->acct_serv_sock6, 0);
634 }
635 
636 
637 static void radius_client_update_timeout(struct radius_client_data *radius)
638 {
639 	struct os_reltime now;
640 	os_time_t first;
641 	struct radius_msg_list *entry;
642 
643 	eloop_cancel_timeout(radius_client_timer, radius, NULL);
644 
645 	if (radius->msgs == NULL) {
646 		return;
647 	}
648 
649 	first = 0;
650 	for (entry = radius->msgs; entry; entry = entry->next) {
651 		if (first == 0 || entry->next_try < first)
652 			first = entry->next_try;
653 	}
654 
655 	os_get_reltime(&now);
656 	if (first < now.sec)
657 		first = now.sec;
658 	eloop_register_timeout(first - now.sec, 0, radius_client_timer, radius,
659 			       NULL);
660 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
661 		       HOSTAPD_LEVEL_DEBUG, "Next RADIUS client retransmit in"
662 		       " %ld seconds", (long int) (first - now.sec));
663 }
664 
665 
666 static void radius_client_list_add(struct radius_client_data *radius,
667 				   struct radius_msg *msg,
668 				   RadiusType msg_type,
669 				   const u8 *shared_secret,
670 				   size_t shared_secret_len, const u8 *addr)
671 {
672 	struct radius_msg_list *entry, *prev;
673 
674 	if (eloop_terminated()) {
675 		/* No point in adding entries to retransmit queue since event
676 		 * loop has already been terminated. */
677 		radius_msg_free(msg);
678 		return;
679 	}
680 
681 	entry = os_zalloc(sizeof(*entry));
682 	if (entry == NULL) {
683 		wpa_printf(MSG_INFO, "RADIUS: Failed to add packet into retransmit list");
684 		radius_msg_free(msg);
685 		return;
686 	}
687 
688 	if (addr)
689 		os_memcpy(entry->addr, addr, ETH_ALEN);
690 	entry->msg = msg;
691 	entry->msg_type = msg_type;
692 	entry->shared_secret = shared_secret;
693 	entry->shared_secret_len = shared_secret_len;
694 	os_get_reltime(&entry->last_attempt);
695 	entry->first_try = entry->last_attempt.sec;
696 	entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
697 	entry->attempts = 1;
698 	entry->accu_attempts = 1;
699 	entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
700 	if (entry->next_wait > RADIUS_CLIENT_MAX_WAIT)
701 		entry->next_wait = RADIUS_CLIENT_MAX_WAIT;
702 	entry->next = radius->msgs;
703 	radius->msgs = entry;
704 	radius_client_update_timeout(radius);
705 
706 	if (radius->num_msgs >= RADIUS_CLIENT_MAX_ENTRIES) {
707 		wpa_printf(MSG_INFO, "RADIUS: Removing the oldest un-ACKed packet due to retransmit list limits");
708 		prev = NULL;
709 		while (entry->next) {
710 			prev = entry;
711 			entry = entry->next;
712 		}
713 		if (prev) {
714 			prev->next = NULL;
715 			radius_client_msg_free(entry);
716 		}
717 	} else
718 		radius->num_msgs++;
719 }
720 
721 
722 /**
723  * radius_client_send - Send a RADIUS request
724  * @radius: RADIUS client context from radius_client_init()
725  * @msg: RADIUS message to be sent
726  * @msg_type: Message type (RADIUS_AUTH, RADIUS_ACCT, RADIUS_ACCT_INTERIM)
727  * @addr: MAC address of the device related to this message or %NULL
728  * Returns: 0 on success, -1 on failure
729  *
730  * This function is used to transmit a RADIUS authentication (RADIUS_AUTH) or
731  * accounting request (RADIUS_ACCT or RADIUS_ACCT_INTERIM). The only difference
732  * between accounting and interim accounting messages is that the interim
733  * message will not be retransmitted. Instead, a callback is used to indicate
734  * that the transmission failed for the specific station @addr so that a new
735  * interim accounting update message can be generated with up-to-date session
736  * data instead of trying to resend old information.
737  *
738  * The message is added on the retransmission queue and will be retransmitted
739  * automatically until a response is received or maximum number of retries
740  * (RADIUS_CLIENT_MAX_FAILOVER * RADIUS_CLIENT_NUM_FAILOVER) is reached. No
741  * such retries are used with RADIUS_ACCT_INTERIM, i.e., such a pending message
742  * is removed from the queue automatically on transmission failure.
743  *
744  * The related device MAC address can be used to identify pending messages that
745  * can be removed with radius_client_flush_auth().
746  */
747 int radius_client_send(struct radius_client_data *radius,
748 		       struct radius_msg *msg, RadiusType msg_type,
749 		       const u8 *addr)
750 {
751 	struct hostapd_radius_servers *conf = radius->conf;
752 	const u8 *shared_secret;
753 	size_t shared_secret_len;
754 	char *name;
755 	int s, res;
756 	struct wpabuf *buf;
757 
758 	if (msg_type == RADIUS_ACCT || msg_type == RADIUS_ACCT_INTERIM) {
759 		if (conf->acct_server && radius->acct_sock < 0)
760 			radius_client_init_acct(radius);
761 
762 		if (conf->acct_server == NULL || radius->acct_sock < 0 ||
763 		    conf->acct_server->shared_secret == NULL) {
764 			hostapd_logger(radius->ctx, NULL,
765 				       HOSTAPD_MODULE_RADIUS,
766 				       HOSTAPD_LEVEL_INFO,
767 				       "No accounting server configured");
768 			return -1;
769 		}
770 		shared_secret = conf->acct_server->shared_secret;
771 		shared_secret_len = conf->acct_server->shared_secret_len;
772 		radius_msg_finish_acct(msg, shared_secret, shared_secret_len);
773 		name = "accounting";
774 		s = radius->acct_sock;
775 		conf->acct_server->requests++;
776 	} else {
777 		if (conf->auth_server && radius->auth_sock < 0)
778 			radius_client_init_auth(radius);
779 
780 		if (conf->auth_server == NULL || radius->auth_sock < 0 ||
781 		    conf->auth_server->shared_secret == NULL) {
782 			hostapd_logger(radius->ctx, NULL,
783 				       HOSTAPD_MODULE_RADIUS,
784 				       HOSTAPD_LEVEL_INFO,
785 				       "No authentication server configured");
786 			return -1;
787 		}
788 		shared_secret = conf->auth_server->shared_secret;
789 		shared_secret_len = conf->auth_server->shared_secret_len;
790 		radius_msg_finish(msg, shared_secret, shared_secret_len);
791 		name = "authentication";
792 		s = radius->auth_sock;
793 		conf->auth_server->requests++;
794 	}
795 
796 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
797 		       HOSTAPD_LEVEL_DEBUG, "Sending RADIUS message to %s "
798 		       "server", name);
799 	if (conf->msg_dumps)
800 		radius_msg_dump(msg);
801 
802 	buf = radius_msg_get_buf(msg);
803 	res = send(s, wpabuf_head(buf), wpabuf_len(buf), 0);
804 	if (res < 0)
805 		radius_client_handle_send_error(radius, s, msg_type);
806 
807 	radius_client_list_add(radius, msg, msg_type, shared_secret,
808 			       shared_secret_len, addr);
809 
810 	return 0;
811 }
812 
813 
814 static void radius_client_receive(int sock, void *eloop_ctx, void *sock_ctx)
815 {
816 	struct radius_client_data *radius = eloop_ctx;
817 	struct hostapd_radius_servers *conf = radius->conf;
818 	RadiusType msg_type = (uintptr_t) sock_ctx;
819 	int len, roundtrip;
820 	unsigned char buf[RADIUS_MAX_MSG_LEN];
821 	struct msghdr msghdr = {0};
822 	struct iovec iov;
823 	struct radius_msg *msg;
824 	struct radius_hdr *hdr;
825 	struct radius_rx_handler *handlers;
826 	size_t num_handlers, i;
827 	struct radius_msg_list *req, *prev_req;
828 	struct os_reltime now;
829 	struct hostapd_radius_server *rconf;
830 	int invalid_authenticator = 0;
831 
832 	if (msg_type == RADIUS_ACCT) {
833 		handlers = radius->acct_handlers;
834 		num_handlers = radius->num_acct_handlers;
835 		rconf = conf->acct_server;
836 	} else {
837 		handlers = radius->auth_handlers;
838 		num_handlers = radius->num_auth_handlers;
839 		rconf = conf->auth_server;
840 	}
841 
842 	iov.iov_base = buf;
843 	iov.iov_len = RADIUS_MAX_MSG_LEN;
844 	msghdr.msg_iov = &iov;
845 	msghdr.msg_iovlen = 1;
846 	msghdr.msg_flags = 0;
847 	len = recvmsg(sock, &msghdr, MSG_DONTWAIT);
848 	if (len < 0) {
849 		wpa_printf(MSG_INFO, "recvmsg[RADIUS]: %s", strerror(errno));
850 		return;
851 	}
852 
853 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
854 		       HOSTAPD_LEVEL_DEBUG, "Received %d bytes from RADIUS "
855 		       "server", len);
856 
857 	if (msghdr.msg_flags & MSG_TRUNC) {
858 		wpa_printf(MSG_INFO, "RADIUS: Possibly too long UDP frame for our buffer - dropping it");
859 		return;
860 	}
861 
862 	msg = radius_msg_parse(buf, len);
863 	if (msg == NULL) {
864 		wpa_printf(MSG_INFO, "RADIUS: Parsing incoming frame failed");
865 		rconf->malformed_responses++;
866 		return;
867 	}
868 	hdr = radius_msg_get_hdr(msg);
869 
870 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
871 		       HOSTAPD_LEVEL_DEBUG, "Received RADIUS message");
872 	if (conf->msg_dumps)
873 		radius_msg_dump(msg);
874 
875 	switch (hdr->code) {
876 	case RADIUS_CODE_ACCESS_ACCEPT:
877 		rconf->access_accepts++;
878 		break;
879 	case RADIUS_CODE_ACCESS_REJECT:
880 		rconf->access_rejects++;
881 		break;
882 	case RADIUS_CODE_ACCESS_CHALLENGE:
883 		rconf->access_challenges++;
884 		break;
885 	case RADIUS_CODE_ACCOUNTING_RESPONSE:
886 		rconf->responses++;
887 		break;
888 	}
889 
890 	prev_req = NULL;
891 	req = radius->msgs;
892 	while (req) {
893 		/* TODO: also match by src addr:port of the packet when using
894 		 * alternative RADIUS servers (?) */
895 		if ((req->msg_type == msg_type ||
896 		     (req->msg_type == RADIUS_ACCT_INTERIM &&
897 		      msg_type == RADIUS_ACCT)) &&
898 		    radius_msg_get_hdr(req->msg)->identifier ==
899 		    hdr->identifier)
900 			break;
901 
902 		prev_req = req;
903 		req = req->next;
904 	}
905 
906 	if (req == NULL) {
907 		hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
908 			       HOSTAPD_LEVEL_DEBUG,
909 			       "No matching RADIUS request found (type=%d "
910 			       "id=%d) - dropping packet",
911 			       msg_type, hdr->identifier);
912 		goto fail;
913 	}
914 
915 	os_get_reltime(&now);
916 	roundtrip = (now.sec - req->last_attempt.sec) * 100 +
917 		(now.usec - req->last_attempt.usec) / 10000;
918 	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
919 		       HOSTAPD_LEVEL_DEBUG,
920 		       "Received RADIUS packet matched with a pending "
921 		       "request, round trip time %d.%02d sec",
922 		       roundtrip / 100, roundtrip % 100);
923 	rconf->round_trip_time = roundtrip;
924 
925 	/* Remove ACKed RADIUS packet from retransmit list */
926 	if (prev_req)
927 		prev_req->next = req->next;
928 	else
929 		radius->msgs = req->next;
930 	radius->num_msgs--;
931 
932 	for (i = 0; i < num_handlers; i++) {
933 		RadiusRxResult res;
934 		res = handlers[i].handler(msg, req->msg, req->shared_secret,
935 					  req->shared_secret_len,
936 					  handlers[i].data);
937 		switch (res) {
938 		case RADIUS_RX_PROCESSED:
939 			radius_msg_free(msg);
940 			/* fall through */
941 		case RADIUS_RX_QUEUED:
942 			radius_client_msg_free(req);
943 			return;
944 		case RADIUS_RX_INVALID_AUTHENTICATOR:
945 			invalid_authenticator++;
946 			/* fall through */
947 		case RADIUS_RX_UNKNOWN:
948 			/* continue with next handler */
949 			break;
950 		}
951 	}
952 
953 	if (invalid_authenticator)
954 		rconf->bad_authenticators++;
955 	else
956 		rconf->unknown_types++;
957 	hostapd_logger(radius->ctx, req->addr, HOSTAPD_MODULE_RADIUS,
958 		       HOSTAPD_LEVEL_DEBUG, "No RADIUS RX handler found "
959 		       "(type=%d code=%d id=%d)%s - dropping packet",
960 		       msg_type, hdr->code, hdr->identifier,
961 		       invalid_authenticator ? " [INVALID AUTHENTICATOR]" :
962 		       "");
963 	radius_client_msg_free(req);
964 
965  fail:
966 	radius_msg_free(msg);
967 }
968 
969 
970 /**
971  * radius_client_get_id - Get an identifier for a new RADIUS message
972  * @radius: RADIUS client context from radius_client_init()
973  * Returns: Allocated identifier
974  *
975  * This function is used to fetch a unique (among pending requests) identifier
976  * for a new RADIUS message.
977  */
978 u8 radius_client_get_id(struct radius_client_data *radius)
979 {
980 	struct radius_msg_list *entry, *prev, *_remove;
981 	u8 id = radius->next_radius_identifier++;
982 
983 	/* remove entries with matching id from retransmit list to avoid
984 	 * using new reply from the RADIUS server with an old request */
985 	entry = radius->msgs;
986 	prev = NULL;
987 	while (entry) {
988 		if (radius_msg_get_hdr(entry->msg)->identifier == id) {
989 			hostapd_logger(radius->ctx, entry->addr,
990 				       HOSTAPD_MODULE_RADIUS,
991 				       HOSTAPD_LEVEL_DEBUG,
992 				       "Removing pending RADIUS message, "
993 				       "since its id (%d) is reused", id);
994 			if (prev)
995 				prev->next = entry->next;
996 			else
997 				radius->msgs = entry->next;
998 			_remove = entry;
999 		} else {
1000 			_remove = NULL;
1001 			prev = entry;
1002 		}
1003 		entry = entry->next;
1004 
1005 		if (_remove)
1006 			radius_client_msg_free(_remove);
1007 	}
1008 
1009 	return id;
1010 }
1011 
1012 
1013 /**
1014  * radius_client_flush - Flush all pending RADIUS client messages
1015  * @radius: RADIUS client context from radius_client_init()
1016  * @only_auth: Whether only authentication messages are removed
1017  */
1018 void radius_client_flush(struct radius_client_data *radius, int only_auth)
1019 {
1020 	struct radius_msg_list *entry, *prev, *tmp;
1021 
1022 	if (!radius)
1023 		return;
1024 
1025 	prev = NULL;
1026 	entry = radius->msgs;
1027 
1028 	while (entry) {
1029 		if (!only_auth || entry->msg_type == RADIUS_AUTH) {
1030 			if (prev)
1031 				prev->next = entry->next;
1032 			else
1033 				radius->msgs = entry->next;
1034 
1035 			tmp = entry;
1036 			entry = entry->next;
1037 			radius_client_msg_free(tmp);
1038 			radius->num_msgs--;
1039 		} else {
1040 			prev = entry;
1041 			entry = entry->next;
1042 		}
1043 	}
1044 
1045 	if (radius->msgs == NULL)
1046 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
1047 }
1048 
1049 
1050 static void radius_client_update_acct_msgs(struct radius_client_data *radius,
1051 					   const u8 *shared_secret,
1052 					   size_t shared_secret_len)
1053 {
1054 	struct radius_msg_list *entry;
1055 
1056 	if (!radius)
1057 		return;
1058 
1059 	for (entry = radius->msgs; entry; entry = entry->next) {
1060 		if (entry->msg_type == RADIUS_ACCT) {
1061 			entry->shared_secret = shared_secret;
1062 			entry->shared_secret_len = shared_secret_len;
1063 			radius_msg_finish_acct(entry->msg, shared_secret,
1064 					       shared_secret_len);
1065 		}
1066 	}
1067 }
1068 
1069 
1070 static int
1071 radius_change_server(struct radius_client_data *radius,
1072 		     struct hostapd_radius_server *nserv,
1073 		     struct hostapd_radius_server *oserv,
1074 		     int sock, int sock6, int auth)
1075 {
1076 	struct sockaddr_in serv, claddr;
1077 #ifdef CONFIG_IPV6
1078 	struct sockaddr_in6 serv6, claddr6;
1079 #endif /* CONFIG_IPV6 */
1080 	struct sockaddr *addr, *cl_addr;
1081 	socklen_t addrlen, claddrlen;
1082 	char abuf[50];
1083 	int sel_sock;
1084 	struct radius_msg_list *entry;
1085 	struct hostapd_radius_servers *conf = radius->conf;
1086 	struct sockaddr_in disconnect_addr = {
1087 		.sin_family = AF_UNSPEC,
1088 	};
1089 
1090 	hostapd_logger(radius->ctx, NULL, HOSTAPD_MODULE_RADIUS,
1091 		       HOSTAPD_LEVEL_INFO,
1092 		       "%s server %s:%d",
1093 		       auth ? "Authentication" : "Accounting",
1094 		       hostapd_ip_txt(&nserv->addr, abuf, sizeof(abuf)),
1095 		       nserv->port);
1096 
1097 	if (oserv && oserv == nserv) {
1098 		/* Reconnect to same server, flush */
1099 		if (auth)
1100 			radius_client_flush(radius, 1);
1101 	}
1102 
1103 	if (oserv && oserv != nserv &&
1104 	    (nserv->shared_secret_len != oserv->shared_secret_len ||
1105 	     os_memcmp(nserv->shared_secret, oserv->shared_secret,
1106 		       nserv->shared_secret_len) != 0)) {
1107 		/* Pending RADIUS packets used different shared secret, so
1108 		 * they need to be modified. Update accounting message
1109 		 * authenticators here. Authentication messages are removed
1110 		 * since they would require more changes and the new RADIUS
1111 		 * server may not be prepared to receive them anyway due to
1112 		 * missing state information. Client will likely retry
1113 		 * authentication, so this should not be an issue. */
1114 		if (auth)
1115 			radius_client_flush(radius, 1);
1116 		else {
1117 			radius_client_update_acct_msgs(
1118 				radius, nserv->shared_secret,
1119 				nserv->shared_secret_len);
1120 		}
1121 	}
1122 
1123 	/* Reset retry counters */
1124 	for (entry = radius->msgs; oserv && entry; entry = entry->next) {
1125 		if ((auth && entry->msg_type != RADIUS_AUTH) ||
1126 		    (!auth && entry->msg_type != RADIUS_ACCT))
1127 			continue;
1128 		entry->next_try = entry->first_try + RADIUS_CLIENT_FIRST_WAIT;
1129 		entry->attempts = 0;
1130 		entry->next_wait = RADIUS_CLIENT_FIRST_WAIT * 2;
1131 	}
1132 
1133 	if (radius->msgs) {
1134 		eloop_cancel_timeout(radius_client_timer, radius, NULL);
1135 		eloop_register_timeout(RADIUS_CLIENT_FIRST_WAIT, 0,
1136 				       radius_client_timer, radius, NULL);
1137 	}
1138 
1139 	switch (nserv->addr.af) {
1140 	case AF_INET:
1141 		os_memset(&serv, 0, sizeof(serv));
1142 		serv.sin_family = AF_INET;
1143 		serv.sin_addr.s_addr = nserv->addr.u.v4.s_addr;
1144 		serv.sin_port = htons(nserv->port);
1145 		addr = (struct sockaddr *) &serv;
1146 		addrlen = sizeof(serv);
1147 		sel_sock = sock;
1148 		break;
1149 #ifdef CONFIG_IPV6
1150 	case AF_INET6:
1151 		os_memset(&serv6, 0, sizeof(serv6));
1152 		serv6.sin6_family = AF_INET6;
1153 		os_memcpy(&serv6.sin6_addr, &nserv->addr.u.v6,
1154 			  sizeof(struct in6_addr));
1155 		serv6.sin6_port = htons(nserv->port);
1156 		addr = (struct sockaddr *) &serv6;
1157 		addrlen = sizeof(serv6);
1158 		sel_sock = sock6;
1159 		break;
1160 #endif /* CONFIG_IPV6 */
1161 	default:
1162 		return -1;
1163 	}
1164 
1165 	if (sel_sock < 0) {
1166 		wpa_printf(MSG_INFO,
1167 			   "RADIUS: No server socket available (af=%d sock=%d sock6=%d auth=%d",
1168 			   nserv->addr.af, sock, sock6, auth);
1169 		return -1;
1170 	}
1171 
1172 	/* Force a reconnect by disconnecting the socket first */
1173 	if (connect(sel_sock, (struct sockaddr *) &disconnect_addr,
1174 		    sizeof(disconnect_addr)) < 0)
1175 		wpa_printf(MSG_INFO, "disconnect[radius]: %s", strerror(errno));
1176 
1177 #ifdef __linux__
1178 	if (conf->force_client_dev && conf->force_client_dev[0]) {
1179 		if (setsockopt(sel_sock, SOL_SOCKET, SO_BINDTODEVICE,
1180 			       conf->force_client_dev,
1181 			       os_strlen(conf->force_client_dev)) < 0) {
1182 			wpa_printf(MSG_ERROR,
1183 				   "RADIUS: setsockopt[SO_BINDTODEVICE]: %s",
1184 				   strerror(errno));
1185 			/* Probably not a critical error; continue on and hope
1186 			 * for the best. */
1187 		} else {
1188 			wpa_printf(MSG_DEBUG,
1189 				   "RADIUS: Bound client socket to device: %s",
1190 				   conf->force_client_dev);
1191 		}
1192 	}
1193 #endif /* __linux__ */
1194 
1195 	if (conf->force_client_addr) {
1196 		switch (conf->client_addr.af) {
1197 		case AF_INET:
1198 			os_memset(&claddr, 0, sizeof(claddr));
1199 			claddr.sin_family = AF_INET;
1200 			claddr.sin_addr.s_addr = conf->client_addr.u.v4.s_addr;
1201 			claddr.sin_port = htons(0);
1202 			cl_addr = (struct sockaddr *) &claddr;
1203 			claddrlen = sizeof(claddr);
1204 			break;
1205 #ifdef CONFIG_IPV6
1206 		case AF_INET6:
1207 			os_memset(&claddr6, 0, sizeof(claddr6));
1208 			claddr6.sin6_family = AF_INET6;
1209 			os_memcpy(&claddr6.sin6_addr, &conf->client_addr.u.v6,
1210 				  sizeof(struct in6_addr));
1211 			claddr6.sin6_port = htons(0);
1212 			cl_addr = (struct sockaddr *) &claddr6;
1213 			claddrlen = sizeof(claddr6);
1214 			break;
1215 #endif /* CONFIG_IPV6 */
1216 		default:
1217 			return -1;
1218 		}
1219 
1220 		if (bind(sel_sock, cl_addr, claddrlen) < 0) {
1221 			wpa_printf(MSG_INFO, "bind[radius]: %s",
1222 				   strerror(errno));
1223 			return -1;
1224 		}
1225 	}
1226 
1227 	if (connect(sel_sock, addr, addrlen) < 0) {
1228 		wpa_printf(MSG_INFO, "connect[radius]: %s", strerror(errno));
1229 		return -1;
1230 	}
1231 
1232 #ifndef CONFIG_NATIVE_WINDOWS
1233 	switch (nserv->addr.af) {
1234 	case AF_INET:
1235 		claddrlen = sizeof(claddr);
1236 		if (getsockname(sel_sock, (struct sockaddr *) &claddr,
1237 				&claddrlen) == 0) {
1238 			wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
1239 				   inet_ntoa(claddr.sin_addr),
1240 				   ntohs(claddr.sin_port));
1241 		}
1242 		break;
1243 #ifdef CONFIG_IPV6
1244 	case AF_INET6: {
1245 		claddrlen = sizeof(claddr6);
1246 		if (getsockname(sel_sock, (struct sockaddr *) &claddr6,
1247 				&claddrlen) == 0) {
1248 			wpa_printf(MSG_DEBUG, "RADIUS local address: %s:%u",
1249 				   inet_ntop(AF_INET6, &claddr6.sin6_addr,
1250 					     abuf, sizeof(abuf)),
1251 				   ntohs(claddr6.sin6_port));
1252 		}
1253 		break;
1254 	}
1255 #endif /* CONFIG_IPV6 */
1256 	}
1257 #endif /* CONFIG_NATIVE_WINDOWS */
1258 
1259 	if (auth)
1260 		radius->auth_sock = sel_sock;
1261 	else
1262 		radius->acct_sock = sel_sock;
1263 
1264 	return 0;
1265 }
1266 
1267 
1268 static void radius_retry_primary_timer(void *eloop_ctx, void *timeout_ctx)
1269 {
1270 	struct radius_client_data *radius = eloop_ctx;
1271 	struct hostapd_radius_servers *conf = radius->conf;
1272 	struct hostapd_radius_server *oserv;
1273 
1274 	if (radius->auth_sock >= 0 && conf->auth_servers &&
1275 	    conf->auth_server != conf->auth_servers) {
1276 		oserv = conf->auth_server;
1277 		conf->auth_server = conf->auth_servers;
1278 		if (radius_change_server(radius, conf->auth_server, oserv,
1279 					 radius->auth_serv_sock,
1280 					 radius->auth_serv_sock6, 1) < 0) {
1281 			conf->auth_server = oserv;
1282 			radius_change_server(radius, oserv, conf->auth_server,
1283 					     radius->auth_serv_sock,
1284 					     radius->auth_serv_sock6, 1);
1285 		}
1286 	}
1287 
1288 	if (radius->acct_sock >= 0 && conf->acct_servers &&
1289 	    conf->acct_server != conf->acct_servers) {
1290 		oserv = conf->acct_server;
1291 		conf->acct_server = conf->acct_servers;
1292 		if (radius_change_server(radius, conf->acct_server, oserv,
1293 					 radius->acct_serv_sock,
1294 					 radius->acct_serv_sock6, 0) < 0) {
1295 			conf->acct_server = oserv;
1296 			radius_change_server(radius, oserv, conf->acct_server,
1297 					     radius->acct_serv_sock,
1298 					     radius->acct_serv_sock6, 0);
1299 		}
1300 	}
1301 
1302 	if (conf->retry_primary_interval)
1303 		eloop_register_timeout(conf->retry_primary_interval, 0,
1304 				       radius_retry_primary_timer, radius,
1305 				       NULL);
1306 }
1307 
1308 
1309 static int radius_client_disable_pmtu_discovery(int s)
1310 {
1311 	int r = -1;
1312 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1313 	/* Turn off Path MTU discovery on IPv4/UDP sockets. */
1314 	int action = IP_PMTUDISC_DONT;
1315 	r = setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &action,
1316 		       sizeof(action));
1317 	if (r == -1)
1318 		wpa_printf(MSG_ERROR, "RADIUS: Failed to set IP_MTU_DISCOVER: %s",
1319 			   strerror(errno));
1320 #endif
1321 	return r;
1322 }
1323 
1324 
1325 static void radius_close_auth_sockets(struct radius_client_data *radius)
1326 {
1327 	radius->auth_sock = -1;
1328 
1329 	if (radius->auth_serv_sock >= 0) {
1330 		eloop_unregister_read_sock(radius->auth_serv_sock);
1331 		close(radius->auth_serv_sock);
1332 		radius->auth_serv_sock = -1;
1333 	}
1334 #ifdef CONFIG_IPV6
1335 	if (radius->auth_serv_sock6 >= 0) {
1336 		eloop_unregister_read_sock(radius->auth_serv_sock6);
1337 		close(radius->auth_serv_sock6);
1338 		radius->auth_serv_sock6 = -1;
1339 	}
1340 #endif /* CONFIG_IPV6 */
1341 }
1342 
1343 
1344 static void radius_close_acct_sockets(struct radius_client_data *radius)
1345 {
1346 	radius->acct_sock = -1;
1347 
1348 	if (radius->acct_serv_sock >= 0) {
1349 		eloop_unregister_read_sock(radius->acct_serv_sock);
1350 		close(radius->acct_serv_sock);
1351 		radius->acct_serv_sock = -1;
1352 	}
1353 #ifdef CONFIG_IPV6
1354 	if (radius->acct_serv_sock6 >= 0) {
1355 		eloop_unregister_read_sock(radius->acct_serv_sock6);
1356 		close(radius->acct_serv_sock6);
1357 		radius->acct_serv_sock6 = -1;
1358 	}
1359 #endif /* CONFIG_IPV6 */
1360 }
1361 
1362 
1363 static int radius_client_init_auth(struct radius_client_data *radius)
1364 {
1365 	struct hostapd_radius_servers *conf = radius->conf;
1366 	int ok = 0;
1367 
1368 	radius_close_auth_sockets(radius);
1369 
1370 	radius->auth_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
1371 	if (radius->auth_serv_sock < 0)
1372 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET,SOCK_DGRAM]: %s",
1373 			   strerror(errno));
1374 	else {
1375 		radius_client_disable_pmtu_discovery(radius->auth_serv_sock);
1376 		ok++;
1377 	}
1378 
1379 #ifdef CONFIG_IPV6
1380 	radius->auth_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
1381 	if (radius->auth_serv_sock6 < 0)
1382 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET6,SOCK_DGRAM]: %s",
1383 			   strerror(errno));
1384 	else
1385 		ok++;
1386 #endif /* CONFIG_IPV6 */
1387 
1388 	if (ok == 0)
1389 		return -1;
1390 
1391 	radius_change_server(radius, conf->auth_server, NULL,
1392 			     radius->auth_serv_sock, radius->auth_serv_sock6,
1393 			     1);
1394 
1395 	if (radius->auth_serv_sock >= 0 &&
1396 	    eloop_register_read_sock(radius->auth_serv_sock,
1397 				     radius_client_receive, radius,
1398 				     (void *) RADIUS_AUTH)) {
1399 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for authentication server");
1400 		radius_close_auth_sockets(radius);
1401 		return -1;
1402 	}
1403 
1404 #ifdef CONFIG_IPV6
1405 	if (radius->auth_serv_sock6 >= 0 &&
1406 	    eloop_register_read_sock(radius->auth_serv_sock6,
1407 				     radius_client_receive, radius,
1408 				     (void *) RADIUS_AUTH)) {
1409 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for authentication server");
1410 		radius_close_auth_sockets(radius);
1411 		return -1;
1412 	}
1413 #endif /* CONFIG_IPV6 */
1414 
1415 	return 0;
1416 }
1417 
1418 
1419 static int radius_client_init_acct(struct radius_client_data *radius)
1420 {
1421 	struct hostapd_radius_servers *conf = radius->conf;
1422 	int ok = 0;
1423 
1424 	radius_close_acct_sockets(radius);
1425 
1426 	radius->acct_serv_sock = socket(PF_INET, SOCK_DGRAM, 0);
1427 	if (radius->acct_serv_sock < 0)
1428 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET,SOCK_DGRAM]: %s",
1429 			   strerror(errno));
1430 	else {
1431 		radius_client_disable_pmtu_discovery(radius->acct_serv_sock);
1432 		ok++;
1433 	}
1434 
1435 #ifdef CONFIG_IPV6
1436 	radius->acct_serv_sock6 = socket(PF_INET6, SOCK_DGRAM, 0);
1437 	if (radius->acct_serv_sock6 < 0)
1438 		wpa_printf(MSG_INFO, "RADIUS: socket[PF_INET6,SOCK_DGRAM]: %s",
1439 			   strerror(errno));
1440 	else
1441 		ok++;
1442 #endif /* CONFIG_IPV6 */
1443 
1444 	if (ok == 0)
1445 		return -1;
1446 
1447 	radius_change_server(radius, conf->acct_server, NULL,
1448 			     radius->acct_serv_sock, radius->acct_serv_sock6,
1449 			     0);
1450 
1451 	if (radius->acct_serv_sock >= 0 &&
1452 	    eloop_register_read_sock(radius->acct_serv_sock,
1453 				     radius_client_receive, radius,
1454 				     (void *) RADIUS_ACCT)) {
1455 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for accounting server");
1456 		radius_close_acct_sockets(radius);
1457 		return -1;
1458 	}
1459 
1460 #ifdef CONFIG_IPV6
1461 	if (radius->acct_serv_sock6 >= 0 &&
1462 	    eloop_register_read_sock(radius->acct_serv_sock6,
1463 				     radius_client_receive, radius,
1464 				     (void *) RADIUS_ACCT)) {
1465 		wpa_printf(MSG_INFO, "RADIUS: Could not register read socket for accounting server");
1466 		radius_close_acct_sockets(radius);
1467 		return -1;
1468 	}
1469 #endif /* CONFIG_IPV6 */
1470 
1471 	return 0;
1472 }
1473 
1474 
1475 /**
1476  * radius_client_init - Initialize RADIUS client
1477  * @ctx: Callback context to be used in hostapd_logger() calls
1478  * @conf: RADIUS client configuration (RADIUS servers)
1479  * Returns: Pointer to private RADIUS client context or %NULL on failure
1480  *
1481  * The caller is responsible for keeping the configuration data available for
1482  * the lifetime of the RADIUS client, i.e., until radius_client_deinit() is
1483  * called for the returned context pointer.
1484  */
1485 struct radius_client_data *
1486 radius_client_init(void *ctx, struct hostapd_radius_servers *conf)
1487 {
1488 	struct radius_client_data *radius;
1489 
1490 	radius = os_zalloc(sizeof(struct radius_client_data));
1491 	if (radius == NULL)
1492 		return NULL;
1493 
1494 	radius->ctx = ctx;
1495 	radius->conf = conf;
1496 	radius->auth_serv_sock = radius->acct_serv_sock =
1497 		radius->auth_serv_sock6 = radius->acct_serv_sock6 =
1498 		radius->auth_sock = radius->acct_sock = -1;
1499 
1500 	if (conf->auth_server && radius_client_init_auth(radius)) {
1501 		radius_client_deinit(radius);
1502 		return NULL;
1503 	}
1504 
1505 	if (conf->acct_server && radius_client_init_acct(radius)) {
1506 		radius_client_deinit(radius);
1507 		return NULL;
1508 	}
1509 
1510 	if (conf->retry_primary_interval)
1511 		eloop_register_timeout(conf->retry_primary_interval, 0,
1512 				       radius_retry_primary_timer, radius,
1513 				       NULL);
1514 
1515 	return radius;
1516 }
1517 
1518 
1519 /**
1520  * radius_client_deinit - Deinitialize RADIUS client
1521  * @radius: RADIUS client context from radius_client_init()
1522  */
1523 void radius_client_deinit(struct radius_client_data *radius)
1524 {
1525 	if (!radius)
1526 		return;
1527 
1528 	radius_close_auth_sockets(radius);
1529 	radius_close_acct_sockets(radius);
1530 
1531 	eloop_cancel_timeout(radius_retry_primary_timer, radius, NULL);
1532 
1533 	radius_client_flush(radius, 0);
1534 	os_free(radius->auth_handlers);
1535 	os_free(radius->acct_handlers);
1536 	os_free(radius);
1537 }
1538 
1539 
1540 /**
1541  * radius_client_flush_auth - Flush pending RADIUS messages for an address
1542  * @radius: RADIUS client context from radius_client_init()
1543  * @addr: MAC address of the related device
1544  *
1545  * This function can be used to remove pending RADIUS authentication messages
1546  * that are related to a specific device. The addr parameter is matched with
1547  * the one used in radius_client_send() call that was used to transmit the
1548  * authentication request.
1549  */
1550 void radius_client_flush_auth(struct radius_client_data *radius,
1551 			      const u8 *addr)
1552 {
1553 	struct radius_msg_list *entry, *prev, *tmp;
1554 
1555 	prev = NULL;
1556 	entry = radius->msgs;
1557 	while (entry) {
1558 		if (entry->msg_type == RADIUS_AUTH &&
1559 		    os_memcmp(entry->addr, addr, ETH_ALEN) == 0) {
1560 			hostapd_logger(radius->ctx, addr,
1561 				       HOSTAPD_MODULE_RADIUS,
1562 				       HOSTAPD_LEVEL_DEBUG,
1563 				       "Removing pending RADIUS authentication"
1564 				       " message for removed client");
1565 
1566 			if (prev)
1567 				prev->next = entry->next;
1568 			else
1569 				radius->msgs = entry->next;
1570 
1571 			tmp = entry;
1572 			entry = entry->next;
1573 			radius_client_msg_free(tmp);
1574 			radius->num_msgs--;
1575 			continue;
1576 		}
1577 
1578 		prev = entry;
1579 		entry = entry->next;
1580 	}
1581 }
1582 
1583 
1584 static int radius_client_dump_auth_server(char *buf, size_t buflen,
1585 					  struct hostapd_radius_server *serv,
1586 					  struct radius_client_data *cli)
1587 {
1588 	int pending = 0;
1589 	struct radius_msg_list *msg;
1590 	char abuf[50];
1591 
1592 	if (cli) {
1593 		for (msg = cli->msgs; msg; msg = msg->next) {
1594 			if (msg->msg_type == RADIUS_AUTH)
1595 				pending++;
1596 		}
1597 	}
1598 
1599 	return os_snprintf(buf, buflen,
1600 			   "radiusAuthServerIndex=%d\n"
1601 			   "radiusAuthServerAddress=%s\n"
1602 			   "radiusAuthClientServerPortNumber=%d\n"
1603 			   "radiusAuthClientRoundTripTime=%d\n"
1604 			   "radiusAuthClientAccessRequests=%u\n"
1605 			   "radiusAuthClientAccessRetransmissions=%u\n"
1606 			   "radiusAuthClientAccessAccepts=%u\n"
1607 			   "radiusAuthClientAccessRejects=%u\n"
1608 			   "radiusAuthClientAccessChallenges=%u\n"
1609 			   "radiusAuthClientMalformedAccessResponses=%u\n"
1610 			   "radiusAuthClientBadAuthenticators=%u\n"
1611 			   "radiusAuthClientPendingRequests=%u\n"
1612 			   "radiusAuthClientTimeouts=%u\n"
1613 			   "radiusAuthClientUnknownTypes=%u\n"
1614 			   "radiusAuthClientPacketsDropped=%u\n",
1615 			   serv->index,
1616 			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
1617 			   serv->port,
1618 			   serv->round_trip_time,
1619 			   serv->requests,
1620 			   serv->retransmissions,
1621 			   serv->access_accepts,
1622 			   serv->access_rejects,
1623 			   serv->access_challenges,
1624 			   serv->malformed_responses,
1625 			   serv->bad_authenticators,
1626 			   pending,
1627 			   serv->timeouts,
1628 			   serv->unknown_types,
1629 			   serv->packets_dropped);
1630 }
1631 
1632 
1633 static int radius_client_dump_acct_server(char *buf, size_t buflen,
1634 					  struct hostapd_radius_server *serv,
1635 					  struct radius_client_data *cli)
1636 {
1637 	int pending = 0;
1638 	struct radius_msg_list *msg;
1639 	char abuf[50];
1640 
1641 	if (cli) {
1642 		for (msg = cli->msgs; msg; msg = msg->next) {
1643 			if (msg->msg_type == RADIUS_ACCT ||
1644 			    msg->msg_type == RADIUS_ACCT_INTERIM)
1645 				pending++;
1646 		}
1647 	}
1648 
1649 	return os_snprintf(buf, buflen,
1650 			   "radiusAccServerIndex=%d\n"
1651 			   "radiusAccServerAddress=%s\n"
1652 			   "radiusAccClientServerPortNumber=%d\n"
1653 			   "radiusAccClientRoundTripTime=%d\n"
1654 			   "radiusAccClientRequests=%u\n"
1655 			   "radiusAccClientRetransmissions=%u\n"
1656 			   "radiusAccClientResponses=%u\n"
1657 			   "radiusAccClientMalformedResponses=%u\n"
1658 			   "radiusAccClientBadAuthenticators=%u\n"
1659 			   "radiusAccClientPendingRequests=%u\n"
1660 			   "radiusAccClientTimeouts=%u\n"
1661 			   "radiusAccClientUnknownTypes=%u\n"
1662 			   "radiusAccClientPacketsDropped=%u\n",
1663 			   serv->index,
1664 			   hostapd_ip_txt(&serv->addr, abuf, sizeof(abuf)),
1665 			   serv->port,
1666 			   serv->round_trip_time,
1667 			   serv->requests,
1668 			   serv->retransmissions,
1669 			   serv->responses,
1670 			   serv->malformed_responses,
1671 			   serv->bad_authenticators,
1672 			   pending,
1673 			   serv->timeouts,
1674 			   serv->unknown_types,
1675 			   serv->packets_dropped);
1676 }
1677 
1678 
1679 /**
1680  * radius_client_get_mib - Get RADIUS client MIB information
1681  * @radius: RADIUS client context from radius_client_init()
1682  * @buf: Buffer for returning MIB data in text format
1683  * @buflen: Maximum buf length in octets
1684  * Returns: Number of octets written into the buffer
1685  */
1686 int radius_client_get_mib(struct radius_client_data *radius, char *buf,
1687 			  size_t buflen)
1688 {
1689 	struct hostapd_radius_servers *conf;
1690 	int i;
1691 	struct hostapd_radius_server *serv;
1692 	int count = 0;
1693 
1694 	if (!radius)
1695 		return 0;
1696 
1697 	conf = radius->conf;
1698 
1699 	if (conf->auth_servers) {
1700 		for (i = 0; i < conf->num_auth_servers; i++) {
1701 			serv = &conf->auth_servers[i];
1702 			count += radius_client_dump_auth_server(
1703 				buf + count, buflen - count, serv,
1704 				serv == conf->auth_server ?
1705 				radius : NULL);
1706 		}
1707 	}
1708 
1709 	if (conf->acct_servers) {
1710 		for (i = 0; i < conf->num_acct_servers; i++) {
1711 			serv = &conf->acct_servers[i];
1712 			count += radius_client_dump_acct_server(
1713 				buf + count, buflen - count, serv,
1714 				serv == conf->acct_server ?
1715 				radius : NULL);
1716 		}
1717 	}
1718 
1719 	return count;
1720 }
1721 
1722 
1723 void radius_client_reconfig(struct radius_client_data *radius,
1724 			    struct hostapd_radius_servers *conf)
1725 {
1726 	if (radius)
1727 		radius->conf = conf;
1728 }
1729