
/* This example show a CGI script in use
 *
 * Includes SMTP client feature: change main title by mailing new subject
 * line as mail subject, to update@thismachine
 */
#include <rtos.h>
#include <net.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <graph.h>
#include <smtpcli.h>

#include <ftpd.h>
#include <httpd.h>
#include <smtpd.h>
#include <strlst.h>

crit_x *dos;

void web_index( tcp_Socket *s )
{
    FILE *f;
    char buf[128];

    sock_puts(s, "Content-Type: text/html\r\n");
    cs_enter( dos );

    f = fopen( "email.htm" , "rt" );
    if ( f != NULL ) {
        while ( fgets( buf, sizeof( buf ), f ) != NULL ) {
            cs_exit( dos );
            sock_puts( s, buf );
            cs_enter( dos );
        }
        fclose( f );
    }
    cs_exit( dos );
}


void web_email( tcp_Socket *s )
{
    stringlist *sl;
    char *p, *q;
    void *x;
    DWORD host = 0;
    char *destuser = NULL;
    int result;

    sock_puts(s, "Content-Type: text/html\r\n");
    sl = cgi_getstrings( s );

    if ( (p = strlst_findfirst( sl, "RELAY", &x, &q )) != NULL )
        host = resolve( q ) ;

    if ( (p = strlst_findfirst( sl, "DESTUSER", &x, &q )) != NULL )
        destuser = q;

    if ( host == 0 )
        sock_puts( s, "Needs a valid mail relay host!");
    else if ( destuser == NULL )
        sock_puts( s, "Missing destination Email userid");
    else {
        result = smtp_client( host, "automail", destuser, "test",
            "This is a test message");

        cprintf("smtp result was: %s\r\n", result == 0 ? "success":"failure");
        sock_puts( s, "result = ");
        sock_puts( s, (result==0) ? "success" : "failure");
    }

    cgi_freestrings( sl );
}
/*
 * - the web server calls this proc for each web request
 * - it is called in the context of *one* of the HTTPD threads,
 *   though which is not known or important
 * - multiple threads may be in the same proc at the same time
 */
void user_proc( tcp_Socket *s, char *cmd, char *file, char *ext )
{
    if ( !stricmp( file, "/" )) web_index( s );
    if ( !stricmp( file, "/email" )) web_email( s );
}

main()
{
    int i;
    kdebug = 1;
    rt_init(100);
    dos = cs_alloc();
    kpreemptive = 1;        /* enable pre-emptive multithreading */
    sock_init();            /* initialize network */

    cputs("starting...\r\n");

    rt_newthread( ftpdthread, 1,2048, 0, "ftpd" );

#define MAXHTTPD 5
    for ( i = 0 ; i < MAXHTTPD; ++i )
        rt_newthread( httpdthread, (DWORD)&user_proc, 8192, 0, "httpd worker" );
    do {
        /* nothing */
        rt_yield();
    } while ( 1 );
}

