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