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