toybox/toys/posix/logger.c
<<
>>
Prefs
   1/* logger.c - Log messages.
   2 *
   3 * Copyright 2013 Ilya Kuzmich <ilya.kuzmich@gmail.com>
   4 *
   5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/logger.html
   6 *
   7 * Deviations from posix: specified manner and format, defined implementation.
   8
   9USE_LOGGER(NEWTOY(logger, "t:p:s", TOYFLAG_USR|TOYFLAG_BIN))
  10
  11config LOGGER
  12  bool "logger"
  13  default y
  14  help
  15    usage: logger [-s] [-t TAG] [-p [FACILITY.]PRIORITY] [MESSAGE...]
  16
  17    Log message (or stdin) to syslog.
  18
  19    -s  Also write message to stderr
  20    -t  Use TAG instead of username to identify message source
  21    -p  Specify PRIORITY with optional FACILITY. Default is "user.notice"
  22*/
  23
  24#define FOR_logger
  25#include "toys.h"
  26
  27GLOBALS(
  28  char *p, *t;
  29)
  30
  31// find str in names[], accepting unambiguous short matches
  32// returns offset into array of match, or -1 if no match
  33// TODO: move to lib?
  34static int arrayfind(char *str, char *names[], int len)
  35{
  36  int j, i, ll = 0, maybe = -1;
  37
  38  for (j = 0; j<len; j++) for (i=0; ; i++) {
  39    if (!str[i]) {
  40      if (!names[j][i]) return j;
  41      if (i>ll) maybe = j;
  42      else if (i==ll) maybe = -1;
  43      break;
  44    }
  45    if (!names[j][i] || toupper(str[i])!=toupper(names[j][i])) break;
  46  }
  47
  48  return maybe;
  49}
  50
  51void logger_main(void)
  52{
  53  int facility = LOG_USER, priority = LOG_NOTICE, len = 0;
  54  char *s1, *s2, **arg,
  55    *priorities[] = {"emerg", "alert", "crit", "error", "warning", "notice",
  56                     "info", "debug"},
  57    *facilities[] = {"kern", "user", "mail", "daemon", "auth", "syslog",
  58                     "lpr", "news", "uucp", "cron", "authpriv", "ftp"};
  59
  60  if (!TT.t) TT.t = xgetpwuid(geteuid())->pw_name;
  61  if (TT.p) {
  62    if (!(s1 = strchr(TT.p, '.'))) s1 = TT.p;
  63    else {
  64      *s1++ = 0;
  65      facility = arrayfind(TT.p, facilities, ARRAY_LEN(facilities));
  66      if (facility<0) {
  67        if (sscanf(TT.p, "local%d", &facility)>0 && !(facility&~7))
  68          facility += 16;
  69        else error_exit("bad facility: %s", TT.p);
  70      }
  71      facility *= 8;
  72    }
  73
  74    priority = arrayfind(s1, priorities, ARRAY_LEN(priorities));
  75    if (priority<0) error_exit("bad priority: %s", s1);
  76  }
  77
  78  if (toys.optc) {
  79    for (arg = toys.optargs; *arg; arg++) len += strlen(*arg)+1;
  80    s1 = s2 = xmalloc(len);
  81    for (arg = toys.optargs; *arg; arg++) {
  82      if (arg != toys.optargs) *s2++ = ' ';
  83      s2 = stpcpy(s2, *arg);
  84    }
  85  } else toybuf[readall(0, s1 = toybuf, sizeof(toybuf)-1)] = 0;
  86
  87  openlog(TT.t, LOG_PERROR*FLAG(s), facility);
  88  syslog(priority, "%s", s1);
  89  closelog();
  90}
  91