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 */
36 static byte dtable[256] = "\0"; /* base64 decode table */
37 static byte etable[256] = "\0"; /* base64 encode table */
39 char *safestrncpy(char *dest, const char *src, size_t n)
43 if (dest == NULL || src == NULL) {
44 fprintf(stderr, "safestrncpy: NULL argument\n");
50 if (dest[i] == 0) return(dest);
60 * num_tokens() - discover number of parameters/tokens in a string
62 int num_tokens(const char *source, char tok)
65 const char *ptr = source;
71 while (*ptr != '\0') {
80 //extern void cit_backtrace(void);
84 * extract_token() - a string tokenizer
85 * returns -1 if not found, or length of token.
87 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
89 const char *s; //* source * /
90 int len = 0; //* running total length of extracted string * /
91 int current_token = 0; //* token currently being processed * /
100 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
110 if (*s == separator) {
113 if ( (current_token == parmnum) &&
119 else if ((current_token > parmnum) || (len >= maxlen)) {
126 if (current_token < parmnum) {
127 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
130 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
137 * extract_token() - a string tokenizer
139 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
142 const char *s; // source
148 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
151 // Locate desired parameter
153 while (count < parmnum) {
154 // End of string, bail!
159 if (*s == separator) {
165 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
166 return -1; // Parameter not found
169 for (d = dest; *s && *s != separator && ++len<maxlen; s++, d++) {
173 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
180 * remove_token() - a tokenizer that kills, maims, and destroys
182 void remove_token(char *source, int parmnum, char separator)
184 char *d, *s; /* dest, source */
187 /* Find desired parameter */
189 while (count < parmnum) {
190 /* End of string, bail! */
195 if (*d == separator) {
200 if (!d) return; /* Parameter not found */
202 /* Find next parameter */
204 while (*s && *s != separator) {
211 else if (d == source)
225 * extract_int() - extract an int parm w/o supplying a buffer
227 int extract_int(const char *source, int parmnum)
231 extract_token(buf, source, parmnum, '|', sizeof buf);
236 * extract_long() - extract an long parm w/o supplying a buffer
238 long extract_long(const char *source, int parmnum)
242 extract_token(buf, source, parmnum, '|', sizeof buf);
248 * extract_unsigned_long() - extract an unsigned long parm
250 unsigned long extract_unsigned_long(const char *source, int parmnum)
254 extract_token(buf, source, parmnum, '|', sizeof buf);
255 return strtoul(buf, NULL, 10);
260 void CtdlInitBase64Table(void)
263 /* Fill dtable with character encodings. */
266 for (i = 0; i < 26; i++) {
268 etable[26 + i] = 'a' + i;
270 for (i = 0; i < 10; i++) {
271 etable[52 + i] = '0' + i;
277 for (i = 0; i < 255; i++) {
280 for (i = 'A'; i <= 'Z'; i++) {
281 dtable[i] = 0 + (i - 'A');
283 for (i = 'a'; i <= 'z'; i++) {
284 dtable[i] = 26 + (i - 'a');
286 for (i = '0'; i <= '9'; i++) {
287 dtable[i] = 52 + (i - '0');
296 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by John Walker.
299 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
301 int i, hiteof = FALSE;
306 /** Fill dtable with character encodings. */
308 for (i = 0; i < 26; i++) {
310 dtable[26 + i] = 'a' + i;
312 for (i = 0; i < 10; i++) {
313 dtable[52 + i] = '0' + i;
319 byte igroup[3], ogroup[4];
322 igroup[0] = igroup[1] = igroup[2] = 0;
323 for (n = 0; n < 3; n++) {
324 if (spos >= sourcelen) {
329 igroup[n] = (byte) c;
332 ogroup[0] = dtable[igroup[0] >> 2];
334 dtable[((igroup[0] & 3) << 4) |
337 dtable[((igroup[1] & 0xF) << 2) |
339 ogroup[3] = dtable[igroup[2] & 0x3F];
342 * Replace characters in output stream with "=" pad
343 * characters if fewer than three characters were
344 * read from the end of the input stream.
353 for (i = 0; i < 4; i++) {
354 dest[dpos++] = ogroup[i];
358 if ( (linebreaks) && (thisline > 70) ) {
366 if ( (linebreaks) && (thisline > 70) ) {
379 * Convert base64-encoded to binary. Returns the length of the decoded data.
380 * It will stop after reading 'length' bytes.
382 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
389 /*CONSTANTCONDITION*/
391 byte a[4], b[4], o[3];
393 for (i = 0; i < 4; i++) {
394 if (spos >= length) {
405 if (dtable[c] & 0x80) {
406 /* Ignoring errors: discard invalid character. */
411 b[i] = (byte) dtable[c];
413 o[0] = (b[0] << 2) | (b[1] >> 4);
414 o[1] = (b[1] << 4) | (b[2] >> 2);
415 o[2] = (b[2] << 6) | b[3];
416 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
417 if (i>=1) dest[dpos++] = o[0];
418 if (i>=2) dest[dpos++] = o[1];
419 if (i>=3) dest[dpos++] = o[2];
429 * if we send out non ascii subjects, we encode it this way.
431 char *rfc2047encode(char *line, long length)
433 char *AlreadyEncoded;
436 #define UTF8_HEADER "=?UTF-8?B?"
438 /* check if we're already done */
439 AlreadyEncoded = strstr(line, "=?");
440 if ((AlreadyEncoded != NULL) &&
441 ((strstr(AlreadyEncoded, "?B?") != NULL)||
442 (strstr(AlreadyEncoded, "?Q?") != NULL)))
447 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
448 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
449 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
450 end = strlen (result);
459 * Strip leading and trailing spaces from a string
461 void striplt(char *buf)
466 if (buf==NULL) return;
467 if (IsEmptyStr(buf)) return;
469 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
471 if (IsEmptyStr(buf)) return;
473 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
476 memmove(buf, &buf[a], len - a + 1);
484 * \brief check for the presence of a character within a string (returns count)
485 * \param st the string to examine
486 * \param ch the char to search
487 * \return the position inside of st
489 int haschar(const char *st,int ch)
495 while (!IsEmptyStr(ptr))
509 * Format a date/time stamp for output
510 * seconds is whether to print the seconds
512 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
516 /* Month strings for date conversions ... this needs to be localized eventually */
517 char *fmt_date_months[12] = {
518 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
522 localtime_r(&thetime, &tm);
525 if (hour == 0) hour = 12;
526 else if (hour > 12) hour = hour - 12;
529 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
530 fmt_date_months[tm.tm_mon],
536 ( (tm.tm_hour >= 12) ? "pm" : "am" )
539 snprintf(buf, n, "%s %d %4d %d:%02d%s",
540 fmt_date_months[tm.tm_mon],
545 ( (tm.tm_hour >= 12) ? "pm" : "am" )
553 * Determine whether the specified message number is contained within the
554 * specified sequence set.
556 int is_msg_in_sequence_set(char *mset, long msgnum) {
559 char setstr[128], lostr[128], histr[128];
562 num_sets = num_tokens(mset, ',');
563 for (s=0; s<num_sets; ++s) {
564 extract_token(setstr, mset, s, ',', sizeof setstr);
566 extract_token(lostr, setstr, 0, ':', sizeof lostr);
567 if (num_tokens(setstr, ':') >= 2) {
568 extract_token(histr, setstr, 1, ':', sizeof histr);
569 if (!strcmp(histr, "*")) {
570 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
574 strcpy(histr, lostr);
579 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
586 * \brief Utility function to "readline" from memory
587 * \param start Location in memory from which we are reading.
588 * \param buf the buffer to place the string in.
589 * \param maxlen Size of string buffer
590 * \return Pointer to the source memory right after we stopped reading.
592 char *memreadline(char *start, char *buf, int maxlen)
596 int len = 0; /**< tally our own length to avoid strlen() delays */
602 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
605 if ((ch == 10) || (ch == 0)) {
614 * \brief Utility function to "readline" from memory
615 * \param start Location in memory from which we are reading.
616 * \param buf the buffer to place the string in.
617 * \param maxlen Size of string buffer
618 * \param retlen the length of the returned string
619 * \return Pointer to the source memory right after we stopped reading.
621 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
625 int len = 0; /**< tally our own length to avoid strlen() delays */
631 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
634 if ((ch == 10) || (ch == 0)) {
646 * Strip a boundarized substring out of a string (for example, remove
647 * parentheses and anything inside them).
649 void stripout(char *str, char leftboundary, char rightboundary) {
654 for (a = 0; a < strlen(str); ++a) {
655 if (str[a] == leftboundary) lb = a;
656 if (str[a] == rightboundary) rb = a;
659 if ( (lb > 0) && (rb > lb) ) {
660 strcpy(&str[lb - 1], &str[rb + 1]);
663 else if ( (lb == 0) && (rb > lb) ) {
664 strcpy(str, &str[rb + 1]);
671 * Reduce a string down to a boundarized substring (for example, remove
672 * parentheses and anything outside them).
674 void stripallbut(char *str, char leftboundary, char rightboundary) {
677 for (a = 0; a < strlen(str); ++ a) {
678 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
681 for (a = 0; a < strlen(str); ++ a) {
682 if (str[a] == rightboundary) str[a] = 0;
687 char *myfgets(char *s, int size, FILE *stream) {
688 char *ret = fgets(s, size, stream);
692 nl = strchr(s, '\n');
702 * Escape a string for feeding out as a URL.
703 * Output buffer must be big enough to handle escape expansion!
705 void urlesc(char *outbuf, char *strbuf)
708 char *ec = " #&;`'|*?-~<>^()[]{}$\\";
712 for (a = 0; a < (int)strlen(strbuf); ++a) {
714 for (b = 0; b < strlen(ec); ++b) {
715 if (strbuf[a] == ec[b])
720 sprintf(&outbuf[b], "%%%02x", strbuf[a]);
722 sprintf(&outbuf[b], "%c", strbuf[a]);
729 * In our world, we want strcpy() to be able to work with overlapping strings.
734 char *strcpy(char *dest, const char *src) {
735 memmove(dest, src, (strlen(src) + 1) );
741 * Generate a new, globally unique UID parameter for a calendar etc. object
743 void generate_uuid(char *buf) {
746 sprintf(buf, "%lx-%lx-%x",
754 * bmstrcasestr() -- case-insensitive substring search
756 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
757 * The code is roughly based on the strstr() replacement from 'tin' written
760 char *bmstrcasestr(char *text, char *pattern) {
762 register unsigned char *p, *t;
763 register int i, j, *delta;
769 textlen = strlen (text);
770 patlen = strlen (pattern);
772 /* algorithm fails if pattern is empty */
773 if ((p1 = patlen) == 0)
776 /* code below fails (whenever i is unsigned) if pattern too long */
782 for (i = 0; i <= 255; i++)
784 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
785 delta[tolower(*p++)] = i;
788 * From now on, we want patlen - 1.
789 * In the loop below, p points to the end of the pattern,
790 * t points to the end of the text to be tested against the
791 * pattern, and i counts the amount of text remaining, not
792 * including the part to be tested.
795 p = (unsigned char *) pattern + p1;
796 t = (unsigned char *) text + p1;
797 i = textlen - patlen;
799 if (tolower(p[0]) == tolower(t[0])) {
800 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
801 return ((char *)t - p1);
804 j = delta[tolower(t[0])];
816 * Local replacement for controversial C library function that generates
817 * names for temporary files. Included to shut up compiler warnings.
819 void CtdlMakeTempFileName(char *name, int len) {
822 while (i++, i < 100) {
823 snprintf(name, len, "/tmp/ctdl.%4lx.%04x",
827 if (!access(name, F_OK)) {
836 * Determine whether the specified message number is contained within the specified set.
837 * Returns nonzero if the specified message number is in the specified message set string.
839 int is_msg_in_mset(char *mset, long msgnum) {
842 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
846 * Now set it for all specified messages.
848 num_sets = num_tokens(mset, ',');
849 for (s=0; s<num_sets; ++s) {
850 extract_token(setstr, mset, s, ',', sizeof setstr);
852 extract_token(lostr, setstr, 0, ':', sizeof lostr);
853 if (num_tokens(setstr, ':') >= 2) {
854 extract_token(histr, setstr, 1, ':', sizeof histr);
855 if (!strcmp(histr, "*")) {
856 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
860 strcpy(histr, lostr);
865 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
873 * \brief searches for a paternn within asearch string
874 * \param search the string to search
875 * \param patn the pattern to find in string
876 * \returns position in string
878 int pattern2(char *search, char *patn)
882 len = strlen (search);
883 plen = strlen (patn);
884 for (a = 0; a < len; ++a) {
885 if (!strncasecmp(&search[a], patn, plen))
893 * \brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
894 * \param buf the string to modify
895 * \param len length of the string.
897 void stripltlen(char *buf, int *len)
900 if (*len == 0) return;
901 while ((*len > delta) && (isspace(buf[delta]))){
904 memmove (buf, &buf[delta], *len - delta + 1);
907 if (*len == 0) return;
908 while (isspace(buf[(*len) - 1])){
909 buf[--(*len)] = '\0';