1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1991, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#if 0
33#ifndef lint
34static const char copyright[] =
35"@(#) Copyright (c) 1991, 1993\n\
36	The Regents of the University of California.  All rights reserved.\n";
37#endif /* not lint */
38
39#ifndef lint
40static const char sccsid[] = "@(#)dmesg.c	8.1 (Berkeley) 6/5/93";
41#endif /* not lint */
42#endif
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD$");
45
46#include <sys/types.h>
47#include <sys/msgbuf.h>
48#include <sys/sysctl.h>
49
50#include <ctype.h>
51#include <err.h>
52#include <errno.h>
53#include <fcntl.h>
54#include <kvm.h>
55#include <limits.h>
56#include <locale.h>
57#include <nlist.h>
58#include <stdio.h>
59#include <stdbool.h>
60#include <stdlib.h>
61#include <string.h>
62#include <unistd.h>
63#include <vis.h>
64#include <sys/syslog.h>
65
66static struct nlist nl[] = {
67#define	X_MSGBUF	0
68	{ "_msgbufp", 0, 0, 0, 0 },
69	{ NULL, 0, 0, 0, 0 },
70};
71
72void usage(void) __dead2;
73
74#define	KREAD(addr, var) \
75	kvm_read(kd, addr, &var, sizeof(var)) != sizeof(var)
76
77int
78main(int argc, char *argv[])
79{
80	struct msgbuf *bufp, cur;
81	char *bp, *ep, *memf, *nextp, *nlistf, *p, *q, *visbp;
82	kvm_t *kd;
83	size_t buflen, bufpos;
84	long pri;
85	int ch, clear;
86	bool all;
87
88	all = false;
89	clear = false;
90	(void) setlocale(LC_CTYPE, "");
91	memf = nlistf = NULL;
92	while ((ch = getopt(argc, argv, "acM:N:")) != -1)
93		switch(ch) {
94		case 'a':
95			all = true;
96			break;
97		case 'c':
98			clear = true;
99			break;
100		case 'M':
101			memf = optarg;
102			break;
103		case 'N':
104			nlistf = optarg;
105			break;
106		case '?':
107		default:
108			usage();
109		}
110	argc -= optind;
111	if (argc != 0)
112		usage();
113
114	if (memf == NULL) {
115		/*
116		 * Running kernel.  Use sysctl.  This gives an unwrapped buffer
117		 * as a side effect.  Remove nulterm (if present) so the value
118		 * returned by sysctl is formatted as the rest of the code
119		 * expects (the same as the value read from a core file below).
120		 */
121		if (sysctlbyname("kern.msgbuf", NULL, &buflen, NULL, 0) == -1)
122			err(1, "sysctl kern.msgbuf");
123		/* Allocate extra room for growth between the sysctl calls. */
124		buflen += buflen/8;
125		/* Allocate more than sysctl sees, for room to append \n\0. */
126		if ((bp = malloc(buflen + 2)) == NULL)
127			errx(1, "malloc failed");
128		if (sysctlbyname("kern.msgbuf", bp, &buflen, NULL, 0) == -1)
129			err(1, "sysctl kern.msgbuf");
130		if (buflen > 0 && bp[buflen - 1] == '\0')
131			buflen--;
132		if (clear)
133			if (sysctlbyname("kern.msgbuf_clear", NULL, NULL, &clear, sizeof(int)))
134				err(1, "sysctl kern.msgbuf_clear");
135	} else {
136		/* Read in kernel message buffer and do sanity checks. */
137		kd = kvm_open(nlistf, memf, NULL, O_RDONLY, "dmesg");
138		if (kd == NULL)
139			exit (1);
140		if (kvm_nlist(kd, nl) == -1)
141			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
142		if (nl[X_MSGBUF].n_type == 0)
143			errx(1, "%s: msgbufp not found",
144			    nlistf ? nlistf : "namelist");
145		if (KREAD(nl[X_MSGBUF].n_value, bufp) || KREAD((long)bufp, cur))
146			errx(1, "kvm_read: %s", kvm_geterr(kd));
147		if (cur.msg_magic != MSG_MAGIC)
148			errx(1, "kernel message buffer has different magic "
149			    "number");
150		if ((bp = malloc(cur.msg_size + 2)) == NULL)
151			errx(1, "malloc failed");
152
153		/* Unwrap the circular buffer to start from the oldest data. */
154		bufpos = MSGBUF_SEQ_TO_POS(&cur, cur.msg_wseq);
155		if (kvm_read(kd, (long)&cur.msg_ptr[bufpos], bp,
156		    cur.msg_size - bufpos) != (ssize_t)(cur.msg_size - bufpos))
157			errx(1, "kvm_read: %s", kvm_geterr(kd));
158		if (bufpos != 0 && kvm_read(kd, (long)cur.msg_ptr,
159		    &bp[cur.msg_size - bufpos], bufpos) != (ssize_t)bufpos)
160			errx(1, "kvm_read: %s", kvm_geterr(kd));
161		kvm_close(kd);
162		buflen = cur.msg_size;
163	}
164
165	/*
166	 * Ensure that the buffer ends with a newline and a \0 to avoid
167	 * complications below.  We left space above.
168	 */
169	if (buflen == 0 || bp[buflen - 1] != '\n')
170		bp[buflen++] = '\n';
171	bp[buflen] = '\0';
172
173	if ((visbp = malloc(4 * buflen + 1)) == NULL)
174		errx(1, "malloc failed");
175
176	/*
177	 * The message buffer is circular, but has been unwrapped so that
178	 * the oldest data comes first.  The data will be preceded by \0's
179	 * if the message buffer was not full.
180	 */
181	p = bp;
182	ep = &bp[buflen];
183	if (*p == '\0') {
184		/* Strip leading \0's */
185		while (*p == '\0')
186			p++;
187	} else if (!all) {
188		/* Skip the first line, since it is probably incomplete. */
189		p = memchr(p, '\n', ep - p);
190		p++;
191	}
192	for (; p < ep; p = nextp) {
193		nextp = memchr(p, '\n', ep - p);
194		nextp++;
195
196		/* Skip ^<[0-9]+> syslog sequences. */
197		if (*p == '<' && isdigit(*(p+1))) {
198			errno = 0;
199			pri = strtol(p + 1, &q, 10);
200			if (*q == '>' && pri >= 0 && pri < INT_MAX &&
201			    errno == 0) {
202				if (LOG_FAC(pri) != LOG_KERN && !all)
203					continue;
204				p = q + 1;
205			}
206		}
207
208		(void)strvisx(visbp, p, nextp - p, 0);
209		(void)printf("%s", visbp);
210	}
211	exit(0);
212}
213
214void
215usage(void)
216{
217	fprintf(stderr, "usage: dmesg [-ac] [-M core [-N system]]\n");
218	exit(1);
219}
220