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