]> code.citadel.org Git - citadel.git/blob - citadel/tools.c
* tools.c: added bmstrcasestr(), a Boyer-Moore, case-insensitive string search
[citadel.git] / citadel / tools.c
1 /*
2  * $Id$
3  *
4  * Utility functions that are used by both the client and server.
5  *
6  */
7
8 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdarg.h>
20
21 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
23 # include <time.h>
24 #else
25 # if HAVE_SYS_TIME_H
26 #  include <sys/time.h>
27 # else
28 #  include <time.h>
29 # endif
30 #endif
31
32 #include "tools.h"
33 #include "citadel.h"
34
35 #define TRUE  1
36 #define FALSE 0
37
38 typedef unsigned char byte;           /* Byte type */
39 static byte dtable[256];              /* base64 encode / decode table */
40
41
42 char *safestrncpy(char *dest, const char *src, size_t n)
43 {
44         if (dest == NULL || src == NULL) {
45                 fprintf(stderr, "safestrncpy: NULL argument\n");
46                 abort();
47         }
48         strncpy(dest, src, n);
49         dest[n - 1] = 0;
50         return dest;
51 }
52
53
54
55 #ifndef HAVE_STRNCASECMP
56 int strncasecmp(char *lstr, char *rstr, int len)
57 {
58         int pos = 0;
59         char lc,rc;
60         while (pos<len) {
61                 lc=tolower(lstr[pos]);
62                 rc=tolower(rstr[pos]);
63                 if ((lc==0)&&(rc==0)) return(0);
64                 if (lc<rc) return(-1);
65                 if (lc>rc) return(1);
66                 pos=pos+1;
67         }
68         return(0);
69 }
70 #endif
71
72
73
74 /*
75  * num_tokens()  -  discover number of parameters/tokens in a string
76  */
77 int num_tokens(const char *source, char tok) {
78         int a;
79         int count = 1;
80
81         if (source == NULL) return(0);
82         for (a=0; a<strlen(source); ++a) {
83                 if (source[a]==tok) ++count;
84         }
85         return(count);
86 }
87
88
89 /* extract_token() - a smarter string tokenizer */
90 void extract_token(char *dest, const char *source, unsigned long parmnum, char separator)
91 {
92         char *d;                /* dest */
93         const char *s;          /* source */
94         int count = 0;
95
96         strcpy(dest, "");
97
98         /* Locate desired parameter */
99         s = source;
100         while (count < parmnum) {
101                 /* End of string, bail! */
102                 if (!*s) {
103                         s = NULL;
104                         break;
105                 }
106                 if (*s == separator) {
107                         count++;
108                 }
109                 s++;
110         }
111         if (!s) return;         /* Parameter not found */
112
113         for (d = dest; *s && *s != separator; s++, d++) {
114                 *d = *s;
115         }
116         *d = 0;
117 }
118
119
120 /* remove_token() - a tokenizer that kills, maims, and destroys fast */
121 void remove_token(char *source, unsigned long parmnum, char separator)
122 {
123         char *d, *s;            /* dest, source */
124         int count = 0;
125
126         /* Find desired parameter */
127         d = source;
128         while (count < parmnum) {
129                 /* End of string, bail! */
130                 if (!*d) {
131                         d = NULL;
132                         break;
133                 }
134                 if (*d == separator) {
135                         count++;
136                 }
137                 d++;
138         }
139         if (!d) return;         /* Parameter not found */
140
141         /* Find next parameter */
142         s = d;
143         while (*s && *s != separator) {
144                 s++;
145         }
146
147         /* Hack and slash */
148         if (*s)
149                 strcpy(d, ++s);
150         else if (d == source)
151                 *d = 0;
152         else
153                 *--d = 0;
154         /*
155         while (*s) {
156                 *d++ = *s++;
157         }
158         *d = 0;
159         */
160 }
161
162
163 /*
164  * extract_int()  -  extract an int parm w/o supplying a buffer
165  */
166 int extract_int(const char *source, unsigned long parmnum)
167 {
168         char buf[SIZ];
169         
170         extract_token(buf, source, parmnum, '|');
171         return(atoi(buf));
172 }
173
174 /*
175  * extract_long()  -  extract an long parm w/o supplying a buffer
176  */
177 long extract_long(const char *source, unsigned long parmnum)
178 {
179         char buf[SIZ];
180         
181         extract_token(buf, source, parmnum, '|');
182         return(atol(buf));
183 }
184
185
186 /*
187  * extract_unsigned_long() - extract an unsigned long parm
188  */
189 unsigned long extract_unsigned_long(const char *source, unsigned long parmnum)
190 {
191         char buf[SIZ];
192
193         extract_token(buf, source, parmnum, '|');
194         return strtoul(buf, NULL, 10);
195 }
196
197
198 /*
199  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
200  * John Walker, found in full in the file "base64.c" included with this
201  * distribution.  We are moving in the direction of eventually discarding
202  * the separate executables, and using the ones in our code exclusively.
203  */
204
205 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
206 {
207     int i, hiteof = FALSE;
208     int spos = 0;
209     int dpos = 0;
210
211     /*  Fill dtable with character encodings.  */
212
213     for (i = 0; i < 26; i++) {
214         dtable[i] = 'A' + i;
215         dtable[26 + i] = 'a' + i;
216     }
217     for (i = 0; i < 10; i++) {
218         dtable[52 + i] = '0' + i;
219     }
220     dtable[62] = '+';
221     dtable[63] = '/';
222
223     while (!hiteof) {
224         byte igroup[3], ogroup[4];
225         int c, n;
226
227         igroup[0] = igroup[1] = igroup[2] = 0;
228         for (n = 0; n < 3; n++) {
229             if (spos >= sourcelen) {
230                 hiteof = TRUE;
231                 break;
232             }
233             c = source[spos++];
234             igroup[n] = (byte) c;
235         }
236         if (n > 0) {
237             ogroup[0] = dtable[igroup[0] >> 2];
238             ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
239             ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
240             ogroup[3] = dtable[igroup[2] & 0x3F];
241
242             /* Replace characters in output stream with "=" pad
243                characters if fewer than three characters were
244                read from the end of the input stream. */
245
246             if (n < 3) {
247                 ogroup[3] = '=';
248                 if (n < 2) {
249                     ogroup[2] = '=';
250                 }
251             }
252             for (i = 0; i < 4; i++) {
253                 dest[dpos++] = ogroup[i];
254                 dest[dpos] = 0;
255             }
256         }
257     }
258 }
259
260
261 /* 
262  * Convert base64-encoded to binary.  Returns the length of the decoded data.
263  * It will stop after reading 'length' bytes.
264  */
265 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
266 {
267     int i, c;
268     int dpos = 0;
269     int spos = 0;
270
271     for (i = 0; i < 255; i++) {
272         dtable[i] = 0x80;
273     }
274     for (i = 'A'; i <= 'Z'; i++) {
275         dtable[i] = 0 + (i - 'A');
276     }
277     for (i = 'a'; i <= 'z'; i++) {
278         dtable[i] = 26 + (i - 'a');
279     }
280     for (i = '0'; i <= '9'; i++) {
281         dtable[i] = 52 + (i - '0');
282     }
283     dtable['+'] = 62;
284     dtable['/'] = 63;
285     dtable['='] = 0;
286
287     /*CONSTANTCONDITION*/
288     while (TRUE) {
289         byte a[4], b[4], o[3];
290
291         for (i = 0; i < 4; i++) {
292             if (spos >= length) {
293                 return(dpos);
294             }
295             c = source[spos++];
296
297             if (c == 0) {
298                 if (i > 0) {
299                     return(dpos);
300                 }
301                 return(dpos);
302             }
303             if (dtable[c] & 0x80) {
304                 /* Ignoring errors: discard invalid character. */
305                 i--;
306                 continue;
307             }
308             a[i] = (byte) c;
309             b[i] = (byte) dtable[c];
310         }
311         o[0] = (b[0] << 2) | (b[1] >> 4);
312         o[1] = (b[1] << 4) | (b[2] >> 2);
313         o[2] = (b[2] << 6) | b[3];
314         i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
315         if (i>=1) dest[dpos++] = o[0];
316         if (i>=2) dest[dpos++] = o[1];
317         if (i>=3) dest[dpos++] = o[2];
318         dest[dpos] = 0;
319         if (i < 3) {
320             return(dpos);
321         }
322     }
323 }
324
325
326
327 /*
328  * Strip leading and trailing spaces from a string
329  */
330 void striplt(char *buf)
331 {
332         while ((strlen(buf) > 0) && (isspace(buf[0])))
333                 strcpy(buf, &buf[1]);
334         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
335                 buf[strlen(buf) - 1] = 0;
336 }
337
338
339
340
341
342 /* 
343  * Return the number of occurances of character ch in string st
344  */ 
345 int haschar(const char *st, int ch)
346 {
347         int a, b;
348         b = 0;
349         for (a = 0; a < strlen(st); ++a)
350                 if (st[a] == ch)
351                         ++b;
352         return (b);
353 }
354
355
356
357
358
359 /*
360  * Format a date/time stamp for output 
361  * seconds is whether to print the seconds
362  */
363 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
364         struct tm *tm;
365         int hour;
366
367         char *ascmonths[] = {
368                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
369                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
370         };
371
372         strcpy(buf, "");
373         tm = localtime(&thetime);
374
375         hour = tm->tm_hour;
376         if (hour == 0)  hour = 12;
377         else if (hour > 12) hour = hour - 12;
378
379         if (seconds) {
380                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
381                         ascmonths[tm->tm_mon],
382                         tm->tm_mday,
383                         tm->tm_year + 1900,
384                         hour,
385                         tm->tm_min,
386                         tm->tm_sec,
387                         ( (tm->tm_hour >= 12) ? "pm" : "am" )
388                 );
389         } else {
390                 snprintf(buf, n, "%s %d %4d %d:%02d%s",
391                         ascmonths[tm->tm_mon],
392                         tm->tm_mday,
393                         tm->tm_year + 1900,
394                         hour,
395                         tm->tm_min,
396                         ( (tm->tm_hour >= 12) ? "pm" : "am" )
397                 );
398         }
399 }
400
401
402
403 /*
404  * Determine whether the specified message number is contained within the
405  * specified set.
406  */
407 int is_msg_in_mset(char *mset, long msgnum) {
408         int num_sets;
409         int s;
410         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
411         long lo, hi;
412
413         /*
414          * Now set it for all specified messages.
415          */
416         num_sets = num_tokens(mset, ',');
417         for (s=0; s<num_sets; ++s) {
418                 extract_token(setstr, mset, s, ',');
419
420                 extract_token(lostr, setstr, 0, ':');
421                 if (num_tokens(setstr, ':') >= 2) {
422                         extract_token(histr, setstr, 1, ':');
423                         if (!strcmp(histr, "*")) {
424                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
425                         }
426                 } 
427                 else {
428                         strcpy(histr, lostr);
429                 }
430                 lo = atol(lostr);
431                 hi = atol(histr);
432
433                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
434         }
435
436         return(0);
437 }
438
439
440 /*
441  * Utility function to "readline" from memory
442  * (returns new pointer)
443  */
444 char *memreadline(char *start, char *buf, int maxlen)
445 {
446         char ch;
447         char *ptr;
448         int len = 0;    /* tally our own length to avoid strlen() delays */
449
450         ptr = start;
451         memset(buf, 0, maxlen);
452
453         while (1) {
454                 ch = *ptr++;
455                 if ( (len < (maxlen - 1)) && (ch != 13) && (ch != 10) ) {
456                         buf[strlen(buf) + 1] = 0;
457                         buf[strlen(buf)] = ch;
458                         ++len;
459                 }
460                 if ((ch == 10) || (ch == 0)) {
461                         return ptr;
462                 }
463         }
464 }
465
466
467 /*
468  * Strip a boundarized substring out of a string (for example, remove
469  * parentheses and anything inside them).
470  */
471 void stripout(char *str, char leftboundary, char rightboundary) {
472         int a;
473         int lb = (-1);
474         int rb = (-1);
475
476         for (a = 0; a < strlen(str); ++a) {
477                 if (str[a] == leftboundary) lb = a;
478                 if (str[a] == rightboundary) rb = a;
479         }
480
481         if ( (lb > 0) && (rb > lb) ) {
482                 strcpy(&str[lb - 1], &str[rb + 1]);
483         }
484
485 }
486
487
488 /*
489  * Reduce a string down to a boundarized substring (for example, remove
490  * parentheses and anything outside them).
491  */
492 void stripallbut(char *str, char leftboundary, char rightboundary) {
493         int a;
494
495         for (a = 0; a < strlen(str); ++ a) {
496                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
497         }
498
499         for (a = 0; a < strlen(str); ++ a) {
500                 if (str[a] == rightboundary) str[a] = 0;
501         }
502
503 }
504
505 char *myfgets(char *s, int size, FILE *stream) {
506         char *ret = fgets(s, size, stream);
507         char *nl;
508
509         if (ret != NULL) {
510                 nl = strchr(s, '\n');
511
512                 if (nl != NULL)
513                         *nl = 0;
514         }
515
516         return ret;
517 }
518
519 /*
520  * Escape a string for feeding out as a URL.
521  * Output buffer must be big enough to handle escape expansion!
522  */
523 void urlesc(char *outbuf, char *strbuf)
524 {
525         int a, b, c;
526         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
527
528         strcpy(outbuf, "");
529
530         for (a = 0; a < strlen(strbuf); ++a) {
531                 c = 0;
532                 for (b = 0; b < strlen(ec); ++b) {
533                         if (strbuf[a] == ec[b])
534                                 c = 1;
535                 }
536                 b = strlen(outbuf);
537                 if (c == 1)
538                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
539                 else
540                         sprintf(&outbuf[b], "%c", strbuf[a]);
541         }
542 }
543
544
545 /*
546  * Citadelian replacement for tmpnam()
547  */
548 char *CtdlTempFileName(char *prefix1, int prefix2) {
549         static int seq = 0;
550         static char buf[SIZ];
551
552         sprintf(buf, "/tmp/Citadel-%s-%d-%04x-%04x",
553                 prefix1,
554                 prefix2,
555                 (int)getpid(),
556                 ++seq
557         );
558         
559         return(buf);
560 }
561
562
563 /*
564  * Citadelian replacement for tmpfile()
565  */
566 FILE *CtdlTempFile(void) {
567         char filename[SIZ];
568         FILE *fp;
569
570         strcpy(filename, tmpnam(NULL));
571         fp = fopen(filename, "w+b");
572         unlink(filename);
573         return(fp);
574 }
575
576
577 /*
578  * bmstrcasestr() is a variant of strstr() that is both case-insensitive
579  * and uses the Boyer-Moore search algorithm.
580  * 
581  * Original code: copyright (c) 1997-1998 by Urs Janssen <urs@tin.org>
582  * Modifications: copyright (c) 2003 by Art Cancro <ajc@uncensored.citadel.org>
583  */
584 char *bmstrcasestr(char *text, char *pattern)
585 {
586         register unsigned char *p, *t;
587         register int i, j, *delta;
588         register size_t p1;
589         int deltaspace[256];
590         size_t textlen;
591         size_t patlen;
592
593         textlen = strlen(text);
594         patlen = strlen(pattern);
595
596         /* algorithm fails if pattern is empty */
597         if ((p1 = patlen) == 0)
598                 return (text);
599
600         /* code below fails (whenever i is unsigned) if pattern too long */
601         if (p1 > textlen)
602                 return (NULL);
603
604         /* set up deltas */
605         delta = deltaspace;
606         for (i = 0; i <= 255; i++)
607                 delta[i] = p1;
608         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
609                 delta[*p++] = i;
610
611         /*
612          * From now on, we want patlen - 1.
613          * In the loop below, p points to the end of the pattern,
614          * t points to the end of the text to be tested against the
615          * pattern, and i counts the amount of text remaining, not
616          * including the part to be tested.
617          */
618         p1--;
619         p = (unsigned char *) pattern + p1;
620         t = (unsigned char *) text + p1;
621         i = textlen - patlen;
622         while (1) {
623                 if (tolower(*p) == tolower(*t)
624                    && strncasecmp((p - p1), (t - p1), p1) == 0)
625                         return ((char *) t - p1);
626                 j = delta[*t];
627                 if (i < j)
628                         break;
629                 i -= j;
630                 t += j;
631         }
632         return (NULL);
633 }
634