]> git.proxmox.com Git - mirror_frr.git/blob - zebra/zserv.c
b666b2e0ab50cd6b2d5ff1294e8777d9e5c1ca6b
[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 a single packet.
203 */
204 static int zserv_write(struct thread *thread)
205 {
206 struct zserv *client = THREAD_ARG(thread);
207 struct stream *msg;
208 uint32_t wcmd;
209 int writerv;
210
211 if (client->is_synchronous)
212 return 0;
213
214 pthread_mutex_lock(&client->obuf_mtx);
215 {
216 msg = stream_fifo_pop(client->obuf_fifo);
217 }
218 pthread_mutex_unlock(&client->obuf_mtx);
219
220 stream_set_getp(msg, 0);
221
222 wcmd = stream_getw_from(msg, 6);
223 atomic_store_explicit(&client->last_write_cmd, wcmd,
224 memory_order_relaxed);
225
226 writerv = buffer_write(client->wb, client->sock, STREAM_DATA(msg),
227 stream_get_endp(msg));
228
229 stream_free(msg);
230
231 switch (writerv) {
232 case BUFFER_ERROR:
233 zlog_warn("%s: buffer_write failed to ZAPI client %s [fd = %d]",
234 __func__, zebra_route_string(client->proto),
235 client->sock);
236 zlog_warn("%s: closing connection to %s", __func__,
237 zebra_route_string(client->proto));
238 zserv_client_close(client);
239 return -1;
240 case BUFFER_PENDING:
241 zserv_client_event(client, ZSERV_CLIENT_FLUSH_DATA);
242 break;
243 case BUFFER_EMPTY:
244 break;
245 }
246
247 pthread_mutex_lock(&client->obuf_mtx);
248 {
249 if (client->obuf_fifo->count)
250 zserv_client_event(client, ZSERV_CLIENT_WRITE);
251 }
252 pthread_mutex_unlock(&client->obuf_mtx);
253
254 atomic_store_explicit(&client->last_write_time,
255 (uint32_t) monotime(NULL), memory_order_relaxed);
256
257 return 0;
258 }
259
260 #if defined(HANDLE_ZAPI_FUZZING)
261 static void zserv_write_incoming(struct stream *orig, uint16_t command)
262 {
263 char fname[MAXPATHLEN];
264 struct stream *copy;
265 int fd = -1;
266
267 copy = stream_dup(orig);
268 stream_set_getp(copy, 0);
269
270 zserv_privs.change(ZPRIVS_RAISE);
271 snprintf(fname, MAXPATHLEN, "%s/%u", DAEMON_VTY_DIR, command);
272 fd = open(fname, O_CREAT | O_WRONLY | O_EXCL, 0644);
273 stream_flush(copy, fd);
274 close(fd);
275 zserv_privs.change(ZPRIVS_LOWER);
276 stream_free(copy);
277 }
278 #endif
279
280 /*
281 * Read and process data from a client socket.
282 *
283 * The responsibilities here are to read raw data from the client socket,
284 * validate the header, encapsulate it into a single stream object, push it
285 * onto the input queue and then notify the main thread that there is new data
286 * available.
287 *
288 * This function first looks for any data in the client structure's working
289 * input buffer. If data is present, it is assumed that reading stopped in a
290 * previous invocation of this task and needs to be resumed to finish a message.
291 * Otherwise, the socket data stream is assumed to be at the beginning of a new
292 * ZAPI message (specifically at the header). The header is read and validated.
293 * If the header passed validation then the length field found in the header is
294 * used to compute the total length of the message. That much data is read (but
295 * not inspected), appended to the header, placed into a stream and pushed onto
296 * the client's input queue. A task is then scheduled on the main thread to
297 * process the client's input queue. Finally, if all of this was successful,
298 * this task reschedules itself.
299 *
300 * Any failure in any of these actions is handled by terminating the client.
301 */
302 static int zserv_read(struct thread *thread)
303 {
304 int sock;
305 struct zserv *client;
306 size_t already;
307 struct stream_fifo *cache = stream_fifo_new();
308 int p2p_orig = atomic_load_explicit(&zebrad.packets_to_process,
309 memory_order_relaxed);
310 uint32_t p2p;
311 struct zmsghdr hdr;
312
313 #if defined(HANDLE_ZAPI_FUZZING)
314 int p2p = 1;
315 #else
316 int p2p = p2p_orig;
317 #endif
318 sock = THREAD_FD(thread);
319 client = THREAD_ARG(thread);
320
321 while (p2p--) {
322 ssize_t nb;
323 bool hdrvalid;
324 char errmsg[256];
325
326 already = stream_get_endp(client->ibuf_work);
327
328 /* Read length and command (if we don't have it already). */
329 if (already < ZEBRA_HEADER_SIZE) {
330 nb = stream_read_try(client->ibuf_work, sock,
331 ZEBRA_HEADER_SIZE - already);
332 if ((nb == 0 || nb == -1) && IS_ZEBRA_DEBUG_EVENT)
333 zlog_debug("connection closed socket [%d]",
334 sock);
335 if ((nb == 0 || nb == -1))
336 goto zread_fail;
337 if (nb != (ssize_t)(ZEBRA_HEADER_SIZE - already)) {
338 /* Try again later. */
339 break;
340 }
341 already = ZEBRA_HEADER_SIZE;
342 }
343
344 /* Reset to read from the beginning of the incoming packet. */
345 stream_set_getp(client->ibuf_work, 0);
346
347 /* Fetch header values */
348 hdrvalid = zapi_parse_header(client->ibuf_work, &hdr);
349
350 if (!hdrvalid) {
351 snprintf(errmsg, sizeof(errmsg),
352 "%s: Message has corrupt header", __func__);
353 zserv_log_message(errmsg, client->ibuf_work, NULL);
354 goto zread_fail;
355 }
356
357 /* Validate header */
358 if (hdr.marker != ZEBRA_HEADER_MARKER
359 || hdr.version != ZSERV_VERSION) {
360 snprintf(
361 errmsg, sizeof(errmsg),
362 "Message has corrupt header\n%s: socket %d version mismatch, marker %d, version %d",
363 __func__, sock, hdr.marker, hdr.version);
364 zserv_log_message(errmsg, client->ibuf_work, &hdr);
365 goto zread_fail;
366 }
367 if (hdr.length < ZEBRA_HEADER_SIZE) {
368 snprintf(
369 errmsg, sizeof(errmsg),
370 "Message has corrupt header\n%s: socket %d message length %u is less than header size %d",
371 __func__, sock, hdr.length, ZEBRA_HEADER_SIZE);
372 zserv_log_message(errmsg, client->ibuf_work, &hdr);
373 goto zread_fail;
374 }
375 if (hdr.length > STREAM_SIZE(client->ibuf_work)) {
376 snprintf(
377 errmsg, sizeof(errmsg),
378 "Message has corrupt header\n%s: socket %d message length %u exceeds buffer size %lu",
379 __func__, sock, hdr.length,
380 (unsigned long)STREAM_SIZE(client->ibuf_work));
381 zserv_log_message(errmsg, client->ibuf_work, &hdr);
382 goto zread_fail;
383 }
384
385 /* Read rest of data. */
386 if (already < hdr.length) {
387 nb = stream_read_try(client->ibuf_work, sock,
388 hdr.length - already);
389 if ((nb == 0 || nb == -1) && IS_ZEBRA_DEBUG_EVENT)
390 zlog_debug(
391 "connection closed [%d] when reading zebra data",
392 sock);
393 if ((nb == 0 || nb == -1))
394 goto zread_fail;
395 if (nb != (ssize_t)(hdr.length - already)) {
396 /* Try again later. */
397 break;
398 }
399 }
400
401 #if defined(HANDLE_ZAPI_FUZZING)
402 zserv_write_incoming(client->ibuf_work, command);
403 #endif
404
405 /* Debug packet information. */
406 if (IS_ZEBRA_DEBUG_EVENT)
407 zlog_debug("zebra message comes from socket [%d]",
408 sock);
409
410 if (IS_ZEBRA_DEBUG_PACKET && IS_ZEBRA_DEBUG_RECV)
411 zserv_log_message(NULL, client->ibuf_work, &hdr);
412
413 stream_set_getp(client->ibuf_work, 0);
414 struct stream *msg = stream_dup(client->ibuf_work);
415
416 stream_fifo_push(cache, msg);
417 stream_reset(client->ibuf_work);
418 }
419
420 if (p2p < p2p_orig) {
421 /* update session statistics */
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);
426
427 /* publish read packets on client's input queue */
428 pthread_mutex_lock(&client->ibuf_mtx);
429 {
430 while (cache->head)
431 stream_fifo_push(client->ibuf_fifo,
432 stream_fifo_pop(cache));
433 }
434 pthread_mutex_unlock(&client->ibuf_mtx);
435 }
436
437 if (IS_ZEBRA_DEBUG_PACKET)
438 zlog_debug("Read %d packets", p2p_orig - p2p);
439
440 /* Schedule job to process those packets */
441 zserv_event(client, ZSERV_PROCESS_MESSAGES);
442
443 /* Reschedule ourselves */
444 zserv_client_event(client, ZSERV_CLIENT_READ);
445
446 stream_fifo_free(cache);
447
448 return 0;
449
450 zread_fail:
451 stream_fifo_free(cache);
452 zserv_client_close(client);
453 return -1;
454 }
455
456 static void zserv_client_event(struct zserv *client,
457 enum zserv_client_event event)
458 {
459 switch (event) {
460 case ZSERV_CLIENT_READ:
461 thread_add_read(client->pthread->master, zserv_read, client,
462 client->sock, &client->t_read);
463 break;
464 case ZSERV_CLIENT_WRITE:
465 thread_add_write(client->pthread->master, zserv_write, client,
466 client->sock, &client->t_write);
467 break;
468 case ZSERV_CLIENT_FLUSH_DATA:
469 thread_add_write(client->pthread->master, zserv_flush_data,
470 client, client->sock, &client->t_write);
471 break;
472 }
473 }
474
475 /* Main thread lifecycle ---------------------------------------------------- */
476
477 /*
478 * Read and process messages from a client.
479 *
480 * This task runs on the main pthread. It is scheduled by client pthreads when
481 * they have new messages available on their input queues. The client is passed
482 * as the task argument.
483 *
484 * Each message is popped off the client's input queue and the action associated
485 * with the message is executed. This proceeds until there are no more messages,
486 * an error occurs, or the processing limit is reached. In the last case, this
487 * task reschedules itself.
488 */
489 static int zserv_process_messages(struct thread *thread)
490 {
491 struct zserv *client = THREAD_ARG(thread);
492 struct zebra_vrf *zvrf;
493 struct zmsghdr hdr;
494 struct stream *msg;
495 bool hdrvalid;
496
497 int p2p = zebrad.packets_to_process;
498
499 do {
500 pthread_mutex_lock(&client->ibuf_mtx);
501 {
502 msg = stream_fifo_pop(client->ibuf_fifo);
503 }
504 pthread_mutex_unlock(&client->ibuf_mtx);
505
506 /* break if out of messages */
507 if (!msg)
508 continue;
509
510 /* read & check header */
511 hdrvalid = zapi_parse_header(msg, &hdr);
512 if (!hdrvalid && IS_ZEBRA_DEBUG_PACKET && IS_ZEBRA_DEBUG_RECV) {
513 const char *emsg = "Message has corrupt header";
514 zserv_log_message(emsg, msg, NULL);
515 }
516 if (!hdrvalid)
517 continue;
518
519 hdr.length -= ZEBRA_HEADER_SIZE;
520 /* lookup vrf */
521 zvrf = zebra_vrf_lookup_by_id(hdr.vrf_id);
522 if (!zvrf && IS_ZEBRA_DEBUG_PACKET && IS_ZEBRA_DEBUG_RECV) {
523 const char *emsg = "Message specifies unknown VRF";
524 zserv_log_message(emsg, msg, &hdr);
525 }
526 if (!zvrf)
527 continue;
528
529 /* process commands */
530 zserv_handle_commands(client, &hdr, msg, zvrf);
531
532 } while (msg && --p2p);
533
534 /* reschedule self if necessary */
535 pthread_mutex_lock(&client->ibuf_mtx);
536 {
537 if (client->ibuf_fifo->count)
538 zserv_event(client, ZSERV_PROCESS_MESSAGES);
539 }
540 pthread_mutex_unlock(&client->ibuf_mtx);
541
542 return 0;
543 }
544
545 int zserv_send_message(struct zserv *client, struct stream *msg)
546 {
547 pthread_mutex_lock(&client->obuf_mtx);
548 {
549 stream_fifo_push(client->obuf_fifo, msg);
550 zserv_client_event(client, ZSERV_CLIENT_WRITE);
551 }
552 pthread_mutex_unlock(&client->obuf_mtx);
553 return 0;
554 }
555
556
557 /* Hooks for client connect / disconnect */
558 DEFINE_HOOK(zserv_client_connect, (struct zserv *client), (client));
559 DEFINE_KOOH(zserv_client_close, (struct zserv *client), (client));
560
561 /*
562 * Deinitialize zebra client.
563 *
564 * - Deregister and deinitialize related internal resources
565 * - Gracefully close socket
566 * - Free associated resources
567 * - Free client structure
568 *
569 * This does *not* take any action on the struct thread * fields. These are
570 * managed by the owning pthread and any tasks associated with them must have
571 * been stopped prior to invoking this function.
572 */
573 static void zserv_client_free(struct zserv *client)
574 {
575 hook_call(zserv_client_close, client);
576
577 /* Close file descriptor. */
578 if (client->sock) {
579 unsigned long nroutes;
580
581 close(client->sock);
582 nroutes = rib_score_proto(client->proto, client->instance);
583 zlog_notice(
584 "client %d disconnected. %lu %s routes removed from the rib",
585 client->sock, nroutes,
586 zebra_route_string(client->proto));
587 client->sock = -1;
588 }
589
590 /* Free stream buffers. */
591 if (client->ibuf_work)
592 stream_free(client->ibuf_work);
593 if (client->obuf_work)
594 stream_free(client->obuf_work);
595 if (client->ibuf_fifo)
596 stream_fifo_free(client->ibuf_fifo);
597 if (client->obuf_fifo)
598 stream_fifo_free(client->obuf_fifo);
599 if (client->wb)
600 buffer_free(client->wb);
601
602 /* Free buffer mutexes */
603 pthread_mutex_destroy(&client->obuf_mtx);
604 pthread_mutex_destroy(&client->ibuf_mtx);
605
606 /* Free bitmaps. */
607 for (afi_t afi = AFI_IP; afi < AFI_MAX; afi++)
608 for (int i = 0; i < ZEBRA_ROUTE_MAX; i++)
609 vrf_bitmap_free(client->redist[afi][i]);
610
611 vrf_bitmap_free(client->redist_default);
612 vrf_bitmap_free(client->ifinfo);
613 vrf_bitmap_free(client->ridinfo);
614
615 XFREE(MTYPE_TMP, client);
616 }
617
618 /*
619 * Finish closing a client.
620 *
621 * This task is scheduled by a ZAPI client pthread on the main pthread when it
622 * wants to stop itself. When this executes, the client connection should
623 * already have been closed. This task's responsibility is to gracefully
624 * terminate the client thread, update relevant internal datastructures and
625 * free any resources allocated by the main thread.
626 */
627 static int zserv_handle_client_close(struct thread *thread)
628 {
629 struct zserv *client = THREAD_ARG(thread);
630
631 /*
632 * Ensure these have been nulled. This does not equate to the
633 * associated task(s) being scheduled or unscheduled on the client
634 * pthread's threadmaster.
635 */
636 assert(!client->t_read);
637 assert(!client->t_write);
638
639 /* synchronously stop thread */
640 frr_pthread_stop(client->pthread, NULL);
641
642 /* destroy frr_pthread */
643 frr_pthread_destroy(client->pthread);
644 client->pthread = NULL;
645
646 listnode_delete(zebrad.client_list, client);
647 zserv_client_free(client);
648 return 0;
649 }
650
651 /*
652 * Create a new client.
653 *
654 * This is called when a new connection is accept()'d on the ZAPI socket. It
655 * initializes new client structure, notifies any subscribers of the connection
656 * event and spawns the client's thread.
657 *
658 * sock
659 * client's socket file descriptor
660 */
661 static void zserv_client_create(int sock)
662 {
663 struct zserv *client;
664 int i;
665 afi_t afi;
666
667 client = XCALLOC(MTYPE_TMP, sizeof(struct zserv));
668
669 /* Make client input/output buffer. */
670 client->sock = sock;
671 client->ibuf_fifo = stream_fifo_new();
672 client->obuf_fifo = stream_fifo_new();
673 client->ibuf_work = stream_new(ZEBRA_MAX_PACKET_SIZ);
674 client->obuf_work = stream_new(ZEBRA_MAX_PACKET_SIZ);
675 pthread_mutex_init(&client->ibuf_mtx, NULL);
676 pthread_mutex_init(&client->obuf_mtx, NULL);
677 client->wb = buffer_new(0);
678
679 /* Set table number. */
680 client->rtm_table = zebrad.rtm_table_default;
681
682 atomic_store_explicit(&client->connect_time, (uint32_t) monotime(NULL),
683 memory_order_relaxed);
684
685 /* Initialize flags */
686 for (afi = AFI_IP; afi < AFI_MAX; afi++)
687 for (i = 0; i < ZEBRA_ROUTE_MAX; i++)
688 client->redist[afi][i] = vrf_bitmap_init();
689 client->redist_default = vrf_bitmap_init();
690 client->ifinfo = vrf_bitmap_init();
691 client->ridinfo = vrf_bitmap_init();
692
693 /* by default, it's not a synchronous client */
694 client->is_synchronous = 0;
695
696 /* Add this client to linked list. */
697 listnode_add(zebrad.client_list, client);
698
699 struct frr_pthread_attr zclient_pthr_attrs = {
700 .id = frr_pthread_get_id(),
701 .start = frr_pthread_attr_default.start,
702 .stop = frr_pthread_attr_default.stop
703 };
704 client->pthread =
705 frr_pthread_new(&zclient_pthr_attrs, "Zebra API client thread");
706
707 zebra_vrf_update_all(client);
708
709 /* start read loop */
710 zserv_client_event(client, ZSERV_CLIENT_READ);
711
712 /* call callbacks */
713 hook_call(zserv_client_connect, client);
714
715 /* start pthread */
716 frr_pthread_run(client->pthread, NULL);
717 }
718
719 /*
720 * Accept socket connection.
721 */
722 static int zserv_accept(struct thread *thread)
723 {
724 int accept_sock;
725 int client_sock;
726 struct sockaddr_in client;
727 socklen_t len;
728
729 accept_sock = THREAD_FD(thread);
730
731 /* Reregister myself. */
732 zserv_event(NULL, ZSERV_ACCEPT);
733
734 len = sizeof(struct sockaddr_in);
735 client_sock = accept(accept_sock, (struct sockaddr *)&client, &len);
736
737 if (client_sock < 0) {
738 zlog_warn("Can't accept zebra socket: %s",
739 safe_strerror(errno));
740 return -1;
741 }
742
743 /* Make client socket non-blocking. */
744 set_nonblocking(client_sock);
745
746 /* Create new zebra client. */
747 zserv_client_create(client_sock);
748
749 return 0;
750 }
751
752 void zserv_start(char *path)
753 {
754 int ret;
755 mode_t old_mask;
756 struct sockaddr_storage sa;
757 socklen_t sa_len;
758
759 if (!frr_zclient_addr(&sa, &sa_len, path))
760 /* should be caught in zebra main() */
761 return;
762
763 /* Set umask */
764 old_mask = umask(0077);
765
766 /* Make UNIX domain socket. */
767 zebrad.sock = socket(sa.ss_family, SOCK_STREAM, 0);
768 if (zebrad.sock < 0) {
769 zlog_warn("Can't create zserv socket: %s",
770 safe_strerror(errno));
771 zlog_warn(
772 "zebra can't provide full functionality due to above error");
773 return;
774 }
775
776 if (sa.ss_family != AF_UNIX) {
777 sockopt_reuseaddr(zebrad.sock);
778 sockopt_reuseport(zebrad.sock);
779 } else {
780 struct sockaddr_un *suna = (struct sockaddr_un *)&sa;
781 if (suna->sun_path[0])
782 unlink(suna->sun_path);
783 }
784
785 zserv_privs.change(ZPRIVS_RAISE);
786 setsockopt_so_recvbuf(zebrad.sock, 1048576);
787 setsockopt_so_sendbuf(zebrad.sock, 1048576);
788 zserv_privs.change(ZPRIVS_LOWER);
789
790 if (sa.ss_family != AF_UNIX && zserv_privs.change(ZPRIVS_RAISE))
791 zlog_err("Can't raise privileges");
792
793 ret = bind(zebrad.sock, (struct sockaddr *)&sa, sa_len);
794 if (ret < 0) {
795 zlog_warn("Can't bind zserv socket on %s: %s", path,
796 safe_strerror(errno));
797 zlog_warn(
798 "zebra can't provide full functionality due to above error");
799 close(zebrad.sock);
800 zebrad.sock = -1;
801 return;
802 }
803 if (sa.ss_family != AF_UNIX && zserv_privs.change(ZPRIVS_LOWER))
804 zlog_err("Can't lower privileges");
805
806 ret = listen(zebrad.sock, 5);
807 if (ret < 0) {
808 zlog_warn("Can't listen to zserv socket %s: %s", path,
809 safe_strerror(errno));
810 zlog_warn(
811 "zebra can't provide full functionality due to above error");
812 close(zebrad.sock);
813 zebrad.sock = -1;
814 return;
815 }
816
817 umask(old_mask);
818
819 zserv_event(NULL, ZSERV_ACCEPT);
820 }
821
822 void zserv_event(struct zserv *client, enum zserv_event event)
823 {
824 switch (event) {
825 case ZSERV_ACCEPT:
826 thread_add_read(zebrad.master, zserv_accept, NULL, zebrad.sock,
827 NULL);
828 break;
829 case ZSERV_PROCESS_MESSAGES:
830 thread_add_event(zebrad.master, zserv_process_messages, client,
831 0, NULL);
832 break;
833 case ZSERV_HANDLE_CLOSE:
834 thread_add_event(zebrad.master, zserv_handle_client_close,
835 client, 0, NULL);
836 }
837 }
838
839
840 /* General purpose ---------------------------------------------------------- */
841
842 #define ZEBRA_TIME_BUF 32
843 static char *zserv_time_buf(time_t *time1, char *buf, int buflen)
844 {
845 struct tm *tm;
846 time_t now;
847
848 assert(buf != NULL);
849 assert(buflen >= ZEBRA_TIME_BUF);
850 assert(time1 != NULL);
851
852 if (!*time1) {
853 snprintf(buf, buflen, "never ");
854 return (buf);
855 }
856
857 now = monotime(NULL);
858 now -= *time1;
859 tm = gmtime(&now);
860
861 if (now < ONE_DAY_SECOND)
862 snprintf(buf, buflen, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min,
863 tm->tm_sec);
864 else if (now < ONE_WEEK_SECOND)
865 snprintf(buf, buflen, "%dd%02dh%02dm", tm->tm_yday, tm->tm_hour,
866 tm->tm_min);
867 else
868 snprintf(buf, buflen, "%02dw%dd%02dh", tm->tm_yday / 7,
869 tm->tm_yday - ((tm->tm_yday / 7) * 7), tm->tm_hour);
870 return buf;
871 }
872
873 static void zebra_show_client_detail(struct vty *vty, struct zserv *client)
874 {
875 char cbuf[ZEBRA_TIME_BUF], rbuf[ZEBRA_TIME_BUF];
876 char wbuf[ZEBRA_TIME_BUF], nhbuf[ZEBRA_TIME_BUF], mbuf[ZEBRA_TIME_BUF];
877 time_t connect_time, last_read_time, last_write_time;
878 uint16_t last_read_cmd, last_write_cmd;
879
880 vty_out(vty, "Client: %s", zebra_route_string(client->proto));
881 if (client->instance)
882 vty_out(vty, " Instance: %d", client->instance);
883 vty_out(vty, "\n");
884
885 vty_out(vty, "------------------------ \n");
886 vty_out(vty, "FD: %d \n", client->sock);
887 vty_out(vty, "Route Table ID: %d \n", client->rtm_table);
888
889 connect_time = (time_t) atomic_load_explicit(&client->connect_time,
890 memory_order_relaxed);
891
892 vty_out(vty, "Connect Time: %s \n",
893 zserv_time_buf(&connect_time, cbuf, ZEBRA_TIME_BUF));
894 if (client->nh_reg_time) {
895 vty_out(vty, "Nexthop Registry Time: %s \n",
896 zserv_time_buf(&client->nh_reg_time, nhbuf,
897 ZEBRA_TIME_BUF));
898 if (client->nh_last_upd_time)
899 vty_out(vty, "Nexthop Last Update Time: %s \n",
900 zserv_time_buf(&client->nh_last_upd_time, mbuf,
901 ZEBRA_TIME_BUF));
902 else
903 vty_out(vty, "No Nexthop Update sent\n");
904 } else
905 vty_out(vty, "Not registered for Nexthop Updates\n");
906
907 last_read_time = (time_t) atomic_load_explicit(&client->last_read_time,
908 memory_order_relaxed);
909 last_read_time = (time_t) atomic_load_explicit(&client->last_write_time,
910 memory_order_relaxed);
911
912 last_read_cmd = atomic_load_explicit(&client->last_read_cmd,
913 memory_order_relaxed);
914 last_write_cmd = atomic_load_explicit(&client->last_write_cmd,
915 memory_order_relaxed);
916
917 vty_out(vty, "Last Msg Rx Time: %s \n",
918 zserv_time_buf(&last_read_time, rbuf, ZEBRA_TIME_BUF));
919 vty_out(vty, "Last Msg Tx Time: %s \n",
920 zserv_time_buf(&last_write_time, wbuf, ZEBRA_TIME_BUF));
921 if (last_read_cmd)
922 vty_out(vty, "Last Rcvd Cmd: %s \n",
923 zserv_command_string(last_read_cmd));
924 if (last_write_cmd)
925 vty_out(vty, "Last Sent Cmd: %s \n",
926 zserv_command_string(last_write_cmd));
927 vty_out(vty, "\n");
928
929 vty_out(vty, "Type Add Update Del \n");
930 vty_out(vty, "================================================== \n");
931 vty_out(vty, "IPv4 %-12d%-12d%-12d\n", client->v4_route_add_cnt,
932 client->v4_route_upd8_cnt, client->v4_route_del_cnt);
933 vty_out(vty, "IPv6 %-12d%-12d%-12d\n", client->v6_route_add_cnt,
934 client->v6_route_upd8_cnt, client->v6_route_del_cnt);
935 vty_out(vty, "Redist:v4 %-12d%-12d%-12d\n", client->redist_v4_add_cnt,
936 0, client->redist_v4_del_cnt);
937 vty_out(vty, "Redist:v6 %-12d%-12d%-12d\n", client->redist_v6_add_cnt,
938 0, client->redist_v6_del_cnt);
939 vty_out(vty, "Connected %-12d%-12d%-12d\n", client->ifadd_cnt, 0,
940 client->ifdel_cnt);
941 vty_out(vty, "BFD peer %-12d%-12d%-12d\n", client->bfd_peer_add_cnt,
942 client->bfd_peer_upd8_cnt, client->bfd_peer_del_cnt);
943 vty_out(vty, "Interface Up Notifications: %d\n", client->ifup_cnt);
944 vty_out(vty, "Interface Down Notifications: %d\n", client->ifdown_cnt);
945 vty_out(vty, "VNI add notifications: %d\n", client->vniadd_cnt);
946 vty_out(vty, "VNI delete notifications: %d\n", client->vnidel_cnt);
947 vty_out(vty, "L3-VNI add notifications: %d\n", client->l3vniadd_cnt);
948 vty_out(vty, "L3-VNI delete notifications: %d\n", client->l3vnidel_cnt);
949 vty_out(vty, "MAC-IP add notifications: %d\n", client->macipadd_cnt);
950 vty_out(vty, "MAC-IP delete notifications: %d\n", client->macipdel_cnt);
951
952 vty_out(vty, "\n");
953 return;
954 }
955
956 static void zebra_show_client_brief(struct vty *vty, struct zserv *client)
957 {
958 char cbuf[ZEBRA_TIME_BUF], rbuf[ZEBRA_TIME_BUF];
959 char wbuf[ZEBRA_TIME_BUF];
960 time_t connect_time, last_read_time, last_write_time;
961
962 connect_time = (time_t) atomic_load_explicit(&client->connect_time,
963 memory_order_relaxed);
964 last_read_time = (time_t) atomic_load_explicit(&client->last_read_time,
965 memory_order_relaxed);
966 last_read_time = (time_t) atomic_load_explicit(&client->last_write_time,
967 memory_order_relaxed);
968
969 vty_out(vty, "%-8s%12s %12s%12s%8d/%-8d%8d/%-8d\n",
970 zebra_route_string(client->proto),
971 zserv_time_buf(&connect_time, cbuf, ZEBRA_TIME_BUF),
972 zserv_time_buf(&last_read_time, rbuf, ZEBRA_TIME_BUF),
973 zserv_time_buf(&last_write_time, wbuf, ZEBRA_TIME_BUF),
974 client->v4_route_add_cnt + client->v4_route_upd8_cnt,
975 client->v4_route_del_cnt,
976 client->v6_route_add_cnt + client->v6_route_upd8_cnt,
977 client->v6_route_del_cnt);
978 }
979
980 struct zserv *zserv_find_client(uint8_t proto, unsigned short instance)
981 {
982 struct listnode *node, *nnode;
983 struct zserv *client;
984
985 for (ALL_LIST_ELEMENTS(zebrad.client_list, node, nnode, client)) {
986 if (client->proto == proto && client->instance == instance)
987 return client;
988 }
989
990 return NULL;
991 }
992
993 /* This command is for debugging purpose. */
994 DEFUN (show_zebra_client,
995 show_zebra_client_cmd,
996 "show zebra client",
997 SHOW_STR
998 ZEBRA_STR
999 "Client information\n")
1000 {
1001 struct listnode *node;
1002 struct zserv *client;
1003
1004 for (ALL_LIST_ELEMENTS_RO(zebrad.client_list, node, client))
1005 zebra_show_client_detail(vty, client);
1006
1007 return CMD_SUCCESS;
1008 }
1009
1010 /* This command is for debugging purpose. */
1011 DEFUN (show_zebra_client_summary,
1012 show_zebra_client_summary_cmd,
1013 "show zebra client summary",
1014 SHOW_STR
1015 ZEBRA_STR
1016 "Client information brief\n"
1017 "Brief Summary\n")
1018 {
1019 struct listnode *node;
1020 struct zserv *client;
1021
1022 vty_out(vty,
1023 "Name Connect Time Last Read Last Write IPv4 Routes IPv6 Routes \n");
1024 vty_out(vty,
1025 "--------------------------------------------------------------------------------\n");
1026
1027 for (ALL_LIST_ELEMENTS_RO(zebrad.client_list, node, client))
1028 zebra_show_client_brief(vty, client);
1029
1030 vty_out(vty, "Routes column shows (added+updated)/deleted\n");
1031 return CMD_SUCCESS;
1032 }
1033
1034 #if defined(HANDLE_ZAPI_FUZZING)
1035 void zserv_read_file(char *input)
1036 {
1037 int fd;
1038 struct zserv *client = NULL;
1039 struct thread t;
1040
1041 zebra_client_create(-1);
1042 client = zebrad.client_list->head->data;
1043 t.arg = client;
1044
1045 fd = open(input, O_RDONLY | O_NONBLOCK);
1046 t.u.fd = fd;
1047
1048 zebra_client_read(&t);
1049
1050 close(fd);
1051 }
1052 #endif
1053
1054 void zserv_init(void)
1055 {
1056 /* Client list init. */
1057 zebrad.client_list = list_new();
1058 zebrad.client_list->del = (void (*)(void *)) zserv_client_free;
1059
1060 /* Misc init. */
1061 zebrad.sock = -1;
1062
1063 install_element(ENABLE_NODE, &show_zebra_client_cmd);
1064 install_element(ENABLE_NODE, &show_zebra_client_summary_cmd);
1065 }