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