/*
**  L2 - OSSP Logging Library
**  Copyright (c) 2001 The OSSP Project (http://www.ossp.org/)
**  Copyright (c) 2001 Cable & Wireless Deutschland (http://www.cw.com/de/)
**
**  This file is part of OSSP L2, a flexible logging library which
**  can be found at http://www.ossp.org/pkg/l2/.
**
**  Permission to use, copy, modify, and distribute this software for
**  any purpose with or without fee is hereby granted, provided that
**  the above copyright notice and this permission notice appear in all
**  copies.
**
**  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
**  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
**  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
**  IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
**  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
**  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
**  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
**  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
**  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
**  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
**  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
**  SUCH DAMAGE.
**
**  l2_ch_smtp.c: SMTP channel implementation
*/

#include "l2.h"
#include "l2_p.h" /* for l2_version */

#include <unistd.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <pwd.h>
#include <time.h>

/* declare private channel configuration */
typedef struct {
    char *cpFrom;
    char *cpRcpt;
    char *cpSubject;
    char *cpHost;
    char *cpPort;
    char *cpLocalProg;
    char *cpLocalUser;
    char *cpLocalHost;
    long nTimeout; 
    sa_addr_t *saaServer;
    sa_t *saServer;
} l2_ch_smtp_t;

/* create channel */
static l2_result_t hook_create(l2_context_t *ctx, l2_channel_t *ch)
{
    l2_ch_smtp_t *cfg;
    struct utsname uts;
    struct passwd *pw;

    /* allocate private channel configuration */
    if ((cfg = (l2_ch_smtp_t *)malloc(sizeof(l2_ch_smtp_t))) == NULL)
        return L2_ERR_ARG;

    /* initialize configuration with reasonable defaults */
    cfg->cpLocalProg = NULL;
    if ((pw = getpwuid(getuid())) != NULL)
        cfg->cpLocalUser = strdup(pw->pw_name);
    else
        cfg->cpLocalUser = l2_util_asprintf("uid#%d", getuid());
    if (uname(&uts) == 0)
        cfg->cpLocalHost = strdup(uts.nodename);
    else
        cfg->cpLocalHost = strdup("localhost");
    cfg->cpFrom    = l2_util_asprintf("%s@%s", cfg->cpLocalUser, cfg->cpLocalHost);
    cfg->cpRcpt    = NULL;
    cfg->cpSubject = l2_util_asprintf("[L2] log channel output on %s", cfg->cpLocalHost);
    cfg->cpHost    = NULL;
    cfg->cpPort    = strdup("smtp");
    cfg->nTimeout  = 30;
    cfg->saaServer = NULL;
    cfg->saServer  = NULL;

    /* link private channel configuration into channel context */
    ctx->vp = cfg;

    return L2_OK;
}

/* configure channel */
static l2_result_t hook_configure(l2_context_t *ctx, l2_channel_t *ch, const char *fmt, va_list ap)
{
    l2_ch_smtp_t *cfg = (l2_ch_smtp_t *)ctx->vp;
    l2_param_t pa[10]; 
    l2_result_t rv;

    /* feed and call generic parameter parsing engine */
    L2_PARAM_SET(pa[0], progname,  STRING, &cfg->cpLocalProg);
    L2_PARAM_SET(pa[1], localhost, STRING, &cfg->cpLocalHost);
    L2_PARAM_SET(pa[2], localuser, STRING, &cfg->cpLocalUser);
    L2_PARAM_SET(pa[3], from,      STRING, &cfg->cpFrom);
    L2_PARAM_SET(pa[4], rcpt,      STRING, &cfg->cpRcpt);
    L2_PARAM_SET(pa[5], subject,   STRING, &cfg->cpSubject);
    L2_PARAM_SET(pa[6], host,      STRING, &cfg->cpHost);
    L2_PARAM_SET(pa[7], port,      STRING, &cfg->cpPort);
    L2_PARAM_SET(pa[8], timeout,   INT,    &cfg->nTimeout);
    L2_PARAM_END(pa[9]);
    rv = l2_util_setparams(pa, fmt, ap);

    return rv;
}

/* open channel */
static l2_result_t hook_open(l2_context_t *ctx, l2_channel_t *ch)
{
    l2_ch_smtp_t *cfg = (l2_ch_smtp_t *)ctx->vp;
    sa_rc_t rc;

    /* make sure a path was set */
    if (cfg->cpHost == NULL || cfg->cpRcpt == NULL)
        return L2_ERR_USE;

    /* create socket address */
    if ((rc = sa_addr_create(&cfg->saaServer)) != SA_OK)
        return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);
    if ((rc = sa_addr_u2a(cfg->saaServer, "inet://%s:%s", 
                          cfg->cpHost, cfg->cpPort)) != SA_OK)
        return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);

    /* create socket */
    if ((rc = sa_create(&cfg->saServer)) != SA_OK)
        return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);

    /* configure socket parameters */
    sa_timeout(cfg->saServer, SA_TIMEOUT_ALL, cfg->nTimeout, 0);
    sa_buffer(cfg->saServer, SA_BUFFER_READ, 4096);
    sa_buffer(cfg->saServer, SA_BUFFER_WRITE, 4096);

    return L2_OK;
}

/* write to channel */
static l2_result_t hook_write(l2_context_t *ctx, l2_channel_t *ch,
                              l2_level_t level, const char *buf, size_t buf_size)
{
    l2_ch_smtp_t *cfg = (l2_ch_smtp_t *)ctx->vp;
    char caLine[1024];
    sa_t *sa;
    sa_addr_t *saa;
    l2_result_t rv = L2_OK;
    sa_rc_t sa_rv;
    size_t n;
    const char *cpB;
    const char *cpE;
    const char *cpL;
    struct tm *tm;
    time_t t;
    char caDate[80];
    
    /* 
     * Sample SMTP transaction for reference:
     *
     * | 220 en1.engelschall.com ESMTP SMTP Sendmail 8.11.0+ ready
     * | HELO l2
     * | 250 en1.engelschall.com Hello en1.engelschall.com [141.1.129.1], pleased to meet you
     * | MAIL From: <l2@localhost>
     * | 250 2.1.0 <l2@localhost>... Sender ok
     * | RCPT To: <rse@engelschall.com>
     * | 250 2.1.5 <rse@engelschall.com>... Recipient ok
     * | DATA
     * | 354 Enter mail, end with "." on a line by itself
     * | Date: Fri, 14 Sep 2001 14:50:51 CEST
     * | From: rse@en1.engelschall.com
     * | To: rse@engelschall.com
     * | Subject: [L2] log channel output on en1.engelschall.com
     * | User-Agent: L2/0.1.0                                                                              
     * |
     * | A program of user rse on host en1.engelschall.com logged:
     * | [2001-09-10/01:02:03] <notice> sample logging message
     * | .
     * | 250 2.0.0 f88Aev847031 Message accepted for delivery
     * | QUIT
     * | 221 2.0.0 en1.engelschall.com closing connection
     *
     * For more details read:
     * RFC 2821: Simple Mail Transfer Protocol; J. Klensin; April 2001.
     * RFC 2822: Internet Message Format; P. Resnick; April 2001.
     */

    /* establish connection to server */
    saa = cfg->saaServer;
    sa  = cfg->saServer;
    if ((sa_rv = sa_connect(sa, saa)) != SA_OK)
        cu(sa_rv == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);

    /* | 220 en1.engelschall.com ESMTP SMTP Sendmail 8.11.0+ ready */
    sa_rv = sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 220), L2_ERR_IO);
    
    /* | HELO l2
     * | 250 en1.engelschall.com Hello en1.engelschall.com [141.1.129.1], pleased to meet you */
    sa_writef(sa, "HELO %s\r\n", cfg->cpLocalHost);
    sa_rv = sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 250), L2_ERR_IO);

    /* | MAIL From: <l2@localhost>
     * | 250 2.1.0 <l2@localhost>... Sender ok */
    sa_writef(sa, "MAIL FROM:<%s>\r\n", cfg->cpFrom);
    sa_rv = sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 250), L2_ERR_IO);

    /* | RCPT To: <rse@engelschall.com>
     * | 250 2.1.5 <rse@engelschall.com>... Recipient ok */
    sa_writef(sa, "RCPT TO:<%s>\r\n", cfg->cpRcpt);
    sa_rv = sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 250), L2_ERR_IO);

    /* | DATA
     * | 354 Enter mail, end with "." on a line by itself */
    sa_writef(sa, "DATA\r\n");
    sa_rv = sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 354), L2_ERR_IO);

    /* | Date: Fri, 14 Sep 2001 14:50:51 CEST
     * | From: rse@en1.engelschall.com
     * | To: rse@engelschall.com
     * | Subject: [L2] log channel output on en1.engelschall.com
     * | User-Agent: L2/0.1.0                                                                              
     * |                                                             */
    t = time(NULL);
    tm = localtime(&t);
    strftime(caDate, sizeof(caDate), "%a, %d %b %Y %H:%M:%S %Z", tm);
    sa_writef(sa, "Date: %s\r\n", caDate);
    sa_writef(sa, "From: %s\r\n", cfg->cpFrom);
    sa_writef(sa, "To: %s\r\n", cfg->cpRcpt);
    sa_writef(sa, "Subject: %s\r\n", cfg->cpSubject);
    if (cfg->cpLocalProg != NULL)
        sa_writef(sa, "User-Agent: %s (%s)\r\n", 
                  l2_version.v_web, cfg->cpLocalProg);
    else
        sa_writef(sa, "User-Agent: %s\r\n", l2_version.v_web);
    sa_write(sa, "\r\n", 2, NULL);

    /* | A program of user rse on host en1.engelschall.com logged:
     * | [2001-09-10/01:02:03] <notice> sample logging message      */
    if (cfg->cpLocalProg != NULL)
        sa_writef(sa, "Program %s of user %s on host %s logged:\r\n", 
                   cfg->cpLocalProg, cfg->cpLocalUser, cfg->cpLocalHost);
    else
        sa_writef(sa, "A program of user %s on host %s logged:\r\n", 
                   cfg->cpLocalUser, cfg->cpLocalHost);
    cpB = buf;
    cpE = buf;
    cpL = buf+buf_size;
    while (cpB < cpL) {
        for (cpE = cpB; cpE < cpL && (*cpE != '\r' && *cpE != '\n'); cpE++)
            ;
        if (*cpB == '.')
            sa_write(sa, ".", 1, NULL);
        sa_write(sa, cpB, cpE-cpB, NULL);
        sa_write(sa, "\r\n", 2, NULL);
        for (; cpE < cpL && (*cpE == '\r' || *cpE == '\n'); cpE++)
            ;
        cpB = cpE;
    }

    /* | .
     * | 250 2.0.0 f88Aev847031 Message accepted for delivery */
    sa_write(sa, ".\r\n", 3, NULL);
    sa_readln(sa, caLine, sizeof(caLine), &n);
    cu_on(!(sa_rv == SA_OK && n > 3 && atoi(caLine) == 250), L2_ERR_IO);

    /* | QUIT
     * | 221 2.0.0 en1.engelschall.com closing connection */
    sa_writef(sa, "QUIT\r\n");
    sa_readln(sa, caLine, sizeof(caLine), &n);

    cus:

    /* shutdown connection to server */
    sa_shutdown(sa, "rw");

    return rv;
}

/* close channel */
static l2_result_t hook_close(l2_context_t *ctx, l2_channel_t *ch)
{
    l2_ch_smtp_t *cfg = (l2_ch_smtp_t *)ctx->vp;

    /* destroy remote address */
    if (cfg->saServer != NULL) {
        sa_destroy(cfg->saServer);
        cfg->saServer = NULL;
    }
    if (cfg->saaServer != NULL) {
        sa_addr_destroy(cfg->saaServer);
        cfg->saaServer = NULL;
    }

    return L2_OK;
}

/* destroy channel */
static l2_result_t hook_destroy(l2_context_t *ctx, l2_channel_t *ch)
{
    l2_ch_smtp_t *cfg = (l2_ch_smtp_t *)ctx->vp;

    /* destroy channel configuration */
    if (cfg->cpFrom != NULL)
        free(cfg->cpFrom);
    if (cfg->cpRcpt != NULL)
        free(cfg->cpRcpt);
    if (cfg->cpSubject != NULL)
        free(cfg->cpSubject);
    if (cfg->cpHost != NULL)
        free(cfg->cpHost);
    if (cfg->cpPort != NULL)
        free(cfg->cpPort);
    if (cfg->cpLocalHost != NULL)
        free(cfg->cpLocalHost);
    if (cfg->cpLocalUser != NULL)
        free(cfg->cpLocalUser);
    free(cfg);

    return L2_OK;
}

/* exported channel handler structure */
l2_handler_t l2_handler_smtp = {
    L2_CHANNEL_OUTPUT,
    hook_create,
    hook_configure,
    hook_open,
    hook_write,
    NULL,
    hook_close,
    hook_destroy
};

