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