/* ====================================================================
 * Copyright (c) 1998 Ralf S. Engelschall. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by 
 *     Ralf S. Engelschall <rse@engelschall.com> for use in the
 *     mod_ssl project (http://www.engelschall.com/sw/mod_ssl/)."
 *
 * 4. The names "mod_ssl" must not be used to endorse or promote
 *    products derived from this software without prior written
 *    permission. For written permission, please contact
 *    rse@engelschall.com.
 *
 * 5. Products derived from this software may not be called "mod_ssl"
 *    nor may "mod_ssl" appear in their names without prior
 *    written permission of Ralf S. Engelschall.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by 
 *     Ralf S. Engelschall <rse@engelschall.com> for use in the
 *     mod_ssl project (http://www.engelschall.com/sw/mod_ssl/)."
 *
 * THIS SOFTWARE IS PROVIDED BY RALF S. ENGELSCHALL ``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 RALF S. ENGELSCHALL OR
 * HIS 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.
 * ====================================================================
 */


#include "mod_ssl.h"


/*  _________________________________________________________________
**
**  Support for Global Configuration
**  _________________________________________________________________
*/

void ssl_config_global_create(void)
{
    pool *pPool;

    if (ssl_ModConfig == NULL) {
        /* 
         * allocate an own subpool which survives server restarts
         */
        pPool = ap_make_sub_pool(NULL);
        ssl_ModConfig = (SSLModConfigRec *)ap_palloc(pPool, sizeof(SSLModConfigRec));
        ssl_ModConfig->pPool = pPool;

        /*
         * initialize per-module configuration
         */
        ssl_ModConfig->nInitCount             = 0;
        ssl_ModConfig->pRSATmpKey             = NULL;
        ssl_ModConfig->nSessionCacheMode      = SSL_SCMODE_UNSET;
        ssl_ModConfig->szSessionCacheDataFile = NULL;
        ssl_ModConfig->nMutexMode             = SSL_MUTEXMODE_UNSET;
        ssl_ModConfig->szMutexFile            = NULL;
        ssl_ModConfig->nMutexFD               = -1;
        ssl_ModConfig->nMutexSEMID            = -1;

        ssl_ModConfig->tPrivateKey            = ssl_ds_table_make(pPool, sizeof(RSA *));
        ssl_ModConfig->tPublicCert            = ssl_ds_table_make(pPool, sizeof(X509 *));

        ssl_ModConfig->rCtx.pConn             = NULL;
        ssl_ModConfig->rCtx.pServ             = NULL;
        ssl_ModConfig->rCtx.pPool             = NULL;
    }
    return;
}


/*  _________________________________________________________________
**
**  Configuration handling
**  _________________________________________________________________
*/

/*
 *  Create per-server SSL configuration
 */
void *ssl_config_server_create(pool *p, server_rec *s)
{
    SSLSrvConfigRec *rec;
    
    ssl_config_global_create();
    
    rec = ap_palloc(p, sizeof(SSLSrvConfigRec));
    rec->bEnabled               = UNSET;
    rec->szCertificateFile      = CFGDEF_CERTIFCATE_FILE;
    rec->szKeyFile              = NULL;
    rec->szCACertificatePath    = NULL;
    rec->szCACertificateFile    = NULL;
    rec->szCACertificateReqFile = NULL;
    rec->szLogFile              = NULL;
    rec->szCipherSuite          = NULL;
    rec->nLogLevel              = SSL_LOG_NONE;
    rec->nVerifyDepth           = 0;
    rec->nVerifyClient          = VERIFY_UNSET;
    rec->bFakeBasicAuth         = UNSET;
    rec->nSessionCacheTimeout   = CFGDEF_SESSION_CACHE_TIMEOUT;
    rec->nPassPhraseDialogType  = SSL_PPTYPE_UNSET;
    rec->szPassPhraseDialogPath = NULL;

    rec->fileLogFile            = NULL;
    rec->px509Certificate       = NULL;
    rec->prsaKey                = NULL;
    rec->pSSLCtx                = NULL;

    return rec;
}

/*
 *  Merge per-server SSL configurations
 */
void *ssl_config_server_merge(pool *p, void *basev, void *addv)
{
    SSLSrvConfigRec *base = (SSLSrvConfigRec *)basev;
    SSLSrvConfigRec *add  = (SSLSrvConfigRec *)addv;
    SSLSrvConfigRec *new  = (SSLSrvConfigRec *)ap_palloc(p, sizeof(SSLSrvConfigRec));

    cfgMergeBool(bEnabled);
    cfgMergeString(szCertificateFile);
    cfgMergeString(szKeyFile);
    cfgMergeString(szCACertificatePath);
    cfgMergeString(szCACertificateFile);
    cfgMergeString(szCACertificateReqFile);
    cfgMergeString(szLogFile);
    cfgMergeString(szCipherSuite);
    cfgMerge(nLogLevel, SSL_LOG_NONE);
    cfgMergeInt(nVerifyDepth);
    cfgMerge(nVerifyClient, VERIFY_UNSET);
    cfgMergeBool(bFakeBasicAuth);
    cfgMergeInt(nSessionCacheTimeout);
    cfgMerge(nPassPhraseDialogType, SSL_PPTYPE_UNSET);
    cfgMergeString(szPassPhraseDialogPath);

    cfgMerge(fileLogFile, NULL);
    cfgMerge(px509Certificate, NULL);
    cfgMerge(prsaKey, NULL);
    cfgMerge(pSSLCtx, NULL);

    return new;
}

/*
 *  Create per-directory SSL configuration
 */
void *ssl_config_perdir_create(pool *p, char *dummy)
{
    SSLDirConfigRec *rec = ap_palloc(p, sizeof(SSLDirConfigRec));

    rec->tbRequiredCiphers = ap_make_table(p, 4);
    rec->tbBannedCiphers   = ap_make_table(p, 4);
    rec->bSSLRequired      = FALSE;

    return rec;
}

/*
 *  Merge per-directory SSL configurations
 */
void *ssl_config_perdir_merge(pool *p, void *basev, void *addv)
{
    SSLDirConfigRec *base = (SSLDirConfigRec *)basev;
    SSLDirConfigRec *add  = (SSLDirConfigRec *)addv;
    SSLDirConfigRec *new  = (SSLDirConfigRec *)ap_palloc(p, 
                                               sizeof(SSLDirConfigRec));

    cfgMergeTable(tbRequiredCiphers);
    cfgMergeTable(tbBannedCiphers);
    cfgMerge(bSSLRequired, FALSE);

    return new;
}

/*
 *  Configuration functions for particular directives
 */

const char *ssl_cmd_SSLMutex(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    if (cmd->server->is_virtual)
        return "SSLMutex: Not allowed inside <VirtualHost> - "
               "Only configurable for main server";
    if (strcEQ(arg, "none")) {
        ssl_ModConfig->nMutexMode  = SSL_MUTEXMODE_NONE;
    }
    else if (strlen(arg) > 5 && strcEQn(arg, "file:", 5)) {
        ssl_ModConfig->nMutexMode  = SSL_MUTEXMODE_FILE;
        ssl_ModConfig->szMutexFile = ap_server_root_relative(cmd->pool, arg+5);
    }
    else if (strcEQ(arg, "ipcsem")) {
#ifdef SSL_CAN_USE_IPCSEM
        ssl_ModConfig->nMutexMode  = SSL_MUTEXMODE_IPCSEM;
#else
        return "SSLMutex: IPC Semaphores not available on this platform";
#endif
    }
    else
        return "SSLMutex: Invalid argument";
    return NULL;
}

const char *ssl_cmd_SSLPassPhraseDialog(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);

    if (cmd->server->is_virtual)
        return "SSLPassPhraseDialog: Not allowed inside <VirtualHost> - "
               "Only configurable for main server";

    if (strcEQ(arg, "builtin")) {
        pConfig->nPassPhraseDialogType  = SSL_PPTYPE_BUILTIN;
        pConfig->szPassPhraseDialogPath = NULL;
    }
    else if (strlen(arg) > 2 && arg[0] == '/') {
        pConfig->nPassPhraseDialogType  = SSL_PPTYPE_FILTER;
        pConfig->szPassPhraseDialogPath = ap_server_root_relative(cmd->pool, arg);
    }
    else 
        return "SSLPassPhraseDialog: Invalid argument";
    return NULL;
}

const char *ssl_cmd_SSLEngine(
    cmd_parms *cmd, char *struct_ptr, int flag)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);

    pConfig->bEnabled = (flag ? TRUE : FALSE);
    return NULL;
}

const char *ssl_cmd_SSLCipherSuite(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szCipherSuite = arg;
    return NULL;
}

const char *ssl_cmd_SSLCertificateFile(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szCertificateFile = arg;
    return NULL;
}

const char *ssl_cmd_SSLCertificateKeyFile(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szKeyFile = arg;
    return NULL;
}

const char *ssl_cmd_SSLCACertificatePath(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szCACertificatePath = arg;
    return NULL;
}

const char *ssl_cmd_SSLCACertificateFile(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szCACertificateFile = arg;
    return NULL;
}

const char *ssl_cmd_SSLCACertificateReqFile(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szCACertificateReqFile = arg;
    return NULL;
}

const char *ssl_cmd_SSLVerifyClient(
    cmd_parms *cmd, char *struct_ptr, char *level)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);

    if (strEQ(level, "0") || strcEQ(level, "none"))
        pConfig->nVerifyClient = VERIFY_NONE;
    else if (strEQ(level, "1") || strcEQ(level, "optional"))
        pConfig->nVerifyClient = VERIFY_OPTIONAL;
    else if (strEQ(level, "2") || strcEQ(level, "require"))
        pConfig->nVerifyClient = VERIFY_REQUIRE;
    else if (strEQ(level, "3") || strcEQ(level, "optional_no_ca"))
        pConfig->nVerifyClient = VERIFY_OPTIONAL_NO_CA;
    else
        return "SSLVerifyClient: Invalid argument";
    return NULL;
}

const char *ssl_cmd_SSLVerifyDepth(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->nVerifyDepth = atoi(arg);
    return NULL;
}

const char *ssl_cmd_SSLSessionCache(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    if (cmd->server->is_virtual)
        return "SSLSessionCache: Not allowed inside <VirtualHost> - "
               "Only configurable for main server";
    if (strcEQ(arg, "none")) {
        ssl_ModConfig->nSessionCacheMode      = SSL_SCMODE_NONE;
        ssl_ModConfig->szSessionCacheDataFile = NULL;
    }
    else if (strlen(arg) > 4 && strcEQn(arg, "dbm:", 4)) {
        ssl_ModConfig->nSessionCacheMode      = SSL_SCMODE_DBM;
        ssl_ModConfig->szSessionCacheDataFile = ap_server_root_relative(cmd->pool, arg+4);
    }
    else
        return "SSLSessionCache: Invalid argument";
    return NULL;
}

const char *ssl_cmd_SSLSessionCacheTimeout(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->nSessionCacheTimeout = atoi(arg);
    return NULL;
}

const char *ssl_cmd_SSLFakeBasicAuth(
    cmd_parms *cmd, char *struct_ptr)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->bFakeBasicAuth = TRUE;
    return NULL;
}

const char *ssl_cmd_SSLLog(
    cmd_parms *cmd, char *struct_ptr, char *arg)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);
    pConfig->szLogFile = arg;
    return NULL;
}

const char *ssl_cmd_SSLLogLevel(
    cmd_parms *cmd, char *struct_ptr, char *level)
{
    SSLSrvConfigRec *pConfig = mySrvConfig(cmd->server);

    if (strcEQ(level, "none"))
        pConfig->nLogLevel = SSL_LOG_NONE;
    else if (strcEQ(level, "error"))
        pConfig->nLogLevel = SSL_LOG_ERROR;
    else if (strcEQ(level, "warn"))
        pConfig->nLogLevel = SSL_LOG_WARN;
    else if (strcEQ(level, "info"))
        pConfig->nLogLevel = SSL_LOG_INFO;
    else if (strcEQ(level, "debug"))
        pConfig->nLogLevel = SSL_LOG_DEBUG;
    else
        return "SSLLogLevel: Invalid argument";
    return NULL;
}

const char *ssl_cmd_SSLRequireSSL(
    cmd_parms *cmd, SSLDirConfigRec *rec, char *cipher)
{
    rec->bSSLRequired = TRUE;
    return NULL;
}

const char *ssl_cmd_SSLRequireCipher(
    cmd_parms *cmd, SSLDirConfigRec *rec, char *cipher)
{
    ap_table_set(rec->tbRequiredCiphers, cipher, "Required");
    return NULL;
}

const char *ssl_cmd_SSLBanCipher(
    cmd_parms *cmd, SSLDirConfigRec *rec, char *cipher)
{
    ap_table_set(rec->tbBannedCiphers, cipher, "Banned");
    return NULL;
}

