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>
30 #include "sysdep_decls.h"
35 typedef unsigned char byte; /* Byte type */
36 static byte dtable[256]; /* base64 encode / decode table */
38 /* Month strings for date conversions */
39 char *ascmonths[12] = {
40 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
41 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
44 char *safestrncpy(char *dest, const char *src, size_t n)
48 if (dest == NULL || src == NULL) {
49 fprintf(stderr, "safestrncpy: NULL argument\n");
55 if (dest[i] == 0) return(dest);
64 #ifndef HAVE_STRNCASECMP
65 int strncasecmp(char *lstr, char *rstr, int len)
70 lc=tolower(lstr[pos]);
71 rc=tolower(rstr[pos]);
72 if ((lc==0)&&(rc==0)) return(0);
73 if (lc<rc) return(-1);
84 * num_tokens() - discover number of parameters/tokens in a string
86 int num_tokens(const char *source, char tok)
89 const char *ptr = source;
95 while (*ptr != '\0') {
104 //extern void cit_backtrace(void);
108 * extract_token() - a string tokenizer
109 * returns -1 if not found, or length of token.
111 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
113 const char *s; //* source * /
114 int len = 0; //* running total length of extracted string * /
115 int current_token = 0; //* token currently being processed * /
124 // lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
132 if (*s == separator) {
135 if ( (current_token == parmnum) &&
141 else if ((current_token > parmnum) || (len >= maxlen)) {
148 if (current_token < parmnum) {
149 // lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
152 // lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
159 * extract_token() - a string tokenizer
161 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
164 const char *s; // source
170 lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
173 // Locate desired parameter
175 while (count < parmnum) {
176 // End of string, bail!
181 if (*s == separator) {
187 lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
188 return -1; // Parameter not found
191 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
195 lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
202 * remove_token() - a tokenizer that kills, maims, and destroys
204 void remove_token(char *source, int parmnum, char separator)
206 char *d, *s; /* dest, source */
209 /* Find desired parameter */
211 while (count < parmnum) {
212 /* End of string, bail! */
217 if (*d == separator) {
222 if (!d) return; /* Parameter not found */
224 /* Find next parameter */
226 while (*s && *s != separator) {
233 else if (d == source)
247 * extract_int() - extract an int parm w/o supplying a buffer
249 int extract_int(const char *source, int parmnum)
253 extract_token(buf, source, parmnum, '|', sizeof buf);
258 * extract_long() - extract an long parm w/o supplying a buffer
260 long extract_long(const char *source, int parmnum)
264 extract_token(buf, source, parmnum, '|', sizeof buf);
270 * extract_unsigned_long() - extract an unsigned long parm
272 unsigned long extract_unsigned_long(const char *source, int parmnum)
276 extract_token(buf, source, parmnum, '|', sizeof buf);
277 return strtoul(buf, NULL, 10);
282 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
283 * John Walker, found in full in the file "base64.c" included with this
284 * distribution. We are moving in the direction of eventually discarding
285 * the separate executables, and using the ones in our code exclusively.
288 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
290 int i, hiteof = FALSE;
294 /* Fill dtable with character encodings. */
296 for (i = 0; i < 26; i++) {
298 dtable[26 + i] = 'a' + i;
300 for (i = 0; i < 10; i++) {
301 dtable[52 + i] = '0' + i;
307 byte igroup[3], ogroup[4];
310 igroup[0] = igroup[1] = igroup[2] = 0;
311 for (n = 0; n < 3; n++) {
312 if (spos >= sourcelen) {
317 igroup[n] = (byte) c;
320 ogroup[0] = dtable[igroup[0] >> 2];
321 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
322 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
323 ogroup[3] = dtable[igroup[2] & 0x3F];
325 /* Replace characters in output stream with "=" pad
326 characters if fewer than three characters were
327 read from the end of the input stream. */
335 for (i = 0; i < 4; i++) {
336 dest[dpos++] = ogroup[i];
345 * Convert base64-encoded to binary. Returns the length of the decoded data.
346 * It will stop after reading 'length' bytes.
348 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
354 for (i = 0; i < 255; i++) {
357 for (i = 'A'; i <= 'Z'; i++) {
358 dtable[i] = 0 + (i - 'A');
360 for (i = 'a'; i <= 'z'; i++) {
361 dtable[i] = 26 + (i - 'a');
363 for (i = '0'; i <= '9'; i++) {
364 dtable[i] = 52 + (i - '0');
370 /*CONSTANTCONDITION*/
372 byte a[4], b[4], o[3];
374 for (i = 0; i < 4; i++) {
375 if (spos >= length) {
386 if (dtable[c] & 0x80) {
387 /* Ignoring errors: discard invalid character. */
392 b[i] = (byte) dtable[c];
394 o[0] = (b[0] << 2) | (b[1] >> 4);
395 o[1] = (b[1] << 4) | (b[2] >> 2);
396 o[2] = (b[2] << 6) | b[3];
397 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
398 if (i>=1) dest[dpos++] = o[0];
399 if (i>=2) dest[dpos++] = o[1];
400 if (i>=3) dest[dpos++] = o[2];
409 * if we send out non ascii subjects, we encode it this way.
411 char *rfc2047encode(char *line, long length)
413 char *AlreadyEncoded;
416 #define UTF8_HEADER "=?UTF-8?B?"
418 /* check if we're already done */
419 AlreadyEncoded = strstr(line, "=?");
420 if ((AlreadyEncoded != NULL) &&
421 ((strstr(AlreadyEncoded, "?B?") != NULL)||
422 (strstr(AlreadyEncoded, "?Q?") != NULL)))
427 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
428 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
429 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
430 end = strlen (result);
439 * Strip leading and trailing spaces from a string
441 void striplt(char *buf)
445 if (IsEmptyStr(buf)) return;
447 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
449 if (IsEmptyStr(buf)) return;
451 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
454 memmove(buf, &buf[a], len - a + 1);
462 * \brief check for the presence of a character within a string (returns count)
463 * \param st the string to examine
464 * \param ch the char to search
465 * \return the position inside of st
467 int haschar(const char *st,int ch)
473 while (!IsEmptyStr(ptr))
487 * Format a date/time stamp for output
488 * seconds is whether to print the seconds
490 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
495 localtime_r(&thetime, &tm);
498 if (hour == 0) hour = 12;
499 else if (hour > 12) hour = hour - 12;
502 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
503 ascmonths[tm.tm_mon],
509 ( (tm.tm_hour >= 12) ? "pm" : "am" )
512 snprintf(buf, n, "%s %d %4d %d:%02d%s",
513 ascmonths[tm.tm_mon],
518 ( (tm.tm_hour >= 12) ? "pm" : "am" )
526 * Determine whether the specified message number is contained within the
527 * specified sequence set.
529 int is_msg_in_sequence_set(char *mset, long msgnum) {
532 char setstr[128], lostr[128], histr[128];
535 num_sets = num_tokens(mset, ',');
536 for (s=0; s<num_sets; ++s) {
537 extract_token(setstr, mset, s, ',', sizeof setstr);
539 extract_token(lostr, setstr, 0, ':', sizeof lostr);
540 if (num_tokens(setstr, ':') >= 2) {
541 extract_token(histr, setstr, 1, ':', sizeof histr);
542 if (!strcmp(histr, "*")) {
543 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
547 strcpy(histr, lostr);
552 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
559 * \brief Utility function to "readline" from memory
560 * \param start Location in memory from which we are reading.
561 * \param buf the buffer to place the string in.
562 * \param maxlen Size of string buffer
563 * \return Pointer to the source memory right after we stopped reading.
565 char *memreadline(char *start, char *buf, int maxlen)
569 int len = 0; /**< tally our own length to avoid strlen() delays */
575 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
578 if ((ch == 10) || (ch == 0)) {
589 * Strip a boundarized substring out of a string (for example, remove
590 * parentheses and anything inside them).
592 void stripout(char *str, char leftboundary, char rightboundary) {
597 for (a = 0; a < strlen(str); ++a) {
598 if (str[a] == leftboundary) lb = a;
599 if (str[a] == rightboundary) rb = a;
602 if ( (lb > 0) && (rb > lb) ) {
603 strcpy(&str[lb - 1], &str[rb + 1]);
606 else if ( (lb == 0) && (rb > lb) ) {
607 strcpy(str, &str[rb + 1]);
614 * Reduce a string down to a boundarized substring (for example, remove
615 * parentheses and anything outside them).
617 void stripallbut(char *str, char leftboundary, char rightboundary) {
620 for (a = 0; a < strlen(str); ++ a) {
621 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
624 for (a = 0; a < strlen(str); ++ a) {
625 if (str[a] == rightboundary) str[a] = 0;
630 char *myfgets(char *s, int size, FILE *stream) {
631 char *ret = fgets(s, size, stream);
635 nl = strchr(s, '\n');
645 * Escape a string for feeding out as a URL.
646 * Output buffer must be big enough to handle escape expansion!
648 void urlesc(char *outbuf, char *strbuf)
651 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
655 for (a = 0; a < (int)strlen(strbuf); ++a) {
657 for (b = 0; b < strlen(ec); ++b) {
658 if (strbuf[a] == ec[b])
663 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
665 sprintf(&outbuf[b], "%c", strbuf[a]);
672 * In our world, we want strcpy() to be able to work with overlapping strings.
677 char *strcpy(char *dest, const char *src) {
678 memmove(dest, src, (strlen(src) + 1) );
684 * Generate a new, globally unique UID parameter for a calendar etc. object
686 void generate_uuid(char *buf) {
689 sprintf(buf, "%lx-"F_XPID_T"-%x",
697 * bmstrcasestr() -- case-insensitive substring search
699 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
700 * The code is roughly based on the strstr() replacement from 'tin' written
703 char *bmstrcasestr(char *text, char *pattern) {
705 register unsigned char *p, *t;
706 register int i, j, *delta;
712 textlen = strlen (text);
713 patlen = strlen (pattern);
715 /* algorithm fails if pattern is empty */
716 if ((p1 = patlen) == 0)
719 /* code below fails (whenever i is unsigned) if pattern too long */
725 for (i = 0; i <= 255; i++)
727 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
728 delta[tolower(*p++)] = i;
731 * From now on, we want patlen - 1.
732 * In the loop below, p points to the end of the pattern,
733 * t points to the end of the text to be tested against the
734 * pattern, and i counts the amount of text remaining, not
735 * including the part to be tested.
738 p = (unsigned char *) pattern + p1;
739 t = (unsigned char *) text + p1;
740 i = textlen - patlen;
742 if (tolower(p[0]) == tolower(t[0])) {
743 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
744 return ((char *)t - p1);
747 j = delta[tolower(t[0])];
759 * Local replacement for controversial C library function that generates
760 * names for temporary files. Included to shut up compiler warnings.
762 void CtdlMakeTempFileName(char *name, int len) {
765 while (i++, i < 100) {
766 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
770 if (!access(name, F_OK)) {