83c4d45e0499c7961cbfadf7f419b2a274c8211c
[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 smarter string tokenizer
77  */
78 void extract_token(char *dest, char *source, int parmnum, char separator)
79 {
80         int i;
81         int len;
82         int curr_parm;
83
84         strcpy(dest, "");
85         len = 0;
86         curr_parm = 0;
87
88         if (strlen(source) == 0) {
89                 return;
90         }
91
92         for (i = 0; i < strlen(source); ++i) {
93                 if (source[i] == separator) {
94                         ++curr_parm;
95                 } else if (curr_parm == parmnum) {
96                         dest[len + 1] = 0;
97                         dest[len++] = source[i];
98                 }
99         }
100 }
101
102
103
104 /*
105  * remove_token()  -  a tokenizer that kills, maims, and destroys
106  */
107 void remove_token(char *source, int parmnum, char separator)
108 {
109         int i;
110         int len;
111         int curr_parm;
112         int start, end;
113
114         len = 0;
115         curr_parm = 0;
116         start = (-1);
117         end = (-1);
118
119         if (strlen(source) == 0) {
120                 return;
121         }
122
123         for (i = 0; i < strlen(source); ++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         strcpy(&source[start], &source[end]);
141 }
142
143
144
145
146 /*
147  * extract_int()  -  extract an int parm w/o supplying a buffer
148  */
149 int extract_int(char *source, int parmnum)
150 {
151         char buf[SIZ];
152
153         extract_token(buf, source, parmnum, '|');
154         return (atoi(buf));
155 }
156
157 /*
158  * extract_long()  -  extract an long parm w/o supplying a buffer
159  */
160 long extract_long(char *source, long int parmnum)
161 {
162         char buf[SIZ];
163
164         extract_token(buf, source, parmnum, '|');
165         return (atol(buf));
166 }
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182 /*
183  * check for the presence of a character within a string (returns count)
184  */
185 int haschar(st, ch)
186 char st[];
187 char ch;
188 {
189         int a, b;
190         b = 0;
191         for (a = 0; a < strlen(st); ++a)
192                 if (st[a] == ch)
193                         ++b;
194         return (b);
195 }
196
197
198 /*
199  * Format a date/time stamp for output 
200  */
201 void fmt_date(char *buf, time_t thetime)
202 {
203         struct tm *tm;
204         int hour;
205
206         strcpy(buf, "");
207         tm = localtime(&thetime);
208         hour = tm->tm_hour;
209         if (hour == 0)
210                 hour = 12;
211         else if (hour > 12)
212                 hour = hour - 12;
213
214         sprintf(buf, "%s %d %d %2d:%02d%s",
215                 ascmonths[tm->tm_mon],
216                 tm->tm_mday,
217                 tm->tm_year + 1900,
218                 hour, tm->tm_min, ((tm->tm_hour >= 12) ? "pm" : "am")
219             );
220 }
221
222
223
224 /*
225  * Format TIME ONLY for output 
226  */
227 void fmt_time(char *buf, time_t thetime)
228 {
229         struct tm *tm;
230         int hour;
231
232         strcpy(buf, "");
233         tm = localtime(&thetime);
234         hour = tm->tm_hour;
235         if (hour == 0)
236                 hour = 12;
237         else if (hour > 12)
238                 hour = hour - 12;
239
240         sprintf(buf, "%d:%02d%s",
241                 hour, tm->tm_min, ((tm->tm_hour > 12) ? "pm" : "am")
242             );
243 }
244
245
246
247
248 /*
249  * Format a date/time stamp to the format used in HTTP headers
250  */
251 void httpdate(char *buf, time_t thetime)
252 {
253         struct tm *tm;
254
255         strcpy(buf, "");
256         tm = localtime(&thetime);
257
258         sprintf(buf, "%s, %02d %s %4d %02d:%02d:%02d",
259                 ascdays[tm->tm_wday],
260                 tm->tm_mday,
261                 ascmonths[tm->tm_mon],
262                 tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec);
263 }
264
265
266
267
268
269 /*
270  * Utility function to "readline" from memory
271  * (returns new pointer)
272  */
273 char *memreadline(char *start, char *buf, int maxlen)
274 {
275         char ch;
276         char *ptr;
277         int len = 0;            /* tally our own length to avoid strlen() delays */
278
279         ptr = start;
280         memset(buf, 0, maxlen);
281
282         while (1) {
283                 ch = *ptr++;
284                 if ((len < (maxlen - 1)) && (ch != 13) && (ch != 10)) {
285                         buf[strlen(buf) + 1] = 0;
286                         buf[strlen(buf)] = ch;
287                         ++len;
288                 }
289                 if ((ch == 10) || (ch == 0)) {
290                         return ptr;
291                 }
292         }
293 }
294
295
296
297 /*
298  * pattern2()  -  searches for patn within search string, returns pos
299  */
300 int pattern2(char *search, char *patn)
301 {
302         int a;
303         for (a = 0; a < strlen(search); ++a) {
304                 if (!strncasecmp(&search[a], patn, strlen(patn)))
305                         return (a);
306         }
307         return (-1);
308 }
309
310
311 /*
312  * Strip leading and trailing spaces from a string
313  */
314 void striplt(char *buf)
315 {
316         if (strlen(buf) == 0) return;
317         while ((strlen(buf) > 0) && (isspace(buf[0])))
318                 strcpy(buf, &buf[1]);
319         if (strlen(buf) == 0) return;
320         while (isspace(buf[strlen(buf) - 1]))
321                 buf[strlen(buf) - 1] = 0;
322 }
323
324
325 /*
326  * Determine whether the specified message number is contained within the
327  * specified set.
328  */
329 int is_msg_in_mset(char *mset, long msgnum)
330 {
331         int num_sets;
332         int s;
333         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
334         long lo, hi;
335
336         /*
337          * Now set it for all specified messages.
338          */
339         num_sets = num_tokens(mset, ',');
340         for (s = 0; s < num_sets; ++s) {
341                 extract_token(setstr, mset, s, ',');
342
343                 extract_token(lostr, setstr, 0, ':');
344                 if (num_tokens(setstr, ':') >= 2) {
345                         extract_token(histr, setstr, 1, ':');
346                         if (!strcmp(histr, "*")) {
347                                 snprintf(histr, sizeof histr, "%ld",
348                                          LONG_MAX);
349                         }
350                 } else {
351                         strcpy(histr, lostr);
352                 }
353                 lo = atol(lostr);
354                 hi = atol(histr);
355
356                 if ((msgnum >= lo) && (msgnum <= hi))
357                         return (1);
358         }
359
360         return (0);
361 }
362
363
364 /*
365  * Strip a boundarized substring out of a string (for example, remove
366  * parentheses and anything inside them).
367  *
368  * This improved version can strip out *multiple* boundarized substrings.
369  */
370 void stripout(char *str, char leftboundary, char rightboundary)
371 {
372         int a;
373         int lb = (-1);
374         int rb = (-1);
375
376         do {
377                 lb = (-1);
378                 rb = (-1);
379
380                 for (a = 0; a < strlen(str); ++a) {
381                         if (str[a] == leftboundary)
382                                 lb = a;
383                         if (str[a] == rightboundary)
384                                 rb = a;
385                 }
386
387                 if ((lb > 0) && (rb > lb)) {
388                         strcpy(&str[lb - 1], &str[rb + 1]);
389                 }
390
391         } while ((lb > 0) && (rb > lb));
392
393 }
394
395
396
397 /*
398  * Replacement for sleep() that uses select() in order to avoid SIGALRM
399  */
400 void sleeeeeeeeeep(int seconds)
401 {
402         struct timeval tv;
403
404         tv.tv_sec = seconds;
405         tv.tv_usec = 0;
406         select(0, NULL, NULL, NULL, &tv);
407 }
408
409
410
411 /*
412  * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
413  * John Walker, copied over from the Citadel server.
414  */
415
416 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
417 {
418         int i, hiteof = FALSE;
419         int spos = 0;
420         int dpos = 0;
421         int thisline = 0;
422
423         /*  Fill dtable with character encodings.  */
424
425         for (i = 0; i < 26; i++) {
426                 dtable[i] = 'A' + i;
427                 dtable[26 + i] = 'a' + i;
428         }
429         for (i = 0; i < 10; i++) {
430                 dtable[52 + i] = '0' + i;
431         }
432         dtable[62] = '+';
433         dtable[63] = '/';
434
435         while (!hiteof) {
436                 byte igroup[3], ogroup[4];
437                 int c, n;
438
439                 igroup[0] = igroup[1] = igroup[2] = 0;
440                 for (n = 0; n < 3; n++) {
441                         if (spos >= sourcelen) {
442                                 hiteof = TRUE;
443                                 break;
444                         }
445                         c = source[spos++];
446                         igroup[n] = (byte) c;
447                 }
448                 if (n > 0) {
449                         ogroup[0] = dtable[igroup[0] >> 2];
450                         ogroup[1] =
451                             dtable[((igroup[0] & 3) << 4) |
452                                    (igroup[1] >> 4)];
453                         ogroup[2] =
454                             dtable[((igroup[1] & 0xF) << 2) |
455                                    (igroup[2] >> 6)];
456                         ogroup[3] = dtable[igroup[2] & 0x3F];
457
458                         /* Replace characters in output stream with "=" pad
459                            characters if fewer than three characters were
460                            read from the end of the input stream. */
461
462                         if (n < 3) {
463                                 ogroup[3] = '=';
464                                 if (n < 2) {
465                                         ogroup[2] = '=';
466                                 }
467                         }
468                         for (i = 0; i < 4; i++) {
469                                 dest[dpos++] = ogroup[i];
470                                 dest[dpos] = 0;
471                         }
472                         thisline += 4;
473                         if (thisline > 70) {
474                                 dest[dpos++] = '\r';
475                                 dest[dpos++] = '\n';
476                                 dest[dpos] = 0;
477                                 thisline = 0;
478                         }
479                 }
480         }
481         if (thisline > 70) {
482                 dest[dpos++] = '\r';
483                 dest[dpos++] = '\n';
484                 dest[dpos] = 0;
485                 thisline = 0;
486         }
487 }
488
489
490 /* 
491  * Convert base64-encoded to binary.  Returns the length of the decoded data.
492  * It will stop after reading 'length' bytes.
493  */
494 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
495 {
496         int i, c;
497         int dpos = 0;
498         int spos = 0;
499
500         for (i = 0; i < 255; i++) {
501                 dtable[i] = 0x80;
502         }
503         for (i = 'A'; i <= 'Z'; i++) {
504                 dtable[i] = 0 + (i - 'A');
505         }
506         for (i = 'a'; i <= 'z'; i++) {
507                 dtable[i] = 26 + (i - 'a');
508         }
509         for (i = '0'; i <= '9'; i++) {
510                 dtable[i] = 52 + (i - '0');
511         }
512         dtable['+'] = 62;
513         dtable['/'] = 63;
514         dtable['='] = 0;
515
516          /*CONSTANTCONDITION*/ while (TRUE) {
517                 byte a[4], b[4], o[3];
518
519                 for (i = 0; i < 4; i++) {
520                         if (spos >= length) {
521                                 return (dpos);
522                         }
523                         c = source[spos++];
524
525                         if (c == 0) {
526                                 if (i > 0) {
527                                         return (dpos);
528                                 }
529                                 return (dpos);
530                         }
531                         if (dtable[c] & 0x80) {
532                                 /* Ignoring errors: discard invalid character. */
533                                 i--;
534                                 continue;
535                         }
536                         a[i] = (byte) c;
537                         b[i] = (byte) dtable[c];
538                 }
539                 o[0] = (b[0] << 2) | (b[1] >> 4);
540                 o[1] = (b[1] << 4) | (b[2] >> 2);
541                 o[2] = (b[2] << 6) | b[3];
542                 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
543                 if (i >= 1)
544                         dest[dpos++] = o[0];
545                 if (i >= 2)
546                         dest[dpos++] = o[1];
547                 if (i >= 3)
548                         dest[dpos++] = o[2];
549                 dest[dpos] = 0;
550                 if (i < 3) {
551                         return (dpos);
552                 }
553         }
554 }
555
556
557 /*
558  * Generate a new, globally unique UID parameter for a calendar etc. object
559  */
560 void generate_uuid(char *buf) {
561         static int seq = 0;
562
563         sprintf(buf, "{%08x-%04x-%04x-%04x-%012x}",
564                 (int)time(NULL),
565                 (seq++),
566                 getpid(),
567                 rand(),
568                 rand()
569         );
570 }
571