xref: /openbsd-src/usr.bin/sendbug/sendbug.c (revision ae6b53b51a631f9a2ae4e059f41143695179c108)
1 /*	$OpenBSD: sendbug.c,v 1.49 2007/05/11 02:07:47 ray Exp $	*/
2 
3 /*
4  * Written by Ray Lai <ray@cyth.net>.
5  * Public domain.
6  */
7 
8 #include <sys/types.h>
9 #include <sys/mman.h>
10 #include <sys/param.h>
11 #include <sys/stat.h>
12 #include <sys/sysctl.h>
13 #include <sys/wait.h>
14 
15 #include <ctype.h>
16 #include <err.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <paths.h>
21 #include <pwd.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 
28 #include "atomicio.h"
29 
30 #define _PATH_DMESG "/var/run/dmesg.boot"
31 
32 int	checkfile(const char *);
33 void	dmesg(FILE *);
34 int	editit(const char *);
35 void	init(void);
36 int	matchline(const char *, const char *, size_t);
37 int	prompt(void);
38 int	send_file(const char *, int);
39 int	sendmail(const char *);
40 void	template(FILE *);
41 
42 const char *categories = "system user library documentation ports kernel "
43     "alpha amd64 arm i386 m68k m88k mips ppc sgi sparc sparc64 vax";
44 char *version = "4.2";
45 
46 struct passwd *pw;
47 char os[BUFSIZ], rel[BUFSIZ], mach[BUFSIZ], details[BUFSIZ];
48 char *fullname, *tmppath;
49 int Dflag, wantcleanup;
50 
51 __dead void
52 usage(void)
53 {
54 	extern char *__progname;
55 
56 	fprintf(stderr, "usage: %s [-DLPV]\n", __progname);
57 	exit(1);
58 }
59 
60 void
61 cleanup()
62 {
63 	if (wantcleanup && tmppath && unlink(tmppath) == -1)
64 		warn("unlink");
65 }
66 
67 
68 int
69 main(int argc, char *argv[])
70 {
71 	int ch, c, fd, ret = 1;
72 	const char *tmpdir;
73 	struct stat sb;
74 	char *pr_form;
75 	time_t mtime;
76 	FILE *fp;
77 
78 	while ((ch = getopt(argc, argv, "DLPV")) != -1)
79 		switch (ch) {
80 		case 'D':
81 			Dflag = 1;
82 			break;
83 		case 'L':
84 			printf("Known categories:\n");
85 			printf("%s\n\n", categories);
86 			exit(0);
87 		case 'P':
88 			init();
89 			template(stdout);
90 			exit(0);
91 		case 'V':
92 			printf("%s\n", version);
93 			exit(0);
94 		default:
95 			usage();
96 		}
97 	argc -= optind;
98 	argv += optind;
99 
100 	if (argc > 0)
101 		usage();
102 
103 	if ((tmpdir = getenv("TMPDIR")) == NULL || tmpdir[0] == '\0')
104 		tmpdir = _PATH_TMP;
105 	if (asprintf(&tmppath, "%s%sp.XXXXXXXXXX", tmpdir,
106 	    tmpdir[strlen(tmpdir) - 1] == '/' ? "" : "/") == -1)
107 		err(1, "asprintf");
108 	if ((fd = mkstemp(tmppath)) == -1)
109 		err(1, "mkstemp");
110 	wantcleanup = 1;
111 	atexit(cleanup);
112 	if ((fp = fdopen(fd, "w+")) == NULL)
113 		err(1, "fdopen");
114 
115 	init();
116 
117 	pr_form = getenv("PR_FORM");
118 	if (pr_form) {
119 		char buf[BUFSIZ];
120 		size_t len;
121 		FILE *frfp;
122 
123 		frfp = fopen(pr_form, "r");
124 		if (frfp == NULL) {
125 			warn("can't seem to read your template file "
126 			    "(`%s'), ignoring PR_FORM", pr_form);
127 			template(fp);
128 		} else {
129 			while (!feof(frfp)) {
130 				len = fread(buf, 1, sizeof buf, frfp);
131 				if (len == 0)
132 					break;
133 				if (fwrite(buf, 1, len, fp) != len)
134 					break;
135 			}
136 			fclose(frfp);
137 		}
138 	} else
139 		template(fp);
140 
141 	if (fflush(fp) == EOF || fstat(fd, &sb) == -1 || fclose(fp) == EOF)
142 		err(1, "error creating template");
143 	mtime = sb.st_mtime;
144 
145  edit:
146 	if (editit(tmppath) == -1)
147 		err(1, "error running editor");
148 
149 	if (stat(tmppath, &sb) == -1)
150 		err(1, "stat");
151 	if (mtime == sb.st_mtime)
152 		errx(1, "report unchanged, nothing sent");
153 
154  prompt:
155 	if (!checkfile(tmppath))
156 		fprintf(stderr, "fields are blank, must be filled in\n");
157 	c = prompt();
158 	switch (c) {
159 	case 'a':
160 	case EOF:
161 		wantcleanup = 0;
162 		errx(1, "unsent report in %s", tmppath);
163 	case 'e':
164 		goto edit;
165 	case 's':
166 		if (sendmail(tmppath) == -1)
167 			goto quit;
168 		break;
169 	default:
170 		goto prompt;
171 	}
172 
173 	ret = 0;
174 quit:
175 	return (ret);
176 }
177 
178 void
179 dmesg(FILE *fp)
180 {
181 	char buf[BUFSIZ];
182 	FILE *dfp;
183 	off_t offset = -1;
184 
185 	dfp = fopen(_PATH_DMESG, "r");
186 	if (dfp == NULL) {
187 		warn("can't read dmesg");
188 		return;
189 	}
190 
191 	fputs("\n"
192 	    "<dmesg is attached.>\n"
193 	    "<Feel free to delete or use the -D flag if it contains "
194 	    "sensitive information.>\n", fp);
195 	/* Find last line starting with "OpenBSD". */
196 	for (;;) {
197 		off_t o;
198 
199 		o = ftello(dfp);
200 		if (fgets(buf, sizeof(buf), dfp) == NULL)
201 			break;
202 		if (!strncmp("OpenBSD ", buf, sizeof("OpenBSD ") - 1))
203 			offset = o;
204 	}
205 	if (offset != -1) {
206 		size_t len;
207 
208 		clearerr(dfp);
209 		fseeko(dfp, offset, SEEK_SET);
210 		while (offset != -1 && !feof(dfp)) {
211 			len = fread(buf, 1, sizeof buf, dfp);
212 			if (len == 0)
213 				break;
214 			if (fwrite(buf, 1, len, fp) != len)
215 				break;
216 		}
217 	}
218 	fclose(dfp);
219 }
220 
221 /*
222  * Execute an editor on the specified pathname, which is interpreted
223  * from the shell.  This means flags may be included.
224  *
225  * Returns -1 on error, or the exit value on success.
226  */
227 int
228 editit(const char *pathname)
229 {
230 	char *argp[] = {"sh", "-c", NULL, NULL}, *ed, *p;
231 	sig_t sighup, sigint, sigquit;
232 	pid_t pid;
233 	int saved_errno, st;
234 
235 	ed = getenv("VISUAL");
236 	if (ed == NULL || ed[0] == '\0')
237 		ed = getenv("EDITOR");
238 	if (ed == NULL || ed[0] == '\0')
239 		ed = _PATH_VI;
240 	if (asprintf(&p, "%s %s", ed, pathname) == -1)
241 		return (-1);
242 	argp[2] = p;
243 
244 	sighup = signal(SIGHUP, SIG_IGN);
245 	sigint = signal(SIGINT, SIG_IGN);
246 	sigquit = signal(SIGQUIT, SIG_IGN);
247 	if ((pid = fork()) == -1)
248 		goto fail;
249 	if (pid == 0) {
250 		execv(_PATH_BSHELL, argp);
251 		_exit(127);
252 	}
253 	while (waitpid(pid, &st, 0) == -1)
254 		if (errno != EINTR)
255 			goto fail;
256 	free(p);
257 	(void)signal(SIGHUP, sighup);
258 	(void)signal(SIGINT, sigint);
259 	(void)signal(SIGQUIT, sigquit);
260 	if (!WIFEXITED(st)) {
261 		errno = EINTR;
262 		return (-1);
263 	}
264 	return (WEXITSTATUS(st));
265 
266  fail:
267 	saved_errno = errno;
268 	(void)signal(SIGHUP, sighup);
269 	(void)signal(SIGINT, sigint);
270 	(void)signal(SIGQUIT, sigquit);
271 	free(p);
272 	errno = saved_errno;
273 	return (-1);
274 }
275 
276 int
277 prompt(void)
278 {
279 	int c, ret;
280 
281 	fpurge(stdin);
282 	fprintf(stderr, "a)bort, e)dit, or s)end: ");
283 	fflush(stderr);
284 	ret = getchar();
285 	if (ret == EOF || ret == '\n')
286 		return (ret);
287 	do {
288 		c = getchar();
289 	} while (c != EOF && c != '\n');
290 	return (ret);
291 }
292 
293 int
294 sendmail(const char *pathname)
295 {
296 	int filedes[2];
297 
298 	if (pipe(filedes) == -1) {
299 		warn("pipe: unsent report in %s", pathname);
300 		return (-1);
301 	}
302 	switch (fork()) {
303 	case -1:
304 		warn("fork error: unsent report in %s",
305 		    pathname);
306 		return (-1);
307 	case 0:
308 		close(filedes[1]);
309 		if (dup2(filedes[0], STDIN_FILENO) == -1) {
310 			warn("dup2 error: unsent report in %s",
311 			    pathname);
312 			return (-1);
313 		}
314 		close(filedes[0]);
315 		execl("/usr/sbin/sendmail", "sendmail",
316 		    "-oi", "-t", (void *)NULL);
317 		warn("sendmail error: unsent report in %s",
318 		    pathname);
319 		return (-1);
320 	default:
321 		close(filedes[0]);
322 		/* Pipe into sendmail. */
323 		if (send_file(pathname, filedes[1]) == -1) {
324 			warn("send_file error: unsent report in %s",
325 			    pathname);
326 			return (-1);
327 		}
328 		close(filedes[1]);
329 		wait(NULL);
330 		break;
331 	}
332 	return (0);
333 }
334 
335 void
336 init(void)
337 {
338 	size_t amp, len, gecoslen, namelen;
339 	int sysname[2];
340 	char ch, *cp;
341 
342 	if ((pw = getpwuid(getuid())) == NULL)
343 		err(1, "getpwuid");
344 	namelen = strlen(pw->pw_name);
345 
346 	/* Count number of '&'. */
347 	for (amp = 0, cp = pw->pw_gecos; *cp && *cp != ','; ++cp)
348 		if (*cp == '&')
349 			++amp;
350 
351 	/* Truncate gecos to full name. */
352 	gecoslen = cp - pw->pw_gecos;
353 	pw->pw_gecos[gecoslen] = '\0';
354 
355 	/* Expanded str = orig str - '&' chars + concatenated logins. */
356 	len = gecoslen - amp + (amp * namelen) + 1;
357 	if ((fullname = malloc(len)) == NULL)
358 		err(1, "malloc");
359 
360 	/* Upper case first char of login. */
361 	ch = pw->pw_name[0];
362 	pw->pw_name[0] = toupper((unsigned char)pw->pw_name[0]);
363 
364 	cp = pw->pw_gecos;
365 	fullname[0] = '\0';
366 	while (cp != NULL) {
367 		char *token;
368 
369 		token = strsep(&cp, "&");
370 		if (token != pw->pw_gecos &&
371 		    strlcat(fullname, pw->pw_name, len) >= len)
372 			errx(1, "truncated string");
373 		if (strlcat(fullname, token, len) >= len)
374 			errx(1, "truncated string");
375 	}
376 	/* Restore case of first char of login. */
377 	pw->pw_name[0] = ch;
378 
379 	sysname[0] = CTL_KERN;
380 	sysname[1] = KERN_OSTYPE;
381 	len = sizeof(os) - 1;
382 	if (sysctl(sysname, 2, &os, &len, NULL, 0) == -1)
383 		err(1, "sysctl");
384 
385 	sysname[0] = CTL_KERN;
386 	sysname[1] = KERN_OSRELEASE;
387 	len = sizeof(rel) - 1;
388 	if (sysctl(sysname, 2, &rel, &len, NULL, 0) == -1)
389 		err(1, "sysctl");
390 
391 	sysname[0] = CTL_KERN;
392 	sysname[1] = KERN_VERSION;
393 	len = sizeof(details) - 1;
394 	if (sysctl(sysname, 2, &details, &len, NULL, 0) == -1)
395 		err(1, "sysctl");
396 
397 	cp = strchr(details, '\n');
398 	if (cp) {
399 		cp++;
400 		if (*cp)
401 			*cp++ = '\t';
402 		if (*cp)
403 			*cp++ = '\t';
404 		if (*cp)
405 			*cp++ = '\t';
406 	}
407 
408 	sysname[0] = CTL_HW;
409 	sysname[1] = HW_MACHINE;
410 	len = sizeof(mach) - 1;
411 	if (sysctl(sysname, 2, &mach, &len, NULL, 0) == -1)
412 		err(1, "sysctl");
413 }
414 
415 int
416 send_file(const char *file, int dst)
417 {
418 	int blank = 0;
419 	size_t len;
420 	char *buf;
421 	FILE *fp;
422 
423 	if ((fp = fopen(file, "r")) == NULL)
424 		return (-1);
425 	while ((buf = fgetln(fp, &len))) {
426 		/* Skip lines starting with "SENDBUG". */
427 		if (len >= sizeof("SENDBUG") - 1 &&
428 		    memcmp(buf, "SENDBUG", sizeof("SENDBUG") - 1) == 0)
429 			continue;
430 		if (len == 1 && buf[0] == '\n')
431 			blank = 1;
432 		/* Skip comments, but only if we encountered a blank line. */
433 		while (len) {
434 			char *sp = NULL, *ep = NULL;
435 			size_t copylen;
436 
437 			if (blank && (sp = memchr(buf, '<', len)) != NULL)
438 				ep = memchr(sp, '>', len - (sp - buf + 1));
439 			/* Length of string before comment. */
440 			if (ep)
441 				copylen = sp - buf;
442 			else
443 				copylen = len;
444 			if (atomicio(vwrite, dst, buf, copylen) != copylen) {
445 				int saved_errno = errno;
446 
447 				fclose(fp);
448 				errno = saved_errno;
449 				return (-1);
450 			}
451 			if (!ep)
452 				break;
453 			/* Skip comment. */
454 			len -= ep - buf + 1;
455 			buf = ep + 1;
456 		}
457 	}
458 	fclose(fp);
459 	return (0);
460 }
461 
462 /*
463  * Does line start with `s' and end with non-comment and non-whitespace?
464  * Note: Does not treat `line' as a C string.
465  */
466 int
467 matchline(const char *s, const char *line, size_t linelen)
468 {
469 	size_t slen;
470 	int comment;
471 
472 	slen = strlen(s);
473 	/* Is line shorter than string? */
474 	if (linelen <= slen)
475 		return (0);
476 	/* Does line start with string? */
477 	if (memcmp(line, s, slen) != 0)
478 		return (0);
479 	/* Does line contain anything but comments and whitespace? */
480 	line += slen;
481 	linelen -= slen;
482 	comment = 0;
483 	while (linelen) {
484 		if (comment) {
485 			if (*line == '>')
486 				comment = 0;
487 		} else if (*line == '<')
488 			comment = 1;
489 		else if (!isspace((unsigned char)*line))
490 			return (1);
491 		++line;
492 		--linelen;
493 	}
494 	return (0);
495 }
496 
497 /*
498  * Are all required fields filled out?
499  */
500 int
501 checkfile(const char *pathname)
502 {
503 	FILE *fp;
504 	size_t len;
505 	int category, class, priority, release, severity, synopsis;
506 	char *buf;
507 
508 	if ((fp = fopen(pathname, "r")) == NULL) {
509 		warn("%s", pathname);
510 		return (0);
511 	}
512 	category = class = priority = release = severity = synopsis = 0;
513 	while ((buf = fgetln(fp, &len))) {
514 		if (matchline(">Category:", buf, len))
515 			category = 1;
516 		else if (matchline(">Class:", buf, len))
517 			class = 1;
518 		else if (matchline(">Priority:", buf, len))
519 			priority = 1;
520 		else if (matchline(">Release:", buf, len))
521 			release = 1;
522 		else if (matchline(">Severity:", buf, len))
523 			severity = 1;
524 		else if (matchline(">Synopsis:", buf, len))
525 			synopsis = 1;
526 	}
527 	fclose(fp);
528 	return (category && class && priority && release && severity &&
529 	    synopsis);
530 }
531 
532 void
533 template(FILE *fp)
534 {
535 	fprintf(fp, "SENDBUG: -*- sendbug -*-\n");
536 	fprintf(fp, "SENDBUG: Lines starting with `SENDBUG' will"
537 	    " be removed automatically, as\n");
538 	fprintf(fp, "SENDBUG: will all comments (text enclosed in `<' and `>').\n");
539 	fprintf(fp, "SENDBUG:\n");
540 	fprintf(fp, "SENDBUG: Choose from the following categories:\n");
541 	fprintf(fp, "SENDBUG:\n");
542 	fprintf(fp, "SENDBUG: %s\n", categories);
543 	fprintf(fp, "SENDBUG:\n");
544 	fprintf(fp, "SENDBUG:\n");
545 	fprintf(fp, "To: %s\n", "gnats@openbsd.org");
546 	fprintf(fp, "Subject: \n");
547 	fprintf(fp, "From: %s\n", pw->pw_name);
548 	fprintf(fp, "Cc: %s\n", pw->pw_name);
549 	fprintf(fp, "Reply-To: %s\n", pw->pw_name);
550 	fprintf(fp, "X-sendbug-version: %s\n", version);
551 	fprintf(fp, "\n");
552 	fprintf(fp, "\n");
553 	fprintf(fp, ">Submitter-Id:\tnet\n");
554 	fprintf(fp, ">Originator:\t%s\n", fullname);
555 	fprintf(fp, ">Organization:\n");
556 	fprintf(fp, "net\n");
557 	fprintf(fp, ">Synopsis:\t<synopsis of the problem (one line)>\n");
558 	fprintf(fp, ">Severity:\t"
559 	    "<[ non-critical | serious | critical ] (one line)>\n");
560 	fprintf(fp, ">Priority:\t<[ low | medium | high ] (one line)>\n");
561 	fprintf(fp, ">Category:\t<PR category (one line)>\n");
562 	fprintf(fp, ">Class:\t\t"
563 	    "<[ sw-bug | doc-bug | change-request | support ] (one line)>\n");
564 	fprintf(fp, ">Release:\t<release number or tag (one line)>\n");
565 	fprintf(fp, ">Environment:\n");
566 	fprintf(fp, "\t<machine, os, target, libraries (multiple lines)>\n");
567 	fprintf(fp, "\tSystem      : %s %s\n", os, rel);
568 	fprintf(fp, "\tDetails     : %s\n", details);
569 	fprintf(fp, "\tArchitecture: %s.%s\n", os, mach);
570 	fprintf(fp, "\tMachine     : %s\n", mach);
571 	fprintf(fp, ">Description:\n");
572 	fprintf(fp, "\t<precise description of the problem (multiple lines)>\n");
573 	fprintf(fp, ">How-To-Repeat:\n");
574 	fprintf(fp, "\t<code/input/activities to reproduce the problem"
575 	    " (multiple lines)>\n");
576 	fprintf(fp, ">Fix:\n");
577 	fprintf(fp, "\t<how to correct or work around the problem,"
578 	    " if known (multiple lines)>\n");
579 
580 	if (!Dflag)
581 		dmesg(fp);
582 }
583