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