/*
   3APA3A simpliest proxy server
   (c) 2002-2003 by ZARAZA <3APA3A@security.nnov.ru>

   please read License Agreement

   $Id: auth.c,v 1.5 2003/10/29 14:40:05 vlad Exp $
*/

#include "proxy.h"

#define HEADERSIZE 57
#define RECORDSIZE  18

pthread_mutex_t bandlim_mutex;
pthread_mutex_t hash_mutex;

struct bandlim * bandlimiter = NULL;
struct trafcount * trafcounter = NULL;


unsigned char request[] = {	
		0xa2, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41, 
		0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 
		0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 
		0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 
		0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21, 
		0x00, 0x01};

unsigned char * getNetBIOSnamebyip(unsigned long ip){
 unsigned char buf[1024];
 struct sockaddr_in sins;
 int res;
 SOCKET sock;
 SASIZETYPE size;
 fd_set fds;
 struct timeval tv;
 unsigned char * username = NULL;
 int i;
 int j;
 int nnames;
 int type;

 tv.tv_sec = timeouts[SINGLEBYTE_L];
 tv.tv_usec = 0;
 if ( (sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) == INVALID_SOCKET) return NULL;
 sins.sin_family = AF_INET;
 sins.sin_port = htons(0);
 sins.sin_addr.s_addr = INADDR_ANY;
 if(bind(sock,(struct sockaddr *)&sins,sizeof(sins))) {
	close(sock);
	return NULL;
 }
 sins.sin_family = AF_INET;
 sins.sin_addr.s_addr = ip;
 sins.sin_port = htons(137);
 res=sendto(sock, request, sizeof(request), 0, (struct sockaddr *)&sins, sizeof(sins));
 if(res <= 0) {
	close(sock);
	return NULL;
 }
 FD_ZERO(&fds);
 FD_SET(sock, &fds);
 res = select(sock+1, &fds, NULL, NULL, &tv);
 if(res != 1) {
	close(sock);
	return NULL;
 }
 size = sizeof(sins);
 res = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&sins, &size);
 close(sock);
 if(res < (HEADERSIZE + RECORDSIZE)) {
	return NULL;
 }
 nnames = buf[HEADERSIZE-1];
 if (res < (HEADERSIZE + (nnames * RECORDSIZE))) return NULL;
 for (i = 0; i < nnames; i++){
	type = buf[HEADERSIZE + (i*RECORDSIZE) + 15];
	if( type == 3) {
		for(j = 14; j && buf[HEADERSIZE + (i*RECORDSIZE) + j] == ' '; j--)
			buf[HEADERSIZE + (i*RECORDSIZE) + j] = 0;
		if(username)free(username);
		username = (unsigned char *)strdup((char *)buf + HEADERSIZE + i*RECORDSIZE);
	}
	buf[HEADERSIZE + (i*RECORDSIZE) + 15] = 0;
 }
 return username;
} 

int clientnegotiate(struct chain * redir, struct clientparam * param, unsigned long ip, unsigned short port){
	unsigned char buf[1024];
	struct in_addr ina;
	int res;

	ina.s_addr = ip;

	switch(redir->type){
		case R_TCP:
		case R_HTTP:
			return 0;
		case R_CONNECT:
		{
			sprintf((char *)buf, "CONNECT ");
			sprintf((char *)buf + 8 + myinet_ntoa(ina, buf+8),
				":%hu HTTP/1.1\r\nProxy-Connection: keep-alive\r\n", ntohs(port));
			if(redir->extuser){
				unsigned char username[256];
				sprintf((char *)buf + strlen((char *)buf), "Proxy-authorization: basic ");
				sprintf((char *)username, "%.32s:%.64s", redir->extuser, redir->extpass?redir->extpass:(unsigned char *)"");
				en64(username, buf+strlen((char *)buf), strlen((char *)username));
				sprintf((char *)buf + strlen((char *)buf), "\r\n");
			}
			sprintf((char *)buf + strlen((char *)buf), "\r\n");
			if(send(param->remsock, buf, strlen((char *)buf), 0) != (int)strlen((char *)buf))
				return 31;
			if((res = sockgetline(param->remsock,buf,13,'\n',timeouts[CHAIN_TO])) < 13)
				return 32;
			if(buf[9] != '2') return 33;
			while((res = sockgetline(param->remsock,buf,1023,'\n', timeouts[CHAIN_TO])) > 2);
			if(res <= 0) return 34;
			return 0;
		}
		case R_SOCKS4:
		{
		 unsigned char *name = (unsigned char *)"anonymous";

			buf[0] = 4;
			buf[1] = 1;
			memcpy(buf+2, &port, 2);
			memcpy(buf+4, &ip, 4);
			if(redir->extuser)name = redir->extuser;
			memcpy(buf+8, name, strlen((char *)name) + 1);
			if(send(param->remsock, buf, strlen((char *)name) + 9, 0) < 9){
				return 41;
			}
			if(sockgetline(param->remsock, buf, 9, EOF, timeouts[CHAIN_TO]) != 9){
				return 42;
			}
			if(buf[1] != 90) {
				return 43;
			}

		}
		return 0;

		case R_SOCKS5:
		{
		 int inbuf = 0;
			buf[0] = 5;
			buf[1] = 1;
			buf[2] = redir->extuser? 2 : 0;
			if(send(param->remsock, buf, 3, 0) != 3){
				return 51;
			}
			if(sockgetline(param->remsock, buf, 2, EOF, timeouts[CHAIN_TO]) != 2){
				return 52;
			}
			if(buf[0] != 5) {
				return 53;
			}
			if(buf[1] != 0 && !(buf[1] == 2 && redir->extuser)){
				return 54;
			}
			if(buf[1] == 2){
				buf[inbuf++] = 1;
				buf[inbuf] = (unsigned char)strlen((char *)redir->extuser);
				memcpy(buf+inbuf+1, redir->extuser, buf[inbuf]);
				inbuf += buf[inbuf] + 1;
				buf[inbuf] = redir->extpass?(unsigned char)strlen((char *)redir->extpass):0;
				if(redir->extpass)memcpy(buf+inbuf+1, redir->extpass, buf[inbuf]);
				inbuf += buf[inbuf] + 1;
				if(send(param->remsock, buf, inbuf, 0) != inbuf){
					return 51;
				}
				if(sockgetline(param->remsock, buf, 2, EOF, 60) != 2){
					return 55;
				}
				if(buf[0] != 1 || buf[1] != 0) {
					return 56;
				}
			}
			buf[0] = 5;
			buf[1] = 1;
			buf[2] = 0;
			buf[3] = 1;
			memcpy(buf+4, &ip, 4);
			memcpy(buf+8, &port, 2);
			if(send(param->remsock, buf, 10, 0) != 10){
				return 51;
			}
			if(sockgetline(param->remsock, buf, 10, EOF, timeouts[CHAIN_TO]) != 10){
				return 57;
			}
			if(buf[0] != 5) {
				return 53;
			}
			if(buf[1] != 0) {
				return 60 + (buf[1] % 10);
			}
			if(buf[3] != 1) {
				return 58;
			}
			return 0;
		}

		default:

			return 30;
	}
}

int randomizer = 1;

int handleredirect(struct clientparam * param, struct ace * acentry){
	int connected = 0;
	int weight = 1000;
	int res;
	int done = 0;
	struct chain * cur;
	struct chain * redir = NULL;
	unsigned long targetip;
	unsigned short targetport;
	int r1, r2;

	targetip = param->sins.sin_addr.s_addr;
	targetport = param->sins.sin_port;

	if(!targetip || !targetport) return 0;

	if(param->remsock != INVALID_SOCKET) return 0;
	srand(randomizer);
	randomizer=rand();

	for(cur = acentry->chains; cur; cur=cur->next){
		if(done || (cur->weight < weight)) {
			r1 = (cur->weight * 12347)/weight;
			r2 = (rand()^targetip^targetport)%12347;
			if( done ||  (r1 < r2)) {
				weight -= cur->weight;
				if(weight <= 0) {
					weight = 1000;
					done = 0;
				}
				continue;
			}
		}
		param->redirected++;
		done = 1;
		weight -= cur->weight;
		if(weight <= 0) {
			weight = 1000;
			done = 0;
		}
		if(!connected){
			if(cur->redirip) param->sins.sin_addr.s_addr = cur->redirip;
			if(cur->redirport) param->sins.sin_port = cur->redirport;
			if(!cur->redirip && !cur->redirport){
				param->extusername = strdup(cur->extuser);
				param->extpassword = strdup(cur->extpass);
				param->redirectfunc = proxychild;
				return 0;
			}
			if((res = alwaysauth(param))){
				return (res == 10)? res : 60+res;
			}
		}
		else {
			res = redir?clientnegotiate(redir, param, cur->redirip, cur->redirport):0;
			if(res) return res;
		}
		redir = cur;
		param->redirtype = redir->type;
		if(redir->type == R_TCP || redir->type ==R_HTTP) {
			param->extusername = strdup(cur->extuser);
			param->extpassword = strdup(cur->extpass);
			return 0;
		}
		connected = 1;
	}

	randomizer=rand();
	if(!connected) return 9;
	return redir?clientnegotiate(redir, param, targetip, targetport):0;
}


int ACLmatches(struct ace* acentry, struct clientparam * param){
	int usermatch, srcmatch, dstmatch, portmatch, opmatch;
	struct userlist * userentry;
	struct iplist *ipentry;
	struct portlist *portentry;
	unsigned char * username;

	if(param->hostname) param->sins.sin_addr.s_addr = getip(param->hostname);
	username = param->username?param->username:(unsigned char *)"*";
	usermatch = srcmatch = dstmatch = portmatch = opmatch = 0;
	if(!acentry->users) usermatch = 1;
	else {
	 for(userentry = acentry->users; userentry; userentry = userentry->next)
		if(!strcmp((char *)username, (char *)userentry->user)){
			usermatch = 1;
			break;
		}
	}
	if(!acentry->src) srcmatch = 1;
	else {
	 for(ipentry = acentry->src; ipentry; ipentry = ipentry->next)
		if(ipentry->ip == (param->sinc.sin_addr.s_addr & ipentry->mask)) {
			srcmatch = 1;
			break;
		}
	}
	if(!acentry->dst) dstmatch = 1;
	else {
	 for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next)
			if(ipentry->ip == (param->sins.sin_addr.s_addr & ipentry->mask)) {
		dstmatch = 1;
			break;
		}
	}
	if(!acentry->ports) portmatch = 1;
	else {
	 for (portentry = acentry->ports; portentry; portentry = portentry->next)
		if(ntohs(param->sins.sin_port) >= portentry->startport &&
			   ntohs(param->sins.sin_port) <= portentry->endport) {
			portmatch = 1;
			break;
		}
	}
		if(!acentry->operation) opmatch = 1;
	else {
		if((acentry->operation & param->operation) == param->operation){
				 opmatch = 1;
		}
	}
	return usermatch && srcmatch && dstmatch && portmatch && opmatch;
}


unsigned bandlimitfunc(struct clientparam *param, unsigned nbytes){
	unsigned sleeptime = 0, nsleeptime;
	unsigned long sec;
	unsigned msec;
	double now;
	int i;

#ifdef _WIN32
	struct timeb tb;

	ftime(&tb);
	sec = (unsigned long)tb.time;
	msec = (unsigned long)tb.millitm;

#else
	struct timeval tv;
	gettimeofday(&tv, NULL);

	sec = tv.tv_sec;
	msec = tv.tv_usec / 1000;
#endif
	pthread_mutex_lock(&bandlim_mutex);
	for(i=0; i<MAXBANDLIMS && param->bandlims[i]; i++){
		if( !param->bandlims[i]->basetime || 
			param->bandlims[i]->basetime > sec ||
			param->bandlims[i]->basetime < (sec - 1800)
		  )
		{
			param->bandlims[i]->basetime = sec;
			param->bandlims[i]->nexttime = 0.;
			continue;
		}
		now = ((sec - param->bandlims[i]->basetime) * 1000.) + msec;
		nsleeptime = (param->bandlims[i]->nexttime > now)?
			(unsigned)(param->bandlims[i]->nexttime - now) : 0;
		sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
		param->bandlims[i]->nexttime = now + nsleeptime + (((double)nbytes * 8000.)/(double)param->bandlims[i]->rate);
	}
	pthread_mutex_unlock(&bandlim_mutex);
	return sleeptime;
}

void trafcountfunc(struct clientparam *param){
	struct trafcount * tc;
	unsigned long val;

	for(tc = trafcounter; tc; tc = tc->next) {
		if(ACLmatches(tc->ace, param)){
			time_t t;
			if(tc->ace->action == NOCOUNT) break;
			val = tc->traf + param->statssrv;
			if(val < tc->traf) tc->trafgb++;
			tc->traf = val;
			time(&t);
			tc->updated = t;
		}
	}
}

int alwaysauth(struct clientparam * param){
	int res;
	int i = 0;
	struct bandlim * be;
	struct trafcount * tc;
	res = doconnect(param);
	for(be = bandlimiter; be && i<MAXBANDLIMS; be = be->next) {
		if(ACLmatches(be->ace, param)){
			if(be->ace->action == NOBANDLIM) {
				break;
			}
			param->bandlims[i++] = be;
			param->bandlimfunc = bandlimitfunc;
		}
	}
	if(i<MAXBANDLIMS)param->bandlims[i] = NULL;
	if(trafcounter) {
		for(tc = trafcounter; tc; tc = tc->next) {
			if(tc->disabled) continue;
			if(ACLmatches(tc->ace, param)){
				if(tc->ace->action == NOCOUNT) break;
				
				if((tc->traflimgb < tc->trafgb) ||
					((tc->traflimgb == tc->trafgb) && (tc->traflim < tc->traf))
				) return 10;
				param->trafcountfunc = trafcountfunc;
			}
		}
	}
	return res;
}

int checkACL(struct clientparam * param){
	struct ace* acentry;

	if(!param->acl) {
		return alwaysauth(param);
	}
	for(acentry = param->acl; acentry; acentry = acentry->next) {
		if(ACLmatches(acentry, param)) {
			if(acentry->action == 2) {
				if(param->operation < 256 && !(param->operation & CONNECT)){
					continue;
				}
				if(param->redirected && acentry->chains && !acentry->chains->redirip && !acentry->chains->redirport) {
					continue;
				}
				return handleredirect(param, acentry);
			}
			return (acentry->action)?acentry->action:alwaysauth(param);
		}
	}
	return 3;
}

int ipauth(struct clientparam * param){
	return checkACL(param);
}

int nbnameauth(struct clientparam * param){
	unsigned char * name = getNetBIOSnamebyip(param->sinc.sin_addr.s_addr);

	if (param->username) free (param->username);
	param->username = name;
	return checkACL(param);
}

int strongauth(struct clientparam * param){
	struct passwords * pwl;
	unsigned char buf[2048];

	if(!param->pwl) return alwaysauth(param);
	if(!param->username) return 4;
	for(pwl = param->pwl; pwl; pwl=pwl->next){
		if(!strcmp((char *)pwl->user, (char *)param->username)) switch(pwl->pwtype) {
			case CL:
				if(!pwl->password || !*pwl->password || (param->password && !strcmp((char *)param->password, (char *)pwl->password))){
					break;
				}
				return 6;
			case CR:
				if(!strcmp((char *)pwl->password, (char *)mycrypt(param->password, pwl->password,buf))) {
					break;
				}
				return 7;
			case NT:
				if(!strcmp((char *)pwl->password, (char *)ntpwdhash(buf,param->password))) {
					break;
				}
				return 8;
				
			default:
				return 999;
		}
		else continue;
		return checkACL(param);
	}
	return 5;
}


struct hashentry {
	char hash[sizeof(unsigned)*2];
	unsigned long value;
	time_t expires;
	struct hashentry *next;
};

struct hashentry ** hashtable = NULL;
struct hashentry * hashvalues = NULL;
struct hashentry * hashempty = NULL;

unsigned hashsize = 0;

void nametohash(const unsigned char * name, unsigned char *hash){
	unsigned i, j;
	memset(hash, 0, sizeof(unsigned)*2);
	for(i=0, j=0; name[j]; j++){
		hash[i] += toupper(name[j]) - 32;
		if(++i == sizeof(unsigned)*2) i = 0;
	}
}

unsigned hashindex(const unsigned char* hash){
	unsigned t1, t2;
	t1 = *(unsigned *)hash;
	t2 = *(unsigned *)(hash + sizeof(unsigned));
	return (t1 * 54321 + t2) % (hashsize >> 2);
}


void destroyhashtable(void){
	pthread_mutex_destroy(&hash_mutex);
	if(hashtable){
		free(hashtable);
		hashtable = NULL;
	}
	if(hashvalues){
		free(hashvalues);
		hashvalues = NULL;
	}
}

int inithashtable(unsigned nhashsize){
	unsigned i;

	pthread_mutex_init(&hash_mutex, NULL);
	if(nhashsize<4) return 1;
	if(hashtable){
		free(hashtable);
		hashtable = NULL;
	}
	if(hashvalues){
		free(hashvalues);
		hashvalues = NULL;
	}
	hashsize = 0;
	if(!(hashtable = malloc((nhashsize>>2) * sizeof(struct hashentry *)))){
		return 2;
	}
	if(!(hashvalues = malloc(nhashsize * sizeof(struct hashentry)))){
		free(hashtable);
		hashtable = NULL;
		return 3;
	}
	hashsize = nhashsize;
	memset(hashtable, 0, (hashsize>>2) * sizeof(struct hashentry *));
	memset(hashvalues, 0, hashsize * sizeof(struct hashentry));
	for(i = 0; i< (hashsize - 1); i++) {
		(hashvalues + i)->next = hashvalues + i + 1;
	}
	hashempty = hashvalues;
	return 0;
}

void hashadd(const unsigned char* name, unsigned long value, time_t expires){
        struct hashentry * he;
	unsigned index;
	
	if(!value||!name||!hashtable||!hashempty) return;
	pthread_mutex_lock(&hash_mutex);
	he = hashempty;
	hashempty = hashempty->next;
	nametohash(name, he->hash);
	he->value = value;
	he->expires = expires;
	he->next = NULL;
	index = hashindex(he->hash);
	if(!hashtable[index] || !memcmp(he->hash, hashtable[index]->hash, sizeof(he->hash))){
		he->next = hashtable[index];
		hashtable[index] = he;
	}
	else {
		memset(he, 0, sizeof(struct hashentry));
		he->next = hashempty;
		hashempty = he;
	}
	pthread_mutex_unlock(&hash_mutex);
}

unsigned long hashresolv(const unsigned char* name){
	char hash[sizeof(unsigned)*2];
        struct hashentry ** hep;
	struct hashentry *he;
	unsigned index;
	time_t t;

	if(!hashtable || !name) return 0;
	time(&t);
	nametohash(name, hash);
	index = hashindex(hash);
	pthread_mutex_lock(&hash_mutex);
	for(hep = hashtable + index; (he = *hep)!=NULL; ){
		if((unsigned long)he->expires < (unsigned long)t) {
			(*hep) = he->next;
			he->expires = 0;
			he->next = hashempty;
			hashempty = he;
		}
		else if(!memcmp(hash, he->hash, sizeof(unsigned)*2)){
			pthread_mutex_unlock(&hash_mutex);
			return he->value;
		}
		else hep=&(he->next);
	}
	pthread_mutex_unlock(&hash_mutex);
	return 0;
}

unsigned long nservers[MAXNSERVERS] = {0, 0, 0, 0, 0};

unsigned long myresolver(const unsigned char * name){
	int i;
	unsigned long retval;

	if((retval = hashresolv(name))) {
		return retval;
	}
	
	for(i=0; i<MAXNSERVERS && nservers[i]; i++){
		unsigned short nquery, nq, na;
		unsigned char buf[4096], *s1, *s2;
		int j, k, len, flen;
		SOCKET sock;
		SASIZETYPE size;
		struct sockaddr_in sin;
		struct timeval tv = {15,0};
		fd_set fds;
		unsigned ttl;


		if((sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) break;
		sin.sin_family = AF_INET;
		sin.sin_port = htons(0);
		sin.sin_addr.s_addr = htonl(0);
		if(bind(sock,(struct sockaddr *)&sin,sizeof(sin))) {
			shutdown(sock, SHUT_RDWR);
			close(sock);
			break;
		}
		sin.sin_addr.s_addr = nservers[i];
		sin.sin_port = htons(53);

		nquery = rand();
		*(unsigned short*)buf = nquery; /* query id */
		buf[2] = 1; 			/* recursive */
		buf[3] = 0;
		buf[4] = 0;
		buf[5] = 1;			/* 1 request */
		buf[6] = buf[7] = 0;		/* no replies */
		buf[8] = buf[9] = 0;		/* no ns count */
		buf[10] = buf[11] = 0;		/* no additional */
		len = strlen((char *)name);
		if(len > 255) {
			len = 255;
		}
		memcpy(buf + 13, name, len);
		len += 13;
		buf[len] = 0;
		for(s2 = buf + 12; (s1 = (unsigned char *)strchr((char *)s2 + 1, '.')); s2 = s1)*s2 = (unsigned char)((s1 - s2) - 1);
		*s2 = (len - (s2 - buf)) - 1;
		len++;
		buf[len++] = 0;
		buf[len++] = 1;			/* host address */
		buf[len++] = 0;
		buf[len++] = 1;			/* INET */
		if(sendto(sock, buf, len, 0, (struct sockaddr *)&sin, sizeof(sin)) != len){
			shutdown(sock, SHUT_RDWR);
			close(sock);
			continue;
		}
		size = sizeof(sin);
		FD_ZERO(&fds);
		FD_SET(sock, &fds);
		if (select (sock+1, &fds, NULL, NULL, &tv) <= 0) {
			shutdown(sock, SHUT_RDWR);
			close(sock);
			continue;
		}
		len = recvfrom(sock, buf, 4096, 0, (struct sockaddr *)&sin, &size);
		shutdown(sock, SHUT_RDWR);
		close(sock);
		if(len <= 13) continue;
		if(*(unsigned short *)buf != nquery)continue;
		if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
			return 0;
		}
		nq = buf[5] + (((unsigned short)buf[4])<<8);
		if (nq != 1) {
			continue;			/* we did only 1 request */
		}
		for(k = 13; k<len && buf[k]; k++) {
		}
		k++;
		if( (k+4) >= len) {
			continue;
		}
		k += 4;
		if(na > 255) na = 255;			/* somebody is very evil */
		for (j = 0; j < na; j++) {		/* now there should be answers */
			if((k+16) >= len) {
				break;
			}
			flen = buf[k+11] + (((unsigned short)buf[k+10])<<8);
			if((k+12+flen) > len) break;
			if(buf[k+2] != 0 || buf[k+3] != 1 || flen != 4) {
				k+= (12 + flen);
				continue; 		/* we need A IPv4 */
			}
			retval = *(unsigned long *)(buf + k + 12);
			ttl = ntohl(*(unsigned long *)(buf + k + 6));
			if(ttl)hashadd(name, retval, ((unsigned)time(0))+ttl);
			return retval;
		}
	}
	return 0;
}

#ifndef NOODBC

SQLHENV  henv = NULL;
SQLHSTMT hstmt = NULL;
SQLHDBC hdbc = NULL;
char * sqlstring = NULL;
pthread_mutex_t odbc_mutex;
int odbc_mutex_init = 0;


void close_sql(){
	if(hstmt) {
		SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
		hstmt = NULL;
	}
	if(hdbc){
		SQLDisconnect(hdbc);
		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
		hdbc = NULL;
	}
	if(henv) {
		SQLFreeHandle(SQL_HANDLE_ENV, henv);
		hdbc = NULL;
	}
}

int init_sql(char * s){
	SQLHDBC hdbc;
	SQLRETURN  retcode;
	char * datasource;
	char * username;
	char * password;
	char * oldstring;

	if(!s) return 0;
	oldstring = sqlstring;
	sqlstring=strdup(s);
	if(oldstring)free(oldstring);

	if(!odbc_mutex_init){
		pthread_mutex_init(&odbc_mutex, NULL);
		odbc_mutex_init = 1;
	}
	if(!henv){
		retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
		if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO){
			return 0;
		}
		retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 

		if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
			return 0;
		}
	}
	retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
		return 0;
	}
       	SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (void*)15, 0);
	datasource = strtok(s, ",");
	username = strtok(NULL, ",");
	password = strtok(NULL, ",");
	

         /* Connect to data source */
        retcode = SQLConnect(hdbc, (SQLCHAR*) datasource, (SQLSMALLINT)strlen(datasource),
                (SQLCHAR*) username, (SQLSMALLINT)((username)?strlen(username):0),
                (SQLCHAR*) password, (SQLSMALLINT)((password)?strlen(password):0));

	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO){
		return 0;
	}
        retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); 
        if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO){
		return 0;
	}
	return 1;
}

void logsql(struct clientparam * param, const unsigned char *s) {
	unsigned char buf[1024];
	SQLRETURN ret;

	if(odbc_mutex_init)pthread_mutex_lock(&odbc_mutex);
	if(!hstmt){
		close_sql();
		init_sql(sqlstring);
	}
	if(hstmt){
		ret = SQLExecDirect(hstmt, (SQLCHAR *)buf, (SQLINTEGER)dobuf(param, buf, s));
		if(ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO){
			close_sql();
			init_sql(sqlstring);
			if(hstmt) SQLExecDirect(hstmt, (SQLCHAR *)buf, (SQLINTEGER)dobuf(param, buf, s));
		}
		
	}
	if(odbc_mutex_init)pthread_mutex_unlock(&odbc_mutex);
}

#endif
 
#ifdef WITHMAIN
int main(int argc, unsigned char * argv[]) {
	unsigned ip = 0;
 WSADATA wd;
 WSAStartup(MAKEWORD( 1, 1 ), &wd);
	if(argc == 2)ip=getip(argv[1]);
	if(!hp) {
		printf("Not found");
		return 0;
	}
	printf("Name: '%s'\n", getnamebyip(ip);
	return 0;
}
#endif
