/* Copyright 2005 The Apache Software Foundation or its licensors, as
 * applicable.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "apr_strings.h"
#include "apr_tables.h"
#include "httpd.h"
#include "http_log.h"
#include "util_filter.h"

#include "mod_smtpd.h"
#include "smtp.h"

SMTPD_DECLARE_NONSTD(void) smtpd_allow_command(smtpd_session_rec *scr,
                                               smtpd_command command)
{
    scr->allowed_commands |= 1 << command;
}

SMTPD_DECLARE_NONSTD(void) smtpd_disallow_command(smtpd_session_rec *scr,
                                                  smtpd_command command)
{
    scr->allowed_commands &= ~(1 << command);
}

SMTPD_DECLARE_NONSTD(smtpd_bool) smtpd_check_command(smtpd_session_rec *scr,
                                                     smtpd_command command)
{
    return (scr->allowed_commands & (1 << command))
      ? SMTPD_TRUE 
      : SMTPD_FALSE;
}

SMTPD_DECLARE_NONSTD(void) smtpd_disallow_all_commands(smtpd_session_rec
                                                       *scr)
{
    scr->allowed_commands = 0;
}

SMTPD_DECLARE_NONSTD(void) smtpd_allow_all_commands(smtpd_session_rec
                                                    *scr)
{
    scr->allowed_commands = ~0;
}

/* should be called at smtpd_hook_connect
 * at least by convention
 */
SMTPD_DECLARE_NONSTD(void) smtpd_register_extension(smtpd_session_rec *scr,
                                                    const char *line)
{
    (*((char **)apr_array_push(scr->extensions))) =
      apr_pstrdup(scr->p, line);
}

/* how to reset the envelope */
SMTPD_DECLARE_NONSTD(void) smtpd_reset_envelope(smtpd_session_rec *scr)
{
  /* REVIEW: don't know whether to run clear request first
   * then run reset hooks, or run reset hooks then clear request
   * depends on whether hooks want to save info before it gets cleared out
   * or if they want to overwrite default values in the request rec
   */
    smtpd_run_on_reset_envelope(scr);
    smtpd_clear_envelope_rec(scr);
}
#if 0
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#endif

SMTPD_DECLARE_NONSTD(apr_status_t)
smtpd_get_mailex(apr_pool_t *pool, /* out */ char **resolved_host,
                 char *original_host) 
{
#if 0
    /* res_search hack, too dependent */
    unsigned char buf[NS_PACKETSZ];
    ns_msg handle;
    ns_rr rr;
    int i, number_of_responses;
    int length;

    length = res_search(original_host, ns_c_in, ns_t_mx, buf, sizeof(buf));
    ns_initparse(buf, length, &handle);
    
    if (ns_msg_getflag(handle, ns_f_rcode) != ns_r_noerror) {
        return APR_EGENERAL;
    }

    /* get highest priority mail server */
    if (ns_parserr(&handle, ns_s_an, 0, &rr)) {
        return APR_EGENERAL;
    }

    number_of_responses = ns_msg_count(handle, ns_s_an);
    for (i = 1; i < number_of_responses; i++) {
        ns_rr rr_tent;

        if (ns_parserr(&handle, ns_s_an, i, &rr_tent)) {
            return APR_EGENERAL;
        }
        
        if (ns_rr_type(rr_tent) != ns_t_mx ||
            ns_rr_class(rr_tent) != ns_c_in) {
            continue;
        }
        
        if (ns_get16(ns_rr_rdata(rr_tent)) 
            < ns_get16(ns_rr_rdata(rr))) {
            rr = rr_tent;
        }
    }

    *resolved_host = apr_palloc(pool, MAXDNAME);

    ns_name_uncompress(ns_msg_base(handle),
                       ns_msg_end(handle),
                       ns_rr_rdata(rr) + 2,
                       *resolved_host,
                       MAXDNAME);
#endif
    *resolved_host = apr_pstrdup(pool, original_host);

    return APR_SUCCESS;
}

static int min(int a, int b) {
    return (a < b) ? a : b;
}

/* read and parse a line of response from the server, returning the response
 * code in *respcode and the response text in *resptext.  the line is placed
 * in buffer, which is buflen bytes long. */
static apr_status_t read_response(/* out */ int *respcode,
                                  /* out */ char **resptext,
                                  apr_bucket_brigade *bb,
                                  apr_bucket_brigade *tb,
                                  char *buffer,
                                  apr_size_t buflen)
{
    char *text;
    char buf[990];
    int advance;
    apr_status_t rv = APR_SUCCESS;
    apr_size_t nbytes;
    apr_size_t pos = 0;

    do {
        rv = apr_brigade_split_line(tb, bb, APR_BLOCK_READ, 990);
        if (rv)
            return rv;
        
        nbytes = 990;
        
        apr_brigade_flatten(tb, buf, &nbytes);
           
        apr_brigade_cleanup(tb);
        
        /* turn the number and extra to ' ' */
        *respcode = strtol(buf, &text, 10);

        advance = min(990 - pos, nbytes - (text + 1 - buf));
        memcpy(buffer + pos, text + 1, advance);
        pos += advance;
    } while (*text != ' ');

    buffer[pos] = '\0';
    *resptext = buffer;

    return rv;
}

SMTPD_DECLARE_NONSTD(apr_status_t)
smtpd_send_message(server_rec *server, apr_pool_t *subpool,
                   char *host, int smtp_port, char *mail_from,
                   apr_array_header_t *rcpts,
                   apr_bucket_brigade *body) {
    apr_status_t apr_err = APR_SUCCESS;
    const int line_buffer_size = 990;
    
    /* note: this is perhaps the stupidest SMTP client implementation
     *       ever, i appologize for it profusely, but it's the minimum
     *       we can get away with and still have this work. */
    do {
        apr_bucket_brigade *bb, *tb;
        char line[line_buffer_size];
        apr_sockaddr_t *saddr;
        apr_socket_t *sock;
        apr_size_t nbytes;
        char *text;
        int resp;
        int i;
        apr_bucket_alloc_t *bucket_alloc = apr_bucket_alloc_create(subpool);

        apr_err = apr_sockaddr_info_get(&saddr, host, APR_UNSPEC,
                                        smtp_port, 0, subpool);
        if (apr_err)
            break;

        /* open a connection to our target server. */
        apr_err = apr_socket_create(&sock, saddr->family, SOCK_STREAM, 0,
                                    subpool);
        if (apr_err)
            break;

        apr_err = apr_socket_connect(sock, saddr);
        if (apr_err)
            break;

        /* wrap a bucket brigade around our socket so we can easily read
         * a line at a time from it. */
        bb = apr_brigade_create(subpool, bucket_alloc);

        APR_BRIGADE_INSERT_TAIL(
            bb, apr_bucket_socket_create(sock, bucket_alloc)
        );

        tb = apr_brigade_create(subpool, bucket_alloc);

        apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
        if (apr_err)
            break;

        if (resp != 220) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "bad response from smtp server: "
                         "got %d, expected 220", resp);

            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "server said '%s'", text);
            break;
        }

        /* say hello to the server. */
        {
          struct iovec vec[3];

          vec[0].iov_base = "HELO ";
          vec[0].iov_len = 5;

          vec[1].iov_base = server->server_hostname;
          vec[1].iov_len = strlen(server->server_hostname);

          vec[2].iov_base = "\r\n";
          vec[2].iov_len = 2;

          apr_err = apr_socket_sendv(sock, vec, 3, &nbytes);
          if (apr_err)
              break;
        }

        apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
        if (apr_err)
            break;

        if (resp != 250) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "bad response from smtp server: "
                         "got %d, expected 250", resp);
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "server said '%s'", text);
            break;
        }

        /* identify the sender. */
        {
            struct iovec vec[3];

            vec[0].iov_base = "MAIL FROM:<";
            vec[0].iov_len = 11;

            vec[1].iov_base = mail_from;
            vec[1].iov_len = strlen(mail_from);

            vec[2].iov_base = ">\r\n";
            vec[2].iov_len = 3;

            apr_err = apr_socket_sendv(sock, vec, 3, &nbytes);
            if (apr_err)
                break;
        }

        apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
        if (apr_err)
            break;

        if (resp != 250) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "bad response from smtp server: "
                         "got %d, expected 250", resp);
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "server said '%s'", text);
            break;
        }

        /* tell the server who we're sending the message to. */
        for (i = 0; i < rcpts->nelts; ++i) {
            struct iovec vec[3];

            char *to = APR_ARRAY_IDX(rcpts, i, char *);

            vec[0].iov_base = "RCPT TO:<";
            vec[0].iov_len = 9;

            vec[1].iov_base = to;
            vec[1].iov_len = strlen(to);

            vec[2].iov_base = ">\r\n";
            vec[2].iov_len = 3;

            apr_err = apr_socket_sendv(sock, vec, 3, &nbytes);
            if (apr_err)
                break;

            apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
            if (apr_err)
                break;

            if (resp != 250 && resp != 251) {
                ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                             "bad response from smtp server: "
                             "got %d, expected 250 or 251", resp);

                ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                             "server said '%s'", text);

                apr_err = APR_EINVAL;

                break;
            }
        }

        /* if we ended up with an error from the loop bail. */
        if (apr_err)
            break;

        /* now start the actual contents of the message. */

        nbytes = 6;

        apr_err = apr_socket_send(sock, "DATA\r\n", &nbytes);
        if (apr_err)
            break;

        apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
        if (apr_err)
            break;

        if (resp != 354) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "bad response from smtp server: "
                         "got %d, expected 354", resp);

            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "server said '%s'", text);
            break;
        }

        /* send body */

        /* loop over the lines in the file, writing them to the socket and
         * dealing with single-period lines as we see them. */
        for (;;) {
            if (APR_BRIGADE_EMPTY(body))
                break;

            memset(line, 0, sizeof(line));

            apr_err = apr_brigade_split_line(tb, body, APR_BLOCK_READ,
                                             sizeof(line));
            if (apr_err)
                break;

            nbytes = sizeof(line);

            apr_brigade_flatten(tb, line, &nbytes);

            if (line[0] == '.' && line[1] == '\0') {
                nbytes = 2;

                apr_err = apr_socket_send(sock, "..", &nbytes);
            } else {
                nbytes = strlen(line);

                apr_err = apr_socket_send(sock, line, &nbytes);
            }

            if (apr_err)
                break;

            apr_brigade_cleanup(tb);
        }

        apr_brigade_destroy(tb);

        /* now finish things off with a single period. */
        if (!apr_err) {
            nbytes = 3;
            apr_err = apr_socket_send(sock, ".\r\n", &nbytes);
        }

        apr_err = read_response(&resp, &text, bb, tb, line, sizeof(line));
        if (apr_err)
            break;

        if (resp != 250) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "bad response from smtp server: "
                         "got %d, expected 250", resp);

            ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
                         "server said '%s'", text);
            break;
        }
    } while (0);

    if (apr_err)
        ap_log_error(APLOG_MARK, APLOG_ERR, apr_err, server,
                     "Error queuing to smtp server");

    return apr_err;
}

SMTPD_DECLARE_NONSTD(apr_status_t) smtpd_getline(smtpd_session_rec *scr,
                                                 char *data, apr_size_t dlen,
                                                 apr_size_t *outlen)
{
    apr_status_t rc;
    apr_bucket *e;
    const char *str;
    char *pos, *last_char = data;
    apr_size_t len, bytes_handled = 0;
    int saw_eos = 0;
    ap_filter_t *input_filters = scr->c->input_filters;

    while (!saw_eos) {
        apr_brigade_cleanup(scr->bb_in);
        rc = ap_get_brigade(input_filters, scr->bb_in, AP_MODE_GETLINE,
                            APR_BLOCK_READ, 0);
        if (rc != APR_SUCCESS)
            return rc;
        
        while(!APR_BRIGADE_EMPTY(scr->bb_in)) {
            e = APR_BRIGADE_FIRST(scr->bb_in);

            /* If we see an EOS, don't bother doing anything more. */
            if (APR_BUCKET_IS_EOS(e)) {
                saw_eos = 1;
                break;
            }

            rc = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
            if (rc != APR_SUCCESS)
                return rc;      

            apr_bucket_delete(e);
            
            if (len == 0)
                continue;
            
            /* Would this overrun our buffer?  If so, we'll die. */
            if (dlen < bytes_handled + len) {
                if (data) {
                    /* ensure this string is NUL terminated */
                    if (bytes_handled > 0) {
                        data[bytes_handled-1] = '\0';
                    }
                    else {
                        data[0] = '\0';
                    }
                }
                return APR_ENOSPC;
            }
            
            /* Just copy the rest of the data to the end of the old buffer. */
            pos = data + bytes_handled;
            memcpy(pos, str, len);
            last_char = pos + len - 1;
            
            /* We've now processed that new data - update accordingly. */
            bytes_handled += len;

        }
        
        /* If we got a full line of input, stop reading */
        if (last_char && (*last_char == APR_ASCII_LF)) {
            break;
        }
    }
    
    /* Now NUL-terminate the string at the end of the line; 
     * if the last-but-one character is a CR, terminate there */
    if (last_char > data && last_char[-1] == APR_ASCII_CR) {
        last_char--;
    }
    
    *last_char = '\0';
    if (outlen)
        *outlen = last_char - data;
    return APR_SUCCESS;
}

SMTPD_DECLARE_NONSTD(apr_status_t) smtpd_respond_multiline(smtpd_session_rec *scr,
                                                           int code,
                                                           apr_array_header_t
                                                           *msgs)
{
    int i;
    
    for (i = 0; i < msgs->nelts - 1; i++) {
        ap_fprintf(scr->c->output_filters, scr->bb_out, "%d-%s\r\n", code,
                   ((char **)msgs->elts)[i]);
        ap_fflush(scr->c->output_filters, scr->bb_out);
    }
    
    ap_fprintf(scr->c->output_filters, scr->bb_out, "%d %s\r\n", code,
               ((char **)msgs->elts)[i]);
    ap_fflush(scr->c->output_filters, scr->bb_out);
    
    return APR_SUCCESS;
}

SMTPD_DECLARE_NONSTD(apr_status_t) smtpd_respond_oneline(smtpd_session_rec *scr,
                                                         int code,
                                                         char *message)
{
    ap_fprintf(scr->c->output_filters, scr->bb_out, "%d %s\r\n", code,
               message);
    ap_fflush(scr->c->output_filters, scr->bb_out);
    
    return APR_SUCCESS;
}

#define INSERT_BEFORE(f, before_this) ((before_this) == NULL \
                           || (before_this)->frec->ftype >= (f)->frec->ftype \
                           || (before_this)->r != (f)->r)
SMTPD_DECLARE_NONSTD(ap_filter_t *)
     smtpd_add_input_filter_handle(ap_filter_rec_t *frec, void *ctx, 
                                   smtpd_session_rec *scr)
{
    smtpd_envelope_rec *str = scr->envelope;
    ap_filter_t *f = apr_palloc(str->p, sizeof(*f));
    ap_filter_t **outf;

    outf = &(str->input_filters);

    f->frec = frec;
    f->ctx = ctx;
    f->c = scr->c;
    f->next = NULL;

    if (INSERT_BEFORE(f, *outf)) {
        f->next = *outf;
        *outf = f;
    }
    else {
        ap_filter_t *fscan = *outf;
        while (!INSERT_BEFORE(f, fscan->next))
            fscan = fscan->next;

        f->next = fscan->next;
	fscan->next = f;
    }

    return f;
}
