/*
 * $Id: wtmp-gate.c,v 1.1 1998/11/25 12:33:32 saw Rel $
 */

#include <utmp.h>

#include <security/pam_appl.h>

#include "../../common/include/wtmp.h"
#include "../include/wtmp-gate.h"

/*
 * Returns:
 *   0     ok,
 *   1     non-fatal error
 *  -1     fatal error
 *  callname and err_descr will be set
 * Be carefull: the function indirectly uses alarm().
 */
int utmp_open_session(pam_handle_t *pamh, pid_t pid
                             , const char **callname, const char **err_descr)
{
    const char *user, *terminal, *rhost;
    int retval;

    retval = pam_get_item(pamh, PAM_USER, (const void **)&user);
    if (retval != PAM_SUCCESS) {
        *callname = "pam_get_item(PAM_USER)";
        *err_descr = pam_strerror(pamh, retval);
        return -1;
    }
    retval = pam_get_item(pamh, PAM_TTY, (const void **)&terminal);
    if (retval != PAM_SUCCESS) {
        *callname = "pam_get_item(PAM_TTY)";
        *err_descr = pam_strerror(pamh, retval);
        return -1;
    }
    retval = pam_get_item(pamh, PAM_RHOST, (const void **)&rhost);
    if (retval != PAM_SUCCESS)
        rhost = NULL;

    return
        utmp_do_open_session(user, terminal, rhost, pid, callname, err_descr);
}

int utmp_close_session(pam_handle_t *pamh
                              , const char **callname, const char **err_descr)
{
    int retval;
    const char *terminal;

    retval = pam_get_item(pamh, PAM_TTY, (const void **)&terminal);
    if (retval != PAM_SUCCESS) {
        *callname = "pam_get_item(PAM_TTY)";
        *err_descr = pam_strerror(pamh, retval);
        return -1;
    }

    return
        utmp_do_close_session(terminal, callname, err_descr);
}
