#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <err.h>
#define SYSLOG_NAMES
#include <syslog.h>
int decode(char *, CODE *);
int pencode(char *);
void usage(void);
int
main(int argc, char *argv[])
{
int ch, logflags, pri;
char *tag, buf[1024];
tag = NULL;
pri = LOG_NOTICE;
logflags = 0;
while ((ch = getopt(argc, argv, "cf:ip:st:")) != -1)
switch(ch) {
case 'c':
logflags |= LOG_CONS;
break;
case 'f':
if (freopen(optarg, "r", stdin) == NULL) {
(void)fprintf(stderr, "logger: %s: %s.\n",
optarg, strerror(errno));
exit(1);
}
break;
case 'i':
logflags |= LOG_PID;
break;
case 'p':
pri = pencode(optarg);
break;
case 's':
logflags |= LOG_PERROR;
break;
case 't':
tag = optarg;
break;
default:
usage();
}
argc -= optind;
argv += optind;
openlog(tag ? tag : getlogin(), logflags, 0);
(void) fclose(stdout);
if (pledge("stdio", NULL) == -1)
err(1, "pledge");
if (argc > 0) {
char *p, *endp;
size_t len;
for (p = buf, endp = buf + sizeof(buf) - 2; *argv;) {
len = strlen(*argv);
if (p + len > endp && p > buf) {
syslog(pri, "%s", buf);
p = buf;
}
if (len > sizeof(buf) - 1)
syslog(pri, "%s", *argv++);
else {
if (p != buf)
*p++ = ' ';
bcopy(*argv++, p, len);
*(p += len) = '\0';
}
}
if (p != buf)
syslog(pri, "%s", buf);
} else
while (fgets(buf, sizeof(buf), stdin) != NULL)
syslog(pri, "%s", buf);
exit(0);
}
int
pencode(char *s)
{
char *save;
int fac, lev;
for (save = s; *s && *s != '.'; ++s);
if (*s) {
*s = '\0';
fac = decode(save, facilitynames);
if (fac < 0) {
(void)fprintf(stderr,
"logger: unknown facility name: %s.\n", save);
exit(1);
}
*s++ = '.';
}
else {
fac = 0;
s = save;
}
lev = decode(s, prioritynames);
if (lev < 0) {
(void)fprintf(stderr,
"logger: unknown priority name: %s.\n", save);
exit(1);
}
return ((lev & LOG_PRIMASK) | (fac & LOG_FACMASK));
}
int
decode(char *name, CODE *codetab)
{
CODE *c;
if (isdigit((unsigned char)*name)) {
const char *errstr;
int n = strtonum(name, 0, INT_MAX, &errstr);
if (!errstr)
return (n);
}
for (c = codetab; c->c_name; c++)
if (!strcasecmp(name, c->c_name))
return (c->c_val);
return (-1);
}
void
usage(void)
{
(void)fprintf(stderr,
"usage: logger [-cis] [-f file] [-p pri] [-t tag] [message ...]\n");
exit(1);
}