* Calendar objects UID now generated by generate_uuid() which creates
[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         while ((strlen(buf) > 0) && (isspace(buf[0])))
315                 strcpy(buf, &buf[1]);
316         while (isspace(buf[strlen(buf) - 1]))
317                 buf[strlen(buf) - 1] = 0;
318 }
319
320
321 /*
322  * Determine whether the specified message number is contained within the
323  * specified set.
324  */
325 int is_msg_in_mset(char *mset, long msgnum)
326 {
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, ',');
338
339                 extract_token(lostr, setstr, 0, ':');
340                 if (num_tokens(setstr, ':') >= 2) {
341                         extract_token(histr, setstr, 1, ':');
342                         if (!strcmp(histr, "*")) {
343                                 snprintf(histr, sizeof histr, "%ld",
344                                          LONG_MAX);
345                         }
346                 } else {
347                         strcpy(histr, lostr);
348                 }
349                 lo = atol(lostr);
350                 hi = atol(histr);
351
352                 if ((msgnum >= lo) && (msgnum <= hi))
353                         return (1);
354         }
355
356         return (0);
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