Home | History | Annotate | Line # | Download | only in syslogd
syslogd.h revision 1.2
      1 /*	$NetBSD: syslogd.h,v 1.2 2008/11/07 07:36:38 minskim Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Martin Schtte.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 #ifndef SYSLOGD_H_
     39 #define SYSLOGD_H_
     40 /*
     41  * hold common data structures and prototypes
     42  * for syslogd.c and tls.c
     43  *
     44  */
     45 
     46 #include <sys/cdefs.h>
     47 #define MAXLINE		1024		/* maximum line length */
     48 #define MAXSVLINE	120		/* maximum saved line length */
     49 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
     50 #define DEFSPRI		(LOG_KERN|LOG_NOTICE)
     51 #define TIMERINTVL	30		/* interval for checking flush, mark */
     52 #define TTYMSGTIME	1		/* timeout passed to ttymsg */
     53 
     54 #include <sys/param.h>
     55 #include <sys/socket.h>
     56 #include <sys/sysctl.h>
     57 #include <sys/types.h>
     58 #include <sys/un.h>
     59 #include <sys/wait.h>
     60 #include <sys/queue.h>
     61 #include <netinet/in.h>
     62 #include <sys/event.h>
     63 #include <event.h>
     64 
     65 #include <assert.h>
     66 #include <ctype.h>
     67 #include <errno.h>
     68 #include <fcntl.h>
     69 #include <grp.h>
     70 #include <locale.h>
     71 #include <netdb.h>
     72 #include <pwd.h>
     73 #include <signal.h>
     74 #include <stdarg.h>
     75 #include <stdio.h>
     76 #include <stdlib.h>
     77 #include <string.h>
     78 #include <unistd.h>
     79 #include <stdbool.h>
     80 #include <utmp.h>
     81 #ifdef __NetBSD_Version__
     82 #include <util.h>
     83 #include "utmpentry.h"
     84 #endif /* __NetBSD_Version__ */
     85 #ifdef __FreeBSD_version
     86 #include <libutil.h>
     87 #include <sys/stat.h>
     88 #include <sys/uio.h>
     89 #include <limits.h>
     90 #endif /* __FreeBSD_version */
     91 
     92 #ifndef DISABLE_TLS
     93 #include <netinet/tcp.h>
     94 #include <openssl/ssl.h>
     95 #endif /* !DISABLE_TLS */
     96 
     97 #include <sys/stdint.h>
     98 #include <sys/resource.h>
     99 
    100 /* additional queue macros copied from FreeBSD	*/
    101 #ifndef SLIST_FOREACH_SAFE
    102 #define SLIST_FOREACH_SAFE(var, head, field, tvar)	    \
    103     for ((var) = SLIST_FIRST((head));		    \
    104 	(var) && ((tvar) = SLIST_NEXT((var), field), 1);	\
    105 	(var) = (tvar))
    106 #endif /* !SLIST_FOREACH_SAFE */
    107 #ifndef STAILQ_FOREACH_SAFE
    108 #define STAILQ_FOREACH_SAFE(var, head, field, tvar)	    \
    109     for ((var) = STAILQ_FIRST((head));		    \
    110 	(var) && ((tvar) = STAILQ_NEXT((var), field), 1);	\
    111 	(var) = (tvar))
    112 #endif /* !STAILQ_FOREACH_SAFE */
    113 #ifndef STAILQ_LAST
    114 #define STAILQ_LAST(head, type, field)			\
    115     (STAILQ_EMPTY((head)) ?			\
    116 	NULL :				\
    117 	    ((struct type *)			\
    118 	((char *)((head)->stqh_last) - offsetof(struct type, field))))
    119 #endif /* !STAILQ_LAST */
    120 #ifndef STAILQ_CONCAT
    121 #define STAILQ_CONCAT(head1, head2) do {	\
    122   if (!STAILQ_EMPTY((head2))) {		\
    123     *(head1)->stqh_last = (head2)->stqh_first;	  \
    124     (head1)->stqh_last = (head2)->stqh_last;	\
    125     STAILQ_INIT((head2));	  \
    126   }		  \
    127 } while (0)
    128 #endif /* !STAILQ_CONCAT */
    129 #ifndef TAILQ_CONCAT
    130 #define TAILQ_CONCAT(head1, head2, field) do {		    \
    131     if (!TAILQ_EMPTY(head2)) {			\
    132 	*(head1)->tqh_last = (head2)->tqh_first;	\
    133 	(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
    134 	(head1)->tqh_last = (head2)->tqh_last;		\
    135 	TAILQ_INIT((head2));			\
    136     }				    \
    137 } while (0)
    138 #endif /* !TAILQ_CONCAT */
    139 
    140 #include "pathnames.h"
    141 #include <sys/syslog.h>
    142 
    143 /* some differences between the BSDs  */
    144 #ifdef __FreeBSD_version
    145 #undef _PATH_UNIX
    146 #define _PATH_UNIX "kernel"
    147 #define HAVE_STRNDUP 0
    148 #endif /* __FreeBSD_version */
    149 
    150 #ifdef __NetBSD_Version__
    151 #define HAVE_STRNDUP 1
    152 #define HAVE_DEHUMANIZE_NUMBER 1
    153 #endif /* __NetBSD_Version__ */
    154 
    155 #ifndef HAVE_DEHUMANIZE_NUMBER	/* not in my 4.0-STABLE yet */
    156 extern int dehumanize_number(const char *str, int64_t *size);
    157 #endif /* !HAVE_DEHUMANIZE_NUMBER */
    158 
    159 #if !HAVE_STRNDUP
    160 char *strndup(const char *str, size_t n);
    161 #endif /* !HAVE_STRNDUP */
    162 
    163 #ifdef LIBWRAP
    164 #include <tcpd.h>
    165 #endif
    166 
    167 #define FDMASK(fd)	(1 << (fd))
    168 
    169 #define A_CNT(x)	(sizeof((x)) / sizeof((x)[0]))
    170 
    171 /* debug messages with categories */
    172 #define D_NONE	   0
    173 #define D_CALL	   1	/* function calls */
    174 #define D_DATA	   2	/* syslog message reading/formatting */
    175 #define D_NET	   4	/* sockets/network */
    176 #define D_FILE	   8	/* local files */
    177 #define D_TLS	  16	/* TLS */
    178 #define D_PARSE	  32	/* configuration/parsing */
    179 #define D_EVENT	  64	/* libevent */
    180 #define D_BUFFER 128	/* message queues */
    181 #define D_MEM	 256	/* malloc/free */
    182 #define D_MEM2	1024	/* every single malloc/free */
    183 #define D_SIGN	2048	/* -sign */
    184 #define D_MISC	4096	/* everything else */
    185 #define D_ALL	(D_CALL | D_DATA | D_NET | D_FILE | D_TLS | D_PARSE |  \
    186 		 D_EVENT | D_BUFFER | D_MEM | D_MEM2 | D_SIGN | D_MISC)
    187 #define D_DEFAULT (D_CALL | D_NET | D_FILE | D_TLS | D_MISC)
    188 
    189 
    190 /* build with -DNDEBUG to remove all assert()s and DPRINTF()s */
    191 #ifdef NDEBUG
    192 #define DPRINTF(x, ...) (void)0
    193 #else
    194 #define DPRINTF(x, ...) /*LINTED null effect */(void)(Debug & (x) \
    195     ? (printf("%s:%s:%s:%.4d\t", make_timestamp(NULL, true), \
    196     __FILE__, __func__, __LINE__), printf(__VA_ARGS__)) : 0)
    197 #endif
    198 
    199 /* shortcuts for libevent */
    200 #define EVENT_ADD(x) do {						\
    201 	DPRINTF(D_EVENT, "event_add(%s@%p)\n", #x, x);			\
    202 	if (event_add(x, NULL) == -1) {					\
    203 		DPRINTF(D_EVENT, "Failure in event_add()\n");		\
    204 	}								\
    205 } while (/*CONSTCOND*/0)
    206 #define RETRYEVENT_ADD(x) do {						\
    207 	struct timeval _tv;						\
    208 	_tv.tv_sec = 0;							\
    209 	_tv.tv_usec = TLS_RETRY_EVENT_USEC;				\
    210 	DPRINTF(D_EVENT, "retryevent_add(%s@%p)\n", #x, x);		\
    211 	if (event_add(x, &_tv) == -1) {					\
    212 		DPRINTF(D_EVENT, "Failure in event_add()\n");		\
    213 	}								\
    214 } while (/*CONSTCOND*/0)
    215 #define DEL_EVENT(x) do {						\
    216 	DPRINTF(D_MEM2, "DEL_EVENT(%s@%p)\n", #x, x);			\
    217 	if ((x) && (event_del(x) == -1)) {				\
    218 		DPRINTF(D_EVENT, "Failure in event_del()\n");		\
    219 	}								\
    220 } while (/*CONSTCOND*/0)
    221 
    222 /* safe calls to free() */
    223 #define FREEPTR(x)	if (x) {					\
    224 		DPRINTF(D_MEM2, "free(%s@%p)\n", #x, x);		\
    225 		free(x);	 x = NULL; }
    226 #define FREE_SSL(x)	if (x) {					\
    227 		DPRINTF(D_MEM2, "SSL_free(%s@%p)\n", #x, x);		\
    228 		SSL_free(x);	 x = NULL; }
    229 #define FREE_SSL_CTX(x) if (x) {					\
    230 		DPRINTF(D_MEM2, "SSL_CTX_free(%s@%p)\n", #x, x);	\
    231 		SSL_CTX_free(x); x = NULL; }
    232 
    233 /* reference counting macros for buffers */
    234 #define NEWREF(x) ((x) ? (DPRINTF(D_BUFFER, "inc refcount of " #x \
    235 			" @ %p: %zu --> %zu\n", (x), (x)->refcount, \
    236 			(x)->refcount + 1), (x)->refcount++, (x))\
    237 		       : (DPRINTF(D_BUFFER, "inc refcount of NULL!\n"), NULL))
    238 #define DELREF(x) /*LINTED null effect*/(void)((x) ? (DPRINTF(D_BUFFER, "dec refcount of " #x \
    239 			" @ %p: %zu --> %zu\n", (x), (x)->refcount, \
    240 			(x)->refcount - 1), buf_msg_free(x), NULL) \
    241 		       : (DPRINTF(D_BUFFER, "dec refcount of NULL!\n"), NULL))
    242 
    243 /* assumption:
    244  * - malloc()/calloc() only fails if not enough memory available
    245  * - once init() has set up all global variables etc.
    246  *   the bulk of available memory is used for buffers
    247  *   and can be freed if necessary
    248  */
    249 #define MALLOC(ptr, size) do {						\
    250 	while(!(ptr = malloc(size))) {					\
    251 		DPRINTF(D_MEM, "Unable to allocate memory");		\
    252 		message_allqueues_purge();				\
    253 	}								\
    254 	DPRINTF(D_MEM2, "MALLOC(%s@%p, %zu)\n", #ptr, ptr, size);	\
    255 } while (/*CONSTCOND*/0)
    256 
    257 #define CALLOC(ptr, size) do {						\
    258 	while(!(ptr = calloc(1, size))) {				\
    259 		DPRINTF(D_MEM, "Unable to allocate memory");		\
    260 		message_allqueues_purge();				\
    261 	}								\
    262 	DPRINTF(D_MEM2, "CALLOC(%s@%p, %zu)\n", #ptr, ptr, size);	\
    263 } while (/*CONSTCOND*/0)
    264 
    265 /* define strlen(NULL) to be 0 */
    266 #define SAFEstrlen(x) ((x) ? strlen(x) : 0)
    267 
    268 /* shorthand to block/restore signals for the duration of one function */
    269 #define BLOCK_SIGNALS(omask, newmask) do {				\
    270 	sigemptyset(&newmask);						\
    271 	sigaddset(&newmask, SIGHUP);					\
    272 	sigaddset(&newmask, SIGALRM);					\
    273 	sigprocmask(SIG_BLOCK, &newmask, &omask);			\
    274 } while (/*CONSTCOND*/0)
    275 
    276 #define RESTORE_SIGNALS(omask) sigprocmask(SIG_SETMASK, &omask, NULL)
    277 
    278 /* small optimization to call send_queue() only if queue has elements */
    279 #define SEND_QUEUE(f) do {						\
    280 	if ((f)->f_qelements)						\
    281 		send_queue(0, 0, f);	      				\
    282 } while (/*CONSTCOND*/0)
    283 
    284 #define MAXUNAMES		20	/* maximum number of user names */
    285 #define BSD_TIMESTAMPLEN	14+1
    286 #define MAX_TIMESTAMPLEN	31+1
    287 
    288 /* maximum field lengths in syslog-protocol */
    289 #define PRI_MAX	      5
    290 #define HOST_MAX    255
    291 #define APPNAME_MAX  48
    292 #define PROCID_MAX  128
    293 #define MSGID_MAX    32
    294 /* longest possible header length */
    295 #define HEADER_LEN_MAX (PRI_MAX + 1 + 1 + MAX_TIMESTAMPLEN + 1 + HOST_MAX \
    296 			+ 1 + APPNAME_MAX + 1 + PROCID_MAX + 1 + MSGID_MAX)
    297 
    298 /* allowed number of priorities by IETF standards */
    299 #define IETF_NUM_PRIVALUES  192
    300 
    301 /* check if message with fac/sev belogs to a destination f */
    302 #define MATCH_PRI(f, fac, sev) \
    303 	   (  (((f)->f_pcmp[fac] & PRI_EQ) && ((f)->f_pmask[fac] == (sev))) \
    304 	    ||(((f)->f_pcmp[fac] & PRI_LT) && ((f)->f_pmask[fac]  < (sev)))  \
    305 	    ||(((f)->f_pcmp[fac] & PRI_GT) && ((f)->f_pmask[fac]  > (sev)))  \
    306 	   )
    307 
    308 /* shorthand to test Byte Order Mark which indicates UTF-8 content */
    309 #define IS_BOM(p) ( \
    310     (p)[0] != '\0' && (unsigned char)(p)[0] == (unsigned char)0xEF && \
    311     (p)[1] != '\0' && (unsigned char)(p)[1] == (unsigned char)0xBB && \
    312     (p)[2] != '\0' && (unsigned char)(p)[2] == (unsigned char)0xBF)
    313 
    314 /* message buffer container used for processing, formatting, and queueing */
    315 struct buf_msg {
    316 	size_t	 refcount;
    317 	int	 pri;
    318 	int	 flags;
    319 	char	*timestamp;
    320 	char	*recvhost;
    321 	char	*host;
    322 	char	*prog;
    323 	char	*pid;
    324 	char	*msgid;
    325 	char	*sd;	    /* structured data */
    326 	char	*msg;	    /* message content */
    327 	char	*msgorig;   /* in case we advance *msg beyond header fields
    328 			       we still want to free() the original ptr  */
    329 	size_t	 msglen;    /* strlen(msg) */
    330 	size_t	 msgsize;   /* allocated memory size   */
    331 	size_t	 tlsprefixlen; /* bytes for the TLS length prefix */
    332 	size_t	 prilen;       /* bytes for priority and version  */
    333 };
    334 
    335 /* queue of messages */
    336 struct buf_queue {
    337 	struct buf_msg* msg;
    338 	STAILQ_ENTRY(buf_queue) entries;
    339 };
    340 STAILQ_HEAD(buf_queue_head, buf_queue);
    341 
    342 /* a pair of a socket and an associated event object */
    343 struct socketEvent {
    344 	int fd;
    345 	struct event *ev;
    346 };
    347 
    348 /*
    349  * Flags to logmsg().
    350  */
    351 #define IGN_CONS	0x001	/* don't print on console */
    352 #define SYNC_FILE	0x002	/* do fsync on file after printing */
    353 #define ADDDATE		0x004	/* add a date to the message */
    354 #define MARK		0x008	/* this message is a mark */
    355 #define ISKERNEL	0x010	/* kernel generated message */
    356 #define BSDSYSLOG	0x020	/* line in traditional BSD Syslog format */
    357 #define SIGN_MSG	0x040	/* syslog-sign data, not signed again */
    358 
    359 /* strategies for message_queue_purge() */
    360 #define PURGE_OLDEST		1
    361 #define PURGE_BY_PRIORITY	2
    362 
    363 /*
    364  * This structure represents the files that will have log
    365  * copies printed.
    366  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY,
    367  * or if f_type is F_PIPE and f_pid > 0.
    368  */
    369 
    370 struct filed {
    371 	struct	filed *f_next;		/* next in linked list */
    372 	short	f_type;			/* entry type, see below */
    373 	short	f_file;			/* file descriptor */
    374 	time_t	f_time;			/* time this was last written */
    375 	char	*f_host;		/* host from which to record */
    376 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
    377 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
    378 #define PRI_LT	0x1
    379 #define PRI_EQ	0x2
    380 #define PRI_GT	0x4
    381 	char	*f_program;		/* program this applies to */
    382 	union {
    383 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
    384 		struct {
    385 			char	f_hname[MAXHOSTNAMELEN];
    386 			struct	addrinfo *f_addr;
    387 		} f_forw;		/* UDP forwarding address */
    388 #ifndef DISABLE_TLS
    389 		struct {
    390 			SSL	*ssl;			/* SSL object  */
    391 			struct tls_conn_settings *tls_conn;  /* certificate info */
    392 		} f_tls;		/* TLS forwarding address */
    393 #endif /* !DISABLE_TLS */
    394 		char	f_fname[MAXPATHLEN];
    395 		struct {
    396 			char	f_pname[MAXPATHLEN];
    397 			pid_t	f_pid;
    398 		} f_pipe;
    399 	} f_un;
    400 #ifndef DISABLE_SIGN
    401 	struct signature_group_t *f_sg;	     /* one signature group */
    402 #endif /* !DISABLE_SIGN */
    403 	struct buf_queue_head f_qhead;	     /* undelivered msgs queue */
    404 	size_t	      	      f_qelements;   /* elements in queue */
    405 	size_t		      f_qsize;	     /* size of queue in bytes */
    406 	struct buf_msg	     *f_prevmsg;     /* last message logged */
    407 	struct event	     *f_sq_event;    /* timer for send_queue() */
    408 	int		      f_prevcount;   /* repetition cnt of prevmsg */
    409 	int		      f_repeatcount; /* number of "repeated" msgs */
    410 	int		      f_lasterror;   /* last error on writev() */
    411 	int		      f_flags;	     /* file-specific flags */
    412 #define FFLAG_SYNC	0x01	/* for F_FILE: fsync after every msg */
    413 #define FFLAG_FULL	0x02	/* for F_FILE | F_PIPE: write PRI header */
    414 #define FFLAG_SIGN	0x04	/* for syslog-sign with SG="3":
    415 				 * sign the messages to this destination */
    416 };
    417 
    418 #ifndef DISABLE_TLS
    419 
    420 /* linked list for allowed TLS peer credentials
    421  * (one for fingerprint, one for cert-files)
    422  */
    423 SLIST_HEAD(peer_cred_head, peer_cred);
    424 struct peer_cred {
    425 	SLIST_ENTRY(peer_cred) entries;
    426 	char *data;
    427 };
    428 
    429 /* config options for TLS server-side */
    430 struct tls_global_options_t {
    431 	SSL_CTX *global_TLS_CTX;
    432 	struct peer_cred_head fprint_head;  /* trusted client fingerprints */
    433 	struct peer_cred_head cert_head;    /* trusted client cert files   */
    434 	char *keyfile;	    /* file with private key	 */
    435 	char *certfile;	    /* file with own certificate */
    436 	char *CAfile;	    /* file with CA certificate	 */
    437 	char *CAdir;	    /* alternative: path to directory with CA certs */
    438 	char *x509verify;   /* level of peer verification */
    439 	char *bindhost;	    /* hostname/IP to bind to	  */
    440 	char *bindport;	    /* port/service to bind to	  */
    441 	char *server;	    /* if !NULL: do not listen to incoming TLS	  */
    442 	char *gen_cert;	    /* if !NULL: generate self-signed certificate */
    443 };
    444 
    445 /* TLS needs three sets of sockets:
    446  * - listening sockets: a fixed size array TLS_Listen_Set, just like finet for UDP.
    447  * - outgoing connections: managed as part of struct filed.
    448  * - incoming connections: variable sized, thus a linked list TLS_Incoming.
    449  */
    450 /* every connection has its own input buffer with status
    451  * variables for message reading */
    452 SLIST_HEAD(TLS_Incoming, TLS_Incoming_Conn);
    453 
    454 struct TLS_Incoming_Conn {
    455 	SLIST_ENTRY(TLS_Incoming_Conn) entries;
    456 	struct tls_conn_settings *tls_conn;
    457 	int socket;
    458 	char *inbuf;		    /* input buffer */
    459 	size_t inbuflen;
    460 	size_t cur_msg_len;	    /* length of current msg */
    461 	size_t cur_msg_start;	    /* beginning of current msg */
    462 	size_t read_pos;	    /* ring buffer position to write to */
    463 	size_t errorcount;	    /* to close faulty connections */
    464 	bool closenow;		    /* close connection as soon as buffer processed */
    465 	bool dontsave;		    /* for receiving oversized messages w/o saving them */
    466 };
    467 
    468 #endif /* !DISABLE_TLS */
    469 
    470 #endif /*SYSLOGD_H_*/
    471