4 * Utility functions that are used by both the client and server.
17 #if TIME_WITH_SYS_TIME
18 # include <sys/time.h>
22 # include <sys/time.h>
34 typedef unsigned char byte; /* Byte type */
35 static byte dtable[256]; /* base64 encode / decode table */
37 /* Month strings for date conversions */
38 char *ascmonths[12] = {
39 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
40 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
43 char *safestrncpy(char *dest, const char *src, size_t n)
47 if (dest == NULL || src == NULL) {
48 fprintf(stderr, "safestrncpy: NULL argument\n");
54 if (dest[i] == 0) return(dest);
63 #ifndef HAVE_STRNCASECMP
64 int strncasecmp(char *lstr, char *rstr, int len)
69 lc=tolower(lstr[pos]);
70 rc=tolower(rstr[pos]);
71 if ((lc==0)&&(rc==0)) return(0);
72 if (lc<rc) return(-1);
83 * num_tokens() - discover number of parameters/tokens in a string
85 int num_tokens(const char *source, char tok) {
89 if (source == NULL) return(0);
90 for (a=0; a<strlen(source); ++a) {
91 if (source[a]==tok) ++count;
98 * extract_token() - a string tokenizer
100 void extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
103 const char *s; /* source */
109 /* Locate desired parameter */
111 while (count < parmnum) {
112 /* End of string, bail! */
117 if (*s == separator) {
122 if (!s) return; /* Parameter not found */
124 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
132 * remove_token() - a tokenizer that kills, maims, and destroys
134 void remove_token(char *source, int parmnum, char separator)
136 char *d, *s; /* dest, source */
139 /* Find desired parameter */
141 while (count < parmnum) {
142 /* End of string, bail! */
147 if (*d == separator) {
152 if (!d) return; /* Parameter not found */
154 /* Find next parameter */
156 while (*s && *s != separator) {
163 else if (d == source)
177 * extract_int() - extract an int parm w/o supplying a buffer
179 int extract_int(const char *source, int parmnum)
183 extract_token(buf, source, parmnum, '|', sizeof buf);
188 * extract_long() - extract an long parm w/o supplying a buffer
190 long extract_long(const char *source, int parmnum)
194 extract_token(buf, source, parmnum, '|', sizeof buf);
200 * extract_unsigned_long() - extract an unsigned long parm
202 unsigned long extract_unsigned_long(const char *source, int parmnum)
206 extract_token(buf, source, parmnum, '|', sizeof buf);
207 return strtoul(buf, NULL, 10);
212 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
213 * John Walker, found in full in the file "base64.c" included with this
214 * distribution. We are moving in the direction of eventually discarding
215 * the separate executables, and using the ones in our code exclusively.
218 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
220 int i, hiteof = FALSE;
224 /* Fill dtable with character encodings. */
226 for (i = 0; i < 26; i++) {
228 dtable[26 + i] = 'a' + i;
230 for (i = 0; i < 10; i++) {
231 dtable[52 + i] = '0' + i;
237 byte igroup[3], ogroup[4];
240 igroup[0] = igroup[1] = igroup[2] = 0;
241 for (n = 0; n < 3; n++) {
242 if (spos >= sourcelen) {
247 igroup[n] = (byte) c;
250 ogroup[0] = dtable[igroup[0] >> 2];
251 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
252 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
253 ogroup[3] = dtable[igroup[2] & 0x3F];
255 /* Replace characters in output stream with "=" pad
256 characters if fewer than three characters were
257 read from the end of the input stream. */
265 for (i = 0; i < 4; i++) {
266 dest[dpos++] = ogroup[i];
275 * Convert base64-encoded to binary. Returns the length of the decoded data.
276 * It will stop after reading 'length' bytes.
278 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
284 for (i = 0; i < 255; i++) {
287 for (i = 'A'; i <= 'Z'; i++) {
288 dtable[i] = 0 + (i - 'A');
290 for (i = 'a'; i <= 'z'; i++) {
291 dtable[i] = 26 + (i - 'a');
293 for (i = '0'; i <= '9'; i++) {
294 dtable[i] = 52 + (i - '0');
300 /*CONSTANTCONDITION*/
302 byte a[4], b[4], o[3];
304 for (i = 0; i < 4; i++) {
305 if (spos >= length) {
316 if (dtable[c] & 0x80) {
317 /* Ignoring errors: discard invalid character. */
322 b[i] = (byte) dtable[c];
324 o[0] = (b[0] << 2) | (b[1] >> 4);
325 o[1] = (b[1] << 4) | (b[2] >> 2);
326 o[2] = (b[2] << 6) | b[3];
327 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
328 if (i>=1) dest[dpos++] = o[0];
329 if (i>=2) dest[dpos++] = o[1];
330 if (i>=3) dest[dpos++] = o[2];
339 * if we send out non ascii subjects, we encode it this way.
341 char *rfc2047encode(char *line, long length)
343 char *AlreadyEncoded;
346 #define UTF8_HEADER "=?UTF-8?B?"
348 /* check if we're already done */
349 AlreadyEncoded = strstr(line, "=?");
350 if ((AlreadyEncoded != NULL) &&
351 ((strstr(AlreadyEncoded, "?B?") != NULL)||
352 (strstr(AlreadyEncoded, "?Q?") != NULL)))
357 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
358 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
359 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
360 end = strlen (result);
369 * Strip leading and trailing spaces from a string
371 void striplt(char *buf)
373 if (strlen(buf) == 0) return;
374 while ((strlen(buf) > 0) && (isspace(buf[0])))
375 strcpy(buf, &buf[1]);
376 if (strlen(buf) == 0) return;
377 while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
378 buf[strlen(buf) - 1] = 0;
386 * Return the number of occurances of character ch in string st
388 int haschar(const char *st, int ch)
392 for (a = 0; a < strlen(st); ++a)
403 * Format a date/time stamp for output
404 * seconds is whether to print the seconds
406 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
411 localtime_r(&thetime, &tm);
414 if (hour == 0) hour = 12;
415 else if (hour > 12) hour = hour - 12;
418 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
419 ascmonths[tm.tm_mon],
425 ( (tm.tm_hour >= 12) ? "pm" : "am" )
428 snprintf(buf, n, "%s %d %4d %d:%02d%s",
429 ascmonths[tm.tm_mon],
434 ( (tm.tm_hour >= 12) ? "pm" : "am" )
442 * Determine whether the specified message number is contained within the
443 * specified sequence set.
445 int is_msg_in_sequence_set(char *mset, long msgnum) {
448 char setstr[128], lostr[128], histr[128];
451 num_sets = num_tokens(mset, ',');
452 for (s=0; s<num_sets; ++s) {
453 extract_token(setstr, mset, s, ',', sizeof setstr);
455 extract_token(lostr, setstr, 0, ':', sizeof lostr);
456 if (num_tokens(setstr, ':') >= 2) {
457 extract_token(histr, setstr, 1, ':', sizeof histr);
458 if (!strcmp(histr, "*")) {
459 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
463 strcpy(histr, lostr);
468 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
476 * Utility function to "readline" from memory
477 * (returns new pointer)
479 char *memreadline(char *start, char *buf, int maxlen)
483 int len = 0; /* tally our own length to avoid strlen() delays */
486 memset(buf, 0, maxlen);
490 if ( (len < (maxlen - 1)) && (ch != 13) && (ch != 10) ) {
491 buf[strlen(buf) + 1] = 0;
492 buf[strlen(buf)] = ch;
495 if ((ch == 10) || (ch == 0)) {
503 * Strip a boundarized substring out of a string (for example, remove
504 * parentheses and anything inside them).
506 void stripout(char *str, char leftboundary, char rightboundary) {
511 for (a = 0; a < strlen(str); ++a) {
512 if (str[a] == leftboundary) lb = a;
513 if (str[a] == rightboundary) rb = a;
516 if ( (lb > 0) && (rb > lb) ) {
517 strcpy(&str[lb - 1], &str[rb + 1]);
520 else if ( (lb == 0) && (rb > lb) ) {
521 strcpy(str, &str[rb + 1]);
528 * Reduce a string down to a boundarized substring (for example, remove
529 * parentheses and anything outside them).
531 void stripallbut(char *str, char leftboundary, char rightboundary) {
534 for (a = 0; a < strlen(str); ++ a) {
535 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
538 for (a = 0; a < strlen(str); ++ a) {
539 if (str[a] == rightboundary) str[a] = 0;
544 char *myfgets(char *s, int size, FILE *stream) {
545 char *ret = fgets(s, size, stream);
549 nl = strchr(s, '\n');
559 * Escape a string for feeding out as a URL.
560 * Output buffer must be big enough to handle escape expansion!
562 void urlesc(char *outbuf, char *strbuf)
565 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
569 for (a = 0; a < (int)strlen(strbuf); ++a) {
571 for (b = 0; b < strlen(ec); ++b) {
572 if (strbuf[a] == ec[b])
577 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
579 sprintf(&outbuf[b], "%c", strbuf[a]);
586 * In our world, we want strcpy() to be able to work with overlapping strings.
591 char *strcpy(char *dest, const char *src) {
592 memmove(dest, src, (strlen(src) + 1) );
598 * Generate a new, globally unique UID parameter for a calendar etc. object
600 void generate_uuid(char *buf) {
603 sprintf(buf, "%lx-"F_XPID_T"-%x",
611 * bmstrcasestr() -- case-insensitive substring search
613 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
614 * The code is roughly based on the strstr() replacement from 'tin' written
617 char *bmstrcasestr(char *text, char *pattern) {
619 register unsigned char *p, *t;
620 register int i, j, *delta;
626 textlen = strlen (text);
627 patlen = strlen (pattern);
629 /* algorithm fails if pattern is empty */
630 if ((p1 = patlen) == 0)
633 /* code below fails (whenever i is unsigned) if pattern too long */
639 for (i = 0; i <= 255; i++)
641 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
642 delta[tolower(*p++)] = i;
645 * From now on, we want patlen - 1.
646 * In the loop below, p points to the end of the pattern,
647 * t points to the end of the text to be tested against the
648 * pattern, and i counts the amount of text remaining, not
649 * including the part to be tested.
652 p = (unsigned char *) pattern + p1;
653 t = (unsigned char *) text + p1;
654 i = textlen - patlen;
656 if (tolower(p[0]) == tolower(t[0])) {
657 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
658 return ((char *)t - p1);
661 j = delta[tolower(t[0])];
673 * Local replacement for controversial C library function that generates
674 * names for temporary files. Included to shut up compiler warnings.
676 void CtdlMakeTempFileName(char *name, int len) {
679 while (i++, i < 100) {
680 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
684 if (!access(name, F_OK)) {