* big profiling stuff:
[citadel.git] / libcitadel / lib / tools.c
1 /*
2  * A basic toolset containing miscellaneous functions for string manipluation,
3  * encoding/decoding, and a bunch of other stuff.
4  */
5
6
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <signal.h>
11 #include <sys/types.h>
12 #include <ctype.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <errno.h>
16 #include <limits.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include "libcitadel.h"
30
31
32 #define TRUE  1
33 #define FALSE 0
34
35 typedef unsigned char byte;           /* Byte type */
36
37 /* Base64 encoding table */
38 const byte etable[256] = {
39         65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
40         82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103,
41         104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
42         118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43,
43         47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
44         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
45         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
46         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
47         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51         0, 0, 0, 0, 0, 0, 0, 0, 0
52 };
53
54 /* Base64 decoding table */
55 const byte dtable[256] = {
56         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
57         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
58         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
59         128, 62, 128, 128, 128, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
60         128, 128, 128, 0, 128, 128, 128, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
61         12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 128, 128, 128,
62         128, 128, 128, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
63         40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 128, 128, 128, 128,
64         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
65         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
66         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
67         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
68         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
69         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
70         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
71         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
72         128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
73         128, 128, 0
74 };
75
76 /*
77  * copy a string into a buffer of a known size. abort if we exceed the limits
78  *
79  * dest the targetbuffer
80  * src  the source string
81  * n    the size od dest
82  *
83  * returns the number of characters copied if dest is big enough, -n if not.
84  */
85 int safestrncpy(char *dest, const char *src, size_t n)
86 {
87         int i = 0;
88
89         if (dest == NULL || src == NULL) {
90                 fprintf(stderr, "safestrncpy: NULL argument\n");
91                 abort();
92         }
93
94         do {
95                 dest[i] = src[i];
96                 if (dest[i] == 0) return i;
97                 ++i;
98         } while (i<n);
99         dest[n - 1] = 0;
100         return -i;
101 }
102
103
104
105 /*
106  * num_tokens()  -  discover number of parameters/tokens in a string
107  */
108 int num_tokens(const char *source, char tok)
109 {
110         int count = 1;
111         const char *ptr = source;
112
113         if (source == NULL) {
114                 return (0);
115         }
116
117         while (*ptr != '\0') {
118                 if (*ptr++ == tok) {
119                         ++count;
120                 }
121         }
122         
123         return (count);
124 }
125
126 //extern void cit_backtrace(void);
127
128
129 /*
130  * extract_token() - a string tokenizer
131  * returns -1 if not found, or length of token.
132  */
133 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
134 {
135         const char *s;                  //* source * /
136         int len = 0;                    //* running total length of extracted string * /
137         int current_token = 0;          //* token currently being processed * /
138
139         s = source;
140
141         if (dest == NULL) {
142                 return(-1);
143         }
144
145         //cit_backtrace();
146         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
147         dest[0] = 0;
148
149         if (s == NULL) {
150                 return(-1);
151         }
152         
153         maxlen--;
154
155         while (*s) {
156                 if (*s == separator) {
157                         ++current_token;
158                 }
159                 if ( (current_token == parmnum) && 
160                      (*s != separator) && 
161                      (len < maxlen) ) {
162                         dest[len] = *s;
163                         ++len;
164                 }
165                 else if ((current_token > parmnum) || (len >= maxlen)) {
166                         break;
167                 }
168                 ++s;
169         }
170
171         dest[len] = '\0';
172         if (current_token < parmnum) {
173                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
174                 return(-1);
175         }
176         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
177         return(len);
178 }
179 //*/
180
181
182 /*
183  * extract_token() - a string tokenizer
184  * /
185 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
186 {
187         char *d;                // dest
188         const char *s;          // source
189         int count = 0;
190         int len = 0;
191
192         
193         //cit_backtrace();
194         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
195         strcpy(dest, "");
196
197         //  Locate desired parameter 
198         s = source;
199         while (count < parmnum) {
200                 //  End of string, bail!
201                 if (!*s) {
202                         s = NULL;
203                         break;
204                 }
205                 if (*s == separator) {
206                         count++;
207                 }
208                 s++;
209         }
210         if (!s) {
211                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
212                 return -1;              // Parameter not found
213         }
214         
215         for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
216                 *d = *s;
217         }
218         *d = 0;
219         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
220         return 0;
221 }
222 */
223
224
225 /*
226  * remove_token() - a tokenizer that kills, maims, and destroys
227  */
228 void remove_token(char *source, int parmnum, char separator)
229 {
230         char *d, *s;            /* dest, source */
231         int count = 0;
232
233         /* Find desired parameter */
234         d = source;
235         while (count < parmnum) {
236                 /* End of string, bail! */
237                 if (!*d) {
238                         d = NULL;
239                         break;
240                 }
241                 if (*d == separator) {
242                         count++;
243                 }
244                 d++;
245         }
246         if (!d) return;         /* Parameter not found */
247
248         /* Find next parameter */
249         s = d;
250         while (*s && *s != separator) {
251                 s++;
252         }
253
254         /* Hack and slash */
255         if (*s)
256                 strcpy(d, ++s);
257         else if (d == source)
258                 *d = 0;
259         else
260                 *--d = 0;
261         /*
262         while (*s) {
263                 *d++ = *s++;
264         }
265         *d = 0;
266         */
267 }
268
269
270 /*
271  * extract_int()  -  extract an int parm w/o supplying a buffer
272  */
273 int extract_int(const char *source, int parmnum)
274 {
275         char buf[32];
276         
277         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
278                 return(atoi(buf));
279         else
280                 return 0;
281 }
282
283 /*
284  * extract_long()  -  extract an long parm w/o supplying a buffer
285  */
286 long extract_long(const char *source, int parmnum)
287 {
288         char buf[32];
289         
290         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
291                 return(atol(buf));
292         else
293                 return 0;
294 }
295
296
297 /*
298  * extract_unsigned_long() - extract an unsigned long parm
299  */
300 unsigned long extract_unsigned_long(const char *source, int parmnum)
301 {
302         char buf[32];
303
304         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
305                 return strtoul(buf, NULL, 10);
306         else 
307                 return 0;
308 }
309
310
311 /*
312  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by John Walker.
313  */
314
315 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
316 {
317         int i, hiteof = FALSE;
318         int spos = 0;
319         int dpos = 0;
320         int thisline = 0;
321
322         while (!hiteof) {
323                 byte igroup[3], ogroup[4];
324                 int c, n;
325
326                 igroup[0] = igroup[1] = igroup[2] = 0;
327                 for (n = 0; n < 3; n++) {
328                         if (spos >= sourcelen) {
329                                 hiteof = TRUE;
330                                 break;
331                         }
332                         c = source[spos++];
333                         igroup[n] = (byte) c;
334                 }
335                 if (n > 0) {
336                         ogroup[0] = etable[igroup[0] >> 2];
337                         ogroup[1] =
338                             etable[((igroup[0] & 3) << 4) |
339                                    (igroup[1] >> 4)];
340                         ogroup[2] =
341                             etable[((igroup[1] & 0xF) << 2) |
342                                    (igroup[2] >> 6)];
343                         ogroup[3] = etable[igroup[2] & 0x3F];
344
345                         /*
346                          * Replace characters in output stream with "=" pad
347                          * characters if fewer than three characters were
348                          * read from the end of the input stream. 
349                          */
350
351                         if (n < 3) {
352                                 ogroup[3] = '=';
353                                 if (n < 2) {
354                                         ogroup[2] = '=';
355                                 }
356                         }
357                         for (i = 0; i < 4; i++) {
358                                 dest[dpos++] = ogroup[i];
359                                 dest[dpos] = 0;
360                         }
361                         thisline += 4;
362                         if ( (linebreaks) && (thisline > 70) ) {
363                                 dest[dpos++] = '\r';
364                                 dest[dpos++] = '\n';
365                                 dest[dpos] = 0;
366                                 thisline = 0;
367                         }
368                 }
369         }
370         if ( (linebreaks) && (thisline > 70) ) {
371                 dest[dpos++] = '\r';
372                 dest[dpos++] = '\n';
373                 dest[dpos] = 0;
374                 thisline = 0;
375         }
376
377         return(dpos);
378 }
379
380
381
382 /* 
383  * Convert base64-encoded to binary.  Returns the length of the decoded data.
384  * It will stop after reading 'length' bytes.
385  */
386 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
387 {
388     int i, c;
389     int dpos = 0;
390     int spos = 0;
391
392     while (TRUE) {
393         byte a[4], b[4], o[3];
394
395         for (i = 0; i < 4; i++) {
396             if (spos >= length) {
397                 return(dpos);
398             }
399             c = source[spos++];
400
401             if (c == 0) {
402                 if (i > 0) {
403                     return(dpos);
404                 }
405                 return(dpos);
406             }
407             if (dtable[c] & 0x80) {
408                 /* Ignoring errors: discard invalid character. */
409                 i--;
410                 continue;
411             }
412             a[i] = (byte) c;
413             b[i] = (byte) dtable[c];
414         }
415         o[0] = (b[0] << 2) | (b[1] >> 4);
416         o[1] = (b[1] << 4) | (b[2] >> 2);
417         o[2] = (b[2] << 6) | b[3];
418         i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
419         if (i>=1) dest[dpos++] = o[0];
420         if (i>=2) dest[dpos++] = o[1];
421         if (i>=3) dest[dpos++] = o[2];
422         dest[dpos] = 0;
423         if (i < 3) {
424             return(dpos);
425         }
426     }
427 }
428
429
430 /*
431  * if we send out non ascii subjects, we encode it this way.
432  */
433 char *rfc2047encode(char *line, long length)
434 {
435         char *AlreadyEncoded;
436         char *result;
437         long end;
438 #define UTF8_HEADER "=?UTF-8?B?"
439
440         /* check if we're already done */
441         AlreadyEncoded = strstr(line, "=?");
442         if ((AlreadyEncoded != NULL) &&
443             ((strstr(AlreadyEncoded, "?B?") != NULL)||
444              (strstr(AlreadyEncoded, "?Q?") != NULL)))
445         {
446                 return strdup(line);
447         }
448
449         result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
450         strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
451         CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
452         end = strlen (result);
453         result[end]='?';
454         result[end+1]='=';
455         result[end+2]='\0';
456         return result;
457 }
458
459
460 /*
461  * Strip leading and trailing spaces from a string
462  */
463 long striplt(char *buf)
464 {
465         int CountTrail = 0;
466         int FromStart = 1;
467         char *aptr, *bptr;
468
469         if ((buf==NULL) || (IsEmptyStr(buf)))
470                 return 0;
471
472         bptr = aptr = buf;
473
474         while (!IsEmptyStr(aptr)) {
475                 if (isspace(*aptr)) {
476                         if (FromStart)
477                                 aptr ++;
478                         else {
479                                 CountTrail ++;
480                                 *bptr = *aptr;
481                                 aptr++; bptr++;
482                         }
483                 }
484                 else {
485                         CountTrail = 0;
486                         *bptr = *aptr;
487                         aptr++; bptr++;
488                 }
489         }
490
491         if (CountTrail > 0) {
492                 bptr -= CountTrail;
493         }
494
495         *bptr = '\0';
496         return bptr - buf;
497 }
498
499
500
501
502
503 /**
504  * \brief check for the presence of a character within a string (returns count)
505  * \param st the string to examine
506  * \param ch the char to search
507  * \return the position inside of st
508  */
509 int haschar(const char *st,int ch)
510 {
511         const char *ptr;
512         int b;
513         b = 0;
514         ptr = st;
515         while (!IsEmptyStr(ptr))
516         {
517                 if (*ptr == ch)
518                         ++b;
519                 ptr ++;
520         }
521         return (b);
522 }
523
524
525
526
527
528 /*
529  * Format a date/time stamp for output 
530  * seconds is whether to print the seconds
531  */
532 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
533         struct tm tm;
534         int hour;
535
536         /* Month strings for date conversions ... this needs to be localized eventually */
537         char *fmt_date_months[12] = {
538                 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
539         };
540
541         strcpy(buf, "");
542         localtime_r(&thetime, &tm);
543
544         hour = tm.tm_hour;
545         if (hour == 0)  hour = 12;
546         else if (hour > 12) hour = hour - 12;
547
548         if (seconds) {
549                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
550                         fmt_date_months[tm.tm_mon],
551                         tm.tm_mday,
552                         tm.tm_year + 1900,
553                         hour,
554                         tm.tm_min,
555                         tm.tm_sec,
556                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
557                 );
558         } else {
559                 snprintf(buf, n, "%s %d %4d %d:%02d%s",
560                         fmt_date_months[tm.tm_mon],
561                         tm.tm_mday,
562                         tm.tm_year + 1900,
563                         hour,
564                         tm.tm_min,
565                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
566                 );
567         }
568 }
569
570
571
572 /*
573  * Determine whether the specified message number is contained within the
574  * specified sequence set.
575  */
576 int is_msg_in_sequence_set(const char *mset, long msgnum) {
577         int num_sets;
578         int s;
579         char setstr[128], lostr[128], histr[128];
580         long lo, hi;
581
582         num_sets = num_tokens(mset, ',');
583         for (s=0; s<num_sets; ++s) {
584                 extract_token(setstr, mset, s, ',', sizeof setstr);
585
586                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
587                 if (num_tokens(setstr, ':') >= 2) {
588                         extract_token(histr, setstr, 1, ':', sizeof histr);
589                         if (!strcmp(histr, "*")) {
590                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
591                         }
592                 } 
593                 else {
594                         strcpy(histr, lostr);
595                 }
596                 lo = atol(lostr);
597                 hi = atol(histr);
598
599                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
600         }
601
602         return(0);
603 }
604
605 /** 
606  * \brief Utility function to "readline" from memory
607  * \param start Location in memory from which we are reading.
608  * \param buf the buffer to place the string in.
609  * \param maxlen Size of string buffer
610  * \return Pointer to the source memory right after we stopped reading.
611  */
612 char *memreadline(char *start, char *buf, int maxlen)
613 {
614         char ch;
615         char *ptr;
616         int len = 0;            /**< tally our own length to avoid strlen() delays */
617
618         ptr = start;
619
620         while (1) {
621                 ch = *ptr++;
622                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
623                         buf[len++] = ch;
624                 }
625                 if ((ch == 10) || (ch == 0)) {
626                         buf[len] = 0;
627                         return ptr;
628                 }
629         }
630 }
631
632
633 /** 
634  * \brief Utility function to "readline" from memory
635  * \param start Location in memory from which we are reading.
636  * \param buf the buffer to place the string in.
637  * \param maxlen Size of string buffer
638  * \param retlen the length of the returned string
639  * \return Pointer to the source memory right after we stopped reading.
640  */
641 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
642 {
643         char ch;
644         char *ptr;
645         int len = 0;            /**< tally our own length to avoid strlen() delays */
646
647         ptr = start;
648
649         while (1) {
650                 ch = *ptr++;
651                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
652                         buf[len++] = ch;
653                 }
654                 if ((ch == 10) || (ch == 0)) {
655                         buf[len] = 0;
656                         *retlen = len;
657                         return ptr;
658                 }
659         }
660 }
661
662
663
664
665 /*
666  * Strip a boundarized substring out of a string (for example, remove
667  * parentheses and anything inside them).
668  */
669 int stripout(char *str, char leftboundary, char rightboundary) {
670         int a;
671         int lb = (-1);
672         int rb = (-1);
673
674         for (a = 0; a < strlen(str); ++a) {
675                 if (str[a] == leftboundary) lb = a;
676                 if (str[a] == rightboundary) rb = a;
677         }
678
679         if ( (lb > 0) && (rb > lb) ) {
680                 strcpy(&str[lb - 1], &str[rb + 1]);
681                 return 1;
682         }
683
684         else if ( (lb == 0) && (rb > lb) ) {
685                 strcpy(str, &str[rb + 1]);
686                 return 1;
687         }
688         return 0;
689 }
690
691
692 /*
693  * Reduce a string down to a boundarized substring (for example, remove
694  * parentheses and anything outside them).
695  */
696 void stripallbut(char *str, char leftboundary, char rightboundary) {
697         int a;
698
699         for (a = 0; a < strlen(str); ++ a) {
700                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
701         }
702
703         for (a = 0; a < strlen(str); ++ a) {
704                 if (str[a] == rightboundary) str[a] = 0;
705         }
706
707 }
708
709 char *myfgets(char *s, int size, FILE *stream) {
710         char *ret = fgets(s, size, stream);
711         char *nl;
712
713         if (ret != NULL) {
714                 nl = strchr(s, '\n');
715
716                 if (nl != NULL)
717                         *nl = 0;
718         }
719
720         return ret;
721 }
722
723 /** 
724  * \brief Escape a string for feeding out as a URL.
725  * \param outbuf the output buffer
726  * \param oblen the size of outbuf to sanitize
727  * \param strbuf the input buffer
728  */
729 void urlesc(char *outbuf, size_t oblen, char *strbuf)
730 {
731         int a, b, c, len, eclen, olen;
732         char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
733
734         strcpy(outbuf, "");
735         len = strlen(strbuf);
736         eclen = strlen(ec);
737         olen = 0;
738         for (a = 0; a < len; ++a) {
739                 c = 0;
740                 for (b = 0; b < eclen; ++b) {
741                         if (strbuf[a] == ec[b])
742                                 c = 1;
743                 }
744                 if (c == 1) {
745                         snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
746                         olen += 3;
747                 }
748                 else 
749                         outbuf[olen ++] = strbuf[a];
750         }
751         outbuf[olen] = '\0';
752 }
753
754
755
756 /*
757  * In our world, we want strcpy() to be able to work with overlapping strings.
758  */
759 #ifdef strcpy
760 #undef strcpy
761 #endif
762 char *strcpy(char *dest, const char *src) {
763         memmove(dest, src, (strlen(src) + 1) );
764         return(dest);
765 }
766
767
768 /*
769  * Generate a new, globally unique UID parameter for a calendar etc. object
770  */
771 void generate_uuid(char *buf) {
772         static int seq = 0;
773
774         sprintf(buf, "%lx-%lx-%x",
775                 time(NULL),
776                 (long)getpid(),
777                 (seq++)
778         );
779 }
780
781 /*
782  * bmstrcasestr() -- case-insensitive substring search
783  *
784  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
785  * The code is roughly based on the strstr() replacement from 'tin' written
786  * by Urs Jannsen.
787  */
788 inline char *_bmstrcasestr_len(char *text, size_t textlen, char *pattern, size_t patlen) {
789
790         register unsigned char *p, *t;
791         register int i, j, *delta;
792         register size_t p1;
793         int deltaspace[256];
794
795         if (!text) return(NULL);
796         if (!pattern) return(NULL);
797
798         /* algorithm fails if pattern is empty */
799         if ((p1 = patlen) == 0)
800                 return (text);
801
802         /* code below fails (whenever i is unsigned) if pattern too long */
803         if (p1 > textlen)
804                 return (NULL);
805
806         /* set up deltas */
807         delta = deltaspace;
808         for (i = 0; i <= 255; i++)
809                 delta[i] = p1;
810         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
811                 delta[tolower(*p++)] = i;
812
813         /*
814          * From now on, we want patlen - 1.
815          * In the loop below, p points to the end of the pattern,
816          * t points to the end of the text to be tested against the
817          * pattern, and i counts the amount of text remaining, not
818          * including the part to be tested.
819          */
820         p1--;
821         p = (unsigned char *) pattern + p1;
822         t = (unsigned char *) text + p1;
823         i = textlen - patlen;
824         while(1) {
825                 if (tolower(p[0]) == tolower(t[0])) {
826                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
827                                 return ((char *)t - p1);
828                         }
829                 }
830                 j = delta[tolower(t[0])];
831                 if (i < j)
832                         break;
833                 i -= j;
834                 t += j;
835         }
836         return (NULL);
837 }
838
839 /*
840  * bmstrcasestr() -- case-insensitive substring search
841  *
842  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
843  * The code is roughly based on the strstr() replacement from 'tin' written
844  * by Urs Jannsen.
845  */
846 char *bmstrcasestr(char *text, char *pattern) {
847         size_t textlen;
848         size_t patlen;
849
850         if (!text) return(NULL);
851         if (!pattern) return(NULL);
852
853         textlen = strlen (text);
854         patlen = strlen (pattern);
855
856         return _bmstrcasestr_len(text, textlen, pattern, patlen);
857 }
858
859 char *bmstrcasestr_len(char *text, size_t textlen, char *pattern, size_t patlen) {
860         return _bmstrcasestr_len(text, textlen, pattern, patlen);
861 }
862
863 /*
864  * Local replacement for controversial C library function that generates
865  * names for temporary files.  Included to shut up compiler warnings.
866  */
867 void CtdlMakeTempFileName(char *name, int len) {
868         int i = 0;
869
870         while (i++, i < 100) {
871                 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
872                         (long)getpid(),
873                         rand()
874                 );
875                 if (!access(name, F_OK)) {
876                         return;
877                 }
878         }
879 }
880
881
882
883 /*
884  * Determine whether the specified message number is contained within the specified set.
885  * Returns nonzero if the specified message number is in the specified message set string.
886  */
887 int is_msg_in_mset(const char *mset, long msgnum) {
888         int num_sets;
889         int s;
890         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
891         long lo, hi;
892
893         /*
894          * Now set it for all specified messages.
895          */
896         num_sets = num_tokens(mset, ',');
897         for (s=0; s<num_sets; ++s) {
898                 extract_token(setstr, mset, s, ',', sizeof setstr);
899
900                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
901                 if (num_tokens(setstr, ':') >= 2) {
902                         extract_token(histr, setstr, 1, ':', sizeof histr);
903                         if (!strcmp(histr, "*")) {
904                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
905                         }
906                 }
907                 else {
908                         strcpy(histr, lostr);
909                 }
910                 lo = atol(lostr);
911                 hi = atol(histr);
912
913                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
914         }
915
916         return(0);
917 }
918
919
920 /*
921  * searches for a pattern within a search string
922  * returns position in string
923  */
924 int pattern2(char *search, char *patn)
925 {
926         int a;
927         int len, plen;
928         len = strlen (search);
929         plen = strlen (patn);
930         for (a = 0; a < len; ++a) {
931                 if (!strncasecmp(&search[a], patn, plen))
932                         return (a);
933         }
934         return (-1);
935 }
936
937
938 /*
939  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
940  * buf - the string to modify
941  * len - length of the string. 
942  */
943 void stripltlen(char *buf, int *len)
944 {
945         int delta = 0;
946         if (*len == 0) return;
947         while ((*len > delta) && (isspace(buf[delta]))){
948                 delta ++;
949         }
950         memmove (buf, &buf[delta], *len - delta + 1);
951         (*len) -=delta;
952
953         if (*len == 0) return;
954         while (isspace(buf[(*len) - 1])){
955                 buf[--(*len)] = '\0';
956         }
957 }
958
959 /**
960  * \brief detect whether this char starts an utf-8 encoded char
961  * \param Char character to inspect
962  * \returns yes or no
963  */
964 inline int Ctdl_IsUtf8SequenceStart(char Char)
965 {
966 /** 11??.???? indicates an UTF8 Sequence. */
967         return ((Char & 0xC0) != 0);
968 }
969
970 /**
971  * \brief evaluate the length of an utf8 special character sequence
972  * \param Char the character to examine
973  * \returns width of utf8 chars in bytes
974  */
975 inline int Ctdl_GetUtf8SequenceLength(char Char)
976 {
977         int n = 1;
978         char test = (1<<7);
979         
980         while ((n < 8) && ((test & Char) != 0)) {
981                 test = test << 1;
982                 n ++;
983         }
984         if (n > 6)
985                 n = 1;
986         return n;
987 }
988
989 /**
990  * \brief measure the number of glyphs in an UTF8 string...
991  * \param str string to measure
992  * \returns the length of str
993  */
994 int Ctdl_Utf8StrLen(char *str)
995 {
996         int n = 0;
997         int m = 0;
998         char *aptr;
999
1000         if (str == NULL)
1001                 return n;
1002         aptr = str;
1003         while (*aptr != '\0') {
1004                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
1005                         m = Ctdl_GetUtf8SequenceLength(*aptr);
1006                         while ((m-- > 0) && (*aptr++ != '\0'))
1007                                 n ++;
1008                 }
1009                 else {
1010                         n++;
1011                         aptr++;
1012                 }
1013                         
1014         }
1015         return n;
1016 }
1017
1018 /**
1019  * \brief cuts a string after maxlen glyphs
1020  * \param str string to cut to maxlen glyphs
1021  * \param maxlen how long may the string become?
1022  * \returns pointer to maxlen or the end of the string
1023  */
1024 char *Ctdl_Utf8StrCut(char *str, int maxlen)
1025 {
1026         int n = 0, m = 0;
1027         char *aptr;
1028
1029         if (str == NULL)
1030                 return NULL;
1031         aptr = str;
1032         while (*aptr != '\0') {
1033                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
1034                         m = Ctdl_GetUtf8SequenceLength(*aptr);
1035                         while ((m-- > 0) && (*aptr++ != '\0'))
1036                                 n ++;
1037                 }
1038                 else {
1039                         n++;
1040                         aptr++;
1041                 }
1042                 if (n > maxlen) {
1043                         *aptr = '\0';
1044                         return aptr;
1045                 }                       
1046         }
1047         return aptr;
1048 }
1049
1050
1051 /*
1052  * Convert all whitespace characters in a supplied string to underscores
1053  */
1054 void convert_spaces_to_underscores(char *str)
1055 {
1056         int len;
1057         int i;
1058
1059         if (!str) return;
1060
1061         len = strlen(str);
1062         for (i=0; i<len; ++i) {
1063                 if (isspace(str[i])) {
1064                         str[i] = '_';
1065                 }
1066         }
1067 }
1068
1069