xref: /illumos-gate/usr/src/lib/libc/port/gen/ttyslot.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
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 /*
31  * Return the number of the slot in the utmp file
32  * corresponding to the current user: try for file 0, 1, 2.
33  * Returns -1 if slot not found.
34  */
35 
36 #include "lint.h"
37 #include <string.h>
38 #include <stdio.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <utmpx.h>
43 #include <stdlib.h>
44 #include <pthread.h>
45 
46 #ifndef TRUE
47 #define	TRUE 1
48 #define	FALSE 0
49 #endif
50 
51 int
52 ttyslot(void)
53 {
54 	struct futmpx ubuf;
55 	char *p;
56 	int s;
57 	int ret = -1;
58 	int console = FALSE;
59 	char ttynm[128];
60 	FILE *fp;
61 	int cancel_state;
62 
63 	/*
64 	 * The UNIX98 Posix conformance test suite requires
65 	 * ttyslot() to not be a cancellation point.
66 	 */
67 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
68 
69 	if ((p = ttyname_r(0, ttynm, 128)) != NULL ||
70 	    (p = ttyname_r(1, ttynm, 128)) != NULL ||
71 	    (p = ttyname_r(2, ttynm, 128)) != NULL) {
72 		if (strncmp(p, "/dev/", 5) == 0)
73 			p += 5;
74 		if (strcmp(p, "console") == 0)
75 			console = TRUE;
76 		s = 0;
77 		if ((fp = fopen(UTMPX_FILE, "rF")) != NULL) {
78 			while ((fread(&ubuf, sizeof (ubuf), 1, fp)) == 1) {
79 				if ((ubuf.ut_type == INIT_PROCESS ||
80 				    ubuf.ut_type == LOGIN_PROCESS ||
81 				    ubuf.ut_type == USER_PROCESS) &&
82 				    strncmp(p, ubuf.ut_line,
83 				    sizeof (ubuf.ut_line)) == 0) {
84 					ret = s;
85 					if (!console ||
86 					    strncmp(ubuf.ut_host, ":0", 2) == 0)
87 						break;
88 				}
89 				s++;
90 			}
91 			(void) fclose(fp);
92 		}
93 	}
94 
95 	(void) pthread_setcancelstate(cancel_state, NULL);
96 	return (ret);
97 }
98