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
]);
644 * If any instance are graceful restart enabled,
645 * client is not deleted
647 if (DYNAMIC_CLIENT_GR_DISABLED(client
)) {
648 if (IS_ZEBRA_DEBUG_EVENT
)
649 zlog_debug("%s: Deleting client %s", __func__
,
650 zebra_route_string(client
->proto
));
651 XFREE(MTYPE_TMP
, client
);
653 /* Handle cases where client has GR instance. */
654 if (IS_ZEBRA_DEBUG_EVENT
)
655 zlog_debug("%s: client %s restart enabled", __func__
,
656 zebra_route_string(client
->proto
));
657 if (zebra_gr_client_disconnect(client
) < 0)
659 "%s: GR enabled but could not handle disconnect event",
664 void zserv_close_client(struct zserv
*client
)
668 if (client
->pthread
) {
669 /* synchronously stop and join pthread */
670 frr_pthread_stop(client
->pthread
, NULL
);
672 if (IS_ZEBRA_DEBUG_EVENT
)
673 zlog_debug("Closing client '%s'",
674 zebra_route_string(client
->proto
));
676 thread_cancel_event(zrouter
.master
, client
);
677 THREAD_OFF(client
->t_cleanup
);
678 THREAD_OFF(client
->t_process
);
680 /* destroy pthread */
681 frr_pthread_destroy(client
->pthread
);
682 client
->pthread
= NULL
;
686 * Final check in case the client struct is in use in another
687 * pthread: if not in-use, continue and free the client
689 frr_with_mutex(&client_mutex
) {
690 if (client
->busy_count
<= 0) {
691 /* remove from client list */
692 listnode_delete(zrouter
.client_list
, client
);
695 * The client session object may be in use, although
696 * the associated pthread is gone. Defer final
699 client
->is_closed
= true;
706 zserv_client_free(client
);
710 * This task is scheduled by a ZAPI client pthread on the main pthread when it
711 * wants to stop itself. When this executes, the client connection should
712 * already have been closed and the thread will most likely have died, but its
713 * resources still need to be cleaned up.
715 static int zserv_handle_client_fail(struct thread
*thread
)
717 struct zserv
*client
= THREAD_ARG(thread
);
719 zserv_close_client(client
);
724 * Create a new client.
726 * This is called when a new connection is accept()'d on the ZAPI socket. It
727 * initializes new client structure, notifies any subscribers of the connection
728 * event and spawns the client's thread.
731 * client's socket file descriptor
733 static struct zserv
*zserv_client_create(int sock
)
735 struct zserv
*client
;
737 MAX(ZEBRA_MAX_PACKET_SIZ
, sizeof(struct zapi_route
));
741 client
= XCALLOC(MTYPE_TMP
, sizeof(struct zserv
));
743 /* Make client input/output buffer. */
745 client
->ibuf_fifo
= stream_fifo_new();
746 client
->obuf_fifo
= stream_fifo_new();
747 client
->ibuf_work
= stream_new(stream_size
);
748 client
->obuf_work
= stream_new(stream_size
);
749 pthread_mutex_init(&client
->ibuf_mtx
, NULL
);
750 pthread_mutex_init(&client
->obuf_mtx
, NULL
);
751 client
->wb
= buffer_new(0);
752 TAILQ_INIT(&(client
->gr_info_queue
));
754 atomic_store_explicit(&client
->connect_time
, (uint32_t) monotime(NULL
),
755 memory_order_relaxed
);
757 /* Initialize flags */
758 for (afi
= AFI_IP
; afi
< AFI_MAX
; afi
++) {
759 for (i
= 0; i
< ZEBRA_ROUTE_MAX
; i
++)
760 client
->redist
[afi
][i
] = vrf_bitmap_init();
761 client
->redist_default
[afi
] = vrf_bitmap_init();
762 client
->ridinfo
[afi
] = vrf_bitmap_init();
765 /* Add this client to linked list. */
766 frr_with_mutex(&client_mutex
) {
767 listnode_add(zrouter
.client_list
, client
);
770 struct frr_pthread_attr zclient_pthr_attrs
= {
771 .start
= frr_pthread_attr_default
.start
,
772 .stop
= frr_pthread_attr_default
.stop
775 frr_pthread_new(&zclient_pthr_attrs
, "Zebra API client thread",
778 /* start read loop */
779 zserv_client_event(client
, ZSERV_CLIENT_READ
);
782 hook_call(zserv_client_connect
, client
);
785 frr_pthread_run(client
->pthread
, NULL
);
791 * Retrieve a client object by the complete tuple of
792 * {protocol, instance, session}. This version supports use
793 * from a different pthread: the object will be returned marked
794 * in-use. The caller *must* release the client object with the
795 * release_client() api, to ensure that the in-use marker is cleared properly.
797 struct zserv
*zserv_acquire_client(uint8_t proto
, unsigned short instance
,
800 struct zserv
*client
= NULL
;
802 frr_with_mutex(&client_mutex
) {
803 client
= find_client_internal(proto
, instance
, session_id
);
805 /* Don't return a dead/closed client object */
806 if (client
->is_closed
)
809 client
->busy_count
++;
817 * Release a client object that was acquired with the acquire_client() api.
818 * After this has been called, the caller must not use the client pointer -
819 * it may be freed if the client has closed.
821 void zserv_release_client(struct zserv
*client
)
824 * Once we've decremented the client object's refcount, it's possible
825 * for it to be deleted as soon as we release the lock, so we won't
826 * touch the object again.
828 frr_with_mutex(&client_mutex
) {
829 client
->busy_count
--;
831 if (client
->busy_count
<= 0) {
833 * No more users of the client object. If the client
834 * session is closed, schedule cleanup on the zebra
837 if (client
->is_closed
)
838 thread_add_event(zrouter
.master
,
839 zserv_handle_client_fail
,
840 client
, 0, &client
->t_cleanup
);
845 * Cleanup must take place on the zebra main pthread, so we've
846 * scheduled an event.
851 * Accept socket connection.
853 static int zserv_accept(struct thread
*thread
)
857 struct sockaddr_in client
;
860 accept_sock
= THREAD_FD(thread
);
862 /* Reregister myself. */
863 zserv_event(NULL
, ZSERV_ACCEPT
);
865 len
= sizeof(struct sockaddr_in
);
866 client_sock
= accept(accept_sock
, (struct sockaddr
*)&client
, &len
);
868 if (client_sock
< 0) {
869 flog_err_sys(EC_LIB_SOCKET
, "Can't accept zebra socket: %s",
870 safe_strerror(errno
));
874 /* Make client socket non-blocking. */
875 set_nonblocking(client_sock
);
877 /* Create new zebra client. */
878 zserv_client_create(client_sock
);
883 void zserv_close(void)
886 * On shutdown, let's close the socket down
887 * so that long running processes of killing the
888 * routing table doesn't leave us in a bad
889 * state where a client tries to reconnect
894 /* Free client list's mutex */
895 pthread_mutex_destroy(&client_mutex
);
898 void zserv_start(char *path
)
902 struct sockaddr_storage sa
;
905 if (!frr_zclient_addr(&sa
, &sa_len
, path
))
906 /* should be caught in zebra main() */
910 old_mask
= umask(0077);
912 /* Make UNIX domain socket. */
913 zsock
= socket(sa
.ss_family
, SOCK_STREAM
, 0);
915 flog_err_sys(EC_LIB_SOCKET
, "Can't create zserv socket: %s",
916 safe_strerror(errno
));
920 if (sa
.ss_family
!= AF_UNIX
) {
921 sockopt_reuseaddr(zsock
);
922 sockopt_reuseport(zsock
);
924 struct sockaddr_un
*suna
= (struct sockaddr_un
*)&sa
;
925 if (suna
->sun_path
[0])
926 unlink(suna
->sun_path
);
929 setsockopt_so_recvbuf(zsock
, 1048576);
930 setsockopt_so_sendbuf(zsock
, 1048576);
932 frr_with_privs((sa
.ss_family
!= AF_UNIX
) ? &zserv_privs
: NULL
) {
933 ret
= bind(zsock
, (struct sockaddr
*)&sa
, sa_len
);
936 flog_err_sys(EC_LIB_SOCKET
, "Can't bind zserv socket on %s: %s",
937 path
, safe_strerror(errno
));
943 ret
= listen(zsock
, 5);
945 flog_err_sys(EC_LIB_SOCKET
,
946 "Can't listen to zserv socket %s: %s", path
,
947 safe_strerror(errno
));
955 zserv_event(NULL
, ZSERV_ACCEPT
);
958 void zserv_event(struct zserv
*client
, enum zserv_event event
)
962 thread_add_read(zrouter
.master
, zserv_accept
, NULL
, zsock
,
965 case ZSERV_PROCESS_MESSAGES
:
966 thread_add_event(zrouter
.master
, zserv_process_messages
, client
,
967 0, &client
->t_process
);
969 case ZSERV_HANDLE_CLIENT_FAIL
:
970 thread_add_event(zrouter
.master
, zserv_handle_client_fail
,
971 client
, 0, &client
->t_cleanup
);
976 /* General purpose ---------------------------------------------------------- */
978 #define ZEBRA_TIME_BUF 32
979 static char *zserv_time_buf(time_t *time1
, char *buf
, int buflen
)
984 assert(buflen
>= ZEBRA_TIME_BUF
);
985 assert(time1
!= NULL
);
988 snprintf(buf
, buflen
, "never ");
992 now
= monotime(NULL
);
995 frrtime_to_interval(now
, buf
, buflen
);
1000 /* Display client info details */
1001 static void zebra_show_client_detail(struct vty
*vty
, struct zserv
*client
)
1003 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1004 char wbuf
[ZEBRA_TIME_BUF
], nhbuf
[ZEBRA_TIME_BUF
], mbuf
[ZEBRA_TIME_BUF
];
1005 time_t connect_time
, last_read_time
, last_write_time
;
1006 uint32_t last_read_cmd
, last_write_cmd
;
1007 struct client_gr_info
*info
= NULL
;
1009 vty_out(vty
, "Client: %s", zebra_route_string(client
->proto
));
1010 if (client
->instance
)
1011 vty_out(vty
, " Instance: %u", client
->instance
);
1012 if (client
->session_id
)
1013 vty_out(vty
, " [%u]", client
->session_id
);
1016 vty_out(vty
, "------------------------ \n");
1017 vty_out(vty
, "FD: %d \n", client
->sock
);
1019 connect_time
= (time_t) atomic_load_explicit(&client
->connect_time
,
1020 memory_order_relaxed
);
1022 vty_out(vty
, "Connect Time: %s \n",
1023 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
));
1024 if (client
->nh_reg_time
) {
1025 vty_out(vty
, "Nexthop Registry Time: %s \n",
1026 zserv_time_buf(&client
->nh_reg_time
, nhbuf
,
1028 if (client
->nh_last_upd_time
)
1029 vty_out(vty
, "Nexthop Last Update Time: %s \n",
1030 zserv_time_buf(&client
->nh_last_upd_time
, mbuf
,
1033 vty_out(vty
, "No Nexthop Update sent\n");
1035 vty_out(vty
, "Not registered for Nexthop Updates\n");
1037 vty_out(vty
, "Client will %sbe notified about it's routes status\n",
1038 client
->notify_owner
? "" : "Not ");
1040 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1041 memory_order_relaxed
);
1042 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1043 memory_order_relaxed
);
1045 last_read_cmd
= atomic_load_explicit(&client
->last_read_cmd
,
1046 memory_order_relaxed
);
1047 last_write_cmd
= atomic_load_explicit(&client
->last_write_cmd
,
1048 memory_order_relaxed
);
1050 vty_out(vty
, "Last Msg Rx Time: %s \n",
1051 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
));
1052 vty_out(vty
, "Last Msg Tx Time: %s \n",
1053 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
));
1055 vty_out(vty
, "Last Rcvd Cmd: %s \n",
1056 zserv_command_string(last_read_cmd
));
1058 vty_out(vty
, "Last Sent Cmd: %s \n",
1059 zserv_command_string(last_write_cmd
));
1062 vty_out(vty
, "Type Add Update Del \n");
1063 vty_out(vty
, "================================================== \n");
1064 vty_out(vty
, "IPv4 %-12u%-12u%-12u\n", client
->v4_route_add_cnt
,
1065 client
->v4_route_upd8_cnt
, client
->v4_route_del_cnt
);
1066 vty_out(vty
, "IPv6 %-12u%-12u%-12u\n", client
->v6_route_add_cnt
,
1067 client
->v6_route_upd8_cnt
, client
->v6_route_del_cnt
);
1068 vty_out(vty
, "Redist:v4 %-12u%-12u%-12u\n", client
->redist_v4_add_cnt
,
1069 0, client
->redist_v4_del_cnt
);
1070 vty_out(vty
, "Redist:v6 %-12u%-12u%-12u\n", client
->redist_v6_add_cnt
,
1071 0, client
->redist_v6_del_cnt
);
1072 vty_out(vty
, "Connected %-12u%-12u%-12u\n", client
->ifadd_cnt
, 0,
1074 vty_out(vty
, "BFD peer %-12u%-12u%-12u\n", client
->bfd_peer_add_cnt
,
1075 client
->bfd_peer_upd8_cnt
, client
->bfd_peer_del_cnt
);
1076 vty_out(vty
, "NHT v4 %-12u%-12u%-12u\n",
1077 client
->v4_nh_watch_add_cnt
, 0, client
->v4_nh_watch_rem_cnt
);
1078 vty_out(vty
, "NHT v6 %-12u%-12u%-12u\n",
1079 client
->v6_nh_watch_add_cnt
, 0, client
->v6_nh_watch_rem_cnt
);
1080 vty_out(vty
, "VxLAN SG %-12u%-12u%-12u\n", client
->vxlan_sg_add_cnt
,
1081 0, client
->vxlan_sg_del_cnt
);
1082 vty_out(vty
, "Interface Up Notifications: %u\n", client
->ifup_cnt
);
1083 vty_out(vty
, "Interface Down Notifications: %u\n", client
->ifdown_cnt
);
1084 vty_out(vty
, "VNI add notifications: %u\n", client
->vniadd_cnt
);
1085 vty_out(vty
, "VNI delete notifications: %u\n", client
->vnidel_cnt
);
1086 vty_out(vty
, "L3-VNI add notifications: %u\n", client
->l3vniadd_cnt
);
1087 vty_out(vty
, "L3-VNI delete notifications: %u\n", client
->l3vnidel_cnt
);
1088 vty_out(vty
, "MAC-IP add notifications: %u\n", client
->macipadd_cnt
);
1089 vty_out(vty
, "MAC-IP delete notifications: %u\n", client
->macipdel_cnt
);
1090 vty_out(vty
, "ES add notifications: %u\n", client
->local_es_add_cnt
);
1091 vty_out(vty
, "ES delete notifications: %u\n", client
->local_es_del_cnt
);
1092 vty_out(vty
, "ES-EVI add notifications: %u\n",
1093 client
->local_es_evi_add_cnt
);
1094 vty_out(vty
, "ES-EVI delete notifications: %u\n",
1095 client
->local_es_evi_del_cnt
);
1097 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1098 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1099 vty_out(vty
, "Capabilities : ");
1100 switch (info
->capabilities
) {
1101 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1102 vty_out(vty
, "Graceful Restart\n");
1104 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1105 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1106 case ZEBRA_CLIENT_GR_DISABLE
:
1107 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1108 vty_out(vty
, "None\n");
1113 #if defined DEV_BUILD
1114 vty_out(vty
, "Input Fifo: %zu:%zu Output Fifo: %zu:%zu\n",
1115 client
->ibuf_fifo
->count
, client
->ibuf_fifo
->max_count
,
1116 client
->obuf_fifo
->count
, client
->obuf_fifo
->max_count
);
1121 /* Display stale client information */
1122 static void zebra_show_stale_client_detail(struct vty
*vty
,
1123 struct zserv
*client
)
1125 char buf
[PREFIX2STR_BUFFER
];
1127 struct client_gr_info
*info
= NULL
;
1128 struct zserv
*s
= NULL
;
1129 bool first_p
= true;
1131 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1133 vty_out(vty
, "Stale Client Information\n");
1134 vty_out(vty
, "------------------------\n");
1136 if (client
->instance
)
1137 vty_out(vty
, " Instance: %u", client
->instance
);
1138 if (client
->session_id
)
1139 vty_out(vty
, " [%u]", client
->session_id
);
1144 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1145 vty_out(vty
, "Capabilities : ");
1146 switch (info
->capabilities
) {
1147 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1148 vty_out(vty
, "Graceful Restart\n");
1150 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1151 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1152 case ZEBRA_CLIENT_GR_DISABLE
:
1153 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1154 vty_out(vty
, "None\n");
1158 if (ZEBRA_CLIENT_GR_ENABLED(info
->capabilities
)) {
1159 if (info
->stale_client_ptr
) {
1160 s
= (struct zserv
*)(info
->stale_client_ptr
);
1161 uptime
= monotime(NULL
);
1162 uptime
-= s
->restart_time
;
1164 frrtime_to_interval(uptime
, buf
, sizeof(buf
));
1166 vty_out(vty
, "Last restart time : %s ago\n",
1169 vty_out(vty
, "Stalepath removal time: %d sec\n",
1170 info
->stale_removal_time
);
1171 if (info
->t_stale_removal
) {
1173 "Stale delete timer: %ld sec\n",
1174 thread_timer_remain_second(
1175 info
->t_stale_removal
));
1178 vty_out(vty
, "Current AFI : %d\n", info
->current_afi
);
1179 if (info
->current_prefix
)
1180 vty_out(vty
, "Current prefix : %pFX\n",
1181 info
->current_prefix
);
1188 static void zebra_show_client_brief(struct vty
*vty
, struct zserv
*client
)
1190 char client_string
[80];
1191 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1192 char wbuf
[ZEBRA_TIME_BUF
];
1193 time_t connect_time
, last_read_time
, last_write_time
;
1195 connect_time
= (time_t)atomic_load_explicit(&client
->connect_time
,
1196 memory_order_relaxed
);
1197 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1198 memory_order_relaxed
);
1199 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1200 memory_order_relaxed
);
1202 if (client
->instance
|| client
->session_id
)
1203 snprintfrr(client_string
, sizeof(client_string
), "%s[%u:%u]",
1204 zebra_route_string(client
->proto
), client
->instance
,
1205 client
->session_id
);
1207 snprintfrr(client_string
, sizeof(client_string
), "%s",
1208 zebra_route_string(client
->proto
));
1210 vty_out(vty
, "%-10s%12s %12s%12s%8d/%-8d%8d/%-8d\n", client_string
,
1211 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
),
1212 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
),
1213 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
),
1214 client
->v4_route_add_cnt
+ client
->v4_route_upd8_cnt
,
1215 client
->v4_route_del_cnt
,
1216 client
->v6_route_add_cnt
+ client
->v6_route_upd8_cnt
,
1217 client
->v6_route_del_cnt
);
1221 * Common logic that searches the client list for a zapi client; this
1222 * MUST be called holding the client list mutex.
1224 static struct zserv
*find_client_internal(uint8_t proto
,
1225 unsigned short instance
,
1226 uint32_t session_id
)
1228 struct listnode
*node
, *nnode
;
1229 struct zserv
*client
= NULL
;
1231 for (ALL_LIST_ELEMENTS(zrouter
.client_list
, node
, nnode
, client
)) {
1232 if (client
->proto
== proto
&& client
->instance
== instance
&&
1233 client
->session_id
== session_id
)
1241 * Public api that searches for a client session; this version is
1242 * used from the zebra main pthread.
1244 struct zserv
*zserv_find_client(uint8_t proto
, unsigned short instance
)
1246 struct zserv
*client
;
1248 frr_with_mutex(&client_mutex
) {
1249 client
= find_client_internal(proto
, instance
, 0);
1256 * Retrieve a client by its protocol, instance number, and session id.
1258 struct zserv
*zserv_find_client_session(uint8_t proto
, unsigned short instance
,
1259 uint32_t session_id
)
1261 struct zserv
*client
;
1263 frr_with_mutex(&client_mutex
) {
1264 client
= find_client_internal(proto
, instance
, session_id
);
1271 /* This command is for debugging purpose. */
1272 DEFUN (show_zebra_client
,
1273 show_zebra_client_cmd
,
1274 "show zebra client",
1277 "Client information\n")
1279 struct listnode
*node
;
1280 struct zserv
*client
;
1282 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
)) {
1283 zebra_show_client_detail(vty
, client
);
1284 /* Show GR info if present */
1285 zebra_show_stale_client_detail(vty
, client
);
1291 /* This command is for debugging purpose. */
1292 DEFUN (show_zebra_client_summary
,
1293 show_zebra_client_summary_cmd
,
1294 "show zebra client summary",
1297 "Client information brief\n"
1300 struct listnode
*node
;
1301 struct zserv
*client
;
1304 "Name Connect Time Last Read Last Write IPv4 Routes IPv6 Routes \n");
1306 "--------------------------------------------------------------------------------\n");
1308 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
))
1309 zebra_show_client_brief(vty
, client
);
1311 vty_out(vty
, "Routes column shows (added+updated)/deleted\n");
1315 static int zserv_client_close_cb(struct zserv
*closed_client
)
1317 struct listnode
*node
, *nnode
;
1318 struct zserv
*client
= NULL
;
1320 for (ALL_LIST_ELEMENTS(zrouter
.client_list
, node
, nnode
, client
)) {
1321 if (client
->proto
== closed_client
->proto
)
1324 zsend_client_close_notify(client
, closed_client
);
1330 void zserv_init(void)
1332 /* Client list init. */
1333 zrouter
.client_list
= list_new();
1334 zrouter
.stale_client_list
= list_new();
1338 pthread_mutex_init(&client_mutex
, NULL
);
1340 install_element(ENABLE_NODE
, &show_zebra_client_cmd
);
1341 install_element(ENABLE_NODE
, &show_zebra_client_summary_cmd
);
1343 hook_register(zserv_client_close
, zserv_client_close_cb
);