Exemplo n.º 1
0
/* ugly workaround to handle facility numbers; values
 * derived from names need to be eight times smaller,
 * i.e.: 0..23
 */
static rsRetVal facilityHdlr(uchar **pp, void *pVal)
{
	DEFiRet;
	char *p;

	skipWhiteSpace(pp);
	p = (char *) *pp;

	if (isdigit((int) *p)) {
		*((int *) pVal) = (int) strtol(p, (char **) pp, 10);
	} else {
		int len;
		syslogName_t *c;

		for (len = 0; p[len] && !isspace((int) p[len]); len++)
			/* noop */;
		for (c = syslogFacNames; c->c_name; c++) {
			if (!strncasecmp(p, (char *) c->c_name, len)) {
				*((int *) pVal) = LOG_FAC(c->c_val);
				break;
			}
		}
		*pp += len;
	}

	RETiRet;
}
Exemplo n.º 2
0
/* enqueue the the kernel message into the message queue.
 * The provided msg string is not freed - thus must be done
 * by the caller.
 * rgerhards, 2008-04-12
 */
static rsRetVal
enqMsg(uchar *msg, uchar* pszTag, int iFacility, int iSeverity)
{
	DEFiRet;
	msg_t *pMsg;

	assert(msg != NULL);
	assert(pszTag != NULL);

	CHKiRet(msgConstruct(&pMsg));
	MsgSetFlowControlType(pMsg, eFLOWCTL_LIGHT_DELAY);
	MsgSetInputName(pMsg, pInputName);
	MsgSetRawMsgWOSize(pMsg, (char*)msg);
	MsgSetMSGoffs(pMsg, 0);	/* we do not have a header... */
	MsgSetRcvFrom(pMsg, glbl.GetLocalHostNameProp());
	MsgSetRcvFromIP(pMsg, pLocalHostIP);
	MsgSetHOSTNAME(pMsg, glbl.GetLocalHostName(), ustrlen(glbl.GetLocalHostName()));
	MsgSetTAG(pMsg, pszTag, ustrlen(pszTag));
	pMsg->iFacility = LOG_FAC(iFacility);
	pMsg->iSeverity = LOG_PRI(iSeverity);
	CHKiRet(submitMsg(pMsg));

finalize_it:
	RETiRet;
}
Exemplo n.º 3
0
static void parse_fac_prio_20(int pri, char *res20)
{
	CODE *c_pri, *c_fac;

	if (pri != 0) {
		c_fac = facilitynames;
		while (c_fac->c_name) {
			if (c_fac->c_val != (LOG_FAC(pri) << 3)) {
				c_fac++; continue;
			}
			/* facility is found, look for prio */
			c_pri = prioritynames;
			while (c_pri->c_name) {
				if (c_pri->c_val != LOG_PRI(pri)) {
					c_pri++; continue;
				}
				snprintf(res20, 20, "%s.%s",
						c_fac->c_name, c_pri->c_name);
				return;
			}
			/* prio not found, bail out */
			break;
		}
		snprintf(res20, 20, "<%d>", pri);
	}
}
Exemplo n.º 4
0
/* log a kernel message 
 * rgerhards, 2008-04-14
 */
rsRetVal Syslog(int priority, uchar *pMsg)
{
	DEFiRet;
	rsRetVal localRet;

	/* Output using syslog */
	localRet = parsePRI(&pMsg, &priority);
	if(localRet != RS_RET_INVALID_PRI && localRet != RS_RET_OK)
		FINALIZE;
	/* if we don't get the pri, we use whatever we were supplied */

	/* ignore non-kernel messages if not permitted */
	if(bPermitNonKernel == 0 && LOG_FAC(priority) != LOG_KERN)
		FINALIZE; /* silently ignore */

	iRet = enqMsg((uchar*)pMsg, (uchar*) "kernel:", LOG_FAC(priority), LOG_PRI(priority));

finalize_it:
	RETiRet;
}
Exemplo n.º 5
0
static
void
dumpbuf(char *bp, size_t bufpos, size_t buflen,
	int *newl, int *skip, int *pri)
{
	int ch;
	char *p, *ep;
	char buf[5];

	/*
	 * The message buffer is circular.  If the buffer has wrapped, the
	 * write pointer points to the oldest data.  Otherwise, the write
	 * pointer points to \0's following the data.  Read the entire
	 * buffer starting at the write pointer and ignore nulls so that
	 * we effectively start at the oldest data.
	 */
	p = bp + bufpos;
	ep = (bufpos == 0 ? bp + buflen : p);
	do {
		if (p == bp + buflen)
			p = bp;
		ch = *p;
		/* Skip "\n<.*>" syslog sequences. */
		if (*skip) {
			if (ch == '\n') {
				*skip = 0;
				*newl = 1;
			} if (ch == '>') {
				if (LOG_FAC(*pri) == LOG_KERN || all_opt)
					*newl = *skip = 0;
			} else if (ch >= '0' && ch <= '9') {
				*pri *= 10;
				*pri += ch - '0';
			}
			continue;
		}
		if (*newl && ch == '<') {
			*pri = 0;
			*skip = 1;
			continue;
		}
		if (ch == '\0')
			continue;
		*newl = ch == '\n';
		vis(buf, ch, 0, 0);
		if (buf[1] == 0)
			putchar(buf[0]);
		else
			printf("%s", buf);
	} while (++p != ep);
}
Exemplo n.º 6
0
/* This function receives data from a socket indicated to be ready
 * to receive and submits the message received for processing.
 * rgerhards, 2007-12-20
 * Interface changed so that this function is passed the array index
 * of the socket which is to be processed. This eases access to the
 * growing number of properties. -- rgerhards, 2008-08-01
 */
static rsRetVal
readLog(int fd, uchar *pRcv, int iMaxLine)
{
	DEFiRet;
	struct strbuf data;
	struct strbuf ctl;
	struct log_ctl hdr;
	int flags;
	msg_t *pMsg;
	int ret;
	char errStr[1024];

	data.buf = (char*)pRcv;
	data.maxlen = iMaxLine;
	ctl.maxlen = sizeof (struct log_ctl);
	ctl.buf = (caddr_t)&hdr;
	flags = 0;
	ret = getmsg(fd, &ctl, &data, &flags);
	if(ret < 0) {
		if(errno == EINTR) {
			FINALIZE;
		} else 	{
			int en = errno;
			rs_strerror_r(errno, errStr, sizeof(errStr));
			DBGPRINTF("imsolaris: stream input error on fd %d: %s.\n", fd, errStr);
			errmsg.LogError(en, NO_ERRCODE, "imsolaris: stream input error: %s", errStr);
			tryRecover();
		}	
	} else {
		DBGPRINTF("imsolaris: message from log stream %d: %s\n", fd, pRcv);
		pRcv[data.len] = '\0'; /* make sure it is a valid C-String */
		CHKiRet(msgConstruct(&pMsg));
		MsgSetInputName(pMsg, pInputName);
		MsgSetRawMsg(pMsg, (char*)pRcv, strlen((char*)pRcv));
		MsgSetHOSTNAME(pMsg, glbl.GetLocalHostName(), ustrlen(glbl.GetLocalHostName()));
		pMsg->iFacility = LOG_FAC(hdr.pri);
		pMsg->iSeverity = LOG_PRI(hdr.pri);
		pMsg->msgFlags = NEEDS_PARSING | NO_PRI_IN_RAW;
		CHKiRet(submitMsg(pMsg));
	}

finalize_it:
	RETiRet;
}
Exemplo n.º 7
0
static int log_do_header(
                char *header,
                size_t size,
                int level,
                int error,
                const char *file, int line, const char *func,
                const char *object_field, const char *object,
                const char *extra_field, const char *extra) {

        snprintf(header, size,
                 "PRIORITY=%i\n"
                 "SYSLOG_FACILITY=%i\n"
                 "%s%s%s"
                 "%s%.*i%s"
                 "%s%s%s"
                 "%s%.*i%s"
                 "%s%s%s"
                 "%s%s%s"
                 "SYSLOG_IDENTIFIER=%s\n",
                 LOG_PRI(level),
                 LOG_FAC(level),
                 isempty(file) ? "" : "CODE_FILE=",
                 isempty(file) ? "" : file,
                 isempty(file) ? "" : "\n",
                 line ? "CODE_LINE=" : "",
                 line ? 1 : 0, line, /* %.0d means no output too, special case for 0 */
                 line ? "\n" : "",
                 isempty(func) ? "" : "CODE_FUNCTION=",
                 isempty(func) ? "" : func,
                 isempty(func) ? "" : "\n",
                 error ? "ERRNO=" : "",
                 error ? 1 : 0, error,
                 error ? "\n" : "",
                 isempty(object) ? "" : object_field,
                 isempty(object) ? "" : object,
                 isempty(object) ? "" : "\n",
                 isempty(extra) ? "" : extra_field,
                 isempty(extra) ? "" : extra,
                 isempty(extra) ? "" : "\n",
                 program_invocation_short_name);

        return 0;
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
    struct msgbuf *bufp, cur;
    char *bp, *ep, *memf, *nextp, *nlistf, *p, *q, *visbp;
    kvm_t *kd;
    size_t buflen, bufpos;
    long pri;
    int ch, clear;
    bool all;

    all = false;
    clear = false;
    (void) setlocale(LC_CTYPE, "");
    memf = nlistf = NULL;
    while ((ch = getopt(argc, argv, "acM:N:")) != -1)
        switch(ch) {
        case 'a':
            all = true;
            break;
        case 'c':
            clear = true;
            break;
        case 'M':
            memf = optarg;
            break;
        case 'N':
            nlistf = optarg;
            break;
        case '?':
        default:
            usage();
        }
    argc -= optind;
    if (argc != 0)
        usage();

    if (memf == NULL) {
        /*
         * Running kernel.  Use sysctl.  This gives an unwrapped
         * buffer as a side effect.
         */
        if (sysctlbyname("kern.msgbuf", NULL, &buflen, NULL, 0) == -1)
            err(1, "sysctl kern.msgbuf");
        if ((bp = malloc(buflen + 2)) == NULL)
            errx(1, "malloc failed");
        if (sysctlbyname("kern.msgbuf", bp, &buflen, NULL, 0) == -1)
            err(1, "sysctl kern.msgbuf");
        if (clear)
            if (sysctlbyname("kern.msgbuf_clear", NULL, NULL, &clear, sizeof(int)))
                err(1, "sysctl kern.msgbuf_clear");
    } else {
        /* Read in kernel message buffer and do sanity checks. */
        kd = kvm_open(nlistf, memf, NULL, O_RDONLY, "dmesg");
        if (kd == NULL)
            exit (1);
        if (kvm_nlist(kd, nl) == -1)
            errx(1, "kvm_nlist: %s", kvm_geterr(kd));
        if (nl[X_MSGBUF].n_type == 0)
            errx(1, "%s: msgbufp not found",
                 nlistf ? nlistf : "namelist");
        if (KREAD(nl[X_MSGBUF].n_value, bufp) || KREAD((long)bufp, cur))
            errx(1, "kvm_read: %s", kvm_geterr(kd));
        if (cur.msg_magic != MSG_MAGIC)
            errx(1, "kernel message buffer has different magic "
                 "number");
        if ((bp = malloc(cur.msg_size + 2)) == NULL)
            errx(1, "malloc failed");

        /* Unwrap the circular buffer to start from the oldest data. */
        bufpos = MSGBUF_SEQ_TO_POS(&cur, cur.msg_wseq);
        if (kvm_read(kd, (long)&cur.msg_ptr[bufpos], bp,
                     cur.msg_size - bufpos) != (ssize_t)(cur.msg_size - bufpos))
            errx(1, "kvm_read: %s", kvm_geterr(kd));
        if (bufpos != 0 && kvm_read(kd, (long)cur.msg_ptr,
                                    &bp[cur.msg_size - bufpos], bufpos) != (ssize_t)bufpos)
            errx(1, "kvm_read: %s", kvm_geterr(kd));
        kvm_close(kd);
        buflen = cur.msg_size;
    }

    /*
     * Ensure that the buffer ends with a newline and a \0 to avoid
     * complications below.  We left space above.
     */
    if (buflen == 0 || bp[buflen - 1] != '\n')
        bp[buflen++] = '\n';
    bp[buflen] = '\0';

    if ((visbp = malloc(4 * buflen + 1)) == NULL)
        errx(1, "malloc failed");

    /*
     * The message buffer is circular, but has been unwrapped so that
     * the oldest data comes first.  The data will be preceded by \0's
     * if the message buffer was not full.
     */
    p = bp;
    ep = &bp[buflen];
    if (*p == '\0') {
        /* Strip leading \0's */
        while (*p == '\0')
            p++;
    } else if (!all) {
        /* Skip the first line, since it is probably incomplete. */
        p = memchr(p, '\n', ep - p);
        p++;
    }
    for (; p < ep; p = nextp) {
        nextp = memchr(p, '\n', ep - p);
        nextp++;

        /* Skip ^<[0-9]+> syslog sequences. */
        if (*p == '<' && isdigit(*(p+1))) {
            errno = 0;
            pri = strtol(p + 1, &q, 10);
            if (*q == '>' && pri >= 0 && pri < INT_MAX &&
                    errno == 0) {
                if (LOG_FAC(pri) != LOG_KERN && !all)
                    continue;
                p = q + 1;
            }
        }

        (void)strvisx(visbp, p, nextp - p, 0);
        (void)printf("%s", visbp);
    }
    exit(0);
}
Exemplo n.º 9
0
/*********************************************************************************************************
** 函数名称: syslog_r
** 功能描述: submits a message to the Syslog facility. It does this by writing to the file (支持不完整)
             LOG_DEFAULT_FILE
** 输 入  : priority      priority
**           data          syslog_data
**           message       message
             ...
** 输 出  : old mask
** 全局变量:
** 调用模块:
                                           API 函数
*********************************************************************************************************/
LW_API
void  syslog_r (int priority, struct syslog_data *data, const char *message, ...)
{
#define __PX_SYSLOG_TIMEFMT   "%s %2d %02d:%02d:%02d"

    CHAR            cBuffer[LOG_DEFAULT_SIZE];
    size_t          stLen;

    time_t          time;
    struct tm       tmBuf;

    va_list         valist;

    if (!data) {
        errno = EINVAL;
        return;
    }

    if (((unsigned)LOG_FAC(priority) >= LOG_NFACILITIES)  ||
            (LOG_MASK(LOG_PRI(priority)) == 0)                ||
            ((priority & ~(LOG_PRIMASK | LOG_FACMASK)) != 0)) {
        return;                                                         /*  不发送                      */
    }

    if ((data->log_file < 0) && (data->log_stat & LOG_ODELAY)) {        /*  是否需要执行一次打开操作    */
        openlog(data->log_tag, data->log_file, 0);
        data->log_file = _G_iSyslogUnix;
    }

    if ((priority & LOG_FACMASK) == 0) {
        priority |= data->log_fac;
    }

    time = lib_time(LW_NULL);
    lib_localtime_r(&time, &tmBuf);                                     /*  RFC3164 is the local time   */

    stLen = bnprintf(cBuffer, sizeof(cBuffer), 0, "<%d>", priority);    /*  打印 priority               */
    stLen = bnprintf(cBuffer, sizeof(cBuffer), stLen,
                     __PX_SYSLOG_TIMEFMT,
                     _G_cMonth[tmBuf.tm_mon],
                     tmBuf.tm_mday,
                     tmBuf.tm_hour,
                     tmBuf.tm_min,
                     tmBuf.tm_sec);                                     /*  打印 时间                   */

    if (data->log_tag) {
        stLen = bnprintf(cBuffer, sizeof(cBuffer), stLen, " %s", data->log_tag);
    }

    if (data->log_stat & LOG_PID) {
        if (sizeof(cBuffer) > stLen) {
            stLen = bnprintf(cBuffer, sizeof(cBuffer), stLen, "[%lx]:",
                             API_ThreadIdSelf());
        }
    }

    if (message) {
        if (sizeof(cBuffer) > stLen) {

#if __STDC__
            va_start(valist, message);
#else
            va_start(valist);
#endif
            stLen = vbnprintf(cBuffer, sizeof(cBuffer), stLen, message, valist);

            va_end(valist);
        }
    }

    if (data->log_file >= 0) {
        sendto(data->log_file, cBuffer, stLen, 0,
               (struct sockaddr *)&_G_sockaddrunLog, _G_sockelenLog);
    }

    if (data->log_stat & LOG_CONS) {
        write(STD_OUT, cBuffer, stLen);
    }

    if (data->log_stat & LOG_PERROR) {
        write(STD_ERR, cBuffer, stLen);
    }
}
Exemplo n.º 10
0
static int stdout_stream_log(StdoutStream *s, const char *p, LineBreak line_break) {
        struct iovec *iovec;
        int priority;
        char syslog_priority[] = "PRIORITY=\0";
        char syslog_facility[sizeof("SYSLOG_FACILITY=")-1 + DECIMAL_STR_MAX(int) + 1];
        _cleanup_free_ char *message = NULL, *syslog_identifier = NULL;
        size_t n = 0, m;
        int r;

        assert(s);
        assert(p);

        if (s->context)
                (void) client_context_maybe_refresh(s->server, s->context, NULL, NULL, 0, NULL, USEC_INFINITY);
        else if (pid_is_valid(s->ucred.pid)) {
                r = client_context_acquire(s->server, s->ucred.pid, &s->ucred, s->label, strlen_ptr(s->label), s->unit_id, &s->context);
                if (r < 0)
                        log_warning_errno(r, "Failed to acquire client context, ignoring: %m");
        }

        priority = s->priority;

        if (s->level_prefix)
                syslog_parse_priority(&p, &priority, false);

        if (!client_context_test_priority(s->context, priority))
                return 0;

        if (isempty(p))
                return 0;

        if (s->forward_to_syslog || s->server->forward_to_syslog)
                server_forward_syslog(s->server, syslog_fixup_facility(priority), s->identifier, p, &s->ucred, NULL);

        if (s->forward_to_kmsg || s->server->forward_to_kmsg)
                server_forward_kmsg(s->server, priority, s->identifier, p, &s->ucred);

        if (s->forward_to_console || s->server->forward_to_console)
                server_forward_console(s->server, priority, s->identifier, p, &s->ucred);

        if (s->server->forward_to_wall)
                server_forward_wall(s->server, priority, s->identifier, p, &s->ucred);

        m = N_IOVEC_META_FIELDS + 7 + client_context_extra_fields_n_iovec(s->context);
        iovec = newa(struct iovec, m);

        iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=stdout");
        iovec[n++] = IOVEC_MAKE_STRING(s->id_field);

        syslog_priority[strlen("PRIORITY=")] = '0' + LOG_PRI(priority);
        iovec[n++] = IOVEC_MAKE_STRING(syslog_priority);

        if (priority & LOG_FACMASK) {
                xsprintf(syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority));
                iovec[n++] = IOVEC_MAKE_STRING(syslog_facility);
        }

        if (s->identifier) {
                syslog_identifier = strappend("SYSLOG_IDENTIFIER=", s->identifier);
                if (syslog_identifier)
                        iovec[n++] = IOVEC_MAKE_STRING(syslog_identifier);
        }

        if (line_break != LINE_BREAK_NEWLINE) {
                const char *c;

                /* If this log message was generated due to an uncommon line break then mention this in the log
                 * entry */

                c =     line_break == LINE_BREAK_NUL ?      "_LINE_BREAK=nul" :
                        line_break == LINE_BREAK_LINE_MAX ? "_LINE_BREAK=line-max" :
                                                            "_LINE_BREAK=eof";
                iovec[n++] = IOVEC_MAKE_STRING(c);
        }

        message = strappend("MESSAGE=", p);
        if (message)
                iovec[n++] = IOVEC_MAKE_STRING(message);

        server_dispatch_message(s->server, iovec, n, m, s->context, NULL, priority, 0);
        return 0;
}
Exemplo n.º 11
0
static void dev_kmsg_record(Server *s, const char *p, size_t l) {

        _cleanup_free_ char *message = NULL, *syslog_priority = NULL, *syslog_pid = NULL, *syslog_facility = NULL, *syslog_identifier = NULL, *source_time = NULL, *identifier = NULL, *pid = NULL;
        struct iovec iovec[N_IOVEC_META_FIELDS + 7 + N_IOVEC_KERNEL_FIELDS + 2 + N_IOVEC_UDEV_FIELDS];
        char *kernel_device = NULL;
        unsigned long long usec;
        size_t n = 0, z = 0, j;
        int priority, r;
        char *e, *f, *k;
        uint64_t serial;
        size_t pl;

        assert(s);
        assert(p);

        if (l <= 0)
                return;

        e = memchr(p, ',', l);
        if (!e)
                return;
        *e = 0;

        r = safe_atoi(p, &priority);
        if (r < 0 || priority < 0 || priority > 999)
                return;

        if (s->forward_to_kmsg && (priority & LOG_FACMASK) != LOG_KERN)
                return;

        l -= (e - p) + 1;
        p = e + 1;
        e = memchr(p, ',', l);
        if (!e)
                return;
        *e = 0;

        r = safe_atou64(p, &serial);
        if (r < 0)
                return;

        if (s->kernel_seqnum) {
                /* We already read this one? */
                if (serial < *s->kernel_seqnum)
                        return;

                /* Did we lose any? */
                if (serial > *s->kernel_seqnum)
                        server_driver_message(s, 0,
                                              "MESSAGE_ID=" SD_MESSAGE_JOURNAL_MISSED_STR,
                                              LOG_MESSAGE("Missed %"PRIu64" kernel messages",
                                                          serial - *s->kernel_seqnum),
                                              NULL);

                /* Make sure we never read this one again. Note that
                 * we always store the next message serial we expect
                 * here, simply because this makes handling the first
                 * message with serial 0 easy. */
                *s->kernel_seqnum = serial + 1;
        }

        l -= (e - p) + 1;
        p = e + 1;
        f = memchr(p, ';', l);
        if (!f)
                return;
        /* Kernel 3.6 has the flags field, kernel 3.5 lacks that */
        e = memchr(p, ',', l);
        if (!e || f < e)
                e = f;
        *e = 0;

        r = safe_atollu(p, &usec);
        if (r < 0)
                return;

        l -= (f - p) + 1;
        p = f + 1;
        e = memchr(p, '\n', l);
        if (!e)
                return;
        *e = 0;

        pl = e - p;
        l -= (e - p) + 1;
        k = e + 1;

        for (j = 0; l > 0 && j < N_IOVEC_KERNEL_FIELDS; j++) {
                char *m;
                /* Metadata fields attached */

                if (*k != ' ')
                        break;

                k++, l--;

                e = memchr(k, '\n', l);
                if (!e)
                        return;

                *e = 0;

                if (cunescape_length_with_prefix(k, e - k, "_KERNEL_", UNESCAPE_RELAX, &m) < 0)
                        break;

                if (startswith(m, "_KERNEL_DEVICE="))
                        kernel_device = m + 15;

                iovec[n++] = IOVEC_MAKE_STRING(m);
                z++;

                l -= (e - k) + 1;
                k = e + 1;
        }

        if (kernel_device) {
                struct udev_device *ud;

                ud = udev_device_new_from_device_id(s->udev, kernel_device);
                if (ud) {
                        const char *g;
                        struct udev_list_entry *ll;
                        char *b;

                        g = udev_device_get_devnode(ud);
                        if (g) {
                                b = strappend("_UDEV_DEVNODE=", g);
                                if (b) {
                                        iovec[n++] = IOVEC_MAKE_STRING(b);
                                        z++;
                                }
                        }

                        g = udev_device_get_sysname(ud);
                        if (g) {
                                b = strappend("_UDEV_SYSNAME=", g);
                                if (b) {
                                        iovec[n++] = IOVEC_MAKE_STRING(b);
                                        z++;
                                }
                        }

                        j = 0;
                        ll = udev_device_get_devlinks_list_entry(ud);
                        udev_list_entry_foreach(ll, ll) {

                                if (j > N_IOVEC_UDEV_FIELDS)
                                        break;

                                g = udev_list_entry_get_name(ll);
                                if (g) {
                                        b = strappend("_UDEV_DEVLINK=", g);
                                        if (b) {
                                                iovec[n++] = IOVEC_MAKE_STRING(b);
                                                z++;
                                        }
                                }

                                j++;
                        }

                        udev_device_unref(ud);
                }
        }

        if (asprintf(&source_time, "_SOURCE_MONOTONIC_TIMESTAMP=%llu", usec) >= 0)
                iovec[n++] = IOVEC_MAKE_STRING(source_time);

        iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=kernel");

        if (asprintf(&syslog_priority, "PRIORITY=%i", priority & LOG_PRIMASK) >= 0)
                iovec[n++] = IOVEC_MAKE_STRING(syslog_priority);

        if (asprintf(&syslog_facility, "SYSLOG_FACILITY=%i", LOG_FAC(priority)) >= 0)
                iovec[n++] = IOVEC_MAKE_STRING(syslog_facility);

        if ((priority & LOG_FACMASK) == LOG_KERN)
                iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=kernel");
        else {
                pl -= syslog_parse_identifier((const char**) &p, &identifier, &pid);

                /* Avoid any messages we generated ourselves via
                 * log_info() and friends. */
                if (pid && is_us(pid))
                        goto finish;

                if (identifier) {
                        syslog_identifier = strappend("SYSLOG_IDENTIFIER=", identifier);
                        if (syslog_identifier)
                                iovec[n++] = IOVEC_MAKE_STRING(syslog_identifier);
                }

                if (pid) {
                        syslog_pid = strappend("SYSLOG_PID=", pid);
                        if (syslog_pid)
                                iovec[n++] = IOVEC_MAKE_STRING(syslog_pid);
                }
        }

        if (cunescape_length_with_prefix(p, pl, "MESSAGE=", UNESCAPE_RELAX, &message) >= 0)
                iovec[n++] = IOVEC_MAKE_STRING(message);

        server_dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, priority, 0);

finish:
        for (j = 0; j < z; j++)
                free(iovec[j].iov_base);
}
Exemplo n.º 12
0
static void logMessage(int pri, char *msg)
{
	time_t now;
	char *timestamp;
	static char res[20] = "";
#ifdef CONFIG_FEATURE_REMOTE_LOG	
	static char line[MAXLINE + 1];
#endif
	CODE *c_pri, *c_fac;
/*BRCM begin*/
	int localLog=1;
	int remoteLog=1;
	int len;
/*BRCM end*/

	if (pri != 0) {
		for (c_fac = facilitynames;
			 c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
		for (c_pri = prioritynames;
			 c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
		if (c_fac->c_name == NULL || c_pri->c_name == NULL) {
			snprintf(res, sizeof(res), "<%d>", pri);
		} else {
			snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
		}
	}

/*BRCM begin*/
	if ((pri != 0) && (c_pri->c_name != NULL)) {
		if (c_pri->c_val > localLogLevel) 
			localLog = 0;
		if (c_pri->c_val > remoteLogLevel)
			remoteLog = 0;
	}
	if (!localLog && !remoteLog)
		return;
/*BRCM end*/

	if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
		msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
		time(&now);
		timestamp = ctime(&now) + 4;
		timestamp[15] = '\0';
	} else {
		timestamp = msg;
		timestamp[15] = '\0';
		msg += 16;
	}

	/* todo: supress duplicates */

#ifdef CONFIG_FEATURE_REMOTE_LOG
	if (doRemoteLog == TRUE) {
		/* trying connect the socket */
		if (-1 == remotefd) {
			init_RemoteLog();
		}

		/* if we have a valid socket, send the message */
		if (-1 != remotefd) {
			now = 1;
			snprintf(line, sizeof(line), "<%d> %s", pri, msg);

		retry:
			/* send message to remote logger */
			if(( -1 == sendto(remotefd, line, strlen(line), 0,
							(struct sockaddr *) &remoteaddr,
							sizeof(remoteaddr))) && (errno == EINTR)) {
				/* sleep now seconds and retry (with now * 2) */
				sleep(now);
				now *= 2;
				goto retry;
			}
		}
	}

/*BRCM begin*/
//	if (local_logging == TRUE)
        /* bug fix ; circular_logging should do too; it only checked
		 *            -L local logging.   */
	if (((local_logging == TRUE) || (circular_logging)) && localLog) {
#endif
        //		/* now spew out the message to wherever it is supposed to go */
        //		message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
        /* brcm, add len of string to do log display with latestest event displayed first */
        /* now spew out the message to wherever it is supposed to go; 4 spaces+ \0 + \n + len(3bytes) */
		len = (strlen(timestamp)+strlen(LocalHostName)+strlen(res)+strlen(msg)+9);
		message("%s %s %s %s %3i\n", timestamp, LocalHostName, res, msg, len);
#ifdef CONFIG_FEATURE_REMOTE_LOG
        }
#endif
/*BRCM end*/
}
Exemplo n.º 13
0
static void logMessage(int pri, char *msg)
{
	time_t now;
	char *timestamp;
	static char res[20];
#ifdef CONFIG_FEATURE_REMOTE_LOG
	static char line[MAXLINE + 1];
#endif
	CODE *c_pri, *c_fac;

	if (pri != 0) {
		for (c_fac = facilitynames;
			 c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
		for (c_pri = prioritynames;
			 c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
		if (c_fac->c_name == NULL || c_pri->c_name == NULL) {
			snprintf(res, sizeof(res), "<%d>", pri);
		} else {
			snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
		}
	}

	if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
		msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
		time(&now);
		timestamp = ctime(&now) + 4;
		timestamp[15] = '\0';
	} else {
		timestamp = msg;
		timestamp[15] = '\0';
// To log AP console message to log file.
// Skip "kernel: "
//		msg += 16;
		msg += 24;
	}

	/* todo: supress duplicates */

#ifdef CONFIG_FEATURE_REMOTE_LOG
	if (doRemoteLog == TRUE) {
		/* trying connect the socket */
		if (-1 == remotefd) {
			init_RemoteLog();
		}

		/* if we have a valid socket, send the message */
		if (-1 != remotefd) {
			now = 1;
			snprintf(line, sizeof(line), "<%d>%s", pri, msg);

		retry:
			/* send message to remote logger */
			if(( -1 == sendto(remotefd, line, strlen(line), 0,
							(struct sockaddr *) &remoteaddr,
							sizeof(remoteaddr))) && (errno == EINTR)) {
				/* sleep now seconds and retry (with now * 2) */
				sleep(now);
				now *= 2;
				goto retry;
			}
		}
	}

	if (local_logging == TRUE)
#endif
	{
		/* now spew out the message to wherever it is supposed to go */
// To log AP console message to log file.
		if (small)
//			message("%s %s\n", timestamp, msg);
			message("%s\n",msg);
		else
//			message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
			message("%s\n",msg);
	}
}
Exemplo n.º 14
0
int
main(int argc, char **argv)
{
	int ch, newl, skip;
	char *p, *ep;
	struct msgbuf *bufp, cur;
	char *bp, *memf, *nlistf;
	kvm_t *kd;
	char buf[5];
	int all = 0;
	int clear = 0;
	int pri = 0;
	size_t buflen, bufpos;

	setlocale(LC_CTYPE, "");
	memf = nlistf = NULL;
	while ((ch = getopt(argc, argv, "acM:N:")) != -1)
		switch(ch) {
		case 'a':
			all++;
			break;
		case 'c':
			clear = 1;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (memf == NULL && nlistf == NULL) {
		/* Running kernel. Use sysctl. */
		if (sysctlbyname("kern.msgbuf", NULL, &buflen, NULL, 0) == -1)
			err(1, "sysctl kern.msgbuf");
		buflen += 4096;		/* add some slop */
		if ((bp = malloc(buflen)) == NULL)
			errx(1, "malloc failed");
		if (sysctlbyname("kern.msgbuf", bp, &buflen, NULL, 0) == -1)
			err(1, "sysctl kern.msgbuf");
		/* We get a dewrapped buffer using sysctl. */
		bufpos = 0;
	} else {
		/* Read in kernel message buffer, do sanity checks. */
		kd = kvm_open(nlistf, memf, NULL, O_RDONLY, "dmesg");
		if (kd == NULL)
			exit (1);
		if (kvm_nlist(kd, nl) == -1)
			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
		if (nl[X_MSGBUF].n_type == 0)
			errx(1, "%s: msgbufp not found",
			    nlistf ? nlistf : "namelist");
		if (KREAD(nl[X_MSGBUF].n_value, bufp) || KREAD((long)bufp, cur))
			errx(1, "kvm_read: %s", kvm_geterr(kd));
		if (cur.msg_magic != MSG_MAGIC)
			errx(1, "kernel message buffer has different magic "
			    "number");
		bp = malloc(cur.msg_size);
		if (!bp)
			errx(1, "malloc failed");
		if (kvm_read(kd, (long)cur.msg_ptr, bp, cur.msg_size) !=
		    (ssize_t)cur.msg_size)
			errx(1, "kvm_read: %s", kvm_geterr(kd));
		kvm_close(kd);
		buflen = cur.msg_size;
		bufpos = cur.msg_bufx;
		if (bufpos >= buflen)
			bufpos = 0;
	}

	/*
	 * The message buffer is circular.  If the buffer has wrapped, the
	 * write pointer points to the oldest data.  Otherwise, the write
	 * pointer points to \0's following the data.  Read the entire
	 * buffer starting at the write pointer and ignore nulls so that
	 * we effectively start at the oldest data.
	 */
	p = bp + bufpos;
	ep = (bufpos == 0 ? bp + buflen : p);
	newl = skip = 0;
	do {
		if (p == bp + buflen)
			p = bp;
		ch = *p;
		/* Skip "\n<.*>" syslog sequences. */
		if (skip) {
			if (ch == '\n') {
				skip = 0;
				newl = 1;
			} if (ch == '>') {
				if (LOG_FAC(pri) == LOG_KERN || all)
					newl = skip = 0;
			} else if (ch >= '0' && ch <= '9') {
				pri *= 10;
				pri += ch - '0';
			}
			continue;
		}
		if (newl && ch == '<') {
			pri = 0;
			skip = 1;
			continue;
		}
		if (ch == '\0')
			continue;
		newl = ch == '\n';
		vis(buf, ch, 0, 0);
		if (buf[1] == 0)
			putchar(buf[0]);
		else
			printf("%s", buf);
	} while (++p != ep);
	if (!newl)
		putchar('\n');
	if (clear)
		if (sysctlbyname("kern.msgbuf_clear", NULL, NULL, &clear, sizeof(int)) != 0)
			err(1, "sysctl kern.msgbuf_clear");
	exit(0);
}
Exemplo n.º 15
0
static int log_notify(struct blob_attr *msg)
{
	struct blob_attr *tb[__LOG_MAX];
	struct stat s;
	char buf[512];
	uint32_t p;
	char *str;
	time_t t;
	char *c, *m;
	int ret = 0;

	if (sender.fd < 0)
		return 0;

	blobmsg_parse(log_policy, ARRAY_SIZE(log_policy), tb, blob_data(msg), blob_len(msg));
	if (!tb[LOG_ID] || !tb[LOG_PRIO] || !tb[LOG_SOURCE] || !tb[LOG_TIME] || !tb[LOG_MSG])
		return 1;

	if ((log_type == LOG_FILE) && log_size && (!stat(log_file, &s)) && (s.st_size > log_size)) {
		char *old = malloc(strlen(log_file) + 5);

		close(sender.fd);
		if (old) {
			sprintf(old, "%s.old", log_file);
			rename(log_file, old);
			free(old);
		}
		sender.fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0600);
		if (sender.fd < 0) {
			fprintf(stderr, "failed to open %s: %s\n", log_file, strerror(errno));
			exit(-1);
		}
	}

	m = blobmsg_get_string(tb[LOG_MSG]);
	t = blobmsg_get_u64(tb[LOG_TIME]) / 1000;
	c = ctime(&t);
	p = blobmsg_get_u32(tb[LOG_PRIO]);
	c[strlen(c) - 1] = '\0';
	str = blobmsg_format_json(msg, true);
	if (log_type == LOG_NET) {
		int err;

		snprintf(buf, sizeof(buf), "<%u>", p);
		strncat(buf, c + 4, 16);
		if (hostname) {
			strncat(buf, hostname, sizeof(buf) - strlen(buf) - 1);
			strncat(buf, " ", sizeof(buf) - strlen(buf) - 1);
		}
		if (log_prefix) {
			strncat(buf, log_prefix, sizeof(buf) - strlen(buf) - 1);
			strncat(buf, ": ", sizeof(buf) - strlen(buf) - 1);
		}
		if (blobmsg_get_u32(tb[LOG_SOURCE]) == SOURCE_KLOG)
			strncat(buf, "kernel: ", sizeof(buf) - strlen(buf) - 1);
		strncat(buf, m, sizeof(buf) - strlen(buf) - 1);
		if (log_udp)
			err = write(sender.fd, buf, strlen(buf));
		else {
			size_t buflen = strlen(buf);
			if (!log_trailer_null)
				buf[buflen] = '\n';
			err = send(sender.fd, buf, buflen + 1, 0);
		}

		if (err < 0) {
			syslog(LOG_INFO, "failed to send log data to %s:%s via %s\n",
				log_ip, log_port, (log_udp) ? ("udp") : ("tcp"));
			uloop_fd_delete(&sender);
			close(sender.fd);
			sender.fd = -1;
			uloop_timeout_set(&retry, 1000);
		}
	} else {
		snprintf(buf, sizeof(buf), "%s %s.%s%s %s\n",
			c, getcodetext(LOG_FAC(p) << 3, facilitynames), getcodetext(LOG_PRI(p), prioritynames),
			(blobmsg_get_u32(tb[LOG_SOURCE])) ? ("") : (" kernel:"), m);
		ret = write(sender.fd, buf, strlen(buf));
	}

	free(str);
	if (log_type == LOG_FILE)
		fsync(sender.fd);

	return ret;
}
Exemplo n.º 16
0
static void logMessage(int pri, char *msg)
{
	time_t now;
	char *timestamp;
	static char res[20] = "";
	CODE *c_pri, *c_fac;

	if (pri != 0) {
		for (c_fac = facilitynames;
			 c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
		for (c_pri = prioritynames;
			 c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
		if (c_fac->c_name == NULL || c_pri->c_name == NULL) {
			snprintf(res, sizeof(res), "<%d>", pri);
		} else {
			snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
		}
	}

	if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
		msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
		time(&now);
		timestamp = ctime(&now) + 4;
		timestamp[15] = '\0';
	} else {
		timestamp = msg;
		timestamp[15] = '\0';
		msg += 16;
	}

	/* todo: supress duplicates */

#ifdef CONFIG_FEATURE_REMOTE_LOG
	/* send message to remote logger */
	if (-1 != remotefd) {
		static const int IOV_COUNT = 2;
		struct iovec iov[IOV_COUNT];
		struct iovec *v = iov;

		memset(&res, 0, sizeof(res));
		snprintf(res, sizeof(res), "<%d>", pri);
		v->iov_base = res;
		v->iov_len = strlen(res);
		v++;

		v->iov_base = msg;
		v->iov_len = strlen(msg);
	  writev_retry:
		if ((-1 == writev(remotefd, iov, IOV_COUNT)) && (errno == EINTR)) {
			goto writev_retry;
		}
	}
	if (local_logging == TRUE)
#endif
	{
		/* now spew out the message to wherever it is supposed to go */
		if (small)
			message("%s %s\n", timestamp, msg);
		else
			message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
	}
}
Exemplo n.º 17
0
//---------------------------------------------------------------------------
bool TSyslogMessage::FromStringSyslogd(char * p, int size, sockaddr_in * from_addr)
{
  if( from_addr )
    SourceAddr = inet_ntoa(from_addr->sin_addr);
  else
    SourceAddr = "";

  PRI = -1; // not exist
  if( *p == '<' )
  {
    for(int i=1; i<5 && p[i]; i++)
    {
      if( p[i] == '>' )
      {
        PRI = atoi(p+1);
        p += i + 1;
        break;
      }
      if( ! isdigit(p[i]) )
        break;
    }
  }
  if( PRI >= 0 )
  {
    // invalid facility number not allowed: message filtering mechanism will fail
    // replace invalid facility number by LOGALERT
    if( LOG_FAC(PRI) >= LOG_NFACILITIES )
      PRI = LOG_PRI(PRI) | LOG_LOGALERT;

    Facility = getcodetext(LOG_FAC(PRI) << 3, facilitynames);
    Priority = getcodetext(LOG_PRI(PRI), prioritynames);
  }

  if( IsValidSyslogDate(p) )
  {
    DateStr = String(p, 15);
    p += 16; // including space
  }
  else
  {
    // month names in english in compliance to syslog rfc
    TFormatSettings fs;
    GetLocaleFormatSettings(0x0409, fs); // usa
    DateStr = FormatDateTime("mmm dd hh:nn:ss", Now(), fs);
  }

  // try to find host name
  for(int i=0; i<255 && p[i]; i++)
  {
    if( p[i] == ' ' )
    {
      // found
      HostName = String(p, i);
      p += i + 1;
      break;
    }
    else if( p[i] == ':' || p[i] == '[' || p[i] == ']' )
    {
      // host name not exist - this is program name
      break;
    }
  }

  // try to find program name
  for(int i=0; i<(48+2) && p[i]; i++)
  {
    if( p[i] == ':' && p[i+1] == ' ' )
    {
      // found
      Tag = String(p, i);
      p += i + 2;
      break;
    }
  }

  // and now - process message
  // Replace all tabs by spaces,
  // cut all carriage returns and line feeds,
  // replace all chars 0..32 by '.'
  Msg = "";
  for(int i=0; p[i]; i++)
  {
    if( p[i] == '\t' || p[i] == '\n' )
      Msg += ' ';
    else if( p[i] == '\r' )
      ;
    else if( p[i] >= 0 && p[i] < 32 )
      Msg += '.';
    else
      Msg += p[i];
  }

  if( MainCfg.bReceiveUTF8 )
    Msg = Utf8ToAnsi(Msg);

  return true;
}