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