]> code.citadel.org Git - citadel.git/blob - webcit/tools.c
7964064f4a8c495e54152db9afc5344aa3bbc81e
[citadel.git] / webcit / tools.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup MiscRout Miscellaneous routines 
6  * \ingroup tools
7  */
8
9 /*@{*/
10 #include "webcit.h"
11 #include "webserver.h"
12
13
14 typedef unsigned char byte; /**< byte data type */
15
16 #define FALSE 0 /**< no. */
17 #define TRUE 1  /**< yes. */
18
19 static byte dtable[256];        /**< base64 encode / decode table */
20
21 /**
22  * \brief sanitize strncopy.
23  * \param dest destination string
24  * \param src source string
25  * \param n length of source to copy 
26  * \return result string
27  */
28 char *safestrncpy(char *dest, const char *src, size_t n)
29 {
30         if (dest == NULL || src == NULL) {
31                 abort();
32         }
33         strncpy(dest, src, n);
34         dest[n - 1] = 0;
35         return dest;
36 }
37
38
39
40 /**
41  * \brief discover number of parameters/tokens in a string
42  * \param source string to inspect
43  * \param tok seperation token
44  * \return number of tokenized parts found
45  */
46 int num_tokens(char *source, char tok)
47 {
48         int a = 0;
49         int count = 1;
50
51         if (source == NULL)
52                 return (0);
53         for (a = 0; a < strlen(source); ++a) {
54                 if (source[a] == tok)
55                         ++count;
56         }
57         return (count);
58 }
59
60 /**
61  * brief a string tokenizer
62  * \param dest destination string 
63  * \param source the string to grab tokens from
64  * \param parmnum the n'th token to grab
65  * \param separator the tokenizer string
66  * \param maxlen the length of dest
67  */
68 void extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
69 {
70         char *d;                /* dest */
71         const char *s;          /* source */
72         int count = 0;
73         int len = 0;
74
75         dest[0] = 0;
76
77         /* Locate desired parameter */
78         s = source;
79         while (count < parmnum) {
80                 /* End of string, bail! */
81                 if (!*s) {
82                         s = NULL;
83                         break;
84                 }
85                 if (*s == separator) {
86                         count++;
87                 }
88                 s++;
89         }
90         if (!s) return;         /* Parameter not found */
91
92         for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
93                 *d = *s;
94         }
95         *d = 0;
96 }
97
98
99
100 /**
101  * \brief a tokenizer that kills, maims, and destroys
102  * \param source the string to process
103  * \param parmnum which token to kill
104  * \param separator the tokenizer string
105  */
106 void remove_token(char *source, int parmnum, char separator)
107 {
108         int i;
109         int len, slen;
110         int curr_parm;
111         int start, end;
112
113         len = 0;
114         curr_parm = 0;
115         start = (-1);
116         end = (-1);
117
118         slen = strlen(source);
119         if (slen == 0) {
120                 return;
121         }
122
123         for (i = 0; i < slen; ++i) {
124                 if ((start < 0) && (curr_parm == parmnum)) {
125                         start = i;
126                 }
127
128                 if ((end < 0) && (curr_parm == (parmnum + 1))) {
129                         end = i;
130                 }
131
132                 if (source[i] == separator) {
133                         ++curr_parm;
134                 }
135         }
136
137         if (end < 0)
138                 end = strlen(source);
139
140         memmove(&source[start], &source[end], slen - end);
141 }
142
143
144
145
146 /**
147  * \brief extract an int parm w/o supplying a buffer
148  * \param source the string to locate the int in
149  * \param parmnum the n'th token to grab the int from
150  * \return the integer
151  */
152 int extract_int(const char *source, int parmnum)
153 {
154         char buf[32];
155         
156         extract_token(buf, source, parmnum, '|', sizeof buf);
157         return(atoi(buf));
158 }
159
160 /**
161  * \brief extract an long parm w/o supplying a buffer
162  * \param source string to examine
163  * \param parmnum n'th token to search long in
164  * \return the found long value
165  */
166 long extract_long(const char *source, int parmnum)
167 {
168         char buf[32];
169         
170         extract_token(buf, source, parmnum, '|', sizeof buf);
171         return(atol(buf));
172 }
173
174
175
176
177
178
179 /**
180  * \brief check for the presence of a character within a string (returns count)
181  * \param st the string to examine
182  * \param ch the char to search
183  * \return the position inside of st
184  */
185 int haschar(char *st,char ch)
186 {
187         int a, b;
188         b = 0;
189         for (a = 0; a < strlen(st); ++a)
190                 if (st[a] == ch)
191                         ++b;
192         return (b);
193 }
194
195
196 /** 
197  * \brief Utility function to "readline" from memory
198  * \param start Location in memory from which we are reading.
199  * \param buf the buffer to place the string in.
200  * \param maxlen Size of string buffer
201  * \return Pointer to the source memory right after we stopped reading.
202  */
203 char *memreadline(char *start, char *buf, int maxlen)
204 {
205         char ch;
206         char *ptr;
207         int len = 0;            /**< tally our own length to avoid strlen() delays */
208
209         ptr = start;
210         memset(buf, 0, maxlen);
211
212         while (1) {
213                 ch = *ptr++;
214                 if ((len < (maxlen - 1)) && (ch != 13) && (ch != 10)) {
215                         buf[strlen(buf) + 1] = 0;
216                         buf[strlen(buf)] = ch;
217                         ++len;
218                 }
219                 if ((ch == 10) || (ch == 0)) {
220                         return ptr;
221                 }
222         }
223 }
224
225
226
227 /**
228  * \brief searches for a  paternn within asearch string
229  * \param search the string to search 
230  * \param patn the pattern to find in string
231  * \returns position in string
232  */
233 int pattern2(char *search, char *patn)
234 {
235         int a;
236         for (a = 0; a < strlen(search); ++a) {
237                 if (!strncasecmp(&search[a], patn, strlen(patn)))
238                         return (a);
239         }
240         return (-1);
241 }
242
243
244 /**
245  * \brief Strip leading and trailing spaces from a string
246  * \param buf the string to modify
247  */
248 void striplt(char *buf)
249 {
250         if (strlen(buf) == 0) return;
251         while ((strlen(buf) > 0) && (isspace(buf[0])))
252                 strcpy(buf, &buf[1]);
253         if (strlen(buf) == 0) return;
254         while (isspace(buf[strlen(buf) - 1]))
255                 buf[strlen(buf) - 1] = 0;
256 }
257
258
259 /**
260  * \brief Determine whether the specified message number is contained within the
261  * specified set.
262  *
263  * \param mset Message set string
264  * \param msgnum Message number we are looking for
265  *
266  * \return Nonzero if the specified message number is in the specified message set string.
267  */
268 int is_msg_in_mset(char *mset, long msgnum) {
269         int num_sets;
270         int s;
271         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
272         long lo, hi;
273
274         /*
275          * Now set it for all specified messages.
276          */
277         num_sets = num_tokens(mset, ',');
278         for (s=0; s<num_sets; ++s) {
279                 extract_token(setstr, mset, s, ',', sizeof setstr);
280
281                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
282                 if (num_tokens(setstr, ':') >= 2) {
283                         extract_token(histr, setstr, 1, ':', sizeof histr);
284                         if (!strcmp(histr, "*")) {
285                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
286                         }
287                 } 
288                 else {
289                         strcpy(histr, lostr);
290                 }
291                 lo = atol(lostr);
292                 hi = atol(histr);
293
294                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
295         }
296
297         return(0);
298 }
299
300
301
302 /**
303  * \brief Strip a boundarized substring out of a string
304  * (for example, remove
305  * parentheses and anything inside them).
306  *
307  * This improved version can strip out *multiple* boundarized substrings.
308  * \param str the string to process
309  * \param leftboundary the boundary character on the left side of the target string 
310  * \param rightboundary the boundary character on the right side of the target string
311  */
312 void stripout(char *str, char leftboundary, char rightboundary)
313 {
314         int a;
315         int lb = (-1);
316         int rb = (-1);
317
318         do {
319                 lb = (-1);
320                 rb = (-1);
321
322                 for (a = 0; a < strlen(str); ++a) {
323                         if (str[a] == leftboundary)
324                                 lb = a;
325                         if (str[a] == rightboundary)
326                                 rb = a;
327                 }
328
329                 if ((lb > 0) && (rb > lb)) {
330                         strcpy(&str[lb - 1], &str[rb + 1]);
331                 }
332
333         } while ((lb > 0) && (rb > lb));
334
335 }
336
337
338
339 /**
340  * \brief Replacement for sleep() that uses select() in order to avoid SIGALRM
341  * \param seconds how many seconds should we sleep?
342  */
343 void sleeeeeeeeeep(int seconds)
344 {
345         struct timeval tv;
346
347         tv.tv_sec = seconds;
348         tv.tv_usec = 0;
349         select(0, NULL, NULL, NULL, &tv);
350 }
351
352
353
354 /**
355  * \brief encode a string into base64 to for example tunnel it through mail transport
356  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
357  * John Walker, copied over from the Citadel server.
358  * \param dest encrypted string
359  * \param source the string to encrypt
360  * \param sourcelen the length of the source data (may contain string terminators)
361  */
362
363 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
364 {
365         int i, hiteof = FALSE;
366         int spos = 0;
367         int dpos = 0;
368         int thisline = 0;
369
370         /**  Fill dtable with character encodings.  */
371
372         for (i = 0; i < 26; i++) {
373                 dtable[i] = 'A' + i;
374                 dtable[26 + i] = 'a' + i;
375         }
376         for (i = 0; i < 10; i++) {
377                 dtable[52 + i] = '0' + i;
378         }
379         dtable[62] = '+';
380         dtable[63] = '/';
381
382         while (!hiteof) {
383                 byte igroup[3], ogroup[4];
384                 int c, n;
385
386                 igroup[0] = igroup[1] = igroup[2] = 0;
387                 for (n = 0; n < 3; n++) {
388                         if (spos >= sourcelen) {
389                                 hiteof = TRUE;
390                                 break;
391                         }
392                         c = source[spos++];
393                         igroup[n] = (byte) c;
394                 }
395                 if (n > 0) {
396                         ogroup[0] = dtable[igroup[0] >> 2];
397                         ogroup[1] =
398                             dtable[((igroup[0] & 3) << 4) |
399                                    (igroup[1] >> 4)];
400                         ogroup[2] =
401                             dtable[((igroup[1] & 0xF) << 2) |
402                                    (igroup[2] >> 6)];
403                         ogroup[3] = dtable[igroup[2] & 0x3F];
404
405                         /**
406                          * Replace characters in output stream with "=" pad
407                          * characters if fewer than three characters were
408                          * read from the end of the input stream. 
409                          */
410
411                         if (n < 3) {
412                                 ogroup[3] = '=';
413                                 if (n < 2) {
414                                         ogroup[2] = '=';
415                                 }
416                         }
417                         for (i = 0; i < 4; i++) {
418                                 dest[dpos++] = ogroup[i];
419                                 dest[dpos] = 0;
420                         }
421                         thisline += 4;
422                         if ( (linebreaks) && (thisline > 70) ) {
423                                 dest[dpos++] = '\r';
424                                 dest[dpos++] = '\n';
425                                 dest[dpos] = 0;
426                                 thisline = 0;
427                         }
428                 }
429         }
430         if ( (linebreaks) && (thisline > 70) ) {
431                 dest[dpos++] = '\r';
432                 dest[dpos++] = '\n';
433                 dest[dpos] = 0;
434                 thisline = 0;
435         }
436 }
437
438
439 /**
440  * \brief Convert base64-encoded to binary.  
441  * It will stop after reading 'length' bytes.
442  *
443  * \param dest The destination buffer 
444  * \param source The base64 data to be decoded.
445  * \param length The number of bytes to decode.
446  * \return The actual length of the decoded data.
447  */
448 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
449 {
450         int i, c;
451         int dpos = 0;
452         int spos = 0;
453
454         for (i = 0; i < 255; i++) {
455                 dtable[i] = 0x80;
456         }
457         for (i = 'A'; i <= 'Z'; i++) {
458                 dtable[i] = 0 + (i - 'A');
459         }
460         for (i = 'a'; i <= 'z'; i++) {
461                 dtable[i] = 26 + (i - 'a');
462         }
463         for (i = '0'; i <= '9'; i++) {
464                 dtable[i] = 52 + (i - '0');
465         }
466         dtable['+'] = 62;
467         dtable['/'] = 63;
468         dtable['='] = 0;
469
470         /**CONSTANTCONDITION*/ while (TRUE) {
471                 byte a[4], b[4], o[3];
472
473                 for (i = 0; i < 4; i++) {
474                         if (spos >= length) {
475                                 return (dpos);
476                         }
477                         c = source[spos++];
478
479                         if (c == 0) {
480                                 if (i > 0) {
481                                         return (dpos);
482                                 }
483                                 return (dpos);
484                         }
485                         if (dtable[c] & 0x80) {
486                                 /** Ignoring errors: discard invalid character */
487                                 i--;
488                                 continue;
489                         }
490                         a[i] = (byte) c;
491                         b[i] = (byte) dtable[c];
492                 }
493                 o[0] = (b[0] << 2) | (b[1] >> 4);
494                 o[1] = (b[1] << 4) | (b[2] >> 2);
495                 o[2] = (b[2] << 6) | b[3];
496                 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
497                 if (i >= 1)
498                         dest[dpos++] = o[0];
499                 if (i >= 2)
500                         dest[dpos++] = o[1];
501                 if (i >= 3)
502                         dest[dpos++] = o[2];
503                 dest[dpos] = 0;
504                 if (i < 3) {
505                         return (dpos);
506                 }
507         }
508 }
509
510
511
512 /**
513  * \brief Generate a new, globally unique UID parameter for a calendar etc. object
514  *
515  * \param buf String buffer into which our newly created UUID should be placed
516  */
517 void generate_uuid(char *buf) {
518         static int seq = 0;
519
520         sprintf(buf, "%s-%lx-%lx-%x",
521                 serv_info.serv_nodename,
522                 (long)time(NULL),
523                 (long)getpid(),
524                 (seq++)
525         );
526 }
527
528
529 /**
530  * \brief Local replacement for controversial C library function that generates
531  * names for temporary files.  Included to shut up compiler warnings.
532  * \todo return a fd to the file instead of the name for security reasons
533  * \param name the created filename
534  * \param len the length of the filename
535  */
536 void CtdlMakeTempFileName(char *name, int len) {
537         int i = 0;
538
539         while (i++, i < 100) {
540                 snprintf(name, len, "/tmp/ctdl.%04x.%04x",
541                         getpid(),
542                         rand()
543                 );
544                 if (!access(name, F_OK)) {
545                         return;
546                 }
547         }
548 }
549
550
551
552 /*
553  * \brief       case-insensitive substring search
554  *
555  *              This uses the Boyer-Moore search algorithm and is therefore quite fast.
556  *              The code is roughly based on the strstr() replacement from 'tin' written
557  *              by Urs Jannsen.
558  *
559  * \param       text    String to be searched
560  * \param       pattern String to search for
561  */
562 char *bmstrcasestr(char *text, char *pattern) {
563
564         register unsigned char *p, *t;
565         register int i, j, *delta;
566         register size_t p1;
567         int deltaspace[256];
568         size_t textlen;
569         size_t patlen;
570
571         textlen = strlen (text);
572         patlen = strlen (pattern);
573
574         /* algorithm fails if pattern is empty */
575         if ((p1 = patlen) == 0)
576                 return (text);
577
578         /* code below fails (whenever i is unsigned) if pattern too long */
579         if (p1 > textlen)
580                 return (NULL);
581
582         /* set up deltas */
583         delta = deltaspace;
584         for (i = 0; i <= 255; i++)
585                 delta[i] = p1;
586         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
587                 delta[tolower(*p++)] = i;
588
589         /*
590          * From now on, we want patlen - 1.
591          * In the loop below, p points to the end of the pattern,
592          * t points to the end of the text to be tested against the
593          * pattern, and i counts the amount of text remaining, not
594          * including the part to be tested.
595          */
596         p1--;
597         p = (unsigned char *) pattern + p1;
598         t = (unsigned char *) text + p1;
599         i = textlen - patlen;
600         while(1) {
601                 if (tolower(p[0]) == tolower(t[0])) {
602                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
603                                 return ((char *)t - p1);
604                         }
605                 }
606                 j = delta[tolower(t[0])];
607                 if (i < j)
608                         break;
609                 i -= j;
610                 t += j;
611         }
612         return (NULL);
613 }
614
615
616
617
618
619 /*@}*/