xref: /illumos-gate/usr/src/lib/libc/port/gen/ttyslot.c (revision ec6bbcf8dba86c3774c6c4a504af383c15109e40)
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 2008 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  * 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 #include <pthread.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 *p;
60 	int s;
61 	int ret = -1;
62 	int console = FALSE;
63 	char ttynm[128];
64 	FILE *fp;
65 	int cancel_state;
66 
67 	/*
68 	 * The UNIX98 Posix conformance test suite requires
69 	 * ttyslot() to not be a cancellation point.
70 	 */
71 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
72 
73 	if ((p = ttyname_r(0, ttynm, 128)) != NULL ||
74 	    (p = ttyname_r(1, ttynm, 128)) != NULL ||
75 	    (p = ttyname_r(2, ttynm, 128)) != NULL) {
76 		if (strncmp(p, "/dev/", 5) == 0)
77 			p += 5;
78 		if (strcmp(p, "console") == 0)
79 			console = TRUE;
80 		s = 0;
81 		if ((fp = fopen(UTMPX_FILE, "rF")) != NULL) {
82 			while ((fread(&ubuf, sizeof (ubuf), 1, fp)) == 1) {
83 				if ((ubuf.ut_type == INIT_PROCESS ||
84 				    ubuf.ut_type == LOGIN_PROCESS ||
85 				    ubuf.ut_type == USER_PROCESS) &&
86 				    strncmp(p, ubuf.ut_line,
87 				    sizeof (ubuf.ut_line)) == 0) {
88 					ret = s;
89 					if (!console ||
90 					    strncmp(ubuf.ut_host, ":0", 2) == 0)
91 						break;
92 				}
93 				s++;
94 			}
95 			(void) fclose(fp);
96 		}
97 	}
98 
99 	(void) pthread_setcancelstate(cancel_state, NULL);
100 	return (ret);
101 }
102