/* Gconnect - codename:Blue Sky Effort (C)  2003 l0rdloki@digitalsynapse-ks.com 
 *
 * Original copyright notice for Proxytunnel - (C) 2001-2002 Jos Visser / Mark Janssen
 * Contact:                  josv@osp.nl / maniac@maniac.nl 
*/


/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gconnect.h"

#ifndef MAX
#define MAX( x, y )     ( ( (x)>(y) ) ? (x) : (y) )
#endif


// Buffer to hold the proxies basic authentication data 
char basicauth[80];  

static const char base64digits[] =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/*
 * Small MAX macro
 */
#ifndef MAX
#define MAX( x, y )	( ( (x)>(y) ) ? (x) : (y) )
#endif

// base64.h
//void base64(unsigned char *out, const unsigned char *in, int len);
//raw bytes to null-terminated base 64 string
void base64(unsigned char *out, const unsigned char *in, int len)
{
  while (len >= 3) 
    {
      *out++ = base64digits[in[0] >> 2];
      *out++ = base64digits[((in[0] << 4) & 0x30) | (in[1] >> 4)];
      *out++ = base64digits[((in[1] << 2) & 0x3c) | (in[2] >> 6)];
      *out++ = base64digits[in[2] & 0x3f];
      len -= 3;
      in += 3;
    }
  // clean up remainder
  if (len > 0) 
    {
      unsigned char fragment;
      *out++ = base64digits[in[0] >> 2];
      fragment = (in[0] << 4) & 0x30;
      if (len > 1)
	fragment |= in[1] >> 4;
      *out++ = base64digits[fragment];
      *out++ = (len < 2) ? '=' : base64digits[(in[1] << 2) & 0x3c];
      *out++ = '=';
    }
  *out = '\0';
}

/*
 * Create the HTTP basic authentication cookie for use by the proxy. Result
 * is stored in basicauth.
 */
void make_basicauth (struct gengetopt_args_info *args_info)
{
	int len = strlen( args_info->user_arg ) + \
		strlen( args_info->pass_arg ) + 2;
	char *p = (char *) malloc( len );

	/*
	 * Set up the cookie in clear text
	 */
	sprintf( p, "%s:%s", args_info->user_arg, args_info->pass_arg );

	/*
	 * Base64 encode the clear text cookie to create the HTTP base64
	 * authentication cookie
	 */
	base64( basicauth, p, strlen( p ) );

	if( args_info->verbose_flag )
	{
		message( "Proxy basic auth is %s\n", basicauth );
	}

	free( p );
}

