1 /*
2    3APA3A simpliest proxy server
3    (c) 2002-2016 by Vladimir Dubrovin <3proxy@3proxy.ru>
4 
5    please read License Agreement
6 
7 */
8 
9 #include "proxy.h"
10 
11 
clientnegotiate(struct chain * redir,struct clientparam * param,struct sockaddr * addr,unsigned char * hostname)12 int clientnegotiate(struct chain * redir, struct clientparam * param, struct sockaddr * addr, unsigned char * hostname){
13 	unsigned char *buf;
14 	unsigned char *username;
15 	int res;
16 	int len=0;
17 	unsigned char * user, *pass;
18 
19 
20 	user = redir->extuser;
21 	pass = redir->extpass;
22 	if (!param->srvbufsize){
23 		param->srvbufsize = SRVBUFSIZE;
24 		param->srvbuf = myalloc(param->srvbufsize);
25 	}
26 	buf = param->srvbuf;
27 	username = buf + 2048;
28 	if(user) {
29 		if (*user == '*') {
30 			if(!param->username) return 4;
31 			user = param->username;
32 			pass = param->password;
33 		}
34 	}
35 	switch(redir->type){
36 		case R_TCP:
37 		case R_HTTP:
38 			return 0;
39 		case R_CONNECT:
40 		case R_CONNECTP:
41 		{
42 			len = sprintf((char *)buf, "CONNECT ");
43 			if(redir->type == R_CONNECTP && hostname) {
44 				char * needreplace;
45 				needreplace = strchr((char *)hostname, ':');
46 				if(needreplace) buf[len++] = '[';
47 				len += sprintf((char *)buf + len, "%.256s", (char *)hostname);
48 				if(needreplace) buf[len++] = ']';
49 			}
50 			else {
51 				if(*SAFAMILY(addr) == AF_INET6) buf[len++] = '[';
52 				len += myinet_ntop(*SAFAMILY(addr), SAADDR(addr), (char *)buf+len, 256);
53 				if(*SAFAMILY(addr) == AF_INET6) buf[len++] = ']';
54 			}
55 			len += sprintf((char *)buf + len,
56 				":%hu HTTP/1.0\r\nConnection: keep-alive\r\n", ntohs(*SAPORT(addr)));
57 			if(user){
58 				len += sprintf((char *)buf + len, "Proxy-Authorization: Basic ");
59 				sprintf((char *)username, "%.128s:%.128s", user, pass?pass:(unsigned char *)"");
60 				en64(username, buf+len, (int)strlen((char *)username));
61 				len = (int)strlen((char *)buf);
62 				len += sprintf((char *)buf + len, "\r\n");
63 			}
64 			len += sprintf((char *)buf + len, "\r\n");
65 			if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != (int)strlen((char *)buf))
66 				return 31;
67 			param->statssrv64+=len;
68 			param->nwrites++;
69 			if((res = sockgetlinebuf(param, SERVER,buf,13,'\n',conf.timeouts[CHAIN_TO])) < 13)
70 				return 32;
71 			if(buf[9] != '2') return 33;
72 			while((res = sockgetlinebuf(param, SERVER,buf,1023,'\n', conf.timeouts[CHAIN_TO])) > 2);
73 			if(res <= 0) return 34;
74 			return 0;
75 		}
76 		case R_SOCKS4:
77 		case R_SOCKS4P:
78 		case R_SOCKS4B:
79 		{
80 
81 			if(*SAFAMILY(addr) != AF_INET) return 44;
82 			buf[0] = 4;
83 			buf[1] = 1;
84 			memcpy(buf+2, SAPORT(addr), 2);
85 			if(redir->type == R_SOCKS4P && hostname) {
86 				buf[4] = buf[5] = buf[6] = 0;
87 				buf[7] = 3;
88 			}
89 			else memcpy(buf+4, SAADDR(addr), 4);
90 			if(!user)user = (unsigned char *)"anonymous";
91 			len = (int)strlen((char *)user) + 1;
92 			memcpy(buf+8, user, len);
93 			len += 8;
94 			if(redir->type == R_SOCKS4P && hostname) {
95 				int hostnamelen;
96 
97 				hostnamelen = (int)strlen((char *)hostname) + 1;
98 				if(hostnamelen > 255) hostnamelen = 255;
99 				memcpy(buf+len, hostname, hostnamelen);
100 				len += hostnamelen;
101 			}
102 			if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) < len){
103 				return 41;
104 			}
105 			param->statssrv64+=len;
106 			param->nwrites++;
107 			if((len = sockgetlinebuf(param, SERVER, buf, (redir->type == R_SOCKS4B)? 3:8, EOF, conf.timeouts[CHAIN_TO])) != ((redir->type == R_SOCKS4B)? 3:8)){
108 				return 42;
109 			}
110 			if(buf[1] != 90) {
111 				return 43;
112 			}
113 
114 		}
115 		return 0;
116 
117 		case R_SOCKS5:
118 		case R_SOCKS5P:
119 		case R_SOCKS5B:
120 		{
121 		 int inbuf = 0;
122 			buf[0] = 5;
123 			buf[1] = 1;
124 			buf[2] = user? 2 : 0;
125 			if(socksend(param->remsock, buf, 3, conf.timeouts[CHAIN_TO]) != 3){
126 				return 51;
127 			}
128 			param->statssrv64+=len;
129 			param->nwrites++;
130 			if(sockgetlinebuf(param, SERVER, buf, 2, EOF, conf.timeouts[CHAIN_TO]) != 2){
131 				return 52;
132 			}
133 			if(buf[0] != 5) {
134 				return 53;
135 			}
136 			if(buf[1] != 0 && !(buf[1] == 2 && user)){
137 				return 54;
138 			}
139 			if(buf[1] == 2){
140 				buf[inbuf++] = 1;
141 				buf[inbuf] = (unsigned char)strlen((char *)user);
142 				memcpy(buf+inbuf+1, user, buf[inbuf]);
143 				inbuf += buf[inbuf] + 1;
144 				buf[inbuf] = pass?(unsigned char)strlen((char *)pass):0;
145 				if(pass)memcpy(buf+inbuf+1, pass, buf[inbuf]);
146 				inbuf += buf[inbuf] + 1;
147 				if(socksend(param->remsock, buf, inbuf, conf.timeouts[CHAIN_TO]) != inbuf){
148 					return 51;
149 				}
150 				param->statssrv64+=inbuf;
151 				param->nwrites++;
152 				if(sockgetlinebuf(param, SERVER, buf, 2, EOF, 60) != 2){
153 					return 55;
154 				}
155 				if(buf[0] != 1 || buf[1] != 0) {
156 					return 56;
157 				}
158 			}
159 			buf[0] = 5;
160 			buf[1] = 1;
161 			buf[2] = 0;
162 			if(redir->type == R_SOCKS5P && hostname) {
163 				buf[3] = 3;
164 				len = (int)strlen((char *)hostname);
165 				if(len > 255) len = 255;
166 				buf[4] = len;
167 				memcpy(buf + 5, hostname, len);
168 				len += 5;
169 			}
170 			else {
171 				len = 3;
172 				buf[len++] = (*SAFAMILY(addr) == AF_INET)? 1 : 4;
173 				memcpy(buf+len, SAADDR(addr), SAADDRLEN(addr));
174 				len += SAADDRLEN(addr);
175 			}
176 			memcpy(buf+len, SAPORT(addr), 2);
177 			len += 2;
178 			if(socksend(param->remsock, buf, len, conf.timeouts[CHAIN_TO]) != len){
179 				return 51;
180 			}
181 			param->statssrv64+=len;
182 			param->nwrites++;
183 			if(sockgetlinebuf(param, SERVER, buf, 4, EOF, conf.timeouts[CHAIN_TO]) != 4){
184 				return 57;
185 			}
186 			if(buf[0] != 5) {
187 				return 53;
188 			}
189 			if(buf[1] != 0) {
190 				return 60 + (buf[1] % 10);
191 			}
192 			switch (buf[3]) {
193 			case 1:
194 			    if (redir->type == R_SOCKS5B ||  sockgetlinebuf(param, SERVER, buf, 6, EOF, conf.timeouts[CHAIN_TO]) == 6)
195 				    break;
196 			    return 59;
197 			case 3:
198 			    if (sockgetlinebuf(param, SERVER, buf, 256, 0, conf.timeouts[CHAIN_TO]) > 1)
199 				    break;
200 			    return 59;
201 			case 4:
202 			    if (sockgetlinebuf(param, SERVER, buf, 18, EOF, conf.timeouts[CHAIN_TO]) == 18)
203 				    break;
204 			    return 59;
205 			default:
206 			    return 58;
207 			}
208 			return 0;
209 		}
210 
211 		default:
212 
213 			return 30;
214 	}
215 }
216 
217 
handleredirect(struct clientparam * param,struct ace * acentry)218 int handleredirect(struct clientparam * param, struct ace * acentry){
219 	int connected = 0;
220 	int weight = 1000;
221 	int res;
222 	int done = 0;
223 	struct chain * cur;
224 	struct chain * redir = NULL;
225 	int r2;
226 
227 	if(param->remsock != INVALID_SOCKET) {
228 		return 0;
229 	}
230 	if(SAISNULL(&param->req) || !*SAPORT(&param->req)) {
231 		return 100;
232 	}
233 
234 	r2 = (myrand(param, sizeof(struct clientparam))%1000);
235 
236 	for(cur = acentry->chains; cur; cur=cur->next){
237 		if(((weight = weight - cur->weight) > r2)|| done) {
238 			if(weight <= 0) {
239 				weight += 1000;
240 				done = 0;
241 				r2 = (myrand(param, sizeof(struct clientparam))%1000);
242 			}
243 			continue;
244 		}
245 		param->redirected++;
246 		done = 1;
247 		if(weight <= 0) {
248 			weight += 1000;
249 			done = 0;
250 			r2 = (myrand(param, sizeof(struct clientparam))%1000);
251 		}
252 		if(!connected){
253 			if(cur->type == R_EXTIP){
254 				param->sinsl = cur->addr;
255 				if(SAISNULL(&param->sinsl))param->sinsl = param->sincr;
256 #ifndef NOIPV6
257 				else if(cur->cidr && *SAFAMILY(&param->sinsl) == AF_INET6){
258 					uint16_t c;
259 					int i;
260 
261 					for(i = 0; i < 8; i++){
262 						if(i==4)myrand(&param->sincr, sizeof(param->sincr));
263 						else if(i==6) myrand(&param->req, sizeof(param->req));
264 
265 						if(i*16 >= cur->cidr) ((uint16_t *)SAADDR(&param->sinsl))[i] |= rand();
266 						else if ((i+1)*16 >  cur->cidr){
267 							c = rand();
268 							c >>= (cur->cidr - (i*16));
269 							c |= ntohs(((uint16_t *)SAADDR(&param->sinsl))[i]);
270 							((uint16_t *)SAADDR(&param->sinsl))[i] = htons(c);
271 						}
272 					}
273 				}
274 #endif
275 				if(cur->next)continue;
276 				return 0;
277 			}
278 			else if(SAISNULL(&cur->addr) && !*SAPORT(&cur->addr)){
279 				if(cur->extuser){
280 					if(param->extusername)
281 						myfree(param->extusername);
282 					param->extusername = (unsigned char *)mystrdup((char *)((*cur->extuser == '*' && param->username)? param->username : cur->extuser));
283 					if(cur->extpass){
284 						if(param->extpassword)
285 							myfree(param->extpassword);
286 						param->extpassword = (unsigned char *)mystrdup((char *)((*cur->extuser == '*' && param->password)?param->password : cur->extpass));
287 					}
288 					if(*cur->extuser == '*' && !param->username) return 4;
289 				}
290 				switch(cur->type){
291 					case R_POP3:
292 						param->redirectfunc = pop3pchild;
293 						break;
294 					case R_FTP:
295 						param->redirectfunc = ftpprchild;
296 						break;
297 					case R_ADMIN:
298 						param->redirectfunc = adminchild;
299 						break;
300 					case R_SMTP:
301 						param->redirectfunc = smtppchild;
302 						break;
303 					default:
304 						param->redirectfunc = proxychild;
305 				}
306 				if(cur->next)continue;
307 				return 0;
308 			}
309 			else if(!*SAPORT(&cur->addr) && !SAISNULL(&cur->addr)) {
310 				unsigned short port = *SAPORT(&param->sinsr);
311 				param->sinsr = cur->addr;
312 				*SAPORT(&param->sinsr) = port;
313 			}
314 			else if(SAISNULL(&cur->addr) && *SAPORT(&cur->addr)) *SAPORT(&param->sinsr) = *SAPORT(&cur->addr);
315 			else {
316 				param->sinsr = cur->addr;
317 			}
318 
319 			if((res = alwaysauth(param))){
320 				return (res >= 10)? res : 60+res;
321 			}
322 		}
323 		else {
324 			res = (redir)?clientnegotiate(redir, param, (struct sockaddr *)&cur->addr, cur->exthost):0;
325 			if(res) return res;
326 		}
327 		redir = cur;
328 		param->redirtype = redir->type;
329 		if(redir->type == R_TCP || redir->type ==R_HTTP) {
330 			if(cur->extuser){
331 				if(*cur -> extuser == '*' && !param->username) return 4;
332 				if(param->extusername)
333 					myfree(param->extusername);
334 				param->extusername = (unsigned char *)mystrdup((char *)((*cur->extuser == '*' && param->username)? param->username : cur->extuser));
335 				if(cur->extpass){
336 					if(param->extpassword)
337 						myfree(param->extpassword);
338 					param->extpassword = (unsigned char *)mystrdup((char *)((*cur->extuser == '*' && param->password)?param->password : cur->extpass));
339 				}
340 			}
341 			return 0;
342 		}
343 		connected = 1;
344 	}
345 
346 	if(!connected || !redir) return 0;
347 	return clientnegotiate(redir, param, (struct sockaddr *)&param->req, param->hostname);
348 }
349 
IPInentry(struct sockaddr * sa,struct iplist * ipentry)350 int IPInentry(struct sockaddr *sa, struct iplist *ipentry){
351 	int addrlen;
352 	unsigned char *ip, *ipf, *ipt;
353 
354 
355 	if(!sa || ! ipentry || *SAFAMILY(sa) != ipentry->family) return 0;
356 
357 	ip = (unsigned char *)SAADDR(sa);
358 	ipf = (unsigned char *)&ipentry->ip_from;
359 	ipt = (unsigned char *)&ipentry->ip_to;
360 
361 
362 	addrlen = SAADDRLEN(sa);
363 
364 	if(memcmp(ip,ipf,addrlen) < 0 || memcmp(ip,ipt,addrlen) > 0) return 0;
365 	return 1;
366 
367 }
368 
ACLmatches(struct ace * acentry,struct clientparam * param)369 int ACLmatches(struct ace* acentry, struct clientparam * param){
370 	struct userlist * userentry;
371 	struct iplist *ipentry;
372 	struct portlist *portentry;
373 	struct period *periodentry;
374 	unsigned char * username;
375 	struct hostname * hstentry=NULL;
376 	int i;
377 	int match = 0;
378 
379 	username = param->username?param->username:(unsigned char *)"-";
380 	if(acentry->src) {
381 	 for(ipentry = acentry->src; ipentry; ipentry = ipentry->next)
382 		if(IPInentry((struct sockaddr *)&param->sincr, ipentry)) {
383 			break;
384 		}
385 	 if(!ipentry) return 0;
386 	}
387 	if((acentry->dst && !SAISNULL(&param->req)) || (acentry->dstnames && param->hostname)) {
388 	 for(ipentry = acentry->dst; ipentry; ipentry = ipentry->next)
389 		if(IPInentry((struct sockaddr *)&param->req, ipentry)) {
390 			break;
391 		}
392 	 if(!ipentry) {
393 		 if(acentry->dstnames && param->hostname){
394 			for(i=0; param->hostname[i]; i++){
395 				param->hostname[i] = tolower(param->hostname[i]);
396 			}
397 			while(i > 5 && param->hostname[i-1] == '.') param->hostname[i-1] = 0;
398 			for(hstentry = acentry->dstnames; hstentry; hstentry = hstentry->next){
399 				int lname, lhost;
400 				switch(hstentry->matchtype){
401 					case 0:
402 #ifndef _WIN32
403 					if(strcasestr((char *)param->hostname, (char *)hstentry->name)) match = 1;
404 #else
405 					if(strstr((char *)param->hostname, (char *)hstentry->name)) match = 1;
406 #endif
407 					break;
408 
409 					case 1:
410 					if(!strncasecmp((char *)param->hostname, (char *)hstentry->name, strlen((char *)hstentry->name)))
411 						match = 1;
412 					break;
413 
414 					case 2:
415 					lname = strlen((char *)hstentry->name);
416 					lhost = strlen((char *)param->hostname);
417 					if(lhost > lname){
418 						if(!strncasecmp((char *)param->hostname + (lhost - lname),
419 							(char *)hstentry->name,
420 							lname))
421 								match = 1;
422 					}
423 					break;
424 
425 					default:
426 					if(!strcasecmp((char *)param->hostname, (char *)hstentry->name)) match = 1;
427 					break;
428         			}
429 				if(match) break;
430 			}
431 		 }
432 	 }
433 	 if(!ipentry && !hstentry) return 0;
434 	}
435 	if(acentry->ports && *SAPORT(&param->req)) {
436 	 for (portentry = acentry->ports; portentry; portentry = portentry->next)
437 		if(ntohs(*SAPORT(&param->req)) >= portentry->startport &&
438 			   ntohs(*SAPORT(&param->req)) <= portentry->endport) {
439 			break;
440 		}
441 		if(!portentry) return 0;
442 	}
443 	if(acentry->wdays){
444 		if(!(acentry -> wdays & wday)) return 0;
445 	}
446 	if(acentry->periods){
447 	 int start_time = (int)(param->time_start - basetime);
448 	 for(periodentry = acentry->periods; periodentry; periodentry = periodentry -> next)
449 		if(start_time >= periodentry->fromtime && start_time < periodentry->totime){
450 			break;
451 		}
452 		if(!periodentry) return 0;
453 	}
454 	if(acentry->users){
455 	 for(userentry = acentry->users; userentry; userentry = userentry->next)
456 		if(!strcmp((char *)username, (char *)userentry->user)){
457 			break;
458 		}
459 	 if(!userentry) return 0;
460 	}
461 	if(acentry->operation) {
462 		if((acentry->operation & param->operation) != param->operation){
463 				 return 0;
464 		}
465 	}
466 	if(acentry->weight && (acentry->weight < param->weight)) return 0;
467 	return 1;
468 }
469 
470 
startconnlims(struct clientparam * param)471 int startconnlims (struct clientparam *param){
472 	struct connlim * ce;
473 	time_t delta;
474 	uint64_t rating;
475 	int ret = 0;
476 
477 	pthread_mutex_lock(&connlim_mutex);
478 	for(ce = conf.connlimiter; ce; ce = ce->next) {
479 		if(ACLmatches(ce->ace, param)){
480 			if(ce->ace->action == NOCONNLIM)break;
481 			if(!ce->period){
482 				if(ce->rate <= ce->rating) {
483 					ret = 1;
484 					break;
485 				}
486 				ce->rating++;
487 				continue;
488 			}
489 			delta = conf.time - ce->basetime;
490 			if(ce->period <= delta || ce->basetime > conf.time){
491 				ce->basetime = conf.time;
492 				ce->rating = 0x100000;
493 				continue;
494 			}
495 			rating = delta? ((ce->rating * (ce->period - delta)) / ce->period) + 0x100000 : ce->rating + 0x100000;
496 			if (rating > (ce->rate<<20)) {
497 				ret = 2;
498 				break;
499 			}
500 			ce->rating = rating;
501 			ce->basetime = conf.time;
502 		}
503 	}
504 	pthread_mutex_unlock(&connlim_mutex);
505 	return ret;
506 }
507 
stopconnlims(struct clientparam * param)508 void stopconnlims (struct clientparam *param){
509 	struct connlim * ce;
510 
511 	pthread_mutex_lock(&connlim_mutex);
512 	for(ce = conf.connlimiter; ce; ce = ce->next) {
513 		if(ACLmatches(ce->ace, param)){
514 			if(ce->ace->action == NOCONNLIM)break;
515 			if(!ce->period && ce->rating){
516 				ce->rating--;
517 				continue;
518 			}
519 		}
520 	}
521 	pthread_mutex_unlock(&connlim_mutex);
522 }
523 
initbandlims(struct clientparam * param)524 static void initbandlims (struct clientparam *param){
525 	struct bandlim * be;
526 	int i;
527 
528 	param->bandlimfunc = NULL;
529 	param->bandlims[0] = NULL;
530 	param->bandlimsout[0] = NULL;
531 	if(!conf.bandlimfunc || (!conf.bandlimiter && !conf.bandlimiterout)) return;
532 	for(i=0, be = conf.bandlimiter; be && i<MAXBANDLIMS; be = be->next) {
533 		if(ACLmatches(be->ace, param)){
534 			if(be->ace->action == NOBANDLIM) {
535 				break;
536 			}
537 			param->bandlims[i++] = be;
538 			param->bandlimfunc = conf.bandlimfunc;
539 		}
540 	}
541 	if(i<MAXBANDLIMS)param->bandlims[i] = NULL;
542 	for(i=0, be = conf.bandlimiterout; be && i<MAXBANDLIMS; be = be->next) {
543 		if(ACLmatches(be->ace, param)){
544 			if(be->ace->action == NOBANDLIM) {
545 				break;
546 			}
547 			param->bandlimsout[i++] = be;
548 			param->bandlimfunc = conf.bandlimfunc;
549 		}
550 	}
551 	if(i<MAXBANDLIMS)param->bandlimsout[i] = NULL;
552 	param->bandlimver = conf.bandlimver;
553 }
554 
bandlimitfunc(struct clientparam * param,unsigned nbytesin,unsigned nbytesout)555 unsigned bandlimitfunc(struct clientparam *param, unsigned nbytesin, unsigned nbytesout){
556 	unsigned sleeptime = 0, nsleeptime;
557 	time_t sec;
558 	unsigned msec;
559 	unsigned now;
560 	int i;
561 
562 #ifdef _WIN32
563 	struct timeb tb;
564 
565 	ftime(&tb);
566 	sec = (unsigned)tb.time;
567 	msec = (unsigned)tb.millitm*1000;
568 #else
569 	struct timeval tv;
570 	gettimeofday(&tv, NULL);
571 
572 	sec = tv.tv_sec;
573 	msec = tv.tv_usec;
574 #endif
575 
576 	if(!nbytesin && !nbytesout) return 0;
577 	pthread_mutex_lock(&bandlim_mutex);
578 	if(param->bandlimver != conf.bandlimver){
579 		initbandlims(param);
580 		param->bandlimver = conf.bandlimver;
581 	}
582 	for(i=0; nbytesin&& i<MAXBANDLIMS && param->bandlims[i]; i++){
583 		if( !param->bandlims[i]->basetime ||
584 			param->bandlims[i]->basetime > sec ||
585 			param->bandlims[i]->basetime < (sec - 120)
586 		  )
587 		{
588 			param->bandlims[i]->basetime = sec;
589 			param->bandlims[i]->nexttime = 0;
590 			continue;
591 		}
592 		now = (unsigned)((sec - param->bandlims[i]->basetime) * 1000000) + msec;
593 		nsleeptime = (param->bandlims[i]->nexttime > now)?
594 			param->bandlims[i]->nexttime - now : 0;
595 		sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
596 		param->bandlims[i]->basetime = sec;
597 		param->bandlims[i]->nexttime = msec + nsleeptime + ((nbytesin > 512)? ((nbytesin+32)/64)*(((64*8*1000000)/param->bandlims[i]->rate)) : ((nbytesin+1) * (8*1000000))/param->bandlims[i]->rate);
598 	}
599 	for(i=0; nbytesout && i<MAXBANDLIMS && param->bandlimsout[i]; i++){
600 		if( !param->bandlimsout[i]->basetime ||
601 			param->bandlimsout[i]->basetime > sec ||
602 			param->bandlimsout[i]->basetime < (sec - 120)
603 		  )
604 		{
605 			param->bandlimsout[i]->basetime = sec;
606 			param->bandlimsout[i]->nexttime = 0;
607 			continue;
608 		}
609 		now = (unsigned)((sec - param->bandlimsout[i]->basetime) * 1000000) + msec;
610 		nsleeptime = (param->bandlimsout[i]->nexttime > now)?
611 			param->bandlimsout[i]->nexttime - now : 0;
612 		sleeptime = (nsleeptime > sleeptime)? nsleeptime : sleeptime;
613 		param->bandlimsout[i]->basetime = sec;
614 		param->bandlimsout[i]->nexttime = msec + nsleeptime + ((nbytesout > 512)? ((nbytesout+32)/64)*((64*8*1000000)/param->bandlimsout[i]->rate) : ((nbytesout+1)* (8*1000000))/param->bandlimsout[i]->rate);
615 	}
616 	pthread_mutex_unlock(&bandlim_mutex);
617 	return sleeptime/1000;
618 }
619 
trafcountfunc(struct clientparam * param)620 void trafcountfunc(struct clientparam *param){
621 	struct trafcount * tc;
622 	int countout = 0;
623 
624 	pthread_mutex_lock(&tc_mutex);
625 	for(tc = conf.trafcounter; tc; tc = tc->next) {
626 		if(ACLmatches(tc->ace, param)){
627 
628 			if(tc->ace->action == NOCOUNTIN) {
629 				countout = 1;
630 				break;
631 			}
632 			if(tc->ace->action == NOCOUNTALL) break;
633 			if(tc->ace->action != COUNTIN && tc->ace->action != COUNTALL) {
634 				countout = 1;
635 				continue;
636 			}
637 			tc->traf64 += param->statssrv64;
638 			tc->updated = conf.time;
639 		}
640 	}
641 	if(countout) for(tc = conf.trafcounter; tc; tc = tc->next) {
642 		if(ACLmatches(tc->ace, param)){
643 			if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break;
644 			if(tc->ace->action != COUNTOUT && tc->ace->action != COUNTALL ) {
645 				continue;
646 			}
647 			tc->traf64 += param->statscli64;
648 			tc->updated = conf.time;
649 		}
650 	}
651 
652 	pthread_mutex_unlock(&tc_mutex);
653 }
654 
alwaysauth(struct clientparam * param)655 int alwaysauth(struct clientparam * param){
656 	int res;
657 	struct trafcount * tc;
658 	int countout = 0;
659 
660 
661 	if(conf.connlimiter && param->remsock == INVALID_SOCKET && startconnlims(param)) return 95;
662 	res = doconnect(param);
663 	if(!res){
664 		if(conf.bandlimfunc && (conf.bandlimiter||conf.bandlimiterout)){
665 			pthread_mutex_lock(&bandlim_mutex);
666 			initbandlims(param);
667 			pthread_mutex_unlock(&bandlim_mutex);
668 		}
669 
670 		if(conf.trafcountfunc && conf.trafcounter) {
671 			pthread_mutex_lock(&tc_mutex);
672 			for(tc = conf.trafcounter; tc; tc = tc->next) {
673 				if(tc->disabled) continue;
674 				if(ACLmatches(tc->ace, param)){
675 					if(tc->ace->action == NOCOUNTIN) {
676 						countout = 1;
677 						break;
678 					}
679 					if(tc->ace->action == NOCOUNTALL) break;
680 					if(tc->ace->action != COUNTIN) {
681 						countout = 1;
682 						if(tc->ace->action != COUNTALL) continue;
683 					}
684 					if(tc->traflim64 <= tc->traf64) return 10;
685 					param->trafcountfunc = conf.trafcountfunc;
686 					param->maxtrafin64 = tc->traflim64 - tc->traf64;
687 				}
688 			}
689 			if(countout)for(tc = conf.trafcounter; tc; tc = tc->next) {
690 				if(tc->disabled) continue;
691 				if(ACLmatches(tc->ace, param)){
692 					if(tc->ace->action == NOCOUNTOUT || tc->ace->action == NOCOUNTALL) break;
693 					if(tc->ace->action != COUNTOUT && tc->ace->action !=  COUNTALL) {
694 						continue;
695 					}
696 					if(tc->traflim64 <= tc->traf64) return 10;
697 					param->trafcountfunc = conf.trafcountfunc;
698 					param->maxtrafout64 = tc->traflim64 - tc->traf64;
699 				}
700 			}
701 			pthread_mutex_unlock(&tc_mutex);
702 		}
703 	}
704 	return res;
705 }
706 
checkACL(struct clientparam * param)707 int checkACL(struct clientparam * param){
708 	struct ace* acentry;
709 
710 	if(!param->srv->acl) {
711 		return 0;
712 	}
713 	for(acentry = param->srv->acl; acentry; acentry = acentry->next) {
714 		if(ACLmatches(acentry, param)) {
715 			param->nolog = acentry->nolog;
716 			param->weight = acentry->weight;
717 			if(acentry->action == 2) {
718 				struct ace dup;
719 				int res=60,i=0;
720 
721 				if(param->operation < 256 && !(param->operation & CONNECT)){
722 					continue;
723 				}
724 				if(param->redirected && acentry->chains && SAISNULL(&acentry->chains->addr) && !*SAPORT(&acentry->chains->addr)) {
725 					continue;
726 				}
727 				if(param->remsock != INVALID_SOCKET) {
728 					return 0;
729 				}
730 				for(; i < conf.parentretries; i++){
731 					dup = *acentry;
732 					res = handleredirect(param, &dup);
733 					if(!res) break;
734 					if(param->remsock != INVALID_SOCKET) so._closesocket(param->remsock);
735 					param->remsock = INVALID_SOCKET;
736 				}
737 				return res;
738 			}
739 			return acentry->action;
740 		}
741 	}
742 	return 3;
743 }
744 
745 struct authcache {
746 	char * username;
747 	char * password;
748 	time_t expires;
749 #ifndef NOIPV6
750 	struct sockaddr_in6 sa, sinsl;
751 #else
752 	struct sockaddr_in sa, sinsl;
753 #endif
754 	struct ace *acl;
755 	struct authcache *next;
756 } *authc = NULL;
757 
cacheauth(struct clientparam * param)758 int cacheauth(struct clientparam * param){
759 	struct authcache *ac, *last=NULL;
760 
761 	pthread_mutex_lock(&hash_mutex);
762 	for(ac = authc; ac; ){
763 		if(ac->expires <= conf.time){
764 			if(ac->username)myfree(ac->username);
765 			if(ac->password)myfree(ac->password);
766 			if(!last){
767 				authc = ac->next;
768 				myfree(ac);
769 				ac = authc;
770 			}
771 			else {
772 				last->next = ac->next;
773 				myfree(ac);
774 				ac = last->next;
775 			}
776 			continue;
777 
778 		}
779 		if(
780 		 (!(conf.authcachetype&2) || (param->username && ac->username && !strcmp(ac->username, (char *)param->username))) &&
781 		 (!(conf.authcachetype&4) || (ac->password && param->password && !strcmp(ac->password, (char *)param->password))) &&
782 		 (!(conf.authcachetype&16) || (ac->acl == param->srv->acl))
783 		) {
784 
785 			if(!(conf.authcachetype&1)
786 				|| ((*SAFAMILY(&ac->sa) ==  *SAFAMILY(&param->sincr)
787 				   && !memcmp(SAADDR(&ac->sa), SAADDR(&param->sincr), SAADDRLEN(&ac->sa))))){
788 
789 				if(conf.authcachetype&32) {
790 					param->sinsl = ac->sinsl;
791 				}
792 				if(param->username){
793 					myfree(param->username);
794 				}
795 				param->username = (unsigned char *)mystrdup(ac->username);
796 				pthread_mutex_unlock(&hash_mutex);
797 				return 0;
798 			}
799 			else if ((conf.authcachetype&1) && (conf.authcachetype&8)) {
800 				pthread_mutex_unlock(&hash_mutex);
801 				return 10;
802 			}
803 		}
804 		last = ac;
805 		ac = ac->next;
806 	}
807 
808 	pthread_mutex_unlock(&hash_mutex);
809 	return 4;
810 }
811 
doauth(struct clientparam * param)812 int doauth(struct clientparam * param){
813 	int res = 0;
814 	struct auth *authfuncs;
815 	struct authcache *ac;
816 	char * tmp;
817 	int ret = 0;
818 
819 	for(authfuncs=param->srv->authfuncs; authfuncs; authfuncs=authfuncs->next){
820 		res = authfuncs->authenticate?(*authfuncs->authenticate)(param):0;
821 		if(!res) {
822 			if(authfuncs->authorize &&
823 				(res = (*authfuncs->authorize)(param)))
824 					return res;
825 			if(conf.authcachetype && authfuncs->authenticate && authfuncs->authenticate != cacheauth && param->username && (!(conf.authcachetype&4) || (!param->pwtype && param->password))){
826 				pthread_mutex_lock(&hash_mutex);
827 				for(ac = authc; ac; ac = ac->next){
828 					if(
829 					   (!(conf.authcachetype&2) || !strcmp(ac->username, (char *)param->username)) &&
830 					   (!(conf.authcachetype&1) || (*SAFAMILY(&ac->sa) ==  *SAFAMILY(&param->sincr) && !memcmp(SAADDR(&ac->sa), SAADDR(&param->sincr), SAADDRLEN(&ac->sa))))  &&
831 					   (!(conf.authcachetype&4) || (ac->password && !strcmp(ac->password, (char *)param->password))) &&
832 					   (!(conf.authcachetype&16) || (ac->acl == param->srv->acl))
833 					) {
834 						ac->expires = conf.time + conf.authcachetime;
835 						if(strcmp(ac->username, (char *)param->username)){
836 							tmp = ac->username;
837 							ac->username = mystrdup((char *)param->username);
838 							myfree(tmp);
839 						}
840 						if((conf.authcachetype&4)){
841 							tmp = ac->password;
842 							ac->password = mystrdup((char *)param->password);
843 							myfree(tmp);
844 						}
845 						ac->sa = param->sincr;
846 						if(conf.authcachetype&32) {
847 							ac->sinsl = param-> sinsl;
848 							*SAPORT(&ac->sinsl) = 0;
849 						}
850 
851 						break;
852 					}
853 				}
854 				if(!ac){
855 					ac = myalloc(sizeof(struct authcache));
856 					if(ac){
857 						ac->expires = conf.time + conf.authcachetime;
858 						ac->username = param->username?mystrdup((char *)param->username):NULL;
859 						ac->sa = param->sincr;
860 						ac->password = NULL;
861 						if((conf.authcachetype&4) && param->password) ac->password = mystrdup((char *)param->password);
862 						if(conf.authcachetype&32) {
863 							ac->sinsl = param->sinsl;
864 							*SAPORT(&ac->sinsl) = 0;
865 						}
866 					}
867 					ac->next = authc;
868 					authc = ac;
869 				}
870 				pthread_mutex_unlock(&hash_mutex);
871 			}
872 			break;
873 		}
874 		if(res > ret) ret = res;
875 		if(ret > 9) return ret;
876 	}
877 	if(!res){
878 		return alwaysauth(param);
879 	}
880 
881 	return ret;
882 }
883 
884 
ipauth(struct clientparam * param)885 int ipauth(struct clientparam * param){
886 	int res;
887 	unsigned char *username;
888 	username = param->username;
889 	param->username = NULL;
890 	res = checkACL(param);
891 	param->username = username;
892 	return res;
893 }
894 
userauth(struct clientparam * param)895 int userauth(struct clientparam * param){
896 	return (param->username)? 0:4;
897 }
898 
dnsauth(struct clientparam * param)899 int dnsauth(struct clientparam * param){
900         char buf[128];
901 	char addr[16];
902 	char dig[]="0123456789abcdef";
903 
904 	unsigned u;
905 	int i;
906 
907 	if(*SAFAMILY(&param->sincr)!=AF_INET){
908 		char *s = buf;
909 		for(i=15; i>=0; i--){
910 			unsigned char c=((unsigned char *)SAADDR(&param->sincr))[i];
911 			*s++ = dig[(c&0xf)];
912 			*s++ = '.';
913 			*s++ = dig[(c>>4)];
914 			*s++ = '.';
915 		}
916 		sprintf(s, "ip6.arpa");
917 	}
918 	else {
919 		u = ntohl(*(unsigned long *)SAADDR(&param->sincr));
920 
921 		sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
922 			((u&0x000000FF)),
923 			((u&0x0000FF00)>>8),
924 			((u&0x00FF0000)>>16),
925 			((u&0xFF000000)>>24));
926 
927 	}
928 	if(!udpresolve(*SAFAMILY(&param->sincr), (unsigned char *)buf, (unsigned char *)addr, NULL, param, 1)) {
929 		return 3;
930 	}
931 	if(memcmp(SAADDR(&param->sincr), addr, SAADDRLEN(&param->sincr))) {
932 		return 3;
933 	}
934 
935 	return param->username? 0:3;
936 }
937 
strongauth(struct clientparam * param)938 int strongauth(struct clientparam * param){
939 	struct passwords * pwl;
940 	unsigned char buf[256];
941 
942 
943 	if(!param->username) return 4;
944 	pthread_mutex_lock(&pwl_mutex);
945 	for(pwl = conf.pwl; pwl; pwl=pwl->next){
946 		if(!strcmp((char *)pwl->user, (char *)param->username)) switch(pwl->pwtype) {
947 			case CL:
948 				if(!pwl->password || !*pwl->password){
949 					break;
950 				}
951 				else if (!param->pwtype && param->password && !strcmp((char *)param->password, (char *)pwl->password)){
952 					break;
953 				}
954 #ifndef NOCRYPT
955 				else if (param->pwtype == 2 && param->password) {
956 					ntpwdhash(buf, pwl->password, 0);
957 					mschap(buf, param->password, buf + 16);
958 					if(!memcmp(buf+16, param->password+8, 24)) {
959 						break;
960 					}
961 				}
962 #endif
963 				pthread_mutex_unlock(&pwl_mutex);
964 				return 6;
965 #ifndef NOCRYPT
966 			case CR:
967 				if(param->password && !param->pwtype && !strcmp((char *)pwl->password, (char *)mycrypt(param->password, pwl->password,buf))) {
968 					break;
969 				}
970 				pthread_mutex_unlock(&pwl_mutex);
971 				return 7;
972 			case NT:
973 				if(param->password && !param->pwtype && !memcmp(pwl->password, ntpwdhash(buf,param->password, 1), 32)) {
974 					break;
975 				}
976 				else if (param->pwtype == 2){
977 					fromhex(pwl->password, buf, 16);
978 					mschap(buf, param->password, buf + 16);
979 					if(!memcmp(buf + 16, param->password+8, 24)) {
980 						break;
981 					}
982 				}
983 				pthread_mutex_unlock(&pwl_mutex);
984 				return 8;
985 #endif
986 			default:
987 				pthread_mutex_unlock(&pwl_mutex);
988 				return 999;
989 		}
990 		else continue;
991 		pthread_mutex_unlock(&pwl_mutex);
992 		return 0;
993 	}
994 	pthread_mutex_unlock(&pwl_mutex);
995 	return 5;
996 }
997 
998 int radauth(struct clientparam * param);
999 
1000 struct auth authfuncs[] = {
1001 	{authfuncs+1, NULL, NULL, ""},
1002 	{authfuncs+2, ipauth, NULL, "iponly"},
1003 	{authfuncs+3, userauth, checkACL, "useronly"},
1004 	{authfuncs+4, dnsauth, checkACL, "dnsname"},
1005 	{authfuncs+5, strongauth, checkACL, "strong"},
1006 	{authfuncs+6, cacheauth, checkACL, "cache"},
1007 #ifndef NORADIUS
1008 #define AUTHOFFSET 1
1009 	{authfuncs+7, radauth, checkACL, "radius"},
1010 #else
1011 #define AUTHOFFSET 0
1012 #endif
1013 	{authfuncs+7+AUTHOFFSET, NULL, NULL, "none"},
1014 	{NULL, NULL, NULL, ""}
1015 };
1016 
1017 
1018 
1019 struct hashtable dns_table = {0, 4, {0,0,0,0}, NULL, NULL, NULL};
1020 struct hashtable dns6_table = {0, 16, {0,0,0,0}, NULL, NULL, NULL};
1021 
1022 
nametohash(const unsigned char * name,unsigned char * hash,unsigned char * rnd)1023 void nametohash(const unsigned char * name, unsigned char *hash, unsigned char *rnd){
1024 	unsigned i, j, k;
1025 	memcpy(hash, rnd, sizeof(unsigned)*4);
1026 	for(i=0, j=0, k=0; name[j]; j++){
1027 		hash[i] += (toupper(name[j]) - 32)+rnd[((toupper(name[j]))*29277+rnd[(k+j+i)%16]+k+j+i)%16];
1028 		if(++i == sizeof(unsigned)*4) {
1029 			i = 0;
1030 			k++;
1031 		}
1032 	}
1033 }
1034 
hashindex(struct hashtable * ht,const unsigned char * hash)1035 unsigned hashindex(struct hashtable *ht, const unsigned char* hash){
1036 	unsigned t1, t2, t3, t4;
1037 	t1 = *(unsigned *)hash;
1038 	t2 = *(unsigned *)(hash + sizeof(unsigned));
1039 	t3 = *(unsigned *)(hash + (2*sizeof(unsigned)));
1040 	t4 = *(unsigned *)(hash + (3*sizeof(unsigned)));
1041 	return (t1 + (t2 * 7) + (t3 * 17) + (t4 * 29) ) % (ht->hashsize >> 2);
1042 }
1043 
1044 
destroyhashtable(struct hashtable * ht)1045 void destroyhashtable(struct hashtable *ht){
1046 	pthread_mutex_lock(&hash_mutex);
1047 	if(ht->hashtable){
1048 		myfree(ht->hashtable);
1049 		ht->hashtable = NULL;
1050 	}
1051 	if(ht->hashvalues){
1052 		myfree(ht->hashvalues);
1053 		ht->hashvalues = NULL;
1054 	}
1055 	ht->hashsize = 0;
1056 	pthread_mutex_unlock(&hash_mutex);
1057 }
1058 
1059 #define hvalue(I) ((struct hashentry *)((char *)ht->hashvalues + (I)*(sizeof(struct hashentry) + ht->recsize - 4)))
inithashtable(struct hashtable * ht,unsigned nhashsize)1060 int inithashtable(struct hashtable *ht, unsigned nhashsize){
1061 	unsigned i;
1062 	clock_t c;
1063 
1064 
1065 #ifdef _WIN32
1066 	struct timeb tb;
1067 
1068 	ftime(&tb);
1069 
1070 #else
1071 	struct timeval tb;
1072 	struct timezone tz;
1073 	gettimeofday(&tb, &tz);
1074 #endif
1075 	c = clock();
1076 
1077 	if(nhashsize<4) return 1;
1078 	pthread_mutex_lock(&hash_mutex);
1079 	if(ht->hashtable){
1080 		myfree(ht->hashtable);
1081 		ht->hashtable = NULL;
1082 	}
1083 	if(ht->hashvalues){
1084 		myfree(ht->hashvalues);
1085 		ht->hashvalues = NULL;
1086 	}
1087 	ht->hashsize = 0;
1088 	if(!(ht->hashtable = myalloc((nhashsize>>2) *  sizeof(struct hashentry *)))){
1089 		pthread_mutex_unlock(&hash_mutex);
1090 		return 2;
1091 	}
1092 	if(!(ht->hashvalues = myalloc(nhashsize * (sizeof(struct hashentry) + (ht->recsize-4))))){
1093 		myfree(ht->hashtable);
1094 		ht->hashtable = NULL;
1095 		pthread_mutex_unlock(&hash_mutex);
1096 		return 3;
1097 	}
1098 	ht->hashsize = nhashsize;
1099 	ht->rnd[0] = myrand(&tb, sizeof(tb));
1100 	ht->rnd[1] = myrand(ht->hashtable, sizeof(ht->hashtable));
1101 	ht->rnd[2] = myrand(&c, sizeof(c));
1102 	ht->rnd[3] = myrand(ht->hashvalues,sizeof(ht->hashvalues));
1103 	memset(ht->hashtable, 0, (ht->hashsize>>2) * sizeof(struct hashentry *));
1104 	memset(ht->hashvalues, 0, ht->hashsize * (sizeof(struct hashentry) + ht->recsize -4));
1105 
1106 	for(i = 0; i< (ht->hashsize - 1); i++) {
1107 		hvalue(i)->next = hvalue(i+1);
1108 	}
1109 	ht->hashempty = ht->hashvalues;
1110 	pthread_mutex_unlock(&hash_mutex);
1111 	return 0;
1112 }
1113 
hashadd(struct hashtable * ht,const unsigned char * name,unsigned char * value,time_t expires)1114 void hashadd(struct hashtable *ht, const unsigned char* name, unsigned char* value, time_t expires){
1115         struct hashentry * hen, *he;
1116         struct hashentry ** hep;
1117 
1118 	unsigned index;
1119 
1120 	pthread_mutex_lock(&hash_mutex);
1121 	if(!ht||!value||!name||!ht->hashtable||!ht->hashempty) {
1122 		pthread_mutex_unlock(&hash_mutex);
1123 		return;
1124 	}
1125 	hen = ht->hashempty;
1126 	ht->hashempty = ht->hashempty->next;
1127 	nametohash(name, hen->hash, (unsigned char *)ht->rnd);
1128 	memcpy(hen->value, value, ht->recsize);
1129 	hen->expires = expires;
1130 	hen->next = NULL;
1131 	index = hashindex(ht, hen->hash);
1132 
1133 	for(hep = ht->hashtable + index; (he = *hep)!=NULL; ){
1134 		if(he->expires < conf.time || !memcmp(hen->hash, he->hash, sizeof(he->hash))) {
1135 			(*hep) = he->next;
1136 			he->expires = 0;
1137 			he->next = ht->hashempty;
1138 			ht->hashempty = he;
1139 		}
1140 		else hep=&(he->next);
1141 	}
1142 	hen->next = ht->hashtable[index];
1143 	ht->hashtable[index] = hen;
1144 	pthread_mutex_unlock(&hash_mutex);
1145 }
1146 
hashresolv(struct hashtable * ht,const unsigned char * name,unsigned char * value,unsigned * ttl)1147 unsigned long hashresolv(struct hashtable *ht, const unsigned char* name, unsigned char* value, unsigned *ttl){
1148 	unsigned char hash[sizeof(unsigned)*4];
1149         struct hashentry ** hep;
1150 	struct hashentry *he;
1151 	unsigned index;
1152 
1153 	pthread_mutex_lock(&hash_mutex);
1154 	if(!ht || !ht->hashtable || !name) {
1155 		pthread_mutex_unlock(&hash_mutex);
1156 		return 0;
1157 	}
1158 	nametohash(name, hash, (unsigned char *)ht->rnd);
1159 	index = hashindex(ht, hash);
1160 	for(hep = ht->hashtable + index; (he = *hep)!=NULL; ){
1161 		if(he->expires < conf.time) {
1162 			(*hep) = he->next;
1163 			he->expires = 0;
1164 			he->next = ht->hashempty;
1165 			ht->hashempty = he;
1166 		}
1167 		else if(!memcmp(hash, he->hash, sizeof(unsigned)*4)){
1168 			if(ttl) *ttl = (unsigned)(he->expires - conf.time);
1169 			memcpy(value, he->value, ht->recsize);
1170 			pthread_mutex_unlock(&hash_mutex);
1171 			return 1;
1172 		}
1173 		else hep=&(he->next);
1174 	}
1175 	pthread_mutex_unlock(&hash_mutex);
1176 	return 0;
1177 }
1178 
1179 struct nserver nservers[MAXNSERVERS] = {{{0},0}, {{0},0}, {{0},0}, {{0},0}, {{0},0}};
1180 struct nserver authnserver;
1181 
1182 
udpresolve(int af,unsigned char * name,unsigned char * value,unsigned * retttl,struct clientparam * param,int makeauth)1183 unsigned long udpresolve(int af, unsigned char * name, unsigned char * value, unsigned *retttl, struct clientparam* param, int makeauth){
1184 
1185 	int i,n;
1186 	unsigned long retval;
1187 
1188 	if((af == AF_INET) && (retval = hashresolv(&dns_table, name, value, retttl))) {
1189 		return retval;
1190 	}
1191 	if((af == AF_INET6) && (retval = hashresolv(&dns6_table, name, value, retttl))) {
1192 		return retval;
1193 	}
1194 	n = (makeauth && !SAISNULL(&authnserver.addr))? 1 : numservers;
1195 	for(i=0; i<n; i++){
1196 		unsigned short nq, na;
1197 		unsigned char b[4098], *buf, *s1, *s2;
1198 		int j, k, len, flen;
1199 		SOCKET sock;
1200 		unsigned ttl;
1201 #ifndef NOIPV6
1202 		struct sockaddr_in6 addr;
1203 		struct sockaddr_in6 *sinsr, *sinsl;
1204 #else
1205 		struct sockaddr_in addr;
1206 		struct sockaddr_in *sinsr, *sinsl;
1207 #endif
1208 		int usetcp = 0;
1209 		unsigned short serial = 1;
1210 
1211 		buf = b+2;
1212 
1213 		sinsl = (param && !makeauth)? &param->sinsl : &addr;
1214 		sinsr = (param && !makeauth)? &param->sinsr : &addr;
1215 		memset(sinsl, 0, sizeof(addr));
1216 		memset(sinsr, 0, sizeof(addr));
1217 
1218 
1219 		if(makeauth && !SAISNULL(&authnserver.addr)){
1220 			usetcp = authnserver.usetcp;
1221 			*SAFAMILY(sinsl) = *SAFAMILY(&authnserver.addr);
1222 		}
1223 		else {
1224 			usetcp = nservers[i].usetcp;
1225 			*SAFAMILY(sinsl) = *SAFAMILY(&nservers[i].addr);
1226 		}
1227 		if((sock=so._socket(SASOCK(sinsl), usetcp?SOCK_STREAM:SOCK_DGRAM, usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) break;
1228 		if(so._bind(sock,(struct sockaddr *)sinsl,SASIZE(sinsl))){
1229 			so._shutdown(sock, SHUT_RDWR);
1230 			so._closesocket(sock);
1231 			break;
1232 		}
1233 		if(makeauth && !SAISNULL(&authnserver.addr)){
1234 			*sinsr = authnserver.addr;
1235 		}
1236 		else {
1237 			*sinsr = nservers[i].addr;
1238 		}
1239 		if(usetcp){
1240 			if(connectwithpoll(sock,(struct sockaddr *)sinsr,SASIZE(sinsr),CONNECT_TO)) {
1241 				so._shutdown(sock, SHUT_RDWR);
1242 				so._closesocket(sock);
1243 				break;
1244 			}
1245 #ifdef TCP_NODELAY
1246 			{
1247 				int opt = 1;
1248 				setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
1249 			}
1250 #endif
1251 		}
1252 		len = (int)strlen((char *)name);
1253 
1254 		serial = myrand(name,len);
1255 		*(unsigned short*)buf = serial; /* query id */
1256 		buf[2] = 1; 			/* recursive */
1257 		buf[3] = 0;
1258 		buf[4] = 0;
1259 		buf[5] = 1;			/* 1 request */
1260 		buf[6] = buf[7] = 0;		/* no replies */
1261 		buf[8] = buf[9] = 0;		/* no ns count */
1262 		buf[10] = buf[11] = 0;		/* no additional */
1263 		if(len > 255) {
1264 			len = 255;
1265 		}
1266 		memcpy(buf + 13, name, len);
1267 		len += 13;
1268 		buf[len] = 0;
1269 		for(s2 = buf + 12; (s1 = (unsigned char *)strchr((char *)s2 + 1, '.')); s2 = s1)*s2 = (unsigned char)((s1 - s2) - 1);
1270 		*s2 = (len - (int)(s2 - buf)) - 1;
1271 		len++;
1272 		buf[len++] = 0;
1273 		buf[len++] = (makeauth == 1)? 0x0c : (af==AF_INET6? 0x1c:0x01);	/* PTR:host address */
1274 		buf[len++] = 0;
1275 		buf[len++] = 1;			/* INET */
1276 		if(usetcp){
1277 			buf-=2;
1278 			*(unsigned short*)buf = htons(len);
1279 			len+=2;
1280 		}
1281 
1282 		if(socksendto(sock, (struct sockaddr *)sinsr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
1283 			so._shutdown(sock, SHUT_RDWR);
1284 			so._closesocket(sock);
1285 			continue;
1286 		}
1287 		if(param) param->statscli64 += len;
1288 		len = sockrecvfrom(sock, (struct sockaddr *)sinsr, buf, 4096, conf.timeouts[DNS_TO]*1000);
1289 		so._shutdown(sock, SHUT_RDWR);
1290 		so._closesocket(sock);
1291 		if(len <= 13) {
1292 			continue;
1293 		}
1294 		if(param) param->statssrv64 += len;
1295 		if(usetcp){
1296 			unsigned short us;
1297 			us = ntohs(*(unsigned short*)buf);
1298 			len-=2;
1299 			buf+=2;
1300 			if(us > 4096 || us < len || (us > len && sockrecvfrom(sock, (struct sockaddr *)sinsr, buf+len, us-len, conf.timeouts[DNS_TO]*1000) != us-len)) {
1301 				continue;
1302 			}
1303 		}
1304 		if(*(unsigned short *)buf != serial)continue;
1305 		if((na = buf[7] + (((unsigned short)buf[6])<<8)) < 1) {
1306 			return 0;
1307 		}
1308 		nq = buf[5] + (((unsigned short)buf[4])<<8);
1309 		if (nq != 1) {
1310 			continue;			/* we did only 1 request */
1311 		}
1312 		for(k = 13; k<len && buf[k]; k++) {
1313 		}
1314 		k++;
1315 		if( (k+4) >= len) {
1316 			continue;
1317 		}
1318 		k += 4;
1319 		if(na > 255) na = 255;			/* somebody is very evil */
1320 		for (j = 0; j < na; j++) {		/* now there should be answers */
1321 			while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
1322 			if(!buf[k]) k--;
1323 			if((k+(af == AF_INET6?28:16)) > len) {
1324 				break;
1325 			}
1326 			flen = buf[k+11] + (((unsigned short)buf[k+10])<<8);
1327 			if((k+12+flen) > len) {
1328 				break;
1329 			}
1330 			if(makeauth != 1){
1331 				if(buf[k+2] != 0 || buf[k+3] != (af == AF_INET6?0x1c:0x1) || flen != (af == AF_INET6?16:4)) {
1332 					k+= (12 + flen);
1333 					continue; 		/* we need A IPv4 */
1334 				}
1335 				ttl = ntohl(*(unsigned long *)(buf + k + 6));
1336 				memcpy(value, buf + k + 12, af == AF_INET6? 16:4);
1337 				if(ttl < 60 || ttl > (3600*12)) ttl = 300;
1338 				hashadd(af == AF_INET6?&dns6_table:&dns_table, name, value, conf.time+ttl);
1339 				if(retttl) *retttl = ttl;
1340 				return 1;
1341 			}
1342 			else {
1343 
1344 				if(buf[k+2] != 0 || buf[k+3] != 0x0c) {
1345 					k+= (12 + flen);
1346 					continue; 		/* we need A PTR */
1347 				}
1348 				for (s2 = buf + k + 12; s2 < (buf + k + 12 + len) && *s2; ){
1349 					s1 = s2 + ((unsigned)*s2) + 1;
1350 					*s2 = '.';
1351 					s2 = s1;
1352 				}
1353 				*s2 = 0;
1354 				if(param->username)myfree(param->username);
1355 				param->username = (unsigned char *)mystrdup ((char *)buf + k + 13);
1356 
1357 				return udpresolve(af,param->username, value, NULL, NULL, 2);
1358 			}
1359 		}
1360 	}
1361 	return 0;
1362 }
1363 
myresolver(int af,unsigned char * name,unsigned char * value)1364 unsigned long myresolver(int af, unsigned char * name, unsigned char * value){
1365  return udpresolve(af, name, value, NULL, NULL, 0);
1366 }
1367 
fakeresolver(int af,unsigned char * name,unsigned char * value)1368 unsigned long fakeresolver (int af, unsigned char *name, unsigned char * value){
1369  memset(value, 0, af == AF_INET6? 16 : 4);
1370  if(af == AF_INET6){
1371 	memset(value, 0, 16);
1372 	value[15] = 2;
1373  }
1374  else {
1375 	value[0] = 127;
1376 	value[1] = 0;
1377 	value[2] = 0;
1378 	value[3] = 2;
1379  }
1380  return 1;
1381 }
1382 
1383 #ifndef NOODBC
1384 
1385 SQLHENV  henv = NULL;
1386 SQLHSTMT hstmt = NULL;
1387 SQLHDBC hdbc = NULL;
1388 char * sqlstring = NULL;
1389 
1390 
close_sql()1391 void close_sql(){
1392 	if(hstmt) {
1393 		SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
1394 		hstmt = NULL;
1395 	}
1396 	if(hdbc){
1397 		SQLDisconnect(hdbc);
1398 		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
1399 		hdbc = NULL;
1400 	}
1401 	if(henv) {
1402 		SQLFreeHandle(SQL_HANDLE_ENV, henv);
1403 		henv = NULL;
1404 	}
1405 }
1406 
1407 int attempt = 0;
1408 time_t attempt_time = 0;
1409 
init_sql(char * s)1410 int init_sql(char * s){
1411 	SQLRETURN  retcode;
1412 	char * datasource;
1413 	char * username;
1414 	char * password;
1415 	char * string;
1416 
1417 	if(!s) return 0;
1418 	if(!sqlstring || strcmp(sqlstring, s)){
1419 		string = sqlstring;
1420 		sqlstring=mystrdup(s);
1421 		if(string)myfree(string);
1422 	}
1423 
1424 	if(hstmt || hdbc || henv) close_sql();
1425 	attempt++;
1426 	attempt_time = time(0);
1427 	if(!henv){
1428 		retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
1429 		if (!henv || (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)){
1430 			henv = NULL;
1431 			return 0;
1432 		}
1433 		retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
1434 
1435 		if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
1436 			return 0;
1437 		}
1438 	}
1439 	if(!hdbc){
1440 		retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
1441 		if (!hdbc || (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)) {
1442 			hdbc = NULL;
1443 			SQLFreeHandle(SQL_HANDLE_ENV, henv);
1444 			henv = NULL;
1445 			return 0;
1446 		}
1447 	       	SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (void*)15, 0);
1448 	}
1449 	string = mystrdup(sqlstring);
1450 	if(!string) return 0;
1451 	datasource = strtok(string, ",");
1452 	username = strtok(NULL, ",");
1453 	password = strtok(NULL, ",");
1454 
1455 
1456          /* Connect to data source */
1457         retcode = SQLConnect(hdbc, (SQLCHAR*) datasource, (SQLSMALLINT)strlen(datasource),
1458                 (SQLCHAR*) username, (SQLSMALLINT)((username)?strlen(username):0),
1459                 (SQLCHAR*) password, (SQLSMALLINT)((password)?strlen(password):0));
1460 
1461 	myfree(string);
1462 	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO){
1463 		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
1464 		hdbc = NULL;
1465 		SQLFreeHandle(SQL_HANDLE_ENV, henv);
1466 		henv = NULL;
1467 		return 0;
1468 	}
1469         retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
1470         if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO){
1471 		close_sql();
1472 		return 0;
1473 	}
1474 	return 1;
1475 }
1476 
sqlerr(char * buf)1477 void sqlerr (char *buf){
1478 	if(conf.stdlog){
1479 		fprintf(conf.stdlog, "%s\n", buf);
1480 		fflush(conf.stdlog);
1481 	}
1482 	pthread_mutex_unlock(&log_mutex);
1483 }
1484 
1485 unsigned char statbuf[8192];
1486 
logsql(struct clientparam * param,const unsigned char * s)1487 void logsql(struct clientparam * param, const unsigned char *s) {
1488 	SQLRETURN ret;
1489 	int len;
1490 
1491 
1492 	if(param->nolog) return;
1493 	pthread_mutex_lock(&log_mutex);
1494 	len = dobuf(param, statbuf, s, (unsigned char *)"\'");
1495 
1496 	if(attempt > 5){
1497 		time_t t;
1498 
1499 		t = time(0);
1500 		if (t - attempt_time < 180){
1501 			sqlerr((char *)statbuf);
1502 			return;
1503 		}
1504 	}
1505 	if(!hstmt){
1506 		if(!init_sql(sqlstring)) {
1507 			sqlerr((char *)statbuf);
1508 			return;
1509 		}
1510 	}
1511 	if(hstmt){
1512 		ret = SQLExecDirect(hstmt, (SQLCHAR *)statbuf, (SQLINTEGER)len);
1513 		if(ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO){
1514 			close_sql();
1515 			if(!init_sql(sqlstring)){
1516 				sqlerr((char *)statbuf);
1517 				return;
1518 			}
1519 			if(hstmt) {
1520 				ret = SQLExecDirect(hstmt, (SQLCHAR *)statbuf, (SQLINTEGER)len);
1521 				if(ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO){
1522 					sqlerr((char *)statbuf);
1523 					return;
1524 				}
1525 				attempt = 0;
1526 			}
1527 		}
1528 		attempt = 0;
1529 	}
1530 	pthread_mutex_unlock(&log_mutex);
1531 }
1532 
1533 #endif
1534