2 * A basic toolset containing miscellaneous functions for string manipluation,
3 * encoding/decoding, and a bunch of other stuff.
5 * Copyright (c) 1987-2011 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #include <sys/types.h>
33 #include "b64/cencode.h"
34 #include "b64/cdecode.h"
36 #if TIME_WITH_SYS_TIME
37 # include <sys/time.h>
41 # include <sys/time.h>
47 #include "libcitadel.h"
53 typedef unsigned char byte; /* Byte type */
56 * copy a string into a buffer of a known size. abort if we exceed the limits
58 * dest the targetbuffer
59 * src the source string
62 * returns the number of characters copied if dest is big enough, -n if not.
64 int safestrncpy(char *dest, const char *src, size_t n)
68 if (dest == NULL || src == NULL) {
69 fprintf(stderr, "safestrncpy: NULL argument\n");
75 if (dest[i] == 0) return i;
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 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
263 * extract_long() - extract an long parm w/o supplying a buffer
265 long extract_long(const char *source, int parmnum)
269 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
277 * extract_unsigned_long() - extract an unsigned long parm
279 unsigned long extract_unsigned_long(const char *source, int parmnum)
283 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
284 return strtoul(buf, NULL, 10);
289 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
291 // linebreaks at 70 are ugly for base64, since 3 bytes in makes 4 bytes out
292 int breaklength = 68;
293 int readlength = 3 * breaklength / 4;
300 base64_encodestate _state;
302 base64_init_encodestate(&_state);
305 sourceremaining = sourcelen;
309 while (sourceremaining > 0) {
310 destoffset += base64_encode_block(
311 &(source[sourceoffset]),
312 (readlength > sourceremaining ? sourceremaining : readlength),
315 sourceoffset += readlength;
316 sourceremaining -= readlength;
317 dest[destoffset++] = '\r';
318 dest[destoffset++] = '\n';
322 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state);
325 destoffset = base64_encode_block(source, sourcelen, dest, &_state);
327 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state);
329 dest[destoffset] = 0;
335 * Convert base64-encoded to binary. Returns the length of the decoded data.
336 * It will stop after reading 'length' bytes.
338 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
340 base64_decodestate _state;
343 base64_init_decodestate(&_state);
345 len = base64_decode_block(source, length, dest, &_state);
352 * if we send out non ascii subjects, we encode it this way.
354 char *rfc2047encode(const char *line, long length)
356 const char *AlreadyEncoded;
359 #define UTF8_HEADER "=?UTF-8?B?"
361 /* check if we're already done */
362 AlreadyEncoded = strstr(line, "=?");
363 if ((AlreadyEncoded != NULL) &&
364 ((strstr(AlreadyEncoded, "?B?") != NULL)||
365 (strstr(AlreadyEncoded, "?Q?") != NULL)))
370 result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
371 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
372 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
373 end = strlen (result);
381 * removes double slashes from pathnames
382 * allows / disallows trailing slashes
384 void StripSlashes(char *Dir, int TrailingSlash)
390 while (!IsEmptyStr(a)) {
402 if ((TrailingSlash) && (*(b - 1) != '/')){
411 * Strip leading and trailing spaces from a string
413 size_t striplt(char *buf) {
414 char *first_nonspace = NULL;
415 char *last_nonspace = NULL;
419 if ((buf == NULL) || (*buf == '\0')) {
423 for (ptr=buf; *ptr!=0; ++ptr) {
424 if (!isspace(*ptr)) {
425 if (!first_nonspace) {
426 first_nonspace = ptr;
432 if ((!first_nonspace) || (!last_nonspace)) {
437 new_len = last_nonspace - first_nonspace + 1;
438 memmove(buf, first_nonspace, new_len);
445 * \brief check for the presence of a character within a string (returns count)
446 * \param st the string to examine
447 * \param ch the char to search
448 * \return the number of times ch appears in st
450 int haschar(const char *st, int ch)
456 while (!IsEmptyStr(ptr))
470 * Format a date/time stamp for output
471 * seconds is whether to print the seconds
473 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
475 char *teh_format = NULL;
478 localtime_r(&thetime, &tm);
481 teh_format = "%F %R:%S";
484 teh_format = "%F %R";
487 strftime(buf, n, teh_format, &tm);
493 * Determine whether the specified message number is contained within the
494 * specified sequence set.
496 int is_msg_in_sequence_set(const char *mset, long msgnum) {
499 char setstr[128], lostr[128], histr[128];
502 num_sets = num_tokens(mset, ',');
503 for (s=0; s<num_sets; ++s) {
504 extract_token(setstr, mset, s, ',', sizeof setstr);
506 extract_token(lostr, setstr, 0, ':', sizeof lostr);
507 if (num_tokens(setstr, ':') >= 2) {
508 extract_token(histr, setstr, 1, ':', sizeof histr);
509 if (!strcmp(histr, "*")) {
510 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
514 strcpy(histr, lostr);
519 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
526 * \brief Utility function to "readline" from memory
527 * \param start Location in memory from which we are reading.
528 * \param buf the buffer to place the string in.
529 * \param maxlen Size of string buffer
530 * \return Pointer to the source memory right after we stopped reading.
532 char *memreadline(char *start, char *buf, int maxlen)
536 int len = 0; /**< tally our own length to avoid strlen() delays */
542 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
545 if ((ch == 10) || (ch == 0)) {
554 * \brief Utility function to "readline" from memory
555 * \param start Location in memory from which we are reading.
556 * \param buf the buffer to place the string in.
557 * \param maxlen Size of string buffer
558 * \param retlen the length of the returned string
559 * \return Pointer to the source memory right after we stopped reading.
561 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
565 int len = 0; /**< tally our own length to avoid strlen() delays */
571 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
574 if ((ch == 10) || (ch == 0)) {
584 * \brief Utility function to "readline" from memory
585 * \param start Location in memory from which we are reading.
586 * \param buf the buffer to place the string in.
587 * \param maxlen Size of string buffer
588 * \return Pointer to the source memory right after we stopped reading.
590 const char *cmemreadline(const char *start, char *buf, int maxlen)
594 int len = 0; /**< tally our own length to avoid strlen() delays */
600 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
603 if ((ch == 10) || (ch == 0)) {
612 * \brief Utility function to "readline" from memory
613 * \param start Location in memory from which we are reading.
614 * \param buf the buffer to place the string in.
615 * \param maxlen Size of string buffer
616 * \param retlen the length of the returned string
617 * \return Pointer to the source memory right after we stopped reading.
619 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
623 int len = 0; /**< tally our own length to avoid strlen() delays */
629 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
632 if ((ch == 10) || (ch == 0)) {
644 * Strip a boundarized substring out of a string (for example, remove
645 * parentheses and anything inside them).
647 int stripout(char *str, char leftboundary, char rightboundary) {
652 for (a = 0; a < strlen(str); ++a) {
653 if (str[a] == leftboundary) lb = a;
654 if (str[a] == rightboundary) rb = a;
657 if ( (lb > 0) && (rb > lb) ) {
658 strcpy(&str[lb - 1], &str[rb + 1]);
662 else if ( (lb == 0) && (rb > lb) ) {
663 strcpy(str, &str[rb + 1]);
671 * Reduce a string down to a boundarized substring (for example, remove
672 * parentheses and anything outside them).
674 long stripallbut(char *str, char leftboundary, char rightboundary) {
680 lb = strrchr(str, leftboundary);
683 rb = strchr(str, rightboundary);
684 if ((rb != NULL) && (rb >= lb)) {
687 len = (long)rb - (long)lb;
688 memmove(str, lb, len);
694 return (long)strlen(str);
698 char *myfgets(char *s, int size, FILE *stream) {
699 char *ret = fgets(s, size, stream);
703 nl = strchr(s, '\n');
713 * \brief Escape a string for feeding out as a URL.
714 * \param outbuf the output buffer
715 * \param oblen the size of outbuf to sanitize
716 * \param strbuf the input buffer
718 void urlesc(char *outbuf, size_t oblen, char *strbuf)
720 int a, b, c, len, eclen, olen;
721 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
724 len = strlen(strbuf);
727 for (a = 0; a < len; ++a) {
729 for (b = 0; b < eclen; ++b) {
730 if (strbuf[a] == ec[b])
734 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
738 outbuf[olen ++] = strbuf[a];
746 * In our world, we want strcpy() to be able to work with overlapping strings.
751 char *strcpy(char *dest, const char *src) {
752 memmove(dest, src, (strlen(src) + 1) );
758 * Generate a new, globally unique UID parameter for a calendar etc. object
760 void generate_uuid(char *buf) {
761 static int seq = (-1);
762 static int no_kernel_uuid = 0;
764 /* If we are running on Linux then we have a kernelspace uuid generator available */
766 if (no_kernel_uuid == 0) {
768 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
771 rv = fread(buf, 36, 1, fp);
780 /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
788 seq = (seq % 0x0FFF) ;
790 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
800 * bmstrcasestr() -- case-insensitive substring search
802 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
803 * The code is roughly based on the strstr() replacement from 'tin' written
806 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
808 register unsigned char *p, *t;
809 register int i, j, *delta;
813 if (!text) return(NULL);
814 if (!pattern) return(NULL);
816 /* algorithm fails if pattern is empty */
817 if ((p1 = patlen) == 0)
820 /* code below fails (whenever i is unsigned) if pattern too long */
826 for (i = 0; i <= 255; i++)
828 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
829 delta[tolower(*p++)] = i;
832 * From now on, we want patlen - 1.
833 * In the loop below, p points to the end of the pattern,
834 * t points to the end of the text to be tested against the
835 * pattern, and i counts the amount of text remaining, not
836 * including the part to be tested.
839 p = (unsigned char *) pattern + p1;
840 t = (unsigned char *) text + p1;
841 i = textlen - patlen;
843 if (tolower(p[0]) == tolower(t[0])) {
844 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
845 return ((char *)t - p1);
848 j = delta[tolower(t[0])];
858 * bmstrcasestr() -- case-insensitive substring search
860 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
861 * The code is roughly based on the strstr() replacement from 'tin' written
864 char *bmstrcasestr(char *text, const char *pattern) {
868 if (!text) return(NULL);
869 if (!pattern) return(NULL);
871 textlen = strlen (text);
872 patlen = strlen (pattern);
874 return _bmstrcasestr_len(text, textlen, pattern, patlen);
877 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
878 return _bmstrcasestr_len(text, textlen, pattern, patlen);
885 * bmstrcasestr() -- case-insensitive substring search
887 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
888 * The code is roughly based on the strstr() replacement from 'tin' written
891 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
893 register unsigned char *p, *t;
894 register int i, j, *delta;
898 if (!text) return(NULL);
899 if (!pattern) return(NULL);
901 /* algorithm fails if pattern is empty */
902 if ((p1 = patlen) == 0)
905 /* code below fails (whenever i is unsigned) if pattern too long */
911 for (i = 0; i <= 255; i++)
913 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
914 delta[tolower(*p++)] = i;
917 * From now on, we want patlen - 1.
918 * In the loop below, p points to the end of the pattern,
919 * t points to the end of the text to be tested against the
920 * pattern, and i counts the amount of text remaining, not
921 * including the part to be tested.
924 p = (unsigned char *) pattern + p1;
925 t = (unsigned char *) text + p1;
926 i = textlen - patlen;
928 if (tolower(p[0]) == tolower(t[0])) {
929 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
930 return ((char *)t - p1);
933 j = delta[tolower(t[0])];
943 * bmstrcasestr() -- case-insensitive substring search
945 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
946 * The code is roughly based on the strstr() replacement from 'tin' written
949 const char *cbmstrcasestr(const char *text, const char *pattern) {
953 if (!text) return(NULL);
954 if (!pattern) return(NULL);
956 textlen = strlen (text);
957 patlen = strlen (pattern);
959 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
962 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
963 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
967 * Local replacement for controversial C library function that generates
968 * names for temporary files. Included to shut up compiler warnings.
970 void CtdlMakeTempFileName(char *name, int len) {
973 while (i++, i < 100) {
974 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
978 if (!access(name, F_OK)) {
987 * Determine whether the specified message number is contained within the specified set.
988 * Returns nonzero if the specified message number is in the specified message set string.
990 int is_msg_in_mset(const char *mset, long msgnum) {
993 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
997 * Now set it for all specified messages.
999 num_sets = num_tokens(mset, ',');
1000 for (s=0; s<num_sets; ++s) {
1001 extract_token(setstr, mset, s, ',', sizeof setstr);
1003 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1004 if (num_tokens(setstr, ':') >= 2) {
1005 extract_token(histr, setstr, 1, ':', sizeof histr);
1006 if (!strcmp(histr, "*")) {
1007 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1011 strcpy(histr, lostr);
1016 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
1024 * searches for a pattern within a search string
1025 * returns position in string
1027 int pattern2(char *search, char *patn)
1031 len = strlen (search);
1032 plen = strlen (patn);
1033 for (a = 0; a < len; ++a) {
1034 if (!strncasecmp(&search[a], patn, plen))
1042 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1043 * buf - the string to modify
1044 * len - length of the string.
1046 void stripltlen(char *buf, int *len)
1049 if (*len == 0) return;
1050 while ((*len > delta) && (isspace(buf[delta]))){
1053 memmove (buf, &buf[delta], *len - delta + 1);
1056 if (*len == 0) return;
1057 while (isspace(buf[(*len) - 1])){
1058 buf[--(*len)] = '\0';
1064 * Convert all whitespace characters in a supplied string to underscores
1066 void convert_spaces_to_underscores(char *str)
1074 for (i=0; i<len; ++i) {
1075 if (isspace(str[i])) {
1083 * check whether the provided string needs to be qp encoded or not
1085 int CheckEncode(const char *pch, long len, const char *pche)
1089 while (pch < pche) {
1090 if (((unsigned char) *pch < 32) ||
1091 ((unsigned char) *pch > 126)) {