xref: /titanic_50/usr/src/lib/libbc/libc/gen/common/ttyslot.c (revision 880d797826457b77414b37d531cc3e1aa166ecbe)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Copyright (c) 1984 Regents of the University of California.
29  * All rights reserved.  The Berkeley software License Agreement
30  * specifies the terms and conditions for redistribution.
31  */
32 
33 /*
34  * Return the number of the slot in the utmp file
35  * corresponding to the current user: try for file 0, 1, 2.
36  * To mimic the behavior of getttyent, we loop through utmp
37  * and try to find an entry with a matching line number.
38  * If we don't find one we return the index of the end of
39  * the file, so that the record can be added to the end of
40  * the file.
41  */
42 #include "../../sys/common/compat.h"
43 #include <sys/syscall.h>
44 #include <sys/fcntl.h>
45 #include <stdio.h>
46 #include <unistd.h>
47 #include <strings.h>
48 
49 int
50 ttyslot(void)
51 {
52 	char *tp, *p;
53 	int s;
54 	int fd;
55 	struct utmpx utx;
56 
57 
58 	if ((tp = ttyname(0)) == NULL &&
59 	    (tp = ttyname(1)) == NULL &&
60 	    (tp = ttyname(2)) == NULL)
61 		return (0);
62 	if ((p = rindex(tp, '/')) == NULL)
63 		p = tp;
64 	else
65 		p++;
66 
67 	if ((fd = _syscall(SYS_openat,
68 	    AT_FDCWD, "/etc/utmpx", O_RDONLY)) == -1) {
69 		perror("ttyslot: open of /etc/utmpx failed:");
70 		return (0);
71 	}
72 
73 	s = 0;
74 	while (_read(fd, &utx, sizeof (struct utmpx)) > 0) {
75 		s++;
76 		if (strncmp(utx.ut_line, p, sizeof (utx.ut_line)) == 0) {
77 			_syscall(SYS_close, fd);
78 			return (s);
79 		}
80 	}
81 	_syscall(SYS_close, fd);
82 	return (s);
83 }
84