ptmget.c revision 1.4
1/*	$OpenBSD: ptmget.c,v 1.4 2021/10/24 21:24:20 deraadt Exp $ */
2/*
3 *	Written by Bob Beck <beck@openbsd.org> 2004 Public Domain.
4 *	Basic test to ensure /dev/ptm works, and what it returns
5 * 	can be used via tty(4);
6 */
7#include <sys/types.h>
8#include <sys/ioctl.h>
9#include <sys/time.h>
10#include <sys/tty.h>
11#include <sys/stat.h>
12
13#include <err.h>
14#include <fcntl.h>
15#include <grp.h>
16#include <stdio.h>
17#include <string.h>
18#include <unistd.h>
19
20int
21main(int argc, char *argv[])
22{
23	int fd;
24	struct ptmget ptm;
25	struct termios ti;
26	struct stat sb;
27	struct group *gr;
28	gid_t ttygid;
29
30	if ((gr = getgrnam("tty")) != NULL)
31		ttygid = gr->gr_gid;
32	else
33		ttygid = 4;
34	fd = open("/dev/ptm", O_RDWR);
35	if (fd == -1)
36		err(1, "Can't open /dev/ptm");
37	if ((ioctl(fd, PTMGET, &ptm) == -1))
38		err(1, "ioctl PTMGET failed");
39	if ((tcgetattr(ptm.sfd, &ti) == -1))
40		err(1, "tcgetattr failed on slave");
41	if ((tcgetattr(ptm.cfd, &ti) == -1))
42		err(1, "tcgetattr failed on master");
43	if ((ioctl(ptm.sfd, TIOCSTOP) == -1))
44		err(1, "ioctl TIOCSTOP failed on slave");
45	if ((ioctl(ptm.cfd, TIOCSTOP) == -1))
46		err(1, "ioctl TIOCSTOP failed on master");
47	bzero(&sb, sizeof(sb));
48	if ((stat(ptm.sn, &sb) == -1))
49		err(1, "can't stat slave %s", ptm.sn);
50	if (sb.st_mode != (S_IFCHR | S_IWUSR | S_IRUSR | S_IWGRP))
51		errx(1, "Bad mode %o on %s, should be %o", sb.st_mode,
52		     ptm.sn, (S_IFCHR | S_IWUSR | S_IRUSR | S_IWGRP));
53	if (sb.st_gid != ttygid)
54		errx(1, "%s gid is %d not the tty group(%d)", ptm.sn,
55		     sb.st_gid, ttygid);
56	if (sb.st_uid != geteuid())
57		errx(1, "%s owned by %d, not the current user (%d)", ptm.sn,
58		     sb.st_uid, geteuid());
59	return(0);
60}
61