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