]> code.citadel.org Git - citadel.git/blob - citadel/tools.c
4a5e4cac0fa0a24305fcdf9469e38e1840be7654
[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         size_t len;
444         int a;
445         if (IsEmptyStr(buf)) return;
446         len = strlen(buf);
447         while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
448                 buf[--len] = 0;
449         if (IsEmptyStr(buf)) return;
450         a = 0;
451         while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
452                 a++;
453         if (a > 0)
454                 memmove(buf, &buf[a], len - a + 1);
455 }
456
457
458
459
460
461 /**
462  * \brief check for the presence of a character within a string (returns count)
463  * \param st the string to examine
464  * \param ch the char to search
465  * \return the position inside of st
466  */
467 int haschar(const char *st,int ch)
468 {
469         const char *ptr;
470         int b;
471         b = 0;
472         ptr = st;
473         while (!IsEmptyStr(ptr))
474         {
475                 if (*ptr == ch)
476                         ++b;
477                 ptr ++;
478         }
479         return (b);
480 }
481
482
483
484
485
486 /*
487  * Format a date/time stamp for output 
488  * seconds is whether to print the seconds
489  */
490 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
491         struct tm tm;
492         int hour;
493
494         strcpy(buf, "");
495         localtime_r(&thetime, &tm);
496
497         hour = tm.tm_hour;
498         if (hour == 0)  hour = 12;
499         else if (hour > 12) hour = hour - 12;
500
501         if (seconds) {
502                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
503                         ascmonths[tm.tm_mon],
504                         tm.tm_mday,
505                         tm.tm_year + 1900,
506                         hour,
507                         tm.tm_min,
508                         tm.tm_sec,
509                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
510                 );
511         } else {
512                 snprintf(buf, n, "%s %d %4d %d:%02d%s",
513                         ascmonths[tm.tm_mon],
514                         tm.tm_mday,
515                         tm.tm_year + 1900,
516                         hour,
517                         tm.tm_min,
518                         ( (tm.tm_hour >= 12) ? "pm" : "am" )
519                 );
520         }
521 }
522
523
524
525 /*
526  * Determine whether the specified message number is contained within the
527  * specified sequence set.
528  */
529 int is_msg_in_sequence_set(char *mset, long msgnum) {
530         int num_sets;
531         int s;
532         char setstr[128], lostr[128], histr[128];
533         long lo, hi;
534
535         num_sets = num_tokens(mset, ',');
536         for (s=0; s<num_sets; ++s) {
537                 extract_token(setstr, mset, s, ',', sizeof setstr);
538
539                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
540                 if (num_tokens(setstr, ':') >= 2) {
541                         extract_token(histr, setstr, 1, ':', sizeof histr);
542                         if (!strcmp(histr, "*")) {
543                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
544                         }
545                 } 
546                 else {
547                         strcpy(histr, lostr);
548                 }
549                 lo = atol(lostr);
550                 hi = atol(histr);
551
552                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
553         }
554
555         return(0);
556 }
557
558 /** 
559  * \brief Utility function to "readline" from memory
560  * \param start Location in memory from which we are reading.
561  * \param buf the buffer to place the string in.
562  * \param maxlen Size of string buffer
563  * \return Pointer to the source memory right after we stopped reading.
564  */
565 char *memreadline(char *start, char *buf, int maxlen)
566 {
567         char ch;
568         char *ptr;
569         int len = 0;            /**< tally our own length to avoid strlen() delays */
570
571         ptr = start;
572
573         while (1) {
574                 ch = *ptr++;
575                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
576                         buf[len++] = ch;
577                 }
578                 if ((ch == 10) || (ch == 0)) {
579                         buf[len] = 0;
580                         return ptr;
581                 }
582         }
583 }
584
585
586
587
588 /*
589  * Strip a boundarized substring out of a string (for example, remove
590  * parentheses and anything inside them).
591  */
592 void stripout(char *str, char leftboundary, char rightboundary) {
593         int a;
594         int lb = (-1);
595         int rb = (-1);
596
597         for (a = 0; a < strlen(str); ++a) {
598                 if (str[a] == leftboundary) lb = a;
599                 if (str[a] == rightboundary) rb = a;
600         }
601
602         if ( (lb > 0) && (rb > lb) ) {
603                 strcpy(&str[lb - 1], &str[rb + 1]);
604         }
605
606         else if ( (lb == 0) && (rb > lb) ) {
607                 strcpy(str, &str[rb + 1]);
608         }
609
610 }
611
612
613 /*
614  * Reduce a string down to a boundarized substring (for example, remove
615  * parentheses and anything outside them).
616  */
617 void stripallbut(char *str, char leftboundary, char rightboundary) {
618         int a;
619
620         for (a = 0; a < strlen(str); ++ a) {
621                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
622         }
623
624         for (a = 0; a < strlen(str); ++ a) {
625                 if (str[a] == rightboundary) str[a] = 0;
626         }
627
628 }
629
630 char *myfgets(char *s, int size, FILE *stream) {
631         char *ret = fgets(s, size, stream);
632         char *nl;
633
634         if (ret != NULL) {
635                 nl = strchr(s, '\n');
636
637                 if (nl != NULL)
638                         *nl = 0;
639         }
640
641         return ret;
642 }
643
644 /*
645  * Escape a string for feeding out as a URL.
646  * Output buffer must be big enough to handle escape expansion!
647  */
648 void urlesc(char *outbuf, char *strbuf)
649 {
650         int a, b, c;
651         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
652
653         strcpy(outbuf, "");
654
655         for (a = 0; a < (int)strlen(strbuf); ++a) {
656                 c = 0;
657                 for (b = 0; b < strlen(ec); ++b) {
658                         if (strbuf[a] == ec[b])
659                                 c = 1;
660                 }
661                 b = strlen(outbuf);
662                 if (c == 1)
663                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
664                 else
665                         sprintf(&outbuf[b], "%c", strbuf[a]);
666         }
667 }
668
669
670
671 /*
672  * In our world, we want strcpy() to be able to work with overlapping strings.
673  */
674 #ifdef strcpy
675 #undef strcpy
676 #endif
677 char *strcpy(char *dest, const char *src) {
678         memmove(dest, src, (strlen(src) + 1) );
679         return(dest);
680 }
681
682
683 /*
684  * Generate a new, globally unique UID parameter for a calendar etc. object
685  */
686 void generate_uuid(char *buf) {
687         static int seq = 0;
688
689         sprintf(buf, "%lx-"F_XPID_T"-%x",
690                 time(NULL),
691                 getpid(),
692                 (seq++)
693         );
694 }
695
696 /*
697  * bmstrcasestr() -- case-insensitive substring search
698  *
699  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
700  * The code is roughly based on the strstr() replacement from 'tin' written
701  * by Urs Jannsen.
702  */
703 char *bmstrcasestr(char *text, char *pattern) {
704
705         register unsigned char *p, *t;
706         register int i, j, *delta;
707         register size_t p1;
708         int deltaspace[256];
709         size_t textlen;
710         size_t patlen;
711
712         textlen = strlen (text);
713         patlen = strlen (pattern);
714
715         /* algorithm fails if pattern is empty */
716         if ((p1 = patlen) == 0)
717                 return (text);
718
719         /* code below fails (whenever i is unsigned) if pattern too long */
720         if (p1 > textlen)
721                 return (NULL);
722
723         /* set up deltas */
724         delta = deltaspace;
725         for (i = 0; i <= 255; i++)
726                 delta[i] = p1;
727         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
728                 delta[tolower(*p++)] = i;
729
730         /*
731          * From now on, we want patlen - 1.
732          * In the loop below, p points to the end of the pattern,
733          * t points to the end of the text to be tested against the
734          * pattern, and i counts the amount of text remaining, not
735          * including the part to be tested.
736          */
737         p1--;
738         p = (unsigned char *) pattern + p1;
739         t = (unsigned char *) text + p1;
740         i = textlen - patlen;
741         while(1) {
742                 if (tolower(p[0]) == tolower(t[0])) {
743                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
744                                 return ((char *)t - p1);
745                         }
746                 }
747                 j = delta[tolower(t[0])];
748                 if (i < j)
749                         break;
750                 i -= j;
751                 t += j;
752         }
753         return (NULL);
754 }
755
756
757
758 /*
759  * Local replacement for controversial C library function that generates
760  * names for temporary files.  Included to shut up compiler warnings.
761  */
762 void CtdlMakeTempFileName(char *name, int len) {
763         int i = 0;
764
765         while (i++, i < 100) {
766                 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
767                         getpid(),
768                         rand()
769                 );
770                 if (!access(name, F_OK)) {
771                         return;
772                 }
773         }
774 }