str_util.c 17.3 KB
Newer Older
1
/* Synchronet string utility routines */
2 3 4 5 6 7 8

/* $Id$ */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
9
 * Copyright Rob Swindell - http://www.synchro.net/copyright.html			*
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 *																			*
 * 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.					*
 * See the GNU General Public License for more details: gpl.txt or			*
 * http://www.fsf.org/copyleft/gpl.html										*
 *																			*
 * Anonymous FTP access to the most recent released source is available at	*
 * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net	*
 *																			*
 * Anonymous CVS access to the development source and modification history	*
 * is available at cvs.synchro.net:/cvsroot/sbbs, example:					*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login			*
 *     (just hit return, no password is necessary)							*
 * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src		*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * You are encouraged to submit any modifications (preferably in Unix diff	*
 * format) via e-mail to mods@synchro.net									*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

#include "sbbs.h"

/****************************************************************************/
39 40
/* For all the functions that take a 'dest' argument, pass NULL to have the	*/
/* function malloc the buffer for you and return it.						*/
41
/****************************************************************************/
42 43 44 45 46

/****************************************************************************/
/* Removes ctrl-a codes from the string 'str'								*/
/****************************************************************************/
char* DLLCALL remove_ctrl_a(const char *str, char *dest)
47
{
48
	int	i,j;
49

50
	if(dest==NULL && (dest=strdup(str))==NULL)
51 52 53
		return NULL;
	for(i=j=0;str[i];i++) {
		if(str[i]==CTRL_A) {
54
			i++;
55 56
			if(str[i]==0 || str[i]=='Z')	/* EOF */
				break;
57 58 59 60
			/* convert non-destructive backspace to a destructive backspace */
			if(str[i]=='<' && j)	
				j--;
		}
61
		else dest[j++]=str[i]; 
62
	}
63
	dest[j]=0;
64
	return dest;
65 66
}

67
char* DLLCALL strip_ctrl(const char *str, char* dest)
68
{
69
	int	i,j;
70

71
	if(dest==NULL && (dest=strdup(str))==NULL)
72 73 74
		return NULL;
	for(i=j=0;str[i];i++) {
		if(str[i]==CTRL_A) {
75
			i++;
76 77
			if(str[i]==0 || str[i]=='Z')	/* EOF */
				break;
78 79 80 81
			/* convert non-destructive backspace to a destructive backspace */
			if(str[i]=='<' && j)	
				j--;
		}
82
		else if((uchar)str[i]>=' ')
83
			dest[j++]=str[i];
84
	}
85
	dest[j]=0;
86
	return dest;
87 88
}

89
char* DLLCALL strip_exascii(const char *str, char* dest)
90
{
91
	int	i,j;
92

93
	if(dest==NULL && (dest=strdup(str))==NULL)
94 95
		return NULL;
	for(i=j=0;str[i];i++)
96
		if(!(str[i]&0x80))
97 98
			dest[j++]=str[i];
	dest[j]=0;
99
	return dest;
100
}
101

102 103 104 105 106 107 108
char* DLLCALL strip_space(const char *str, char* dest)
{
	int	i,j;

	if(dest==NULL && (dest=strdup(str))==NULL)
		return NULL;
	for(i=j=0;str[i];i++)
109
		if(!isspace((unsigned char)str[i]))
110 111 112 113 114
			dest[j++]=str[i];
	dest[j]=0;
	return dest;
}

115
char* DLLCALL prep_file_desc(const char *str, char* dest)
116
{
117
	int	i,j;
118

119
	if(dest==NULL && (dest=strdup(str))==NULL)
120
		return NULL;
121
	for(i=j=0;str[i];i++)
122
		if(str[i]==CTRL_A && str[i+1]!=0) {
123
			i++;
124 125
			if(str[i]==0 || str[i]=='Z')	/* EOF */
				break;
126 127 128 129
			/* convert non-destructive backspace to a destructive backspace */
			if(str[i]=='<' && j)	
				j--;
		}
130
		else if(j && str[i]<=' ' && dest[j-1]==' ')
131
			continue;
132
		else if(i && !isalnum((unsigned char)str[i]) && str[i]==str[i-1])
133
			continue;
134
		else if((uchar)str[i]>=' ')
135
			dest[j++]=str[i];
136
		else if(str[i]==TAB || (str[i]==CR && str[i+1]==LF))
137 138
			dest[j++]=' ';
	dest[j]=0;
139
	return dest;
140 141
}

142
/****************************************************************************/
143
/* Pattern matching string search of 'insearchof' in 'string'.				*/
144
/****************************************************************************/
145
BOOL DLLCALL findstr_in_string(const char* insearchof, char* string)
146
{
147
	char*	p;
rswindell's avatar
rswindell committed
148
	char	str[256];
149 150 151
	char	search[81];
	int		c;
	int		i;
152
	BOOL	found=FALSE;
153

154
	if(string==NULL || insearchof==NULL)
rswindell's avatar
rswindell committed
155
		return(FALSE);
156 157 158

	SAFECOPY(search,insearchof);
	strupr(search);
159
	SAFECOPY(str,string);
160

161
	p=str;	
162
//	SKIP_WHITESPACE(p);
163

164 165
	if(*p==';')		/* comment */
		return(FALSE);
166

167 168 169 170
	if(*p=='!')	{	/* !match */
		found=TRUE;
		p++;
	}
171

172 173 174 175 176 177 178 179 180 181
	truncsp(p);
	c=strlen(p);
	if(c) {
		c--;
		strupr(p);
		if(p[c]=='~') {
			p[c]=0;
			if(strstr(search,p))
				found=!found; 
		}
182

183 184 185 186
		else if(p[c]=='^' || p[c]=='*') {
			p[c]=0;
			if(!strncmp(p,search,c))
				found=!found; 
187 188
		}

189 190 191 192 193
		else if(p[0]=='*') {
			i=strlen(search);
			if(i<c)
				return(found);
			if(!strncmp(p+1,search+(i-c),c))
194
				found=!found; 
195 196 197 198 199 200 201 202
		}

		else if(!strcmp(p,search))
			found=!found; 
	} 
	return(found);
}

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
static uint32_t encode_ipv4_address(unsigned int byte[])
{
	if(byte[0] > 0xff || byte[1] > 0xff || byte[2] > 0xff || byte[3] > 0xff)
		return 0;
	return (byte[0]<<24) | (byte[1]<<16) | (byte[2]<<8) | byte[3];
}

static uint32_t parse_ipv4_address(const char* str)
{
	unsigned int byte[4];

	if(sscanf(str, "%u.%u.%u.%u", &byte[0], &byte[1], &byte[2], &byte[3]) != 4)
		return 0;
	return encode_ipv4_address(byte);
}

static uint32_t parse_cidr(const char* p, unsigned* subnet)
{
	unsigned int byte[4];

	if(*p == '!')
		p++;

	*subnet = 0;
	if(sscanf(p, "%u.%u.%u.%u/%u", &byte[0], &byte[1], &byte[2], &byte[3], subnet) != 5 || *subnet > 32)
		return 0;
	return encode_ipv4_address(byte);
}

static BOOL is_cidr_match(const char *p, uint32_t ip_addr, uint32_t cidr, unsigned subnet)
{
	BOOL	match = FALSE;

	if(*p == '!')
		match = TRUE;

	if(((ip_addr ^ cidr) >> (32-subnet)) == 0)
		match = !match;

	return match;
}

245
/****************************************************************************/
rswindell's avatar
rswindell committed
246
/* Pattern matching string search of 'insearchof' in 'list'.				*/
247 248 249 250 251
/****************************************************************************/
BOOL DLLCALL findstr_in_list(const char* insearchof, str_list_t list)
{
	size_t	index;
	BOOL	found=FALSE;
252
	char*	p;
253 254
	uint32_t ip_addr, cidr;
	unsigned subnet;
255 256

	if(list==NULL || insearchof==NULL)
257 258
		return FALSE;
	ip_addr = parse_ipv4_address(insearchof);
259 260
	for(index=0; list[index]!=NULL; index++) {
		p=list[index];
261
//		SKIP_WHITESPACE(p);
262 263 264 265 266
		if(ip_addr != 0 && (cidr = parse_cidr(p, &subnet)) != 0)
			found = is_cidr_match(p, ip_addr, cidr, subnet);
		else
			found = findstr_in_string(insearchof,p);
		if(found != (*p=='!'))
267 268
			break;
	}
269
	return found;
rswindell's avatar
rswindell committed
270 271 272 273 274 275 276
}

/****************************************************************************/
/* Pattern matching string search of 'insearchof' in 'fname'.				*/
/****************************************************************************/
BOOL DLLCALL findstr(const char* insearchof, const char* fname)
{
277 278
	char		str[256];
	BOOL		found=FALSE;
rswindell's avatar
rswindell committed
279
	FILE*		fp;
280 281
	uint32_t	ip_addr, cidr;
	unsigned	subnet;
rswindell's avatar
rswindell committed
282

283
	if(insearchof==NULL || fname==NULL)
284
		return FALSE;
rswindell's avatar
rswindell committed
285 286

	if((fp=fopen(fname,"r"))==NULL)
287
		return FALSE; 
rswindell's avatar
rswindell committed
288

289
	ip_addr = parse_ipv4_address(insearchof);
290 291 292
	while(!feof(fp) && !ferror(fp) && !found) {
		if(!fgets(str,sizeof(str),fp))
			break;
293 294 295 296 297
		char* p = str;
		SKIP_WHITESPACE(p);
		c_unescape_str(p);
		if(ip_addr !=0 && (cidr = parse_cidr(p, &subnet)) != 0)
			found = is_cidr_match(p, ip_addr, cidr, subnet);
298
		else
299
			found = findstr_in_string(insearchof, p);
300
	}
rswindell's avatar
rswindell committed
301

302
	fclose(fp);
303
	return found;
304 305 306 307 308 309
}

/****************************************************************************/
/* Searches the file <name>.can in the TEXT directory for matches			*/
/* Returns TRUE if found in list, FALSE if not.								*/
/****************************************************************************/
rswindell's avatar
rswindell committed
310
BOOL DLLCALL trashcan(scfg_t* cfg, const char* insearchof, const char* name)
311 312 313
{
	char fname[MAX_PATH+1];

rswindell's avatar
rswindell committed
314 315 316 317 318 319 320 321 322 323
	return(findstr(insearchof,trashcan_fname(cfg,name,fname,sizeof(fname))));
}

/****************************************************************************/
char* DLLCALL trashcan_fname(scfg_t* cfg, const char* name, char* fname, size_t maxlen)
{
	safe_snprintf(fname,maxlen,"%s%s.can",cfg->text_dir,name);
	return fname;
}

324 325 326 327 328 329
static char* process_findstr_item(size_t index, char *str, void* cbdata)
{
	SKIP_WHITESPACE(str);
	return c_unescape_str(str);
}

rswindell's avatar
rswindell committed
330
/****************************************************************************/
331
str_list_t DLLCALL findstr_list(const char* fname)
rswindell's avatar
rswindell committed
332 333 334 335
{
	FILE*	fp;
	str_list_t	list;

336
	if((fp=fopen(fname,"r"))==NULL)
rswindell's avatar
rswindell committed
337 338
		return NULL;

339 340
	list=strListReadFile(fp, NULL, /* Max line length: */255);
	strListModifyEach(list, process_findstr_item, /* cbdata: */NULL);
rswindell's avatar
rswindell committed
341 342 343 344

	fclose(fp);

	return list;
345
}
346

347 348 349 350 351 352 353 354
/****************************************************************************/
str_list_t DLLCALL trashcan_list(scfg_t* cfg, const char* name)
{
	char	fname[MAX_PATH+1];

	return findstr_list(trashcan_fname(cfg, name, fname, sizeof(fname)));
}

355
/****************************************************************************/
356
/* Returns the printed columns from 'str' accounting for Ctrl-A codes		*/
357
/****************************************************************************/
358
size_t bstrlen(const char *str)
359
{
360
	size_t i=0;
361 362

	while(*str) {
363
		if(*str==CTRL_A) {
364
			str++;
365 366
			if(*str==0 || *str=='Z')	/* EOF */
				break;
367 368 369 370 371
			if(*str=='[')
				i=0;
			else if(*str=='<' && i)
				i--;
		} else
372 373
			i++;
		if(!(*str)) break;
374 375
		str++; 
	}
376 377 378 379 380 381 382
	return(i);
}

/****************************************************************************/
/* Returns in 'string' a character representation of the number in l with   */
/* commas.																	*/
/****************************************************************************/
383
char* DLLCALL ultoac(ulong l, char *string)
384 385
{
	char str[256];
386
	int i,j,k;
387 388 389 390 391 392 393 394

	ultoa(l,str,10);
	i=strlen(str)-1;
	j=i/3+1+i;
	string[j--]=0;
	for(k=1;i>-1;k++) {
		string[j--]=str[i--];
		if(j>0 && !(k%3))
395 396
			string[j--]=','; 
	}
397 398 399
	return(string);
}

400
/****************************************************************************/
rswindell's avatar
rswindell committed
401
/* Truncate string at first occurrence of char in specified character set	*/
402
/****************************************************************************/
403
char* DLLCALL truncstr(char* str, const char* set)
404 405 406 407
{
	char* p;

	p=strpbrk(str,set);
408
	if(p!=NULL && *p!=0)
409 410 411 412 413
		*p=0;

	return(p);
}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
/****************************************************************************/
/* rot13 encoder/decoder - courtesy of Mike Acar							*/
/****************************************************************************/
char* DLLCALL rot13(char* str)
{
	char ch, cap;
	char* p;
  
	p=str;
	while((ch=*p)!=0) {
		cap = ch & 32;
		ch &= ~cap;
		ch = ((ch >= 'A') && (ch <= 'Z') ? ((ch - 'A' + 13) % 26 + 'A') : ch) | cap;
		*(p++)=ch;
    }

	return(str);
}

433 434 435
/****************************************************************************/
/* Puts a backslash on path strings if not just a drive letter and colon	*/
/****************************************************************************/
436
char* backslashcolon(char *str)
437 438 439 440
{
    int i;

	i=strlen(str);
441 442
	if(i && !IS_PATH_DELIM(str[i-1]) && str[i-1]!=':') {
		str[i]=PATH_DELIM; 
rswindell's avatar
rswindell committed
443 444
		str[i+1]=0; 
	}
445 446

	return str;
447 448 449
}

/****************************************************************************/
rswindell's avatar
rswindell committed
450
/* Compares pointers to pointers to char. Used in conjunction with qsort()  */
451
/****************************************************************************/
452
int pstrcmp(const char **str1, const char **str2)
453 454 455 456 457 458 459
{
	return(strcmp(*str1,*str2));
}

/****************************************************************************/
/* Returns the number of characters that are the same between str1 and str2 */
/****************************************************************************/
460
int strsame(const char *str1, const char *str2)
461 462 463 464 465 466 467 468
{
	int i,j=0;

	for(i=0;str1[i];i++)
		if(str1[i]==str2[i]) j++;
	return(j);
}

469

470 471 472 473 474 475 476 477 478 479 480 481
/****************************************************************************/
/* Returns string for 2 digit hex+ numbers up to 575						*/
/****************************************************************************/
char *hexplus(uint num, char *str)
{
	sprintf(str,"%03x",num);
	str[0]=num/0x100 ? 'f'+(num/0x10)-0xf : str[1];
	str[1]=str[2];
	str[2]=0;
	return(str);
}

482 483 484 485
/****************************************************************************/
/* Converts an ASCII Hex string into an ulong                               */
/* by Steve Deppe (Ille Homine Albe)										*/
/****************************************************************************/
486
ulong ahtoul(const char *str)
487 488 489 490 491 492 493 494
{
    ulong l,val=0;

	while((l=(*str++)|0x20)!=0x20)
		val=(l&0xf)+(l>>6&1)*9+val*16;
	return(val);
}

495 496 497
/****************************************************************************/
/* Converts hex-plus string to integer										*/
/****************************************************************************/
498
uint hptoi(const char *str)
499 500 501 502 503 504 505 506 507 508 509 510
{
	char tmp[128];
	uint i;

	if(!str[1] || toupper(str[0])<='F')
		return(ahtoul(str));
	strcpy(tmp,str);
	tmp[0]='F';
	i=ahtoul(tmp)+((toupper(str[0])-'F')*0x10);
	return(i);
}

511
/****************************************************************************/
512
/* Returns TRUE if a is a valid ctrl-a "attribute" code, FALSE if it isn't. */
513
/****************************************************************************/
514
BOOL DLLCALL valid_ctrl_a_attr(char a)
515 516
{
	switch(toupper(a)) {
517 518
		case '+':	/* push attr	*/
		case '-':   /* pop attr		*/
519 520 521 522 523
		case '_':   /* clear        */
		case 'B':   /* blue     fg  */
		case 'C':   /* cyan     fg  */
		case 'G':   /* green    fg  */
		case 'H':   /* high     fg  */
rswindell's avatar
rswindell committed
524
		case 'E':	/* high		bg	*/
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
		case 'I':   /* blink        */
		case 'K':   /* black    fg  */
		case 'M':   /* magenta  fg  */
		case 'N':   /* normal       */
		case 'R':   /* red      fg  */
		case 'W':   /* white    fg  */
		case 'Y':   /* yellow   fg  */
		case '0':   /* black    bg  */
		case '1':   /* red      bg  */
		case '2':   /* green    bg  */
		case '3':   /* brown    bg  */
		case '4':   /* blue     bg  */
		case '5':   /* magenta  bg  */
		case '6':   /* cyan     bg  */
		case '7':   /* white    bg  */
			return(TRUE); 
	}
	return(FALSE);
}

545 546 547 548 549 550 551 552 553 554 555 556 557 558
/****************************************************************************/
/* Returns TRUE if a is a valid QWKnet compatible Ctrl-A code, else FALSE	*/
/****************************************************************************/
BOOL DLLCALL valid_ctrl_a_code(char a)
{
	switch(toupper(a)) {
		case 'P':		/* Pause */
		case 'L':		/* CLS */
		case ',':		/* 100ms delay */
			return TRUE;
	}
	return valid_ctrl_a_attr(a);
}

559
/****************************************************************************/
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
/****************************************************************************/
char DLLCALL ctrl_a_to_ascii_char(char a)
{
	switch(toupper(a)) {
		case 'L':   /* cls          */
			return FF;
		case '<':	/* backspace	*/
			return '\b';
		case '[':	/* CR			*/
			return '\r';
		case ']':	/* LF			*/
			return '\n';
	}
	return 0;
}

/****************************************************************************/
/* Strips invalid Ctrl-Ax "attribute" sequences from str                    */
578 579
/* Returns number of ^A's in line                                           */
/****************************************************************************/
580
size_t DLLCALL strip_invalid_attr(char *str)
581
{
582
    char*	dest;
583
    size_t	a,c,d;
584

585
	dest=str;
586 587
	for(a=c=d=0;str[c];c++) {
		if(str[c]==CTRL_A) {
588
			a++;
589 590
			if(str[c+1]==0)
				break;
591
			if(!valid_ctrl_a_attr(str[c+1])) {
592 593 594
				/* convert non-destructive backspace to a destructive backspace */
				if(str[c+1]=='<' && d)	
					d--;
595 596
				c++;
				continue; 
597
			}
598
		}
599
		dest[d++]=str[c]; 
600
	}
601
	dest[d]=0;
602 603
	return(a);
}
604

605 606 607 608 609 610 611
/****************************************************************************/
/****************************************************************************/
char DLLCALL exascii_to_ascii_char(uchar ch)
{
	/* Seven bit table for EXASCII to ASCII conversion */
	const char *sbtbl="CUeaaaaceeeiiiAAEaAooouuyOUcLYRfaiounNao?--24!<>"
			"###||||++||++++++--|-+||++--|-+----++++++++##[]#"
612
			"abrpEout*ono%0ENE+><rj%=o*.+n2* ";
613 614 615 616 617 618

	if(ch&0x80)
		return sbtbl[ch^0x80];
	return ch;
}

619 620 621 622 623 624 625 626 627
BOOL DLLCALL str_is_ascii(const char* str)
{
	for(const char* p = str; *p != 0; p++) {
		if(*p < 0)
			return FALSE;
	}
	return TRUE;
}

628 629 630 631 632
/****************************************************************************/
/* Convert string from IBM extended ASCII to just ASCII						*/
/****************************************************************************/
char* DLLCALL ascii_str(uchar* str)
{
deuce's avatar
deuce committed
633
	uchar*	p=str;
634 635 636 637 638 639 640 641 642

	while(*p) {
		if((*p)&0x80)
			*p=exascii_to_ascii_char(*p);	
		p++;
	}
	return((char*)str);
}

643 644 645 646
uint32_t DLLCALL str_to_bits(uint32_t val, const char *str)
{
	/* op can be 0 for replace, + for add, or - for remove */
	int op=0;
deuce's avatar
deuce committed
647
	const char *s;
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
	char ctrl;

	for(s=str; *s; s++) {
		if(*s=='+')
			op=1;
		else if(*s=='-')
			op=2;
		else {
			if(!op) {
				val=0;
				op=1;
			}
			ctrl=toupper(*s);
			ctrl&=0x1f;			/* Ensure it fits */
			switch(op) {
				case 1:		/* Add to the set */
					val |= 1<<ctrl;
					break;
				case 2:		/* Remove from the set */
					val &= ~(1<<ctrl);
					break;
			}
		}
	}
672
	return val;
673
}
674