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