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