4 * Copyright (C) 1997-1999 Kunihiro Ishiguro
5 * Copyright (C) 2015-2018 Cumulus Networks, Inc.
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the Free
10 * Software Foundation; either version 2 of the License, or (at your option)
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18 * You should have received a copy of the GNU General Public License along
19 * with this program; see the file COPYING; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 /* clang-format off */
26 #include <errno.h> /* for errno */
27 #include <netinet/in.h> /* for sockaddr_in */
28 #include <stdint.h> /* for uint8_t */
29 #include <stdio.h> /* for snprintf */
30 #include <sys/socket.h> /* for sockaddr_storage, AF_UNIX, accept... */
31 #include <sys/stat.h> /* for umask, mode_t */
32 #include <sys/un.h> /* for sockaddr_un */
33 #include <time.h> /* for NULL, tm, gmtime, time_t */
34 #include <unistd.h> /* for close, unlink, ssize_t */
36 #include "lib/buffer.h" /* for BUFFER_EMPTY, BUFFER_ERROR, BUFFE... */
37 #include "lib/command.h" /* for vty, install_element, CMD_SUCCESS... */
38 #include "lib/hook.h" /* for DEFINE_HOOK, DEFINE_KOOH, hook_call */
39 #include "lib/linklist.h" /* for ALL_LIST_ELEMENTS_RO, ALL_LIST_EL... */
40 #include "lib/libfrr.h" /* for frr_zclient_addr */
41 #include "lib/log.h" /* for zlog_warn, zlog_debug, safe_strerror */
42 #include "lib/memory.h" /* for MTYPE_TMP, XCALLOC, XFREE */
43 #include "lib/monotime.h" /* for monotime, ONE_DAY_SECOND, ONE_WEE... */
44 #include "lib/network.h" /* for set_nonblocking */
45 #include "lib/privs.h" /* for zebra_privs_t, ZPRIVS_LOWER, ZPRI... */
46 #include "lib/route_types.h" /* for ZEBRA_ROUTE_MAX */
47 #include "lib/sockopt.h" /* for setsockopt_so_recvbuf, setsockopt... */
48 #include "lib/sockunion.h" /* for sockopt_reuseaddr, sockopt_reuseport */
49 #include "lib/stream.h" /* for STREAM_SIZE, stream (ptr only), ... */
50 #include "lib/thread.h" /* for thread (ptr only), THREAD_ARG, ... */
51 #include "lib/vrf.h" /* for vrf_info_lookup, VRF_DEFAULT */
52 #include "lib/vty.h" /* for vty_out, vty (ptr only) */
53 #include "lib/zassert.h" /* for assert */
54 #include "lib/zclient.h" /* for zmsghdr, ZEBRA_HEADER_SIZE, ZEBRA... */
55 #include "lib/frr_pthread.h" /* for frr_pthread_new, frr_pthread_stop... */
56 #include "lib/frratomic.h" /* for atomic_load_explicit, atomic_stor... */
57 #include "lib/lib_errors.h" /* for generic ferr ids */
58 #include "lib/printfrr.h" /* for string functions */
60 #include "zebra/debug.h" /* for various debugging macros */
61 #include "zebra/rib.h" /* for rib_score_proto */
62 #include "zebra/zapi_msg.h" /* for zserv_handle_commands */
63 #include "zebra/zebra_vrf.h" /* for zebra_vrf_lookup_by_id, zvrf */
64 #include "zebra/zserv.h" /* for zserv */
65 #include "zebra/zebra_router.h"
66 #include "zebra/zebra_errors.h" /* for error messages */
70 extern struct zebra_privs_t zserv_privs
;
72 /* The listener socket for clients connecting to us */
75 /* The lock that protects access to zapi client objects */
76 static pthread_mutex_t client_mutex
;
78 static struct zserv
*find_client_internal(uint8_t proto
,
79 unsigned short instance
,
84 * Client thread events.
86 * These are used almost exclusively by client threads to drive their own event
87 * loops. The only exception is in zserv_client_create(), which pushes an
88 * initial ZSERV_CLIENT_READ event to start the API handler loop.
90 enum zserv_client_event
{
91 /* Schedule a socket read */
93 /* Schedule a buffer write */
100 * These are used by client threads to notify the main thread about various
101 * events and to make processing requests.
104 /* Schedule listen job on Zebra API socket */
106 /* The calling client has packets on its input buffer */
107 ZSERV_PROCESS_MESSAGES
,
108 /* The calling client wishes to be killed */
109 ZSERV_HANDLE_CLIENT_FAIL
,
113 * Zebra server event driver for all client threads.
115 * This is essentially a wrapper around thread_add_event() that centralizes
116 * those scheduling calls into one place.
118 * All calls to this function schedule an event on the pthread running the
122 * the client in question, and thread target
125 * the event to notify them about
127 static void zserv_client_event(struct zserv
*client
,
128 enum zserv_client_event event
);
131 * Zebra server event driver for the main thread.
133 * This is essentially a wrapper around thread_add_event() that centralizes
134 * those scheduling calls into one place.
136 * All calls to this function schedule an event on Zebra's main pthread.
139 * the client in question
142 * the event to notify the main thread about
144 static void zserv_event(struct zserv
*client
, enum zserv_event event
);
147 /* Client thread lifecycle -------------------------------------------------- */
150 * Log zapi message to zlog.
161 void zserv_log_message(const char *errmsg
, struct stream
*msg
,
164 zlog_debug("Rx'd ZAPI message");
166 zlog_debug("%s", errmsg
);
168 zlog_debug(" Length: %d", hdr
->length
);
169 zlog_debug("Command: %s", zserv_command_string(hdr
->command
));
170 zlog_debug(" VRF: %u", hdr
->vrf_id
);
176 * Gracefully shut down a client connection.
178 * Cancel any pending tasks for the client's thread. Then schedule a task on
179 * the main thread to shut down the calling thread.
181 * It is not safe to close the client socket in this function. The socket is
182 * owned by the main thread.
184 * Must be called from the client pthread, never the main thread.
186 static void zserv_client_fail(struct zserv
*client
)
188 flog_warn(EC_ZEBRA_CLIENT_IO_ERROR
,
189 "Client '%s' encountered an error and is shutting down.",
190 zebra_route_string(client
->proto
));
192 atomic_store_explicit(&client
->pthread
->running
, false,
193 memory_order_relaxed
);
195 THREAD_OFF(client
->t_read
);
196 THREAD_OFF(client
->t_write
);
197 zserv_event(client
, ZSERV_HANDLE_CLIENT_FAIL
);
201 * Write all pending messages to client socket.
203 * This function first attempts to flush any buffered data. If unsuccessful,
204 * the function reschedules itself and returns. If successful, it pops all
205 * available messages from the output queue and continues to write data
206 * directly to the socket until the socket would block. If the socket never
207 * blocks and all data is written, the function returns without rescheduling
208 * itself. If the socket ends up throwing EWOULDBLOCK, the remaining data is
209 * buffered and the function reschedules itself.
211 * The utility of the buffer is that it allows us to vastly reduce lock
212 * contention by allowing us to pop *all* messages off the output queue at once
213 * instead of locking and unlocking each time we want to pop a single message
214 * off the queue. The same thing could arguably be accomplished faster by
215 * allowing the main thread to write directly into the buffer instead of
216 * enqueuing packets onto an intermediary queue, but the intermediary queue
217 * allows us to expose information about input and output queues to the user in
218 * terms of number of packets rather than size of data.
220 static int zserv_write(struct thread
*thread
)
222 struct zserv
*client
= THREAD_ARG(thread
);
225 struct stream_fifo
*cache
;
227 /* If we have any data pending, try to flush it first */
228 switch (buffer_flush_all(client
->wb
, client
->sock
)) {
232 atomic_store_explicit(&client
->last_write_time
,
233 (uint32_t)monotime(NULL
),
234 memory_order_relaxed
);
235 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
241 cache
= stream_fifo_new();
243 frr_with_mutex(&client
->obuf_mtx
) {
244 while (stream_fifo_head(client
->obuf_fifo
))
245 stream_fifo_push(cache
,
246 stream_fifo_pop(client
->obuf_fifo
));
251 stream_set_getp(msg
, 0);
252 wcmd
= stream_getw_from(msg
, ZAPI_HEADER_CMD_LOCATION
);
255 while (stream_fifo_head(cache
)) {
256 msg
= stream_fifo_pop(cache
);
257 buffer_put(client
->wb
, STREAM_DATA(msg
), stream_get_endp(msg
));
261 stream_fifo_free(cache
);
263 /* If we have any data pending, try to flush it first */
264 switch (buffer_flush_all(client
->wb
, client
->sock
)) {
268 atomic_store_explicit(&client
->last_write_time
,
269 (uint32_t)monotime(NULL
),
270 memory_order_relaxed
);
271 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
277 atomic_store_explicit(&client
->last_write_cmd
, wcmd
,
278 memory_order_relaxed
);
280 atomic_store_explicit(&client
->last_write_time
,
281 (uint32_t)monotime(NULL
), memory_order_relaxed
);
286 flog_warn(EC_ZEBRA_CLIENT_WRITE_FAILED
,
287 "%s: could not write to %s [fd = %d], closing.", __func__
,
288 zebra_route_string(client
->proto
), client
->sock
);
289 zserv_client_fail(client
);
294 * Read and process data from a client socket.
296 * The responsibilities here are to read raw data from the client socket,
297 * validate the header, encapsulate it into a single stream object, push it
298 * onto the input queue and then notify the main thread that there is new data
301 * This function first looks for any data in the client structure's working
302 * input buffer. If data is present, it is assumed that reading stopped in a
303 * previous invocation of this task and needs to be resumed to finish a message.
304 * Otherwise, the socket data stream is assumed to be at the beginning of a new
305 * ZAPI message (specifically at the header). The header is read and validated.
306 * If the header passed validation then the length field found in the header is
307 * used to compute the total length of the message. That much data is read (but
308 * not inspected), appended to the header, placed into a stream and pushed onto
309 * the client's input queue. A task is then scheduled on the main thread to
310 * process the client's input queue. Finally, if all of this was successful,
311 * this task reschedules itself.
313 * Any failure in any of these actions is handled by terminating the client.
315 static int zserv_read(struct thread
*thread
)
317 struct zserv
*client
= THREAD_ARG(thread
);
320 struct stream_fifo
*cache
;
326 p2p_orig
= atomic_load_explicit(&zrouter
.packets_to_process
,
327 memory_order_relaxed
);
328 cache
= stream_fifo_new();
330 sock
= THREAD_FD(thread
);
337 already
= stream_get_endp(client
->ibuf_work
);
339 /* Read length and command (if we don't have it already). */
340 if (already
< ZEBRA_HEADER_SIZE
) {
341 nb
= stream_read_try(client
->ibuf_work
, sock
,
342 ZEBRA_HEADER_SIZE
- already
);
343 if ((nb
== 0 || nb
== -1)) {
344 if (IS_ZEBRA_DEBUG_EVENT
)
345 zlog_debug("connection closed socket [%d]",
349 if (nb
!= (ssize_t
)(ZEBRA_HEADER_SIZE
- already
)) {
350 /* Try again later. */
353 already
= ZEBRA_HEADER_SIZE
;
356 /* Reset to read from the beginning of the incoming packet. */
357 stream_set_getp(client
->ibuf_work
, 0);
359 /* Fetch header values */
360 hdrvalid
= zapi_parse_header(client
->ibuf_work
, &hdr
);
363 snprintf(errmsg
, sizeof(errmsg
),
364 "%s: Message has corrupt header", __func__
);
365 zserv_log_message(errmsg
, client
->ibuf_work
, NULL
);
369 /* Validate header */
370 if (hdr
.marker
!= ZEBRA_HEADER_MARKER
371 || hdr
.version
!= ZSERV_VERSION
) {
373 errmsg
, sizeof(errmsg
),
374 "Message has corrupt header\n%s: socket %d version mismatch, marker %d, version %d",
375 __func__
, sock
, hdr
.marker
, hdr
.version
);
376 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
379 if (hdr
.length
< ZEBRA_HEADER_SIZE
) {
381 errmsg
, sizeof(errmsg
),
382 "Message has corrupt header\n%s: socket %d message length %u is less than header size %d",
383 __func__
, sock
, hdr
.length
, ZEBRA_HEADER_SIZE
);
384 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
387 if (hdr
.length
> STREAM_SIZE(client
->ibuf_work
)) {
389 errmsg
, sizeof(errmsg
),
390 "Message has corrupt header\n%s: socket %d message length %u exceeds buffer size %lu",
391 __func__
, sock
, hdr
.length
,
392 (unsigned long)STREAM_SIZE(client
->ibuf_work
));
393 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
397 /* Read rest of data. */
398 if (already
< hdr
.length
) {
399 nb
= stream_read_try(client
->ibuf_work
, sock
,
400 hdr
.length
- already
);
401 if ((nb
== 0 || nb
== -1)) {
402 if (IS_ZEBRA_DEBUG_EVENT
)
404 "connection closed [%d] when reading zebra data",
408 if (nb
!= (ssize_t
)(hdr
.length
- already
)) {
409 /* Try again later. */
414 /* Debug packet information. */
415 if (IS_ZEBRA_DEBUG_PACKET
)
416 zlog_debug("zebra message[%s:%u:%u] comes from socket [%d]",
417 zserv_command_string(hdr
.command
),
418 hdr
.vrf_id
, hdr
.length
,
421 stream_set_getp(client
->ibuf_work
, 0);
422 struct stream
*msg
= stream_dup(client
->ibuf_work
);
424 stream_fifo_push(cache
, msg
);
425 stream_reset(client
->ibuf_work
);
429 if (p2p
< p2p_orig
) {
430 /* update session statistics */
431 atomic_store_explicit(&client
->last_read_time
, monotime(NULL
),
432 memory_order_relaxed
);
433 atomic_store_explicit(&client
->last_read_cmd
, hdr
.command
,
434 memory_order_relaxed
);
436 /* publish read packets on client's input queue */
437 frr_with_mutex(&client
->ibuf_mtx
) {
439 stream_fifo_push(client
->ibuf_fifo
,
440 stream_fifo_pop(cache
));
443 /* Schedule job to process those packets */
444 zserv_event(client
, ZSERV_PROCESS_MESSAGES
);
448 if (IS_ZEBRA_DEBUG_PACKET
)
449 zlog_debug("Read %d packets from client: %s", p2p_orig
- p2p
,
450 zebra_route_string(client
->proto
));
452 /* Reschedule ourselves */
453 zserv_client_event(client
, ZSERV_CLIENT_READ
);
455 stream_fifo_free(cache
);
460 stream_fifo_free(cache
);
461 zserv_client_fail(client
);
465 static void zserv_client_event(struct zserv
*client
,
466 enum zserv_client_event event
)
469 case ZSERV_CLIENT_READ
:
470 thread_add_read(client
->pthread
->master
, zserv_read
, client
,
471 client
->sock
, &client
->t_read
);
473 case ZSERV_CLIENT_WRITE
:
474 thread_add_write(client
->pthread
->master
, zserv_write
, client
,
475 client
->sock
, &client
->t_write
);
480 /* Main thread lifecycle ---------------------------------------------------- */
483 * Read and process messages from a client.
485 * This task runs on the main pthread. It is scheduled by client pthreads when
486 * they have new messages available on their input queues. The client is passed
487 * as the task argument.
489 * Each message is popped off the client's input queue and the action associated
490 * with the message is executed. This proceeds until there are no more messages,
491 * an error occurs, or the processing limit is reached.
493 * The client's I/O thread can push at most zrouter.packets_to_process messages
494 * onto the input buffer before notifying us there are packets to read. As long
495 * as we always process zrouter.packets_to_process messages here, then we can
496 * rely on the read thread to handle queuing this task enough times to process
497 * everything on the input queue.
499 static int zserv_process_messages(struct thread
*thread
)
501 struct zserv
*client
= THREAD_ARG(thread
);
503 struct stream_fifo
*cache
= stream_fifo_new();
504 uint32_t p2p
= zrouter
.packets_to_process
;
505 bool need_resched
= false;
507 frr_with_mutex(&client
->ibuf_mtx
) {
509 for (i
= 0; i
< p2p
&& stream_fifo_head(client
->ibuf_fifo
);
511 msg
= stream_fifo_pop(client
->ibuf_fifo
);
512 stream_fifo_push(cache
, msg
);
517 /* Need to reschedule processing work if there are still
518 * packets in the fifo.
520 if (stream_fifo_head(client
->ibuf_fifo
))
524 /* Process the batch of messages */
525 if (stream_fifo_head(cache
))
526 zserv_handle_commands(client
, cache
);
528 stream_fifo_free(cache
);
530 /* Reschedule ourselves if necessary */
532 zserv_event(client
, ZSERV_PROCESS_MESSAGES
);
537 int zserv_send_message(struct zserv
*client
, struct stream
*msg
)
539 frr_with_mutex(&client
->obuf_mtx
) {
540 stream_fifo_push(client
->obuf_fifo
, msg
);
543 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
549 * Send a batch of messages to a connected Zebra API client.
551 int zserv_send_batch(struct zserv
*client
, struct stream_fifo
*fifo
)
555 frr_with_mutex(&client
->obuf_mtx
) {
556 msg
= stream_fifo_pop(fifo
);
558 stream_fifo_push(client
->obuf_fifo
, msg
);
559 msg
= stream_fifo_pop(fifo
);
563 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
568 /* Hooks for client connect / disconnect */
569 DEFINE_HOOK(zserv_client_connect
, (struct zserv
*client
), (client
));
570 DEFINE_KOOH(zserv_client_close
, (struct zserv
*client
), (client
));
573 * Deinitialize zebra client.
575 * - Deregister and deinitialize related internal resources
576 * - Gracefully close socket
577 * - Free associated resources
578 * - Free client structure
580 * This does *not* take any action on the struct thread * fields. These are
581 * managed by the owning pthread and any tasks associated with them must have
582 * been stopped prior to invoking this function.
584 static void zserv_client_free(struct zserv
*client
)
589 hook_call(zserv_client_close
, client
);
591 /* Close file descriptor. */
593 unsigned long nroutes
;
598 if (DYNAMIC_CLIENT_GR_DISABLED(client
)) {
599 nroutes
= rib_score_proto(client
->proto
,
602 "client %d disconnected %lu %s routes removed from the rib",
603 client
->sock
, nroutes
,
604 zebra_route_string(client
->proto
));
606 /* Not worrying about instance for now */
607 nnhgs
= zebra_nhg_score_proto(client
->proto
);
609 "client %d disconnected %lu %s nhgs removed from the rib",
611 zebra_route_string(client
->proto
));
616 /* Free stream buffers. */
617 if (client
->ibuf_work
)
618 stream_free(client
->ibuf_work
);
619 if (client
->obuf_work
)
620 stream_free(client
->obuf_work
);
621 if (client
->ibuf_fifo
)
622 stream_fifo_free(client
->ibuf_fifo
);
623 if (client
->obuf_fifo
)
624 stream_fifo_free(client
->obuf_fifo
);
626 buffer_free(client
->wb
);
628 /* Free buffer mutexes */
629 pthread_mutex_destroy(&client
->obuf_mtx
);
630 pthread_mutex_destroy(&client
->ibuf_mtx
);
633 for (afi_t afi
= AFI_IP
; afi
< AFI_MAX
; afi
++) {
634 for (int i
= 0; i
< ZEBRA_ROUTE_MAX
; i
++) {
635 vrf_bitmap_free(client
->redist
[afi
][i
]);
636 redist_del_all_instances(&client
->mi_redist
[afi
][i
]);
639 vrf_bitmap_free(client
->redist_default
[afi
]);
640 vrf_bitmap_free(client
->ridinfo
[afi
]);
641 vrf_bitmap_free(client
->nhrp_neighinfo
[afi
]);
645 * If any instance are graceful restart enabled,
646 * client is not deleted
648 if (DYNAMIC_CLIENT_GR_DISABLED(client
)) {
649 if (IS_ZEBRA_DEBUG_EVENT
)
650 zlog_debug("%s: Deleting client %s", __func__
,
651 zebra_route_string(client
->proto
));
652 XFREE(MTYPE_TMP
, client
);
654 /* Handle cases where client has GR instance. */
655 if (IS_ZEBRA_DEBUG_EVENT
)
656 zlog_debug("%s: client %s restart enabled", __func__
,
657 zebra_route_string(client
->proto
));
658 if (zebra_gr_client_disconnect(client
) < 0)
660 "%s: GR enabled but could not handle disconnect event",
665 void zserv_close_client(struct zserv
*client
)
669 if (client
->pthread
) {
670 /* synchronously stop and join pthread */
671 frr_pthread_stop(client
->pthread
, NULL
);
673 if (IS_ZEBRA_DEBUG_EVENT
)
674 zlog_debug("Closing client '%s'",
675 zebra_route_string(client
->proto
));
677 thread_cancel_event(zrouter
.master
, client
);
678 THREAD_OFF(client
->t_cleanup
);
679 THREAD_OFF(client
->t_process
);
681 /* destroy pthread */
682 frr_pthread_destroy(client
->pthread
);
683 client
->pthread
= NULL
;
687 * Final check in case the client struct is in use in another
688 * pthread: if not in-use, continue and free the client
690 frr_with_mutex(&client_mutex
) {
691 if (client
->busy_count
<= 0) {
692 /* remove from client list */
693 listnode_delete(zrouter
.client_list
, client
);
696 * The client session object may be in use, although
697 * the associated pthread is gone. Defer final
700 client
->is_closed
= true;
707 zserv_client_free(client
);
711 * This task is scheduled by a ZAPI client pthread on the main pthread when it
712 * wants to stop itself. When this executes, the client connection should
713 * already have been closed and the thread will most likely have died, but its
714 * resources still need to be cleaned up.
716 static int zserv_handle_client_fail(struct thread
*thread
)
718 struct zserv
*client
= THREAD_ARG(thread
);
720 zserv_close_client(client
);
725 * Create a new client.
727 * This is called when a new connection is accept()'d on the ZAPI socket. It
728 * initializes new client structure, notifies any subscribers of the connection
729 * event and spawns the client's thread.
732 * client's socket file descriptor
734 static struct zserv
*zserv_client_create(int sock
)
736 struct zserv
*client
;
738 MAX(ZEBRA_MAX_PACKET_SIZ
, sizeof(struct zapi_route
));
742 client
= XCALLOC(MTYPE_TMP
, sizeof(struct zserv
));
744 /* Make client input/output buffer. */
746 client
->ibuf_fifo
= stream_fifo_new();
747 client
->obuf_fifo
= stream_fifo_new();
748 client
->ibuf_work
= stream_new(stream_size
);
749 client
->obuf_work
= stream_new(stream_size
);
750 pthread_mutex_init(&client
->ibuf_mtx
, NULL
);
751 pthread_mutex_init(&client
->obuf_mtx
, NULL
);
752 client
->wb
= buffer_new(0);
753 TAILQ_INIT(&(client
->gr_info_queue
));
755 atomic_store_explicit(&client
->connect_time
, (uint32_t) monotime(NULL
),
756 memory_order_relaxed
);
758 /* Initialize flags */
759 for (afi
= AFI_IP
; afi
< AFI_MAX
; afi
++) {
760 for (i
= 0; i
< ZEBRA_ROUTE_MAX
; i
++)
761 client
->redist
[afi
][i
] = vrf_bitmap_init();
762 client
->redist_default
[afi
] = vrf_bitmap_init();
763 client
->ridinfo
[afi
] = vrf_bitmap_init();
764 client
->nhrp_neighinfo
[afi
] = vrf_bitmap_init();
767 /* Add this client to linked list. */
768 frr_with_mutex(&client_mutex
) {
769 listnode_add(zrouter
.client_list
, client
);
772 struct frr_pthread_attr zclient_pthr_attrs
= {
773 .start
= frr_pthread_attr_default
.start
,
774 .stop
= frr_pthread_attr_default
.stop
777 frr_pthread_new(&zclient_pthr_attrs
, "Zebra API client thread",
780 /* start read loop */
781 zserv_client_event(client
, ZSERV_CLIENT_READ
);
784 hook_call(zserv_client_connect
, client
);
787 frr_pthread_run(client
->pthread
, NULL
);
793 * Retrieve a client object by the complete tuple of
794 * {protocol, instance, session}. This version supports use
795 * from a different pthread: the object will be returned marked
796 * in-use. The caller *must* release the client object with the
797 * release_client() api, to ensure that the in-use marker is cleared properly.
799 struct zserv
*zserv_acquire_client(uint8_t proto
, unsigned short instance
,
802 struct zserv
*client
= NULL
;
804 frr_with_mutex(&client_mutex
) {
805 client
= find_client_internal(proto
, instance
, session_id
);
807 /* Don't return a dead/closed client object */
808 if (client
->is_closed
)
811 client
->busy_count
++;
819 * Release a client object that was acquired with the acquire_client() api.
820 * After this has been called, the caller must not use the client pointer -
821 * it may be freed if the client has closed.
823 void zserv_release_client(struct zserv
*client
)
826 * Once we've decremented the client object's refcount, it's possible
827 * for it to be deleted as soon as we release the lock, so we won't
828 * touch the object again.
830 frr_with_mutex(&client_mutex
) {
831 client
->busy_count
--;
833 if (client
->busy_count
<= 0) {
835 * No more users of the client object. If the client
836 * session is closed, schedule cleanup on the zebra
839 if (client
->is_closed
)
840 thread_add_event(zrouter
.master
,
841 zserv_handle_client_fail
,
842 client
, 0, &client
->t_cleanup
);
847 * Cleanup must take place on the zebra main pthread, so we've
848 * scheduled an event.
853 * Accept socket connection.
855 static int zserv_accept(struct thread
*thread
)
859 struct sockaddr_in client
;
862 accept_sock
= THREAD_FD(thread
);
864 /* Reregister myself. */
865 zserv_event(NULL
, ZSERV_ACCEPT
);
867 len
= sizeof(struct sockaddr_in
);
868 client_sock
= accept(accept_sock
, (struct sockaddr
*)&client
, &len
);
870 if (client_sock
< 0) {
871 flog_err_sys(EC_LIB_SOCKET
, "Can't accept zebra socket: %s",
872 safe_strerror(errno
));
876 /* Make client socket non-blocking. */
877 set_nonblocking(client_sock
);
879 /* Create new zebra client. */
880 zserv_client_create(client_sock
);
885 void zserv_close(void)
888 * On shutdown, let's close the socket down
889 * so that long running processes of killing the
890 * routing table doesn't leave us in a bad
891 * state where a client tries to reconnect
896 /* Free client list's mutex */
897 pthread_mutex_destroy(&client_mutex
);
900 void zserv_start(char *path
)
904 struct sockaddr_storage sa
;
907 if (!frr_zclient_addr(&sa
, &sa_len
, path
))
908 /* should be caught in zebra main() */
912 old_mask
= umask(0077);
914 /* Make UNIX domain socket. */
915 zsock
= socket(sa
.ss_family
, SOCK_STREAM
, 0);
917 flog_err_sys(EC_LIB_SOCKET
, "Can't create zserv socket: %s",
918 safe_strerror(errno
));
922 if (sa
.ss_family
!= AF_UNIX
) {
923 sockopt_reuseaddr(zsock
);
924 sockopt_reuseport(zsock
);
926 struct sockaddr_un
*suna
= (struct sockaddr_un
*)&sa
;
927 if (suna
->sun_path
[0])
928 unlink(suna
->sun_path
);
931 setsockopt_so_recvbuf(zsock
, 1048576);
932 setsockopt_so_sendbuf(zsock
, 1048576);
934 frr_with_privs((sa
.ss_family
!= AF_UNIX
) ? &zserv_privs
: NULL
) {
935 ret
= bind(zsock
, (struct sockaddr
*)&sa
, sa_len
);
938 flog_err_sys(EC_LIB_SOCKET
, "Can't bind zserv socket on %s: %s",
939 path
, safe_strerror(errno
));
945 ret
= listen(zsock
, 5);
947 flog_err_sys(EC_LIB_SOCKET
,
948 "Can't listen to zserv socket %s: %s", path
,
949 safe_strerror(errno
));
957 zserv_event(NULL
, ZSERV_ACCEPT
);
960 void zserv_event(struct zserv
*client
, enum zserv_event event
)
964 thread_add_read(zrouter
.master
, zserv_accept
, NULL
, zsock
,
967 case ZSERV_PROCESS_MESSAGES
:
968 thread_add_event(zrouter
.master
, zserv_process_messages
, client
,
969 0, &client
->t_process
);
971 case ZSERV_HANDLE_CLIENT_FAIL
:
972 thread_add_event(zrouter
.master
, zserv_handle_client_fail
,
973 client
, 0, &client
->t_cleanup
);
978 /* General purpose ---------------------------------------------------------- */
980 #define ZEBRA_TIME_BUF 32
981 static char *zserv_time_buf(time_t *time1
, char *buf
, int buflen
)
986 assert(buflen
>= ZEBRA_TIME_BUF
);
987 assert(time1
!= NULL
);
990 snprintf(buf
, buflen
, "never ");
994 now
= monotime(NULL
);
997 frrtime_to_interval(now
, buf
, buflen
);
1002 /* Display client info details */
1003 static void zebra_show_client_detail(struct vty
*vty
, struct zserv
*client
)
1005 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1006 char wbuf
[ZEBRA_TIME_BUF
], nhbuf
[ZEBRA_TIME_BUF
], mbuf
[ZEBRA_TIME_BUF
];
1007 time_t connect_time
, last_read_time
, last_write_time
;
1008 uint32_t last_read_cmd
, last_write_cmd
;
1009 struct client_gr_info
*info
= NULL
;
1011 vty_out(vty
, "Client: %s", zebra_route_string(client
->proto
));
1012 if (client
->instance
)
1013 vty_out(vty
, " Instance: %u", client
->instance
);
1014 if (client
->session_id
)
1015 vty_out(vty
, " [%u]", client
->session_id
);
1018 vty_out(vty
, "------------------------ \n");
1019 vty_out(vty
, "FD: %d \n", client
->sock
);
1021 connect_time
= (time_t) atomic_load_explicit(&client
->connect_time
,
1022 memory_order_relaxed
);
1024 vty_out(vty
, "Connect Time: %s \n",
1025 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
));
1026 if (client
->nh_reg_time
) {
1027 vty_out(vty
, "Nexthop Registry Time: %s \n",
1028 zserv_time_buf(&client
->nh_reg_time
, nhbuf
,
1030 if (client
->nh_last_upd_time
)
1031 vty_out(vty
, "Nexthop Last Update Time: %s \n",
1032 zserv_time_buf(&client
->nh_last_upd_time
, mbuf
,
1035 vty_out(vty
, "No Nexthop Update sent\n");
1037 vty_out(vty
, "Not registered for Nexthop Updates\n");
1039 vty_out(vty
, "Client will %sbe notified about it's routes status\n",
1040 client
->notify_owner
? "" : "Not ");
1042 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1043 memory_order_relaxed
);
1044 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1045 memory_order_relaxed
);
1047 last_read_cmd
= atomic_load_explicit(&client
->last_read_cmd
,
1048 memory_order_relaxed
);
1049 last_write_cmd
= atomic_load_explicit(&client
->last_write_cmd
,
1050 memory_order_relaxed
);
1052 vty_out(vty
, "Last Msg Rx Time: %s \n",
1053 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
));
1054 vty_out(vty
, "Last Msg Tx Time: %s \n",
1055 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
));
1057 vty_out(vty
, "Last Rcvd Cmd: %s \n",
1058 zserv_command_string(last_read_cmd
));
1060 vty_out(vty
, "Last Sent Cmd: %s \n",
1061 zserv_command_string(last_write_cmd
));
1064 vty_out(vty
, "Type Add Update Del \n");
1065 vty_out(vty
, "================================================== \n");
1066 vty_out(vty
, "IPv4 %-12u%-12u%-12u\n", client
->v4_route_add_cnt
,
1067 client
->v4_route_upd8_cnt
, client
->v4_route_del_cnt
);
1068 vty_out(vty
, "IPv6 %-12u%-12u%-12u\n", client
->v6_route_add_cnt
,
1069 client
->v6_route_upd8_cnt
, client
->v6_route_del_cnt
);
1070 vty_out(vty
, "Redist:v4 %-12u%-12u%-12u\n", client
->redist_v4_add_cnt
,
1071 0, client
->redist_v4_del_cnt
);
1072 vty_out(vty
, "Redist:v6 %-12u%-12u%-12u\n", client
->redist_v6_add_cnt
,
1073 0, client
->redist_v6_del_cnt
);
1074 vty_out(vty
, "Connected %-12u%-12u%-12u\n", client
->ifadd_cnt
, 0,
1076 vty_out(vty
, "BFD peer %-12u%-12u%-12u\n", client
->bfd_peer_add_cnt
,
1077 client
->bfd_peer_upd8_cnt
, client
->bfd_peer_del_cnt
);
1078 vty_out(vty
, "NHT v4 %-12u%-12u%-12u\n",
1079 client
->v4_nh_watch_add_cnt
, 0, client
->v4_nh_watch_rem_cnt
);
1080 vty_out(vty
, "NHT v6 %-12u%-12u%-12u\n",
1081 client
->v6_nh_watch_add_cnt
, 0, client
->v6_nh_watch_rem_cnt
);
1082 vty_out(vty
, "VxLAN SG %-12u%-12u%-12u\n", client
->vxlan_sg_add_cnt
,
1083 0, client
->vxlan_sg_del_cnt
);
1084 vty_out(vty
, "Interface Up Notifications: %u\n", client
->ifup_cnt
);
1085 vty_out(vty
, "Interface Down Notifications: %u\n", client
->ifdown_cnt
);
1086 vty_out(vty
, "VNI add notifications: %u\n", client
->vniadd_cnt
);
1087 vty_out(vty
, "VNI delete notifications: %u\n", client
->vnidel_cnt
);
1088 vty_out(vty
, "L3-VNI add notifications: %u\n", client
->l3vniadd_cnt
);
1089 vty_out(vty
, "L3-VNI delete notifications: %u\n", client
->l3vnidel_cnt
);
1090 vty_out(vty
, "MAC-IP add notifications: %u\n", client
->macipadd_cnt
);
1091 vty_out(vty
, "MAC-IP delete notifications: %u\n", client
->macipdel_cnt
);
1092 vty_out(vty
, "ES add notifications: %u\n", client
->local_es_add_cnt
);
1093 vty_out(vty
, "ES delete notifications: %u\n", client
->local_es_del_cnt
);
1094 vty_out(vty
, "ES-EVI add notifications: %u\n",
1095 client
->local_es_evi_add_cnt
);
1096 vty_out(vty
, "ES-EVI delete notifications: %u\n",
1097 client
->local_es_evi_del_cnt
);
1099 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1100 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1101 vty_out(vty
, "Capabilities : ");
1102 switch (info
->capabilities
) {
1103 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1104 vty_out(vty
, "Graceful Restart\n");
1106 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1107 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1108 case ZEBRA_CLIENT_GR_DISABLE
:
1109 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1110 vty_out(vty
, "None\n");
1115 #if defined DEV_BUILD
1116 vty_out(vty
, "Input Fifo: %zu:%zu Output Fifo: %zu:%zu\n",
1117 client
->ibuf_fifo
->count
, client
->ibuf_fifo
->max_count
,
1118 client
->obuf_fifo
->count
, client
->obuf_fifo
->max_count
);
1123 /* Display stale client information */
1124 static void zebra_show_stale_client_detail(struct vty
*vty
,
1125 struct zserv
*client
)
1127 char buf
[PREFIX2STR_BUFFER
];
1129 struct client_gr_info
*info
= NULL
;
1130 struct zserv
*s
= NULL
;
1131 bool first_p
= true;
1133 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1135 vty_out(vty
, "Stale Client Information\n");
1136 vty_out(vty
, "------------------------\n");
1138 if (client
->instance
)
1139 vty_out(vty
, " Instance: %u", client
->instance
);
1140 if (client
->session_id
)
1141 vty_out(vty
, " [%u]", client
->session_id
);
1146 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1147 vty_out(vty
, "Capabilities : ");
1148 switch (info
->capabilities
) {
1149 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1150 vty_out(vty
, "Graceful Restart\n");
1152 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1153 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1154 case ZEBRA_CLIENT_GR_DISABLE
:
1155 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1156 vty_out(vty
, "None\n");
1160 if (ZEBRA_CLIENT_GR_ENABLED(info
->capabilities
)) {
1161 if (info
->stale_client_ptr
) {
1162 s
= (struct zserv
*)(info
->stale_client_ptr
);
1163 uptime
= monotime(NULL
);
1164 uptime
-= s
->restart_time
;
1166 frrtime_to_interval(uptime
, buf
, sizeof(buf
));
1168 vty_out(vty
, "Last restart time : %s ago\n",
1171 vty_out(vty
, "Stalepath removal time: %d sec\n",
1172 info
->stale_removal_time
);
1173 if (info
->t_stale_removal
) {
1175 "Stale delete timer: %ld sec\n",
1176 thread_timer_remain_second(
1177 info
->t_stale_removal
));
1180 vty_out(vty
, "Current AFI : %d\n", info
->current_afi
);
1181 if (info
->current_prefix
)
1182 vty_out(vty
, "Current prefix : %pFX\n",
1183 info
->current_prefix
);
1190 static void zebra_show_client_brief(struct vty
*vty
, struct zserv
*client
)
1192 char client_string
[80];
1193 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1194 char wbuf
[ZEBRA_TIME_BUF
];
1195 time_t connect_time
, last_read_time
, last_write_time
;
1197 connect_time
= (time_t)atomic_load_explicit(&client
->connect_time
,
1198 memory_order_relaxed
);
1199 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1200 memory_order_relaxed
);
1201 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1202 memory_order_relaxed
);
1204 if (client
->instance
|| client
->session_id
)
1205 snprintfrr(client_string
, sizeof(client_string
), "%s[%u:%u]",
1206 zebra_route_string(client
->proto
), client
->instance
,
1207 client
->session_id
);
1209 snprintfrr(client_string
, sizeof(client_string
), "%s",
1210 zebra_route_string(client
->proto
));
1212 vty_out(vty
, "%-10s%12s %12s%12s%8d/%-8d%8d/%-8d\n", client_string
,
1213 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
),
1214 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
),
1215 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
),
1216 client
->v4_route_add_cnt
+ client
->v4_route_upd8_cnt
,
1217 client
->v4_route_del_cnt
,
1218 client
->v6_route_add_cnt
+ client
->v6_route_upd8_cnt
,
1219 client
->v6_route_del_cnt
);
1223 * Common logic that searches the client list for a zapi client; this
1224 * MUST be called holding the client list mutex.
1226 static struct zserv
*find_client_internal(uint8_t proto
,
1227 unsigned short instance
,
1228 uint32_t session_id
)
1230 struct listnode
*node
, *nnode
;
1231 struct zserv
*client
= NULL
;
1233 for (ALL_LIST_ELEMENTS(zrouter
.client_list
, node
, nnode
, client
)) {
1234 if (client
->proto
== proto
&& client
->instance
== instance
&&
1235 client
->session_id
== session_id
)
1243 * Public api that searches for a client session; this version is
1244 * used from the zebra main pthread.
1246 struct zserv
*zserv_find_client(uint8_t proto
, unsigned short instance
)
1248 struct zserv
*client
;
1250 frr_with_mutex(&client_mutex
) {
1251 client
= find_client_internal(proto
, instance
, 0);
1258 * Retrieve a client by its protocol, instance number, and session id.
1260 struct zserv
*zserv_find_client_session(uint8_t proto
, unsigned short instance
,
1261 uint32_t session_id
)
1263 struct zserv
*client
;
1265 frr_with_mutex(&client_mutex
) {
1266 client
= find_client_internal(proto
, instance
, session_id
);
1273 /* This command is for debugging purpose. */
1274 DEFUN (show_zebra_client
,
1275 show_zebra_client_cmd
,
1276 "show zebra client",
1279 "Client information\n")
1281 struct listnode
*node
;
1282 struct zserv
*client
;
1284 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
)) {
1285 zebra_show_client_detail(vty
, client
);
1286 /* Show GR info if present */
1287 zebra_show_stale_client_detail(vty
, client
);
1293 /* This command is for debugging purpose. */
1294 DEFUN (show_zebra_client_summary
,
1295 show_zebra_client_summary_cmd
,
1296 "show zebra client summary",
1299 "Client information brief\n"
1302 struct listnode
*node
;
1303 struct zserv
*client
;
1306 "Name Connect Time Last Read Last Write IPv4 Routes IPv6 Routes \n");
1308 "--------------------------------------------------------------------------------\n");
1310 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
))
1311 zebra_show_client_brief(vty
, client
);
1313 vty_out(vty
, "Routes column shows (added+updated)/deleted\n");
1317 static int zserv_client_close_cb(struct zserv
*closed_client
)
1319 struct listnode
*node
, *nnode
;
1320 struct zserv
*client
= NULL
;
1322 for (ALL_LIST_ELEMENTS(zrouter
.client_list
, node
, nnode
, client
)) {
1323 if (client
->proto
== closed_client
->proto
)
1326 zsend_client_close_notify(client
, closed_client
);
1332 void zserv_init(void)
1334 /* Client list init. */
1335 zrouter
.client_list
= list_new();
1336 zrouter
.stale_client_list
= list_new();
1340 pthread_mutex_init(&client_mutex
, NULL
);
1342 install_element(ENABLE_NODE
, &show_zebra_client_cmd
);
1343 install_element(ENABLE_NODE
, &show_zebra_client_summary_cmd
);
1345 hook_register(zserv_client_close
, zserv_client_close_cb
);