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