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);
133 if (*s == separator) {
136 if ( (current_token == parmnum) &&
142 else if ((current_token > parmnum) || (len >= maxlen)) {
149 if (current_token < parmnum) {
150 // lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
153 // lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
160 * extract_token() - a string tokenizer
162 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
165 const char *s; // source
171 lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
174 // Locate desired parameter
176 while (count < parmnum) {
177 // End of string, bail!
182 if (*s == separator) {
188 lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
189 return -1; // Parameter not found
192 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
196 lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
203 * remove_token() - a tokenizer that kills, maims, and destroys
205 void remove_token(char *source, int parmnum, char separator)
207 char *d, *s; /* dest, source */
210 /* Find desired parameter */
212 while (count < parmnum) {
213 /* End of string, bail! */
218 if (*d == separator) {
223 if (!d) return; /* Parameter not found */
225 /* Find next parameter */
227 while (*s && *s != separator) {
234 else if (d == source)
248 * extract_int() - extract an int parm w/o supplying a buffer
250 int extract_int(const char *source, int parmnum)
254 extract_token(buf, source, parmnum, '|', sizeof buf);
259 * extract_long() - extract an long parm w/o supplying a buffer
261 long extract_long(const char *source, int parmnum)
265 extract_token(buf, source, parmnum, '|', sizeof buf);
271 * extract_unsigned_long() - extract an unsigned long parm
273 unsigned long extract_unsigned_long(const char *source, int parmnum)
277 extract_token(buf, source, parmnum, '|', sizeof buf);
278 return strtoul(buf, NULL, 10);
283 void CtdlInitBase64Table(void)
286 /* Fill dtable with character encodings. */
289 for (i = 0; i < 26; i++) {
291 etable[26 + i] = 'a' + i;
293 for (i = 0; i < 10; i++) {
294 etable[52 + i] = '0' + i;
300 for (i = 0; i < 255; i++) {
303 for (i = 'A'; i <= 'Z'; i++) {
304 dtable[i] = 0 + (i - 'A');
306 for (i = 'a'; i <= 'z'; i++) {
307 dtable[i] = 26 + (i - 'a');
309 for (i = '0'; i <= '9'; i++) {
310 dtable[i] = 52 + (i - '0');
318 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by
319 * John Walker, found in full in the file "base64.c" included with this
320 * distribution. We are moving in the direction of eventually discarding
321 * the separate executables, and using the ones in our code exclusively.
324 void CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen)
326 int i, hiteof = FALSE;
331 byte igroup[3], ogroup[4];
334 igroup[0] = igroup[1] = igroup[2] = 0;
335 for (n = 0; n < 3; n++) {
336 if (spos >= sourcelen) {
341 igroup[n] = (byte) c;
344 ogroup[0] = etable[igroup[0] >> 2];
345 ogroup[1] = etable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
346 ogroup[2] = etable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
347 ogroup[3] = etable[igroup[2] & 0x3F];
349 /* Replace characters in output stream with "=" pad
350 characters if fewer than three characters were
351 read from the end of the input stream. */
359 for (i = 0; i < 4; i++) {
360 dest[dpos++] = ogroup[i];
369 * Convert base64-encoded to binary. Returns the length of the decoded data.
370 * It will stop after reading 'length' bytes.
372 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
379 /*CONSTANTCONDITION*/
381 byte a[4], b[4], o[3];
383 for (i = 0; i < 4; i++) {
384 if (spos >= length) {
395 if (dtable[c] & 0x80) {
396 /* Ignoring errors: discard invalid character. */
401 b[i] = (byte) dtable[c];
403 o[0] = (b[0] << 2) | (b[1] >> 4);
404 o[1] = (b[1] << 4) | (b[2] >> 2);
405 o[2] = (b[2] << 6) | b[3];
406 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
407 if (i>=1) dest[dpos++] = o[0];
408 if (i>=2) dest[dpos++] = o[1];
409 if (i>=3) dest[dpos++] = o[2];
418 * if we send out non ascii subjects, we encode it this way.
420 char *rfc2047encode(char *line, long length)
422 char *AlreadyEncoded;
425 #define UTF8_HEADER "=?UTF-8?B?"
427 /* check if we're already done */
428 AlreadyEncoded = strstr(line, "=?");
429 if ((AlreadyEncoded != NULL) &&
430 ((strstr(AlreadyEncoded, "?B?") != NULL)||
431 (strstr(AlreadyEncoded, "?Q?") != NULL)))
436 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
437 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
438 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
439 end = strlen (result);
448 * Strip leading and trailing spaces from a string
450 void striplt(char *buf)
454 if (IsEmptyStr(buf)) return;
456 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
458 if (IsEmptyStr(buf)) return;
460 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
463 memmove(buf, &buf[a], len - a + 1);
471 * \brief check for the presence of a character within a string (returns count)
472 * \param st the string to examine
473 * \param ch the char to search
474 * \return the position inside of st
476 int haschar(const char *st,int ch)
482 while (!IsEmptyStr(ptr))
496 * Format a date/time stamp for output
497 * seconds is whether to print the seconds
499 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
504 localtime_r(&thetime, &tm);
507 if (hour == 0) hour = 12;
508 else if (hour > 12) hour = hour - 12;
511 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
512 ascmonths[tm.tm_mon],
518 ( (tm.tm_hour >= 12) ? "pm" : "am" )
521 snprintf(buf, n, "%s %d %4d %d:%02d%s",
522 ascmonths[tm.tm_mon],
527 ( (tm.tm_hour >= 12) ? "pm" : "am" )
535 * Determine whether the specified message number is contained within the
536 * specified sequence set.
538 int is_msg_in_sequence_set(char *mset, long msgnum) {
541 char setstr[128], lostr[128], histr[128];
544 num_sets = num_tokens(mset, ',');
545 for (s=0; s<num_sets; ++s) {
546 extract_token(setstr, mset, s, ',', sizeof setstr);
548 extract_token(lostr, setstr, 0, ':', sizeof lostr);
549 if (num_tokens(setstr, ':') >= 2) {
550 extract_token(histr, setstr, 1, ':', sizeof histr);
551 if (!strcmp(histr, "*")) {
552 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
556 strcpy(histr, lostr);
561 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
568 * \brief Utility function to "readline" from memory
569 * \param start Location in memory from which we are reading.
570 * \param buf the buffer to place the string in.
571 * \param maxlen Size of string buffer
572 * \return Pointer to the source memory right after we stopped reading.
574 char *memreadline(char *start, char *buf, int maxlen)
578 int len = 0; /**< tally our own length to avoid strlen() delays */
584 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
587 if ((ch == 10) || (ch == 0)) {
598 * Strip a boundarized substring out of a string (for example, remove
599 * parentheses and anything inside them).
601 void stripout(char *str, char leftboundary, char rightboundary) {
606 for (a = 0; a < strlen(str); ++a) {
607 if (str[a] == leftboundary) lb = a;
608 if (str[a] == rightboundary) rb = a;
611 if ( (lb > 0) && (rb > lb) ) {
612 strcpy(&str[lb - 1], &str[rb + 1]);
615 else if ( (lb == 0) && (rb > lb) ) {
616 strcpy(str, &str[rb + 1]);
623 * Reduce a string down to a boundarized substring (for example, remove
624 * parentheses and anything outside them).
626 void stripallbut(char *str, char leftboundary, char rightboundary) {
629 for (a = 0; a < strlen(str); ++ a) {
630 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
633 for (a = 0; a < strlen(str); ++ a) {
634 if (str[a] == rightboundary) str[a] = 0;
639 char *myfgets(char *s, int size, FILE *stream) {
640 char *ret = fgets(s, size, stream);
644 nl = strchr(s, '\n');
654 * Escape a string for feeding out as a URL.
655 * Output buffer must be big enough to handle escape expansion!
657 void urlesc(char *outbuf, char *strbuf)
660 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
664 for (a = 0; a < (int)strlen(strbuf); ++a) {
666 for (b = 0; b < strlen(ec); ++b) {
667 if (strbuf[a] == ec[b])
672 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
674 sprintf(&outbuf[b], "%c", strbuf[a]);
681 * In our world, we want strcpy() to be able to work with overlapping strings.
686 char *strcpy(char *dest, const char *src) {
687 memmove(dest, src, (strlen(src) + 1) );
693 * Generate a new, globally unique UID parameter for a calendar etc. object
695 void generate_uuid(char *buf) {
698 sprintf(buf, "%lx-"F_XPID_T"-%x",
706 * bmstrcasestr() -- case-insensitive substring search
708 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
709 * The code is roughly based on the strstr() replacement from 'tin' written
712 char *bmstrcasestr(char *text, char *pattern) {
714 register unsigned char *p, *t;
715 register int i, j, *delta;
721 textlen = strlen (text);
722 patlen = strlen (pattern);
724 /* algorithm fails if pattern is empty */
725 if ((p1 = patlen) == 0)
728 /* code below fails (whenever i is unsigned) if pattern too long */
734 for (i = 0; i <= 255; i++)
736 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
737 delta[tolower(*p++)] = i;
740 * From now on, we want patlen - 1.
741 * In the loop below, p points to the end of the pattern,
742 * t points to the end of the text to be tested against the
743 * pattern, and i counts the amount of text remaining, not
744 * including the part to be tested.
747 p = (unsigned char *) pattern + p1;
748 t = (unsigned char *) text + p1;
749 i = textlen - patlen;
751 if (tolower(p[0]) == tolower(t[0])) {
752 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
753 return ((char *)t - p1);
756 j = delta[tolower(t[0])];
768 * Local replacement for controversial C library function that generates
769 * names for temporary files. Included to shut up compiler warnings.
771 void CtdlMakeTempFileName(char *name, int len) {
774 while (i++, i < 100) {
775 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
779 if (!access(name, F_OK)) {