xref: /titanic_44/usr/src/lib/libc/port/gen/ttyslot.c (revision 8de5c4f463386063e184a851437d58080c6c626c)
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 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
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 #include "lint.h"
39 #include <string.h>
40 #include <stdio.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #include <utmpx.h>
45 #include <stdlib.h>
46 #include <pthread.h>
47 
48 #ifndef TRUE
49 #define	TRUE 1
50 #define	FALSE 0
51 #endif
52 
53 int
54 ttyslot(void)
55 {
56 	struct futmpx ubuf;
57 	char *p;
58 	int s;
59 	int ret = -1;
60 	int console = FALSE;
61 	char ttynm[128];
62 	FILE *fp;
63 	int cancel_state;
64 
65 	/*
66 	 * The UNIX98 Posix conformance test suite requires
67 	 * ttyslot() to not be a cancellation point.
68 	 */
69 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
70 
71 	if ((p = ttyname_r(0, ttynm, 128)) != NULL ||
72 	    (p = ttyname_r(1, ttynm, 128)) != NULL ||
73 	    (p = ttyname_r(2, ttynm, 128)) != NULL) {
74 		if (strncmp(p, "/dev/", 5) == 0)
75 			p += 5;
76 		if (strcmp(p, "console") == 0)
77 			console = TRUE;
78 		s = 0;
79 		if ((fp = fopen(UTMPX_FILE, "rF")) != NULL) {
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,
85 				    sizeof (ubuf.ut_line)) == 0) {
86 					ret = s;
87 					if (!console ||
88 					    strncmp(ubuf.ut_host, ":0", 2) == 0)
89 						break;
90 				}
91 				s++;
92 			}
93 			(void) fclose(fp);
94 		}
95 	}
96 
97 	(void) pthread_setcancelstate(cancel_state, NULL);
98 	return (ret);
99 }
100