// ============================================================================
// This is a Servlet sample for the G-WAN Web Server (http://www.trustleap.com)
// ----------------------------------------------------------------------------
// contact.c: Build dynamic HTML pages to process a 'Contact Form'
//
//            GET and POST forms are processed with the SAME code (the server
//            does the URL/Entity parsing for Request Handlers like contact.c).
//
//            When the form is sent to the server, we use the form fields
//            (and the client IP address) to build an email which is sent
//            to your SMTP server. A feedback page is then sent to clients.
//
// ============================================================================
#include "xbuffer.h" // G-WAN dynamic buffers

// Title of our HTML page
static char title []="Contact Form";

// Top of our HTML page
static char top[]="<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"
        "<html lang=\"en\"><head><title>%s</title><meta http-equiv"
        "=\"Content-Type\" content=\"text/html; charset=utf-8\">"
        "<link href=\"imgs/style.css\" rel=\"stylesheet\" type=\"text/css\">"
        "</head><body><h1>%s</h1>";

// ----------------------------------------------------------------------------
// imported functions:
//   get_reply(): get a pointer on the 'reply' dynamic buffer from the server
//   set_reply(): send back the 'reply' dynamic buffer's pointer to the server
//  xbuf_reset(): (re)initiatize a dynamic buffer object
// xbuf_frfile(): load a file and append its contents to a specified buffer
//   xbuf_repl(): replace a string by another string in a specified buffer
//    xbuf_cat(): like strcat(), but in the specified dynamic buffer 
//   xbuf_ncat(): like strncat(), but in the specified dynamic buffer 
//   xbuf_xcat(): formatted strcat() (a la printf) in a given dynamic buffer 
//   xbuf_free(): release the memory allocated for a dynamic buffer
//     get_arg(): get the specified form field value
//    sendmail(): send mail for relaying to the 'from' mail address' SMTPserver
//   s_asctime(): like asctime(), but thread-safe
//     get_env(): get connection's 'environment' variables from the server:
// ----------------------------------------------------------------------------
enum HTTP_Env {
   REQUEST=0,      // char  *REQUEST;         // "GET / HTTP/1.1\r\n..."
   REQUEST_METHOD, // int    REQUEST_METHOD;  // 1=GET, 2=HEAD, 3=PUT, 4=POST
   QUERY_STRING,	 // char  *QUERY_STRING     // Request URL after '?'
   CONTENT_TYPE,   // int    CONTENT_TYPE;    // 1="x-www-form-urlencoded"
   CONTENT_LENGTH, // int    CONTENT_LENGTH;  // body length provided by client
   SESSION_ID,     // int    SESSION_ID;      // 12345678 (range: 0-4294967295)
   AUTH_TYPE,
   REMOTE_ADDR,    // char  *REMOTE_ADDR;     // "192.168.54.128"
   REMOTE_PORT,    // int    REMOTE_PORT;     // 1460 (range: 1024-65535)
   REMOTE_PROTOCOL,// int    REMOTE_PROTOCOL; // ((HTTP_major*1000)+HTTP_minor)
   REMOTE_USER,
   SERVER_SOFTWARE,// char  *SERVER_SOFTWARE  // "G-WAN/1.0.2"
   SERVER_NAME,    // char  *SERVER_NAME;     // "domain.com"
   SERVER_ADDR,    // char  *SERVER_ADDR;     // "192.168.10.14"
   SERVER_PORT,    // int    SERVER_PORT;     // 80 (443, 8080, etc.)
   SERVER_DATE,    // char  *SERVER_DATE;     // "Sun, 06 Nov 1994 08:49:37 GMT"
   SERVER_PROTOCOL,// int    SERVER_PROTOCOL; // ((HTTP_major*1000)+HTTP_minor)
   WWW_ROOT,       // char  *WWW_ROOT;        // the HTML pages root folder
   CSP_ROOT,       // char  *CSP_ROOT;        // the CSP .C files folder
};
// ----------------------------------------------------------------------------
// main() is receiving the query parameters ("csp?arg1&arg2&arg3...") in argv[]
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
   int  client_port; // the client port number we get from the server
   char *client_ip,  // the client IP address we get from the server
        *wwwpath;    // the filesystem path to the server's "www" directory

   // create a dynamic buffer and get a pointer on the server response buffer
   xbuf_ctx reply; get_reply(argv, &reply);

   xbuf_ctx f;       // create a dynamic buffer
   xbuf_reset(&f);   // initialize buffer

   // get the connection variables (client_port is not used in this example, we
   // get it just to show how to retreive integers, as opposed to strings)
   client_port=get_env(argv, REMOTE_PORT, &client_ip); // client_ip   = null;
   client_port=get_env(argv, REMOTE_ADDR, &client_ip); // client_port = 0;

   // ---- no URL parameters, we have to send the initial "Contact Form"
   if(argc<2)
   {
      // a template HTML file, with fields that will be replaced by variables 
      char *file="contact.html", str[1024], tmp[80];

      // open the template HTML file located under ".../www/contact.html"
      get_env(argv, WWW_ROOT, &wwwpath);         // get the ".../www/" path
      sprintf(str, "%s%s", wwwpath, file);       // build full file path
      xbuf_frfile(&f, str);                      // load file in buffer
      if(f.len)                                  // load succeeded?
      {
         // build the time and IP address strings
         sprintf(str, "Our current time is: %s", s_asctime(tmp));
         sprintf(tmp, "Your IP address is: %s",  client_ip);

         xbuf_repl(&f, "<!--time-->", str);   // replace field1 by variable
         xbuf_repl(&f, "<!--ip-->",   tmp);   // replace field2 by variable
         xbuf_ncat(&reply, f.ptr, f.len);     // dump file into HTML page
         xbuf_free(&f);                       // free dynamic buffer
      }
      else
      {
         // confirm the reply's dynamic buffer address and size to the server
         // (they have changed when more memory is allocated during formatting)
         set_reply(argv, &reply); 
         return(404); // return an HTTP code (200:'Not found')
      }
   }
   else // ---- if we have URL parameters, we must process a 'POST' Form
   {
      // the form field "names" we want to find values for 
      char *url="", *address="", *subject="", *text="";

      // build the top of our HTML page
      xbuf_xcat(&reply, top, title, title);

      // get the form field values (note the ending '=' name delimiter)
      get_arg("url=",     &url,     argc, argv);
      get_arg("address=", &address, argc, argv);
      get_arg("subject=", &subject, argc, argv);
      get_arg("text=",    &text,    argc, argv);
     
      // insert useful information like which language was used (the 'url' arg)
      // and which IP address the client has used to send this email
      xbuf_xcat (&f, "From:%s in '%s'\n---\n%s", client_ip, url, text);

      // send the form data to your mail server (nobody will spam you if
      // this address is known only by this program and your mail server)
      //sendmail(address, "from_a2583df4@home.com", subject, f.ptr);
      xbuf_free(&f);

      // send feedback to your correspondant and close the HTML page
      xbuf_cat(&reply, "<p>Thank you!<br></p></body></html>");
   }
   // confirm the reply's dynamic buffer address and size to the server
   // (they have changed when more memory is allocated during formatting)
   set_reply(argv, &reply); return(200); // return an HTTP code (200:'OK')
}
// ============================================================================
// End of Source Code
// ============================================================================
