xref: /titanic_52/usr/src/lib/libc/port/gen/ttyslot.c (revision 7aec1d6e253b21f9e9b7ef68b4d81ab9859b51fe)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*	Copyright (c) 1988 AT&T	*/
30 /*	  All Rights Reserved  	*/
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  * Returns -1 if slot not found.
37  */
38 
39 #pragma weak ttyslot = _ttyslot
40 
41 #include "synonyms.h"
42 #include <string.h>
43 #include <stdio.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <unistd.h>
47 #include <utmpx.h>
48 #include <stdlib.h>
49 
50 #ifndef TRUE
51 #define	TRUE 1
52 #define	FALSE 0
53 #endif
54 
55 int
56 ttyslot(void)
57 {
58 	struct futmpx ubuf;
59 	char *tp, *p;
60 	int s;
61 	int ret = -1, console = FALSE;
62 	char ttynm[128];
63 	FILE	*fp;
64 
65 	if ((tp = ttyname_r(0, ttynm, 128)) == NULL &&
66 	    (tp = ttyname_r(1, ttynm, 128)) == NULL &&
67 	    (tp = ttyname_r(2, ttynm, 128)) == NULL)
68 		return (-1);
69 
70 	p = tp;
71 	if (strncmp(tp, "/dev/", 5) == 0)
72 		p += 5;
73 
74 	if (strcmp(p, "console") == 0)
75 		console = TRUE;
76 
77 	s = 0;
78 	if ((fp = fopen(UTMPX_FILE, "r")) == NULL)
79 		return (-1);
80 	while ((fread(&ubuf, sizeof (ubuf), 1, fp)) == 1) {
81 		if ((ubuf.ut_type == INIT_PROCESS ||
82 		    ubuf.ut_type == LOGIN_PROCESS ||
83 		    ubuf.ut_type == USER_PROCESS) &&
84 		    strncmp(p, ubuf.ut_line, sizeof (ubuf.ut_line)) == 0) {
85 			ret = s;
86 			if (!console || strncmp(ubuf.ut_host, ":0", 2) == 0)
87 				break;
88 		}
89 		s++;
90 	}
91 	(void) fclose(fp);
92 	return (ret);
93 }
94