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