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