Debian Codegraph @

WWW/Library/Implementation/HTString.c

raw
1 /*
2 * $LynxId: HTString.c,v 1.87 2026/04/21 00:30:54 tom Exp $
3 *
4 * Case-independent string comparison HTString.c
5 *
6 * Original version came with listserv implementation.
7 * Version TBL Oct 91 replaces one which modified the strings.
8 * 02-Dec-91 (JFG) Added stralloccopy and stralloccat
9 * 23 Jan 92 (TBL) Changed strallocc* to 8 char HTSAC* for VM and suchlike
10 * 6 Oct 92 (TBL) Moved WWW_TraceFlag in here to be in library
11 * 15 Nov 98 (TD) Added HTSprintf.
12 */
13
14 #include <HTUtils.h>
15 #include <HTFile.h>
16
17 #include <LYLeaks.h>
18 #include <LYUtils.h>
19 #include <LYStrings.h>
20
21 #ifdef USE_IGNORE_RC
22 int ignore_unused;
23 #endif
24
25 #ifndef NO_LYNX_TRACE
26 BOOLEAN WWW_TraceFlag = 0; /* Global trace flag for ALL W3 code */
27 int WWW_TraceMask = 0; /* Global trace flag for ALL W3 code */
28 #endif
29
30 #ifdef _WINDOWS
31 #undef VC
32 #define VC "2.14FM"
33 #endif
34
35 #ifndef VC
36 #define VC "2.14"
37 #endif /* !VC */
38
39 const char *HTLibraryVersion = VC; /* String for help screen etc */
40
41 /*
42 * strcasecomp8 is a variant of strcasecomp (below)
43 * ------------ -----------
44 * but uses 8bit upper/lower case information
45 * from the current display charset.
46 * It returns 0 if exact match.
47 */
48 int strcasecomp8(const char *a,
49 const char *b)
50 {
51 const char *p = a;
52 const char *q = b;
53
54 for (; *p && *q; p++, q++) {
55 int diff = UPPER8(*p, *q);
56
57 if (diff)
58 return diff;
59 }
60 if (*p)
61 return 1; /* p was longer than q */
62 if (*q)
63 return -1; /* p was shorter than q */
64 return 0; /* Exact match */
65 }
66
67 /*
68 * strncasecomp8 is a variant of strncasecomp (below)
69 * ------------- ------------
70 * but uses 8bit upper/lower case information
71 * from the current display charset.
72 * It returns 0 if exact match.
73 */
74 int strncasecomp8(const char *a,
75 const char *b,
76 int n)
77 {
78 const char *p = a;
79 const char *q = b;
80
81 for (;; p++, q++) {
82 int diff;
83
84 if (p == (a + n))
85 return 0; /* Match up to n characters */
86 if (!(*p && *q))
87 return (*p - *q);
88 diff = UPPER8(*p, *q);
89 if (diff)
90 return diff;
91 }
92 /*NOTREACHED */
93 }
94
95 #ifndef VM /* VM has these already it seems */
96 /* Strings of any length
97 * ---------------------
98 */
99 int strcasecomp(const char *a,
100 const char *b)
101 {
102 const char *p = a;
103 const char *q = b;
104
105 for (; *p && *q; p++, q++) {
106 int diff = TOLOWER(*p) - TOLOWER(*q);
107
108 if (diff)
109 return diff;
110 }
111 if (*p)
112 return 1; /* p was longer than q */
113 if (*q)
114 return -1; /* p was shorter than q */
115 return 0; /* Exact match */
116 }
117
118 /* With count limit
119 * ----------------
120 */
121 int strncasecomp(const char *a,
122 const char *b,
123 int n)
124 {
125 const char *p = a;
126 const char *q = b;
127
128 for (;; p++, q++) {
129 int diff;
130
131 if (p == (a + n))
132 return 0; /* Match up to n characters */
133 if (!(*p && *q))
134 return (*p - *q);
135 diff = TOLOWER(*p) - TOLOWER(*q);
136 if (diff)
137 return diff;
138 }
139 /*NOTREACHED */
140 }
141 #endif /* VM */
142
143 #define end_component(p) (*(p) == '.' || *(p) == '\0')
144
145 #ifdef DEBUG_ASTERISK
146 #define SHOW_ASTERISK CTRACE
147 #else
148 #define SHOW_ASTERISK(p) /* nothing */
149 #endif
150
151 #define SHOW_ASTERISK_NUM(a,b,c) \
152 SHOW_ASTERISK((tfp, "test @%d, '%s' vs '%s' (%d)\n", __LINE__, a,b,c))
153
154 #define SHOW_ASTERISK_TXT(a,b,c) \
155 SHOW_ASTERISK((tfp, "test @%d, '%s' vs '%s' %s\n", __LINE__, a,b,c))
156
157 /*
158 * Compare names as described in RFC 2818: ignore case, allow wildcards.
159 * Return zero on a match, nonzero on mismatch -TD
160 *
161 * From RFC 2818:
162 * Names may contain the wildcard character * which is considered to match any
163 * single domain name component or component fragment. E.g., *.a.com matches
164 * foo.a.com but not bar.foo.a.com. f*.com matches foo.com but not bar.com.
165 */
166 int strcasecomp_asterisk(const char *a, const char *b)
167 {
168 const char *p;
169 int result = 0;
170 int done = FALSE;
171
172 while (!result && !done) {
173 SHOW_ASTERISK_TXT(a, b, "main");
174 if (*a == '*') {
175 p = b;
176 for (;;) {
177 SHOW_ASTERISK_TXT(a, p, "loop");
178 if (end_component(p)) {
179 if (end_component(a + 1)) {
180 b = p - 1;
181 result = 0;
182 } else {
183 result = 1;
184 }
185 break;
186 } else if (strcasecomp_asterisk(a + 1, p)) {
187 ++p;
188 } else {
189 b = p - 1;
190 result = 0; /* found a match starting at 'p' */
191 done = TRUE;
192 break;
193 }
194 }
195 SHOW_ASTERISK_NUM(a, b, result);
196 } else if (*b == '*') {
197 result = strcasecomp_asterisk(b, a);
198 SHOW_ASTERISK_NUM(a, b, result);
199 done = (result == 0);
200 } else if (*a == '\0' || *b == '\0') {
201 result = (*a != *b);
202 SHOW_ASTERISK_NUM(a, b, result);
203 break;
204 } else if (TOLOWER(UCH(*a)) != TOLOWER(UCH(*b))) {
205 result = 1;
206 SHOW_ASTERISK_NUM(a, b, result);
207 break;
208 }
209 ++a;
210 ++b;
211 }
212 return result;
213 }
214
215 #ifdef DEBUG_ASTERISK
216 void mismatch_asterisk(void)
217 {
218 /* *INDENT-OFF* */
219 static struct {
220 const char *a;
221 const char *b;
222 int code;
223 } table[] = {
224 { "foo.bar", "*.*", 0 },
225 { "foo.bar", "*.b*", 0 },
226 { "foo.bar", "*.ba*", 0 },
227 { "foo.bar", "*.bar*", 0 },
228 { "foo.bar", "*.*bar*", 0 },
229 { "foo.bar", "*.*.", 1 },
230 { "foo.bar", "fo*.b*", 0 },
231 { "*oo.bar", "fo*.b*", 0 },
232 { "*oo.bar.com", "fo*.b*", 1 },
233 { "*oo.bar.com", "fo*.b*m", 1 },
234 { "*oo.bar.com", "fo*.b*.c*", 0 },
235 };
236 /* *INDENT-ON* */
237
238 unsigned n;
239 int code;
240
241 CTRACE((tfp, "mismatch_asterisk testing\n"));
242 for (n = 0; n < TABLESIZE(table); ++n) {
243 CTRACE((tfp, "-------%d\n", n));
244 code = strcasecomp_asterisk(table[n].a, table[n].b);
245 if (code != table[n].code) {
246 CTRACE((tfp, "mismatch_asterisk '%s' '%s' got %d, want %d\n",
247 table[n].a, table[n].b, code, table[n].code));
248 }
249 }
250 }
251 #endif
252
253 #ifdef NOT_ASCII
254
255 /* Case-insensitive with ASCII collating sequence
256 * ----------------
257 */
258 int AS_casecomp(const char *p,
259 const char *q)
260 {
261 int diff;
262
263 for (;; p++, q++) {
264 if (!(*p && *q))
265 return (UCH(*p) - UCH(*q));
266 diff = TOASCII(TOLOWER(*p))
267 - TOASCII(TOLOWER(*q));
268 if (diff)
269 return diff;
270 }
271 /*NOTREACHED */
272 }
273
274 /* With count limit and ASCII collating sequence
275 * ----------------
276 * AS_cmp uses n == -1 to compare indefinite length.
277 */
278 int AS_ncmp(const char *p,
279 const char *q,
280 unsigned int n)
281 {
282 const char *a = p;
283 int diff;
284
285 for (; (unsigned) (p - a) < n; p++, q++) {
286 if (!(*p && *q))
287 return (UCH(*p) - UCH(*q));
288 diff = TOASCII(*p)
289 - TOASCII(*q);
290 if (diff)
291 return diff;
292 }
293 return 0; /* Match up to n characters */
294 }
295 #endif /* NOT_ASCII */
296
297 /* Allocate a new copy of a string, and returns it
298 */
299 char *HTSACopy(char **dest,
300 const char *src)
301 {
302 if (src != NULL) {
303 if (src != *dest) {
304 size_t size = strlen(src) + 1;
305
306 FREE(*dest);
307 *dest = (char *) malloc(size);
308 if (*dest == NULL)
309 outofmem(__FILE__, "HTSACopy");
310 MemCpy(*dest, src, size);
311 }
312 } else {
313 FREE(*dest);
314 }
315 return *dest;
316 }
317
318 /* String Allocate and Concatenate
319 */
320 char *HTSACat(char **dest,
321 const char *src)
322 {
323 if (src && *src && (src != *dest)) {
324 if (*dest) {
325 size_t length = strlen(*dest);
326
327 *dest = (char *) realloc(*dest, length + strlen(src) + 1);
328 if (*dest == NULL)
329 outofmem(__FILE__, "HTSACat");
330 strcpy(*dest + length, src);
331 } else {
332 *dest = (char *) malloc(strlen(src) + 1);
333 if (*dest == NULL)
334 outofmem(__FILE__, "HTSACat");
335 strcpy(*dest, src);
336 }
337 }
338 return *dest;
339 }
340
341 /* optimized for heavily realloc'd strings, store length inside */
342
343 #define EXTRA_TYPE size_t /* type we use for length */
344 #define EXTRA_SIZE sizeof(void *) /* alignment >= sizeof(EXTRA_TYPE) */
345
346 void HTSAFree_extra(char *s)
347 {
348 free(s - EXTRA_SIZE);
349 }
350
351 /* never shrink */
352 char *HTSACopy_extra(char **dest,
353 const char *src)
354 {
355 if (src != NULL) {
356 size_t srcsize = strlen(src) + 1;
357 EXTRA_TYPE size = 0;
358
359 if (*dest != NULL) {
360 size = *(EXTRA_TYPE *) (void *) ((*dest) - EXTRA_SIZE);
361 }
362 if ((*dest == NULL) || (size < srcsize)) {
363 FREE_extra(*dest);
364 size = srcsize * 2; /* x2 step */
365 *dest = (char *) malloc(size + EXTRA_SIZE);
366 if (*dest == NULL)
367 outofmem(__FILE__, "HTSACopy_extra");
368 *(EXTRA_TYPE *) (void *) (*dest) = size;
369 *dest += EXTRA_SIZE;
370 }
371 MemCpy(*dest, src, srcsize);
372 } else {
373 Clear_extra(*dest);
374 }
375 return *dest;
376 }
377
378 /* Find next Field
379 * ---------------
380 *
381 * On entry,
382 * *pstr points to a string containing white space separated
383 * field, optionally quoted.
384 *
385 * On exit,
386 * *pstr has been moved to the first delimiter past the
387 * field
388 * THE STRING HAS BEEN MUTILATED by a 0 terminator
389 *
390 * returns a pointer to the first field
391 */
392 char *HTNextField(char **pstr)
393 {
394 char *p = *pstr;
395 char *start = NULL; /* start of field */
396
397 if (p != NULL) {
398 while (*p && WHITE(*p))
399 p++; /* Strip white space */
400 if (!*p) {
401 *pstr = p;
402 } else {
403 if (*p == '"') { /* quoted field */
404 p++;
405 start = p;
406 for (; *p && *p != '"'; p++) {
407 if (*p == '\\' && p[1])
408 p++; /* Skip escaped chars */
409 }
410 } else {
411 start = p;
412 while (*p && !WHITE(*p))
413 p++; /* Skip first field */
414 }
415 if (*p)
416 *p++ = '\0';
417 *pstr = p;
418 }
419 }
420 return start;
421 }
422
423 /* Find next Token
424 * ---------------
425 * Finds the next token in a string
426 * On entry,
427 * *pstr points to a string to be parsed.
428 * delims lists characters to be recognized as delimiters.
429 * If NULL, default is white space "," ";" or "=".
430 * The word can optionally be quoted or enclosed with
431 * chars from bracks.
432 * Comments surrounded by '(' ')' are filtered out
433 * unless they are specifically requested by including
434 * ' ' or '(' in delims or bracks.
435 * bracks lists bracketing chars. Some are recognized as
436 * special, for those give the opening char.
437 * If NULL, defaults to <"> and "<" ">".
438 * found points to location to fill with the ending delimiter
439 * found, or is NULL.
440 *
441 * On exit,
442 * *pstr has been moved to the first delimiter past the
443 * field
444 * THE STRING HAS BEEN MUTILATED by a 0 terminator
445 * found points to the delimiter found unless it was NULL.
446 * Returns a pointer to the first word or NULL on error
447 */
448 char *HTNextTok(char **pstr,
449 const char *delims,
450 const char *bracks,
451 char *found)
452 {
453 char *p = *pstr;
454 char *start = NULL;
455 BOOL get_blanks, skip_comments;
456 BOOL get_comments;
457 BOOL get_closing_char_too = FALSE;
458 char closer;
459
460 if (isEmptyS(pstr))
461 return NULL;
462 if (!delims)
463 delims = " ;,=";
464 if (!bracks)
465 bracks = "<\"";
466
467 get_blanks = (BOOL) (!StrChr(delims, ' ') && !StrChr(bracks, ' '));
468 get_comments = (BOOL) (StrChr(bracks, '(') != NULL);
469 skip_comments = (BOOL) (!get_comments && !StrChr(delims, '(') && !get_blanks);
470 #define skipWHITE(c) (!get_blanks && WHITE(c))
471
472 while (*p && skipWHITE(*p))
473 p++; /* Strip white space */
474 if (!*p) {
475 *pstr = p;
476 if (found)
477 *found = '\0';
478 return NULL; /* No first field */
479 }
480 while (1) {
481 /* Strip white space and other delimiters */
482 while (*p && (skipWHITE(*p) || StrChr(delims, *p)))
483 p++;
484 if (!*p) {
485 *pstr = p;
486 if (found)
487 *found = *(p - 1);
488 return NULL; /* No field */
489 }
490
491 if (*p == '(' && (skip_comments || get_comments)) { /* Comment */
492 int comment_level = 0;
493
494 if (get_comments && !start)
495 start = p + 1;
496 for (; *p && (*p != ')' || --comment_level > 0); p++) {
497 if (*p == '(')
498 comment_level++;
499 else if (*p == '"') { /* quoted field within Comment */
500 for (p++; *p && *p != '"'; p++)
501 if (*p == '\\' && *(p + 1))
502 p++; /* Skip escaped chars */
503 if (!*p)
504 break; /* (invalid) end of string found, leave */
505 }
506 if (*p == '\\' && *(p + 1))
507 p++; /* Skip escaped chars */
508 }
509 if (get_comments)
510 break;
511 if (*p)
512 p++;
513 if (get_closing_char_too) {
514 if (!*p || (!StrChr(bracks, *p) && StrChr(delims, *p))) {
515 break;
516 } else
517 get_closing_char_too = (BOOL) (StrChr(bracks, *p) != NULL);
518 }
519 } else if (StrChr(bracks, *p)) { /* quoted or bracketed field */
520 switch (*p) {
521 case '<':
522 closer = '>';
523 break;
524 case '[':
525 closer = ']';
526 break;
527 case '{':
528 closer = '}';
529 break;
530 case ':':
531 closer = ';';
532 break;
533 default:
534 closer = *p;
535 }
536 if (!start)
537 start = ++p;
538 for (; *p && *p != closer; p++)
539 if (*p == '\\' && *(p + 1))
540 p++; /* Skip escaped chars */
541 if (get_closing_char_too) {
542 p++;
543 if (!*p || (!StrChr(bracks, *p) && StrChr(delims, *p))) {
544 break;
545 } else
546 get_closing_char_too = (BOOL) (StrChr(bracks, *p) != NULL);
547 } else
548 break; /* kr95-10-9: needs to stop here */
549 } else { /* Spool field */
550 if (!start)
551 start = p;
552 while (*p && !skipWHITE(*p) && !StrChr(bracks, *p) &&
553 !StrChr(delims, *p))
554 p++;
555 if (*p && StrChr(bracks, *p)) {
556 get_closing_char_too = TRUE;
557 } else {
558 if (*p == '(' && skip_comments) {
559 *pstr = p;
560 HTNextTok(pstr, NULL, "(", found); /* Advance pstr */
561 *p = '\0';
562 if (*pstr && **pstr)
563 (*pstr)++;
564 return start;
565 }
566 break; /* Got it */
567 }
568 }
569 }
570 if (found)
571 *found = *p;
572
573 if (*p)
574 *p++ = '\0';
575 *pstr = p;
576 return start;
577 }
578
579 static char *HTAlloc(char *ptr, size_t length)
580 {
581 if (ptr != NULL)
582 ptr = (char *) realloc(ptr, length);
583 else
584 ptr = (char *) malloc(length);
585 if (ptr == NULL)
586 outofmem(__FILE__, "HTAlloc");
587 return ptr;
588 }
589
590 /*
591 * If SAVE_TIME_NOT_SPACE is defined, StrAllocVsprintf will hang on to
592 * its temporary string buffers instead of allocating and freeing them
593 * in each invocation. They only grow and never shrink, and won't be
594 * cleaned up on exit. - kw
595 */
596 #if defined(_REENTRANT) || defined(_THREAD_SAFE) || defined(LY_FIND_LEAKS)
597 #undef SAVE_TIME_NOT_SPACE
598 #endif
599
600 /*
601 * Replacement for sprintf, allocates buffer on the fly according to what's
602 * needed for its arguments. Unlike sprintf, this always concatenates to the
603 * destination buffer, so we do not have to provide both flavors.
604 */
605 typedef enum {
606 Flags,
607 Width,
608 Prec,
609 Type,
610 Format
611 } PRINTF;
612
613 #define VA_INTGR(type) ival = (int) va_arg((*ap), type)
614 #define VA_FLOAT(type) fval = (double) va_arg((*ap), type)
615 #define VA_POINT(type) pval = (char *) va_arg((*ap), type)
616
617 #define NUM_WIDTH 10 /* allow for width substituted for "*" in "%*s" */
618 /* also number of chars assumed to be needed in addition
619 to a given precision in floating point formats */
620
621 #define GROW_EXPR(n) (((n) * 3) / 2)
622 #define GROW_SIZE 256
623
624 PUBLIC_IF_FIND_LEAKS char *StrAllocVsprintf(char **pstr,
625 size_t dst_len,
626 const char *fmt,
627 va_list *ap)
628 {
629 #ifdef HAVE_VASPRINTF
630 /*
631 * Use vasprintf() if we have it, since it is simplest.
632 */
633 char *result = NULL;
634 char *temp = NULL;
635
636 /* discard old destination if no length was given */
637 if (pstr && !dst_len) {
638 if (*pstr)
639 FREE(*pstr);
640 }
641
642 if (vasprintf(&temp, fmt, *ap) >= 0) {
643 if (dst_len != 0) {
644 size_t src_len = strlen(temp);
645 size_t new_len = dst_len + src_len + 1;
646
647 result = HTAlloc(pstr ? *pstr : NULL, new_len);
648 if (result != NULL) {
649 strcpy(result + dst_len, temp);
650 }
651 (free) (temp);
652 } else {
653 result = temp;
654 mark_malloced(temp, strlen(temp));
655 }
656 }
657
658 if (pstr != NULL)
659 *pstr = result;
660
661 return result;
662 #else /* !HAVE_VASPRINTF */
663 /*
664 * If vasprintf() is not available, this works - but does not implement
665 * the POSIX '$' formatting character which may be used in some of the
666 * ".po" files.
667 */
668 #ifdef SAVE_TIME_NOT_SPACE
669 static size_t tmp_len = 0;
670 static size_t fmt_len = 0;
671 static char *tmp_ptr = NULL;
672 static char *fmt_ptr = NULL;
673
674 #else
675 size_t tmp_len = GROW_SIZE;
676 char *tmp_ptr = 0;
677 char *fmt_ptr;
678 #endif /* SAVE_TIME_NOT_SPACE */
679 size_t have, need;
680 char *dst_ptr = pstr ? *pstr : NULL;
681 const char *format = fmt;
682
683 if (isEmpty(fmt))
684 return 0;
685
686 need = strlen(fmt) + 1;
687 #ifdef SAVE_TIME_NOT_SPACE
688 if (!fmt_ptr || fmt_len < need * NUM_WIDTH) {
689 fmt_ptr = HTAlloc(fmt_ptr, fmt_len = need * NUM_WIDTH);
690 }
691 if (!tmp_ptr || tmp_len < GROW_SIZE) {
692 tmp_ptr = HTAlloc(tmp_ptr, tmp_len = GROW_SIZE);
693 }
694 #else
695 if ((fmt_ptr = malloc(need * NUM_WIDTH)) == 0
696 || (tmp_ptr = malloc(tmp_len)) == 0) {
697 outofmem(__FILE__, "StrAllocVsprintf");
698 }
699 #endif /* SAVE_TIME_NOT_SPACE */
700
701 if (dst_ptr == 0) {
702 dst_ptr = HTAlloc(dst_ptr, have = GROW_SIZE + need);
703 } else {
704 have = strlen(dst_ptr) + 1;
705 need += dst_len;
706 if (have < need)
707 dst_ptr = HTAlloc(dst_ptr, have = GROW_SIZE + need);
708 }
709
710 while (*fmt != '\0') {
711 if (*fmt == '%') {
712 static char dummy[] = "";
713 PRINTF state = Flags;
714 char *pval = dummy; /* avoid const-cast */
715 double fval = 0.0;
716 int done = FALSE;
717 int ival = 0;
718 int prec = -1;
719 int type = 0;
720 int used = 0;
721 int width = -1;
722 size_t f = 0;
723
724 fmt_ptr[f++] = *fmt;
725 while (*++fmt != '\0' && !done) {
726 fmt_ptr[f++] = *fmt;
727
728 if (isdigit(UCH(*fmt))) {
729 int num = *fmt - '0';
730
731 if (state == Flags && num != 0)
732 state = Width;
733 if (state == Width) {
734 if (width < 0)
735 width = 0;
736 width = (width * 10) + num;
737 } else if (state == Prec) {
738 if (prec < 0)
739 prec = 0;
740 prec = (prec * 10) + num;
741 }
742 } else if (*fmt == '*') {
743 VA_INTGR(int);
744
745 if (state == Flags)
746 state = Width;
747 if (state == Width) {
748 width = ival;
749 } else if (state == Prec) {
750 prec = ival;
751 }
752 sprintf(&fmt_ptr[--f], "%d", ival);
753 f = strlen(fmt_ptr);
754 } else if (isalpha(UCH(*fmt))) {
755 done = TRUE;
756 switch (*fmt) {
757 case 'Z': /* FALLTHRU */
758 case 'h': /* FALLTHRU */
759 case 'l': /* FALLTHRU */
760 case 'L': /* FALLTHRU */
761 done = FALSE;
762 type = *fmt;
763 break;
764 case 'o': /* FALLTHRU */
765 case 'i': /* FALLTHRU */
766 case 'd': /* FALLTHRU */
767 case 'u': /* FALLTHRU */
768 case 'x': /* FALLTHRU */
769 case 'X': /* FALLTHRU */
770 if (type == 'l')
771 VA_INTGR(long);
772
773 else if (type == 'Z')
774 VA_INTGR(size_t);
775
776 else
777 VA_INTGR(int);
778
779 used = 'i';
780 break;
781 case 'f': /* FALLTHRU */
782 case 'e': /* FALLTHRU */
783 case 'E': /* FALLTHRU */
784 case 'g': /* FALLTHRU */
785 case 'G': /* FALLTHRU */
786 VA_FLOAT(double);
787
788 used = 'f';
789 break;
790 case 'c':
791 VA_INTGR(int);
792
793 used = 'c';
794 break;
795 case 's':
796 VA_POINT(char *);
797
798 if (prec < 0)
799 prec = (int) strlen(pval);
800 used = 's';
801 break;
802 case 'p':
803 VA_POINT(void *);
804
805 used = 'p';
806 break;
807 case 'n':
808 VA_POINT(int *);
809
810 used = 0;
811 break;
812 default:
813 CTRACE((tfp, "unknown format character '%c' in %s\n",
814 *fmt, format));
815 break;
816 }
817 } else if (*fmt == '.') {
818 state = Prec;
819 } else if (*fmt == '%') {
820 done = TRUE;
821 used = '%';
822 }
823 }
824 fmt_ptr[f] = '\0';
825
826 if (prec > 0) {
827 switch (used) {
828 case 'f':
829 if (width < prec + NUM_WIDTH)
830 width = prec + NUM_WIDTH;
831 /* FALLTHRU */
832 case 'i':
833 /* FALLTHRU */
834 case 'p':
835 if (width < prec + 2)
836 width = prec + 2; /* leading sign/space/zero, "0x" */
837 break;
838 case 'c':
839 break;
840 case '%':
841 break;
842 default:
843 if (width < prec)
844 width = prec;
845 break;
846 }
847 }
848 if (width >= (int) tmp_len) {
849 tmp_len = GROW_EXPR(tmp_len + width);
850 tmp_ptr = HTAlloc(tmp_ptr, tmp_len);
851 }
852
853 switch (used) {
854 case 'i':
855 case 'c':
856 sprintf(tmp_ptr, fmt_ptr, ival);
857 break;
858 case 'f':
859 sprintf(tmp_ptr, fmt_ptr, fval);
860 break;
861 default:
862 sprintf(tmp_ptr, fmt_ptr, pval);
863 break;
864 }
865 need = dst_len + strlen(tmp_ptr) + 1;
866 if (need >= have) {
867 dst_ptr = HTAlloc(dst_ptr, have = GROW_EXPR(need));
868 }
869 strcpy(dst_ptr + dst_len, tmp_ptr);
870 dst_len += strlen(tmp_ptr);
871 } else {
872 if ((dst_len + 2) >= have) {
873 dst_ptr = HTAlloc(dst_ptr, (have += GROW_SIZE));
874 }
875 dst_ptr[dst_len++] = *fmt++;
876 }
877 }
878
879 #ifndef SAVE_TIME_NOT_SPACE
880 FREE(tmp_ptr);
881 FREE(fmt_ptr);
882 #endif
883 dst_ptr[dst_len] = '\0';
884 if (pstr)
885 *pstr = dst_ptr;
886 return (dst_ptr);
887 #endif /* HAVE_VASPRINTF */
888 }
889 #undef SAVE_TIME_NOT_SPACE
890
891 /*
892 * Replacement for sprintf, allocates buffer on the fly according to what's
893 * needed for its arguments. Unlike sprintf, this always concatenates to the
894 * destination buffer.
895 */
896 /* Note: if making changes, also check the memory tracking version
897 * LYLeakHTSprintf in LYLeaks.c. - kw */
898 #ifdef HTSprintf /* if hidden by LYLeaks stuff */
899 #undef HTSprintf
900 #endif
901 char *HTSprintf(char **pstr, const char *fmt, ...)
902 {
903 char *result = NULL;
904 size_t inuse = 0;
905 va_list ap;
906
907 LYva_start(ap, fmt);
908 {
909 if (pstr != NULL && *pstr != NULL)
910 inuse = strlen(*pstr);
911 result = StrAllocVsprintf(pstr, inuse, fmt, &ap);
912 }
913 va_end(ap);
914
915 return (result);
916 }
917
918 /*
919 * Replacement for sprintf, allocates buffer on the fly according to what's
920 * needed for its arguments. Like sprintf, this always resets the destination
921 * buffer.
922 */
923 /* Note: if making changes, also check the memory tracking version
924 * LYLeakHTSprintf0 in LYLeaks.c. - kw */
925 #ifdef HTSprintf0 /* if hidden by LYLeaks stuff */
926 #undef HTSprintf0
927 #endif
928 char *HTSprintf0(char **pstr, const char *fmt, ...)
929 {
930 char *result = NULL;
931 va_list ap;
932
933 LYva_start(ap, fmt);
934 {
935 result = StrAllocVsprintf(pstr, (size_t) 0, fmt, &ap);
936 }
937 va_end(ap);
938
939 return (result);
940 }
941
942 #if LY_TEST_FMTS == 1
943 /*
944 * Check if the parameter points to the beginning of a conversion
945 * specification, ignoring "%%".
946 */
947 static BOOL is_format(const char *source)
948 {
949 BOOL result = FALSE;
950
951 if (source != NULL && source[0] == '%' && source[1] != '%')
952 result = TRUE;
953 return result;
954 }
955
956 /*
957 * Skip to the next conversion specifier, returning NULL if no more are found.
958 */
959 static const char *next_format(const char *source)
960 {
961 if (source != NULL) {
962 if (is_format(source))
963 ++source;
964 while (*source != '\0' && !is_format(source))
965 ++source;
966 if (*source == '\0')
967 source = NULL;
968 }
969 return source;
970 }
971
972 /*
973 * Compare the conversion specifier to which expect/actual point.
974 */
975 static BOOL same_format(const char *expect, const char *actual)
976 {
977 BOOL result = FALSE;
978
979 if (expect != NULL && actual != NULL) {
980 result = TRUE;
981 while (*expect != '\0' && *actual != '\0') {
982 if (*expect != *actual) {
983 result = FALSE;
984 break;
985 }
986 if (strchr("diouxXeEfFgGcsp", *expect) != NULL)
987 break;
988 expect++;
989 actual++;
990 }
991 }
992 return result;
993 }
994
995 /*
996 * At runtime, compare the reference 'expect' format to 'actual', to log cases
997 * of missing or unexpected parameters, e.g., due to a coding error or problem
998 * with message translation.
999 */
1000 const char *LYtextFmts(const char *expect, const char *actual)
1001 {
1002 const char *result = actual;
1003
1004 if (TRACE) {
1005 const char *assume = expect;
1006 BOOL problem = FALSE;
1007
1008 if (!is_format(expect))
1009 expect = next_format(expect);
1010 if (!is_format(actual))
1011 actual = next_format(actual);
1012 while (expect != NULL && actual != NULL) {
1013 if (!same_format(expect, actual)) {
1014 problem = TRUE;
1015 break;
1016 }
1017 expect = next_format(expect);
1018 actual = next_format(actual);
1019 }
1020 if (!problem && (expect != NULL || actual != NULL))
1021 problem = TRUE;
1022 if (problem) {
1023 CTRACE((tfp, "LYtextFmts \"%s\" vs \"%s\"\n", assume, result));
1024 }
1025 }
1026
1027 return result;
1028 }
1029 #endif
1030
1031 /*
1032 * Returns a quoted or escaped form of the given parameter, suitable for use in
1033 * a command string.
1034 */
1035 #if USE_QUOTED_PARAMETER
1036 #define S_QUOTE '\''
1037 #define D_QUOTE '"'
1038 char *HTQuoteParameter(const char *parameter)
1039 {
1040 size_t i;
1041 size_t last;
1042 size_t n = 0;
1043 size_t quoted = 0;
1044 char *result;
1045
1046 if (parameter == NULL)
1047 parameter = "";
1048
1049 last = strlen(parameter);
1050 for (i = 0; i < last; ++i)
1051 if (StrChr("\\&#$^*?(){}<>\"';`|", parameter[i]) != NULL
1052 || isspace(UCH(parameter[i])))
1053 ++quoted;
1054
1055 result = (char *) malloc(last + 5 * quoted + 3);
1056 if (result == NULL)
1057 outofmem(__FILE__, "HTQuoteParameter");
1058
1059 n = 0;
1060 #if (USE_QUOTED_PARAMETER == 1)
1061 /*
1062 * Only double-quotes are used in Win32/DOS -TD
1063 */
1064 if (quoted)
1065 result[n++] = D_QUOTE;
1066 for (i = 0; i < last; i++) {
1067 result[n++] = parameter[i];
1068 }
1069 if (quoted)
1070 result[n++] = D_QUOTE;
1071 #else
1072 if (quoted)
1073 result[n++] = S_QUOTE;
1074 for (i = 0; i < last; i++) {
1075 if (parameter[i] == S_QUOTE) {
1076 result[n++] = S_QUOTE;
1077 result[n++] = D_QUOTE;
1078 result[n++] = parameter[i];
1079 result[n++] = D_QUOTE;
1080 result[n++] = S_QUOTE;
1081 } else {
1082 /* Note: No special handling of other characters, including
1083 backslash, since we are constructing a single-quoted string!
1084 Backslash has no special escape meaning within those for sh
1085 and compatible shells, so trying to escape a backslash by
1086 doubling it is unnecessary and would be interpreted by the
1087 shell as an additional data character. - kw 2000-05-02
1088 */
1089 result[n++] = parameter[i];
1090 }
1091 }
1092 if (quoted)
1093 result[n++] = S_QUOTE;
1094 #endif
1095 result[n] = '\0';
1096 return result;
1097 }
1098 #endif
1099
1100 #define HTIsParam(string) ((string[0] == '%' && string[1] == 's'))
1101
1102 /*
1103 * Returns the number of "%s" tokens in a system command-template.
1104 */
1105 int HTCountCommandArgs(const char *command)
1106 {
1107 int number = 0;
1108
1109 while (command[0] != 0) {
1110 if (HTIsParam(command))
1111 number++;
1112 command++;
1113 }
1114 return number;
1115 }
1116
1117 /*
1118 * Returns a pointer into the given string after the given parameter number
1119 */
1120 static const char *HTAfterCommandArg(const char *command,
1121 int number)
1122 {
1123 while (number > 0) {
1124 if (command[0] != 0) {
1125 if (HTIsParam(command)) {
1126 number--;
1127 command++;
1128 }
1129 command++;
1130 } else {
1131 break;
1132 }
1133 }
1134 return command;
1135 }
1136
1137 #if USE_QUOTED_PARAMETER
1138 /*
1139 * Recursively trim possible parameters of the source until an existing file
1140 * is found. If no file is found, return -1. If a file is found, return
1141 * the offset to a blank just after the filename.
1142 *
1143 * TODO: this could be smarter about trimming, e.g., matching quotes.
1144 */
1145 static int skipPathname(const char *target, const char *source)
1146 {
1147 int result = -1;
1148 const char *last;
1149 struct stat stat_info;
1150
1151 if (HTStat(target, &stat_info) == 0
1152 && S_ISREG(stat_info.st_mode)) {
1153 result = 0;
1154 } else if (*target != ' ' && (last = strrchr(target, ' ')) != NULL) {
1155 char *temp = NULL;
1156 int inner;
1157
1158 while (last != target && last[-1] == ' ')
1159 --last;
1160
1161 StrAllocCopy(temp, target);
1162 result = (int) (last - target);
1163 temp[result] = '\0';
1164
1165 if ((inner = skipPathname(temp, source)) < 0) {
1166 result = -1;
1167 } else if (inner > 0) {
1168 result = inner;
1169 }
1170
1171 FREE(temp);
1172 }
1173 CTRACE((tfp, "skip/recur %d '%s'\n", result, target));
1174 return result;
1175 }
1176 #endif
1177
1178 /*
1179 * Like HTAddParam, but the parameter may be an environment variable, which we
1180 * will expand and append. Do this only for things like the command-verb,
1181 * where we obtain the parameter from the user's configuration. Any quoting
1182 * required for the environment variable has to be done within its value, e.g.,
1183 *
1184 * setenv EDITOR 'xvile -name "No such class"'
1185 *
1186 * This is useful only when we quote parameters, of course.
1187 */
1188 #if USE_QUOTED_PARAMETER
1189 void HTAddXpand(char **result,
1190 const char *command,
1191 int number,
1192 const char *parameter)
1193 {
1194 if (parameter == NULL)
1195 parameter = "";
1196 if (number > 0) {
1197 const char *last = HTAfterCommandArg(command, number - 1);
1198 const char *next = last;
1199
1200 if (number <= 1) {
1201 FREE(*result);
1202 }
1203
1204 while (next[0] != 0) {
1205 if (HTIsParam(next)) {
1206 if (next != last) {
1207 size_t len = ((size_t) (next - last)
1208 + ((*result != NULL)
1209 ? strlen(*result)
1210 : 0));
1211
1212 HTSACat(result, last);
1213 (*result)[len] = 0;
1214 }
1215 if (LYisAbsPath(parameter)) {
1216 int skip = skipPathname(parameter, parameter);
1217 char *quoted;
1218
1219 if (skip > 0) {
1220 char *temp = NULL;
1221
1222 StrAllocCopy(temp, parameter);
1223 temp[skip] = 0;
1224
1225 quoted = HTQuoteParameter(temp);
1226 HTSACat(result, quoted);
1227 FREE(quoted);
1228
1229 temp[skip] = ' ';
1230 HTSACat(result, temp + skip);
1231 FREE(temp);
1232 } else {
1233 quoted = HTQuoteParameter(parameter);
1234 HTSACat(result, quoted);
1235 FREE(quoted);
1236 }
1237 } else {
1238 /* leave it unquoted, e.g., environment variable expanded */
1239 HTSACat(result, parameter);
1240 }
1241 CTRACE((tfp, "PARAM-EXP:%s\n", *result));
1242 return;
1243 }
1244 next++;
1245 }
1246 }
1247 }
1248 #endif /* USE_QUOTED_PARAMETER */
1249
1250 /*
1251 * Append string to a system command that we are constructing, without quoting.
1252 * We're given the index of the newest parameter we're processing. Zero
1253 * indicates none, so a value of '1' indicates that we copy from the beginning
1254 * of the command string up to the first parameter, substitute the quoted
1255 * parameter and return the result.
1256 *
1257 * Parameters are substituted at "%s" tokens, like printf. Other printf-style
1258 * tokens are not substituted; they are passed through without change.
1259 */
1260 void HTAddToCmd(char **result,
1261 const char *command,
1262 int number,
1263 const char *string)
1264 {
1265 if (number > 0) {
1266 const char *last = HTAfterCommandArg(command, number - 1);
1267 const char *next = last;
1268
1269 if (number <= 1) {
1270 FREE(*result);
1271 }
1272 if (string == NULL)
1273 string = "";
1274 while (next[0] != 0) {
1275 if (HTIsParam(next)) {
1276 if (next != last) {
1277 size_t len = ((size_t) (next - last)
1278 + ((*result != NULL)
1279 ? strlen(*result)
1280 : 0));
1281
1282 HTSACat(result, last);
1283 (*result)[len] = 0;
1284 }
1285 HTSACat(result, string);
1286 CTRACE((tfp, "PARAM-ADD:%s\n", *result));
1287 return;
1288 }
1289 next++;
1290 }
1291 }
1292 }
1293
1294 /*
1295 * Append string-parameter to a system command that we are constructing. The
1296 * string is a complete parameter (which is a necessary assumption so we can
1297 * quote it properly).
1298 */
1299 void HTAddParam(char **result,
1300 const char *command,
1301 int number,
1302 const char *parameter)
1303 {
1304 if (number > 0) {
1305 #if USE_QUOTED_PARAMETER
1306 char *quoted = HTQuoteParameter(parameter);
1307
1308 HTAddToCmd(result, command, number, quoted);
1309 FREE(quoted);
1310 #else
1311 HTAddToCmd(result, command, number, parameter);
1312 #endif
1313 }
1314 }
1315
1316 /*
1317 * Append the remaining command-string to a system command (compare with
1318 * HTAddParam). Any remaining "%s" tokens are copied as empty strings.
1319 */
1320 void HTEndParam(char **result,
1321 const char *command,
1322 int number)
1323 {
1324 const char *last;
1325 int count;
1326
1327 count = HTCountCommandArgs(command);
1328 if (count < number)
1329 number = count;
1330 last = HTAfterCommandArg(command, number);
1331 if (last[0] != 0) {
1332 HTSACat(result, last);
1333 }
1334 CTRACE((tfp, "PARAM-END:%s\n", *result));
1335 }
1336
1337 /* Binary-strings (may have embedded nulls). Some modules (HTGopher) assume
1338 * there is a null on the end, anyway.
1339 */
1340
1341 /* (Re)allocate a bstring, e.g., to increase its buffer size for ad hoc
1342 * operations.
1343 */
1344 void HTSABAlloc(bstring **dest, int len)
1345 {
1346 if (*dest == NULL) {
1347 *dest = typecalloc(bstring);
1348
1349 if (*dest == NULL)
1350 outofmem(__FILE__, "HTSABAlloc");
1351 }
1352
1353 if ((*dest)->len != len) {
1354 (*dest)->str = typeRealloc(char, (*dest)->str, len);
1355
1356 if ((*dest)->str == NULL)
1357 outofmem(__FILE__, "HTSABAlloc");
1358
1359 (*dest)->len = len;
1360 }
1361 }
1362
1363 /* Allocate a new bstring, and return it.
1364 */
1365 void HTSABCopy(bstring **dest, const char *src,
1366 int len)
1367 {
1368 bstring *t;
1369 unsigned need = (unsigned) (len + 1);
1370
1371 CTRACE2(TRACE_BSTRING,
1372 (tfp, "HTSABCopy(%p, %p, %d)\n",
1373 (void *) dest, (const void *) src, len));
1374 HTSABFree(dest);
1375 if (src) {
1376 if (TRACE_BSTRING) {
1377 CTRACE((tfp, "=== %4d:", len));
1378 trace_bstring2(src, len);
1379 CTRACE((tfp, "\n"));
1380 }
1381 if ((t = (bstring *) malloc(sizeof(bstring))) == NULL)
1382 outofmem(__FILE__, "HTSABCopy");
1383
1384 if ((t->str = typeMallocn(char, need)) == NULL)
1385 outofmem(__FILE__, "HTSABCopy");
1386
1387 MemCpy(t->str, src, len);
1388 t->len = len;
1389 t->str[t->len] = '\0';
1390 *dest = t;
1391 }
1392 if (TRACE_BSTRING) {
1393 CTRACE((tfp, "=> %4d:", BStrLen(*dest)));
1394 trace_bstring(*dest);
1395 CTRACE((tfp, "\n"));
1396 }
1397 }
1398
1399 /*
1400 * Initialize with a null-terminated string (discards the null).
1401 */
1402 void HTSABCopy0(bstring **dest, const char *src)
1403 {
1404 HTSABCopy(dest, src, (int) strlen(src));
1405 }
1406
1407 /*
1408 * Append a block of memory to a bstring.
1409 */
1410 void HTSABCat(bstring **dest, const char *src,
1411 int len)
1412 {
1413 bstring *t = *dest;
1414
1415 CTRACE2(TRACE_BSTRING,
1416 (tfp, "HTSABCat(%p, %p, %d)\n",
1417 (void *) dest, (const void *) src, len));
1418 if (src) {
1419 unsigned need = (unsigned) (len + 1);
1420 char *target;
1421
1422 if (TRACE_BSTRING) {
1423 CTRACE((tfp, "=== %4d:", len));
1424 trace_bstring2(src, len);
1425 CTRACE((tfp, "\n"));
1426 }
1427 if (t) {
1428 unsigned length = (unsigned) t->len + need;
1429
1430 target = typeRealloc(char, t->str, length);
1431 } else {
1432 if ((t = typecalloc(bstring)) == NULL)
1433 outofmem(__FILE__, "HTSACat");
1434
1435 target = typeMallocn(char, need);
1436 }
1437 if (target == NULL)
1438 outofmem(__FILE__, "HTSACat");
1439
1440 t->str = target;
1441 MemCpy(t->str + t->len, src, len);
1442 t->len += len;
1443 t->str[t->len] = '\0';
1444 *dest = t;
1445 }
1446 if (TRACE_BSTRING) {
1447 CTRACE((tfp, "=> %4d:", BStrLen(*dest)));
1448 trace_bstring(*dest);
1449 CTRACE((tfp, "\n"));
1450 }
1451 }
1452
1453 /*
1454 * Append a null-terminated string (discards the null).
1455 */
1456 void HTSABCat0(bstring **dest, const char *src)
1457 {
1458 HTSABCat(dest, src, (int) strlen(src));
1459 }
1460
1461 /*
1462 * Compare two bstring's for equality
1463 */
1464 BOOL HTSABEql(bstring *a, bstring *b)
1465 {
1466 unsigned len_a = (unsigned) ((a != NULL) ? a->len : 0);
1467 unsigned len_b = (unsigned) ((b != NULL) ? b->len : 0);
1468
1469 if (len_a == len_b) {
1470 if (len_a == 0
1471 || MemCmp(a->str, b->str, a->len) == 0)
1472 return TRUE;
1473 }
1474 return FALSE;
1475 }
1476
1477 /*
1478 * Deallocate a bstring.
1479 */
1480 void HTSABFree(bstring **ptr)
1481 {
1482 if (*ptr != NULL) {
1483 FREE((*ptr)->str);
1484 FREE(*ptr);
1485 *ptr = NULL;
1486 }
1487 }
1488
1489 /*
1490 * Use this function to perform formatted sprintf's onto the end of a bstring.
1491 * The bstring may contain embedded nulls; the formatted portions must not.
1492 */
1493 bstring *HTBprintf(bstring **pstr, const char *fmt, ...)
1494 {
1495 bstring *result = NULL;
1496 char *temp = NULL;
1497 va_list ap;
1498
1499 LYva_start(ap, fmt);
1500 {
1501 temp = StrAllocVsprintf(&temp, (size_t) 0, fmt, &ap);
1502 if (non_empty(temp)) {
1503 HTSABCat(pstr, temp, (int) strlen(temp));
1504 }
1505 FREE(temp);
1506 result = *pstr;
1507 }
1508 va_end(ap);
1509
1510 return (result);
1511 }
1512
1513 /*
1514 * Write binary-data to the logfile, making it safe for most editors to view.
1515 * That is most, since we do not restrict line-length. Nulls and other
1516 * non-printing characters are addressed.
1517 */
1518 void trace_bstring2(const char *text,
1519 int size)
1520 {
1521 int n;
1522
1523 if (text != NULL) {
1524 for (n = 0; n < size; ++n) {
1525 int ch = UCH(text[n]);
1526
1527 switch (ch) {
1528 case '\\':
1529 fputs("\\\\", tfp);
1530 break;
1531 case '\r':
1532 fputs("\\r", tfp);
1533 break;
1534 case '\t':
1535 fputs("\\t", tfp);
1536 break;
1537 case '\f':
1538 fputs("\\f", tfp);
1539 break;
1540 default:
1541 if (isprint(ch) || isspace(ch)) {
1542 fputc(ch, tfp);
1543 } else {
1544 fprintf(tfp, "\\%03o", ch);
1545 }
1546 break;
1547 }
1548 }
1549 }
1550 }
1551
1552 void trace_bstring(bstring *data)
1553 {
1554 trace_bstring2(BStrData(data), BStrLen(data));
1555 }