/*
 * $Id$
 *
 * DEBUG: section 61    Srewriter
 * AUTHOR: Duane Wessels
 *
 * SQUID Web Proxy Cache          http://www.squid-cache.org/
 * ----------------------------------------------------------
 *
 *  Squid is the result of efforts by numerous individuals from
 *  the Internet community; see the CONTRIBUTORS file for full
 *  details.   Many organizations have provided support for Squid's
 *  development; see the SPONSORS file for full details.  Squid is
 *  Copyrighted (C) 2001 by the Regents of the University of
 *  California; see the COPYRIGHT file for full details.  Squid
 *  incorporates software developed and/or copyrighted by other
 *  sources; see the CREDITS file for full details.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 *
 */

#include "squid-old.h"
#if USE_AUTH
#include "auth/UserRequest.h"
#endif
#include "comm/Connection.h"
#include "mgr/Registration.h"
#include "Store.h"
#include "fde.h"
#include "client_side_request.h"
#include "acl/Checklist.h"
#include "HttpRequest.h"
#include "client_side.h"
#include "client_side_reply.h"
#include "helper.h"
#include "rfc1738.h"
#if USE_SSL
#include "ssl/support.h"
#endif

/// url maximum lengh + extra informations passed to srewriter
#define MAX_REDIRECTOR_REQUEST_STRLEN (MAX_URL + 1024)

typedef struct {
    void *data;
    char *orig_url;

    Ip::Address client_addr;
    const char *client_ident;
    const char *method_s;
    RH *handler;
} srewriterStateData;

static HLPCB srewriteHandleReply;
static void srewriterStateFree(srewriterStateData * r);
static helper *srewriters = NULL;
static OBJH srewriterStats;
static int n_bypassed = 0;
CBDATA_TYPE(srewriterStateData);

static void
srewriteHandleReply(void *data, char *reply)
{
    srewriterStateData *r = static_cast<srewriterStateData *>(data);
    char *t;
    void *cbdata;
    debugs(61, 5, "srewriteHandleRead: {" << (reply && *reply != '\0' ? reply : "<NULL>") << "}");

    if (reply) {
        if ((t = strchr(reply, ' ')))
            *t = '\0';

        if (*reply == '\0')
            reply = NULL;
    }

    if (cbdataReferenceValidDone(r->data, &cbdata))
        r->handler(cbdata, reply);

    srewriterStateFree(r);
}

static void
srewriterStateFree(srewriterStateData * r)
{
    safe_free(r->orig_url);
    cbdataFree(r);
}

static void
srewriterStats(StoreEntry * sentry)
{
    if (srewriters == NULL) {
        storeAppendPrintf(sentry, "No srewriters defined\n");
        return;
    }

    helperStats(sentry, srewriters, "Srewriter Statistics");

    if (Config.onoff.srewriter_bypass)
        storeAppendPrintf(sentry, "\nNumber of requests bypassed "
                          "because all srewriters were busy: %d\n", n_bypassed);
}

/**** PUBLIC FUNCTIONS ****/

void
srewriterStart(ClientHttpRequest * http, RH * handler, void *data)
{
    ConnStateData * conn = http->getConn();
    srewriterStateData *r = NULL;
    const char *fqdn;
    char buf[MAX_REDIRECTOR_REQUEST_STRLEN];
    int sz;
    http_status status;
    char claddr[MAX_IPSTRLEN];
    char myaddr[MAX_IPSTRLEN];
    assert(http);
    assert(handler);
    debugs(61, 5, "srewriterStart: '" << http->uri << "'");

    if (Config.onoff.srewriter_bypass && srewriters->stats.queue_size) {
        /* Skip srewriter if there is one request queued */
        ++n_bypassed;
        handler(data, NULL);
        return;
    }

    r = cbdataAlloc(srewriterStateData);
    r->orig_url = xstrdup(http->uri);
    if (conn != NULL)
        r->client_addr = conn->log_addr;
    else
        r->client_addr.SetNoAddr();
    r->client_ident = NULL;
#if USE_AUTH
    if (http->request->auth_user_request != NULL) {
        r->client_ident = http->request->auth_user_request->username();
        debugs(61, 5, HERE << "auth-user=" << (r->client_ident?r->client_ident:"NULL"));
    }
#endif

    // HttpRequest initializes with null_string. So we must check both defined() and size()
    if (!r->client_ident && http->request->extacl_user.defined() && http->request->extacl_user.size()) {
        r->client_ident = http->request->extacl_user.termedBuf();
        debugs(61, 5, HERE << "acl-user=" << (r->client_ident?r->client_ident:"NULL"));
    }

    if (!r->client_ident && conn != NULL && conn->clientConnection != NULL && conn->clientConnection->rfc931[0]) {
        r->client_ident = conn->clientConnection->rfc931;
        debugs(61, 5, HERE << "ident-user=" << (r->client_ident?r->client_ident:"NULL"));
    }

#if USE_SSL

    if (!r->client_ident && conn != NULL && Comm::IsConnOpen(conn->clientConnection)) {
        r->client_ident = sslGetUserEmail(fd_table[conn->clientConnection->fd].ssl);
        debugs(61, 5, HERE << "ssl-user=" << (r->client_ident?r->client_ident:"NULL"));
    }
#endif

    if (!r->client_ident)
        r->client_ident = dash_str;

    r->method_s = RequestMethodStr(http->request->method);

    r->handler = handler;

    r->data = cbdataReference(data);

    if ((fqdn = fqdncache_gethostbyaddr(r->client_addr, 0)) == NULL)
        fqdn = dash_str;

    sz = snprintf(buf, MAX_REDIRECTOR_REQUEST_STRLEN, "%s %s/%s %s %s myip=%s myport=%d\n",
                  r->orig_url,
                  r->client_addr.NtoA(claddr,MAX_IPSTRLEN),
                  fqdn,
                  r->client_ident[0] ? rfc1738_escape(r->client_ident) : dash_str,
                  r->method_s,
                  http->request->my_addr.NtoA(myaddr,MAX_IPSTRLEN),
                  http->request->my_addr.GetPort());

    if ((sz<=0) || (sz>=MAX_REDIRECTOR_REQUEST_STRLEN)) {
        if (sz<=0) {
            status = HTTP_INTERNAL_SERVER_ERROR;
            debugs(61, DBG_CRITICAL, "ERROR: Gateway Failure. Can not build request to be passed to srewriter. Request ABORTED.");
        } else {
            status = HTTP_REQUEST_URI_TOO_LARGE;
            debugs(61, DBG_CRITICAL, "ERROR: Gateway Failure. Request passed to srewriter exceeds MAX_REDIRECTOR_REQUEST_STRLEN (" << MAX_REDIRECTOR_REQUEST_STRLEN << "). Request ABORTED.");
        }

        clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
        clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
        assert (repContext);
        Ip::Address tmpnoaddr;
        tmpnoaddr.SetNoAddr();
        repContext->setReplyToError(ERR_GATEWAY_FAILURE, status,
                                    http->request->method, NULL,
                                    http->getConn() != NULL && http->getConn()->clientConnection != NULL ?
                                    http->getConn()->clientConnection->remote : tmpnoaddr,
                                    http->request,
                                    NULL,
#if USE_AUTH
                                    http->getConn() != NULL && http->getConn()->auth_user_request != NULL ?
                                    http->getConn()->auth_user_request : http->request->auth_user_request);
#else
                                    NULL);
#endif

        node = (clientStreamNode *)http->client_stream.tail->data;
        clientStreamRead(node, http, node->readBuffer);
        return;
    }

    debugs(61,6, HERE << "sending '" << buf << "' to the helper");
    helperSubmit(srewriters, buf, srewriteHandleReply, r);
}

static void
srewriteRegisterWithCacheManager(void)
{
    Mgr::RegisterAction("srewriter", "URL Srewriter Stats", srewriterStats, 0, 1);
}

void
srewriteInit(void)
{
    static int init = 0;

    srewriteRegisterWithCacheManager();

    if (!Config.Program.srewrite)
        return;

    if (srewriters == NULL)
        srewriters = new helper("srewriter");

    srewriters->cmdline = Config.Program.srewrite;

    srewriters->childs.updateLimits(Config.srewriteChildren);

    srewriters->ipc_type = IPC_STREAM;

    helperOpenServers(srewriters);

    if (!init) {
        init = 1;
        CBDATA_INIT_TYPE(srewriterStateData);
    }
}

void
srewriterShutdown(void)
{
    if (!srewriters)
        return;

    helperShutdown(srewriters);

    if (!shutting_down)
        return;

    delete srewriters;
    srewriters = NULL;
}

