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] = "\0"; /* base64 decode table */
37 static byte etable[256] = "\0"; /* base64 encode table */
39 /* Month strings for date conversions */
40 char *ascmonths[12] = {
41 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
42 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
45 char *safestrncpy(char *dest, const char *src, size_t n)
49 if (dest == NULL || src == NULL) {
50 fprintf(stderr, "safestrncpy: NULL argument\n");
56 if (dest[i] == 0) return(dest);
65 #ifndef HAVE_STRNCASECMP
66 int strncasecmp(char *lstr, char *rstr, int len)
71 lc=tolower(lstr[pos]);
72 rc=tolower(rstr[pos]);
73 if ((lc==0)&&(rc==0)) return(0);
74 if (lc<rc) return(-1);
85 * num_tokens() - discover number of parameters/tokens in a string
87 int num_tokens(const char *source, char tok)
90 const char *ptr = source;
96 while (*ptr != '\0') {
105 //extern void cit_backtrace(void);
109 * extract_token() - a string tokenizer
110 * returns -1 if not found, or length of token.
112 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
114 const char *s; //* source * /
115 int len = 0; //* running total length of extracted string * /
116 int current_token = 0; //* token currently being processed * /
125 // lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
135 if (*s == separator) {
138 if ( (current_token == parmnum) &&
144 else if ((current_token > parmnum) || (len >= maxlen)) {
151 if (current_token < parmnum) {
152 // lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
155 // lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
162 * extract_token() - a string tokenizer
164 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
167 const char *s; // source
173 lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
176 // Locate desired parameter
178 while (count < parmnum) {
179 // End of string, bail!
184 if (*s == separator) {
190 lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
191 return -1; // Parameter not found
194 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
198 lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
205 * remove_token() - a tokenizer that kills, maims, and destroys
207 void remove_token(char *source, int parmnum, char separator)
209 char *d, *s; /* dest, source */
212 /* Find desired parameter */
214 while (count < parmnum) {
215 /* End of string, bail! */
220 if (*d == separator) {
225 if (!d) return; /* Parameter not found */
227 /* Find next parameter */
229 while (*s && *s != separator) {
236 else if (d == source)
250 * extract_int() - extract an int parm w/o supplying a buffer
252 int extract_int(const char *source, int parmnum)
256 extract_token(buf, source, parmnum, '|', sizeof buf);
261 * extract_long() - extract an long parm w/o supplying a buffer
263 long extract_long(const char *source, int parmnum)
267 extract_token(buf, source, parmnum, '|', sizeof buf);
273 * extract_unsigned_long() - extract an unsigned long parm
275 unsigned long extract_unsigned_long(const char *source, int parmnum)
279 extract_token(buf, source, parmnum, '|', sizeof buf);
280 return strtoul(buf, NULL, 10);
285 void CtdlInitBase64Table(void)
288 /* Fill dtable with character encodings. */
291 for (i = 0; i < 26; i++) {
293 etable[26 + i] = 'a' + i;
295 for (i = 0; i < 10; i++) {
296 etable[52 + i] = '0' + i;
302 for (i = 0; i < 255; i++) {
305 for (i = 'A'; i <= 'Z'; i++) {
306 dtable[i] = 0 + (i - 'A');
308 for (i = 'a'; i <= 'z'; i++) {
309 dtable[i] = 26 + (i - 'a');
311 for (i = '0'; i <= '9'; i++) {
312 dtable[i] = 52 + (i - '0');
320 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
321 * John Walker, found in full in the file "base64.c" included with this
322 * distribution. We are moving in the direction of eventually discarding
323 * the separate executables, and using the ones in our code exclusively.
326 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
328 int i, hiteof = FALSE;
333 byte igroup[3], ogroup[4];
336 igroup[0] = igroup[1] = igroup[2] = 0;
337 for (n = 0; n < 3; n++) {
338 if (spos >= sourcelen) {
343 igroup[n] = (byte) c;
346 ogroup[0] = etable[igroup[0] >> 2];
347 ogroup[1] = etable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
348 ogroup[2] = etable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
349 ogroup[3] = etable[igroup[2] & 0x3F];
351 /* Replace characters in output stream with "=" pad
352 characters if fewer than three characters were
353 read from the end of the input stream. */
361 for (i = 0; i < 4; i++) {
362 dest[dpos++] = ogroup[i];
371 * Convert base64-encoded to binary. Returns the length of the decoded data.
372 * It will stop after reading 'length' bytes.
374 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
381 /*CONSTANTCONDITION*/
383 byte a[4], b[4], o[3];
385 for (i = 0; i < 4; i++) {
386 if (spos >= length) {
397 if (dtable[c] & 0x80) {
398 /* Ignoring errors: discard invalid character. */
403 b[i] = (byte) dtable[c];
405 o[0] = (b[0] << 2) | (b[1] >> 4);
406 o[1] = (b[1] << 4) | (b[2] >> 2);
407 o[2] = (b[2] << 6) | b[3];
408 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
409 if (i>=1) dest[dpos++] = o[0];
410 if (i>=2) dest[dpos++] = o[1];
411 if (i>=3) dest[dpos++] = o[2];
420 * if we send out non ascii subjects, we encode it this way.
422 char *rfc2047encode(char *line, long length)
424 char *AlreadyEncoded;
427 #define UTF8_HEADER "=?UTF-8?B?"
429 /* check if we're already done */
430 AlreadyEncoded = strstr(line, "=?");
431 if ((AlreadyEncoded != NULL) &&
432 ((strstr(AlreadyEncoded, "?B?") != NULL)||
433 (strstr(AlreadyEncoded, "?Q?") != NULL)))
438 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
439 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
440 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
441 end = strlen (result);
450 * Strip leading and trailing spaces from a string
452 void striplt(char *buf)
456 if (IsEmptyStr(buf)) return;
458 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
460 if (IsEmptyStr(buf)) return;
462 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
465 memmove(buf, &buf[a], len - a + 1);
473 * \brief check for the presence of a character within a string (returns count)
474 * \param st the string to examine
475 * \param ch the char to search
476 * \return the position inside of st
478 int haschar(const char *st,int ch)
484 while (!IsEmptyStr(ptr))
498 * Format a date/time stamp for output
499 * seconds is whether to print the seconds
501 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
506 localtime_r(&thetime, &tm);
509 if (hour == 0) hour = 12;
510 else if (hour > 12) hour = hour - 12;
513 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
514 ascmonths[tm.tm_mon],
520 ( (tm.tm_hour >= 12) ? "pm" : "am" )
523 snprintf(buf, n, "%s %d %4d %d:%02d%s",
524 ascmonths[tm.tm_mon],
529 ( (tm.tm_hour >= 12) ? "pm" : "am" )
537 * Determine whether the specified message number is contained within the
538 * specified sequence set.
540 int is_msg_in_sequence_set(char *mset, long msgnum) {
543 char setstr[128], lostr[128], histr[128];
546 num_sets = num_tokens(mset, ',');
547 for (s=0; s<num_sets; ++s) {
548 extract_token(setstr, mset, s, ',', sizeof setstr);
550 extract_token(lostr, setstr, 0, ':', sizeof lostr);
551 if (num_tokens(setstr, ':') >= 2) {
552 extract_token(histr, setstr, 1, ':', sizeof histr);
553 if (!strcmp(histr, "*")) {
554 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
558 strcpy(histr, lostr);
563 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
570 * \brief Utility function to "readline" from memory
571 * \param start Location in memory from which we are reading.
572 * \param buf the buffer to place the string in.
573 * \param maxlen Size of string buffer
574 * \return Pointer to the source memory right after we stopped reading.
576 char *memreadline(char *start, char *buf, int maxlen)
580 int len = 0; /**< tally our own length to avoid strlen() delays */
586 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
589 if ((ch == 10) || (ch == 0)) {
598 * \brief Utility function to "readline" from memory
599 * \param start Location in memory from which we are reading.
600 * \param buf the buffer to place the string in.
601 * \param maxlen Size of string buffer
602 * \param retlen the length of the returned string
603 * \return Pointer to the source memory right after we stopped reading.
605 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
609 int len = 0; /**< tally our own length to avoid strlen() delays */
615 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
618 if ((ch == 10) || (ch == 0)) {
630 * Strip a boundarized substring out of a string (for example, remove
631 * parentheses and anything inside them).
633 void stripout(char *str, char leftboundary, char rightboundary) {
638 for (a = 0; a < strlen(str); ++a) {
639 if (str[a] == leftboundary) lb = a;
640 if (str[a] == rightboundary) rb = a;
643 if ( (lb > 0) && (rb > lb) ) {
644 strcpy(&str[lb - 1], &str[rb + 1]);
647 else if ( (lb == 0) && (rb > lb) ) {
648 strcpy(str, &str[rb + 1]);
655 * Reduce a string down to a boundarized substring (for example, remove
656 * parentheses and anything outside them).
658 void stripallbut(char *str, char leftboundary, char rightboundary) {
661 for (a = 0; a < strlen(str); ++ a) {
662 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
665 for (a = 0; a < strlen(str); ++ a) {
666 if (str[a] == rightboundary) str[a] = 0;
671 char *myfgets(char *s, int size, FILE *stream) {
672 char *ret = fgets(s, size, stream);
676 nl = strchr(s, '\n');
686 * Escape a string for feeding out as a URL.
687 * Output buffer must be big enough to handle escape expansion!
689 void urlesc(char *outbuf, char *strbuf)
692 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
696 for (a = 0; a < (int)strlen(strbuf); ++a) {
698 for (b = 0; b < strlen(ec); ++b) {
699 if (strbuf[a] == ec[b])
704 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
706 sprintf(&outbuf[b], "%c", strbuf[a]);
713 * In our world, we want strcpy() to be able to work with overlapping strings.
718 char *strcpy(char *dest, const char *src) {
719 memmove(dest, src, (strlen(src) + 1) );
725 * Generate a new, globally unique UID parameter for a calendar etc. object
727 void generate_uuid(char *buf) {
730 sprintf(buf, "%lx-"F_XPID_T"-%x",
738 * bmstrcasestr() -- case-insensitive substring search
740 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
741 * The code is roughly based on the strstr() replacement from 'tin' written
744 char *bmstrcasestr(char *text, char *pattern) {
746 register unsigned char *p, *t;
747 register int i, j, *delta;
753 textlen = strlen (text);
754 patlen = strlen (pattern);
756 /* algorithm fails if pattern is empty */
757 if ((p1 = patlen) == 0)
760 /* code below fails (whenever i is unsigned) if pattern too long */
766 for (i = 0; i <= 255; i++)
768 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
769 delta[tolower(*p++)] = i;
772 * From now on, we want patlen - 1.
773 * In the loop below, p points to the end of the pattern,
774 * t points to the end of the text to be tested against the
775 * pattern, and i counts the amount of text remaining, not
776 * including the part to be tested.
779 p = (unsigned char *) pattern + p1;
780 t = (unsigned char *) text + p1;
781 i = textlen - patlen;
783 if (tolower(p[0]) == tolower(t[0])) {
784 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
785 return ((char *)t - p1);
788 j = delta[tolower(t[0])];
800 * Local replacement for controversial C library function that generates
801 * names for temporary files. Included to shut up compiler warnings.
803 void CtdlMakeTempFileName(char *name, int len) {
806 while (i++, i < 100) {
807 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
811 if (!access(name, F_OK)) {