/*
**  OSSP l2 - Flexible Logging
**  Copyright (c) 2001-2003 Cable & Wireless Deutschland GmbH
**  Copyright (c) 2001-2003 The OSSP Project (http://www.ossp.org/)
**  Copyright (c) 2001-2003 Ralf S. Engelschall <rse@engelschall.com>
**
**  This file is part of OSSP l2, a flexible logging library which
**  can be found at http://www.ossp.org/pkg/lib/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_socket.c: socket channel implementation
*/

#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "l2.h"
#include "l2_p.h"

/* declare private channel configuration */
typedef struct {
    char      *szProto;
    char      *szHost;
    char      *szPort;
    long       nTimeout;
    sa_addr_t *saaRemote;
    sa_t      *saRemote;
} l2_ch_socket_t;

/* create channel */
static l2_result_t hook_create(l2_context_t *ctx, l2_channel_t *ch)
{
    l2_ch_socket_t *cfg = NULL;

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

    /* initialize configuration with reasonable defaults */
    cfg->szProto   = strdup("tcp");
    cfg->szHost    = NULL;
    cfg->szPort    = NULL;
    cfg->nTimeout  = 30;
    cfg->saaRemote = NULL;
    cfg->saRemote  = 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_socket_t *cfg = (l2_ch_socket_t *)ctx->vp;
    l2_param_t pa[5];
    l2_result_t rv;
    l2_env_t *env;

    /* feed and call generic parameter parsing engine */
    L2_PARAM_SET(pa[0], proto,   STR, &cfg->szProto);
    L2_PARAM_SET(pa[1], host,    STR, &cfg->szHost);
    L2_PARAM_SET(pa[2], port,    STR, &cfg->szPort);
    L2_PARAM_SET(pa[3], timeout, INT, &cfg->nTimeout);
    L2_PARAM_END(pa[4]);
    l2_channel_env(ch, &env);
    rv = l2_util_setparams(env, pa, fmt, ap);

    /* sanity check configuration parameters */
    if (   cfg->szProto != NULL
        && !(   strcmp(cfg->szProto, "udp") == 0
             || strcmp(cfg->szProto, "tcp") == 0))
        return L2_ERR_ARG;

    return rv;
}

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

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

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

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

    /* configure socket parameters */
    sa_timeout(cfg->saRemote, SA_TIMEOUT_ALL, cfg->nTimeout, 0);
    if (strcmp(cfg->szProto, "tcp") == 0) {
        sa_buffer(cfg->saRemote, SA_BUFFER_READ,  4096);
        sa_buffer(cfg->saRemote, 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_socket_t *cfg = (l2_ch_socket_t *)ctx->vp;
    size_t sizeWrite;
    size_t sizeRemain;
    sa_rc_t rc;

    /* establish connection to server (TCP only) */
    if (strcmp(cfg->szProto, "tcp") == 0) {
        if ((rc = sa_connect(cfg->saRemote, cfg->saaRemote)) != SA_OK)
            return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);
    }

    /* write message to channel socket, but check to make
       sure that the whole message was successfully written */
    sizeWrite  = 0;
    sizeRemain = buf_size;
    while (sizeRemain > 0) {
        if (strcmp(cfg->szProto, "tcp") == 0)
            rc = sa_write(cfg->saRemote, buf, sizeRemain, &sizeWrite);
        else
            rc = sa_send(cfg->saRemote, cfg->saaRemote, buf, sizeRemain, &sizeWrite);
        if (rc != SA_OK)
            return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);
        sizeRemain = sizeRemain - sizeWrite; /* how much is left? */
    }

    /* shutdown connection to server (TCP only) */
    if (strcmp(cfg->szProto, "tcp") == 0) {
        if ((rc = sa_shutdown(cfg->saRemote, "rw")) != SA_OK)
            return (rc == SA_ERR_SYS ? L2_ERR_SYS : L2_ERR_INT);
    }

    return L2_OK;
}

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

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

    return L2_OK;
}

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

    /* destroy channel configuration */
    if (cfg->szProto != NULL)
        free(cfg->szProto);
    if (cfg->szHost != NULL)
        free(cfg->szHost);
    if (cfg->szPort != NULL)
        free(cfg->szPort);
    free(cfg);

    return L2_OK;
}

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

