* Moved to the new string tokenizer API
[citadel.git] / webcit / tools.c
1 /*
2  * $Id$
3  *
4  * Miscellaneous routines 
5  */
6
7 #include <ctype.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <fcntl.h>
12 #include <signal.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <sys/socket.h>
16 #include <sys/time.h>
17 #include <limits.h>
18 #include <netinet/in.h>
19 #include <netdb.h>
20 #include <string.h>
21 #include <pwd.h>
22 #include <errno.h>
23 #include <stdarg.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <sys/time.h>
27 #include "webcit.h"
28 #include "webserver.h"
29
30 typedef unsigned char byte;
31
32 #define FALSE 0
33 #define TRUE 1
34
35 char *ascmonths[] = {
36         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
37         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
38 };
39
40 char *ascdays[] = {
41         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
42 };
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         strcpy(dest, "");
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  * Format a date/time stamp for output 
197  */
198 void fmt_date(char *buf, time_t thetime)
199 {
200         struct tm *tm;
201         int hour;
202
203         strcpy(buf, "");
204         tm = localtime(&thetime);
205         hour = tm->tm_hour;
206         if (hour == 0)
207                 hour = 12;
208         else if (hour > 12)
209                 hour = hour - 12;
210
211         sprintf(buf, "%s %d %d %2d:%02d%s",
212                 ascmonths[tm->tm_mon],
213                 tm->tm_mday,
214                 tm->tm_year + 1900,
215                 hour, tm->tm_min, ((tm->tm_hour >= 12) ? "pm" : "am")
216             );
217 }
218
219
220
221 /*
222  * Format TIME ONLY for output 
223  */
224 void fmt_time(char *buf, time_t thetime)
225 {
226         struct tm *tm;
227         int hour;
228
229         strcpy(buf, "");
230         tm = localtime(&thetime);
231         hour = tm->tm_hour;
232         if (hour == 0)
233                 hour = 12;
234         else if (hour > 12)
235                 hour = hour - 12;
236
237         sprintf(buf, "%d:%02d%s",
238                 hour, tm->tm_min, ((tm->tm_hour > 12) ? "pm" : "am")
239             );
240 }
241
242
243
244
245 /*
246  * Format a date/time stamp to the format used in HTTP headers
247  */
248 void httpdate(char *buf, time_t thetime)
249 {
250         struct tm *tm;
251
252         strcpy(buf, "");
253         tm = localtime(&thetime);
254
255         sprintf(buf, "%s, %02d %s %4d %02d:%02d:%02d",
256                 ascdays[tm->tm_wday],
257                 tm->tm_mday,
258                 ascmonths[tm->tm_mon],
259                 tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec);
260 }
261
262
263
264
265
266 /*
267  * Utility function to "readline" from memory
268  * (returns new pointer)
269  */
270 char *memreadline(char *start, char *buf, int maxlen)
271 {
272         char ch;
273         char *ptr;
274         int len = 0;            /* tally our own length to avoid strlen() delays */
275
276         ptr = start;
277         memset(buf, 0, maxlen);
278
279         while (1) {
280                 ch = *ptr++;
281                 if ((len < (maxlen - 1)) && (ch != 13) && (ch != 10)) {
282                         buf[strlen(buf) + 1] = 0;
283                         buf[strlen(buf)] = ch;
284                         ++len;
285                 }
286                 if ((ch == 10) || (ch == 0)) {
287                         return ptr;
288                 }
289         }
290 }
291
292
293
294 /*
295  * pattern2()  -  searches for patn within search string, returns pos
296  */
297 int pattern2(char *search, char *patn)
298 {
299         int a;
300         for (a = 0; a < strlen(search); ++a) {
301                 if (!strncasecmp(&search[a], patn, strlen(patn)))
302                         return (a);
303         }
304         return (-1);
305 }
306
307
308 /*
309  * Strip leading and trailing spaces from a string
310  */
311 void striplt(char *buf)
312 {
313         if (strlen(buf) == 0) return;
314         while ((strlen(buf) > 0) && (isspace(buf[0])))
315                 strcpy(buf, &buf[1]);
316         if (strlen(buf) == 0) return;
317         while (isspace(buf[strlen(buf) - 1]))
318                 buf[strlen(buf) - 1] = 0;
319 }
320
321
322 /*
323  * Determine whether the specified message number is contained within the
324  * specified set.
325  */
326 int is_msg_in_mset(char *mset, long msgnum) {
327         int num_sets;
328         int s;
329         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
330         long lo, hi;
331
332         /*
333          * Now set it for all specified messages.
334          */
335         num_sets = num_tokens(mset, ',');
336         for (s=0; s<num_sets; ++s) {
337                 extract_token(setstr, mset, s, ',', sizeof setstr);
338
339                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
340                 if (num_tokens(setstr, ':') >= 2) {
341                         extract_token(histr, setstr, 1, ':', sizeof histr);
342                         if (!strcmp(histr, "*")) {
343                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
344                         }
345                 } 
346                 else {
347                         strcpy(histr, lostr);
348                 }
349                 lo = atol(lostr);
350                 hi = atol(histr);
351
352                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
353         }
354
355         return(0);
356 }
357
358
359
360 /*
361  * Strip a boundarized substring out of a string (for example, remove
362  * parentheses and anything inside them).
363  *
364  * This improved version can strip out *multiple* boundarized substrings.
365  */
366 void stripout(char *str, char leftboundary, char rightboundary)
367 {
368         int a;
369         int lb = (-1);
370         int rb = (-1);
371
372         do {
373                 lb = (-1);
374                 rb = (-1);
375
376                 for (a = 0; a < strlen(str); ++a) {
377                         if (str[a] == leftboundary)
378                                 lb = a;
379                         if (str[a] == rightboundary)
380                                 rb = a;
381                 }
382
383                 if ((lb > 0) && (rb > lb)) {
384                         strcpy(&str[lb - 1], &str[rb + 1]);
385                 }
386
387         } while ((lb > 0) && (rb > lb));
388
389 }
390
391
392
393 /*
394  * Replacement for sleep() that uses select() in order to avoid SIGALRM
395  */
396 void sleeeeeeeeeep(int seconds)
397 {
398         struct timeval tv;
399
400         tv.tv_sec = seconds;
401         tv.tv_usec = 0;
402         select(0, NULL, NULL, NULL, &tv);
403 }
404
405
406
407 /*
408  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
409  * John Walker, copied over from the Citadel server.
410  */
411
412 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
413 {
414         int i, hiteof = FALSE;
415         int spos = 0;
416         int dpos = 0;
417         int thisline = 0;
418
419         /*  Fill dtable with character encodings.  */
420
421         for (i = 0; i < 26; i++) {
422                 dtable[i] = 'A' + i;
423                 dtable[26 + i] = 'a' + i;
424         }
425         for (i = 0; i < 10; i++) {
426                 dtable[52 + i] = '0' + i;
427         }
428         dtable[62] = '+';
429         dtable[63] = '/';
430
431         while (!hiteof) {
432                 byte igroup[3], ogroup[4];
433                 int c, n;
434
435                 igroup[0] = igroup[1] = igroup[2] = 0;
436                 for (n = 0; n < 3; n++) {
437                         if (spos >= sourcelen) {
438                                 hiteof = TRUE;
439                                 break;
440                         }
441                         c = source[spos++];
442                         igroup[n] = (byte) c;
443                 }
444                 if (n > 0) {
445                         ogroup[0] = dtable[igroup[0] >> 2];
446                         ogroup[1] =
447                             dtable[((igroup[0] & 3) << 4) |
448                                    (igroup[1] >> 4)];
449                         ogroup[2] =
450                             dtable[((igroup[1] & 0xF) << 2) |
451                                    (igroup[2] >> 6)];
452                         ogroup[3] = dtable[igroup[2] & 0x3F];
453
454                         /* Replace characters in output stream with "=" pad
455                            characters if fewer than three characters were
456                            read from the end of the input stream. */
457
458                         if (n < 3) {
459                                 ogroup[3] = '=';
460                                 if (n < 2) {
461                                         ogroup[2] = '=';
462                                 }
463                         }
464                         for (i = 0; i < 4; i++) {
465                                 dest[dpos++] = ogroup[i];
466                                 dest[dpos] = 0;
467                         }
468                         thisline += 4;
469                         if (thisline > 70) {
470                                 dest[dpos++] = '\r';
471                                 dest[dpos++] = '\n';
472                                 dest[dpos] = 0;
473                                 thisline = 0;
474                         }
475                 }
476         }
477         if (thisline > 70) {
478                 dest[dpos++] = '\r';
479                 dest[dpos++] = '\n';
480                 dest[dpos] = 0;
481                 thisline = 0;
482         }
483 }
484
485
486 /* 
487  * Convert base64-encoded to binary.  Returns the length of the decoded data.
488  * It will stop after reading 'length' bytes.
489  */
490 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
491 {
492         int i, c;
493         int dpos = 0;
494         int spos = 0;
495
496         for (i = 0; i < 255; i++) {
497                 dtable[i] = 0x80;
498         }
499         for (i = 'A'; i <= 'Z'; i++) {
500                 dtable[i] = 0 + (i - 'A');
501         }
502         for (i = 'a'; i <= 'z'; i++) {
503                 dtable[i] = 26 + (i - 'a');
504         }
505         for (i = '0'; i <= '9'; i++) {
506                 dtable[i] = 52 + (i - '0');
507         }
508         dtable['+'] = 62;
509         dtable['/'] = 63;
510         dtable['='] = 0;
511
512          /*CONSTANTCONDITION*/ while (TRUE) {
513                 byte a[4], b[4], o[3];
514
515                 for (i = 0; i < 4; i++) {
516                         if (spos >= length) {
517                                 return (dpos);
518                         }
519                         c = source[spos++];
520
521                         if (c == 0) {
522                                 if (i > 0) {
523                                         return (dpos);
524                                 }
525                                 return (dpos);
526                         }
527                         if (dtable[c] & 0x80) {
528                                 /* Ignoring errors: discard invalid character. */
529                                 i--;
530                                 continue;
531                         }
532                         a[i] = (byte) c;
533                         b[i] = (byte) dtable[c];
534                 }
535                 o[0] = (b[0] << 2) | (b[1] >> 4);
536                 o[1] = (b[1] << 4) | (b[2] >> 2);
537                 o[2] = (b[2] << 6) | b[3];
538                 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
539                 if (i >= 1)
540                         dest[dpos++] = o[0];
541                 if (i >= 2)
542                         dest[dpos++] = o[1];
543                 if (i >= 3)
544                         dest[dpos++] = o[2];
545                 dest[dpos] = 0;
546                 if (i < 3) {
547                         return (dpos);
548                 }
549         }
550 }
551
552
553 /*
554  * Generate a new, globally unique UID parameter for a calendar etc. object
555  */
556 void generate_uuid(char *buf) {
557         static int seq = 0;
558
559         sprintf(buf, "{%08x-%04x-%04x-%04x-%012x}",
560                 (int)time(NULL),
561                 (seq++),
562                 getpid(),
563                 rand(),
564                 rand()
565         );
566 }
567