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 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
421 * according to RFC2045 section 6.7
423 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
425 int decoded_length = 0;
428 while (pos < sourcelen)
430 if (!strncmp(&encoded[pos], "=\r\n", 3))
434 else if (!strncmp(&encoded[pos], "=\n", 2))
438 else if (encoded[pos] == '=')
441 sscanf(&encoded[pos+1], "%02x", &ch);
443 decoded[decoded_length++] = ch;
447 decoded[decoded_length++] = encoded[pos];
451 decoded[decoded_length] = 0;
452 return(decoded_length);
457 * if we send out non ascii subjects, we encode it this way.
459 char *rfc2047encode(char *line, long length)
461 char *AlreadyEncoded;
464 #define UTF8_HEADER "=?UTF-8?B?"
466 /* check if we're already done */
467 AlreadyEncoded = strstr(line, "=?");
468 if ((AlreadyEncoded != NULL) &&
469 ((strstr(AlreadyEncoded, "?B?") != NULL)||
470 (strstr(AlreadyEncoded, "?Q?") != NULL)))
475 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
476 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
477 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length);
478 end = strlen (result);
487 * Strip leading and trailing spaces from a string
489 void striplt(char *buf)
494 if (buf==NULL) return;
495 if (IsEmptyStr(buf)) return;
497 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
499 if (IsEmptyStr(buf)) return;
501 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
504 memmove(buf, &buf[a], len - a + 1);
512 * \brief check for the presence of a character within a string (returns count)
513 * \param st the string to examine
514 * \param ch the char to search
515 * \return the position inside of st
517 int haschar(const char *st,int ch)
523 while (!IsEmptyStr(ptr))
537 * Format a date/time stamp for output
538 * seconds is whether to print the seconds
540 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
545 localtime_r(&thetime, &tm);
548 if (hour == 0) hour = 12;
549 else if (hour > 12) hour = hour - 12;
552 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
553 ascmonths[tm.tm_mon],
559 ( (tm.tm_hour >= 12) ? "pm" : "am" )
562 snprintf(buf, n, "%s %d %4d %d:%02d%s",
563 ascmonths[tm.tm_mon],
568 ( (tm.tm_hour >= 12) ? "pm" : "am" )
576 * Determine whether the specified message number is contained within the
577 * specified sequence set.
579 int is_msg_in_sequence_set(char *mset, long msgnum) {
582 char setstr[128], lostr[128], histr[128];
585 num_sets = num_tokens(mset, ',');
586 for (s=0; s<num_sets; ++s) {
587 extract_token(setstr, mset, s, ',', sizeof setstr);
589 extract_token(lostr, setstr, 0, ':', sizeof lostr);
590 if (num_tokens(setstr, ':') >= 2) {
591 extract_token(histr, setstr, 1, ':', sizeof histr);
592 if (!strcmp(histr, "*")) {
593 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
597 strcpy(histr, lostr);
602 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
609 * \brief Utility function to "readline" from memory
610 * \param start Location in memory from which we are reading.
611 * \param buf the buffer to place the string in.
612 * \param maxlen Size of string buffer
613 * \return Pointer to the source memory right after we stopped reading.
615 char *memreadline(char *start, char *buf, int maxlen)
619 int len = 0; /**< tally our own length to avoid strlen() delays */
625 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
628 if ((ch == 10) || (ch == 0)) {
637 * \brief Utility function to "readline" from memory
638 * \param start Location in memory from which we are reading.
639 * \param buf the buffer to place the string in.
640 * \param maxlen Size of string buffer
641 * \param retlen the length of the returned string
642 * \return Pointer to the source memory right after we stopped reading.
644 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
648 int len = 0; /**< tally our own length to avoid strlen() delays */
654 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
657 if ((ch == 10) || (ch == 0)) {
669 * Strip a boundarized substring out of a string (for example, remove
670 * parentheses and anything inside them).
672 void stripout(char *str, char leftboundary, char rightboundary) {
677 for (a = 0; a < strlen(str); ++a) {
678 if (str[a] == leftboundary) lb = a;
679 if (str[a] == rightboundary) rb = a;
682 if ( (lb > 0) && (rb > lb) ) {
683 strcpy(&str[lb - 1], &str[rb + 1]);
686 else if ( (lb == 0) && (rb > lb) ) {
687 strcpy(str, &str[rb + 1]);
694 * Reduce a string down to a boundarized substring (for example, remove
695 * parentheses and anything outside them).
697 void stripallbut(char *str, char leftboundary, char rightboundary) {
700 for (a = 0; a < strlen(str); ++ a) {
701 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
704 for (a = 0; a < strlen(str); ++ a) {
705 if (str[a] == rightboundary) str[a] = 0;
710 char *myfgets(char *s, int size, FILE *stream) {
711 char *ret = fgets(s, size, stream);
715 nl = strchr(s, '\n');
725 * Escape a string for feeding out as a URL.
726 * Output buffer must be big enough to handle escape expansion!
728 void urlesc(char *outbuf, char *strbuf)
731 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
735 for (a = 0; a < (int)strlen(strbuf); ++a) {
737 for (b = 0; b < strlen(ec); ++b) {
738 if (strbuf[a] == ec[b])
743 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
745 sprintf(&outbuf[b], "%c", strbuf[a]);
752 * In our world, we want strcpy() to be able to work with overlapping strings.
757 char *strcpy(char *dest, const char *src) {
758 memmove(dest, src, (strlen(src) + 1) );
764 * Generate a new, globally unique UID parameter for a calendar etc. object
766 void generate_uuid(char *buf) {
769 sprintf(buf, "%lx-"F_XPID_T"-%x",
777 * bmstrcasestr() -- case-insensitive substring search
779 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
780 * The code is roughly based on the strstr() replacement from 'tin' written
783 char *bmstrcasestr(char *text, char *pattern) {
785 register unsigned char *p, *t;
786 register int i, j, *delta;
792 textlen = strlen (text);
793 patlen = strlen (pattern);
795 /* algorithm fails if pattern is empty */
796 if ((p1 = patlen) == 0)
799 /* code below fails (whenever i is unsigned) if pattern too long */
805 for (i = 0; i <= 255; i++)
807 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
808 delta[tolower(*p++)] = i;
811 * From now on, we want patlen - 1.
812 * In the loop below, p points to the end of the pattern,
813 * t points to the end of the text to be tested against the
814 * pattern, and i counts the amount of text remaining, not
815 * including the part to be tested.
818 p = (unsigned char *) pattern + p1;
819 t = (unsigned char *) text + p1;
820 i = textlen - patlen;
822 if (tolower(p[0]) == tolower(t[0])) {
823 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
824 return ((char *)t - p1);
827 j = delta[tolower(t[0])];
839 * Local replacement for controversial C library function that generates
840 * names for temporary files. Included to shut up compiler warnings.
842 void CtdlMakeTempFileName(char *name, int len) {
845 while (i++, i < 100) {
846 snprintf(name, len, "/tmp/ctdl."F_XPID_T".%04x",
850 if (!access(name, F_OK)) {