]> git.proxmox.com Git - mirror_frr.git/blame - zebra/zserv.c
zebra: include zebra nexthop debug in show runn
[mirror_frr.git] / zebra / zserv.c
CommitLineData
bf094f69
QY
1/*
2 * Zebra API server.
3 * Portions:
4 * Copyright (C) 1997-1999 Kunihiro Ishiguro
5 * Copyright (C) 2015-2018 Cumulus Networks, Inc.
6 * et al.
718e3744 7 *
bf094f69
QY
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)
11 * any later version.
718e3744 12 *
bf094f69
QY
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
16 * more details.
718e3744 17 *
896014f4
DL
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
718e3744 21 */
22
23#include <zebra.h>
d8647095
QY
24
25/* clang-format off */
bf094f69
QY
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 */
35
36#include "lib/buffer.h" /* for BUFFER_EMPTY, BUFFER_ERROR, BUFFE... */
37#include "lib/command.h" /* for vty, install_element, CMD_SUCCESS... */
453844ab 38#include "lib/hook.h" /* for DEFINE_HOOK, DEFINE_KOOH, hook_call */
bf094f69
QY
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... */
52f6868d 55#include "lib/frr_pthread.h" /* for frr_pthread_new, frr_pthread_stop... */
ae6670d0 56#include "lib/frratomic.h" /* for atomic_load_explicit, atomic_stor... */
174482ef 57#include "lib/lib_errors.h" /* for generic ferr ids */
bf094f69
QY
58
59#include "zebra/debug.h" /* for various debugging macros */
bf094f69 60#include "zebra/rib.h" /* for rib_score_proto */
bf094f69 61#include "zebra/zapi_msg.h" /* for zserv_handle_commands */
bf094f69 62#include "zebra/zebra_vrf.h" /* for zebra_vrf_lookup_by_id, zvrf */
d8647095 63#include "zebra/zserv.h" /* for zserv */
3801e764 64#include "zebra/zebra_router.h"
364fed6b 65#include "zebra/zebra_errors.h" /* for error messages */
d8647095 66/* clang-format on */
6b0655a2 67
1002497a 68/* privileges */
edd7c245 69extern struct zebra_privs_t zserv_privs;
453844ab 70
cc3d8834
DS
71/* The listener socket for clients connecting to us */
72static int zsock;
73
329e35da 74/*
f2efe6a3 75 * Client thread events.
329e35da 76 *
f2efe6a3 77 * These are used almost exclusively by client threads to drive their own event
24f8f979 78 * loops. The only exception is in zserv_client_create(), which pushes an
21ccc0cf 79 * initial ZSERV_CLIENT_READ event to start the API handler loop.
329e35da 80 */
21ccc0cf
QY
81enum zserv_client_event {
82 /* Schedule a socket read */
83 ZSERV_CLIENT_READ,
84 /* Schedule a buffer write */
85 ZSERV_CLIENT_WRITE,
21ccc0cf 86};
453844ab 87
21ccc0cf
QY
88/*
89 * Main thread events.
90 *
91 * These are used by client threads to notify the main thread about various
92 * events and to make processing requests.
93 */
94enum zserv_event {
95 /* Schedule listen job on Zebra API socket */
96 ZSERV_ACCEPT,
97 /* The calling client has packets on its input buffer */
98 ZSERV_PROCESS_MESSAGES,
99 /* The calling client wishes to be killed */
f3e33b69 100 ZSERV_HANDLE_CLIENT_FAIL,
21ccc0cf
QY
101};
102
103/*
104 * Zebra server event driver for all client threads.
105 *
106 * This is essentially a wrapper around thread_add_event() that centralizes
107 * those scheduling calls into one place.
108 *
109 * All calls to this function schedule an event on the pthread running the
110 * provided client.
111 *
112 * client
113 * the client in question, and thread target
114 *
115 * event
116 * the event to notify them about
117 */
118static void zserv_client_event(struct zserv *client,
119 enum zserv_client_event event);
120
121/*
122 * Zebra server event driver for the main thread.
123 *
124 * This is essentially a wrapper around thread_add_event() that centralizes
125 * those scheduling calls into one place.
126 *
127 * All calls to this function schedule an event on Zebra's main pthread.
128 *
129 * client
130 * the client in question
131 *
132 * event
133 * the event to notify the main thread about
134 */
135static void zserv_event(struct zserv *client, enum zserv_event event);
e16abbb3 136
e16abbb3 137
f2efe6a3 138/* Client thread lifecycle -------------------------------------------------- */
e16abbb3 139
9bcbcae2 140/*
1002497a
QY
141 * Log zapi message to zlog.
142 *
143 * errmsg (optional)
144 * Debugging message
9bcbcae2 145 *
1002497a
QY
146 * msg
147 * The message
148 *
149 * hdr (optional)
150 * The message header
9bcbcae2 151 */
49b3b01f
QY
152void zserv_log_message(const char *errmsg, struct stream *msg,
153 struct zmsghdr *hdr)
1002497a
QY
154{
155 zlog_debug("Rx'd ZAPI message");
156 if (errmsg)
157 zlog_debug("%s", errmsg);
158 if (hdr) {
159 zlog_debug(" Length: %d", hdr->length);
160 zlog_debug("Command: %s", zserv_command_string(hdr->command));
161 zlog_debug(" VRF: %u", hdr->vrf_id);
162 }
163 zlog_hexdump(msg->data, STREAM_READABLE(msg));
9bcbcae2
QY
164}
165
f2efe6a3
QY
166/*
167 * Gracefully shut down a client connection.
168 *
f3e33b69
QY
169 * Cancel any pending tasks for the client's thread. Then schedule a task on
170 * the main thread to shut down the calling thread.
f2efe6a3 171 *
c0226378
QY
172 * It is not safe to close the client socket in this function. The socket is
173 * owned by the main thread.
174 *
f2efe6a3
QY
175 * Must be called from the client pthread, never the main thread.
176 */
f3e33b69 177static void zserv_client_fail(struct zserv *client)
f2efe6a3 178{
e914ccbe 179 flog_warn(EC_ZEBRA_CLIENT_IO_ERROR,
9df414fe 180 "Client '%s' encountered an error and is shutting down.",
f3e33b69
QY
181 zebra_route_string(client->proto));
182
c2ca5ee6 183 atomic_store_explicit(&client->pthread->running, false,
f3e33b69 184 memory_order_relaxed);
c0226378 185
f2efe6a3
QY
186 THREAD_OFF(client->t_read);
187 THREAD_OFF(client->t_write);
f3e33b69 188 zserv_event(client, ZSERV_HANDLE_CLIENT_FAIL);
f2efe6a3
QY
189}
190
1002497a 191/*
370d8dad
QY
192 * Write all pending messages to client socket.
193 *
29bed51b
QY
194 * This function first attempts to flush any buffered data. If unsuccessful,
195 * the function reschedules itself and returns. If successful, it pops all
196 * available messages from the output queue and continues to write data
197 * directly to the socket until the socket would block. If the socket never
198 * blocks and all data is written, the function returns without rescheduling
199 * itself. If the socket ends up throwing EWOULDBLOCK, the remaining data is
200 * buffered and the function reschedules itself.
370d8dad 201 *
29bed51b
QY
202 * The utility of the buffer is that it allows us to vastly reduce lock
203 * contention by allowing us to pop *all* messages off the output queue at once
204 * instead of locking and unlocking each time we want to pop a single message
205 * off the queue. The same thing could arguably be accomplished faster by
206 * allowing the main thread to write directly into the buffer instead of
207 * enqueuing packets onto an intermediary queue, but the intermediary queue
208 * allows us to expose information about input and output queues to the user in
209 * terms of number of packets rather than size of data.
1002497a
QY
210 */
211static int zserv_write(struct thread *thread)
d62a17ae 212{
1002497a
QY
213 struct zserv *client = THREAD_ARG(thread);
214 struct stream *msg;
ce4f1050 215 uint32_t wcmd = 0;
29bed51b
QY
216 struct stream_fifo *cache;
217
218 /* If we have any data pending, try to flush it first */
ccd51bd2 219 switch (buffer_flush_all(client->wb, client->sock)) {
29bed51b
QY
220 case BUFFER_ERROR:
221 goto zwrite_fail;
222 case BUFFER_PENDING:
ccd51bd2
QY
223 atomic_store_explicit(&client->last_write_time,
224 (uint32_t)monotime(NULL),
225 memory_order_relaxed);
29bed51b
QY
226 zserv_client_event(client, ZSERV_CLIENT_WRITE);
227 return 0;
228 case BUFFER_EMPTY:
229 break;
230 }
231
232 cache = stream_fifo_new();
89f4e507 233
00dffa8c 234 frr_with_mutex(&client->obuf_mtx) {
c2ca5ee6 235 while (stream_fifo_head(client->obuf_fifo))
370d8dad
QY
236 stream_fifo_push(cache,
237 stream_fifo_pop(client->obuf_fifo));
329e35da 238 }
329e35da 239
ccd51bd2
QY
240 if (cache->tail) {
241 msg = cache->tail;
370d8dad 242 stream_set_getp(msg, 0);
6e8e0925 243 wcmd = stream_getw_from(msg, ZAPI_HEADER_CMD_LOCATION);
ccd51bd2 244 }
822167e7 245
ccd51bd2
QY
246 while (stream_fifo_head(cache)) {
247 msg = stream_fifo_pop(cache);
248 buffer_put(client->wb, STREAM_DATA(msg), stream_get_endp(msg));
370d8dad
QY
249 stream_free(msg);
250 }
1002497a 251
822167e7 252 stream_fifo_free(cache);
1002497a 253
ccd51bd2
QY
254 /* If we have any data pending, try to flush it first */
255 switch (buffer_flush_all(client->wb, client->sock)) {
256 case BUFFER_ERROR:
257 goto zwrite_fail;
258 case BUFFER_PENDING:
259 atomic_store_explicit(&client->last_write_time,
260 (uint32_t)monotime(NULL),
261 memory_order_relaxed);
262 zserv_client_event(client, ZSERV_CLIENT_WRITE);
263 return 0;
ccd51bd2
QY
264 case BUFFER_EMPTY:
265 break;
266 }
267
370d8dad
QY
268 atomic_store_explicit(&client->last_write_cmd, wcmd,
269 memory_order_relaxed);
1002497a 270
52f6868d 271 atomic_store_explicit(&client->last_write_time,
370d8dad 272 (uint32_t)monotime(NULL), memory_order_relaxed);
52f6868d 273
1002497a 274 return 0;
29bed51b
QY
275
276zwrite_fail:
e914ccbe 277 flog_warn(EC_ZEBRA_CLIENT_WRITE_FAILED,
9df414fe 278 "%s: could not write to %s [fd = %d], closing.", __func__,
29bed51b 279 zebra_route_string(client->proto), client->sock);
f3e33b69 280 zserv_client_fail(client);
29bed51b 281 return 0;
0c5e7be5
DS
282}
283
329e35da
QY
284/*
285 * Read and process data from a client socket.
286 *
287 * The responsibilities here are to read raw data from the client socket,
288 * validate the header, encapsulate it into a single stream object, push it
289 * onto the input queue and then notify the main thread that there is new data
290 * available.
291 *
292 * This function first looks for any data in the client structure's working
293 * input buffer. If data is present, it is assumed that reading stopped in a
294 * previous invocation of this task and needs to be resumed to finish a message.
295 * Otherwise, the socket data stream is assumed to be at the beginning of a new
296 * ZAPI message (specifically at the header). The header is read and validated.
297 * If the header passed validation then the length field found in the header is
298 * used to compute the total length of the message. That much data is read (but
299 * not inspected), appended to the header, placed into a stream and pushed onto
300 * the client's input queue. A task is then scheduled on the main thread to
301 * process the client's input queue. Finally, if all of this was successful,
302 * this task reschedules itself.
303 *
304 * Any failure in any of these actions is handled by terminating the client.
305 */
1002497a 306static int zserv_read(struct thread *thread)
0c5e7be5 307{
ae6670d0 308 struct zserv *client = THREAD_ARG(thread);
0c5e7be5 309 int sock;
0c5e7be5 310 size_t already;
ae6670d0
QY
311 struct stream_fifo *cache;
312 uint32_t p2p_orig;
313
1572d9af
QY
314 uint32_t p2p;
315 struct zmsghdr hdr;
316
5ec5a716 317 p2p_orig = atomic_load_explicit(&zrouter.packets_to_process,
ae6670d0
QY
318 memory_order_relaxed);
319 cache = stream_fifo_new();
370d8dad 320 p2p = p2p_orig;
0c5e7be5 321 sock = THREAD_FD(thread);
0c5e7be5 322
43ea2c76 323 while (p2p) {
107afcd1
QY
324 ssize_t nb;
325 bool hdrvalid;
326 char errmsg[256];
327
1002497a
QY
328 already = stream_get_endp(client->ibuf_work);
329
5a762c8a 330 /* Read length and command (if we don't have it already). */
1002497a
QY
331 if (already < ZEBRA_HEADER_SIZE) {
332 nb = stream_read_try(client->ibuf_work, sock,
333 ZEBRA_HEADER_SIZE - already);
03f29018
DS
334 if ((nb == 0 || nb == -1)) {
335 if (IS_ZEBRA_DEBUG_EVENT)
336 zlog_debug("connection closed socket [%d]",
337 sock);
1002497a 338 goto zread_fail;
03f29018 339 }
1002497a 340 if (nb != (ssize_t)(ZEBRA_HEADER_SIZE - already)) {
5a762c8a 341 /* Try again later. */
1002497a 342 break;
5a762c8a
DS
343 }
344 already = ZEBRA_HEADER_SIZE;
0c5e7be5 345 }
0c5e7be5 346
5a762c8a 347 /* Reset to read from the beginning of the incoming packet. */
1002497a 348 stream_set_getp(client->ibuf_work, 0);
0c5e7be5 349
5a762c8a 350 /* Fetch header values */
1002497a 351 hdrvalid = zapi_parse_header(client->ibuf_work, &hdr);
0c5e7be5 352
1002497a
QY
353 if (!hdrvalid) {
354 snprintf(errmsg, sizeof(errmsg),
355 "%s: Message has corrupt header", __func__);
356 zserv_log_message(errmsg, client->ibuf_work, NULL);
357 goto zread_fail;
0c5e7be5 358 }
1002497a
QY
359
360 /* Validate header */
361 if (hdr.marker != ZEBRA_HEADER_MARKER
362 || hdr.version != ZSERV_VERSION) {
363 snprintf(
364 errmsg, sizeof(errmsg),
365 "Message has corrupt header\n%s: socket %d version mismatch, marker %d, version %d",
366 __func__, sock, hdr.marker, hdr.version);
367 zserv_log_message(errmsg, client->ibuf_work, &hdr);
368 goto zread_fail;
5a762c8a 369 }
1002497a
QY
370 if (hdr.length < ZEBRA_HEADER_SIZE) {
371 snprintf(
372 errmsg, sizeof(errmsg),
373 "Message has corrupt header\n%s: socket %d message length %u is less than header size %d",
374 __func__, sock, hdr.length, ZEBRA_HEADER_SIZE);
375 zserv_log_message(errmsg, client->ibuf_work, &hdr);
376 goto zread_fail;
377 }
378 if (hdr.length > STREAM_SIZE(client->ibuf_work)) {
379 snprintf(
380 errmsg, sizeof(errmsg),
381 "Message has corrupt header\n%s: socket %d message length %u exceeds buffer size %lu",
382 __func__, sock, hdr.length,
383 (unsigned long)STREAM_SIZE(client->ibuf_work));
1572d9af 384 zserv_log_message(errmsg, client->ibuf_work, &hdr);
1002497a 385 goto zread_fail;
0c5e7be5 386 }
0c5e7be5 387
5a762c8a 388 /* Read rest of data. */
1002497a
QY
389 if (already < hdr.length) {
390 nb = stream_read_try(client->ibuf_work, sock,
391 hdr.length - already);
03f29018
DS
392 if ((nb == 0 || nb == -1)) {
393 if (IS_ZEBRA_DEBUG_EVENT)
394 zlog_debug(
395 "connection closed [%d] when reading zebra data",
396 sock);
1002497a 397 goto zread_fail;
03f29018 398 }
1002497a 399 if (nb != (ssize_t)(hdr.length - already)) {
5a762c8a 400 /* Try again later. */
1002497a 401 break;
5a762c8a
DS
402 }
403 }
0c5e7be5 404
5a762c8a 405 /* Debug packet information. */
494247b5
DS
406 if (IS_ZEBRA_DEBUG_PACKET)
407 zlog_debug("zebra message[%s:%u:%u] comes from socket [%d]",
408 zserv_command_string(hdr.command),
409 hdr.vrf_id, hdr.length,
996c9314 410 sock);
0c5e7be5 411
1572d9af
QY
412 stream_set_getp(client->ibuf_work, 0);
413 struct stream *msg = stream_dup(client->ibuf_work);
414
415 stream_fifo_push(cache, msg);
416 stream_reset(client->ibuf_work);
43ea2c76 417 p2p--;
1572d9af
QY
418 }
419
420 if (p2p < p2p_orig) {
421 /* update session statistics */
52f6868d
QY
422 atomic_store_explicit(&client->last_read_time, monotime(NULL),
423 memory_order_relaxed);
424 atomic_store_explicit(&client->last_read_cmd, hdr.command,
425 memory_order_relaxed);
5a762c8a 426
1572d9af 427 /* publish read packets on client's input queue */
00dffa8c 428 frr_with_mutex(&client->ibuf_mtx) {
1572d9af
QY
429 while (cache->head)
430 stream_fifo_push(client->ibuf_fifo,
431 stream_fifo_pop(cache));
329e35da 432 }
822167e7
QY
433
434 /* Schedule job to process those packets */
435 zserv_event(client, ZSERV_PROCESS_MESSAGES);
436
d62a17ae 437 }
438
1002497a 439 if (IS_ZEBRA_DEBUG_PACKET)
494247b5
DS
440 zlog_debug("Read %d packets from client: %s", p2p_orig - p2p,
441 zebra_route_string(client->proto));
1002497a 442
1002497a 443 /* Reschedule ourselves */
21ccc0cf 444 zserv_client_event(client, ZSERV_CLIENT_READ);
1002497a 445
1572d9af
QY
446 stream_fifo_free(cache);
447
d62a17ae 448 return 0;
1002497a
QY
449
450zread_fail:
1572d9af 451 stream_fifo_free(cache);
f3e33b69 452 zserv_client_fail(client);
1002497a 453 return -1;
718e3744 454}
455
21ccc0cf
QY
456static void zserv_client_event(struct zserv *client,
457 enum zserv_client_event event)
1002497a
QY
458{
459 switch (event) {
21ccc0cf 460 case ZSERV_CLIENT_READ:
329e35da
QY
461 thread_add_read(client->pthread->master, zserv_read, client,
462 client->sock, &client->t_read);
1002497a 463 break;
21ccc0cf 464 case ZSERV_CLIENT_WRITE:
329e35da 465 thread_add_write(client->pthread->master, zserv_write, client,
1002497a
QY
466 client->sock, &client->t_write);
467 break;
468 }
469}
718e3744 470
f2efe6a3
QY
471/* Main thread lifecycle ---------------------------------------------------- */
472
f2efe6a3
QY
473/*
474 * Read and process messages from a client.
475 *
476 * This task runs on the main pthread. It is scheduled by client pthreads when
477 * they have new messages available on their input queues. The client is passed
478 * as the task argument.
479 *
480 * Each message is popped off the client's input queue and the action associated
481 * with the message is executed. This proceeds until there are no more messages,
904e0d88
QY
482 * an error occurs, or the processing limit is reached.
483 *
2561d12e 484 * The client's I/O thread can push at most zrouter.packets_to_process messages
822167e7 485 * onto the input buffer before notifying us there are packets to read. As long
2561d12e 486 * as we always process zrouter.packets_to_process messages here, then we can
822167e7
QY
487 * rely on the read thread to handle queuing this task enough times to process
488 * everything on the input queue.
f2efe6a3
QY
489 */
490static int zserv_process_messages(struct thread *thread)
491{
492 struct zserv *client = THREAD_ARG(thread);
f2efe6a3 493 struct stream *msg;
904e0d88 494 struct stream_fifo *cache = stream_fifo_new();
5ec5a716 495 uint32_t p2p = zrouter.packets_to_process;
dded2aba 496 bool need_resched = false;
f2efe6a3 497
00dffa8c 498 frr_with_mutex(&client->ibuf_mtx) {
822167e7
QY
499 uint32_t i;
500 for (i = 0; i < p2p && stream_fifo_head(client->ibuf_fifo);
501 ++i) {
502 msg = stream_fifo_pop(client->ibuf_fifo);
503 stream_fifo_push(cache, msg);
504 }
904e0d88 505
822167e7 506 msg = NULL;
dded2aba
MS
507
508 /* Need to reschedule processing work if there are still
509 * packets in the fifo.
510 */
511 if (stream_fifo_head(client->ibuf_fifo))
512 need_resched = true;
f2efe6a3 513 }
f2efe6a3 514
822167e7 515 while (stream_fifo_head(cache)) {
904e0d88 516 msg = stream_fifo_pop(cache);
904e0d88
QY
517 zserv_handle_commands(client, msg);
518 stream_free(msg);
519 }
520
521 stream_fifo_free(cache);
522
dded2aba
MS
523 /* Reschedule ourselves if necessary */
524 if (need_resched)
525 zserv_event(client, ZSERV_PROCESS_MESSAGES);
526
f2efe6a3
QY
527 return 0;
528}
529
21ccc0cf 530int zserv_send_message(struct zserv *client, struct stream *msg)
f2efe6a3 531{
00dffa8c 532 frr_with_mutex(&client->obuf_mtx) {
f2efe6a3 533 stream_fifo_push(client->obuf_fifo, msg);
f2efe6a3 534 }
ccd51bd2
QY
535
536 zserv_client_event(client, ZSERV_CLIENT_WRITE);
537
f2efe6a3
QY
538 return 0;
539}
540
541
542/* Hooks for client connect / disconnect */
21ccc0cf
QY
543DEFINE_HOOK(zserv_client_connect, (struct zserv *client), (client));
544DEFINE_KOOH(zserv_client_close, (struct zserv *client), (client));
f2efe6a3
QY
545
546/*
547 * Deinitialize zebra client.
548 *
549 * - Deregister and deinitialize related internal resources
550 * - Gracefully close socket
551 * - Free associated resources
552 * - Free client structure
553 *
554 * This does *not* take any action on the struct thread * fields. These are
555 * managed by the owning pthread and any tasks associated with them must have
556 * been stopped prior to invoking this function.
557 */
21ccc0cf 558static void zserv_client_free(struct zserv *client)
f2efe6a3 559{
21ccc0cf 560 hook_call(zserv_client_close, client);
f2efe6a3
QY
561
562 /* Close file descriptor. */
563 if (client->sock) {
564 unsigned long nroutes;
565
566 close(client->sock);
a580357a 567
f2efe6a3
QY
568 nroutes = rib_score_proto(client->proto, client->instance);
569 zlog_notice(
570 "client %d disconnected. %lu %s routes removed from the rib",
571 client->sock, nroutes,
572 zebra_route_string(client->proto));
573 client->sock = -1;
574 }
575
576 /* Free stream buffers. */
577 if (client->ibuf_work)
578 stream_free(client->ibuf_work);
579 if (client->obuf_work)
580 stream_free(client->obuf_work);
581 if (client->ibuf_fifo)
582 stream_fifo_free(client->ibuf_fifo);
583 if (client->obuf_fifo)
584 stream_fifo_free(client->obuf_fifo);
585 if (client->wb)
586 buffer_free(client->wb);
587
588 /* Free buffer mutexes */
589 pthread_mutex_destroy(&client->obuf_mtx);
590 pthread_mutex_destroy(&client->ibuf_mtx);
591
592 /* Free bitmaps. */
49db7a7b 593 for (afi_t afi = AFI_IP; afi < AFI_MAX; afi++) {
f2efe6a3
QY
594 for (int i = 0; i < ZEBRA_ROUTE_MAX; i++)
595 vrf_bitmap_free(client->redist[afi][i]);
596
49db7a7b
RW
597 vrf_bitmap_free(client->redist_default[afi]);
598 }
f2efe6a3
QY
599 vrf_bitmap_free(client->ridinfo);
600
601 XFREE(MTYPE_TMP, client);
602}
603
f3e33b69 604void zserv_close_client(struct zserv *client)
f2efe6a3 605{
f3e33b69 606 /* synchronously stop and join pthread */
f2efe6a3
QY
607 frr_pthread_stop(client->pthread, NULL);
608
f3e33b69
QY
609 if (IS_ZEBRA_DEBUG_EVENT)
610 zlog_debug("Closing client '%s'",
611 zebra_route_string(client->proto));
612
3801e764 613 thread_cancel_event(zrouter.master, client);
f3e33b69 614 THREAD_OFF(client->t_cleanup);
dded2aba 615 THREAD_OFF(client->t_process);
f3e33b69
QY
616
617 /* destroy pthread */
f2efe6a3
QY
618 frr_pthread_destroy(client->pthread);
619 client->pthread = NULL;
620
f3e33b69 621 /* remove from client list */
161e9ab7 622 listnode_delete(zrouter.client_list, client);
f3e33b69
QY
623
624 /* delete client */
21ccc0cf 625 zserv_client_free(client);
f3e33b69
QY
626}
627
628/*
629 * This task is scheduled by a ZAPI client pthread on the main pthread when it
630 * wants to stop itself. When this executes, the client connection should
631 * already have been closed and the thread will most likely have died, but its
632 * resources still need to be cleaned up.
633 */
634static int zserv_handle_client_fail(struct thread *thread)
635{
636 struct zserv *client = THREAD_ARG(thread);
637
638 zserv_close_client(client);
f2efe6a3
QY
639 return 0;
640}
641
642/*
643 * Create a new client.
644 *
645 * This is called when a new connection is accept()'d on the ZAPI socket. It
646 * initializes new client structure, notifies any subscribers of the connection
647 * event and spawns the client's thread.
648 *
649 * sock
650 * client's socket file descriptor
651 */
2875801f 652static struct zserv *zserv_client_create(int sock)
f2efe6a3
QY
653{
654 struct zserv *client;
f3f45626
DS
655 size_t stream_size =
656 MAX(ZEBRA_MAX_PACKET_SIZ, sizeof(struct zapi_route));
f2efe6a3
QY
657 int i;
658 afi_t afi;
659
660 client = XCALLOC(MTYPE_TMP, sizeof(struct zserv));
661
662 /* Make client input/output buffer. */
663 client->sock = sock;
664 client->ibuf_fifo = stream_fifo_new();
665 client->obuf_fifo = stream_fifo_new();
f3f45626
DS
666 client->ibuf_work = stream_new(stream_size);
667 client->obuf_work = stream_new(stream_size);
f2efe6a3
QY
668 pthread_mutex_init(&client->ibuf_mtx, NULL);
669 pthread_mutex_init(&client->obuf_mtx, NULL);
670 client->wb = buffer_new(0);
671
f2efe6a3
QY
672 atomic_store_explicit(&client->connect_time, (uint32_t) monotime(NULL),
673 memory_order_relaxed);
674
675 /* Initialize flags */
49db7a7b 676 for (afi = AFI_IP; afi < AFI_MAX; afi++) {
f2efe6a3
QY
677 for (i = 0; i < ZEBRA_ROUTE_MAX; i++)
678 client->redist[afi][i] = vrf_bitmap_init();
49db7a7b
RW
679 client->redist_default[afi] = vrf_bitmap_init();
680 }
f2efe6a3
QY
681 client->ridinfo = vrf_bitmap_init();
682
f2efe6a3 683 /* Add this client to linked list. */
161e9ab7 684 listnode_add(zrouter.client_list, client);
f2efe6a3
QY
685
686 struct frr_pthread_attr zclient_pthr_attrs = {
f2efe6a3
QY
687 .start = frr_pthread_attr_default.start,
688 .stop = frr_pthread_attr_default.stop
689 };
690 client->pthread =
57019528
CS
691 frr_pthread_new(&zclient_pthr_attrs, "Zebra API client thread",
692 "zebra_apic");
f2efe6a3 693
f2efe6a3 694 /* start read loop */
21ccc0cf 695 zserv_client_event(client, ZSERV_CLIENT_READ);
f2efe6a3
QY
696
697 /* call callbacks */
21ccc0cf 698 hook_call(zserv_client_connect, client);
f2efe6a3
QY
699
700 /* start pthread */
701 frr_pthread_run(client->pthread, NULL);
2875801f
QY
702
703 return client;
f2efe6a3 704}
329e35da 705
21ccc0cf
QY
706/*
707 * Accept socket connection.
708 */
709static int zserv_accept(struct thread *thread)
718e3744 710{
d62a17ae 711 int accept_sock;
712 int client_sock;
713 struct sockaddr_in client;
714 socklen_t len;
715
716 accept_sock = THREAD_FD(thread);
718e3744 717
d62a17ae 718 /* Reregister myself. */
21ccc0cf 719 zserv_event(NULL, ZSERV_ACCEPT);
718e3744 720
d62a17ae 721 len = sizeof(struct sockaddr_in);
722 client_sock = accept(accept_sock, (struct sockaddr *)&client, &len);
719e9741 723
d62a17ae 724 if (client_sock < 0) {
450971aa 725 flog_err_sys(EC_LIB_SOCKET, "Can't accept zebra socket: %s",
9df414fe 726 safe_strerror(errno));
d62a17ae 727 return -1;
728 }
718e3744 729
d62a17ae 730 /* Make client socket non-blocking. */
731 set_nonblocking(client_sock);
718e3744 732
d62a17ae 733 /* Create new zebra client. */
21ccc0cf 734 zserv_client_create(client_sock);
718e3744 735
d62a17ae 736 return 0;
718e3744 737}
738
41674562
DS
739void zserv_close(void)
740{
741 /*
742 * On shutdown, let's close the socket down
743 * so that long running processes of killing the
744 * routing table doesn't leave us in a bad
745 * state where a client tries to reconnect
746 */
747 close(zsock);
748 zsock = -1;
749}
750
21ccc0cf 751void zserv_start(char *path)
d62a17ae 752{
753 int ret;
d62a17ae 754 mode_t old_mask;
689f5a8c
DL
755 struct sockaddr_storage sa;
756 socklen_t sa_len;
d62a17ae 757
689f5a8c
DL
758 if (!frr_zclient_addr(&sa, &sa_len, path))
759 /* should be caught in zebra main() */
760 return;
d62a17ae 761
762 /* Set umask */
763 old_mask = umask(0077);
764
765 /* Make UNIX domain socket. */
cc3d8834
DS
766 zsock = socket(sa.ss_family, SOCK_STREAM, 0);
767 if (zsock < 0) {
450971aa 768 flog_err_sys(EC_LIB_SOCKET, "Can't create zserv socket: %s",
9df414fe 769 safe_strerror(errno));
d62a17ae 770 return;
771 }
772
689f5a8c 773 if (sa.ss_family != AF_UNIX) {
cc3d8834
DS
774 sockopt_reuseaddr(zsock);
775 sockopt_reuseport(zsock);
689f5a8c
DL
776 } else {
777 struct sockaddr_un *suna = (struct sockaddr_un *)&sa;
778 if (suna->sun_path[0])
779 unlink(suna->sun_path);
780 }
781
338b8e91
RW
782 setsockopt_so_recvbuf(zsock, 1048576);
783 setsockopt_so_sendbuf(zsock, 1048576);
689f5a8c 784
0cf6db21 785 frr_with_privs((sa.ss_family != AF_UNIX) ? &zserv_privs : NULL) {
cc3d8834 786 ret = bind(zsock, (struct sockaddr *)&sa, sa_len);
6bb30c2c 787 }
d62a17ae 788 if (ret < 0) {
1c50c1c0
QY
789 flog_err_sys(EC_LIB_SOCKET, "Can't bind zserv socket on %s: %s",
790 path, safe_strerror(errno));
cc3d8834
DS
791 close(zsock);
792 zsock = -1;
d62a17ae 793 return;
794 }
795
cc3d8834 796 ret = listen(zsock, 5);
d62a17ae 797 if (ret < 0) {
450971aa 798 flog_err_sys(EC_LIB_SOCKET,
9df414fe
QY
799 "Can't listen to zserv socket %s: %s", path,
800 safe_strerror(errno));
cc3d8834
DS
801 close(zsock);
802 zsock = -1;
d62a17ae 803 return;
804 }
805
806 umask(old_mask);
807
21ccc0cf 808 zserv_event(NULL, ZSERV_ACCEPT);
718e3744 809}
6b0655a2 810
21ccc0cf
QY
811void zserv_event(struct zserv *client, enum zserv_event event)
812{
813 switch (event) {
814 case ZSERV_ACCEPT:
cc3d8834 815 thread_add_read(zrouter.master, zserv_accept, NULL, zsock,
21ccc0cf
QY
816 NULL);
817 break;
818 case ZSERV_PROCESS_MESSAGES:
3801e764 819 thread_add_event(zrouter.master, zserv_process_messages, client,
dded2aba 820 0, &client->t_process);
21ccc0cf 821 break;
f3e33b69 822 case ZSERV_HANDLE_CLIENT_FAIL:
3801e764 823 thread_add_event(zrouter.master, zserv_handle_client_fail,
f3e33b69 824 client, 0, &client->t_cleanup);
21ccc0cf
QY
825 }
826}
827
828
f2efe6a3
QY
829/* General purpose ---------------------------------------------------------- */
830
04b02fda 831#define ZEBRA_TIME_BUF 32
d62a17ae 832static char *zserv_time_buf(time_t *time1, char *buf, int buflen)
04b02fda 833{
d62a17ae 834 struct tm *tm;
835 time_t now;
04b02fda 836
d62a17ae 837 assert(buf != NULL);
838 assert(buflen >= ZEBRA_TIME_BUF);
839 assert(time1 != NULL);
04b02fda 840
d62a17ae 841 if (!*time1) {
842 snprintf(buf, buflen, "never ");
843 return (buf);
844 }
04b02fda 845
d62a17ae 846 now = monotime(NULL);
847 now -= *time1;
848 tm = gmtime(&now);
04b02fda 849
d62a17ae 850 if (now < ONE_DAY_SECOND)
851 snprintf(buf, buflen, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min,
852 tm->tm_sec);
853 else if (now < ONE_WEEK_SECOND)
854 snprintf(buf, buflen, "%dd%02dh%02dm", tm->tm_yday, tm->tm_hour,
855 tm->tm_min);
96ade3ed 856 else
d62a17ae 857 snprintf(buf, buflen, "%02dw%dd%02dh", tm->tm_yday / 7,
858 tm->tm_yday - ((tm->tm_yday / 7) * 7), tm->tm_hour);
859 return buf;
860}
861
862static void zebra_show_client_detail(struct vty *vty, struct zserv *client)
863{
864 char cbuf[ZEBRA_TIME_BUF], rbuf[ZEBRA_TIME_BUF];
865 char wbuf[ZEBRA_TIME_BUF], nhbuf[ZEBRA_TIME_BUF], mbuf[ZEBRA_TIME_BUF];
52f6868d 866 time_t connect_time, last_read_time, last_write_time;
0545c373 867 uint32_t last_read_cmd, last_write_cmd;
d62a17ae 868
869 vty_out(vty, "Client: %s", zebra_route_string(client->proto));
870 if (client->instance)
871 vty_out(vty, " Instance: %d", client->instance);
872 vty_out(vty, "\n");
873
874 vty_out(vty, "------------------------ \n");
875 vty_out(vty, "FD: %d \n", client->sock);
d62a17ae 876
52f6868d
QY
877 connect_time = (time_t) atomic_load_explicit(&client->connect_time,
878 memory_order_relaxed);
879
d62a17ae 880 vty_out(vty, "Connect Time: %s \n",
52f6868d 881 zserv_time_buf(&connect_time, cbuf, ZEBRA_TIME_BUF));
d62a17ae 882 if (client->nh_reg_time) {
883 vty_out(vty, "Nexthop Registry Time: %s \n",
884 zserv_time_buf(&client->nh_reg_time, nhbuf,
885 ZEBRA_TIME_BUF));
886 if (client->nh_last_upd_time)
887 vty_out(vty, "Nexthop Last Update Time: %s \n",
888 zserv_time_buf(&client->nh_last_upd_time, mbuf,
889 ZEBRA_TIME_BUF));
890 else
891 vty_out(vty, "No Nexthop Update sent\n");
892 } else
893 vty_out(vty, "Not registered for Nexthop Updates\n");
894
1f312c84
QY
895 last_read_time = (time_t)atomic_load_explicit(&client->last_read_time,
896 memory_order_relaxed);
897 last_write_time = (time_t)atomic_load_explicit(&client->last_write_time,
52f6868d
QY
898 memory_order_relaxed);
899
900 last_read_cmd = atomic_load_explicit(&client->last_read_cmd,
901 memory_order_relaxed);
902 last_write_cmd = atomic_load_explicit(&client->last_write_cmd,
903 memory_order_relaxed);
904
d62a17ae 905 vty_out(vty, "Last Msg Rx Time: %s \n",
52f6868d 906 zserv_time_buf(&last_read_time, rbuf, ZEBRA_TIME_BUF));
d62a17ae 907 vty_out(vty, "Last Msg Tx Time: %s \n",
52f6868d
QY
908 zserv_time_buf(&last_write_time, wbuf, ZEBRA_TIME_BUF));
909 if (last_read_cmd)
d62a17ae 910 vty_out(vty, "Last Rcvd Cmd: %s \n",
52f6868d
QY
911 zserv_command_string(last_read_cmd));
912 if (last_write_cmd)
d62a17ae 913 vty_out(vty, "Last Sent Cmd: %s \n",
52f6868d 914 zserv_command_string(last_write_cmd));
d62a17ae 915 vty_out(vty, "\n");
916
0037287b 917 vty_out(vty, "Type Add Update Del \n");
d62a17ae 918 vty_out(vty, "================================================== \n");
919 vty_out(vty, "IPv4 %-12d%-12d%-12d\n", client->v4_route_add_cnt,
920 client->v4_route_upd8_cnt, client->v4_route_del_cnt);
921 vty_out(vty, "IPv6 %-12d%-12d%-12d\n", client->v6_route_add_cnt,
922 client->v6_route_upd8_cnt, client->v6_route_del_cnt);
923 vty_out(vty, "Redist:v4 %-12d%-12d%-12d\n", client->redist_v4_add_cnt,
924 0, client->redist_v4_del_cnt);
925 vty_out(vty, "Redist:v6 %-12d%-12d%-12d\n", client->redist_v6_add_cnt,
926 0, client->redist_v6_del_cnt);
927 vty_out(vty, "Connected %-12d%-12d%-12d\n", client->ifadd_cnt, 0,
928 client->ifdel_cnt);
929 vty_out(vty, "BFD peer %-12d%-12d%-12d\n", client->bfd_peer_add_cnt,
930 client->bfd_peer_upd8_cnt, client->bfd_peer_del_cnt);
ab5990d8
DS
931 vty_out(vty, "NHT v4 %-12d%-12d%-12d\n",
932 client->v4_nh_watch_add_cnt, 0, client->v4_nh_watch_rem_cnt);
933 vty_out(vty, "NHT v6 %-12d%-12d%-12d\n",
934 client->v6_nh_watch_add_cnt, 0, client->v6_nh_watch_rem_cnt);
4ab3321f
AK
935 vty_out(vty, "VxLAN SG %-12d%-12d%-12d\n", client->vxlan_sg_add_cnt,
936 0, client->vxlan_sg_del_cnt);
d62a17ae 937 vty_out(vty, "Interface Up Notifications: %d\n", client->ifup_cnt);
938 vty_out(vty, "Interface Down Notifications: %d\n", client->ifdown_cnt);
939 vty_out(vty, "VNI add notifications: %d\n", client->vniadd_cnt);
940 vty_out(vty, "VNI delete notifications: %d\n", client->vnidel_cnt);
b7cfce93
MK
941 vty_out(vty, "L3-VNI add notifications: %d\n", client->l3vniadd_cnt);
942 vty_out(vty, "L3-VNI delete notifications: %d\n", client->l3vnidel_cnt);
d62a17ae 943 vty_out(vty, "MAC-IP add notifications: %d\n", client->macipadd_cnt);
944 vty_out(vty, "MAC-IP delete notifications: %d\n", client->macipdel_cnt);
945
03ed85a6
DS
946#if defined DEV_BUILD
947 vty_out(vty, "Input Fifo: %zu:%zu Output Fifo: %zu:%zu\n",
948 client->ibuf_fifo->count, client->ibuf_fifo->max_count,
949 client->obuf_fifo->count, client->obuf_fifo->max_count);
950#endif
d62a17ae 951 vty_out(vty, "\n");
952 return;
953}
954
955static void zebra_show_client_brief(struct vty *vty, struct zserv *client)
956{
957 char cbuf[ZEBRA_TIME_BUF], rbuf[ZEBRA_TIME_BUF];
958 char wbuf[ZEBRA_TIME_BUF];
52f6868d
QY
959 time_t connect_time, last_read_time, last_write_time;
960
e1de21d7
QY
961 connect_time = (time_t)atomic_load_explicit(&client->connect_time,
962 memory_order_relaxed);
963 last_read_time = (time_t)atomic_load_explicit(&client->last_read_time,
964 memory_order_relaxed);
965 last_write_time = (time_t)atomic_load_explicit(&client->last_write_time,
52f6868d 966 memory_order_relaxed);
d62a17ae 967
588a3027 968 vty_out(vty, "%-10s%12s %12s%12s%8d/%-8d%8d/%-8d\n",
d62a17ae 969 zebra_route_string(client->proto),
52f6868d
QY
970 zserv_time_buf(&connect_time, cbuf, ZEBRA_TIME_BUF),
971 zserv_time_buf(&last_read_time, rbuf, ZEBRA_TIME_BUF),
972 zserv_time_buf(&last_write_time, wbuf, ZEBRA_TIME_BUF),
d62a17ae 973 client->v4_route_add_cnt + client->v4_route_upd8_cnt,
974 client->v4_route_del_cnt,
975 client->v6_route_add_cnt + client->v6_route_upd8_cnt,
976 client->v6_route_del_cnt);
977}
978
21ccc0cf 979struct zserv *zserv_find_client(uint8_t proto, unsigned short instance)
d62a17ae 980{
981 struct listnode *node, *nnode;
982 struct zserv *client;
983
161e9ab7 984 for (ALL_LIST_ELEMENTS(zrouter.client_list, node, nnode, client)) {
996c9314 985 if (client->proto == proto && client->instance == instance)
d62a17ae 986 return client;
987 }
988
989 return NULL;
8ed6821e 990}
991
718e3744 992/* This command is for debugging purpose. */
993DEFUN (show_zebra_client,
994 show_zebra_client_cmd,
995 "show zebra client",
996 SHOW_STR
41e7fb80 997 ZEBRA_STR
b9ee4999 998 "Client information\n")
718e3744 999{
d62a17ae 1000 struct listnode *node;
1001 struct zserv *client;
718e3744 1002
161e9ab7 1003 for (ALL_LIST_ELEMENTS_RO(zrouter.client_list, node, client))
d62a17ae 1004 zebra_show_client_detail(vty, client);
04b02fda 1005
d62a17ae 1006 return CMD_SUCCESS;
04b02fda
DS
1007}
1008
1009/* This command is for debugging purpose. */
1010DEFUN (show_zebra_client_summary,
1011 show_zebra_client_summary_cmd,
1012 "show zebra client summary",
1013 SHOW_STR
41e7fb80 1014 ZEBRA_STR
b9ee4999
DS
1015 "Client information brief\n"
1016 "Brief Summary\n")
04b02fda 1017{
d62a17ae 1018 struct listnode *node;
1019 struct zserv *client;
04b02fda 1020
d62a17ae 1021 vty_out(vty,
588a3027 1022 "Name Connect Time Last Read Last Write IPv4 Routes IPv6 Routes \n");
d62a17ae 1023 vty_out(vty,
1024 "--------------------------------------------------------------------------------\n");
04b02fda 1025
161e9ab7 1026 for (ALL_LIST_ELEMENTS_RO(zrouter.client_list, node, client))
d62a17ae 1027 zebra_show_client_brief(vty, client);
fb018d25 1028
d62a17ae 1029 vty_out(vty, "Routes column shows (added+updated)/deleted\n");
1030 return CMD_SUCCESS;
718e3744 1031}
1032
411314ed
DS
1033#if defined(HANDLE_ZAPI_FUZZING)
1034void zserv_read_file(char *input)
1035{
1036 int fd;
411314ed 1037
996c9314 1038 fd = open(input, O_RDONLY | O_NONBLOCK);
411314ed 1039
2875801f 1040 zserv_client_create(fd);
411314ed
DS
1041}
1042#endif
1043
5f145fb8 1044void zserv_init(void)
718e3744 1045{
d62a17ae 1046 /* Client list init. */
161e9ab7 1047 zrouter.client_list = list_new();
21ccc0cf
QY
1048
1049 /* Misc init. */
cc3d8834 1050 zsock = -1;
718e3744 1051
d62a17ae 1052 install_element(ENABLE_NODE, &show_zebra_client_cmd);
1053 install_element(ENABLE_NODE, &show_zebra_client_summary_cmd);
718e3744 1054}