/* ====================================================================
 * 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"


/*  _________________________________________________________________
**
**  Mutex Support (Common)
**  _________________________________________________________________
*/

#define MUTEX_LOCK_MODE ( S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH )

void ssl_mutex_init(server_rec *s, pool *p)
{
    if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_FILE) {
        ssl_mutex_file_create(s, p);
        ap_register_cleanup(p, (void *)s, ssl_mutex_file_remove, ap_null_cleanup);
    }
    else if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_IPCSEM) {
        ssl_mutex_ipcsem_create(s, p);
        ap_register_cleanup(p, (void *)s, ssl_mutex_ipcsem_remove, ap_null_cleanup);
    }
    return;
}

void ssl_mutex_open(server_rec *s, pool *p)
{
    if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_FILE)
        ssl_mutex_file_open(s, p);
    else if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_IPCSEM)
        ssl_mutex_ipcsem_open(s, p);
    return;
}

void ssl_mutex_on(void)
{
    if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_FILE)
        ssl_mutex_file_acquire();
    else if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_IPCSEM)
        ssl_mutex_ipcsem_acquire();
    return;
}

void ssl_mutex_off(void)
{
    if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_FILE)
        ssl_mutex_file_release();
    else if (ssl_ModConfig->nMutexMode == SSL_MUTEXMODE_IPCSEM)
        ssl_mutex_ipcsem_release();
    return;
}


/*  _________________________________________________________________
**
**  Mutex Support (Lockfile)
**  _________________________________________________________________
*/

void ssl_mutex_file_create(server_rec *s, pool *p)
{
    /* create the lockfile */
    unlink(ssl_ModConfig->szMutexFile);
    if ((ssl_ModConfig->nMutexFD = ap_popenf(p, ssl_ModConfig->szMutexFile,
                                           O_WRONLY|O_CREAT, MUTEX_LOCK_MODE)) < 0) {
        ssl_log(s, SSL_LOG_ERROR|SSL_ADD_ERRNO,
                "Parent process could not create SSLMutex lockfile %s",
                ssl_ModConfig->szMutexFile);
        ssl_die();
    }
    /* make sure the childs have access to this file */
    if (geteuid() == 0 /* is superuser */)
        chown(ssl_ModConfig->szMutexFile, ap_user_id, -1 /* no gid change */);
    return;
}

void ssl_mutex_file_open(server_rec *s, pool *p)
{
    /* open the lockfile (once per child) to get a unique fd */
    if ((ssl_ModConfig->nMutexFD = ap_popenf(p, ssl_ModConfig->szMutexFile,
                                           O_WRONLY, MUTEX_LOCK_MODE)) < 0) {
        ssl_log(s, SSL_LOG_ERROR|SSL_ADD_ERRNO,
                "Child could not create SSLMutex lockfile %s",
                ssl_ModConfig->szMutexFile);
        ssl_die();
    }
    return;
}

void ssl_mutex_file_remove(void *data)
{
    /* remove the mutex lockfile */
    unlink(ssl_ModConfig->szMutexFile);
}


#ifdef SSL_USE_FCNTL
static struct flock   lock_it;
static struct flock unlock_it;
#endif

BOOL ssl_mutex_file_acquire(void)
{
    int rc;

#ifdef SSL_USE_FCNTL
    lock_it.l_whence = SEEK_SET; /* from current point */
    lock_it.l_start  = 0;        /* -"- */
    lock_it.l_len    = 0;        /* until end of file */
    lock_it.l_type   = F_WRLCK;  /* set exclusive/write lock */
    lock_it.l_pid    = 0;        /* pid not actually interesting */

    while (   ((rc = fcntl(ssl_ModConfig->nMutexFD, F_SETLKW, &lock_it)) < 0)
              && (errno == EINTR)                               ) {
        continue;
    }
#endif
#ifdef SSL_USE_FLOCK
    while (   ((rc = flock(ssl_ModConfig->nMutexFD, LOCK_EX)) < 0)
              && (errno == EINTR)               ) {
        continue;
    }
#endif

    if (rc < 0)
        return FALSE;
    else
        return TRUE;
}

BOOL ssl_mutex_file_release(void)
{
    int rc;

#ifdef SSL_USE_FCNTL
    unlock_it.l_whence = SEEK_SET; /* from current point */
    unlock_it.l_start  = 0;        /* -"- */
    unlock_it.l_len    = 0;        /* until end of file */
    unlock_it.l_type   = F_UNLCK;  /* unlock */
    unlock_it.l_pid    = 0;        /* pid not actually interesting */

    rc = fcntl(ssl_ModConfig->nMutexFD, F_SETLKW, &unlock_it);
#endif
#ifdef SSL_USE_FLOCK
    rc = flock(ssl_ModConfig->nMutexFD, LOCK_UN);
#endif

    if (rc < 0)
        return FALSE;
    else
        return TRUE;
}

/*  _________________________________________________________________
**
**  Mutex Support (SysV IPC Semaphore)
**  _________________________________________________________________
*/

void ssl_mutex_ipcsem_create(server_rec *s, pool *p)
{
#ifdef SSL_CAN_USE_IPCSEM
    int semid;

    semid = semget(IPC_PRIVATE, 1, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
    if (semid == -1 && errno == EEXIST)
        semid = semget(IPC_PRIVATE, 1, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
    if (semid == -1) {
        ssl_log(s, SSL_LOG_ERROR|SSL_ADD_ERRNO,
                "Parent process could not create private SSLMutex semaphore");
        ssl_die();
    }
    ssl_ModConfig->nMutexSEMID = semid;
#endif
    return;
}

void ssl_mutex_ipcsem_open(server_rec *s, pool *p)
{
    return;
}

void ssl_mutex_ipcsem_remove(void *data)
{
#ifdef SSL_CAN_USE_IPCSEM
    /* remove the semaphore */
    semctl(ssl_ModConfig->nMutexSEMID, 0, IPC_RMID, 0);
#endif
	return;
}

BOOL ssl_mutex_ipcsem_acquire(void)
{
    int rc = 0;
#ifdef SSL_CAN_USE_IPCSEM
    struct sembuf sb[] = {
        { 0, 0, 0 },       /* wait for semaphore */
        { 0, 1, SEM_UNDO } /* increment semaphore */
    };

    rc = semop(ssl_ModConfig->nMutexSEMID, sb, 2);
#endif
    return rc;
}

BOOL ssl_mutex_ipcsem_release(void)
{
    int rc = 0;
#ifdef SSL_CAN_USE_IPCSEM
    struct sembuf sb[] = {
        { 0, -1, SEM_UNDO } /* derements semaphore */
    };

    rc = semop(ssl_ModConfig->nMutexSEMID, sb, 1);
#endif
    return rc;
}

