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