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