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