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 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
238 * extract_long() - extract an long parm w/o supplying a buffer
240 long extract_long(const char *source, int parmnum)
244 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
252 * extract_unsigned_long() - extract an unsigned long parm
254 unsigned long extract_unsigned_long(const char *source, int parmnum)
258 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
259 return strtoul(buf, NULL, 10);
266 void CtdlInitBase64Table(void)
269 /* Fill dtable with character encodings. */
272 for (i = 0; i < 26; i++) {
274 etable[26 + i] = 'a' + i;
276 for (i = 0; i < 10; i++) {
277 etable[52 + i] = '0' + i;
283 for (i = 0; i < 255; i++) {
286 for (i = 'A'; i <= 'Z'; i++) {
287 dtable[i] = 0 + (i - 'A');
289 for (i = 'a'; i <= 'z'; i++) {
290 dtable[i] = 26 + (i - 'a');
292 for (i = '0'; i <= '9'; i++) {
293 dtable[i] = 52 + (i - '0');
302 * CtdlDecodeBase64() and CtdlEncodeBase64() are adaptations of code by John Walker.
305 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
307 int i, hiteof = FALSE;
313 byte igroup[3], ogroup[4];
316 igroup[0] = igroup[1] = igroup[2] = 0;
317 for (n = 0; n < 3; n++) {
318 if (spos >= sourcelen) {
323 igroup[n] = (byte) c;
326 ogroup[0] = etable[igroup[0] >> 2];
328 etable[((igroup[0] & 3) << 4) |
331 etable[((igroup[1] & 0xF) << 2) |
333 ogroup[3] = etable[igroup[2] & 0x3F];
336 * Replace characters in output stream with "=" pad
337 * characters if fewer than three characters were
338 * read from the end of the input stream.
347 for (i = 0; i < 4; i++) {
348 dest[dpos++] = ogroup[i];
352 if ( (linebreaks) && (thisline > 70) ) {
360 if ( (linebreaks) && (thisline > 70) ) {
373 * Convert base64-encoded to binary. Returns the length of the decoded data.
374 * It will stop after reading 'length' bytes.
376 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
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];
421 * if we send out non ascii subjects, we encode it this way.
423 char *rfc2047encode(char *line, long length)
425 char *AlreadyEncoded;
428 #define UTF8_HEADER "=?UTF-8?B?"
430 /* check if we're already done */
431 AlreadyEncoded = strstr(line, "=?");
432 if ((AlreadyEncoded != NULL) &&
433 ((strstr(AlreadyEncoded, "?B?") != NULL)||
434 (strstr(AlreadyEncoded, "?Q?") != NULL)))
439 result = (char*) malloc(strlen(UTF8_HEADER) + 4 + length * 2);
440 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
441 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
442 end = strlen (result);
451 * Strip leading and trailing spaces from a string
453 void striplt(char *buf)
458 if (buf==NULL) return;
459 if (IsEmptyStr(buf)) return;
461 while ((!IsEmptyStr(buf)) && (isspace(buf[len - 1])))
463 if (IsEmptyStr(buf)) return;
465 while ((!IsEmptyStr(buf)) && (isspace(buf[a])))
468 memmove(buf, &buf[a], len - a + 1);
476 * \brief check for the presence of a character within a string (returns count)
477 * \param st the string to examine
478 * \param ch the char to search
479 * \return the position inside of st
481 int haschar(const char *st,int ch)
487 while (!IsEmptyStr(ptr))
501 * Format a date/time stamp for output
502 * seconds is whether to print the seconds
504 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
508 /* Month strings for date conversions ... this needs to be localized eventually */
509 char *fmt_date_months[12] = {
510 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
514 localtime_r(&thetime, &tm);
517 if (hour == 0) hour = 12;
518 else if (hour > 12) hour = hour - 12;
521 snprintf(buf, n, "%s %d %4d %d:%02d:%02d%s",
522 fmt_date_months[tm.tm_mon],
528 ( (tm.tm_hour >= 12) ? "pm" : "am" )
531 snprintf(buf, n, "%s %d %4d %d:%02d%s",
532 fmt_date_months[tm.tm_mon],
537 ( (tm.tm_hour >= 12) ? "pm" : "am" )
545 * Determine whether the specified message number is contained within the
546 * specified sequence set.
548 int is_msg_in_sequence_set(char *mset, long msgnum) {
551 char setstr[128], lostr[128], histr[128];
554 num_sets = num_tokens(mset, ',');
555 for (s=0; s<num_sets; ++s) {
556 extract_token(setstr, mset, s, ',', sizeof setstr);
558 extract_token(lostr, setstr, 0, ':', sizeof lostr);
559 if (num_tokens(setstr, ':') >= 2) {
560 extract_token(histr, setstr, 1, ':', sizeof histr);
561 if (!strcmp(histr, "*")) {
562 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
566 strcpy(histr, lostr);
571 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
578 * \brief Utility function to "readline" from memory
579 * \param start Location in memory from which we are reading.
580 * \param buf the buffer to place the string in.
581 * \param maxlen Size of string buffer
582 * \return Pointer to the source memory right after we stopped reading.
584 char *memreadline(char *start, char *buf, int maxlen)
588 int len = 0; /**< tally our own length to avoid strlen() delays */
594 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
597 if ((ch == 10) || (ch == 0)) {
606 * \brief Utility function to "readline" from memory
607 * \param start Location in memory from which we are reading.
608 * \param buf the buffer to place the string in.
609 * \param maxlen Size of string buffer
610 * \param retlen the length of the returned string
611 * \return Pointer to the source memory right after we stopped reading.
613 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
617 int len = 0; /**< tally our own length to avoid strlen() delays */
623 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
626 if ((ch == 10) || (ch == 0)) {
638 * Strip a boundarized substring out of a string (for example, remove
639 * parentheses and anything inside them).
641 void stripout(char *str, char leftboundary, char rightboundary) {
646 for (a = 0; a < strlen(str); ++a) {
647 if (str[a] == leftboundary) lb = a;
648 if (str[a] == rightboundary) rb = a;
651 if ( (lb > 0) && (rb > lb) ) {
652 strcpy(&str[lb - 1], &str[rb + 1]);
655 else if ( (lb == 0) && (rb > lb) ) {
656 strcpy(str, &str[rb + 1]);
663 * Reduce a string down to a boundarized substring (for example, remove
664 * parentheses and anything outside them).
666 void stripallbut(char *str, char leftboundary, char rightboundary) {
669 for (a = 0; a < strlen(str); ++ a) {
670 if (str[a] == leftboundary) strcpy(str, &str[a+1]);
673 for (a = 0; a < strlen(str); ++ a) {
674 if (str[a] == rightboundary) str[a] = 0;
679 char *myfgets(char *s, int size, FILE *stream) {
680 char *ret = fgets(s, size, stream);
684 nl = strchr(s, '\n');
694 * \brief Escape a string for feeding out as a URL.
695 * \param outbuf the output buffer
696 * \param oblen the size of outbuf to sanitize
697 * \param strbuf the input buffer
699 void urlesc(char *outbuf, size_t oblen, char *strbuf)
701 int a, b, c, len, eclen, olen;
702 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
705 len = strlen(strbuf);
708 for (a = 0; a < len; ++a) {
710 for (b = 0; b < eclen; ++b) {
711 if (strbuf[a] == ec[b])
715 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
719 outbuf[olen ++] = strbuf[a];
727 * In our world, we want strcpy() to be able to work with overlapping strings.
732 char *strcpy(char *dest, const char *src) {
733 memmove(dest, src, (strlen(src) + 1) );
739 * Generate a new, globally unique UID parameter for a calendar etc. object
741 void generate_uuid(char *buf) {
744 sprintf(buf, "%lx-%lx-%x",
752 * bmstrcasestr() -- case-insensitive substring search
754 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
755 * The code is roughly based on the strstr() replacement from 'tin' written
758 char *bmstrcasestr(char *text, char *pattern) {
760 register unsigned char *p, *t;
761 register int i, j, *delta;
767 textlen = strlen (text);
768 patlen = strlen (pattern);
770 /* algorithm fails if pattern is empty */
771 if ((p1 = patlen) == 0)
774 /* code below fails (whenever i is unsigned) if pattern too long */
780 for (i = 0; i <= 255; i++)
782 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
783 delta[tolower(*p++)] = i;
786 * From now on, we want patlen - 1.
787 * In the loop below, p points to the end of the pattern,
788 * t points to the end of the text to be tested against the
789 * pattern, and i counts the amount of text remaining, not
790 * including the part to be tested.
793 p = (unsigned char *) pattern + p1;
794 t = (unsigned char *) text + p1;
795 i = textlen - patlen;
797 if (tolower(p[0]) == tolower(t[0])) {
798 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
799 return ((char *)t - p1);
802 j = delta[tolower(t[0])];
814 * Local replacement for controversial C library function that generates
815 * names for temporary files. Included to shut up compiler warnings.
817 void CtdlMakeTempFileName(char *name, int len) {
820 while (i++, i < 100) {
821 snprintf(name, len, "/tmp/ctdl.%4lx.%04x",
825 if (!access(name, F_OK)) {
834 * Determine whether the specified message number is contained within the specified set.
835 * Returns nonzero if the specified message number is in the specified message set string.
837 int is_msg_in_mset(char *mset, long msgnum) {
840 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
844 * Now set it for all specified messages.
846 num_sets = num_tokens(mset, ',');
847 for (s=0; s<num_sets; ++s) {
848 extract_token(setstr, mset, s, ',', sizeof setstr);
850 extract_token(lostr, setstr, 0, ':', sizeof lostr);
851 if (num_tokens(setstr, ':') >= 2) {
852 extract_token(histr, setstr, 1, ':', sizeof histr);
853 if (!strcmp(histr, "*")) {
854 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
858 strcpy(histr, lostr);
863 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
871 * \brief searches for a paternn within asearch string
872 * \param search the string to search
873 * \param patn the pattern to find in string
874 * \returns position in string
876 int pattern2(char *search, char *patn)
880 len = strlen (search);
881 plen = strlen (patn);
882 for (a = 0; a < len; ++a) {
883 if (!strncasecmp(&search[a], patn, plen))
891 * \brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
892 * \param buf the string to modify
893 * \param len length of the string.
895 void stripltlen(char *buf, int *len)
898 if (*len == 0) return;
899 while ((*len > delta) && (isspace(buf[delta]))){
902 memmove (buf, &buf[delta], *len - delta + 1);
905 if (*len == 0) return;
906 while (isspace(buf[(*len) - 1])){
907 buf[--(*len)] = '\0';