#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)ttyname.c 8.2 (Berkeley) 1/27/94";
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/lib/libc/gen/ttyname.c,v 1.16 2004/01/06 18:26:14 nectar Exp $");
#include "namespace.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <paths.h>
#include <pthread.h>
#include <errno.h>
#include "un-namespace.h"
#include "libc_private.h"
#ifndef BUILDING_VARIANT
static char buf[sizeof(_PATH_DEV) + MAXNAMLEN];
static char *ttyname_threaded(int fd);
static char *ttyname_unthreaded(int fd);
static pthread_mutex_t ttyname_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_key_t ttyname_key;
static int ttyname_init = 0;
char *
ttyname(int fd)
{
char *ret;
if (__isthreaded == 0)
ret = ttyname_unthreaded(fd);
else
ret = ttyname_threaded(fd);
return (ret);
}
#endif
#if __DARWIN_UNIX03
int
#else
char *
#endif
ttyname_r(int fd, char *thrbuf, size_t len)
{
struct stat sb;
#if __DARWIN_UNIX03
if (_fstat(fd, &sb) < 0)
return (EBADF);
if (!isatty(fd))
return (ENOTTY);
if (!S_ISCHR(sb.st_mode))
return (ENOTTY);
if (len <= sizeof(_PATH_DEV))
return (ERANGE);
#else
if (!isatty(fd))
return (NULL);
if (_fstat(fd, &sb))
return (NULL);
if (!S_ISCHR(sb.st_mode)) {
errno = ENOTTY;
return (NULL);
}
if (len <= sizeof(_PATH_DEV)) {
errno = ERANGE;
return (NULL);
}
#endif
strcpy(thrbuf, _PATH_DEV);
if (devname_r(sb.st_rdev, S_IFCHR,
thrbuf + strlen(thrbuf), len - strlen(thrbuf)) == NULL)
#if __DARWIN_UNIX03
return (ERANGE);
return (0);
#else
{
errno = ERANGE;
return (NULL);
}
return (thrbuf);
#endif
}
#ifndef BUILDING_VARIANT
static char *
ttyname_threaded(int fd)
{
char *buf;
if (ttyname_init == 0) {
_pthread_mutex_lock(&ttyname_lock);
if (ttyname_init == 0) {
ttyname_key = __LIBC_PTHREAD_KEY_TTYNAME;
if (pthread_key_init_np(ttyname_key, free)) {
int save = errno;
_pthread_mutex_unlock(&ttyname_lock);
errno = save;
return (NULL);
}
ttyname_init = 1;
}
_pthread_mutex_unlock(&ttyname_lock);
}
if ((buf = _pthread_getspecific(ttyname_key)) == NULL) {
if ((buf = malloc(sizeof(_PATH_DEV) + MAXNAMLEN)) != NULL) {
if (_pthread_setspecific(ttyname_key, buf) != 0) {
int save = errno;
free(buf);
errno = save;
return (NULL);
}
} else {
return (NULL);
}
}
#if __DARWIN_UNIX03
return (ttyname_r(fd, buf, sizeof(_PATH_DEV) + MAXNAMLEN) == 0 ? buf : NULL);
#else
return (ttyname_r(fd, buf, sizeof(_PATH_DEV) + MAXNAMLEN));
#endif
}
static char *
ttyname_unthreaded(int fd)
{
struct stat sb;
struct termios ttyb;
if (tcgetattr(fd, &ttyb) < 0)
return (NULL);
if (_fstat(fd, &sb))
return (NULL);
if (!S_ISCHR(sb.st_mode)) {
errno = ENOTTY;
return (NULL);
}
strcpy(buf, _PATH_DEV);
if (devname_r(sb.st_rdev, S_IFCHR,
buf + strlen(buf), sizeof(buf) - strlen(buf)) == NULL) {
errno = ERANGE;
return (NULL);
}
return (buf);
}
#endif