/* Jon Arney, (c) 2000 */

/* This file is distributed under the GPL, see file COPYING for details */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifndef WIN32
#include <sys/socket.h>
#include <sys/file.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#endif

#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <string.h>
#include <pthread.h>
#include <ctype.h>

#include "gnut_lib.h"
#include "gnut_connection.h"
#include "gnut_net.h"
#include "host.h"
#include "gnut_transfer.h"
#include "query.h"
#include "conf.h"
#include "share.h"
#include "gnut_threads.h"
#include "gnut_http.h"

static void cgi_to_normal( char * news, char * olds );

/*
 * Argument parsing routines
 * Return: 1 if invalid CGI string
 *         0 if   valid CGI string
 */
int cgi_parse( char * CGI, char * field, char * value )
{
  char  * start;
  char  * end;
  char  * eq;
  char  tmp[8192];
  char  tmp2[8192];
  int  flag=1;

  if ( ! strstr( CGI, "=" ) ) {
    /* If no equal sign
     * then this is an invalid CGI string
     */
    gd_s(1, "This is _not_ a CGI string\n");
    return 1;
  }

  start = CGI;
  end   = start;

  while(  *start  &&  *end  &&  ( flag == 1 )  )
    {
      /* Find the end of the CGI string */
      end = strstr( start, "&" );
      if ( ! end )
	end = start + ( strlen( start ) );

      /* Is this the correct one? */
      strncpy( tmp, start, end - start );
      tmp[ end - start + 1 ] = '\0';

      cgi_to_normal( tmp2, tmp );

      if (  ! strcmp( tmp2, field ) || ! strcmp( tmp, field )  )
	{
	  eq = strstr( start, "=" );
	  if ( eq )
	    {
              strncpy( tmp, eq + 1, end - eq + 1  );
	      tmp[ end - eq + 1 ] = '\0';

	      cgi_to_normal( value, tmp );

	      flag = 0;
	    }
	}

      /* Move on to next one */
      start = end + 1;

    }

  return flag;
}




static void cgi_to_normal( char * news, char * olds )
{
        int     done = 0;
  int  c;
  char  pbuf[3];

  while( ! done )
        {
    if ( isalnum( * olds ) || * olds == '_' || * olds == '.'  )
                {
      * news = * olds;
    }
    else if ( * olds == '+' )
                {
      * news = ' ';
    }
    else if ( * olds == '%' )
                {
      olds++;
      pbuf[0] = * olds;
      pbuf[1] = * ( olds + 1 );
      pbuf[2] = '\0';
      sscanf( pbuf, "%02x", & c );
      * news = c;
      olds++;
    }
    else
                {
      * news = '\0';
      done = 1;
    }
    olds++;
    news++;
   }

  return;
}
