#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <unistd.h>

#include "httpd.h"
#include "http_config.h"
#include "http_log.h"
#include "apr_strings.h"

#include "mod_smtpd.h"

module AP_MODULE_DECLARE_DATA smtpd_queue_postfix_module;

typedef enum {
    REC_TYPE_SIZE = 'C',    /* first record, created by cleanup */
    REC_TYPE_TIME = 'T',    /* time stamp, required */
    REC_TYPE_FULL = 'F',    /* full name, optional */
    REC_TYPE_INSP = 'I',    /* inspector transport */
    REC_TYPE_FILT = 'L',    /* loop filter transport */
    REC_TYPE_FROM = 'S',    /* sender, required */ 
    REC_TYPE_DONE = 'D',    /* delivered recipient, optional */
    REC_TYPE_RCPT = 'R',    /* todo recipient, optional */
    REC_TYPE_ORCP = 'O',    /* original recipient, optional */
    REC_TYPE_WARN = 'W',    /* warning message time */ 
    REC_TYPE_ATTR = 'A',    /* named attribute for extensions */
    REC_TYPE_MESG = 'M',    /* start message records */
    REC_TYPE_CONT = 'L',    /* long data record */
    REC_TYPE_NORM = 'N',    /* normal data record */
    REC_TYPE_XTRA = 'X',    /* start extracted records */
    REC_TYPE_RRTO = 'r',    /* return-receipt, from headers */
    REC_TYPE_ERTO = 'e',    /* errors-to, from headers */
    REC_TYPE_PRIO = 'P',    /* priority */
    REC_TYPE_VERP = 'V',    /* VERP delimiters */
    REC_TYPE_END  = 'E',    /* terminator, required */
} smtpd_postfix_printrec_t;

typedef struct {
    const char *cleanup_path;
    int on; 
} smtpd_queue_postfix_config;

/* XXX: Currently this function is Mac OS X specific,
   it may work on other Unices, especially the BSDs
   but does not currently succeed on Linux */
static int open_cleanup(const char *cleanup_path)
{
    struct sockaddr_un cleanup_sockaddr;
    int fd, rv;
    
    rv = socket(AF_UNIX, SOCK_STREAM, 0);
    if (rv < 0)
        return rv;
 
    fd = rv;

    memset(&cleanup_sockaddr, 0, sizeof(cleanup_sockaddr));
    cleanup_sockaddr.sun_family = AF_UNIX;
    apr_cpystrn(cleanup_sockaddr.sun_path, cleanup_path,
                sizeof(cleanup_sockaddr.sun_path));
    cleanup_sockaddr.sun_len = sizeof(cleanup_sockaddr) +
      - sizeof(cleanup_sockaddr.sun_path) + strlen(cleanup_path) + 1;
    
    rv = connect(fd, (struct sockaddr *) &cleanup_sockaddr,
                 cleanup_sockaddr.sun_len);
    if (rv < 0)
        return rv;

    return fd;
}

static void close_cleanup(int fd)
{
    close(fd);
}

static void print_rec(int fd, smtpd_postfix_printrec_t type,
                      void *data, int len)
{
    char stack_buf[1024];
    int i;
    
    stack_buf[0] = type;
    /* send message type */
    write(fd, stack_buf, 1);

    /* data len is a little-endian base 128 number
     * where each byte except the last has the high bit set
     */
    for (i = 0; len >= 0x80; len >>= 7, ++i) {
        stack_buf[i] = (len & 0x7F) | 0x80;
    }
    stack_buf[i++] = len;
    write(fd, stack_buf, i);
    
    /* write data */
    write(fd, data, len);
}

static void print_msg_line(int fd, char *line)
{
    char *newline_loc = strchr(line, '\n');
    
    if (newline_loc) {
        if (newline_loc[-1] == '\r')
            newline_loc--;

        print_rec(fd, REC_TYPE_NORM, line, newline_loc - line);
    } else {
        print_rec(fd, REC_TYPE_NORM, line, strlen(line));
    }
}

static void print_rec_time(int fd, apr_time_t record)
{
    char stack_buf[1024];
    int num_printed = apr_snprintf(stack_buf, 1024, "%" APR_TIME_T_FMT,
                                   apr_time_sec(record));
    print_rec(fd, REC_TYPE_TIME, stack_buf, num_printed);
}

static int get_attr_el(int fd, char *buf, int len)
{
    int i;

    for (i = 0; i < len-1; i++) {
        read(fd, buf + i, 1);
        if (buf[i] == '\0') 
            break;
    }
    buf[i] = '\0';
    return i;
}

static void get_attr(int fd, apr_hash_t *kv, apr_pool_t *p)
{
    char stack_buf[1024];
    char *key;
    char *val;

    while(1) {
        if (!get_attr_el(fd, stack_buf, 1024))
            break;

        key = apr_pstrdup(p, stack_buf);

        get_attr_el(fd, stack_buf, 1024);
        val = apr_pstrdup(p, stack_buf);

        apr_hash_set(kv, key, APR_HASH_KEY_STRING, val);
    }
}

static int write_out_headers(void *fd, const char *key,
                             const char *val)
{
    char stack_buf[1024];
    sprintf(stack_buf, "%s: %s", key, val);
    print_msg_line((int)fd, stack_buf);

    return 1;
}

smtpd_retcode postfix_queue(smtpd_conn_rec *scr, smtpd_return_data *out)
{
    smtpd_trans_rec *str = scr->transaction;
    apr_hash_t *first_attr = apr_hash_make(str->p);
    apr_hash_t *last_attr = apr_hash_make(str->p);
    char stack_buf[1024];
    char *status, *reason, *qid;
    const char *msg_id;
    int status_int;
    int i;
    int cleanup_socket;
    smtpd_queue_postfix_config *cfg =
      ap_get_module_config(scr->s->module_config,
                           &smtpd_queue_postfix_module);

    if (!cfg->on)
        return SMTPD_DECLINED;

    cleanup_socket = open_cleanup(cfg->cleanup_path);
    if (cleanup_socket < 0) {
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, scr->s,
                     "mod_smtpd_queue_postfix: "
                     "Could not make unix domain connection to: %s",
                     cfg->cleanup_path);
        return SMTPD_DECLINED;
    }

    /* get attributes */
    get_attr(cleanup_socket, first_attr, str->p);
    qid = apr_hash_get(first_attr, "queue_id", APR_HASH_KEY_STRING);

    /* log queue id?
     * print STDERR "qid=$qid\n"
     */

    /* send out attributes */
    write(cleanup_socket, "flags", sizeof("flags"));
    write(cleanup_socket, "0000", sizeof("0000"));
    write(cleanup_socket, "", sizeof(""));

    /* send time */
    print_rec_time(cleanup_socket, apr_time_now());
    
    /* send sender and receiver */
    print_rec(cleanup_socket, REC_TYPE_FROM, str->mail_from,
              strlen(str->mail_from));
    for (i = 0; i < str->rcpt_to->nelts; ++i) {
        print_rec(cleanup_socket, REC_TYPE_RCPT,
                  ((char **)str->rcpt_to->elts)[i],
                  strlen(((char **)str->rcpt_to->elts)[i]));
    }

    /* add an empty message length record.
     * cleanup is supposed to understand that.
     * see src/pickup/pickup.c 
     */
    print_rec(cleanup_socket, REC_TYPE_MESG, "", 0);
    
    apr_table_do(write_out_headers, (void *) cleanup_socket,
                 str->headers, NULL);

    smtpd_body_resetpos(str, SMTPD_BODY);
    while (smtpd_body_getline(str, stack_buf, 1024) == APR_SUCCESS) {
        print_msg_line(cleanup_socket, stack_buf);
    }

    /* finish it. */
    print_rec(cleanup_socket, REC_TYPE_XTRA, "", 0);
    print_rec(cleanup_socket, REC_TYPE_END, "", 0);
    get_attr(cleanup_socket, last_attr, str->p);
    
    status = apr_hash_get(last_attr, "status", APR_HASH_KEY_STRING);
    reason = apr_hash_get(last_attr, "reason", APR_HASH_KEY_STRING);
    status_int = atoi(status);

    close_cleanup(cleanup_socket);

    out->msgs = apr_array_make(out->p, 1, sizeof(char *));

    if (status_int) {
        *((char **)apr_array_push(out->msgs)) =
          apr_psprintf(out->p, "Unable to queue message (%s, %s",
                       status, reason);
        return SMTPD_DECLINED;
    }
    
    msg_id = apr_table_get(str->headers, "Message-Id");
    *((char **)apr_array_push(out->msgs)) =
      apr_psprintf(out->p, "Queued! %s (Queue-Id: %s)",
                   msg_id ? msg_id : "", qid);

    return SMTPD_OK;
}

/* registers httpd hooks */
static void register_hooks(apr_pool_t *p)
{
    APR_OPTIONAL_HOOK(smtpd, queue, postfix_queue, NULL, NULL, APR_HOOK_MIDDLE);
}

static void *smtpd_queue_postfix_create_server_config(apr_pool_t *p,
                                                   server_rec *s)
{
  smtpd_queue_postfix_config *cfg = 
    apr_pcalloc(p, sizeof(smtpd_queue_postfix_config));
  cfg->on = 0;
  cfg->cleanup_path = "/var/spool/postfix/public/cleanup";
  return cfg;
}

static const char *enable_queue_postfix(cmd_parms *cmd,
                                        void *baton,
                                        int arg)
{
    smtpd_queue_postfix_config *cfg = ap_get_module_config(
        cmd->server->module_config, &smtpd_queue_postfix_module
    );

    cfg->on = arg;

    return NULL;
}

static const char *set_cleanup_path(cmd_parms *cmd,
                                    void *baton,
                                    const char *arg)
{
    smtpd_queue_postfix_config *cfg =
      ap_get_module_config(cmd->server->module_config,
                           &smtpd_queue_postfix_module);
    cfg->cleanup_path = arg;

    return NULL;
}

static const command_rec smtpd_queue_postfix_cmds[] = {
    AP_INIT_FLAG("SmtpQueuePostfix", enable_queue_postfix, NULL, RSRC_CONF,
                 "Enable queuing to a local postfix server.  Default: Off"),
    AP_INIT_TAKE1("SmtpQueuePostfixCleanupPath", set_cleanup_path, NULL, RSRC_CONF,
                  "Set the path of the unix cleanup socket. "
                  "Default: /var/spool/postfix/public/cleanup"),
    { NULL }
};

module AP_MODULE_DECLARE_DATA smtpd_queue_postfix_module = {
  STANDARD20_MODULE_STUFF,
  NULL,                       /* create per-directory config structure */
  NULL,                       /* merge per-directory config structures */
  smtpd_queue_postfix_create_server_config,
  NULL,                       /* merge per-server config structures */
  smtpd_queue_postfix_cmds,
  register_hooks              /* register hooks */
};
