]> git.proxmox.com Git - mirror_frr.git/blob - lib/log.c
lib: perform a bind inside vrf_socket() call
[mirror_frr.git] / lib / log.c
1 /*
2 * Logging of zebra
3 * Copyright (C) 1997, 1998, 1999 Kunihiro Ishiguro
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; see the file COPYING; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #define FRR_DEFINE_DESC_TABLE
23
24 #include <zebra.h>
25
26 #include "zclient.h"
27 #include "log.h"
28 #include "log_int.h"
29 #include "memory.h"
30 #include "command.h"
31 #include "lib_errors.h"
32 #include "lib/hook.h"
33
34 #ifndef SUNOS_5
35 #include <sys/un.h>
36 #endif
37 /* for printstack on solaris */
38 #ifdef HAVE_UCONTEXT_H
39 #include <ucontext.h>
40 #endif
41
42 #ifdef HAVE_LIBUNWIND
43 #define UNW_LOCAL_ONLY
44 #include <libunwind.h>
45 #include <dlfcn.h>
46 #endif
47
48 DEFINE_MTYPE_STATIC(LIB, ZLOG, "Logging")
49
50 /* hook for external logging */
51 DEFINE_HOOK(zebra_ext_log, (int priority, const char *format, va_list args),
52 (priority, format, args));
53
54 static int logfile_fd = -1; /* Used in signal handler. */
55
56 struct zlog *zlog_default = NULL;
57 bool zlog_startup_stderr = true;
58
59 /* lock protecting zlog_default for mt-safe zlog */
60 static pthread_mutex_t loglock = PTHREAD_MUTEX_INITIALIZER;
61
62 const char *zlog_priority[] = {
63 "emergencies", "alerts", "critical", "errors", "warnings",
64 "notifications", "informational", "debugging", NULL,
65 };
66
67 /*
68 * write_wrapper
69 *
70 * glibc has declared that the return value from write *must* not be
71 * ignored.
72 * gcc see's this problem and issues a warning for the line.
73 *
74 * Why is this a big deal you say? Because both of them are right
75 * and if you have -Werror enabled then all calls to write
76 * generate a build error and the build stops.
77 *
78 * clang has helpfully allowed this construct:
79 * (void)write(...)
80 * to tell the compiler yeah I know it has a return value
81 * I don't care about it at this time.
82 * gcc doesn't have this ability.
83 *
84 * This code was written such that it didn't care about the
85 * return value from write. At this time do I want
86 * to go through and fix and test this code for correctness.
87 * So just wrapper the bad behavior and move on.
88 */
89 static void write_wrapper(int fd, const void *buf, size_t count)
90 {
91 if (write(fd, buf, count) <= 0)
92 return;
93
94 return;
95 }
96
97 /**
98 * Looks up a message in a message list by key.
99 *
100 * If the message is not found, returns the provided error message.
101 *
102 * Terminates when it hits a struct message that's all zeros.
103 *
104 * @param mz the message list
105 * @param kz the message key
106 * @param nf the message to return if not found
107 * @return the message
108 */
109 const char *lookup_msg(const struct message *mz, int kz, const char *nf)
110 {
111 static struct message nt = {0};
112 const char *rz = nf ? nf : "(no message found)";
113 const struct message *pnt;
114 for (pnt = mz; memcmp(pnt, &nt, sizeof(struct message)); pnt++)
115 if (pnt->key == kz) {
116 rz = pnt->str ? pnt->str : rz;
117 break;
118 }
119 return rz;
120 }
121
122 /* For time string format. */
123 size_t quagga_timestamp(int timestamp_precision, char *buf, size_t buflen)
124 {
125 static struct {
126 time_t last;
127 size_t len;
128 char buf[28];
129 } cache;
130 struct timeval clock;
131
132 gettimeofday(&clock, NULL);
133
134 /* first, we update the cache if the time has changed */
135 if (cache.last != clock.tv_sec) {
136 struct tm *tm;
137 cache.last = clock.tv_sec;
138 tm = localtime(&cache.last);
139 cache.len = strftime(cache.buf, sizeof(cache.buf),
140 "%Y/%m/%d %H:%M:%S", tm);
141 }
142 /* note: it's not worth caching the subsecond part, because
143 chances are that back-to-back calls are not sufficiently close
144 together
145 for the clock not to have ticked forward */
146
147 if (buflen > cache.len) {
148 memcpy(buf, cache.buf, cache.len);
149 if ((timestamp_precision > 0)
150 && (buflen > cache.len + 1 + timestamp_precision)) {
151 /* should we worry about locale issues? */
152 static const int divisor[] = {0, 100000, 10000, 1000,
153 100, 10, 1};
154 int prec;
155 char *p = buf + cache.len + 1
156 + (prec = timestamp_precision);
157 *p-- = '\0';
158 while (prec > 6)
159 /* this is unlikely to happen, but protect anyway */
160 {
161 *p-- = '0';
162 prec--;
163 }
164 clock.tv_usec /= divisor[prec];
165 do {
166 *p-- = '0' + (clock.tv_usec % 10);
167 clock.tv_usec /= 10;
168 } while (--prec > 0);
169 *p = '.';
170 return cache.len + 1 + timestamp_precision;
171 }
172 buf[cache.len] = '\0';
173 return cache.len;
174 }
175 if (buflen > 0)
176 buf[0] = '\0';
177 return 0;
178 }
179
180 /* Utility routine for current time printing. */
181 static void time_print(FILE *fp, struct timestamp_control *ctl)
182 {
183 if (!ctl->already_rendered) {
184 ctl->len = quagga_timestamp(ctl->precision, ctl->buf,
185 sizeof(ctl->buf));
186 ctl->already_rendered = 1;
187 }
188 fprintf(fp, "%s ", ctl->buf);
189 }
190
191
192 static void vzlog_file(struct zlog *zl, struct timestamp_control *tsctl,
193 const char *proto_str, int record_priority, int priority,
194 FILE *fp, const char *format, va_list args)
195 {
196 va_list ac;
197
198 time_print(fp, tsctl);
199 if (record_priority)
200 fprintf(fp, "%s: ", zlog_priority[priority]);
201
202 fprintf(fp, "%s", proto_str);
203 va_copy(ac, args);
204 vfprintf(fp, format, ac);
205 va_end(ac);
206 fprintf(fp, "\n");
207 fflush(fp);
208 }
209
210 /* va_list version of zlog. */
211 void vzlog(int priority, const char *format, va_list args)
212 {
213 pthread_mutex_lock(&loglock);
214
215 char proto_str[32];
216 int original_errno = errno;
217 struct timestamp_control tsctl;
218 tsctl.already_rendered = 0;
219 struct zlog *zl = zlog_default;
220
221 /* call external hook */
222 hook_call(zebra_ext_log, priority, format, args);
223
224 /* When zlog_default is also NULL, use stderr for logging. */
225 if (zl == NULL) {
226 tsctl.precision = 0;
227 time_print(stderr, &tsctl);
228 fprintf(stderr, "%s: ", "unknown");
229 vfprintf(stderr, format, args);
230 fprintf(stderr, "\n");
231 fflush(stderr);
232
233 /* In this case we return at here. */
234 errno = original_errno;
235 pthread_mutex_unlock(&loglock);
236 return;
237 }
238 tsctl.precision = zl->timestamp_precision;
239
240 /* Syslog output */
241 if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG]) {
242 va_list ac;
243 va_copy(ac, args);
244 vsyslog(priority | zlog_default->facility, format, ac);
245 va_end(ac);
246 }
247
248 if (zl->instance)
249 sprintf(proto_str, "%s[%d]: ", zl->protoname, zl->instance);
250 else
251 sprintf(proto_str, "%s: ", zl->protoname);
252
253 /* File output. */
254 if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
255 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
256 zl->fp, format, args);
257
258 /* fixed-config logging to stderr while we're stating up & haven't
259 * daemonized / reached mainloop yet
260 *
261 * note the "else" on stdout output -- we don't want to print the same
262 * message to both stderr and stdout. */
263 if (zlog_startup_stderr && priority <= LOG_WARNING)
264 vzlog_file(zl, &tsctl, proto_str, 1, priority, stderr, format,
265 args);
266 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
267 vzlog_file(zl, &tsctl, proto_str, zl->record_priority, priority,
268 stdout, format, args);
269
270 /* Terminal monitor. */
271 if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
272 vty_log((zl->record_priority ? zlog_priority[priority] : NULL),
273 proto_str, format, &tsctl, args);
274
275 errno = original_errno;
276 pthread_mutex_unlock(&loglock);
277 }
278
279 int vzlog_test(int priority)
280 {
281 pthread_mutex_lock(&loglock);
282
283 int ret = 0;
284
285 struct zlog *zl = zlog_default;
286
287 /* When zlog_default is also NULL, use stderr for logging. */
288 if (zl == NULL)
289 ret = 1;
290 /* Syslog output */
291 else if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG])
292 ret = 1;
293 /* File output. */
294 else if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp)
295 ret = 1;
296 /* stdout output. */
297 else if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT])
298 ret = 1;
299 /* Terminal monitor. */
300 else if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR])
301 ret = 1;
302
303 pthread_mutex_unlock(&loglock);
304
305 return ret;
306 }
307
308 static char *str_append(char *dst, int len, const char *src)
309 {
310 while ((len-- > 0) && *src)
311 *dst++ = *src++;
312 return dst;
313 }
314
315 static char *num_append(char *s, int len, unsigned long x)
316 {
317 char buf[30];
318 char *t;
319
320 if (!x)
321 return str_append(s, len, "0");
322 *(t = &buf[sizeof(buf) - 1]) = '\0';
323 while (x && (t > buf)) {
324 *--t = '0' + (x % 10);
325 x /= 10;
326 }
327 return str_append(s, len, t);
328 }
329
330 #if defined(SA_SIGINFO) \
331 || defined(HAVE_PRINTSTACK) \
332 || defined(HAVE_GLIBC_BACKTRACE)
333 static char *hex_append(char *s, int len, unsigned long x)
334 {
335 char buf[30];
336 char *t;
337
338 if (!x)
339 return str_append(s, len, "0");
340 *(t = &buf[sizeof(buf) - 1]) = '\0';
341 while (x && (t > buf)) {
342 unsigned int cc = (x % 16);
343 *--t = ((cc < 10) ? ('0' + cc) : ('a' + cc - 10));
344 x /= 16;
345 }
346 return str_append(s, len, t);
347 }
348 #endif
349
350 /* Needs to be enhanced to support Solaris. */
351 static int syslog_connect(void)
352 {
353 #ifdef SUNOS_5
354 return -1;
355 #else
356 int fd;
357 char *s;
358 struct sockaddr_un addr;
359
360 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
361 return -1;
362 addr.sun_family = AF_UNIX;
363 #ifdef _PATH_LOG
364 #define SYSLOG_SOCKET_PATH _PATH_LOG
365 #else
366 #define SYSLOG_SOCKET_PATH "/dev/log"
367 #endif
368 s = str_append(addr.sun_path, sizeof(addr.sun_path),
369 SYSLOG_SOCKET_PATH);
370 #undef SYSLOG_SOCKET_PATH
371 *s = '\0';
372 if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
373 close(fd);
374 return -1;
375 }
376 return fd;
377 #endif
378 }
379
380 static void syslog_sigsafe(int priority, const char *msg, size_t msglen)
381 {
382 static int syslog_fd = -1;
383 char buf[sizeof("<1234567890>ripngd[1234567890]: ") + msglen + 50];
384 char *s;
385
386 if ((syslog_fd < 0) && ((syslog_fd = syslog_connect()) < 0))
387 return;
388
389 #define LOC s,buf+sizeof(buf)-s
390 s = buf;
391 s = str_append(LOC, "<");
392 s = num_append(LOC, priority);
393 s = str_append(LOC, ">");
394 /* forget about the timestamp, too difficult in a signal handler */
395 s = str_append(LOC, zlog_default->ident);
396 if (zlog_default->syslog_options & LOG_PID) {
397 s = str_append(LOC, "[");
398 s = num_append(LOC, getpid());
399 s = str_append(LOC, "]");
400 }
401 s = str_append(LOC, ": ");
402 s = str_append(LOC, msg);
403 write_wrapper(syslog_fd, buf, s - buf);
404 #undef LOC
405 }
406
407 static int open_crashlog(void)
408 {
409 #define CRASHLOG_PREFIX "/var/tmp/quagga."
410 #define CRASHLOG_SUFFIX "crashlog"
411 if (zlog_default && zlog_default->ident) {
412 /* Avoid strlen since it is not async-signal-safe. */
413 const char *p;
414 size_t ilen;
415
416 for (p = zlog_default->ident, ilen = 0; *p; p++)
417 ilen++;
418 {
419 char buf[sizeof(CRASHLOG_PREFIX) + ilen
420 + sizeof(CRASHLOG_SUFFIX) + 3];
421 char *s = buf;
422 #define LOC s,buf+sizeof(buf)-s
423 s = str_append(LOC, CRASHLOG_PREFIX);
424 s = str_append(LOC, zlog_default->ident);
425 s = str_append(LOC, ".");
426 s = str_append(LOC, CRASHLOG_SUFFIX);
427 #undef LOC
428 *s = '\0';
429 return open(buf, O_WRONLY | O_CREAT | O_EXCL,
430 LOGFILE_MASK);
431 }
432 }
433 return open(CRASHLOG_PREFIX CRASHLOG_SUFFIX,
434 O_WRONLY | O_CREAT | O_EXCL, LOGFILE_MASK);
435 #undef CRASHLOG_SUFFIX
436 #undef CRASHLOG_PREFIX
437 }
438
439 /* Note: the goal here is to use only async-signal-safe functions. */
440 void zlog_signal(int signo, const char *action
441 #ifdef SA_SIGINFO
442 ,
443 siginfo_t *siginfo, void *program_counter
444 #endif
445 )
446 {
447 time_t now;
448 char buf[sizeof("DEFAULT: Received signal S at T (si_addr 0xP, PC 0xP); aborting...")
449 + 100];
450 char *s = buf;
451 char *msgstart = buf;
452 #define LOC s,buf+sizeof(buf)-s
453
454 time(&now);
455 if (zlog_default) {
456 s = str_append(LOC, zlog_default->protoname);
457 *s++ = ':';
458 *s++ = ' ';
459 msgstart = s;
460 }
461 s = str_append(LOC, "Received signal ");
462 s = num_append(LOC, signo);
463 s = str_append(LOC, " at ");
464 s = num_append(LOC, now);
465 #ifdef SA_SIGINFO
466 s = str_append(LOC, " (si_addr 0x");
467 s = hex_append(LOC, (unsigned long)(siginfo->si_addr));
468 if (program_counter) {
469 s = str_append(LOC, ", PC 0x");
470 s = hex_append(LOC, (unsigned long)program_counter);
471 }
472 s = str_append(LOC, "); ");
473 #else /* SA_SIGINFO */
474 s = str_append(LOC, "; ");
475 #endif /* SA_SIGINFO */
476 s = str_append(LOC, action);
477 if (s < buf + sizeof(buf))
478 *s++ = '\n';
479
480 /* N.B. implicit priority is most severe */
481 #define PRI LOG_CRIT
482
483 #define DUMP(FD) write_wrapper(FD, buf, s-buf);
484 /* If no file logging configured, try to write to fallback log file. */
485 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
486 DUMP(logfile_fd)
487 if (!zlog_default)
488 DUMP(STDERR_FILENO)
489 else {
490 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
491 DUMP(STDOUT_FILENO)
492 /* Remove trailing '\n' for monitor and syslog */
493 *--s = '\0';
494 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
495 vty_log_fixed(buf, s - buf);
496 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
497 syslog_sigsafe(PRI | zlog_default->facility, msgstart,
498 s - msgstart);
499 }
500 #undef DUMP
501
502 zlog_backtrace_sigsafe(PRI,
503 #ifdef SA_SIGINFO
504 program_counter
505 #else
506 NULL
507 #endif
508 );
509
510 s = buf;
511 struct thread *tc;
512 tc = pthread_getspecific(thread_current);
513 if (!tc)
514 s = str_append(LOC, "no thread information available\n");
515 else {
516 s = str_append(LOC, "in thread ");
517 s = str_append(LOC, tc->funcname);
518 s = str_append(LOC, " scheduled from ");
519 s = str_append(LOC, tc->schedfrom);
520 s = str_append(LOC, ":");
521 s = num_append(LOC, tc->schedfrom_line);
522 s = str_append(LOC, "\n");
523 }
524
525 #define DUMP(FD) write_wrapper(FD, buf, s-buf);
526 /* If no file logging configured, try to write to fallback log file. */
527 if (logfile_fd >= 0)
528 DUMP(logfile_fd)
529 if (!zlog_default)
530 DUMP(STDERR_FILENO)
531 else {
532 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
533 DUMP(STDOUT_FILENO)
534 /* Remove trailing '\n' for monitor and syslog */
535 *--s = '\0';
536 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
537 vty_log_fixed(buf, s - buf);
538 if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
539 syslog_sigsafe(PRI | zlog_default->facility, msgstart,
540 s - msgstart);
541 }
542 #undef DUMP
543
544 #undef PRI
545 #undef LOC
546 }
547
548 /* Log a backtrace using only async-signal-safe functions.
549 Needs to be enhanced to support syslog logging. */
550 void zlog_backtrace_sigsafe(int priority, void *program_counter)
551 {
552 #ifdef HAVE_LIBUNWIND
553 char buf[100];
554 unw_cursor_t cursor;
555 unw_context_t uc;
556 unw_word_t ip, off, sp;
557 Dl_info dlinfo;
558
559 unw_getcontext(&uc);
560 unw_init_local(&cursor, &uc);
561 while (unw_step(&cursor) > 0) {
562 char name[128] = "?";
563
564 unw_get_reg(&cursor, UNW_REG_IP, &ip);
565 unw_get_reg(&cursor, UNW_REG_SP, &sp);
566
567 if (unw_is_signal_frame(&cursor))
568 dprintf(2, " ---- signal ----\n");
569
570 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off)) {
571 snprintf(name, sizeof(name), "%s+%#lx",
572 buf, (long)off);
573 }
574 dprintf(2, "%-30s %16lx %16lx", name, (long)ip, (long)sp);
575 if (dladdr((void *)ip, &dlinfo)) {
576 dprintf(2, " %s (mapped at %p)",
577 dlinfo.dli_fname, dlinfo.dli_fbase);
578 }
579 dprintf(2, "\n");
580
581 }
582 #elif defined(HAVE_GLIBC_BACKTRACE) || defined(HAVE_PRINTSTACK)
583 static const char pclabel[] = "Program counter: ";
584 void *array[64];
585 int size;
586 char buf[100];
587 char *s, **bt = NULL;
588 #define LOC s,buf+sizeof(buf)-s
589
590 #ifdef HAVE_GLIBC_BACKTRACE
591 size = backtrace(array, array_size(array));
592 if (size <= 0 || (size_t)size > array_size(array))
593 return;
594
595 #define DUMP(FD) \
596 { \
597 if (program_counter) { \
598 write_wrapper(FD, pclabel, sizeof(pclabel) - 1); \
599 backtrace_symbols_fd(&program_counter, 1, FD); \
600 } \
601 write_wrapper(FD, buf, s - buf); \
602 backtrace_symbols_fd(array, size, FD); \
603 }
604 #elif defined(HAVE_PRINTSTACK)
605 #define DUMP(FD) \
606 { \
607 if (program_counter) \
608 write_wrapper((FD), pclabel, sizeof(pclabel) - 1); \
609 write_wrapper((FD), buf, s - buf); \
610 printstack((FD)); \
611 }
612 #endif /* HAVE_GLIBC_BACKTRACE, HAVE_PRINTSTACK */
613
614 s = buf;
615 s = str_append(LOC, "Backtrace for ");
616 s = num_append(LOC, size);
617 s = str_append(LOC, " stack frames:\n");
618
619 if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0))
620 DUMP(logfile_fd)
621 if (!zlog_default)
622 DUMP(STDERR_FILENO)
623 else {
624 if (priority <= zlog_default->maxlvl[ZLOG_DEST_STDOUT])
625 DUMP(STDOUT_FILENO)
626 /* Remove trailing '\n' for monitor and syslog */
627 *--s = '\0';
628 if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
629 vty_log_fixed(buf, s - buf);
630 if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
631 syslog_sigsafe(priority | zlog_default->facility, buf,
632 s - buf);
633 {
634 int i;
635 #ifdef HAVE_GLIBC_BACKTRACE
636 bt = backtrace_symbols(array, size);
637 #endif
638 /* Just print the function addresses. */
639 for (i = 0; i < size; i++) {
640 s = buf;
641 if (bt)
642 s = str_append(LOC, bt[i]);
643 else {
644 s = str_append(LOC, "[bt ");
645 s = num_append(LOC, i);
646 s = str_append(LOC, "] 0x");
647 s = hex_append(
648 LOC, (unsigned long)(array[i]));
649 }
650 *s = '\0';
651 if (priority
652 <= zlog_default->maxlvl[ZLOG_DEST_MONITOR])
653 vty_log_fixed(buf, s - buf);
654 if (priority
655 <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG])
656 syslog_sigsafe(
657 priority
658 | zlog_default
659 ->facility,
660 buf, s - buf);
661 }
662 if (bt)
663 free(bt);
664 }
665 }
666 #undef DUMP
667 #undef LOC
668 #endif /* HAVE_STRACK_TRACE */
669 }
670
671 void zlog_backtrace(int priority)
672 {
673 #ifdef HAVE_LIBUNWIND
674 char buf[100];
675 unw_cursor_t cursor;
676 unw_context_t uc;
677 unw_word_t ip, off, sp;
678 Dl_info dlinfo;
679
680 unw_getcontext(&uc);
681 unw_init_local(&cursor, &uc);
682 zlog(priority, "Backtrace:");
683 while (unw_step(&cursor) > 0) {
684 char name[128] = "?";
685
686 unw_get_reg(&cursor, UNW_REG_IP, &ip);
687 unw_get_reg(&cursor, UNW_REG_SP, &sp);
688
689 if (unw_is_signal_frame(&cursor))
690 zlog(priority, " ---- signal ----");
691
692 if (!unw_get_proc_name(&cursor, buf, sizeof(buf), &off))
693 snprintf(name, sizeof(name), "%s+%#lx",
694 buf, (long)off);
695
696 if (dladdr((void *)ip, &dlinfo))
697 zlog(priority, "%-30s %16lx %16lx %s (mapped at %p)",
698 name, (long)ip, (long)sp,
699 dlinfo.dli_fname, dlinfo.dli_fbase);
700 else
701 zlog(priority, "%-30s %16lx %16lx",
702 name, (long)ip, (long)sp);
703 }
704 #elif defined(HAVE_GLIBC_BACKTRACE)
705 void *array[20];
706 int size, i;
707 char **strings;
708
709 size = backtrace(array, array_size(array));
710 if (size <= 0 || (size_t)size > array_size(array)) {
711 flog_err_sys(
712 EC_LIB_SYSTEM_CALL,
713 "Cannot get backtrace, returned invalid # of frames %d "
714 "(valid range is between 1 and %lu)",
715 size, (unsigned long)(array_size(array)));
716 return;
717 }
718 zlog(priority, "Backtrace for %d stack frames:", size);
719 if (!(strings = backtrace_symbols(array, size))) {
720 flog_err_sys(EC_LIB_SYSTEM_CALL,
721 "Cannot get backtrace symbols (out of memory?)");
722 for (i = 0; i < size; i++)
723 zlog(priority, "[bt %d] %p", i, array[i]);
724 } else {
725 for (i = 0; i < size; i++)
726 zlog(priority, "[bt %d] %s", i, strings[i]);
727 free(strings);
728 }
729 #else /* !HAVE_GLIBC_BACKTRACE && !HAVE_LIBUNWIND */
730 zlog(priority, "No backtrace available on this platform.");
731 #endif
732 }
733
734 void zlog(int priority, const char *format, ...)
735 {
736 va_list args;
737
738 va_start(args, format);
739 vzlog(priority, format, args);
740 va_end(args);
741 }
742
743 #define ZLOG_FUNC(FUNCNAME, PRIORITY) \
744 void FUNCNAME(const char *format, ...) \
745 { \
746 va_list args; \
747 va_start(args, format); \
748 vzlog(PRIORITY, format, args); \
749 va_end(args); \
750 }
751
752 ZLOG_FUNC(zlog_err, LOG_ERR)
753
754 ZLOG_FUNC(zlog_warn, LOG_WARNING)
755
756 ZLOG_FUNC(zlog_info, LOG_INFO)
757
758 ZLOG_FUNC(zlog_notice, LOG_NOTICE)
759
760 ZLOG_FUNC(zlog_debug, LOG_DEBUG)
761
762 #undef ZLOG_FUNC
763
764 void zlog_thread_info(int log_level)
765 {
766 struct thread *tc;
767 tc = pthread_getspecific(thread_current);
768
769 if (tc)
770 zlog(log_level,
771 "Current thread function %s, scheduled from "
772 "file %s, line %u",
773 tc->funcname, tc->schedfrom, tc->schedfrom_line);
774 else
775 zlog(log_level, "Current thread not known/applicable");
776 }
777
778 void _zlog_assert_failed(const char *assertion, const char *file,
779 unsigned int line, const char *function)
780 {
781 /* Force fallback file logging? */
782 if (zlog_default && !zlog_default->fp
783 && ((logfile_fd = open_crashlog()) >= 0)
784 && ((zlog_default->fp = fdopen(logfile_fd, "w")) != NULL))
785 zlog_default->maxlvl[ZLOG_DEST_FILE] = LOG_ERR;
786 zlog(LOG_CRIT, "Assertion `%s' failed in file %s, line %u, function %s",
787 assertion, file, line, (function ? function : "?"));
788 zlog_backtrace(LOG_CRIT);
789 zlog_thread_info(LOG_CRIT);
790 log_memstats(stderr, "log");
791 abort();
792 }
793
794 void memory_oom(size_t size, const char *name)
795 {
796 flog_err_sys(EC_LIB_SYSTEM_CALL,
797 "out of memory: failed to allocate %zu bytes for %s"
798 "object",
799 size, name);
800 zlog_backtrace(LOG_ERR);
801 abort();
802 }
803
804 /* Open log stream */
805 void openzlog(const char *progname, const char *protoname,
806 unsigned short instance, int syslog_flags, int syslog_facility)
807 {
808 struct zlog *zl;
809 unsigned int i;
810
811 zl = XCALLOC(MTYPE_ZLOG, sizeof(struct zlog));
812
813 zl->ident = progname;
814 zl->protoname = protoname;
815 zl->instance = instance;
816 zl->facility = syslog_facility;
817 zl->syslog_options = syslog_flags;
818
819 /* Set default logging levels. */
820 for (i = 0; i < array_size(zl->maxlvl); i++)
821 zl->maxlvl[i] = ZLOG_DISABLED;
822 zl->maxlvl[ZLOG_DEST_MONITOR] = LOG_DEBUG;
823 zl->default_lvl = LOG_DEBUG;
824
825 openlog(progname, syslog_flags, zl->facility);
826
827 pthread_mutex_lock(&loglock);
828 zlog_default = zl;
829 pthread_mutex_unlock(&loglock);
830
831 #ifdef HAVE_GLIBC_BACKTRACE
832 /* work around backtrace() using lazily resolved dynamically linked
833 * symbols, which will otherwise cause funny breakage in the SEGV
834 * handler.
835 * (particularly, the dynamic linker can call malloc(), which uses locks
836 * in programs linked with -pthread, thus can deadlock.) */
837 void *bt[4];
838 backtrace(bt, array_size(bt));
839 free(backtrace_symbols(bt, 0));
840 backtrace_symbols_fd(bt, 0, 0);
841 #endif
842 }
843
844 void closezlog(void)
845 {
846 pthread_mutex_lock(&loglock);
847 struct zlog *zl = zlog_default;
848
849 closelog();
850
851 if (zl->fp != NULL)
852 fclose(zl->fp);
853
854 XFREE(MTYPE_ZLOG, zl->filename);
855
856 XFREE(MTYPE_ZLOG, zl);
857 zlog_default = NULL;
858 pthread_mutex_unlock(&loglock);
859 }
860
861 /* Called from command.c. */
862 void zlog_set_level(zlog_dest_t dest, int log_level)
863 {
864 pthread_mutex_lock(&loglock);
865 zlog_default->maxlvl[dest] = log_level;
866 pthread_mutex_unlock(&loglock);
867 }
868
869 int zlog_set_file(const char *filename, int log_level)
870 {
871 struct zlog *zl;
872 FILE *fp;
873 mode_t oldumask;
874 int ret = 1;
875
876 /* There is opend file. */
877 zlog_reset_file();
878
879 /* Open file. */
880 oldumask = umask(0777 & ~LOGFILE_MASK);
881 fp = fopen(filename, "a");
882 umask(oldumask);
883 if (fp == NULL) {
884 ret = 0;
885 } else {
886 pthread_mutex_lock(&loglock);
887 zl = zlog_default;
888
889 /* Set flags. */
890 zl->filename = XSTRDUP(MTYPE_ZLOG, filename);
891 zl->maxlvl[ZLOG_DEST_FILE] = log_level;
892 zl->fp = fp;
893 logfile_fd = fileno(fp);
894 pthread_mutex_unlock(&loglock);
895 }
896
897 return ret;
898 }
899
900 /* Reset opend file. */
901 int zlog_reset_file(void)
902 {
903 pthread_mutex_lock(&loglock);
904
905 struct zlog *zl = zlog_default;
906
907 if (zl->fp)
908 fclose(zl->fp);
909 zl->fp = NULL;
910 logfile_fd = -1;
911 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
912
913 XFREE(MTYPE_ZLOG, zl->filename);
914 zl->filename = NULL;
915
916 pthread_mutex_unlock(&loglock);
917
918 return 1;
919 }
920
921 /* Reopen log file. */
922 int zlog_rotate(void)
923 {
924 pthread_mutex_lock(&loglock);
925
926 struct zlog *zl = zlog_default;
927 int level;
928 int ret = 1;
929
930 if (zl->fp)
931 fclose(zl->fp);
932 zl->fp = NULL;
933 logfile_fd = -1;
934 level = zl->maxlvl[ZLOG_DEST_FILE];
935 zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED;
936
937 if (zl->filename) {
938 mode_t oldumask;
939 int save_errno;
940
941 oldumask = umask(0777 & ~LOGFILE_MASK);
942 zl->fp = fopen(zl->filename, "a");
943 save_errno = errno;
944 umask(oldumask);
945 if (zl->fp == NULL) {
946
947 pthread_mutex_unlock(&loglock);
948
949 flog_err_sys(
950 EC_LIB_SYSTEM_CALL,
951 "Log rotate failed: cannot open file %s for append: %s",
952 zl->filename, safe_strerror(save_errno));
953 ret = -1;
954
955 pthread_mutex_lock(&loglock);
956 } else {
957 logfile_fd = fileno(zl->fp);
958 zl->maxlvl[ZLOG_DEST_FILE] = level;
959 }
960 }
961
962 pthread_mutex_unlock(&loglock);
963
964 return ret;
965 }
966
967 /* Wrapper around strerror to handle case where it returns NULL. */
968 const char *safe_strerror(int errnum)
969 {
970 const char *s = strerror(errnum);
971 return (s != NULL) ? s : "Unknown error";
972 }
973
974 #define DESC_ENTRY(T) [(T)] = { (T), (#T), '\0' }
975 static const struct zebra_desc_table command_types[] = {
976 DESC_ENTRY(ZEBRA_INTERFACE_ADD),
977 DESC_ENTRY(ZEBRA_INTERFACE_DELETE),
978 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_ADD),
979 DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_DELETE),
980 DESC_ENTRY(ZEBRA_INTERFACE_UP),
981 DESC_ENTRY(ZEBRA_INTERFACE_DOWN),
982 DESC_ENTRY(ZEBRA_INTERFACE_SET_MASTER),
983 DESC_ENTRY(ZEBRA_ROUTE_ADD),
984 DESC_ENTRY(ZEBRA_ROUTE_DELETE),
985 DESC_ENTRY(ZEBRA_ROUTE_NOTIFY_OWNER),
986 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ADD),
987 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DELETE),
988 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_ADD),
989 DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_DELETE),
990 DESC_ENTRY(ZEBRA_ROUTER_ID_ADD),
991 DESC_ENTRY(ZEBRA_ROUTER_ID_DELETE),
992 DESC_ENTRY(ZEBRA_ROUTER_ID_UPDATE),
993 DESC_ENTRY(ZEBRA_HELLO),
994 DESC_ENTRY(ZEBRA_CAPABILITIES),
995 DESC_ENTRY(ZEBRA_NEXTHOP_REGISTER),
996 DESC_ENTRY(ZEBRA_NEXTHOP_UNREGISTER),
997 DESC_ENTRY(ZEBRA_NEXTHOP_UPDATE),
998 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_ADD),
999 DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_DELETE),
1000 DESC_ENTRY(ZEBRA_INTERFACE_BFD_DEST_UPDATE),
1001 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_REGISTER),
1002 DESC_ENTRY(ZEBRA_IMPORT_ROUTE_UNREGISTER),
1003 DESC_ENTRY(ZEBRA_IMPORT_CHECK_UPDATE),
1004 DESC_ENTRY(ZEBRA_BFD_DEST_REGISTER),
1005 DESC_ENTRY(ZEBRA_BFD_DEST_DEREGISTER),
1006 DESC_ENTRY(ZEBRA_BFD_DEST_UPDATE),
1007 DESC_ENTRY(ZEBRA_BFD_DEST_REPLAY),
1008 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_ADD),
1009 DESC_ENTRY(ZEBRA_REDISTRIBUTE_ROUTE_DEL),
1010 DESC_ENTRY(ZEBRA_VRF_UNREGISTER),
1011 DESC_ENTRY(ZEBRA_VRF_ADD),
1012 DESC_ENTRY(ZEBRA_VRF_DELETE),
1013 DESC_ENTRY(ZEBRA_VRF_LABEL),
1014 DESC_ENTRY(ZEBRA_INTERFACE_VRF_UPDATE),
1015 DESC_ENTRY(ZEBRA_BFD_CLIENT_REGISTER),
1016 DESC_ENTRY(ZEBRA_BFD_CLIENT_DEREGISTER),
1017 DESC_ENTRY(ZEBRA_INTERFACE_ENABLE_RADV),
1018 DESC_ENTRY(ZEBRA_INTERFACE_DISABLE_RADV),
1019 DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB),
1020 DESC_ENTRY(ZEBRA_INTERFACE_LINK_PARAMS),
1021 DESC_ENTRY(ZEBRA_MPLS_LABELS_ADD),
1022 DESC_ENTRY(ZEBRA_MPLS_LABELS_DELETE),
1023 DESC_ENTRY(ZEBRA_IPMR_ROUTE_STATS),
1024 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT),
1025 DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT_ASYNC),
1026 DESC_ENTRY(ZEBRA_GET_LABEL_CHUNK),
1027 DESC_ENTRY(ZEBRA_RELEASE_LABEL_CHUNK),
1028 DESC_ENTRY(ZEBRA_FEC_REGISTER),
1029 DESC_ENTRY(ZEBRA_FEC_UNREGISTER),
1030 DESC_ENTRY(ZEBRA_FEC_UPDATE),
1031 DESC_ENTRY(ZEBRA_ADVERTISE_ALL_VNI),
1032 DESC_ENTRY(ZEBRA_ADVERTISE_DEFAULT_GW),
1033 DESC_ENTRY(ZEBRA_ADVERTISE_SVI_MACIP),
1034 DESC_ENTRY(ZEBRA_ADVERTISE_SUBNET),
1035 DESC_ENTRY(ZEBRA_LOCAL_ES_ADD),
1036 DESC_ENTRY(ZEBRA_LOCAL_ES_DEL),
1037 DESC_ENTRY(ZEBRA_VNI_ADD),
1038 DESC_ENTRY(ZEBRA_VNI_DEL),
1039 DESC_ENTRY(ZEBRA_L3VNI_ADD),
1040 DESC_ENTRY(ZEBRA_L3VNI_DEL),
1041 DESC_ENTRY(ZEBRA_REMOTE_VTEP_ADD),
1042 DESC_ENTRY(ZEBRA_REMOTE_VTEP_DEL),
1043 DESC_ENTRY(ZEBRA_MACIP_ADD),
1044 DESC_ENTRY(ZEBRA_MACIP_DEL),
1045 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_ADD),
1046 DESC_ENTRY(ZEBRA_IP_PREFIX_ROUTE_DEL),
1047 DESC_ENTRY(ZEBRA_REMOTE_MACIP_ADD),
1048 DESC_ENTRY(ZEBRA_REMOTE_MACIP_DEL),
1049 DESC_ENTRY(ZEBRA_DUPLICATE_ADDR_DETECTION),
1050 DESC_ENTRY(ZEBRA_PW_ADD),
1051 DESC_ENTRY(ZEBRA_PW_DELETE),
1052 DESC_ENTRY(ZEBRA_PW_SET),
1053 DESC_ENTRY(ZEBRA_PW_UNSET),
1054 DESC_ENTRY(ZEBRA_PW_STATUS_UPDATE),
1055 DESC_ENTRY(ZEBRA_RULE_ADD),
1056 DESC_ENTRY(ZEBRA_RULE_DELETE),
1057 DESC_ENTRY(ZEBRA_RULE_NOTIFY_OWNER),
1058 DESC_ENTRY(ZEBRA_TABLE_MANAGER_CONNECT),
1059 DESC_ENTRY(ZEBRA_GET_TABLE_CHUNK),
1060 DESC_ENTRY(ZEBRA_RELEASE_TABLE_CHUNK),
1061 DESC_ENTRY(ZEBRA_IPSET_CREATE),
1062 DESC_ENTRY(ZEBRA_IPSET_DESTROY),
1063 DESC_ENTRY(ZEBRA_IPSET_ENTRY_ADD),
1064 DESC_ENTRY(ZEBRA_IPSET_ENTRY_DELETE),
1065 DESC_ENTRY(ZEBRA_IPSET_NOTIFY_OWNER),
1066 DESC_ENTRY(ZEBRA_IPSET_ENTRY_NOTIFY_OWNER),
1067 DESC_ENTRY(ZEBRA_IPTABLE_ADD),
1068 DESC_ENTRY(ZEBRA_IPTABLE_DELETE),
1069 DESC_ENTRY(ZEBRA_IPTABLE_NOTIFY_OWNER),
1070 DESC_ENTRY(ZEBRA_VXLAN_FLOOD_CONTROL),
1071 DESC_ENTRY(ZEBRA_VXLAN_SG_ADD),
1072 DESC_ENTRY(ZEBRA_VXLAN_SG_DEL),
1073 };
1074 #undef DESC_ENTRY
1075
1076 static const struct zebra_desc_table unknown = {0, "unknown", '?'};
1077
1078 static const struct zebra_desc_table *zroute_lookup(unsigned int zroute)
1079 {
1080 unsigned int i;
1081
1082 if (zroute >= array_size(route_types)) {
1083 flog_err(EC_LIB_DEVELOPMENT, "unknown zebra route type: %u",
1084 zroute);
1085 return &unknown;
1086 }
1087 if (zroute == route_types[zroute].type)
1088 return &route_types[zroute];
1089 for (i = 0; i < array_size(route_types); i++) {
1090 if (zroute == route_types[i].type) {
1091 zlog_warn(
1092 "internal error: route type table out of order "
1093 "while searching for %u, please notify developers",
1094 zroute);
1095 return &route_types[i];
1096 }
1097 }
1098 flog_err(EC_LIB_DEVELOPMENT,
1099 "internal error: cannot find route type %u in table!", zroute);
1100 return &unknown;
1101 }
1102
1103 const char *zebra_route_string(unsigned int zroute)
1104 {
1105 return zroute_lookup(zroute)->string;
1106 }
1107
1108 char zebra_route_char(unsigned int zroute)
1109 {
1110 return zroute_lookup(zroute)->chr;
1111 }
1112
1113 const char *zserv_command_string(unsigned int command)
1114 {
1115 if (command >= array_size(command_types)) {
1116 flog_err(EC_LIB_DEVELOPMENT, "unknown zserv command type: %u",
1117 command);
1118 return unknown.string;
1119 }
1120 return command_types[command].string;
1121 }
1122
1123 int proto_name2num(const char *s)
1124 {
1125 unsigned i;
1126
1127 for (i = 0; i < array_size(route_types); ++i)
1128 if (strcasecmp(s, route_types[i].string) == 0)
1129 return route_types[i].type;
1130 return -1;
1131 }
1132
1133 int proto_redistnum(int afi, const char *s)
1134 {
1135 if (!s)
1136 return -1;
1137
1138 if (afi == AFI_IP) {
1139 if (strmatch(s, "kernel"))
1140 return ZEBRA_ROUTE_KERNEL;
1141 else if (strmatch(s, "connected"))
1142 return ZEBRA_ROUTE_CONNECT;
1143 else if (strmatch(s, "static"))
1144 return ZEBRA_ROUTE_STATIC;
1145 else if (strmatch(s, "rip"))
1146 return ZEBRA_ROUTE_RIP;
1147 else if (strmatch(s, "eigrp"))
1148 return ZEBRA_ROUTE_EIGRP;
1149 else if (strmatch(s, "ospf"))
1150 return ZEBRA_ROUTE_OSPF;
1151 else if (strmatch(s, "isis"))
1152 return ZEBRA_ROUTE_ISIS;
1153 else if (strmatch(s, "bgp"))
1154 return ZEBRA_ROUTE_BGP;
1155 else if (strmatch(s, "table"))
1156 return ZEBRA_ROUTE_TABLE;
1157 else if (strmatch(s, "vnc"))
1158 return ZEBRA_ROUTE_VNC;
1159 else if (strmatch(s, "vnc-direct"))
1160 return ZEBRA_ROUTE_VNC_DIRECT;
1161 else if (strmatch(s, "nhrp"))
1162 return ZEBRA_ROUTE_NHRP;
1163 else if (strmatch(s, "babel"))
1164 return ZEBRA_ROUTE_BABEL;
1165 else if (strmatch(s, "sharp"))
1166 return ZEBRA_ROUTE_SHARP;
1167 else if (strmatch(s, "openfabric"))
1168 return ZEBRA_ROUTE_OPENFABRIC;
1169 }
1170 if (afi == AFI_IP6) {
1171 if (strmatch(s, "kernel"))
1172 return ZEBRA_ROUTE_KERNEL;
1173 else if (strmatch(s, "connected"))
1174 return ZEBRA_ROUTE_CONNECT;
1175 else if (strmatch(s, "static"))
1176 return ZEBRA_ROUTE_STATIC;
1177 else if (strmatch(s, "ripng"))
1178 return ZEBRA_ROUTE_RIPNG;
1179 else if (strmatch(s, "ospf6"))
1180 return ZEBRA_ROUTE_OSPF6;
1181 else if (strmatch(s, "isis"))
1182 return ZEBRA_ROUTE_ISIS;
1183 else if (strmatch(s, "bgp"))
1184 return ZEBRA_ROUTE_BGP;
1185 else if (strmatch(s, "table"))
1186 return ZEBRA_ROUTE_TABLE;
1187 else if (strmatch(s, "vnc"))
1188 return ZEBRA_ROUTE_VNC;
1189 else if (strmatch(s, "vnc-direct"))
1190 return ZEBRA_ROUTE_VNC_DIRECT;
1191 else if (strmatch(s, "nhrp"))
1192 return ZEBRA_ROUTE_NHRP;
1193 else if (strmatch(s, "babel"))
1194 return ZEBRA_ROUTE_BABEL;
1195 else if (strmatch(s, "sharp"))
1196 return ZEBRA_ROUTE_SHARP;
1197 else if (strmatch(s, "openfabric"))
1198 return ZEBRA_ROUTE_OPENFABRIC;
1199 }
1200 return -1;
1201 }
1202
1203 void zlog_hexdump(const void *mem, unsigned int len)
1204 {
1205 unsigned long i = 0;
1206 unsigned int j = 0;
1207 unsigned int columns = 8;
1208 /*
1209 * 19 bytes for 0xADDRESS:
1210 * 24 bytes for data; 2 chars plus a space per data byte
1211 * 1 byte for space
1212 * 8 bytes for ASCII representation
1213 * 1 byte for a newline
1214 * =====================
1215 * 53 bytes per 8 bytes of data
1216 * 1 byte for null term
1217 */
1218 size_t bs = ((len / 8) + 1) * 53 + 1;
1219 char buf[bs];
1220 char *s = buf;
1221
1222 memset(buf, 0, sizeof(buf));
1223
1224 for (i = 0; i < len + ((len % columns) ? (columns - len % columns) : 0);
1225 i++) {
1226 /* print offset */
1227 if (i % columns == 0)
1228 s += snprintf(s, bs - (s - buf),
1229 "0x%016lx: ", (unsigned long)mem + i);
1230
1231 /* print hex data */
1232 if (i < len)
1233 s += snprintf(s, bs - (s - buf), "%02x ",
1234 0xFF & ((const char *)mem)[i]);
1235
1236 /* end of block, just aligning for ASCII dump */
1237 else
1238 s += snprintf(s, bs - (s - buf), " ");
1239
1240 /* print ASCII dump */
1241 if (i % columns == (columns - 1)) {
1242 for (j = i - (columns - 1); j <= i; j++) {
1243 /* end of block not really printing */
1244 if (j >= len)
1245 s += snprintf(s, bs - (s - buf), " ");
1246 else if (isprint((int)((const char *)mem)[j]))
1247 s += snprintf(
1248 s, bs - (s - buf), "%c",
1249 0xFF & ((const char *)mem)[j]);
1250 else /* other char */
1251 s += snprintf(s, bs - (s - buf), ".");
1252 }
1253 s += snprintf(s, bs - (s - buf), "\n");
1254 }
1255 }
1256 zlog_debug("\n%s", buf);
1257 }
1258
1259 const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, size_t inlen)
1260 {
1261 const char *inbuf = in;
1262 char *pos = buf, *end = buf + bufsz;
1263 const char *iend = inbuf + inlen;
1264
1265 memset(buf, 0, bufsz);
1266 for (; inbuf < iend; inbuf++) {
1267 /* don't write partial escape sequence */
1268 if (end - pos < 5)
1269 break;
1270
1271 if (*inbuf == '\n')
1272 snprintf(pos, end - pos, "\\n");
1273 else if (*inbuf == '\r')
1274 snprintf(pos, end - pos, "\\r");
1275 else if (*inbuf == '\t')
1276 snprintf(pos, end - pos, "\\t");
1277 else if (*inbuf < ' ' || *inbuf == '"' || *inbuf >= 127)
1278 snprintf(pos, end - pos, "\\x%02hhx", *inbuf);
1279 else
1280 *pos = *inbuf;
1281
1282 pos += strlen(pos);
1283 }
1284 return buf;
1285 }