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