]> code.citadel.org Git - citadel.git/blob - citadel/tools.c
* sysdep.c: optimized MyContext() a bit, and inlined it. A little profiling
[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() - 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 /* remove_token() - a tokenizer that kills, maims, and destroys fast */
121 void remove_token(char *source, unsigned long parmnum, char separator)
122 {
123         char *d, *s;            /* dest, source */
124         int count = 0;
125
126         /* Find desired parameter */
127         d = source;
128         while (count < parmnum) {
129                 /* End of string, bail! */
130                 if (!*d) {
131                         d = NULL;
132                         break;
133                 }
134                 if (*d == separator) {
135                         count++;
136                 }
137                 d++;
138         }
139         if (!d) return;         /* Parameter not found */
140
141         /* Find next parameter */
142         s = d;
143         while (*s && *s != separator) {
144                 s++;
145         }
146
147         /* Hack and slash */
148         if (*s)
149                 strcpy(d, ++s);
150         else if (d == source)
151                 *d = 0;
152         else
153                 *--d = 0;
154         /*
155         while (*s) {
156                 *d++ = *s++;
157         }
158         *d = 0;
159         */
160 }
161
162
163 /*
164  * extract_int()  -  extract an int parm w/o supplying a buffer
165  */
166 int extract_int(const char *source, unsigned long parmnum)
167 {
168         char buf[SIZ];
169         
170         extract_token(buf, source, parmnum, '|');
171         return(atoi(buf));
172 }
173
174 /*
175  * extract_long()  -  extract an long parm w/o supplying a buffer
176  */
177 long extract_long(const char *source, unsigned long parmnum)
178 {
179         char buf[SIZ];
180         
181         extract_token(buf, source, parmnum, '|');
182         return(atol(buf));
183 }
184
185
186 /*
187  * extract_unsigned_long() - extract an unsigned long parm
188  */
189 unsigned long extract_unsigned_long(const char *source, unsigned long parmnum)
190 {
191         char buf[SIZ];
192
193         extract_token(buf, source, parmnum, '|');
194         return strtoul(buf, NULL, 10);
195 }
196
197
198 /*
199  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
200  * John Walker, found in full in the file "base64.c" included with this
201  * distribution.  We are moving in the direction of eventually discarding
202  * the separate executables, and using the ones in our code exclusively.
203  */
204
205 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
206 {
207     int i, hiteof = FALSE;
208     int spos = 0;
209     int dpos = 0;
210
211     /*  Fill dtable with character encodings.  */
212
213     for (i = 0; i < 26; i++) {
214         dtable[i] = 'A' + i;
215         dtable[26 + i] = 'a' + i;
216     }
217     for (i = 0; i < 10; i++) {
218         dtable[52 + i] = '0' + i;
219     }
220     dtable[62] = '+';
221     dtable[63] = '/';
222
223     while (!hiteof) {
224         byte igroup[3], ogroup[4];
225         int c, n;
226
227         igroup[0] = igroup[1] = igroup[2] = 0;
228         for (n = 0; n < 3; n++) {
229             if (spos >= sourcelen) {
230                 hiteof = TRUE;
231                 break;
232             }
233             c = source[spos++];
234             igroup[n] = (byte) c;
235         }
236         if (n > 0) {
237             ogroup[0] = dtable[igroup[0] >> 2];
238             ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
239             ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
240             ogroup[3] = dtable[igroup[2] & 0x3F];
241
242             /* Replace characters in output stream with "=" pad
243                characters if fewer than three characters were
244                read from the end of the input stream. */
245
246             if (n < 3) {
247                 ogroup[3] = '=';
248                 if (n < 2) {
249                     ogroup[2] = '=';
250                 }
251             }
252             for (i = 0; i < 4; i++) {
253                 dest[dpos++] = ogroup[i];
254                 dest[dpos] = 0;
255             }
256         }
257     }
258 }
259
260
261 /* 
262  * Convert base64-encoded to binary.  Returns the length of the decoded data.
263  * It will stop after reading 'length' bytes.
264  */
265 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
266 {
267     int i, c;
268     int dpos = 0;
269     int spos = 0;
270
271     for (i = 0; i < 255; i++) {
272         dtable[i] = 0x80;
273     }
274     for (i = 'A'; i <= 'Z'; i++) {
275         dtable[i] = 0 + (i - 'A');
276     }
277     for (i = 'a'; i <= 'z'; i++) {
278         dtable[i] = 26 + (i - 'a');
279     }
280     for (i = '0'; i <= '9'; i++) {
281         dtable[i] = 52 + (i - '0');
282     }
283     dtable['+'] = 62;
284     dtable['/'] = 63;
285     dtable['='] = 0;
286
287     /*CONSTANTCONDITION*/
288     while (TRUE) {
289         byte a[4], b[4], o[3];
290
291         for (i = 0; i < 4; i++) {
292             if (spos >= length) {
293                 return(dpos);
294             }
295             c = source[spos++];
296
297             if (c == 0) {
298                 if (i > 0) {
299                     return(dpos);
300                 }
301                 return(dpos);
302             }
303             if (dtable[c] & 0x80) {
304                 /* Ignoring errors: discard invalid character. */
305                 i--;
306                 continue;
307             }
308             a[i] = (byte) c;
309             b[i] = (byte) dtable[c];
310         }
311         o[0] = (b[0] << 2) | (b[1] >> 4);
312         o[1] = (b[1] << 4) | (b[2] >> 2);
313         o[2] = (b[2] << 6) | b[3];
314         i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
315         if (i>=1) dest[dpos++] = o[0];
316         if (i>=2) dest[dpos++] = o[1];
317         if (i>=3) dest[dpos++] = o[2];
318         dest[dpos] = 0;
319         if (i < 3) {
320             return(dpos);
321         }
322     }
323 }
324
325
326
327 /*
328  * Strip leading and trailing spaces from a string
329  */
330 void striplt(char *buf)
331 {
332         while ((strlen(buf) > 0) && (isspace(buf[0])))
333                 strcpy(buf, &buf[1]);
334         while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
335                 buf[strlen(buf) - 1] = 0;
336 }
337
338
339
340
341
342 /* 
343  * Return the number of occurances of character ch in string st
344  */ 
345 int haschar(const char *st, int ch)
346 {
347         int a, b;
348         b = 0;
349         for (a = 0; a < strlen(st); ++a)
350                 if (st[a] == ch)
351                         ++b;
352         return (b);
353 }
354
355
356
357
358 /*
359  * Compare two strings, insensitive to case, punctuation, and non-alnum chars
360  */
361 int collapsed_strcmp(char *s1, char *s2) {
362         char *c1, *c2;
363         int i, ret, pos;
364
365         c1 = malloc(strlen(s1)+1);
366         c2 = malloc(strlen(s2)+1);
367         c1[0] = 0;
368         c2[0] = 0;
369
370         pos = 0;
371         for (i=0; i<strlen(s1); ++i) {
372                 if (isalnum(s1[i])) {
373                         c1[pos] = tolower(s1[i]);
374                         c1[++pos] = 0;
375                 }
376         }
377
378         pos = 0;
379         for (i=0; i<strlen(s2); ++i) {
380                 if (isalnum(s2[i])) {
381                         c2[pos] = tolower(s2[i]);
382                         c2[++pos] = 0;
383                 }
384         }
385
386         ret = strcmp(c1, c2);
387         free(c1);
388         free(c2);
389         return(ret);
390 }
391
392
393
394 /*
395  * Format a date/time stamp for output 
396  * seconds is whether to print the seconds
397  */
398 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
399         struct tm *tm;
400         int hour;
401
402         char *ascmonths[] = {
403                 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
404                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
405         };
406
407         strcpy(buf, "");
408         tm = localtime(&thetime);
409
410         hour = tm->tm_hour;
411         if (hour == 0)  hour = 12;
412         else if (hour > 12) hour = hour - 12;
413
414         if (seconds) {
415                 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
416                         ascmonths[tm->tm_mon],
417                         tm->tm_mday,
418                         tm->tm_year + 1900,
419                         hour,
420                         tm->tm_min,
421                         tm->tm_sec,
422                         ( (tm->tm_hour >= 12) ? "pm" : "am" )
423                 );
424         } else {
425                 snprintf(buf, n, "%s %d %4d %d:%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_hour >= 12) ? "pm" : "am" )
432                 );
433         }
434 }
435
436
437
438 /*
439  * Determine whether the specified message number is contained within the
440  * specified set.
441  */
442 int is_msg_in_mset(char *mset, long msgnum) {
443         int num_sets;
444         int s;
445         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
446         long lo, hi;
447
448         /*
449          * Now set it for all specified messages.
450          */
451         num_sets = num_tokens(mset, ',');
452         for (s=0; s<num_sets; ++s) {
453                 extract_token(setstr, mset, s, ',');
454
455                 extract_token(lostr, setstr, 0, ':');
456                 if (num_tokens(setstr, ':') >= 2) {
457                         extract_token(histr, setstr, 1, ':');
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 }
521
522
523 /*
524  * Reduce a string down to a boundarized substring (for example, remove
525  * parentheses and anything outside them).
526  */
527 void stripallbut(char *str, char leftboundary, char rightboundary) {
528         int a;
529
530         for (a = 0; a < strlen(str); ++ a) {
531                 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
532         }
533
534         for (a = 0; a < strlen(str); ++ a) {
535                 if (str[a] == rightboundary) str[a] = 0;
536         }
537
538 }
539
540 char *myfgets(char *s, int size, FILE *stream) {
541         char *ret = fgets(s, size, stream);
542         char *nl;
543
544         if (ret != NULL) {
545                 nl = strchr(s, '\n');
546
547                 if (nl != NULL)
548                         *nl = 0;
549         }
550
551         return ret;
552 }
553
554 /*
555  * Escape a string for feeding out as a URL.
556  * Output buffer must be big enough to handle escape expansion!
557  */
558 void urlesc(char *outbuf, char *strbuf)
559 {
560         int a, b, c;
561         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
562
563         strcpy(outbuf, "");
564
565         for (a = 0; a < strlen(strbuf); ++a) {
566                 c = 0;
567                 for (b = 0; b < strlen(ec); ++b) {
568                         if (strbuf[a] == ec[b])
569                                 c = 1;
570                 }
571                 b = strlen(outbuf);
572                 if (c == 1)
573                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
574                 else
575                         sprintf(&outbuf[b], "%c", strbuf[a]);
576         }
577 }
578
579
580 /*
581  * Citadelian replacement for tmpnam()
582  */
583 char *CtdlTempFileName(char *prefix1, int prefix2) {
584         static int seq = 0;
585         static char buf[SIZ];
586
587         sprintf(buf, "/tmp/Citadel-%s-%d-%04x-%04x",
588                 prefix1,
589                 prefix2,
590                 (int)getpid(),
591                 ++seq
592         );
593         
594         return(buf);
595 }
596
597
598 /*
599  * Citadelian replacement for tmpfile()
600  */
601 FILE *CtdlTempFile(void) {
602         char filename[SIZ];
603         FILE *fp;
604
605         strcpy(filename, tmpnam(NULL));
606         fp = fopen(filename, "w+b");
607         unlink(filename);
608         return(fp);
609 }