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