November 1st, 2014

Random API of the Day

Today’s API is the traditional UNIX API login(3), which updates
the system utmp and wtmp databases so the sysadmin can figure out
who’s using the computer. On most systems, you use it something like this:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

/* Linux */
#include <sys/types.h>
#include <pwd.h>

/* BSD */
#include <utmp.h>
#include <libutil.h>

/* Mac OS X */
#include <util.h>

/* Solaris and IRIX */
#include <utmpx.h>

void log_user(void)
  struct utmp ut;

  memset(&ut, 0, sizeof(ut));

  if(geteuid() != 0) {
    fprintf(stderr, "You need to be root.\n");

  /* Here's how to fill out the structure on one OS */
  ut.ut_type = USER_PROCESS;
  ut.ut_pid = getpid();
  memcpy(ut.ut_line, ttyname(STDIN_FILENO), UT_LINESIZE - 1);
  memcpy(ut.ut_user, getpwuid(getuid())->pw_name, UT_NAMESIZE - 1);
  gethostname(ut.ut_host, UT_HOSTSIZE);
  gettimeofday(&ut.ut_tv, NULL);


On nearly all systems, login(3) just writes out some database
records to some log files, usually utmp and wtmp. It may surprise you
to know that any remote logging that’s provided by your system is done
by the login(1) program, not the login(3) API. In fact,
it’s possible to log in successfully without ever using login(3) if
your site uses another mechanism for accounting, such as a dedicated
WORM logger.

Leave a Response

Imhotep theme designed by Chris Lin. Proudly powered by Wordpress.
XHTML | CSS | RSS | Comments RSS