/* location.c - find user's current location
 */

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <utmp.h>

#ifndef UT_HOSTSIZE
#define UT_HOSTSIZE 32
#define NO_UT_HOST
#endif				/* UT_HOSTSIZE */

#ifndef UT_LINESIZE
#define UT_LINESIZE 12
#endif				/* UT_LINESIZE */


/* Fill in "*ptr" with a pointer to a string containing the address that the
 * current user is logged in from.
 */
void hook_location(char **ptr)
{
	static char buf[1 + UT_HOSTSIZE];
	struct utmp *u;
	struct utmp ut;
	int unknown = 0;
	char *a;

	if (!ptr)
		return;

	a = ttyname(0);			    /* get stdin terminal name */
	if (!a)
		unknown = 1;		    /* oops - not a terminal */
	else if (strncmp(a, "/dev/", 5) != 0)
		unknown = 1;		    /* not /dev/??? */

	if (!unknown) {
		a += 5;
		setutent();
		strncpy(ut.ut_line, a, UT_LINESIZE);
		u = getutline(&ut);	    /* read entry from utmp */
		endutent();
		if (!u) {		    /* not found in utmp */
			unknown = 1;
		} else {
#ifdef NO_UT_HOST
			unknown = 1;	    /* TODO: use Solaris getutxline() */
#else				/* !NO_UT_HOST */
			strncpy(buf, u->ut_host, UT_HOSTSIZE);
#endif				/* NO_UT_HOST */
			buf[UT_HOSTSIZE] = 0;	/* copy location to static buffer */
			*ptr = buf;	    /* store pointer to buffer */
		}
	}

	if (!unknown)
		return;			    /* managed to get hostname - return */

	a = getenv("REMOTE_HOST");	    /* try reading from environment */
	if (!a)
		return;

	strncpy(buf, a, UT_HOSTSIZE);	    /* copy first few characters */
	buf[UT_HOSTSIZE] = 0;		    /* always terminate string */
	*ptr = buf;			    /* store pointer to buffer */
}

/* EOF */
