/*
   cipelib - library routines common to CIPE (user-mode part) and PKCIPE

   Copyright 2000 Olaf Titz <olaf@bigred.inka.de>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version
   2 of the License, or (at your option) any later version.
*/
/* $Id: cipe_syslog.c,v 1.4 2000/12/13 01:38:55 olaf Exp $ */

#define _USE_BSD
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cipelib.h"

int logstderr=0;

static char *buf=NULL;
static int bufl=0;

#define CHUNK 128 /* power of two! */

/* have to duplicate nonstandard "%m" format */
INLINE void vstderr(const char *fmt, va_list v)
{
    char *p, *s;
    register const char *q;
    register char *r;
    int l;

    p=strstr(fmt, "%m");
    if (!p) {
        vfprintf(stderr, fmt, v);
        fputc('\n', stderr);
        return;
    }
    s=strerror(errno);
    l=p-fmt+strlen(s)+strlen(p);
    if (l>bufl) {
        bufl=(l+CHUNK)&(~(CHUNK-1));
        if (!(buf=realloc(buf, bufl))) {
            bufl=0;
            fprintf(stderr, "cipe_syslog: malloc failure\n");
            return;
        }
    }
    for (q=fmt, r=buf; q<p;)
        *r++=*q++;
    while (*s)
        *r++=*s++;
    for (q=p+2; *q;)
        *r++=*q++;
    *r++='\n';
    *r='\0';
    vfprintf(stderr, buf, v);
}

void cipe_vsyslog(int level, const char *fmt, va_list v)
{
    if (logstderr || level==LOG_STDERR)
        vstderr(fmt, v);
    else
        vsyslog(level, fmt, v);
}

void cipe_syslog(int level, const char *fmt, ...)
{
    va_list v;
    va_start(v, fmt);
    cipe_vsyslog(level, fmt, v);
    va_end(v);
}
