/*******************************************************************************
**
** extension.c
**
** This file is part of the ABYSS Web server project.
**
** Version: 0.4.1 SSL
**
** Date: January 27th, 2003
**
** Copyright (C) 2000-2001 Moez Mahfoudh <moez.mahfoudh@aprelium.com>
** and/or <mmoez@bigfoot.com>
** Copyright (C) 2001-2003 Aprelium Technologies <http://www.aprelium.com>
** All rights reserved.
**
** Redistribution and total or partial use in source and binary forms, with
** or without modification, are not permitted without the prior written
** permission of the authors.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS 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 THE AUTHOR OR 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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>

#include "abyss.h"

/*******************************************************************************
**
** HandleTime
**
** This a custom extension handler.
**
** Usage: http[s]://host:port/time
**
** Time handler tries to authentificate the user. Access is granted for
** user 'guest' with password 'hello'. Once authentification done, current time
** is displayed.
**
** This sample demonstrates the fundamentals of extension handlers writing
** and authentification processing.
**
*******************************************************************************/

bool
HandleTime (TSession * r)
{
  char z[50];
  time_t now;
  TDate date;

  /* Is it our job to handle the request ? */
  if (strcmp (r->uri, "/time") != 0)
    return FALSE;

  /* It seems to be so... */

  /* Ask for authentification of the request */
  /* We need a user which name is 'guest' and which password is 'hello' */
  /* RequestAuth returns TRUE if the user is authentificated else */
  /* it sets the correct response status (i.e. 401) and returns FALSE */
  if (!RequestAuth (r, "Access to time", "guest", "hello"))
    return TRUE;

  /* OK, the user access is granted */
  /* So let's read the clock */
  time (&now);

  /* And convert it to our date format (in GMT) */
  DateFromGMT (&date, now);

  /* Start the response */
  ResponseChunked (r);

  /* Set the response status to OK (200) */
  ResponseStatus (r, 200);

  /* Set the response content type (in our case, it is HTML) */
  ResponseContentType (r, "text/html");

  /* Flush the response header */
  ResponseWrite (r);

  /* Start sending the response content */
  HTTPWriteString (r, "<HTML><BODY>The time is ");

  /* Convert the date to a human readable string */
  DateToString (&date, z);

  /* send the string to the client */
  HTTPWriteString (r, z);

  /* send the HTML trailer */
  HTTPWriteString (r, "</BODY></HTML>");

  /* Flush the response */
  HTTPWriteEnd (r);

  /* And that's all folks */
  return TRUE;
}

/*******************************************************************************
**
** HandleStatus
**
** This a custom extension handler.
**
** Usage: http[s]://host:port/status/nnn
**
** This handler forces the server to generate status nnn and to output
** an error page.
**
** This sample demonstrates the fundamentals of extension handlers writing,
** status manipulation and error generation.
**
*******************************************************************************/

bool
HandleStatus (TSession * r)
{
  uint32 status;

  /* Scan the request's URI and test if we have to handle it */
  if (sscanf (r->uri, "/status/%d", &status) <= 0)
    return FALSE;

  /* If so, set the response status */
  ResponseStatus (r, (uint16) status);

  /* And return */
  return TRUE;

  /* Notice that we don't need to call the Response* functions */
  /* This is done automagically by the callers which are able  */
  /* to detect the case and to generate the response */
}

/*******************************************************************************
**
** HandleSpy
**
** This a custom extension handler.
**
** Usage: http[s]://host:port/spy
**
** Spy decodes POST or GET requests and lists query variables with their
** respective values.
**
** This sample demonstrates the fundamentals of extension handlers writing
** and queries processing.
**
*******************************************************************************/

bool
HandleSpy (TSession * r)
{
  TTable t;
  uint32 i;

  /* Is our handle requested ? */
  if (strcmp (r->uri, "/spy") != 0)
    return FALSE;

  /* Initialize the table t which will receive the query variables */
  TableInit (&t);

  /* Read the request query and decode it */
  /* If decoding is ok, then the table t is filled with */
  /* pairs of variable name/variable value */
  if (RequestQueryRead (r) && RequestQueryDecode (r, &t))
    {
      /* Start the response */
      ResponseChunked (r);

      /* Set the response status to OK (200) */
      ResponseStatus (r, 200);

      /* Set the response content type (in our case, it is HTML) */
      ResponseContentType (r, "text/html");

      /* Flush the response header */
      ResponseWrite (r);

      /* Start sending the response content */
      HTTPWriteString (r,
		       "<HTML><head><title>Query Spy</title><body><h1>Query Spy</h1>");

      /* For each pair in the table ... */
      for (i = 0; i < t.size; i++)
	{
        /* Get a pointer on the table item */
	  TTableItem *item = &t.item[i];

          /* Output its name */
	  HTTPWriteString (r, "<b>");
	  HTTPWriteString (r, item->name);
	  HTTPWriteString (r, " = </b>");
          /* and its value */
	  HTTPWriteString (r, item->value);
	  HTTPWriteString (r, "</br>");
	};

        /* Send the HTML trailer */
      HTTPWriteString (r, "</body></html>");

      /* Flush the response */
      HTTPWriteEnd (r);
    };

    /* Free the table t */
  TableFree (&t);

  /* The job is done, return */
  return TRUE;
}

/*******************************************************************************
**
** HandleHello
**
** This a custom extension handler.
**
** Usage: http[s]://host:port/hello
**
** Displays a form with a text field. Enter your name there and press submit.
** The same handler is recalled again with some posted data. This results in
** a tiny 'Hi x' message.
**
** This sample demonstrates the fundamentals of extension handlers writing
** and queries processing.
**
*******************************************************************************/

bool
HandleHello (TSession * r)
{
  TTable t;
  char *name;

  /* Is our handle requested ? */
  if (strcmp (r->uri, "/hello") != 0)
    return FALSE;

  /* Initialize the table t which will receive the query variables */
  TableInit (&t);

  /* Read the request query and decode it */
  /* If decoding is ok, then the table t is filled with */
  /* pairs of variable name/variable value */
  if (RequestQueryRead (r) && RequestQueryDecode (r, &t))
    {
      /* Start the response */
      ResponseChunked (r);

      /* Set the response status to OK (200) */
      ResponseStatus (r, 200);

      /* Set the response content type (in our case, it is HTML) */
      ResponseContentType (r, "text/html");

      /* Flush the response header */
      ResponseWrite (r);

      /* Start sending the response content */
      HTTPWriteString (r,
		       "<HTML><head><title>Hello</title><body><h1>Hello</h1>");

      /* Test existence in the query of a variable called 'name' */
      if ((name = TableFind (&t, "name")))
	{
	  /* Yes, we have such a variable */
	  /* So say Hi to the user */
	  HTTPWriteString (r, "Hi <b>");
	  HTTPWriteString (r, name);
	  HTTPWriteString (r, "</b></body></html>");
	}
      else
	/* No, we haven't such a variable so send to the client a form */
	/* to ask him the user's name */
	HTTPWriteString (r,
			 "<form method=post action=\"/hello\">What's your name ?<p><input type=text name=\"name\" value=\"Your name\"><p><input type=submit><input type=reset value=\"Reset Request\"></form></body></html>");

      /* Flush the response */
      HTTPWriteEnd (r);


    };

  /* Free the table */
  TableFree (&t);

  /* That's it ! */
  return TRUE;
}

/*******************************************************************************
**
** ExtensionAddHandlers
**
** This function must always exist even if it is empty.
**
** Put in it calls to ServerAddHandler to register extension handlers.
**
*******************************************************************************/

void
ExtensionAddHandlers (TServer * srv)
{
  /* Install extension handlers */
  ServerAddHandler (srv, HandleTime);
  ServerAddHandler (srv, HandleStatus);
  ServerAddHandler (srv, HandleSpy);
  ServerAddHandler (srv, HandleHello);
}