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