
/*
 *  Author: Arvin Schnell <arvin@suse.de>
 *
 *  This plugin let's you pass the password to the pppd via
 *  a file descriptor. That's easy and secure - no fiddling
 *  with pap- and chap-secrets files.
 */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include "pppd.h"
#include "msglib.h"

void plugin_init (void);

char pppd_version[] = VERSION;
int initialized = 0;

static int passfile[100];

static option_t options[] = {
    { "passfile", o_string, passfile,
      "Write password to this file descriptor" },
    { NULL }
};

static int oomapass_check (void)
{
    return 1;
}

static char *addr = "*";
static char  paddr[sizeof(struct wordlist) + 2];

static int oomapass_auth_hook (char *user, char *pass,
                               char **msgp,
                               struct wordlist **paddrs,
                               struct wordlist **popts)
{
    ooma_msg_err_t      ret;
    char *msg[3], user_tmp[50], pass_tmp[50];
    
    msg[0] = "type:cred";
    msg[1] = user_tmp;
    msg[2] = pass_tmp;

    if (!initialized) {
    	warn("Password authentication when uninitialized");
        plugin_init();
        return 0;
    }
        
    sprintf(msg[1], "user:%s", user);
    sprintf(msg[2], "passwd:%s", pass);
    	

    /*
     * The mtype value below should be set to a positive value,
     * otherwise the message send fails.
     */
    ret = ooma_msg_send("netmgr", 1, msg, 3);
    if (ret != OOMA_MSG_SUCCESS) {
        warn("Authentication failed %d %d", ret, errno);
        return 0;
    }


    *paddrs = (struct wordlist *) paddr;
    (*paddrs)->word = (char*)(*paddrs + 1);
    (*paddrs)->next = NULL;
    memcpy((*paddrs)->word, addr, strlen(addr) + 1);

    /*
     * If the message was sent always return success.
     */
    return 1;
}

void plugin_init (void)
{
    passfile[0] = '\0';
    add_options (options);

    pap_check_hook = oomapass_check;
    pap_auth_hook = oomapass_auth_hook;

    if (ooma_msg_init(NULL, NULL, NULL) != OOMA_MSG_SUCCESS) {
        return;
    }
    initialized = 1;
}
