#include <unistd.h>
#include <syslog.h>

#define LOGIN "/usr/bin/login"
#define STDERR STDERR_FILENO

main(int argc, char *argv[]) {
    int i;
    size_t buflen;
    char *args[4];
    char *client;
    char *hbuf, *argbuf;

    openlog(NULL, LOG_PID, LOG_AUTH);
    client = (char *)getenv("SSH_CLIENT");

    if ( client ) {
        strtok(client, " ");
    } else {
        client = "<UNKNOWN>";
    }

    syslog(LOG_NOTICE, "login attempt from %s", client);

    for ( i = 0 , buflen = 0 ; i < argc ; i++ ) {
        buflen += strlen((char *)argv[i]) + 1;
    }

    if ( ! ( argbuf = (void *) malloc(buflen) ) ) {
        perror("Could not allocate memory for argument log");
    }

    for ( i = 0 ; (i < argc) && strcat(argbuf, " ") ; i++ ) {
        strcat(argbuf, argv[i]);
    }
    
    syslog(LOG_DEBUG, "called with arguments:%s", argbuf);

    if ( argc > 1 ) {
        syslog(LOG_DEBUG,"%s called with too many arguments", argv[0]);
        closelog();
        exit(1);
    }

    if ( ! ( hbuf = (void *) malloc(strlen(client) + 4) ) ) {
        perror("Could not allocate memory");
        exit(1);
    }
    snprintf(hbuf, strlen(client) + 4, "-h %s", client);

    args[0] = "skeylogin";
    args[1] = "-s";
    args[2] = hbuf;
    args[3] = NULL;

    closelog();

    seteuid(0); setuid(0);

    if ( execve(LOGIN, args, NULL) )
        perror("Could not exec login");
    exit(1);
}
