041fe027e853c0fb28d78807867f62acc5cfe43b
[citadel.git] / webcit / tools.c
1 /*
2  * $Id$
3  *
4  * Miscellaneous routines 
5  */
6
7 #include <ctype.h>
8 #include <stdlib.h>
9 #ifdef HAVE_UNISTD_H
10 #include <unistd.h>
11 #endif
12 #include <stdio.h>
13 #ifdef HAVE_FCNTL_H
14 #include <fcntl.h>
15 #endif
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <sys/socket.h>
20 #ifdef HAVE_SYS_TIME_H
21 #include <sys/time.h>
22 #endif
23 #ifdef HAVE_LIMITS_H
24 #include <limits.h>
25 #endif
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #include <netdb.h>
29 #include <string.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <pthread.h>
34 #include <signal.h>
35 #include "webcit.h"
36 #include "webserver.h"
37
38
39 typedef unsigned char byte;
40
41 #define FALSE 0
42 #define TRUE 1
43
44 static byte dtable[256];        /* base64 encode / decode table */
45
46 char *safestrncpy(char *dest, const char *src, size_t n)
47 {
48         if (dest == NULL || src == NULL) {
49                 abort();
50         }
51         strncpy(dest, src, n);
52         dest[n - 1] = 0;
53         return dest;
54 }
55
56
57
58 /*
59  * num_tokens()  -  discover number of parameters/tokens in a string
60  */
61 int num_tokens(char *source, char tok)
62 {
63         int a;
64         int count = 1;
65
66         if (source == NULL)
67                 return (0);
68         for (a = 0; a < strlen(source); ++a) {
69                 if (source[a] == tok)
70                         ++count;
71         }
72         return (count);
73 }
74
75 /*
76  * extract_token() - a string tokenizer
77  */
78 void extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
79 {
80         char *d;                /* dest */
81         const char *s;          /* source */
82         int count = 0;
83         int len = 0;
84
85         dest[0] = 0;
86
87         /* Locate desired parameter */
88         s = source;
89         while (count < parmnum) {
90                 /* End of string, bail! */
91                 if (!*s) {
92                         s = NULL;
93                         break;
94                 }
95                 if (*s == separator) {
96                         count++;
97                 }
98                 s++;
99         }
100         if (!s) return;         /* Parameter not found */
101
102         for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
103                 *d = *s;
104         }
105         *d = 0;
106 }
107
108
109
110 /*
111  * remove_token()  -  a tokenizer that kills, maims, and destroys
112  */
113 void remove_token(char *source, int parmnum, char separator)
114 {
115         int i;
116         int len;
117         int curr_parm;
118         int start, end;
119
120         len = 0;
121         curr_parm = 0;
122         start = (-1);
123         end = (-1);
124
125         if (strlen(source) == 0) {
126                 return;
127         }
128
129         for (i = 0; i < strlen(source); ++i) {
130                 if ((start < 0) && (curr_parm == parmnum)) {
131                         start = i;
132                 }
133
134                 if ((end < 0) && (curr_parm == (parmnum + 1))) {
135                         end = i;
136                 }
137
138                 if (source[i] == separator) {
139                         ++curr_parm;
140                 }
141         }
142
143         if (end < 0)
144                 end = strlen(source);
145
146         strcpy(&source[start], &source[end]);
147 }
148
149
150
151
152 /*
153  * extract_int()  -  extract an int parm w/o supplying a buffer
154  */
155 int extract_int(const char *source, int parmnum)
156 {
157         char buf[32];
158         
159         extract_token(buf, source, parmnum, '|', sizeof buf);
160         return(atoi(buf));
161 }
162
163 /*
164  * extract_long()  -  extract an long parm w/o supplying a buffer
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  * check for the presence of a character within a string (returns count)
181  */
182 int haschar(st, ch)
183 char st[];
184 char ch;
185 {
186         int a, b;
187         b = 0;
188         for (a = 0; a < strlen(st); ++a)
189                 if (st[a] == ch)
190                         ++b;
191         return (b);
192 }
193
194
195 /*
196  * Utility function to "readline" from memory
197  * (returns new pointer)
198  */
199 char *memreadline(char *start, char *buf, int maxlen)
200 {
201         char ch;
202         char *ptr;
203         int len = 0;            /* tally our own length to avoid strlen() delays */
204
205         ptr = start;
206         memset(buf, 0, maxlen);
207
208         while (1) {
209                 ch = *ptr++;
210                 if ((len < (maxlen - 1)) && (ch != 13) && (ch != 10)) {
211                         buf[strlen(buf) + 1] = 0;
212                         buf[strlen(buf)] = ch;
213                         ++len;
214                 }
215                 if ((ch == 10) || (ch == 0)) {
216                         return ptr;
217                 }
218         }
219 }
220
221
222
223 /*
224  * pattern2()  -  searches for patn within search string, returns pos
225  */
226 int pattern2(char *search, char *patn)
227 {
228         int a;
229         for (a = 0; a < strlen(search); ++a) {
230                 if (!strncasecmp(&search[a], patn, strlen(patn)))
231                         return (a);
232         }
233         return (-1);
234 }
235
236
237 /*
238  * Strip leading and trailing spaces from a string
239  */
240 void striplt(char *buf)
241 {
242         if (strlen(buf) == 0) return;
243         while ((strlen(buf) > 0) && (isspace(buf[0])))
244                 strcpy(buf, &buf[1]);
245         if (strlen(buf) == 0) return;
246         while (isspace(buf[strlen(buf) - 1]))
247                 buf[strlen(buf) - 1] = 0;
248 }
249
250
251 /*
252  * Determine whether the specified message number is contained within the
253  * specified set.
254  */
255 int is_msg_in_mset(char *mset, long msgnum) {
256         int num_sets;
257         int s;
258         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
259         long lo, hi;
260
261         /*
262          * Now set it for all specified messages.
263          */
264         num_sets = num_tokens(mset, ',');
265         for (s=0; s<num_sets; ++s) {
266                 extract_token(setstr, mset, s, ',', sizeof setstr);
267
268                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
269                 if (num_tokens(setstr, ':') >= 2) {
270                         extract_token(histr, setstr, 1, ':', sizeof histr);
271                         if (!strcmp(histr, "*")) {
272                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
273                         }
274                 } 
275                 else {
276                         strcpy(histr, lostr);
277                 }
278                 lo = atol(lostr);
279                 hi = atol(histr);
280
281                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
282         }
283
284         return(0);
285 }
286
287
288
289 /*
290  * Strip a boundarized substring out of a string (for example, remove
291  * parentheses and anything inside them).
292  *
293  * This improved version can strip out *multiple* boundarized substrings.
294  */
295 void stripout(char *str, char leftboundary, char rightboundary)
296 {
297         int a;
298         int lb = (-1);
299         int rb = (-1);
300
301         do {
302                 lb = (-1);
303                 rb = (-1);
304
305                 for (a = 0; a < strlen(str); ++a) {
306                         if (str[a] == leftboundary)
307                                 lb = a;
308                         if (str[a] == rightboundary)
309                                 rb = a;
310                 }
311
312                 if ((lb > 0) && (rb > lb)) {
313                         strcpy(&str[lb - 1], &str[rb + 1]);
314                 }
315
316         } while ((lb > 0) && (rb > lb));
317
318 }
319
320
321
322 /*
323  * Replacement for sleep() that uses select() in order to avoid SIGALRM
324  */
325 void sleeeeeeeeeep(int seconds)
326 {
327         struct timeval tv;
328
329         tv.tv_sec = seconds;
330         tv.tv_usec = 0;
331         select(0, NULL, NULL, NULL, &tv);
332 }
333
334
335
336 /*
337  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
338  * John Walker, copied over from the Citadel server.
339  */
340
341 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
342 {
343         int i, hiteof = FALSE;
344         int spos = 0;
345         int dpos = 0;
346         int thisline = 0;
347
348         /*  Fill dtable with character encodings.  */
349
350         for (i = 0; i < 26; i++) {
351                 dtable[i] = 'A' + i;
352                 dtable[26 + i] = 'a' + i;
353         }
354         for (i = 0; i < 10; i++) {
355                 dtable[52 + i] = '0' + i;
356         }
357         dtable[62] = '+';
358         dtable[63] = '/';
359
360         while (!hiteof) {
361                 byte igroup[3], ogroup[4];
362                 int c, n;
363
364                 igroup[0] = igroup[1] = igroup[2] = 0;
365                 for (n = 0; n < 3; n++) {
366                         if (spos >= sourcelen) {
367                                 hiteof = TRUE;
368                                 break;
369                         }
370                         c = source[spos++];
371                         igroup[n] = (byte) c;
372                 }
373                 if (n > 0) {
374                         ogroup[0] = dtable[igroup[0] >> 2];
375                         ogroup[1] =
376                             dtable[((igroup[0] & 3) << 4) |
377                                    (igroup[1] >> 4)];
378                         ogroup[2] =
379                             dtable[((igroup[1] & 0xF) << 2) |
380                                    (igroup[2] >> 6)];
381                         ogroup[3] = dtable[igroup[2] & 0x3F];
382
383                         /* Replace characters in output stream with "=" pad
384                            characters if fewer than three characters were
385                            read from the end of the input stream. */
386
387                         if (n < 3) {
388                                 ogroup[3] = '=';
389                                 if (n < 2) {
390                                         ogroup[2] = '=';
391                                 }
392                         }
393                         for (i = 0; i < 4; i++) {
394                                 dest[dpos++] = ogroup[i];
395                                 dest[dpos] = 0;
396                         }
397                         thisline += 4;
398                         if (thisline > 70) {
399                                 dest[dpos++] = '\r';
400                                 dest[dpos++] = '\n';
401                                 dest[dpos] = 0;
402                                 thisline = 0;
403                         }
404                 }
405         }
406         if (thisline > 70) {
407                 dest[dpos++] = '\r';
408                 dest[dpos++] = '\n';
409                 dest[dpos] = 0;
410                 thisline = 0;
411         }
412 }
413
414
415 /* 
416  * Convert base64-encoded to binary.  Returns the length of the decoded data.
417  * It will stop after reading 'length' bytes.
418  */
419 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
420 {
421         int i, c;
422         int dpos = 0;
423         int spos = 0;
424
425         for (i = 0; i < 255; i++) {
426                 dtable[i] = 0x80;
427         }
428         for (i = 'A'; i <= 'Z'; i++) {
429                 dtable[i] = 0 + (i - 'A');
430         }
431         for (i = 'a'; i <= 'z'; i++) {
432                 dtable[i] = 26 + (i - 'a');
433         }
434         for (i = '0'; i <= '9'; i++) {
435                 dtable[i] = 52 + (i - '0');
436         }
437         dtable['+'] = 62;
438         dtable['/'] = 63;
439         dtable['='] = 0;
440
441          /*CONSTANTCONDITION*/ while (TRUE) {
442                 byte a[4], b[4], o[3];
443
444                 for (i = 0; i < 4; i++) {
445                         if (spos >= length) {
446                                 return (dpos);
447                         }
448                         c = source[spos++];
449
450                         if (c == 0) {
451                                 if (i > 0) {
452                                         return (dpos);
453                                 }
454                                 return (dpos);
455                         }
456                         if (dtable[c] & 0x80) {
457                                 /* Ignoring errors: discard invalid character */
458                                 i--;
459                                 continue;
460                         }
461                         a[i] = (byte) c;
462                         b[i] = (byte) dtable[c];
463                 }
464                 o[0] = (b[0] << 2) | (b[1] >> 4);
465                 o[1] = (b[1] << 4) | (b[2] >> 2);
466                 o[2] = (b[2] << 6) | b[3];
467                 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
468                 if (i >= 1)
469                         dest[dpos++] = o[0];
470                 if (i >= 2)
471                         dest[dpos++] = o[1];
472                 if (i >= 3)
473                         dest[dpos++] = o[2];
474                 dest[dpos] = 0;
475                 if (i < 3) {
476                         return (dpos);
477                 }
478         }
479 }
480
481
482
483 /*
484  * Generate a new, globally unique UID parameter for a calendar etc. object
485  */
486 void generate_uuid(char *buf) {
487         static int seq = 0;
488
489         sprintf(buf, "%s-%lx-%x-%x",
490                 serv_info.serv_nodename,
491                 (long)time(NULL),
492                 getpid(),
493                 (seq++)
494         );
495 }
496
497
498
499 /*
500  * bmstrstr() is a variant of strstr() that uses the Boyer-Moore search
501  * algorithm, and can use any caller-supplied string compare function whose
502  * calling syntax is similar to strncmp().  For example, we can supply it
503  * with strncasecmp() to do a case-insensitive search.
504  * 
505  * Original code: copyright (c) 1997-1998 by Urs Janssen <urs@tin.org>
506  * Modifications: copyright (c) 2003 by Art Cancro <ajc@uncensored.citadel.org>
507  */
508 char *bmstrstr(char *text, char *pattern,
509         int (*cmpfunc)(const char *, const char *, size_t) )
510 {
511         register unsigned char *p, *t;
512         register int i, j, *delta;
513         register size_t p1;
514         int deltaspace[256];
515         size_t textlen;
516         size_t patlen;
517
518         if (text == NULL) return(NULL);
519         if (pattern == NULL) return(NULL);
520
521         textlen = strlen(text);
522         patlen = strlen(pattern);
523
524         /* algorithm fails if pattern is empty */
525         if ((p1 = patlen) == 0)
526                 return (text);
527
528         /* code below fails (whenever i is unsigned) if pattern too long */
529         if (p1 > textlen)
530                 return (NULL);
531
532         /* set up deltas */
533         delta = deltaspace;
534         for (i = 0; i <= 255; i++)
535                 delta[i] = p1;
536         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
537                 delta[*p++] = i;
538
539         /*
540          * From now on, we want patlen - 1.
541          * In the loop below, p points to the end of the pattern,
542          * t points to the end of the text to be tested against the
543          * pattern, and i counts the amount of text remaining, not
544          * including the part to be tested.
545          */
546         p1--;
547         p = (unsigned char *) pattern + p1;
548         t = (unsigned char *) text + p1;
549         i = textlen - patlen;
550         while (1) {
551                 if (tolower(*p) == tolower(*t)
552                    && cmpfunc((p - p1), (t - p1), p1) == 0)
553                         return ((char *) t - p1);
554                 j = delta[*t];
555                 if (i < j)
556                         break;
557                 i -= j;
558                 t += j;
559         }
560         return (NULL);
561 }
562