* Bug fixes: Fix numerous char array size mismatches, signed/unsigned
[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 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <stdarg.h>
20
21 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
23 # include <time.h>
24 #else
25 # if HAVE_SYS_TIME_H
26 #  include <sys/time.h>
27 # else
28 #  include <time.h>
29 # endif
30 #endif
31
32 #include "tools.h"
33 #include "citadel.h"
34
35 #define TRUE  1
36 #define FALSE 0
37
38 typedef unsigned char byte;           /* Byte type */
39 static byte dtable[256];              /* base64 encode / decode table */
40
41
42 char *safestrncpy(char *dest, const char *src, size_t n)
43 {
44         if (dest == NULL || src == NULL) {
45                 fprintf(stderr, "safestrncpy: NULL argument\n");
46                 abort();
47         }
48         strncpy(dest, src, n);
49         dest[n - 1] = 0;
50         return dest;
51 }
52
53
54
55 #ifndef HAVE_STRNCASECMP
56 int strncasecmp(char *lstr, char *rstr, int len)
57 {
58         int pos = 0;
59         char lc,rc;
60         while (pos<len) {
61                 lc=tolower(lstr[pos]);
62                 rc=tolower(rstr[pos]);
63                 if ((lc==0)&&(rc==0)) return(0);
64                 if (lc<rc) return(-1);
65                 if (lc>rc) return(1);
66                 pos=pos+1;
67         }
68         return(0);
69 }
70 #endif
71
72
73
74 /*
75  * num_tokens()  -  discover number of parameters/tokens in a string
76  */
77 int num_tokens(const char *source, char tok) {
78         int a;
79         int count = 1;
80
81         if (source == NULL) return(0);
82         for (a=0; a<strlen(source); ++a) {
83                 if (source[a]==tok) ++count;
84         }
85         return(count);
86 }
87
88
89 /* extract_token_fast() - a smarter string tokenizer */
90 void extract_token(char *dest, const char *source, unsigned long parmnum, char separator)
91 {
92         char *d;                /* dest */
93         const char *s;          /* source */
94         int count = 0;
95
96         strcpy(dest, "");
97
98         /* Locate desired parameter */
99         s = source;
100         while (count < parmnum) {
101                 /* End of string, bail! */
102                 if (!*s) {
103                         s = NULL;
104                         break;
105                 }
106                 if (*s == separator) {
107                         count++;
108                 }
109                 s++;
110         }
111         if (!s) return;         /* Parameter not found */
112
113         for (d = dest; *s && *s != separator; s++, d++) {
114                 *d = *s;
115         }
116         *d = 0;
117 }
118
119
120 /*
121  * extract_token()  -  a smarter string tokenizer
122  */
123 void extract_token_old(char *dest, const char *source, unsigned long parmnum, char separator) 
124 {
125         int i;
126         int len;
127         int curr_parm;
128
129         strcpy(dest,"");
130         len = 0;
131         curr_parm = 0;
132
133         if (strlen(source)==0) {
134                 return;
135         }
136
137         for (i=0; i<strlen(source); ++i) {
138                 if (source[i]==separator) {
139                         ++curr_parm;
140                 }
141                 else if (curr_parm == parmnum) {
142                         dest[len+1] = 0;
143                         dest[len++] = source[i];
144                 }
145         }
146 }
147
148
149
150 /* remove_token_fast() - a tokenizer that kills, maims, and destroys fast */
151 void remove_token(char *source, unsigned long parmnum, char separator)
152 {
153         char *d, *s;            /* dest, source */
154         int count = 0;
155
156         /* Find desired parameter */
157         d = source;
158         while (count < parmnum) {
159                 /* End of string, bail! */
160                 if (!*d) {
161                         d = NULL;
162                         break;
163                 }
164                 if (*d == separator) {
165                         count++;
166                 }
167                 d++;
168         }
169         if (!d) return;         /* Parameter not found */
170
171         /* Find next parameter */
172         s = d;
173         while (*s && *s != separator) {
174                 s++;
175         }
176
177         /* Hack and slash */
178         if (*s)
179                 strcpy(d, ++s);
180         else if (d == source)
181                 *d = 0;
182         else
183                 *--d = 0;
184         /*
185         while (*s) {
186                 *d++ = *s++;
187         }
188         *d = 0;
189         */
190 }
191
192
193 /*
194  * remove_token()  -  a tokenizer that kills, maims, and destroys
195  */
196 void remove_token_old(char *source, int parmnum, char separator)
197 {
198         int i;
199         int len;
200         int curr_parm;
201         int start, end;
202
203         len = 0;
204         curr_parm = 0;
205         start = (-1);
206         end = (-1);
207
208         if (strlen(source)==0) {
209                 return;
210         }
211
212         for (i=0; i<strlen(source); ++i) {
213                 if ( (start < 0) && (curr_parm == parmnum) ) {
214                         start = i;
215                 }
216
217                 if ( (end < 0) && (curr_parm == (parmnum+1)) ) {
218                         end = i;
219                 }
220
221                 if (source[i]==separator) {
222                         ++curr_parm;
223                 }
224         }
225
226         if (end < 0) end = strlen(source);
227         strcpy(&source[start], &source[end]);
228 }
229
230
231
232
233 /*
234  * extract_int()  -  extract an int parm w/o supplying a buffer
235  */
236 int extract_int(const char *source, unsigned long parmnum)
237 {
238         char buf[SIZ];
239         
240         extract_token(buf, source, parmnum, '|');
241         return(atoi(buf));
242 }
243
244 /*
245  * extract_long()  -  extract an long parm w/o supplying a buffer
246  */
247 long extract_long(const char *source, unsigned long parmnum)
248 {
249         char buf[SIZ];
250         
251         extract_token(buf, source, parmnum, '|');
252         return(atol(buf));
253 }
254
255
256 /*
257  * extract_unsigned_long() - extract an unsigned long parm
258  */
259 unsigned long extract_unsigned_long(const char *source, unsigned long parmnum)
260 {
261         char buf[SIZ];
262
263         extract_token(buf, source, parmnum, '|');
264         return strtoul(buf, NULL, 10);
265 }
266
267
268 /*
269  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
270  * John Walker, found in full in the file "base64.c" included with this
271  * distribution.  We are moving in the direction of eventually discarding
272  * the separate executables, and using the ones in our code exclusively.
273  */
274
275 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
276 {
277     int i, hiteof = FALSE;
278     int spos = 0;
279     int dpos = 0;
280
281     /*  Fill dtable with character encodings.  */
282
283     for (i = 0; i < 26; i++) {
284         dtable[i] = 'A' + i;
285         dtable[26 + i] = 'a' + i;
286     }
287     for (i = 0; i < 10; i++) {
288         dtable[52 + i] = '0' + i;
289     }
290     dtable[62] = '+';
291     dtable[63] = '/';
292
293     while (!hiteof) {
294         byte igroup[3], ogroup[4];
295         int c, n;
296
297         igroup[0] = igroup[1] = igroup[2] = 0;
298         for (n = 0; n < 3; n++) {
299             if (spos >= sourcelen) {
300                 hiteof = TRUE;
301                 break;
302             }
303             c = source[spos++];
304             igroup[n] = (byte) c;
305         }
306         if (n > 0) {
307             ogroup[0] = dtable[igroup[0] >> 2];
308             ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
309             ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
310             ogroup[3] = dtable[igroup[2] & 0x3F];
311
312             /* Replace characters in output stream with "=" pad
313                characters if fewer than three characters were
314                read from the end of the input stream. */
315
316             if (n < 3) {
317                 ogroup[3] = '=';
318                 if (n < 2) {
319                     ogroup[2] = '=';
320                 }
321             }
322             for (i = 0; i < 4; i++) {
323                 dest[dpos++] = ogroup[i];
324                 dest[dpos] = 0;
325             }
326         }
327     }
328 }
329
330
331 /* 
332  * Convert base64-encoded to binary.  Returns the length of the decoded data.
333  * It will stop after reading 'length' bytes.
334  */
335 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
336 {
337     int i, c;
338     int dpos = 0;
339     int spos = 0;
340
341     for (i = 0; i < 255; i++) {
342         dtable[i] = 0x80;
343     }
344     for (i = 'A'; i <= 'Z'; i++) {
345         dtable[i] = 0 + (i - 'A');
346     }
347     for (i = 'a'; i <= 'z'; i++) {
348         dtable[i] = 26 + (i - 'a');
349     }
350     for (i = '0'; i <= '9'; i++) {
351         dtable[i] = 52 + (i - '0');
352     }
353     dtable['+'] = 62;
354     dtable['/'] = 63;
355     dtable['='] = 0;
356
357     /*CONSTANTCONDITION*/
358     while (TRUE) {
359         byte a[4], b[4], o[3];
360
361         for (i = 0; i < 4; i++) {
362             if (spos >= length) {
363                 return(dpos);
364             }
365             c = source[spos++];
366
367             if (c == 0) {
368                 if (i > 0) {
369                     return(dpos);
370                 }
371                 return(dpos);
372             }
373             if (dtable[c] & 0x80) {
374                 /* Ignoring errors: discard invalid character. */
375                 i--;
376                 continue;
377             }
378             a[i] = (byte) c;
379             b[i] = (byte) dtable[c];
380         }
381         o[0] = (b[0] << 2) | (b[1] >> 4);
382         o[1] = (b[1] << 4) | (b[2] >> 2);
383         o[2] = (b[2] << 6) | b[3];
384         i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
385         if (i>=1) dest[dpos++] = o[0];
386         if (i>=2) dest[dpos++] = o[1];
387         if (i>=3) dest[dpos++] = o[2];
388         dest[dpos] = 0;
389         if (i < 3) {
390             return(dpos);
391         }
392     }
393 }
394
395
396
397 /*
398  * Strip leading and trailing spaces from a string
399  */
400 void striplt(char *buf)
401 {
402         while ((strlen(buf) > 0) && (isspace(buf[0])))
403                 strcpy(buf, &buf[1]);
404         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
405                 buf[strlen(buf) - 1] = 0;
406 }
407
408
409
410
411
412 /* 
413  * Return the number of occurances of character ch in string st
414  */ 
415 int haschar(const char *st, int ch)
416 {
417         int a, b;
418         b = 0;
419         for (a = 0; a < strlen(st); ++a)
420                 if (st[a] == ch)
421                         ++b;
422         return (b);
423 }
424
425
426
427
428 /*
429  * Compare two strings, insensitive to case, punctuation, and non-alnum chars
430  */
431 int collapsed_strcmp(char *s1, char *s2) {
432         char *c1, *c2;
433         int i, ret, pos;
434
435         c1 = malloc(strlen(s1)+1);
436         c2 = malloc(strlen(s2)+1);
437         c1[0] = 0;
438         c2[0] = 0;
439
440         pos = 0;
441         for (i=0; i<strlen(s1); ++i) {
442                 if (isalnum(s1[i])) {
443                         c1[pos] = tolower(s1[i]);
444                         c1[++pos] = 0;
445                 }
446         }
447
448         pos = 0;
449         for (i=0; i<strlen(s2); ++i) {
450                 if (isalnum(s2[i])) {
451                         c2[pos] = tolower(s2[i]);
452                         c2[++pos] = 0;
453                 }
454         }
455
456         ret = strcmp(c1, c2);
457         free(c1);
458         free(c2);
459         return(ret);
460 }
461
462
463
464 /*
465  * Format a date/time stamp for output 
466  * seconds is whether to print the seconds
467  */
468 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
469         struct tm *tm;
470         int hour;
471
472         char *ascmonths[] = {
473                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
474                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
475         };
476
477         strcpy(buf, "");
478         tm = localtime(&thetime);
479
480         hour = tm->tm_hour;
481         if (hour == 0)  hour = 12;
482         else if (hour > 12) hour = hour - 12;
483
484         if (seconds) {
485                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
486                         ascmonths[tm->tm_mon],
487                         tm->tm_mday,
488                         tm->tm_year + 1900,
489                         hour,
490                         tm->tm_min,
491                         tm->tm_sec,
492                         ( (tm->tm_hour >= 12) ? "pm" : "am" )
493                 );
494         } else {
495                 snprintf(buf, n, "%s %d %4d %d:%02d%s",
496                         ascmonths[tm->tm_mon],
497                         tm->tm_mday,
498                         tm->tm_year + 1900,
499                         hour,
500                         tm->tm_min,
501                         ( (tm->tm_hour >= 12) ? "pm" : "am" )
502                 );
503         }
504 }
505
506
507
508 /*
509  * Determine whether the specified message number is contained within the
510  * specified set.
511  */
512 int is_msg_in_mset(char *mset, long msgnum) {
513         int num_sets;
514         int s;
515         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
516         long lo, hi;
517
518         /*
519          * Now set it for all specified messages.
520          */
521         num_sets = num_tokens(mset, ',');
522         for (s=0; s<num_sets; ++s) {
523                 extract_token(setstr, mset, s, ',');
524
525                 extract_token(lostr, setstr, 0, ':');
526                 if (num_tokens(setstr, ':') >= 2) {
527                         extract_token(histr, setstr, 1, ':');
528                         if (!strcmp(histr, "*")) {
529                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
530                         }
531                 } 
532                 else {
533                         strcpy(histr, lostr);
534                 }
535                 lo = atol(lostr);
536                 hi = atol(histr);
537
538                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
539         }
540
541         return(0);
542 }
543
544
545 /*
546  * Utility function to "readline" from memory
547  * (returns new pointer)
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         memset(buf, 0, maxlen);
557
558         while (1) {
559                 ch = *ptr++;
560                 if ( (len < (maxlen - 1)) && (ch != 13) && (ch != 10) ) {
561                         buf[strlen(buf) + 1] = 0;
562                         buf[strlen(buf)] = ch;
563                         ++len;
564                 }
565                 if ((ch == 10) || (ch == 0)) {
566                         return ptr;
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 }
591
592
593 /*
594  * Reduce a string down to a boundarized substring (for example, remove
595  * parentheses and anything outside them).
596  */
597 void stripallbut(char *str, char leftboundary, char rightboundary) {
598         int a;
599
600         for (a = 0; a < strlen(str); ++ a) {
601                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
602         }
603
604         for (a = 0; a < strlen(str); ++ a) {
605                 if (str[a] == rightboundary) str[a] = 0;
606         }
607
608 }
609
610 char *myfgets(char *s, int size, FILE *stream) {
611         char *ret = fgets(s, size, stream);
612         char *nl;
613
614         if (ret != NULL) {
615                 nl = strchr(s, '\n');
616
617                 if (nl != NULL)
618                         *nl = 0;
619         }
620
621         return ret;
622 }
623
624 /*
625  * Escape a string for feeding out as a URL.
626  * Output buffer must be big enough to handle escape expansion!
627  */
628 void urlesc(char *outbuf, char *strbuf)
629 {
630         int a, b, c;
631         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
632
633         strcpy(outbuf, "");
634
635         for (a = 0; a < strlen(strbuf); ++a) {
636                 c = 0;
637                 for (b = 0; b < strlen(ec); ++b) {
638                         if (strbuf[a] == ec[b])
639                                 c = 1;
640                 }
641                 b = strlen(outbuf);
642                 if (c == 1)
643                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
644                 else
645                         sprintf(&outbuf[b], "%c", strbuf[a]);
646         }
647 }
648
649
650 /*
651  * Citadelian replacement for tmpnam()
652  */
653 char *CtdlTempFileName(char *prefix1, int prefix2) {
654         static int seq = 0;
655         static char buf[SIZ];
656
657         sprintf(buf, "/tmp/Citadel-%s-%d-%04x-%04x",
658                 prefix1,
659                 prefix2,
660                 (int)getpid(),
661                 ++seq
662         );
663         
664         return(buf);
665 }
666
667
668 /*
669  * Citadelian replacement for tmpfile()
670  */
671 FILE *CtdlTempFile(void) {
672         char filename[SIZ];
673         FILE *fp;
674
675         strcpy(filename, tmpnam(NULL));
676         fp = fopen(filename, "w+b");
677         unlink(filename);
678         return(fp);
679 }