# include <windows.h>
# include <httpext.h>

# include <stdlib.h>

#define FILE_SIZE       10240
#define MALLOC_FAILURE  "Out of memory"


const char PSZ_CONTENT_TYPE[] = "Content-type: text/plain\r\n\r\n";

DWORD WINAPI
HttpExtensionProc( IN OUT EXTENSION_CONTROL_BLOCK * pecb)
{
    char *query_string;
    char *buffer;
    const char *pszHeader;
    int filesize;
    DWORD cbFileSize;
    int index;
    
    /* Get the query string, if any; check to see if an alternate
     * file size was specified.
     */
    
    if ( !(query_string = pecb->lpszQueryString) )
      filesize = FILE_SIZE;
    else {
        if ( !strncmp(query_string, "size=", 5) )
          filesize = atoi(&(query_string[5]));
        else
          filesize = FILE_SIZE;
    }
    
    /* Set the content type */
    pszHeader = PSZ_CONTENT_TYPE;
    if ( !pecb->ServerSupportFunction( pecb->ConnID,
                                      HSE_REQ_SEND_RESPONSE_HEADER,
                                      "200 OK",
                                      NULL,
                                      (LPDWORD) pszHeader )) {

        return HSE_STATUS_ERROR;
    }


    /* Allocate the output buffer */
    if ( !(buffer = (char *)malloc(filesize)) ) {
        
        DWORD cbMallocFailed = sizeof(MALLOC_FAILURE) - sizeof(CHAR);

        pecb->WriteClient( pecb->ConnID, MALLOC_FAILURE, &cbMallocFailed, 0);
        
        return ( HSE_STATUS_ERROR);
    }

    
    /* Generate the output */
    for (index=0; index < filesize; index++)
      /* generate random characters from A-Z */
      buffer[index] = rand() %26 + 63;

    /* Send the output */
    cbFileSize = filesize;
    if (!pecb->WriteClient( pecb->ConnID, 
                          buffer, &cbFileSize, 0)) {

        return (HSE_STATUS_ERROR);
    }
    
    free(buffer);
    
    return HSE_STATUS_SUCCESS;

} // HttpExtensionProc()


BOOL WINAPI
GetExtensionVersion(
    HSE_VERSION_INFO * pver
    )
{
    pver->dwExtensionVersion = MAKELONG( 1, 0 );
    strcpy( pver->lpszExtensionDesc,
            "WebStone Extension Example" );

    return TRUE;
}
