/*
 * http get client
 * Copyright (c) 1999 Erick Engelke
 */


#include <stdio.h>
#include <string.h>
#include <rtos.h>
#include <net.h>
#include <strlst.h>

#define	BUFFERSIZE	2048
#define HTTPPORT        80

#define	HTTPVER10	"HTTP/1.0"

int http_get( char *url, DWORD optgateway,
    stringlist **asciiback,
    void (*binback)(void *p, int len) )
{
    tcp_Socket *s;
    char *host;
    DWORD hostip;
    int len;
    char *buf;
    int retval = 0;
    int docopy = 0;

    /* must be //host/... */
    len = strlen( url );

    if ( len < 3 ) return( 0 );
    if ( memcmp( url, "//", 2 )) return( 0 );

    s = kcalloc( sizeof( tcp_Socket ), 1 );
    if ( s == NULL ) return( 0 );


    do {
        buf = kcalloc( BUFFERSIZE , 1 );
        if ( buf == NULL ) break;

        /* if we are using a gateway, we don't parse off the host name */
        if ( optgateway == 0L ) {
            host = url+2;       /* skip // */
            url = strchr( host, '/');
            if ( url == NULL ) break;

            *url = 0;       /* temporary */
            hostip = resolve( host );
            if ( hostip == 0L ) break;
            *url = '/';

        } else
            hostip = optgateway;

        if (!tcp_open(s, 0, hostip, HTTPPORT, NULL)) break;

        while ( ! sock_established( s ) ) {
            if ( !tcp_tick( s )) break;
            rt_sleep( 1 );
        }
        if ( ! tcp_tick( s )) break;

        sock_mode( s, TCP_MODE_ASCII );

        sprintf( buf, "GET %s HTTP/1.0\r\n", url );
        sock_puts( s, buf );
        sock_puts( s, "\r\n");

        if ( asciiback != NULL ) {
            *asciiback = strlst_new();
            do {
                if ( sock_dataready( s )) {
                    sock_gets( s, buf, BUFFERSIZE );
                    rip( buf );
                    if ( *buf == 0 )
                        docopy = 1;

                    if ( docopy && (*asciiback != NULL))
                        strlst_add( *asciiback, buf );
                } else
                    if ( ! tcp_tick( s )) break;

                rt_sleep(0);
            } while ( 1 );
        } else {
            /* binary */
            sock_mode( s, TCP_MODE_BINARY );
            do {
                tcp_tick( NULL );
                len = sock_fastread( s, buf, BUFFERSIZE );
                if ( len == 0 ) {
                    if ( !tcp_tick( s )) break;
                    rt_sleep( 1 );
                } else
                    (*binback)( buf, len );
            } while( 1 );
        }
        sock_close( s );
        while ( tcp_tick( s )) rt_sleep( 1 );
        retval = 1;
    } while ( 0 );
    sock_abort( s );
    kfree( s );
    kfree( buf );
    return( retval );
}

