Radcli library 2.0.2
A simple radius library -- new API reference
Loading...
Searching...
No Matches
session.c
1/*
2 * Copyright (c) 2014-2026, Nikos Mavrogiannopoulos. All rights reserved.
3 * Copyright (c) 2015, Red Hat, Inc. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26/* The persistent connection that carries every request of a TCP, TLS or
27 * DTLS ctx: establishment and restart, packet framing, the send queue and
28 * the rc_sockets_override vtable. Plain TCP is implemented here; lib/tls.c
29 * supplies the TLS/DTLS backend (rc_sess_ops). */
30
31#include <config.h>
32#include <includes.h>
33#include <radcli/radcli.h>
34#include "util.h"
35#include "options.h"
36#include "session.h"
37
38#include <poll.h>
39#include <time.h>
40
41static int restart_session(rc_session *s);
42
43/*- Return rh's session, or NULL if its transport does not use one. -*/
44static rc_session *sess_of(rc_handle *rh)
45{
46 if (rh->so_type != RC_SOCKET_TCP && rh->so_type != RC_SOCKET_TLS &&
47 rh->so_type != RC_SOCKET_DTLS)
48 return NULL;
49 return rh->so.ptr;
50}
51
52/*- rc_sockets_override.get_fd: return s's socket, restarting the
53 * connection first if it was marked for restart.
54 *
55 * @param ptr the rc_session.
56 * @param our_sockaddr unused; part of the get_fd calling convention.
57 * @return the socket, or -1 if a needed restart failed.
58 -*/
59static int sess_get_fd(void *ptr, struct sockaddr *our_sockaddr)
60{
61 rc_session *s = ptr;
62
63 if (s->conn.need_restart != 0) {
64 if (restart_session(s) < 0)
65 return -1;
66 }
67 return s->conn.sockfd;
68}
69
70/*- rc_sockets_override.get_active_fd: return s's current socket without
71 * attempting a restart.
72 *
73 * @param ptr the rc_session.
74 * @return the socket, or -1 if none is open.
75 -*/
76static int sess_get_active_fd(void *ptr)
77{
78 rc_session *s = ptr;
79
80 return s->conn.sockfd;
81}
82
83/*- Wait, up to radius_timeout, for s's socket to be ready to repeat a
84 * backend call that returned SESS_AGAIN, or mark s for restart.
85 *
86 * @param s the session to wait on.
87 * @param events POLLIN or POLLOUT, matching the call being repeated.
88 * @param what a short verb ("send"/"receive") for the timeout log message.
89 * @return 1 if the caller should repeat the call, or -1 if it should give
90 * up (errno set to EIO, session marked for restart).
91 -*/
92static int sess_wait_or_give_up(rc_session *s, short events, const char *what)
93{
94 int64_t start_ms = rc_getmtime_ms();
95 int timeout = rc_conf_int_id(s->rh, OPT_RADIUS_TIMEOUT);
96
97 if (timeout <= 0)
98 timeout = 1;
99
100 for (; timeout > 0; timeout -= (int)((rc_getmtime_ms() - start_ms) / 1000)) {
101 struct pollfd pfd = { s->conn.sockfd, events, 0 };
102 int ret = poll(&pfd, 1, timeout * 1000);
103
104 if (ret > 0)
105 return 1;
106 if (ret == 0)
107 break;
108 if (errno != EINTR) {
109 rc_log(LOG_ERR, "%s: poll: %s", __func__, strerror(errno));
110 goto give_up;
111 }
112 /* poll() itself was interrupted; retry against the same
113 * deadline rather than treating it as a timeout. */
114 }
115 rc_log(LOG_ERR, "%s: timeout waiting to %s data", __func__, what);
116give_up:
117 errno = EIO;
118 s->conn.need_restart = 1;
119 return -1;
120}
121
122/*- Read towards one RADIUS packet on s without waiting, on a stream
123 * reassembling it by its Length field (RFC 6614 SS3.4 (1), RFC 6613 SS2.6.4).
124 * Reads no further than the packet's end, so what follows stays unread.
125 *
126 * @param s the session to read from.
127 * @param buf destination for the packet.
128 * @param cap buf's capacity in bytes.
129 * @return the packet's length, else an rc_sess_ops.recv result <= 0, or
130 * -1 on a framing error.
131 -*/
132static int sess_recv_packet(rc_session *s, void *buf, size_t cap)
133{
134 rc_sess_conn *c = &s->conn;
135 size_t want = AUTH_HDR_LENGTH_END;
136 int ret;
137
138 if (s->ops->datagram)
139 return s->ops->recv(c, buf, cap);
140
141 for (;;) {
142 if (c->rlen >= AUTH_HDR_LENGTH_END) {
143 want = ntohs(((AUTH_HDR *)c->rbuf)->length);
144 /* RFC 6613 SS2.6.4: a bad Length leaves the stream unframed. */
145 if (want < AUTH_HDR_LEN || want > RC_MAX_PACKET_LEN || want > cap) {
146 rc_log(LOG_ERR, "%s: invalid RADIUS packet length %u on the connection",
147 __func__, (unsigned)want);
148 return -1;
149 }
150 if (c->rlen == want) {
151 memcpy(buf, c->rbuf, want);
152 c->rlen = 0;
153 return (int)want;
154 }
155 }
156
157 ret = s->ops->recv(c, c->rbuf + c->rlen, want - c->rlen);
158 if (ret <= 0)
159 return ret;
160 c->rlen += ret;
161 }
162}
163
164/*- Discard everything s has queued.
165 *
166 * @param s the session whose queue to empty.
167 -*/
168static void sendq_clear(rc_session *s)
169{
170 s->sendq_len = 0;
171 s->head_started = 0;
172 s->copies_used = 0;
173}
174
175/*- Remove entry i from s's queue, releasing its copy.
176 *
177 * @param s the session whose queue to shorten.
178 * @param i the entry's index; 0 only if the backend has not started on it
179 * or is done with it.
180 -*/
181static void sendq_remove(rc_session *s, unsigned i)
182{
183 if (s->sendq[i].copy >= 0)
184 s->copies_used &= ~(1u << s->sendq[i].copy);
185 if (i == 0)
186 s->head_started = 0;
187 s->sendq_len--;
188 memmove(&s->sendq[i], &s->sendq[i + 1], (s->sendq_len - i) * sizeof(s->sendq[0]));
189}
190
191/*- Report whether s's queue has a free copy for one more record. -*/
192static int sendq_has_copy(rc_session *s)
193{
194 return s->copies_used != (1u << SESS_SENDQ_SIZE) - 1;
195}
196
197/*- Append a record to s's queue: by reference if it is a registry slot's
198 * packet, otherwise into a free copy, which the caller ensured exists.
199 *
200 * @param s the session whose queue to append to.
201 * @param buf the record; a slot's packet must outlive the entry.
202 * @param len buf's length in bytes, at most RC_MAX_PACKET_LEN.
203 * @param kind the record's RADSEC_SEND_* kind.
204 * @param slot the registry slot buf belongs to, or -1.
205 -*/
206static void sendq_append(rc_session *s, const void *buf, size_t len, int kind, int slot)
207{
208 struct sess_pending_send *p = &s->sendq[s->sendq_len++];
209
210 p->len = len;
211 p->kind = kind;
212 p->slot = slot;
213 p->copy = -1;
214 if (slot >= 0) {
215 p->data = buf;
216 return;
217 }
218 while (s->copies_used & (1u << ++p->copy))
219 ;
220 s->copies_used |= 1u << p->copy;
221 memcpy(s->copies[p->copy], buf, len);
222 p->data = s->copies[p->copy];
223}
224
225/*- Make one non-blocking attempt to send s's oldest queued record.
226 *
227 * @param s the session whose queue to advance.
228 * @return 1 if the record went out, 0 if it would block, -1 on a
229 * connection error (the session is marked for restart and the queue
230 * discarded).
231 -*/
232static int sendq_try_head(rc_session *s)
233{
234 int ret = s->ops->send(&s->conn, s->sendq[0].data, s->sendq[0].len);
235
236 if (ret == SESS_AGAIN) {
237 s->head_started = 1;
238 return 0;
239 }
240 if (ret < 0) {
241 s->conn.need_restart = 1;
242 sendq_clear(s);
243 return -1;
244 }
245
246 s->conn.last_msg = time(0);
247 sendq_remove(s, 0);
248 return 1;
249}
250
251/*- rc_sockets_override.sendto: send buf over s, waiting via
252 * sess_wait_or_give_up() while the backend cannot take it, restarting the
253 * connection first if needed.
254 *
255 * @param ptr the rc_session.
256 * @param sockfd unused; part of the sendto calling convention.
257 * @param buf the data to send.
258 * @param len buf's length in bytes.
259 * @param flags unused; part of the sendto calling convention.
260 * @param dest_addr unused; part of the sendto calling convention.
261 * @param addrlen unused; part of the sendto calling convention.
262 * @return the number of bytes sent, or -1 on failure (errno set to EIO).
263 -*/
264static ssize_t sess_sendto(void *ptr, int sockfd,
265 const void *buf, size_t len,
266 int flags, const struct sockaddr *dest_addr,
267 socklen_t addrlen)
268{
269 rc_session *s = ptr;
270 int ret;
271
272 if (s->conn.need_restart != 0) {
273 if (restart_session(s) < 0) {
274 errno = EIO;
275 return -1;
276 }
277 }
278
279 /* What radcli_ctx_dispatch() queued goes first, in order
280 * (REQ-NET2-NET-005); a blocking exchange may wait for it. */
281 while (s->sendq_len > 0) {
282 int r = sendq_try_head(s);
283
284 if (r < 0) {
285 errno = EIO;
286 return -1;
287 }
288 if (r == 0 && sess_wait_or_give_up(s, POLLOUT, "send") < 0)
289 return -1;
290 }
291
292 for (;;) {
293 ret = s->ops->send(&s->conn, buf, len);
294 if (ret == SESS_AGAIN) {
295 if (sess_wait_or_give_up(s, POLLOUT, "send") < 0)
296 return -1;
297 continue;
298 }
299
300 if (ret < 0) {
301 errno = EIO;
302 s->conn.need_restart = 1;
303 return -1;
304 }
305
306 break;
307 }
308
309 s->conn.last_msg = time(0);
310 return ret;
311}
312
313/*- rc_sockets_override.lock: acquire s's lock.
314 *
315 * @param ptr the rc_session.
316 * @return pthread_mutex_lock()'s return value.
317 -*/
318static int sess_lock(void *ptr)
319{
320 rc_session *s = ptr;
321
322 return pthread_mutex_lock(&s->lock);
323}
324
325/*- rc_sockets_override.unlock: release s's lock.
326 *
327 * @param ptr the rc_session.
328 * @return pthread_mutex_unlock()'s return value.
329 -*/
330static int sess_unlock(void *ptr)
331{
332 rc_session *s = ptr;
333
334 return pthread_mutex_unlock(&s->lock);
335}
336
337/*- rc_sockets_override.recvfrom: read one RADIUS packet from s without
338 * waiting; a TLS record carrying no RADIUS data (e.g. a TLS 1.3 session
339 * ticket) or part of a packet leaves the caller to poll() again. The packet
340 * may be any type (RFC 6614 §2.1/§2.5, RFC 7360 §2.2); the caller routes
341 * what is not its own reply.
342 *
343 * @param ptr the rc_session.
344 * @param sockfd unused; part of the recvfrom calling convention.
345 * @param buf destination buffer for the received packet.
346 * @param len buf's capacity in bytes.
347 * @param flags unused; part of the recvfrom calling convention.
348 * @param src_addr unused; part of the recvfrom calling convention.
349 * @param addrlen unused; part of the recvfrom calling convention.
350 * @return the number of bytes received, or -1 on failure (errno set to
351 * EAGAIN if no whole packet is ready yet, EINTR on a received alert, EIO
352 * otherwise).
353 -*/
354static ssize_t sess_recvfrom(void *ptr, int sockfd,
355 void *buf, size_t len,
356 int flags, struct sockaddr *src_addr,
357 socklen_t * addrlen)
358{
359 rc_session *s = ptr;
360 int ret;
361
362 ret = sess_recv_packet(s, buf, len);
363 if (ret == SESS_AGAIN) {
364 errno = EAGAIN;
365 return -1;
366 }
367
368 if (ret == SESS_ALERT) {
369 errno = EINTR;
370 return -1;
371 }
372
373 if (ret <= 0) {
374 if (ret == 0)
375 rc_log(LOG_ERR, "%s: connection closed by the server", __func__);
376 errno = EIO;
377 s->conn.need_restart = 1;
378 return -1;
379 }
380
381 s->conn.last_msg = time(0);
382 s->conn.last_recv = s->conn.last_msg;
383 return ret;
384}
385
386/*- Close c: release the backend's state, then the socket.
387 *
388 * @param s the session c belongs to.
389 * @param c the connection; c->init is left 0.
390 -*/
391static void conn_close(rc_session *s, rc_sess_conn *c)
392{
393 if (c->init == 0)
394 return;
395 c->init = 0;
396 if (s->ops->stop)
397 s->ops->stop(c);
398 if (c->sockfd != -1)
399 close(c->sockfd);
400}
401
402/*- Open and start connecting the socket of a new connection attempt.
403 *
404 * @param s the session to connect, with no attempt in progress.
405 * @return 0 if the attempt is in progress, -1 if it could not start.
406 -*/
407static int attempt_open(rc_session *s)
408{
409 rc_sess_conn *c = &s->next;
410 struct sockaddr_storage our_sockaddr;
411 struct addrinfo *info;
412 int sockfd, ret, e, sock_flags, timeout;
413
414 /* The backend relies on fields it does not write being zero:
415 * REQ-NET-NET-016 */
416 memset(c, 0, sizeof(*c));
417 c->sockfd = -1;
418 c->init = 1;
419 sendq_clear(s);
420
421 memcpy(&our_sockaddr, &s->our_sockaddr, sizeof(our_sockaddr));
422 if (our_sockaddr.ss_family == AF_INET)
423 ((struct sockaddr_in *)&our_sockaddr)->sin_port = 0;
424 else
425 ((struct sockaddr_in6 *)&our_sockaddr)->sin6_port = 0;
426
427 sockfd = socket(our_sockaddr.ss_family, s->ops->datagram ? SOCK_DGRAM : SOCK_STREAM, 0);
428 if (sockfd < 0) {
429 rc_log(LOG_ERR, "%s: cannot open socket", __func__);
430 goto fail;
431 }
432 c->sockfd = sockfd;
433
434 if (s->bind_local) {
435 if (bind(sockfd, SA(&our_sockaddr), SS_LEN(&our_sockaddr)) < 0) {
436 rc_log(LOG_ERR, "%s: bind: %s", __func__, strerror(errno));
437 goto fail;
438 }
439 if (our_sockaddr.ss_family == AF_INET6 &&
440 radcli2_priv_prefer_public_addr(s->rh, sockfd) < 0)
441 goto fail;
442 }
443
444 /* Every operation on the socket must see SESS_AGAIN rather than block
445 * in the kernel with no timeout at all. */
446 sock_flags = fcntl(sockfd, F_GETFL, 0);
447 if (sock_flags == -1 ||
448 fcntl(sockfd, F_SETFL, sock_flags | O_NONBLOCK) == -1) {
449 e = errno;
450 rc_log(LOG_CRIT, "%s: cannot set socket non-blocking: %s",
451 __func__, strerror(e));
452 goto fail;
453 }
454
455 info = rc_getaddrinfo(s->hostname, PW_AI_AUTH);
456 if (info == NULL) {
457 rc_log(LOG_ERR, "%s: cannot resolve %s", __func__, s->hostname);
458 goto fail;
459 }
460
461 if (s->port == 0) {
462 rc_log(LOG_ERR, "%s: no port specified for server %s", __func__, s->hostname);
463 freeaddrinfo(info);
464 goto fail;
465 }
466 if (info->ai_addr->sa_family == AF_INET)
467 ((struct sockaddr_in *)info->ai_addr)->sin_port = htons(s->port);
468 else
469 ((struct sockaddr_in6 *)info->ai_addr)->sin6_port = htons(s->port);
470
471 /* we connect since we are talking to a single server */
472 ret = connect(sockfd, info->ai_addr, info->ai_addrlen);
473 e = errno;
474 freeaddrinfo(info);
475 if (ret == -1 && e != EINPROGRESS) {
476 rc_log(LOG_CRIT, "%s: cannot connect to %s: %s",
477 __func__, s->hostname, strerror(e));
478 goto fail;
479 }
480
481 timeout = rc_conf_int_id(s->rh, OPT_RADIUS_TIMEOUT);
482 s->deadline_ms = rc_getmtime_ms() + rc_timeout_sec_to_ms((timeout > 0) ? timeout : 1);
483 if (++s->gen == 0)
484 s->gen = 1;
485 c->gen = s->gen;
486 s->phase = SESS_CONNECTING;
487 return 0;
488 fail:
489 conn_close(s, c);
490 return -1;
491}
492
493/*- Begin a connection attempt to s's server, unless one is in progress:
494 * open a non-blocking socket and start connecting it, discarding what was
495 * queued for the failed connection. Name resolution may block
496 * (REQ-NET2-NET-001).
497 *
498 * @param s the session to connect.
499 * @return 0 if an attempt is in progress, -1 if it could not start.
500 -*/
501static int attempt_begin(rc_session *s)
502{
503 char *ns;
504 int ns_def_hdl = 0;
505 int ret;
506
507 if (s->phase != SESS_IDLE)
508 return 0;
509
510 /* A socket stays in the namespace it was opened in, and a reconnect
511 * can begin outside any request's own switch (REQ-NET-NET-015). */
512 ns = rc_conf_str_id(s->rh, OPT_NAMESPACE);
513 if (ns != NULL && rc_set_netns(ns, &ns_def_hdl) == -1) {
514 rc_log(LOG_ERR, "%s: namespace %s set failed", __func__, ns);
515 return -1;
516 }
517 ret = attempt_open(s);
518 if (ns != NULL && rc_reset_netns(&ns_def_hdl) == -1)
519 rc_log(LOG_ERR, "%s: namespace %s reset failed", __func__, ns);
520 return ret;
521}
522
523/*- Check, without waiting, whether s's attempt has finished connecting.
524 *
525 * @param s the session whose attempt to check.
526 * @return 1 once connected, 0 while pending, -1 if connecting failed.
527 -*/
528static int attempt_connected(rc_session *s)
529{
530 struct pollfd pfd = { s->next.sockfd, POLLOUT, 0 };
531 socklen_t len = sizeof(int);
532 int err = 0;
533
534 if (poll(&pfd, 1, 0) <= 0)
535 return 0;
536 if (getsockopt(s->next.sockfd, SOL_SOCKET, SO_ERROR, &err, &len) < 0)
537 err = errno;
538 if (err != 0) {
539 rc_log(LOG_CRIT, "%s: cannot connect to %s: %s",
540 __func__, s->hostname, strerror(err));
541 return -1;
542 }
543 return 1;
544}
545
546/*- Advance s's connection attempt as far as it goes without waiting;
547 * once established, it replaces s->conn.
548 *
549 * @param s the session whose attempt to advance.
550 * @return 1 once established, 0 while in progress, -1 if the attempt
551 * failed (s->conn is left unchanged) or none is in progress.
552 -*/
553static int attempt_step(rc_session *s)
554{
555 rc_sess_conn *c = &s->next;
556 int ret;
557
558 if (s->phase == SESS_IDLE)
559 return -1;
560 if (rc_getmtime_ms() >= s->deadline_ms) {
561 rc_log(LOG_ERR, "%s: timeout connecting to %s", __func__, s->hostname);
562 goto fail;
563 }
564
565 if (s->phase == SESS_CONNECTING) {
566 ret = attempt_connected(s);
567 if (ret < 0)
568 goto fail;
569 if (ret == 0)
570 return 0;
571 if (s->ops->start &&
572 s->ops->start(s, c, rc_conf_int_id(s->rh, OPT_RADIUS_TIMEOUT)) < 0)
573 goto fail;
574 s->phase = SESS_HANDSHAKING;
575 }
576
577 if (s->ops->handshake) {
578 ret = s->ops->handshake(c);
579 if (ret == SESS_AGAIN)
580 return 0;
581 if (ret < 0)
582 goto fail;
583 }
584
585 /* A fresh connection counts as activity: without this, last_msg stays
586 * at zero until the first send/receive, which radcli_ctx_get_poll()'s
587 * watchdog-deadline math (lib/dae.c) would read as "idle since the
588 * epoch" right after radcli_dae_start()'s eager connect
589 * (REQ-DAE-INIT-010). */
590 c->last_msg = time(0);
591 c->last_recv = c->last_msg;
592
593 if (c->sockfd == s->conn.sockfd)
594 s->conn.sockfd = -1;
595 conn_close(s, &s->conn);
596 memcpy(&s->conn, c, sizeof(*c));
597 c->init = 0;
598 s->conn.need_restart = 0;
599 s->phase = SESS_IDLE;
600 return 1;
601 fail:
602 rc_log(LOG_ERR, "%s: error in re-initializing the connection", __func__);
603 conn_close(s, c);
604 s->phase = SESS_IDLE;
605 sendq_clear(s);
606 return -1;
607}
608
609/*- Report what s's connection attempt is waiting for.
610 *
611 * @param s a session with an attempt in progress.
612 * @param events set to POLLIN or POLLOUT.
613 * @return milliseconds after which to advance the attempt regardless.
614 -*/
615static int attempt_wait(rc_session *s, short *events)
616{
617 int ms = rc_ms_until(s->deadline_ms);
618 int hs_ms;
619
620 *events = POLLOUT;
621 if (s->phase == SESS_HANDSHAKING && s->ops->handshake_wait) {
622 hs_ms = s->ops->handshake_wait(&s->next, events);
623 if (hs_ms >= 0 && hs_ms < ms)
624 ms = hs_ms;
625 }
626 return ms;
627}
628
629/*- Reconnect s, waiting for the attempt (continuing one already in
630 * progress) to finish. Every call site only ever calls this when the
631 * connection is already known to need it (a send/recv failure already set
632 * need_restart, or session init preset it before the first connection),
633 * so this always reconnects unconditionally -- no rate-limiting.
634 *
635 * @param s the session to restart.
636 * @return 0 on success, -1 if reconnecting failed (s->conn is left
637 * unchanged).
638 -*/
639static int restart_session(rc_session *s)
640{
641 int ret;
642
643 if (attempt_begin(s) < 0)
644 return -1;
645
646 while ((ret = attempt_step(s)) == 0) {
647 struct pollfd pfd = { s->next.sockfd, 0, 0 };
648 int ms = attempt_wait(s, &pfd.events);
649
650 /* A timeout or EINTR only means stepping again. */
651 poll(&pfd, 1, ms);
652 }
653 return ret > 0 ? 0 : -1;
654}
655
656/*- Return the socket of rh's connection, if one is established and not
657 * known to have failed.
658 *
659 * @param rh a handle to parsed configuration.
660 * @return the socket, or -1 if rh uses no session or none is usable.
661 -*/
662int radcli2_priv_sess_fd(rc_handle *rh)
663{
664 rc_session *s = sess_of(rh);
665
666 if (s != NULL && s->conn.init != 0 && s->conn.need_restart == 0)
667 return s->conn.sockfd;
668 return -1;
669}
670
671/*- Report what rh's session needs watched: its connection attempt, or its
672 * established connection.
673 *
674 * @param rh a handle to parsed configuration.
675 * @param events set to the poll() events to wait for.
676 * @param timeout_ms set to the milliseconds after which to call
677 * radcli_ctx_dispatch() regardless, or -1 for none.
678 * @return the socket to watch, or -1 if there is nothing to watch.
679 -*/
680int radcli2_priv_sess_poll(rc_handle *rh, short *events, int *timeout_ms)
681{
682 rc_session *s = sess_of(rh);
683
684 *events = 0;
685 *timeout_ms = -1;
686 if (s == NULL)
687 return -1;
688 if (s->phase != SESS_IDLE) {
689 *timeout_ms = attempt_wait(s, events);
690 return s->next.sockfd;
691 }
692 if (s->conn.init == 0 || s->conn.need_restart != 0)
693 return -1;
694
695 *events = POLLIN;
696 /* Queued records go out once the socket is writable again
697 * (REQ-NET2-NET-005). */
698 if (s->sendq_len > 0)
699 *events |= POLLOUT;
700 /* Data the backend already holds raises no POLLIN. */
701 if (s->ops->pending && s->ops->pending(&s->conn))
702 *timeout_ms = 0;
703 return s->conn.sockfd;
704}
705
706/*- Advance rh's connection attempt, if any, without waiting
707 * (REQ-NET2-NET-001).
708 *
709 * @param rh a handle to parsed configuration.
710 -*/
711void radcli2_priv_sess_progress(rc_handle *rh)
712{
713 rc_session *s = sess_of(rh);
714
715 if (s != NULL && s->phase != SESS_IDLE)
716 attempt_step(s);
717}
718
719/*- Return the generation of rh's newest stream connection or connection
720 * attempt, to record what a request was sent on for
721 * radcli2_priv_sess_holds().
722 *
723 * @param rh a handle to parsed configuration.
724 * @return the generation, or 0 if rh's transport has no stream connection
725 * (UDP, DTLS).
726 -*/
727unsigned radcli2_priv_sess_gen(rc_handle *rh)
728{
729 rc_session *s = sess_of(rh);
730
731 if (s == NULL || s->ops->datagram)
732 return 0;
733 return s->gen;
734}
735
736/*- Report whether a request sent on generation gen is still in flight on
737 * the same healthy stream connection, over which RFC 6613 SS2.6.1 forbids
738 * sending it again (REQ-NET-NET-022).
739 *
740 * @param rh a handle to parsed configuration.
741 * @param gen the radcli2_priv_sess_gen() value recorded when it was sent.
742 * @return nonzero if it must not be sent again.
743 -*/
744int radcli2_priv_sess_holds(rc_handle *rh, unsigned gen)
745{
746 rc_session *s = sess_of(rh);
747
748 return s != NULL && gen != 0 && s->phase == SESS_IDLE && s->conn.init != 0 &&
749 s->conn.need_restart == 0 && s->conn.gen == gen;
750}
751
752/*- Return the socket of rh's TLS/DTLS session, if one is established --
753 * rc_tls_fd()'s implementation, also usable as a test for whether TLS or
754 * DTLS is in use.
755 *
756 * @param rh a handle to parsed configuration.
757 * @return the socket, or -1 if TLS/DTLS is not in use or no session is
758 * established.
759 -*/
760int radcli2_priv_tls_fd(rc_handle *rh)
761{
762 rc_session *s;
763
764 if (rh->so_type != RC_SOCKET_TLS && rh->so_type != RC_SOCKET_DTLS)
765 return -1;
766 s = rh->so.ptr;
767 if (s != NULL && s->conn.init != 0)
768 return s->conn.sockfd;
769 return -1;
770}
771
772/*- Return the time of the last packet sent or received on rh's connection
773 * (rc_sess_conn.last_msg). Used by lib/dae.c's radcli_ctx_get_poll() to
774 * compute a watchdog deadline (watchdog-interval).
775 *
776 * @param rh a handle to parsed configuration.
777 * @return the last-activity timestamp, or 0 if rh uses no session or none
778 * is established.
779 -*/
780time_t radcli2_priv_sess_last_msg(rc_handle *rh)
781{
782 rc_session *s = sess_of(rh);
783
784 if (s != NULL && s->conn.init != 0)
785 return s->conn.last_msg;
786 return 0;
787}
788
789/*- Return the time of the last packet actually *received* on rh's
790 * connection (rc_sess_conn.last_recv) -- unlike
791 * radcli2_priv_sess_last_msg(), never advanced by a send. Used by lib/
792 * dae.c's radcli2_priv_dae_send_watchdog() (REQ-WATCHDOG-NET-003) to
793 * detect a peer that has gone silent while the connection is still open.
794 *
795 * @param rh a handle to parsed configuration.
796 * @return the last-receive timestamp, or 0 if rh uses no session or none
797 * is established.
798 -*/
799time_t radcli2_priv_sess_last_recv(rc_handle *rh)
800{
801 rc_session *s = sess_of(rh);
802
803 if (s != NULL && s->conn.init != 0)
804 return s->conn.last_recv;
805 return 0;
806}
807
808/*- Treat rh's connection as failed, the same way an actual send/recv
809 * error does (need_restart), and begin reconnecting without waiting --
810 * used by lib/dae.c's radcli2_priv_dae_send_watchdog()
811 * (REQ-WATCHDOG-NET-003) when the peer is presumed dead from elapsed time
812 * alone.
813 *
814 * @param rh a handle to parsed configuration.
815 * @return 0 if a connection attempt is in progress, -1 if rh uses no
816 * session or the attempt could not start.
817 -*/
818int radcli2_priv_sess_force_reconnect(rc_handle *rh)
819{
820 rc_session *s = sess_of(rh);
821
822 if (s == NULL)
823 return -1;
824 s->conn.need_restart = 1;
825 return attempt_begin(s);
826}
827
828/*- Probe an established TLS/DTLS session's liveness and reconnect if it is
829 * dead. Once watchdog-interval has elapsed since the session's last
830 * activity, sends an RFC 5997 Status-Server watchdog
831 * (radcli2_priv_dae_send_watchdog(), REQ-WATCHDOG-NET-001) -- which itself
832 * already detects and reconnects from a peer gone silent for 2.5x that
833 * interval (REQ-WATCHDOG-NET-003), so this one call covers both probing and
834 * recovering. For a caller that wants a dead session detected proactively
835 * (e.g. from a periodic timer) rather than on the next request.
836 *
837 * @param rh a handle to parsed configuration.
838 * @return 0 on success or when TLS/DTLS is not in use, -1 if a
839 * known-broken session could not be re-established.
840 -*/
841int radcli2_priv_check_tls(rc_handle *rh)
842{
843 rc_session *s;
844 int interval;
845
846 if (rh->so_type != RC_SOCKET_TLS && rh->so_type != RC_SOCKET_DTLS)
847 return 0;
848
849 s = rh->so.ptr;
850
851 if (s->conn.init == 0)
852 return 0;
853
854 if (s->conn.need_restart != 0)
855 return restart_session(s) < 0 ? -1 : 0;
856
857 interval = rc_conf_int_id(rh, OPT_WATCHDOG_INTERVAL);
858 if (interval > 0 && time(0) - s->conn.last_msg >= interval)
859 radcli2_priv_dae_send_watchdog((radcli_ctx *)rh);
860
861 return 0;
862}
863
864/*- Establish rh's connection now, rather than waiting for the first
865 * request to do so -- used by radcli_dae_start() so enabling DAE makes
866 * the NAS reachable immediately, matching the UDP listener's own
867 * immediate bind().
868 *
869 * @param rh a handle to parsed configuration.
870 * @return 0 on success or if already connected and healthy, -1 if rh uses
871 * no session or connecting failed.
872 -*/
873int radcli2_priv_sess_ensure_connected(rc_handle *rh)
874{
875 rc_session *s = sess_of(rh);
876
877 if (s == NULL)
878 return -1;
879
880 if (s->conn.init != 0 && s->conn.need_restart == 0)
881 return 0; /* already connected and healthy */
882
883 return restart_session(s);
884}
885
886/*- Send whatever rh's connection has queued that can go out without
887 * waiting (REQ-NET2-NET-005).
888 *
889 * @param rh a handle to parsed configuration.
890 -*/
891void radcli2_priv_sess_flush(rc_handle *rh)
892{
893 rc_session *s = sess_of(rh);
894
895 if (s == NULL || s->conn.init == 0 || s->conn.need_restart != 0)
896 return;
897 while (s->sendq_len > 0 && sendq_try_head(s) == 1)
898 ;
899}
900
901/*- Send a record on rh's connection without ever waiting (REQ-NET2-NET-001,
902 * REQ-NET2-NET-005): sent at once when nothing is queued ahead of it,
903 * queued otherwise. A request's packet is queued by reference to its
904 * registry slot; with no copy free for anything else, a DAE reply
905 * displaces the oldest unstarted DAE reply (REQ-DAE-SEC-013) and a
906 * watchdog is skipped. Anything but a DAE reply on a failed connection
907 * begins reconnecting and is queued for the new connection; a DAE reply,
908 * which belongs to the failed connection, fails instead.
909 *
910 * @param rh a handle to parsed configuration.
911 * @param buf the record; a slot's packet must stay valid until sent or
912 * radcli2_priv_sess_unqueue().
913 * @param len buf's length in bytes.
914 * @param kind RADSEC_SEND_DAE_REPLY, RADSEC_SEND_REQUEST,
915 * RADSEC_SEND_RETRANSMIT or RADSEC_SEND_WATCHDOG.
916 * @param slot the registry slot whose packet buf is, or -1.
917 * @return the number of bytes sent if it went out at once, 0 if queued,
918 * -1 on a connection error or with no connection, -2 if skipped or
919 * dropped because no copy is free.
920 -*/
921int radcli2_priv_sess_send_queued(rc_handle *rh, const void *buf, size_t len, int kind, int slot)
922{
923 rc_session *s = sess_of(rh);
924 unsigned i;
925 int ret;
926
927 if (s == NULL || len > RC_MAX_PACKET_LEN)
928 return -1;
929
930 if (s->conn.init == 0 || s->conn.need_restart != 0) {
931 if (kind == RADSEC_SEND_DAE_REPLY || attempt_begin(s) < 0)
932 return -1;
933 } else {
934 radcli2_priv_sess_flush(rh);
935 if (s->conn.need_restart != 0)
936 return -1;
937 }
938
939 if (s->phase == SESS_IDLE && s->sendq_len == 0) {
940 ret = s->ops->send(&s->conn, buf, len);
941 if (ret == SESS_AGAIN) {
942 sendq_append(s, buf, len, kind, slot);
943 s->head_started = 1;
944 return 0;
945 }
946 if (ret < 0) {
947 s->conn.need_restart = 1;
948 return -1;
949 }
950 s->conn.last_msg = time(0);
951 return ret;
952 }
953
954 if (slot >= 0 || sendq_has_copy(s)) {
955 sendq_append(s, buf, len, kind, slot);
956 return 0;
957 }
958
959 if (kind == RADSEC_SEND_DAE_REPLY) {
960 for (i = s->head_started; i < s->sendq_len; i++) {
961 if (s->sendq[i].kind == RADSEC_SEND_DAE_REPLY)
962 break;
963 }
964 if (i < s->sendq_len) {
965 rc_log(LOG_WARNING, "%s: send queue full (%u), dropping the "
966 "oldest unsent dynamic-authorization reply", __func__,
967 (unsigned)SESS_SENDQ_SIZE);
968 sendq_remove(s, i);
969 sendq_append(s, buf, len, kind, slot);
970 return 0;
971 }
972 }
973
974 rc_log(LOG_WARNING, "%s: send queue full (%u), skipping this %s", __func__,
975 (unsigned)SESS_SENDQ_SIZE,
976 kind == RADSEC_SEND_WATCHDOG ? "watchdog" : "dynamic-authorization reply");
977 return -2;
978}
979
980/*- Report whether the packet of registry slot slot is queued on rh's
981 * connection, not yet sent.
982 *
983 * @param rh a handle to parsed configuration.
984 * @param slot the in-flight registry slot.
985 * @return nonzero if it is queued.
986 -*/
987int radcli2_priv_sess_queued(rc_handle *rh, int slot)
988{
989 rc_session *s = sess_of(rh);
990 unsigned i;
991
992 if (s == NULL)
993 return 0;
994 for (i = 0; i < s->sendq_len; i++) {
995 if (s->sendq[i].slot == slot)
996 return 1;
997 }
998 return 0;
999}
1000
1001/*- Stop rh's queue from referencing registry slot slot, which is being
1002 * vacated: its packet leaves the queue, unless the backend has started on
1003 * it, which must then be finished from the session's own copy
1004 * (REQ-NET2-NET-005).
1005 *
1006 * @param rh a handle to parsed configuration.
1007 * @param slot the in-flight registry slot.
1008 -*/
1009void radcli2_priv_sess_unqueue(rc_handle *rh, int slot)
1010{
1011 rc_session *s = sess_of(rh);
1012 unsigned i;
1013
1014 if (s == NULL)
1015 return;
1016 for (i = 0; i < s->sendq_len; i++) {
1017 if (s->sendq[i].slot != slot)
1018 continue;
1019 if (i == 0 && s->head_started) {
1020 memcpy(s->head_buf, s->sendq[0].data, s->sendq[0].len);
1021 s->sendq[0].data = s->head_buf;
1022 s->sendq[0].slot = -1;
1023 } else {
1024 sendq_remove(s, i);
1025 }
1026 return;
1027 }
1028}
1029
1030/*- Make one non-blocking attempt (never waits, unlike sess_recvfrom()) to
1031 * read one already-available RADIUS packet from rh's connection, for
1032 * lib/sendserver.c's radcli2_priv_sess_drain() to route. A partly received
1033 * packet is kept for the next call.
1034 *
1035 * @param rh a handle to parsed configuration.
1036 * @param buf destination for the packet.
1037 * @param cap buf's capacity in bytes.
1038 * @return the packet length (>0) on success, 0 if no whole packet is ready
1039 * or no connection is established, -1 on a connection error (also marks
1040 * the session for reconnection, same as sess_recvfrom()).
1041 -*/
1042int radcli2_priv_sess_try_recv(rc_handle *rh, uint8_t *buf, size_t cap)
1043{
1044 rc_session *s = sess_of(rh);
1045 int ret;
1046
1047 if (s == NULL)
1048 return -1;
1049 if (s->conn.init == 0 || s->conn.need_restart != 0)
1050 return 0; /* reconnecting is an ordinary send's job, not a read's */
1051
1052 ret = sess_recv_packet(s, buf, cap);
1053
1054 /* A warning alert is transient, not a reason to reconnect. */
1055 if (ret == SESS_AGAIN || ret == SESS_ALERT)
1056 return 0;
1057
1058 if (ret <= 0) {
1059 if (ret == 0)
1060 rc_log(LOG_ERR, "%s: connection closed by the server", __func__);
1061 s->conn.need_restart = 1;
1062 return -1;
1063 }
1064
1065 s->conn.last_msg = time(0);
1066 s->conn.last_recv = s->conn.last_msg;
1067 return ret;
1068}
1069
1070/*- Report whether rh's connection holds already-received data that no read
1071 * has returned yet -- data no poll() on the socket will signal.
1072 *
1073 * @param rh a handle to parsed configuration.
1074 * @return nonzero if a read would return data without waiting.
1075 -*/
1076int radcli2_priv_sess_pending(rc_handle *rh)
1077{
1078 rc_session *s = sess_of(rh);
1079
1080 if (s == NULL || s->conn.init == 0 || s->conn.need_restart != 0 ||
1081 s->ops->pending == NULL)
1082 return 0;
1083 return s->ops->pending(&s->conn);
1084}
1085
1086/*- Close rh's connection, if any, and free its session.
1087 *
1088 * @param rh the configuration handle.
1089 -*/
1090void radcli2_priv_sess_deinit(rc_handle *rh)
1091{
1092 rc_session *s = sess_of(rh);
1093 char *ns = NULL;
1094 int ns_def_hdl = 0;
1095
1096 if (s == NULL)
1097 return;
1098
1099 ns = rc_conf_str_id(rh, OPT_NAMESPACE);
1100 if (ns != NULL && rc_set_netns(ns, &ns_def_hdl) == -1) {
1101 rc_log(LOG_ERR, "%s: namespace %s set failed", __func__, ns);
1102 return;
1103 }
1104 if (s->phase != SESS_IDLE)
1105 conn_close(s, &s->next);
1106 conn_close(s, &s->conn);
1107 if (ns != NULL && rc_reset_netns(&ns_def_hdl) == -1)
1108 rc_log(LOG_ERR, "%s: namespace %s reset failed", __func__, ns);
1109
1110 if (s->ops->free)
1111 s->ops->free(s);
1112 pthread_mutex_destroy(&s->lock);
1113 free(s);
1114 rh->so.ptr = NULL;
1115}
1116
1117/*- Give rh a session to its single authserver over the backend ops,
1118 * connected on first use. rh->so_type must already be set; on success
1119 * the session owns backend.
1120 *
1121 * @param rh a handle to parsed configuration.
1122 * @param ops the transport backend.
1123 * @param backend the backend's per-ctx state, released by ops->free.
1124 * @return 0 on success, -1 on failure.
1125 -*/
1126int radcli2_priv_sess_init(rc_handle *rh, const rc_sess_ops *ops, void *backend)
1127{
1128 SERVER *authservers;
1129 rc_session *s;
1130
1131 authservers = rc_conf_srv_id(rh, OPT_AUTHSERVER);
1132 if (authservers == NULL || authservers->max == 0) {
1133 rc_log(LOG_ERR, "%s: cannot find authserver", __func__);
1134 return -1;
1135 }
1136 if (authservers->max > 1) {
1137 rc_log(LOG_ERR, "%s: too many auth servers for TCP/TLS/DTLS; only one is allowed",
1138 __func__);
1139 return -1;
1140 }
1141
1142 s = calloc(1, sizeof(*s));
1143 if (s == NULL)
1144 return -1;
1145
1146 s->ops = ops;
1147 s->backend = backend;
1148 s->rh = rh;
1149 strlcpy(s->hostname, authservers->name[0], sizeof(s->hostname));
1150 s->port = authservers->port[0];
1151 rc_own_bind_addr(rh, &s->our_sockaddr);
1152 pthread_mutex_init(&s->lock, NULL);
1153 /* calloc() left 0, a valid descriptor: no connection exists yet
1154 * (REQ-NET-NET-019). */
1155 s->conn.sockfd = -1;
1156 /* Connect on first use (REQ-NET-NET-005). */
1157 s->conn.need_restart = 1;
1158
1159 rh->so.ptr = s;
1160 rh->so.get_fd = sess_get_fd;
1161 rh->so.get_active_fd = sess_get_active_fd;
1162 rh->so.sendto = sess_sendto;
1163 rh->so.recvfrom = sess_recvfrom;
1164 rh->so.lock = sess_lock;
1165 rh->so.unlock = sess_unlock;
1166 return 0;
1167}
1168
1169/*- rc_sess_ops.send for plain TCP: write all of buf, resuming after a
1170 * short write from where the previous call stopped.
1171 -*/
1172static int tcp_send(rc_sess_conn *c, const void *buf, size_t len)
1173{
1174 while (c->wpos < len) {
1175 ssize_t n = send(c->sockfd, (const uint8_t *)buf + c->wpos, len - c->wpos, 0);
1176
1177 if (n < 0) {
1178 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1179 return SESS_AGAIN;
1180 rc_log(LOG_ERR, "%s: send: %s", __func__, strerror(errno));
1181 return -1;
1182 }
1183 c->wpos += (size_t)n;
1184 }
1185 c->wpos = 0;
1186 return (int)len;
1187}
1188
1189/*- rc_sess_ops.recv for plain TCP: a thin recv(2) wrapper. -*/
1190static int tcp_recv(rc_sess_conn *c, void *buf, size_t len)
1191{
1192 ssize_t n = recv(c->sockfd, buf, len, 0);
1193
1194 if (n < 0) {
1195 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1196 return SESS_AGAIN;
1197 rc_log(LOG_ERR, "%s: recv: %s", __func__, strerror(errno));
1198 return -1;
1199 }
1200 return (int)n;
1201}
1202
1203static const rc_sess_ops tcp_ops = {
1204 .send = tcp_send,
1205 .recv = tcp_recv,
1206};
1207
1208/*- Select the plain TCP transport: one persistent connection to the
1209 * single authserver, carrying every request (RFC 6613).
1210 *
1211 * @param rh a handle to parsed configuration.
1212 * @return 0 on success, -1 on failure.
1213 -*/
1214int radcli2_priv_sess_init_tcp(rc_handle *rh)
1215{
1216 memset(&rh->so, 0, sizeof(rh->so));
1217 rh->so_type = RC_SOCKET_TCP;
1218 if (radcli2_priv_sess_init(rh, &tcp_ops, NULL) < 0)
1219 return -1;
1220 ((rc_session *)rh->so.ptr)->bind_local = 1;
1221 return 0;
1222}