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 */
59 #include "zebra/debug.h" /* for various debugging macros */
60 #include "zebra/rib.h" /* for rib_score_proto */
61 #include "zebra/zapi_msg.h" /* for zserv_handle_commands */
62 #include "zebra/zebra_vrf.h" /* for zebra_vrf_lookup_by_id, zvrf */
63 #include "zebra/zserv.h" /* for zserv */
64 #include "zebra/zebra_router.h"
65 #include "zebra/zebra_errors.h" /* for error messages */
69 extern struct zebra_privs_t zserv_privs
;
71 /* The listener socket for clients connecting to us */
74 /* The lock that protects access to zapi client objects */
75 static pthread_mutex_t client_mutex
;
77 static struct zserv
*find_client_internal(uint8_t proto
,
78 unsigned short instance
,
83 * Client thread events.
85 * These are used almost exclusively by client threads to drive their own event
86 * loops. The only exception is in zserv_client_create(), which pushes an
87 * initial ZSERV_CLIENT_READ event to start the API handler loop.
89 enum zserv_client_event
{
90 /* Schedule a socket read */
92 /* Schedule a buffer write */
99 * These are used by client threads to notify the main thread about various
100 * events and to make processing requests.
103 /* Schedule listen job on Zebra API socket */
105 /* The calling client has packets on its input buffer */
106 ZSERV_PROCESS_MESSAGES
,
107 /* The calling client wishes to be killed */
108 ZSERV_HANDLE_CLIENT_FAIL
,
112 * Zebra server event driver for all client threads.
114 * This is essentially a wrapper around thread_add_event() that centralizes
115 * those scheduling calls into one place.
117 * All calls to this function schedule an event on the pthread running the
121 * the client in question, and thread target
124 * the event to notify them about
126 static void zserv_client_event(struct zserv
*client
,
127 enum zserv_client_event event
);
130 * Zebra server event driver for the main thread.
132 * This is essentially a wrapper around thread_add_event() that centralizes
133 * those scheduling calls into one place.
135 * All calls to this function schedule an event on Zebra's main pthread.
138 * the client in question
141 * the event to notify the main thread about
143 static void zserv_event(struct zserv
*client
, enum zserv_event event
);
146 /* Client thread lifecycle -------------------------------------------------- */
149 * Log zapi message to zlog.
160 void zserv_log_message(const char *errmsg
, struct stream
*msg
,
163 zlog_debug("Rx'd ZAPI message");
165 zlog_debug("%s", errmsg
);
167 zlog_debug(" Length: %d", hdr
->length
);
168 zlog_debug("Command: %s", zserv_command_string(hdr
->command
));
169 zlog_debug(" VRF: %u", hdr
->vrf_id
);
175 * Gracefully shut down a client connection.
177 * Cancel any pending tasks for the client's thread. Then schedule a task on
178 * the main thread to shut down the calling thread.
180 * It is not safe to close the client socket in this function. The socket is
181 * owned by the main thread.
183 * Must be called from the client pthread, never the main thread.
185 static void zserv_client_fail(struct zserv
*client
)
187 flog_warn(EC_ZEBRA_CLIENT_IO_ERROR
,
188 "Client '%s' encountered an error and is shutting down.",
189 zebra_route_string(client
->proto
));
191 atomic_store_explicit(&client
->pthread
->running
, false,
192 memory_order_relaxed
);
194 THREAD_OFF(client
->t_read
);
195 THREAD_OFF(client
->t_write
);
196 zserv_event(client
, ZSERV_HANDLE_CLIENT_FAIL
);
200 * Write all pending messages to client socket.
202 * This function first attempts to flush any buffered data. If unsuccessful,
203 * the function reschedules itself and returns. If successful, it pops all
204 * available messages from the output queue and continues to write data
205 * directly to the socket until the socket would block. If the socket never
206 * blocks and all data is written, the function returns without rescheduling
207 * itself. If the socket ends up throwing EWOULDBLOCK, the remaining data is
208 * buffered and the function reschedules itself.
210 * The utility of the buffer is that it allows us to vastly reduce lock
211 * contention by allowing us to pop *all* messages off the output queue at once
212 * instead of locking and unlocking each time we want to pop a single message
213 * off the queue. The same thing could arguably be accomplished faster by
214 * allowing the main thread to write directly into the buffer instead of
215 * enqueuing packets onto an intermediary queue, but the intermediary queue
216 * allows us to expose information about input and output queues to the user in
217 * terms of number of packets rather than size of data.
219 static int zserv_write(struct thread
*thread
)
221 struct zserv
*client
= THREAD_ARG(thread
);
224 struct stream_fifo
*cache
;
226 /* If we have any data pending, try to flush it first */
227 switch (buffer_flush_all(client
->wb
, client
->sock
)) {
231 atomic_store_explicit(&client
->last_write_time
,
232 (uint32_t)monotime(NULL
),
233 memory_order_relaxed
);
234 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
240 cache
= stream_fifo_new();
242 frr_with_mutex(&client
->obuf_mtx
) {
243 while (stream_fifo_head(client
->obuf_fifo
))
244 stream_fifo_push(cache
,
245 stream_fifo_pop(client
->obuf_fifo
));
250 stream_set_getp(msg
, 0);
251 wcmd
= stream_getw_from(msg
, ZAPI_HEADER_CMD_LOCATION
);
254 while (stream_fifo_head(cache
)) {
255 msg
= stream_fifo_pop(cache
);
256 buffer_put(client
->wb
, STREAM_DATA(msg
), stream_get_endp(msg
));
260 stream_fifo_free(cache
);
262 /* If we have any data pending, try to flush it first */
263 switch (buffer_flush_all(client
->wb
, client
->sock
)) {
267 atomic_store_explicit(&client
->last_write_time
,
268 (uint32_t)monotime(NULL
),
269 memory_order_relaxed
);
270 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
276 atomic_store_explicit(&client
->last_write_cmd
, wcmd
,
277 memory_order_relaxed
);
279 atomic_store_explicit(&client
->last_write_time
,
280 (uint32_t)monotime(NULL
), memory_order_relaxed
);
285 flog_warn(EC_ZEBRA_CLIENT_WRITE_FAILED
,
286 "%s: could not write to %s [fd = %d], closing.", __func__
,
287 zebra_route_string(client
->proto
), client
->sock
);
288 zserv_client_fail(client
);
293 * Read and process data from a client socket.
295 * The responsibilities here are to read raw data from the client socket,
296 * validate the header, encapsulate it into a single stream object, push it
297 * onto the input queue and then notify the main thread that there is new data
300 * This function first looks for any data in the client structure's working
301 * input buffer. If data is present, it is assumed that reading stopped in a
302 * previous invocation of this task and needs to be resumed to finish a message.
303 * Otherwise, the socket data stream is assumed to be at the beginning of a new
304 * ZAPI message (specifically at the header). The header is read and validated.
305 * If the header passed validation then the length field found in the header is
306 * used to compute the total length of the message. That much data is read (but
307 * not inspected), appended to the header, placed into a stream and pushed onto
308 * the client's input queue. A task is then scheduled on the main thread to
309 * process the client's input queue. Finally, if all of this was successful,
310 * this task reschedules itself.
312 * Any failure in any of these actions is handled by terminating the client.
314 static int zserv_read(struct thread
*thread
)
316 struct zserv
*client
= THREAD_ARG(thread
);
319 struct stream_fifo
*cache
;
325 p2p_orig
= atomic_load_explicit(&zrouter
.packets_to_process
,
326 memory_order_relaxed
);
327 cache
= stream_fifo_new();
329 sock
= THREAD_FD(thread
);
336 already
= stream_get_endp(client
->ibuf_work
);
338 /* Read length and command (if we don't have it already). */
339 if (already
< ZEBRA_HEADER_SIZE
) {
340 nb
= stream_read_try(client
->ibuf_work
, sock
,
341 ZEBRA_HEADER_SIZE
- already
);
342 if ((nb
== 0 || nb
== -1)) {
343 if (IS_ZEBRA_DEBUG_EVENT
)
344 zlog_debug("connection closed socket [%d]",
348 if (nb
!= (ssize_t
)(ZEBRA_HEADER_SIZE
- already
)) {
349 /* Try again later. */
352 already
= ZEBRA_HEADER_SIZE
;
355 /* Reset to read from the beginning of the incoming packet. */
356 stream_set_getp(client
->ibuf_work
, 0);
358 /* Fetch header values */
359 hdrvalid
= zapi_parse_header(client
->ibuf_work
, &hdr
);
362 snprintf(errmsg
, sizeof(errmsg
),
363 "%s: Message has corrupt header", __func__
);
364 zserv_log_message(errmsg
, client
->ibuf_work
, NULL
);
368 /* Validate header */
369 if (hdr
.marker
!= ZEBRA_HEADER_MARKER
370 || hdr
.version
!= ZSERV_VERSION
) {
372 errmsg
, sizeof(errmsg
),
373 "Message has corrupt header\n%s: socket %d version mismatch, marker %d, version %d",
374 __func__
, sock
, hdr
.marker
, hdr
.version
);
375 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
378 if (hdr
.length
< ZEBRA_HEADER_SIZE
) {
380 errmsg
, sizeof(errmsg
),
381 "Message has corrupt header\n%s: socket %d message length %u is less than header size %d",
382 __func__
, sock
, hdr
.length
, ZEBRA_HEADER_SIZE
);
383 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
386 if (hdr
.length
> STREAM_SIZE(client
->ibuf_work
)) {
388 errmsg
, sizeof(errmsg
),
389 "Message has corrupt header\n%s: socket %d message length %u exceeds buffer size %lu",
390 __func__
, sock
, hdr
.length
,
391 (unsigned long)STREAM_SIZE(client
->ibuf_work
));
392 zserv_log_message(errmsg
, client
->ibuf_work
, &hdr
);
396 /* Read rest of data. */
397 if (already
< hdr
.length
) {
398 nb
= stream_read_try(client
->ibuf_work
, sock
,
399 hdr
.length
- already
);
400 if ((nb
== 0 || nb
== -1)) {
401 if (IS_ZEBRA_DEBUG_EVENT
)
403 "connection closed [%d] when reading zebra data",
407 if (nb
!= (ssize_t
)(hdr
.length
- already
)) {
408 /* Try again later. */
413 /* Debug packet information. */
414 if (IS_ZEBRA_DEBUG_PACKET
)
415 zlog_debug("zebra message[%s:%u:%u] comes from socket [%d]",
416 zserv_command_string(hdr
.command
),
417 hdr
.vrf_id
, hdr
.length
,
420 stream_set_getp(client
->ibuf_work
, 0);
421 struct stream
*msg
= stream_dup(client
->ibuf_work
);
423 stream_fifo_push(cache
, msg
);
424 stream_reset(client
->ibuf_work
);
428 if (p2p
< p2p_orig
) {
429 /* update session statistics */
430 atomic_store_explicit(&client
->last_read_time
, monotime(NULL
),
431 memory_order_relaxed
);
432 atomic_store_explicit(&client
->last_read_cmd
, hdr
.command
,
433 memory_order_relaxed
);
435 /* publish read packets on client's input queue */
436 frr_with_mutex(&client
->ibuf_mtx
) {
438 stream_fifo_push(client
->ibuf_fifo
,
439 stream_fifo_pop(cache
));
442 /* Schedule job to process those packets */
443 zserv_event(client
, ZSERV_PROCESS_MESSAGES
);
447 if (IS_ZEBRA_DEBUG_PACKET
)
448 zlog_debug("Read %d packets from client: %s", p2p_orig
- p2p
,
449 zebra_route_string(client
->proto
));
451 /* Reschedule ourselves */
452 zserv_client_event(client
, ZSERV_CLIENT_READ
);
454 stream_fifo_free(cache
);
459 stream_fifo_free(cache
);
460 zserv_client_fail(client
);
464 static void zserv_client_event(struct zserv
*client
,
465 enum zserv_client_event event
)
468 case ZSERV_CLIENT_READ
:
469 thread_add_read(client
->pthread
->master
, zserv_read
, client
,
470 client
->sock
, &client
->t_read
);
472 case ZSERV_CLIENT_WRITE
:
473 thread_add_write(client
->pthread
->master
, zserv_write
, client
,
474 client
->sock
, &client
->t_write
);
479 /* Main thread lifecycle ---------------------------------------------------- */
482 * Read and process messages from a client.
484 * This task runs on the main pthread. It is scheduled by client pthreads when
485 * they have new messages available on their input queues. The client is passed
486 * as the task argument.
488 * Each message is popped off the client's input queue and the action associated
489 * with the message is executed. This proceeds until there are no more messages,
490 * an error occurs, or the processing limit is reached.
492 * The client's I/O thread can push at most zrouter.packets_to_process messages
493 * onto the input buffer before notifying us there are packets to read. As long
494 * as we always process zrouter.packets_to_process messages here, then we can
495 * rely on the read thread to handle queuing this task enough times to process
496 * everything on the input queue.
498 static int zserv_process_messages(struct thread
*thread
)
500 struct zserv
*client
= THREAD_ARG(thread
);
502 struct stream_fifo
*cache
= stream_fifo_new();
503 uint32_t p2p
= zrouter
.packets_to_process
;
504 bool need_resched
= false;
506 frr_with_mutex(&client
->ibuf_mtx
) {
508 for (i
= 0; i
< p2p
&& stream_fifo_head(client
->ibuf_fifo
);
510 msg
= stream_fifo_pop(client
->ibuf_fifo
);
511 stream_fifo_push(cache
, msg
);
516 /* Need to reschedule processing work if there are still
517 * packets in the fifo.
519 if (stream_fifo_head(client
->ibuf_fifo
))
523 /* Process the batch of messages */
524 if (stream_fifo_head(cache
))
525 zserv_handle_commands(client
, cache
);
527 stream_fifo_free(cache
);
529 /* Reschedule ourselves if necessary */
531 zserv_event(client
, ZSERV_PROCESS_MESSAGES
);
536 int zserv_send_message(struct zserv
*client
, struct stream
*msg
)
538 frr_with_mutex(&client
->obuf_mtx
) {
539 stream_fifo_push(client
->obuf_fifo
, msg
);
542 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
548 * Send a batch of messages to a connected Zebra API client.
550 int zserv_send_batch(struct zserv
*client
, struct stream_fifo
*fifo
)
554 frr_with_mutex(&client
->obuf_mtx
) {
555 msg
= stream_fifo_pop(fifo
);
557 stream_fifo_push(client
->obuf_fifo
, msg
);
558 msg
= stream_fifo_pop(fifo
);
562 zserv_client_event(client
, ZSERV_CLIENT_WRITE
);
567 /* Hooks for client connect / disconnect */
568 DEFINE_HOOK(zserv_client_connect
, (struct zserv
*client
), (client
));
569 DEFINE_KOOH(zserv_client_close
, (struct zserv
*client
), (client
));
572 * Deinitialize zebra client.
574 * - Deregister and deinitialize related internal resources
575 * - Gracefully close socket
576 * - Free associated resources
577 * - Free client structure
579 * This does *not* take any action on the struct thread * fields. These are
580 * managed by the owning pthread and any tasks associated with them must have
581 * been stopped prior to invoking this function.
583 static void zserv_client_free(struct zserv
*client
)
588 hook_call(zserv_client_close
, client
);
590 /* Close file descriptor. */
592 unsigned long nroutes
;
597 if (DYNAMIC_CLIENT_GR_DISABLED(client
)) {
598 nroutes
= rib_score_proto(client
->proto
,
601 "client %d disconnected %lu %s routes removed from the rib",
602 client
->sock
, nroutes
,
603 zebra_route_string(client
->proto
));
605 /* Not worrying about instance for now */
606 nnhgs
= zebra_nhg_score_proto(client
->proto
);
608 "client %d disconnected %lu %s nhgs removed from the rib",
610 zebra_route_string(client
->proto
));
615 /* Free stream buffers. */
616 if (client
->ibuf_work
)
617 stream_free(client
->ibuf_work
);
618 if (client
->obuf_work
)
619 stream_free(client
->obuf_work
);
620 if (client
->ibuf_fifo
)
621 stream_fifo_free(client
->ibuf_fifo
);
622 if (client
->obuf_fifo
)
623 stream_fifo_free(client
->obuf_fifo
);
625 buffer_free(client
->wb
);
627 /* Free buffer mutexes */
628 pthread_mutex_destroy(&client
->obuf_mtx
);
629 pthread_mutex_destroy(&client
->ibuf_mtx
);
632 for (afi_t afi
= AFI_IP
; afi
< AFI_MAX
; afi
++) {
633 for (int i
= 0; i
< ZEBRA_ROUTE_MAX
; i
++) {
634 vrf_bitmap_free(client
->redist
[afi
][i
]);
635 redist_del_all_instances(&client
->mi_redist
[afi
][i
]);
638 vrf_bitmap_free(client
->redist_default
[afi
]);
639 vrf_bitmap_free(client
->ridinfo
[afi
]);
643 * If any instance are graceful restart enabled,
644 * client is not deleted
646 if (DYNAMIC_CLIENT_GR_DISABLED(client
)) {
647 if (IS_ZEBRA_DEBUG_EVENT
)
648 zlog_debug("%s: Deleting client %s", __func__
,
649 zebra_route_string(client
->proto
));
650 XFREE(MTYPE_TMP
, client
);
652 /* Handle cases where client has GR instance. */
653 if (IS_ZEBRA_DEBUG_EVENT
)
654 zlog_debug("%s: client %s restart enabled", __func__
,
655 zebra_route_string(client
->proto
));
656 if (zebra_gr_client_disconnect(client
) < 0)
658 "%s: GR enabled but could not handle disconnect event",
663 void zserv_close_client(struct zserv
*client
)
667 if (client
->pthread
) {
668 /* synchronously stop and join pthread */
669 frr_pthread_stop(client
->pthread
, NULL
);
671 if (IS_ZEBRA_DEBUG_EVENT
)
672 zlog_debug("Closing client '%s'",
673 zebra_route_string(client
->proto
));
675 thread_cancel_event(zrouter
.master
, client
);
676 THREAD_OFF(client
->t_cleanup
);
677 THREAD_OFF(client
->t_process
);
679 /* destroy pthread */
680 frr_pthread_destroy(client
->pthread
);
681 client
->pthread
= NULL
;
685 * Final check in case the client struct is in use in another
686 * pthread: if not in-use, continue and free the client
688 frr_with_mutex(&client_mutex
) {
689 if (client
->busy_count
<= 0) {
690 /* remove from client list */
691 listnode_delete(zrouter
.client_list
, client
);
694 * The client session object may be in use, although
695 * the associated pthread is gone. Defer final
698 client
->is_closed
= true;
705 zserv_client_free(client
);
709 * This task is scheduled by a ZAPI client pthread on the main pthread when it
710 * wants to stop itself. When this executes, the client connection should
711 * already have been closed and the thread will most likely have died, but its
712 * resources still need to be cleaned up.
714 static int zserv_handle_client_fail(struct thread
*thread
)
716 struct zserv
*client
= THREAD_ARG(thread
);
718 zserv_close_client(client
);
723 * Create a new client.
725 * This is called when a new connection is accept()'d on the ZAPI socket. It
726 * initializes new client structure, notifies any subscribers of the connection
727 * event and spawns the client's thread.
730 * client's socket file descriptor
732 static struct zserv
*zserv_client_create(int sock
)
734 struct zserv
*client
;
736 MAX(ZEBRA_MAX_PACKET_SIZ
, sizeof(struct zapi_route
));
740 client
= XCALLOC(MTYPE_TMP
, sizeof(struct zserv
));
742 /* Make client input/output buffer. */
744 client
->ibuf_fifo
= stream_fifo_new();
745 client
->obuf_fifo
= stream_fifo_new();
746 client
->ibuf_work
= stream_new(stream_size
);
747 client
->obuf_work
= stream_new(stream_size
);
748 pthread_mutex_init(&client
->ibuf_mtx
, NULL
);
749 pthread_mutex_init(&client
->obuf_mtx
, NULL
);
750 client
->wb
= buffer_new(0);
751 TAILQ_INIT(&(client
->gr_info_queue
));
753 atomic_store_explicit(&client
->connect_time
, (uint32_t) monotime(NULL
),
754 memory_order_relaxed
);
756 /* Initialize flags */
757 for (afi
= AFI_IP
; afi
< AFI_MAX
; afi
++) {
758 for (i
= 0; i
< ZEBRA_ROUTE_MAX
; i
++)
759 client
->redist
[afi
][i
] = vrf_bitmap_init();
760 client
->redist_default
[afi
] = vrf_bitmap_init();
761 client
->ridinfo
[afi
] = vrf_bitmap_init();
764 /* Add this client to linked list. */
765 frr_with_mutex(&client_mutex
) {
766 listnode_add(zrouter
.client_list
, client
);
769 struct frr_pthread_attr zclient_pthr_attrs
= {
770 .start
= frr_pthread_attr_default
.start
,
771 .stop
= frr_pthread_attr_default
.stop
774 frr_pthread_new(&zclient_pthr_attrs
, "Zebra API client thread",
777 /* start read loop */
778 zserv_client_event(client
, ZSERV_CLIENT_READ
);
781 hook_call(zserv_client_connect
, client
);
784 frr_pthread_run(client
->pthread
, NULL
);
790 * Retrieve a client object by the complete tuple of
791 * {protocol, instance, session}. This version supports use
792 * from a different pthread: the object will be returned marked
793 * in-use. The caller *must* release the client object with the
794 * release_client() api, to ensure that the in-use marker is cleared properly.
796 struct zserv
*zserv_acquire_client(uint8_t proto
, unsigned short instance
,
799 struct zserv
*client
= NULL
;
801 frr_with_mutex(&client_mutex
) {
802 client
= find_client_internal(proto
, instance
, session_id
);
804 /* Don't return a dead/closed client object */
805 if (client
->is_closed
)
808 client
->busy_count
++;
816 * Release a client object that was acquired with the acquire_client() api.
817 * After this has been called, the caller must not use the client pointer -
818 * it may be freed if the client has closed.
820 void zserv_release_client(struct zserv
*client
)
823 * Once we've decremented the client object's refcount, it's possible
824 * for it to be deleted as soon as we release the lock, so we won't
825 * touch the object again.
827 frr_with_mutex(&client_mutex
) {
828 client
->busy_count
--;
830 if (client
->busy_count
<= 0) {
832 * No more users of the client object. If the client
833 * session is closed, schedule cleanup on the zebra
836 if (client
->is_closed
)
837 thread_add_event(zrouter
.master
,
838 zserv_handle_client_fail
,
839 client
, 0, &client
->t_cleanup
);
844 * Cleanup must take place on the zebra main pthread, so we've
845 * scheduled an event.
850 * Accept socket connection.
852 static int zserv_accept(struct thread
*thread
)
856 struct sockaddr_in client
;
859 accept_sock
= THREAD_FD(thread
);
861 /* Reregister myself. */
862 zserv_event(NULL
, ZSERV_ACCEPT
);
864 len
= sizeof(struct sockaddr_in
);
865 client_sock
= accept(accept_sock
, (struct sockaddr
*)&client
, &len
);
867 if (client_sock
< 0) {
868 flog_err_sys(EC_LIB_SOCKET
, "Can't accept zebra socket: %s",
869 safe_strerror(errno
));
873 /* Make client socket non-blocking. */
874 set_nonblocking(client_sock
);
876 /* Create new zebra client. */
877 zserv_client_create(client_sock
);
882 void zserv_close(void)
885 * On shutdown, let's close the socket down
886 * so that long running processes of killing the
887 * routing table doesn't leave us in a bad
888 * state where a client tries to reconnect
893 /* Free client list's mutex */
894 pthread_mutex_destroy(&client_mutex
);
897 void zserv_start(char *path
)
901 struct sockaddr_storage sa
;
904 if (!frr_zclient_addr(&sa
, &sa_len
, path
))
905 /* should be caught in zebra main() */
909 old_mask
= umask(0077);
911 /* Make UNIX domain socket. */
912 zsock
= socket(sa
.ss_family
, SOCK_STREAM
, 0);
914 flog_err_sys(EC_LIB_SOCKET
, "Can't create zserv socket: %s",
915 safe_strerror(errno
));
919 if (sa
.ss_family
!= AF_UNIX
) {
920 sockopt_reuseaddr(zsock
);
921 sockopt_reuseport(zsock
);
923 struct sockaddr_un
*suna
= (struct sockaddr_un
*)&sa
;
924 if (suna
->sun_path
[0])
925 unlink(suna
->sun_path
);
928 setsockopt_so_recvbuf(zsock
, 1048576);
929 setsockopt_so_sendbuf(zsock
, 1048576);
931 frr_with_privs((sa
.ss_family
!= AF_UNIX
) ? &zserv_privs
: NULL
) {
932 ret
= bind(zsock
, (struct sockaddr
*)&sa
, sa_len
);
935 flog_err_sys(EC_LIB_SOCKET
, "Can't bind zserv socket on %s: %s",
936 path
, safe_strerror(errno
));
942 ret
= listen(zsock
, 5);
944 flog_err_sys(EC_LIB_SOCKET
,
945 "Can't listen to zserv socket %s: %s", path
,
946 safe_strerror(errno
));
954 zserv_event(NULL
, ZSERV_ACCEPT
);
957 void zserv_event(struct zserv
*client
, enum zserv_event event
)
961 thread_add_read(zrouter
.master
, zserv_accept
, NULL
, zsock
,
964 case ZSERV_PROCESS_MESSAGES
:
965 thread_add_event(zrouter
.master
, zserv_process_messages
, client
,
966 0, &client
->t_process
);
968 case ZSERV_HANDLE_CLIENT_FAIL
:
969 thread_add_event(zrouter
.master
, zserv_handle_client_fail
,
970 client
, 0, &client
->t_cleanup
);
975 /* General purpose ---------------------------------------------------------- */
977 #define ZEBRA_TIME_BUF 32
978 static char *zserv_time_buf(time_t *time1
, char *buf
, int buflen
)
983 assert(buflen
>= ZEBRA_TIME_BUF
);
984 assert(time1
!= NULL
);
987 snprintf(buf
, buflen
, "never ");
991 now
= monotime(NULL
);
994 frrtime_to_interval(now
, buf
, buflen
);
999 /* Display client info details */
1000 static void zebra_show_client_detail(struct vty
*vty
, struct zserv
*client
)
1002 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1003 char wbuf
[ZEBRA_TIME_BUF
], nhbuf
[ZEBRA_TIME_BUF
], mbuf
[ZEBRA_TIME_BUF
];
1004 time_t connect_time
, last_read_time
, last_write_time
;
1005 uint32_t last_read_cmd
, last_write_cmd
;
1006 struct client_gr_info
*info
= NULL
;
1008 vty_out(vty
, "Client: %s", zebra_route_string(client
->proto
));
1009 if (client
->instance
)
1010 vty_out(vty
, " Instance: %u", client
->instance
);
1011 if (client
->session_id
)
1012 vty_out(vty
, " [%u]", client
->session_id
);
1015 vty_out(vty
, "------------------------ \n");
1016 vty_out(vty
, "FD: %d \n", client
->sock
);
1018 connect_time
= (time_t) atomic_load_explicit(&client
->connect_time
,
1019 memory_order_relaxed
);
1021 vty_out(vty
, "Connect Time: %s \n",
1022 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
));
1023 if (client
->nh_reg_time
) {
1024 vty_out(vty
, "Nexthop Registry Time: %s \n",
1025 zserv_time_buf(&client
->nh_reg_time
, nhbuf
,
1027 if (client
->nh_last_upd_time
)
1028 vty_out(vty
, "Nexthop Last Update Time: %s \n",
1029 zserv_time_buf(&client
->nh_last_upd_time
, mbuf
,
1032 vty_out(vty
, "No Nexthop Update sent\n");
1034 vty_out(vty
, "Not registered for Nexthop Updates\n");
1036 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1037 memory_order_relaxed
);
1038 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1039 memory_order_relaxed
);
1041 last_read_cmd
= atomic_load_explicit(&client
->last_read_cmd
,
1042 memory_order_relaxed
);
1043 last_write_cmd
= atomic_load_explicit(&client
->last_write_cmd
,
1044 memory_order_relaxed
);
1046 vty_out(vty
, "Last Msg Rx Time: %s \n",
1047 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
));
1048 vty_out(vty
, "Last Msg Tx Time: %s \n",
1049 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
));
1051 vty_out(vty
, "Last Rcvd Cmd: %s \n",
1052 zserv_command_string(last_read_cmd
));
1054 vty_out(vty
, "Last Sent Cmd: %s \n",
1055 zserv_command_string(last_write_cmd
));
1058 vty_out(vty
, "Type Add Update Del \n");
1059 vty_out(vty
, "================================================== \n");
1060 vty_out(vty
, "IPv4 %-12u%-12u%-12u\n", client
->v4_route_add_cnt
,
1061 client
->v4_route_upd8_cnt
, client
->v4_route_del_cnt
);
1062 vty_out(vty
, "IPv6 %-12u%-12u%-12u\n", client
->v6_route_add_cnt
,
1063 client
->v6_route_upd8_cnt
, client
->v6_route_del_cnt
);
1064 vty_out(vty
, "Redist:v4 %-12u%-12u%-12u\n", client
->redist_v4_add_cnt
,
1065 0, client
->redist_v4_del_cnt
);
1066 vty_out(vty
, "Redist:v6 %-12u%-12u%-12u\n", client
->redist_v6_add_cnt
,
1067 0, client
->redist_v6_del_cnt
);
1068 vty_out(vty
, "Connected %-12u%-12u%-12u\n", client
->ifadd_cnt
, 0,
1070 vty_out(vty
, "BFD peer %-12u%-12u%-12u\n", client
->bfd_peer_add_cnt
,
1071 client
->bfd_peer_upd8_cnt
, client
->bfd_peer_del_cnt
);
1072 vty_out(vty
, "NHT v4 %-12u%-12u%-12u\n",
1073 client
->v4_nh_watch_add_cnt
, 0, client
->v4_nh_watch_rem_cnt
);
1074 vty_out(vty
, "NHT v6 %-12u%-12u%-12u\n",
1075 client
->v6_nh_watch_add_cnt
, 0, client
->v6_nh_watch_rem_cnt
);
1076 vty_out(vty
, "VxLAN SG %-12u%-12u%-12u\n", client
->vxlan_sg_add_cnt
,
1077 0, client
->vxlan_sg_del_cnt
);
1078 vty_out(vty
, "Interface Up Notifications: %u\n", client
->ifup_cnt
);
1079 vty_out(vty
, "Interface Down Notifications: %u\n", client
->ifdown_cnt
);
1080 vty_out(vty
, "VNI add notifications: %u\n", client
->vniadd_cnt
);
1081 vty_out(vty
, "VNI delete notifications: %u\n", client
->vnidel_cnt
);
1082 vty_out(vty
, "L3-VNI add notifications: %u\n", client
->l3vniadd_cnt
);
1083 vty_out(vty
, "L3-VNI delete notifications: %u\n", client
->l3vnidel_cnt
);
1084 vty_out(vty
, "MAC-IP add notifications: %u\n", client
->macipadd_cnt
);
1085 vty_out(vty
, "MAC-IP delete notifications: %u\n", client
->macipdel_cnt
);
1086 vty_out(vty
, "ES add notifications: %u\n", client
->local_es_add_cnt
);
1087 vty_out(vty
, "ES delete notifications: %u\n", client
->local_es_del_cnt
);
1088 vty_out(vty
, "ES-EVI add notifications: %u\n",
1089 client
->local_es_evi_add_cnt
);
1090 vty_out(vty
, "ES-EVI delete notifications: %u\n",
1091 client
->local_es_evi_del_cnt
);
1093 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1094 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1095 vty_out(vty
, "Capabilities : ");
1096 switch (info
->capabilities
) {
1097 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1098 vty_out(vty
, "Graceful Restart\n");
1100 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1101 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1102 case ZEBRA_CLIENT_GR_DISABLE
:
1103 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1104 vty_out(vty
, "None\n");
1109 #if defined DEV_BUILD
1110 vty_out(vty
, "Input Fifo: %zu:%zu Output Fifo: %zu:%zu\n",
1111 client
->ibuf_fifo
->count
, client
->ibuf_fifo
->max_count
,
1112 client
->obuf_fifo
->count
, client
->obuf_fifo
->max_count
);
1117 /* Display stale client information */
1118 static void zebra_show_stale_client_detail(struct vty
*vty
,
1119 struct zserv
*client
)
1121 char buf
[PREFIX2STR_BUFFER
];
1123 struct client_gr_info
*info
= NULL
;
1124 struct zserv
*s
= NULL
;
1125 bool first_p
= true;
1127 TAILQ_FOREACH (info
, &client
->gr_info_queue
, gr_info
) {
1129 vty_out(vty
, "Stale Client Information\n");
1130 vty_out(vty
, "------------------------\n");
1132 if (client
->instance
)
1133 vty_out(vty
, " Instance: %u", client
->instance
);
1134 if (client
->session_id
)
1135 vty_out(vty
, " [%u]", client
->session_id
);
1140 vty_out(vty
, "VRF : %s\n", vrf_id_to_name(info
->vrf_id
));
1141 vty_out(vty
, "Capabilities : ");
1142 switch (info
->capabilities
) {
1143 case ZEBRA_CLIENT_GR_CAPABILITIES
:
1144 vty_out(vty
, "Graceful Restart\n");
1146 case ZEBRA_CLIENT_ROUTE_UPDATE_COMPLETE
:
1147 case ZEBRA_CLIENT_ROUTE_UPDATE_PENDING
:
1148 case ZEBRA_CLIENT_GR_DISABLE
:
1149 case ZEBRA_CLIENT_RIB_STALE_TIME
:
1150 vty_out(vty
, "None\n");
1154 if (ZEBRA_CLIENT_GR_ENABLED(info
->capabilities
)) {
1155 if (info
->stale_client_ptr
) {
1156 s
= (struct zserv
*)(info
->stale_client_ptr
);
1157 uptime
= monotime(NULL
);
1158 uptime
-= s
->restart_time
;
1160 frrtime_to_interval(uptime
, buf
, sizeof(buf
));
1162 vty_out(vty
, "Last restart time : %s ago\n",
1165 vty_out(vty
, "Stalepath removal time: %d sec\n",
1166 info
->stale_removal_time
);
1167 if (info
->t_stale_removal
) {
1169 "Stale delete timer: %ld sec\n",
1170 thread_timer_remain_second(
1171 info
->t_stale_removal
));
1174 vty_out(vty
, "Current AFI : %d\n", info
->current_afi
);
1175 if (info
->current_prefix
) {
1176 prefix2str(info
->current_prefix
, buf
,
1178 vty_out(vty
, "Current prefix : %s\n", buf
);
1186 static void zebra_show_client_brief(struct vty
*vty
, struct zserv
*client
)
1188 char cbuf
[ZEBRA_TIME_BUF
], rbuf
[ZEBRA_TIME_BUF
];
1189 char wbuf
[ZEBRA_TIME_BUF
];
1190 time_t connect_time
, last_read_time
, last_write_time
;
1192 connect_time
= (time_t)atomic_load_explicit(&client
->connect_time
,
1193 memory_order_relaxed
);
1194 last_read_time
= (time_t)atomic_load_explicit(&client
->last_read_time
,
1195 memory_order_relaxed
);
1196 last_write_time
= (time_t)atomic_load_explicit(&client
->last_write_time
,
1197 memory_order_relaxed
);
1199 vty_out(vty
, "%-10s%12s %12s%12s%8d/%-8d%8d/%-8d\n",
1200 zebra_route_string(client
->proto
),
1201 zserv_time_buf(&connect_time
, cbuf
, ZEBRA_TIME_BUF
),
1202 zserv_time_buf(&last_read_time
, rbuf
, ZEBRA_TIME_BUF
),
1203 zserv_time_buf(&last_write_time
, wbuf
, ZEBRA_TIME_BUF
),
1204 client
->v4_route_add_cnt
+ client
->v4_route_upd8_cnt
,
1205 client
->v4_route_del_cnt
,
1206 client
->v6_route_add_cnt
+ client
->v6_route_upd8_cnt
,
1207 client
->v6_route_del_cnt
);
1211 * Common logic that searches the client list for a zapi client; this
1212 * MUST be called holding the client list mutex.
1214 static struct zserv
*find_client_internal(uint8_t proto
,
1215 unsigned short instance
,
1216 uint32_t session_id
)
1218 struct listnode
*node
, *nnode
;
1219 struct zserv
*client
= NULL
;
1221 for (ALL_LIST_ELEMENTS(zrouter
.client_list
, node
, nnode
, client
)) {
1222 if (client
->proto
== proto
&& client
->instance
== instance
&&
1223 client
->session_id
== session_id
)
1231 * Public api that searches for a client session; this version is
1232 * used from the zebra main pthread.
1234 struct zserv
*zserv_find_client(uint8_t proto
, unsigned short instance
)
1236 struct zserv
*client
;
1238 frr_with_mutex(&client_mutex
) {
1239 client
= find_client_internal(proto
, instance
, 0);
1246 * Retrieve a client by its protocol, instance number, and session id.
1248 struct zserv
*zserv_find_client_session(uint8_t proto
, unsigned short instance
,
1249 uint32_t session_id
)
1251 struct zserv
*client
;
1253 frr_with_mutex(&client_mutex
) {
1254 client
= find_client_internal(proto
, instance
, session_id
);
1261 /* This command is for debugging purpose. */
1262 DEFUN (show_zebra_client
,
1263 show_zebra_client_cmd
,
1264 "show zebra client",
1267 "Client information\n")
1269 struct listnode
*node
;
1270 struct zserv
*client
;
1272 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
)) {
1273 zebra_show_client_detail(vty
, client
);
1274 /* Show GR info if present */
1275 zebra_show_stale_client_detail(vty
, client
);
1281 /* This command is for debugging purpose. */
1282 DEFUN (show_zebra_client_summary
,
1283 show_zebra_client_summary_cmd
,
1284 "show zebra client summary",
1287 "Client information brief\n"
1290 struct listnode
*node
;
1291 struct zserv
*client
;
1294 "Name Connect Time Last Read Last Write IPv4 Routes IPv6 Routes \n");
1296 "--------------------------------------------------------------------------------\n");
1298 for (ALL_LIST_ELEMENTS_RO(zrouter
.client_list
, node
, client
))
1299 zebra_show_client_brief(vty
, client
);
1301 vty_out(vty
, "Routes column shows (added+updated)/deleted\n");
1305 void zserv_init(void)
1307 /* Client list init. */
1308 zrouter
.client_list
= list_new();
1309 zrouter
.stale_client_list
= list_new();
1313 pthread_mutex_init(&client_mutex
, NULL
);
1315 install_element(ENABLE_NODE
, &show_zebra_client_cmd
);
1316 install_element(ENABLE_NODE
, &show_zebra_client_summary_cmd
);