xref: /illumos-gate/usr/src/lib/libc/port/gen/ttyslot.c (revision 06e1a714)
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  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*	Copyright (c) 1988 AT&T	*/
29 /*	  All Rights Reserved  	*/
30 
31 
32 /*
33  * Return the number of the slot in the utmp file
34  * corresponding to the current user: try for file 0, 1, 2.
35  * Returns -1 if slot not found.
36  */
37 
38 #pragma weak ttyslot = _ttyslot
39 
40 #include "synonyms.h"
41 #include <string.h>
42 #include <stdio.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <unistd.h>
46 #include <utmpx.h>
47 #include <stdlib.h>
48 
49 #ifndef TRUE
50 #define	TRUE 1
51 #define	FALSE 0
52 #endif
53 
54 int
55 ttyslot(void)
56 {
57 	struct futmpx ubuf;
58 	char *tp, *p;
59 	int s;
60 	int ret = -1, console = FALSE;
61 	char ttynm[128];
62 	FILE	*fp;
63 
64 	if ((tp = ttyname_r(0, ttynm, 128)) == NULL &&
65 	    (tp = ttyname_r(1, ttynm, 128)) == NULL &&
66 	    (tp = ttyname_r(2, ttynm, 128)) == NULL)
67 		return (-1);
68 
69 	p = tp;
70 	if (strncmp(tp, "/dev/", 5) == 0)
71 		p += 5;
72 
73 	if (strcmp(p, "console") == 0)
74 		console = TRUE;
75 
76 	s = 0;
77 	if ((fp = fopen(UTMPX_FILE, "rF")) == NULL)
78 		return (-1);
79 	while ((fread(&ubuf, sizeof (ubuf), 1, fp)) == 1) {
80 		if ((ubuf.ut_type == INIT_PROCESS ||
81 		    ubuf.ut_type == LOGIN_PROCESS ||
82 		    ubuf.ut_type == USER_PROCESS) &&
83 		    strncmp(p, ubuf.ut_line, sizeof (ubuf.ut_line)) == 0) {
84 			ret = s;
85 			if (!console || strncmp(ubuf.ut_host, ":0", 2) == 0)
86 				break;
87 		}
88 		s++;
89 	}
90 	(void) fclose(fp);
91 	return (ret);
92 }
93