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)
88 const char *ptr = source;
94 while (*ptr != '\0') {
105 * extract_token() - a string tokenizer
107 void extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
110 const char *s; /* source */
116 /* Locate desired parameter */
118 while (count < parmnum) {
119 /* End of string, bail! */
124 if (*s == separator) {
129 if (!s) return; /* Parameter not found */
131 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
139 * remove_token() - a tokenizer that kills, maims, and destroys
141 void remove_token(char *source, int parmnum, char separator)
143 char *d, *s; /* dest, source */
146 /* Find desired parameter */
148 while (count < parmnum) {
149 /* End of string, bail! */
154 if (*d == separator) {
159 if (!d) return; /* Parameter not found */
161 /* Find next parameter */
163 while (*s && *s != separator) {
170 else if (d == source)
184 * extract_int() - extract an int parm w/o supplying a buffer
186 int extract_int(const char *source, int parmnum)
190 extract_token(buf, source, parmnum, '|', sizeof buf);
195 * extract_long() - extract an long parm w/o supplying a buffer
197 long extract_long(const char *source, int parmnum)
201 extract_token(buf, source, parmnum, '|', sizeof buf);
207 * extract_unsigned_long() - extract an unsigned long parm
209 unsigned long extract_unsigned_long(const char *source, int parmnum)
213 extract_token(buf, source, parmnum, '|', sizeof buf);
214 return strtoul(buf, NULL, 10);
219 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
220 * John Walker, found in full in the file "base64.c" included with this
221 * distribution. We are moving in the direction of eventually discarding
222 * the separate executables, and using the ones in our code exclusively.
225 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
227 int i, hiteof = FALSE;
231 /* Fill dtable with character encodings. */
233 for (i = 0; i < 26; i++) {
235 dtable[26 + i] = 'a' + i;
237 for (i = 0; i < 10; i++) {
238 dtable[52 + i] = '0' + i;
244 byte igroup[3], ogroup[4];
247 igroup[0] = igroup[1] = igroup[2] = 0;
248 for (n = 0; n < 3; n++) {
249 if (spos >= sourcelen) {
254 igroup[n] = (byte) c;
257 ogroup[0] = dtable[igroup[0] >> 2];
258 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
259 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
260 ogroup[3] = dtable[igroup[2] & 0x3F];
262 /* Replace characters in output stream with "=" pad
263 characters if fewer than three characters were
264 read from the end of the input stream. */
272 for (i = 0; i < 4; i++) {
273 dest[dpos++] = ogroup[i];
282 * Convert base64-encoded to binary. Returns the length of the decoded data.
283 * It will stop after reading 'length' bytes.
285 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
291 for (i = 0; i < 255; i++) {
294 for (i = 'A'; i <= 'Z'; i++) {
295 dtable[i] = 0 + (i - 'A');
297 for (i = 'a'; i <= 'z'; i++) {
298 dtable[i] = 26 + (i - 'a');
300 for (i = '0'; i <= '9'; i++) {
301 dtable[i] = 52 + (i - '0');
307 /*CONSTANTCONDITION*/
309 byte a[4], b[4], o[3];
311 for (i = 0; i < 4; i++) {
312 if (spos >= length) {
323 if (dtable[c] & 0x80) {
324 /* Ignoring errors: discard invalid character. */
329 b[i] = (byte) dtable[c];
331 o[0] = (b[0] << 2) | (b[1] >> 4);
332 o[1] = (b[1] << 4) | (b[2] >> 2);
333 o[2] = (b[2] << 6) | b[3];
334 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
335 if (i>=1) dest[dpos++] = o[0];
336 if (i>=2) dest[dpos++] = o[1];
337 if (i>=3) dest[dpos++] = o[2];
346 * if we send out non ascii subjects, we encode it this way.
348 char *rfc2047encode(char *line, long length)
350 char *AlreadyEncoded;
353 #define UTF8_HEADER "=?UTF-8?B?"
355 /* check if we're already done */
356 AlreadyEncoded = strstr(line, "=?");
357 if ((AlreadyEncoded != NULL) &&
358 ((strstr(AlreadyEncoded, "?B?") != NULL)||
359 (strstr(AlreadyEncoded, "?Q?") != NULL)))
364 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
365 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
366 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
367 end = strlen (result);
376 * Strip leading and trailing spaces from a string
378 void striplt(char *buf)
380 if (strlen(buf) == 0) return;
381 while ((strlen(buf) > 0) && (isspace(buf[0])))
382 strcpy(buf, &buf[1]);
383 if (strlen(buf) == 0) return;
384 while ((strlen(buf) > 0) && (isspace(buf[strlen(buf) - 1])))
385 buf[strlen(buf) - 1] = 0;
393 * Return the number of occurances of character ch in string st
395 int haschar(const char *st, int ch)
399 for (a = 0; a < strlen(st); ++a)
410 * Format a date/time stamp for output
411 * seconds is whether to print the seconds
413 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
418 localtime_r(&thetime, &tm);
421 if (hour == 0) hour = 12;
422 else if (hour > 12) hour = hour - 12;
425 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
426 ascmonths[tm.tm_mon],
432 ( (tm.tm_hour >= 12) ? "pm" : "am" )
435 snprintf(buf, n, "%s %d %4d %d:%02d%s",
436 ascmonths[tm.tm_mon],
441 ( (tm.tm_hour >= 12) ? "pm" : "am" )
449 * Determine whether the specified message number is contained within the
450 * specified sequence set.
452 int is_msg_in_sequence_set(char *mset, long msgnum) {
455 char setstr[128], lostr[128], histr[128];
458 num_sets = num_tokens(mset, ',');
459 for (s=0; s<num_sets; ++s) {
460 extract_token(setstr, mset, s, ',', sizeof setstr);
462 extract_token(lostr, setstr, 0, ':', sizeof lostr);
463 if (num_tokens(setstr, ':') >= 2) {
464 extract_token(histr, setstr, 1, ':', sizeof histr);
465 if (!strcmp(histr, "*")) {
466 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
470 strcpy(histr, lostr);
475 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
483 * Utility function to "readline" from memory
484 * (returns new pointer)
486 char *memreadline(char *start, char *buf, int maxlen)
490 int len = 0; /* tally our own length to avoid strlen() delays */
493 memset(buf, 0, maxlen);
497 if ( (len < (maxlen - 1)) && (ch != 13) && (ch != 10) ) {
498 buf[strlen(buf) + 1] = 0;
499 buf[strlen(buf)] = ch;
502 if ((ch == 10) || (ch == 0)) {
510 * Strip a boundarized substring out of a string (for example, remove
511 * parentheses and anything inside them).
513 void stripout(char *str, char leftboundary, char rightboundary) {
518 for (a = 0; a < strlen(str); ++a) {
519 if (str[a] == leftboundary) lb = a;
520 if (str[a] == rightboundary) rb = a;
523 if ( (lb > 0) && (rb > lb) ) {
524 strcpy(&str[lb - 1], &str[rb + 1]);
527 else if ( (lb == 0) && (rb > lb) ) {
528 strcpy(str, &str[rb + 1]);
535 * Reduce a string down to a boundarized substring (for example, remove
536 * parentheses and anything outside them).
538 void stripallbut(char *str, char leftboundary, char rightboundary) {
541 for (a = 0; a < strlen(str); ++ a) {
542 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
545 for (a = 0; a < strlen(str); ++ a) {
546 if (str[a] == rightboundary) str[a] = 0;
551 char *myfgets(char *s, int size, FILE *stream) {
552 char *ret = fgets(s, size, stream);
556 nl = strchr(s, '\n');
566 * Escape a string for feeding out as a URL.
567 * Output buffer must be big enough to handle escape expansion!
569 void urlesc(char *outbuf, char *strbuf)
572 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
576 for (a = 0; a < (int)strlen(strbuf); ++a) {
578 for (b = 0; b < strlen(ec); ++b) {
579 if (strbuf[a] == ec[b])
584 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
586 sprintf(&outbuf[b], "%c", strbuf[a]);
593 * In our world, we want strcpy() to be able to work with overlapping strings.
598 char *strcpy(char *dest, const char *src) {
599 memmove(dest, src, (strlen(src) + 1) );
605 * Generate a new, globally unique UID parameter for a calendar etc. object
607 void generate_uuid(char *buf) {
610 sprintf(buf, "%lx-"F_XPID_T"-%x",
618 * bmstrcasestr() -- case-insensitive substring search
620 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
621 * The code is roughly based on the strstr() replacement from 'tin' written
624 char *bmstrcasestr(char *text, char *pattern) {
626 register unsigned char *p, *t;
627 register int i, j, *delta;
633 textlen = strlen (text);
634 patlen = strlen (pattern);
636 /* algorithm fails if pattern is empty */
637 if ((p1 = patlen) == 0)
640 /* code below fails (whenever i is unsigned) if pattern too long */
646 for (i = 0; i <= 255; i++)
648 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
649 delta[tolower(*p++)] = i;
652 * From now on, we want patlen - 1.
653 * In the loop below, p points to the end of the pattern,
654 * t points to the end of the text to be tested against the
655 * pattern, and i counts the amount of text remaining, not
656 * including the part to be tested.
659 p = (unsigned char *) pattern + p1;
660 t = (unsigned char *) text + p1;
661 i = textlen - patlen;
663 if (tolower(p[0]) == tolower(t[0])) {
664 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
665 return ((char *)t - p1);
668 j = delta[tolower(t[0])];
680 * Local replacement for controversial C library function that generates
681 * names for temporary files. Included to shut up compiler warnings.
683 void CtdlMakeTempFileName(char *name, int len) {
686 while (i++, i < 100) {
687 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
691 if (!access(name, F_OK)) {