/* mod_daytime.c
   Modul für Apache 2
   Autor: Sascha Kersken
          sk@lingoworld.de
          
   Diese Modul ist Open-Source-Software und steht
   unter derselben Lizenz wie der Apache HTTP Server.
   Siehe: http://httpd.apache.org/docs-2.0/license.html
   
   Es wird KEINE GARANTIE für das Funktionieren dieser
   Software übernommen. */
   
#include "ap_config.h"
#include "ap_mmn.h"
#include "httpd.h"
#include "http_config.h"
#include "http_connection.h"

#include "apr_buckets.h"
#include "util_filter.h"

#include <time.h>

module AP_MODULE_DECLARE_DATA daytime_module;

/* Konfigurations-Datenstruktur */
typedef struct {
    int dt_enabled;
} daytime_config;

/* Erstellen der Konfiguration pro Server */
static void *create_daytime_server_config(apr_pool_t *p, server_rec *s)
{
    daytime_config *conf = apr_pcalloc(p, sizeof *conf);

    conf->dt_enabled = 0;

    return conf;
}

/* Verarbeiten der Konfigurationsdirektive ProtocolDaytime */
static const char *daytime_on(cmd_parms *cmd, void *dummy, int arg)
{
    daytime_config *conf = ap_get_module_config(cmd->server->module_config,
                                                &daytime_module);
    conf->dt_enabled = arg;

    return NULL;
}

/* Verarbeiten der daytime-Verbindung */
static int process_daytime_connection(conn_rec *c)
{
    apr_bucket_brigade *bb;
    apr_bucket *b;
    apr_status_t rv;
    time_t now;
    daytime_config *conf = ap_get_module_config(c->base_server->module_config,
                                               &daytime_module);

    if (!conf->dt_enabled) {
        return DECLINED;
    }

    bb = apr_brigade_create(c->pool, c->bucket_alloc);

    now = time (NULL);
    
    ap_fprintf(c->output_filters, bb, "%s\r\n", ctime(&now));
    ap_fflush(c->output_filters, bb);

    return OK;
}

/* Direktive */
static const command_rec daytime_cmds[] = 
{
    AP_INIT_FLAG("ProtocolDaytime", daytime_on, NULL, RSRC_CONF,
                 "Run a daytime server on this host"),
    { NULL }
};

/* Hooks registrieren */
static void register_hooks(apr_pool_t *p)
{
    ap_hook_process_connection(process_daytime_connection, NULL, NULL,
                               APR_HOOK_MIDDLE);
}

/* Modulstruktur */
module AP_MODULE_DECLARE_DATA daytime_module = {
    STANDARD20_MODULE_STUFF,
    NULL,                       /* create per-directory config structure */
    NULL,                       /* merge per-directory config structures */
    create_daytime_server_config,  /* create per-server config structure */
    NULL,                       /* merge per-server config structures */
    daytime_cmds,                  /* command apr_table_t */
    register_hooks              /* register hooks */
};
