2 * A basic toolset containing miscellaneous functions for string manipluation,
3 * encoding/decoding, and a bunch of other stuff.
11 #include <sys/types.h>
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
23 # include <sys/time.h>
29 #include "libcitadel.h"
35 typedef unsigned char byte; /* Byte type */
37 /* Base64 encoding table */
38 const byte etable[256] = {
39 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
40 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103,
41 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
42 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43,
43 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
44 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
45 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
46 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51 0, 0, 0, 0, 0, 0, 0, 0, 0
54 /* Base64 decoding table */
55 const byte dtable[256] = {
56 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
57 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
58 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
59 128, 62, 128, 128, 128, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
60 128, 128, 128, 0, 128, 128, 128, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
61 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 128, 128, 128,
62 128, 128, 128, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
63 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 128, 128, 128, 128,
64 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
65 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
66 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
67 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
68 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
69 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
70 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
71 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
72 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
77 * copy a string into a buffer of a known size. abort if we exceed the limits
79 * dest the targetbuffer
80 * src the source string
83 * returns the number of characters copied if dest is big enough, -n if not.
85 int safestrncpy(char *dest, const char *src, size_t n)
89 if (dest == NULL || src == NULL) {
90 fprintf(stderr, "safestrncpy: NULL argument\n");
96 if (dest[i] == 0) return i;
106 * num_tokens() - discover number of parameters/tokens in a string
108 int num_tokens(const char *source, char tok)
111 const char *ptr = source;
113 if (source == NULL) {
117 while (*ptr != '\0') {
126 //extern void cit_backtrace(void);
130 * extract_token() - a string tokenizer
131 * returns -1 if not found, or length of token.
133 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
135 const char *s; //* source * /
136 int len = 0; //* running total length of extracted string * /
137 int current_token = 0; //* token currently being processed * /
146 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
156 if (*s == separator) {
159 if ( (current_token == parmnum) &&
165 else if ((current_token > parmnum) || (len >= maxlen)) {
172 if (current_token < parmnum) {
173 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
176 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
183 * extract_token() - a string tokenizer
185 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
188 const char *s; // source
194 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
197 // Locate desired parameter
199 while (count < parmnum) {
200 // End of string, bail!
205 if (*s == separator) {
211 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
212 return -1; // Parameter not found
215 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
219 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
226 * remove_token() - a tokenizer that kills, maims, and destroys
228 void remove_token(char *source, int parmnum, char separator)
230 char *d, *s; /* dest, source */
233 /* Find desired parameter */
235 while (count < parmnum) {
236 /* End of string, bail! */
241 if (*d == separator) {
246 if (!d) return; /* Parameter not found */
248 /* Find next parameter */
250 while (*s && *s != separator) {
257 else if (d == source)
271 * extract_int() - extract an int parm w/o supplying a buffer
273 int extract_int(const char *source, int parmnum)
277 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
284 * extract_long() - extract an long parm w/o supplying a buffer
286 long extract_long(const char *source, int parmnum)
290 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
298 * extract_unsigned_long() - extract an unsigned long parm
300 unsigned long extract_unsigned_long(const char *source, int parmnum)
304 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
305 return strtoul(buf, NULL, 10);
312 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by John Walker.
315 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
317 int i, hiteof = FALSE;
323 byte igroup[3], ogroup[4];
326 igroup[0] = igroup[1] = igroup[2] = 0;
327 for (n = 0; n < 3; n++) {
328 if (spos >= sourcelen) {
333 igroup[n] = (byte) c;
336 ogroup[0] = etable[igroup[0] >> 2];
338 etable[((igroup[0] & 3) << 4) |
341 etable[((igroup[1] & 0xF) << 2) |
343 ogroup[3] = etable[igroup[2] & 0x3F];
346 * Replace characters in output stream with "=" pad
347 * characters if fewer than three characters were
348 * read from the end of the input stream.
357 for (i = 0; i < 4; i++) {
358 dest[dpos++] = ogroup[i];
362 if ( (linebreaks) && (thisline > 70) ) {
370 if ( (linebreaks) && (thisline > 70) ) {
383 * Convert base64-encoded to binary. Returns the length of the decoded data.
384 * It will stop after reading 'length' bytes.
386 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
393 byte a[4], b[4], o[3];
395 for (i = 0; i < 4; i++) {
396 if (spos >= length) {
407 if (dtable[c] & 0x80) {
408 /* Ignoring errors: discard invalid character. */
413 b[i] = (byte) dtable[c];
415 o[0] = (b[0] << 2) | (b[1] >> 4);
416 o[1] = (b[1] << 4) | (b[2] >> 2);
417 o[2] = (b[2] << 6) | b[3];
418 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
419 if (i>=1) dest[dpos++] = o[0];
420 if (i>=2) dest[dpos++] = o[1];
421 if (i>=3) dest[dpos++] = o[2];
431 * if we send out non ascii subjects, we encode it this way.
433 char *rfc2047encode(char *line, long length)
435 char *AlreadyEncoded;
438 #define UTF8_HEADER "=?UTF-8?B?"
440 /* check if we're already done */
441 AlreadyEncoded = strstr(line, "=?");
442 if ((AlreadyEncoded != NULL) &&
443 ((strstr(AlreadyEncoded, "?B?") != NULL)||
444 (strstr(AlreadyEncoded, "?Q?") != NULL)))
449 result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
450 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
451 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
452 end = strlen (result);
460 * removes double slashes from pathnames
461 * allows / disallows trailing slashes
463 void StripSlashes(char *Dir, int TrailingSlash)
469 while (!IsEmptyStr(a)) {
481 if ((TrailingSlash) && (*(b - 1) != '/')){
490 * Strip leading and trailing spaces from a string
492 size_t striplt(char *buf) {
493 char *first_nonspace = NULL;
494 char *last_nonspace = NULL;
498 if ((buf == NULL) || (*buf == '\0')) {
502 for (ptr=buf; *ptr!=0; ++ptr) {
503 if (!isspace(*ptr)) {
504 if (!first_nonspace) {
505 first_nonspace = ptr;
511 if ((!first_nonspace) || (!last_nonspace)) {
516 new_len = last_nonspace - first_nonspace + 1;
517 memmove(buf, first_nonspace, new_len);
524 * \brief check for the presence of a character within a string (returns count)
525 * \param st the string to examine
526 * \param ch the char to search
527 * \return the number of times ch appears in st
529 int haschar(const char *st, int ch)
535 while (!IsEmptyStr(ptr))
549 * Format a date/time stamp for output
550 * seconds is whether to print the seconds
552 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
556 /* Month strings for date conversions ... this needs to be localized eventually */
557 char *fmt_date_months[12] = {
558 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
562 localtime_r(&thetime, &tm);
565 if (hour == 0) hour = 12;
566 else if (hour > 12) hour = hour - 12;
569 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
570 fmt_date_months[tm.tm_mon],
576 ( (tm.tm_hour >= 12) ? "pm" : "am" )
579 snprintf(buf, n, "%s %d %4d %d:%02d%s",
580 fmt_date_months[tm.tm_mon],
585 ( (tm.tm_hour >= 12) ? "pm" : "am" )
593 * Determine whether the specified message number is contained within the
594 * specified sequence set.
596 int is_msg_in_sequence_set(const char *mset, long msgnum) {
599 char setstr[128], lostr[128], histr[128];
602 num_sets = num_tokens(mset, ',');
603 for (s=0; s<num_sets; ++s) {
604 extract_token(setstr, mset, s, ',', sizeof setstr);
606 extract_token(lostr, setstr, 0, ':', sizeof lostr);
607 if (num_tokens(setstr, ':') >= 2) {
608 extract_token(histr, setstr, 1, ':', sizeof histr);
609 if (!strcmp(histr, "*")) {
610 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
614 strcpy(histr, lostr);
619 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
626 * \brief Utility function to "readline" from memory
627 * \param start Location in memory from which we are reading.
628 * \param buf the buffer to place the string in.
629 * \param maxlen Size of string buffer
630 * \return Pointer to the source memory right after we stopped reading.
632 char *memreadline(char *start, char *buf, int maxlen)
636 int len = 0; /**< tally our own length to avoid strlen() delays */
642 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
645 if ((ch == 10) || (ch == 0)) {
654 * \brief Utility function to "readline" from memory
655 * \param start Location in memory from which we are reading.
656 * \param buf the buffer to place the string in.
657 * \param maxlen Size of string buffer
658 * \param retlen the length of the returned string
659 * \return Pointer to the source memory right after we stopped reading.
661 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
665 int len = 0; /**< tally our own length to avoid strlen() delays */
671 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
674 if ((ch == 10) || (ch == 0)) {
684 * \brief Utility function to "readline" from memory
685 * \param start Location in memory from which we are reading.
686 * \param buf the buffer to place the string in.
687 * \param maxlen Size of string buffer
688 * \return Pointer to the source memory right after we stopped reading.
690 const char *cmemreadline(const char *start, char *buf, int maxlen)
694 int len = 0; /**< tally our own length to avoid strlen() delays */
700 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
703 if ((ch == 10) || (ch == 0)) {
712 * \brief Utility function to "readline" from memory
713 * \param start Location in memory from which we are reading.
714 * \param buf the buffer to place the string in.
715 * \param maxlen Size of string buffer
716 * \param retlen the length of the returned string
717 * \return Pointer to the source memory right after we stopped reading.
719 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
723 int len = 0; /**< tally our own length to avoid strlen() delays */
729 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
732 if ((ch == 10) || (ch == 0)) {
744 * Strip a boundarized substring out of a string (for example, remove
745 * parentheses and anything inside them).
747 int stripout(char *str, char leftboundary, char rightboundary) {
752 for (a = 0; a < strlen(str); ++a) {
753 if (str[a] == leftboundary) lb = a;
754 if (str[a] == rightboundary) rb = a;
757 if ( (lb > 0) && (rb > lb) ) {
758 strcpy(&str[lb - 1], &str[rb + 1]);
762 else if ( (lb == 0) && (rb > lb) ) {
763 strcpy(str, &str[rb + 1]);
771 * Reduce a string down to a boundarized substring (for example, remove
772 * parentheses and anything outside them).
774 long stripallbut(char *str, char leftboundary, char rightboundary) {
780 lb = strrchr(str, leftboundary);
783 rb = strchr(str, rightboundary);
784 if ((rb != NULL) && (rb >= lb)) {
787 len = (long)rb - (long)lb;
788 memmove(str, lb, len);
794 return (long)strlen(str);
798 char *myfgets(char *s, int size, FILE *stream) {
799 char *ret = fgets(s, size, stream);
803 nl = strchr(s, '\n');
813 * \brief Escape a string for feeding out as a URL.
814 * \param outbuf the output buffer
815 * \param oblen the size of outbuf to sanitize
816 * \param strbuf the input buffer
818 void urlesc(char *outbuf, size_t oblen, char *strbuf)
820 int a, b, c, len, eclen, olen;
821 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
824 len = strlen(strbuf);
827 for (a = 0; a < len; ++a) {
829 for (b = 0; b < eclen; ++b) {
830 if (strbuf[a] == ec[b])
834 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
838 outbuf[olen ++] = strbuf[a];
846 * In our world, we want strcpy() to be able to work with overlapping strings.
851 char *strcpy(char *dest, const char *src) {
852 memmove(dest, src, (strlen(src) + 1) );
858 * Generate a new, globally unique UID parameter for a calendar etc. object
860 void generate_uuid(char *buf) {
861 static int seq = (-1);
867 seq = (seq % 0x0FFF) ;
869 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
879 * bmstrcasestr() -- case-insensitive substring search
881 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
882 * The code is roughly based on the strstr() replacement from 'tin' written
885 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
887 register unsigned char *p, *t;
888 register int i, j, *delta;
892 if (!text) return(NULL);
893 if (!pattern) return(NULL);
895 /* algorithm fails if pattern is empty */
896 if ((p1 = patlen) == 0)
899 /* code below fails (whenever i is unsigned) if pattern too long */
905 for (i = 0; i <= 255; i++)
907 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
908 delta[tolower(*p++)] = i;
911 * From now on, we want patlen - 1.
912 * In the loop below, p points to the end of the pattern,
913 * t points to the end of the text to be tested against the
914 * pattern, and i counts the amount of text remaining, not
915 * including the part to be tested.
918 p = (unsigned char *) pattern + p1;
919 t = (unsigned char *) text + p1;
920 i = textlen - patlen;
922 if (tolower(p[0]) == tolower(t[0])) {
923 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
924 return ((char *)t - p1);
927 j = delta[tolower(t[0])];
937 * bmstrcasestr() -- case-insensitive substring search
939 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
940 * The code is roughly based on the strstr() replacement from 'tin' written
943 char *bmstrcasestr(char *text, const char *pattern) {
947 if (!text) return(NULL);
948 if (!pattern) return(NULL);
950 textlen = strlen (text);
951 patlen = strlen (pattern);
953 return _bmstrcasestr_len(text, textlen, pattern, patlen);
956 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
957 return _bmstrcasestr_len(text, textlen, pattern, patlen);
964 * bmstrcasestr() -- case-insensitive substring search
966 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
967 * The code is roughly based on the strstr() replacement from 'tin' written
970 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
972 register unsigned char *p, *t;
973 register int i, j, *delta;
977 if (!text) return(NULL);
978 if (!pattern) return(NULL);
980 /* algorithm fails if pattern is empty */
981 if ((p1 = patlen) == 0)
984 /* code below fails (whenever i is unsigned) if pattern too long */
990 for (i = 0; i <= 255; i++)
992 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
993 delta[tolower(*p++)] = i;
996 * From now on, we want patlen - 1.
997 * In the loop below, p points to the end of the pattern,
998 * t points to the end of the text to be tested against the
999 * pattern, and i counts the amount of text remaining, not
1000 * including the part to be tested.
1003 p = (unsigned char *) pattern + p1;
1004 t = (unsigned char *) text + p1;
1005 i = textlen - patlen;
1007 if (tolower(p[0]) == tolower(t[0])) {
1008 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
1009 return ((char *)t - p1);
1012 j = delta[tolower(t[0])];
1022 * bmstrcasestr() -- case-insensitive substring search
1024 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
1025 * The code is roughly based on the strstr() replacement from 'tin' written
1028 const char *cbmstrcasestr(const char *text, const char *pattern) {
1032 if (!text) return(NULL);
1033 if (!pattern) return(NULL);
1035 textlen = strlen (text);
1036 patlen = strlen (pattern);
1038 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
1041 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
1042 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
1046 * Local replacement for controversial C library function that generates
1047 * names for temporary files. Included to shut up compiler warnings.
1049 void CtdlMakeTempFileName(char *name, int len) {
1052 while (i++, i < 100) {
1053 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
1057 if (!access(name, F_OK)) {
1066 * Determine whether the specified message number is contained within the specified set.
1067 * Returns nonzero if the specified message number is in the specified message set string.
1069 int is_msg_in_mset(const char *mset, long msgnum) {
1072 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
1076 * Now set it for all specified messages.
1078 num_sets = num_tokens(mset, ',');
1079 for (s=0; s<num_sets; ++s) {
1080 extract_token(setstr, mset, s, ',', sizeof setstr);
1082 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1083 if (num_tokens(setstr, ':') >= 2) {
1084 extract_token(histr, setstr, 1, ':', sizeof histr);
1085 if (!strcmp(histr, "*")) {
1086 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1090 strcpy(histr, lostr);
1095 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
1103 * searches for a pattern within a search string
1104 * returns position in string
1106 int pattern2(char *search, char *patn)
1110 len = strlen (search);
1111 plen = strlen (patn);
1112 for (a = 0; a < len; ++a) {
1113 if (!strncasecmp(&search[a], patn, plen))
1121 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1122 * buf - the string to modify
1123 * len - length of the string.
1125 void stripltlen(char *buf, int *len)
1128 if (*len == 0) return;
1129 while ((*len > delta) && (isspace(buf[delta]))){
1132 memmove (buf, &buf[delta], *len - delta + 1);
1135 if (*len == 0) return;
1136 while (isspace(buf[(*len) - 1])){
1137 buf[--(*len)] = '\0';
1143 * Convert all whitespace characters in a supplied string to underscores
1145 void convert_spaces_to_underscores(char *str)
1153 for (i=0; i<len; ++i) {
1154 if (isspace(str[i])) {
1162 * check whether the provided string needs to be qp encoded or not
1164 int CheckEncode(const char *pch, long len, const char *pche)
1168 while (pch < pche) {
1169 if (((unsigned char) *pch < 32) ||
1170 ((unsigned char) *pch > 126)) {