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