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);
323 if (t < destoffset) {
324 dest[destoffset++] = '\r';
325 dest[destoffset++] = '\n';
329 destoffset = base64_encode_block(source, sourcelen, dest, &_state);
331 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state);
333 dest[destoffset] = 0;
339 * Convert base64-encoded to binary. Returns the length of the decoded data.
340 * It will stop after reading 'length' bytes.
342 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
344 base64_decodestate _state;
346 base64_init_decodestate(&_state);
348 return base64_decode_block(source, length, dest, &_state);
353 * if we send out non ascii subjects, we encode it this way.
355 char *rfc2047encode(const char *line, long length)
357 const char *AlreadyEncoded;
360 #define UTF8_HEADER "=?UTF-8?B?"
362 /* check if we're already done */
363 AlreadyEncoded = strstr(line, "=?");
364 if ((AlreadyEncoded != NULL) &&
365 ((strstr(AlreadyEncoded, "?B?") != NULL)||
366 (strstr(AlreadyEncoded, "?Q?") != NULL)))
371 result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
372 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
373 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
374 end = strlen (result);
382 * removes double slashes from pathnames
383 * allows / disallows trailing slashes
385 void StripSlashes(char *Dir, int TrailingSlash)
391 while (!IsEmptyStr(a)) {
403 if ((TrailingSlash) && (*(b - 1) != '/')){
412 * Strip leading and trailing spaces from a string
414 size_t striplt(char *buf) {
415 char *first_nonspace = NULL;
416 char *last_nonspace = NULL;
420 if ((buf == NULL) || (*buf == '\0')) {
424 for (ptr=buf; *ptr!=0; ++ptr) {
425 if (!isspace(*ptr)) {
426 if (!first_nonspace) {
427 first_nonspace = ptr;
433 if ((!first_nonspace) || (!last_nonspace)) {
438 new_len = last_nonspace - first_nonspace + 1;
439 memmove(buf, first_nonspace, new_len);
446 * \brief check for the presence of a character within a string (returns count)
447 * \param st the string to examine
448 * \param ch the char to search
449 * \return the number of times ch appears in st
451 int haschar(const char *st, int ch)
457 while (!IsEmptyStr(ptr))
471 * Format a date/time stamp for output
472 * seconds is whether to print the seconds
474 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
476 char *teh_format = NULL;
479 localtime_r(&thetime, &tm);
482 teh_format = "%F %R:%S";
485 teh_format = "%F %R";
488 strftime(buf, n, teh_format, &tm);
494 * Determine whether the specified message number is contained within the
495 * specified sequence set.
497 int is_msg_in_sequence_set(const char *mset, long msgnum) {
500 char setstr[128], lostr[128], histr[128];
503 num_sets = num_tokens(mset, ',');
504 for (s=0; s<num_sets; ++s) {
505 extract_token(setstr, mset, s, ',', sizeof setstr);
507 extract_token(lostr, setstr, 0, ':', sizeof lostr);
508 if (num_tokens(setstr, ':') >= 2) {
509 extract_token(histr, setstr, 1, ':', sizeof histr);
510 if (!strcmp(histr, "*")) {
511 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
515 strcpy(histr, lostr);
520 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
527 * \brief Utility function to "readline" from memory
528 * \param start Location in memory from which we are reading.
529 * \param buf the buffer to place the string in.
530 * \param maxlen Size of string buffer
531 * \return Pointer to the source memory right after we stopped reading.
533 char *memreadline(char *start, char *buf, int maxlen)
537 int len = 0; /**< tally our own length to avoid strlen() delays */
543 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
546 if ((ch == 10) || (ch == 0)) {
555 * \brief Utility function to "readline" from memory
556 * \param start Location in memory from which we are reading.
557 * \param buf the buffer to place the string in.
558 * \param maxlen Size of string buffer
559 * \param retlen the length of the returned string
560 * \return Pointer to the source memory right after we stopped reading.
562 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
566 int len = 0; /**< tally our own length to avoid strlen() delays */
572 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
575 if ((ch == 10) || (ch == 0)) {
585 * \brief Utility function to "readline" from memory
586 * \param start Location in memory from which we are reading.
587 * \param buf the buffer to place the string in.
588 * \param maxlen Size of string buffer
589 * \return Pointer to the source memory right after we stopped reading.
591 const char *cmemreadline(const char *start, char *buf, int maxlen)
595 int len = 0; /**< tally our own length to avoid strlen() delays */
601 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
604 if ((ch == 10) || (ch == 0)) {
613 * \brief Utility function to "readline" from memory
614 * \param start Location in memory from which we are reading.
615 * \param buf the buffer to place the string in.
616 * \param maxlen Size of string buffer
617 * \param retlen the length of the returned string
618 * \return Pointer to the source memory right after we stopped reading.
620 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
624 int len = 0; /**< tally our own length to avoid strlen() delays */
630 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
633 if ((ch == 10) || (ch == 0)) {
645 * Strip a boundarized substring out of a string (for example, remove
646 * parentheses and anything inside them).
648 int stripout(char *str, char leftboundary, char rightboundary) {
653 for (a = 0; a < strlen(str); ++a) {
654 if (str[a] == leftboundary) lb = a;
655 if (str[a] == rightboundary) rb = a;
658 if ( (lb > 0) && (rb > lb) ) {
659 strcpy(&str[lb - 1], &str[rb + 1]);
663 else if ( (lb == 0) && (rb > lb) ) {
664 strcpy(str, &str[rb + 1]);
672 * Reduce a string down to a boundarized substring (for example, remove
673 * parentheses and anything outside them).
675 long stripallbut(char *str, char leftboundary, char rightboundary) {
681 lb = strrchr(str, leftboundary);
684 rb = strchr(str, rightboundary);
685 if ((rb != NULL) && (rb >= lb)) {
688 len = (long)rb - (long)lb;
689 memmove(str, lb, len);
695 return (long)strlen(str);
699 char *myfgets(char *s, int size, FILE *stream) {
700 char *ret = fgets(s, size, stream);
704 nl = strchr(s, '\n');
714 * \brief Escape a string for feeding out as a URL.
715 * \param outbuf the output buffer
716 * \param oblen the size of outbuf to sanitize
717 * \param strbuf the input buffer
719 void urlesc(char *outbuf, size_t oblen, char *strbuf)
721 int a, b, c, len, eclen, olen;
722 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
725 len = strlen(strbuf);
728 for (a = 0; a < len; ++a) {
730 for (b = 0; b < eclen; ++b) {
731 if (strbuf[a] == ec[b])
735 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
739 outbuf[olen ++] = strbuf[a];
747 * In our world, we want strcpy() to be able to work with overlapping strings.
752 char *strcpy(char *dest, const char *src) {
753 memmove(dest, src, (strlen(src) + 1) );
759 * Generate a new, globally unique UID parameter for a calendar etc. object
761 void generate_uuid(char *buf) {
762 static int seq = (-1);
763 static int no_kernel_uuid = 0;
765 /* If we are running on Linux then we have a kernelspace uuid generator available */
767 if (no_kernel_uuid == 0) {
769 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
772 rv = fread(buf, 36, 1, fp);
781 /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
789 seq = (seq % 0x0FFF) ;
791 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
801 * bmstrcasestr() -- case-insensitive substring search
803 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
804 * The code is roughly based on the strstr() replacement from 'tin' written
807 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
809 register unsigned char *p, *t;
810 register int i, j, *delta;
814 if (!text) return(NULL);
815 if (!pattern) return(NULL);
817 /* algorithm fails if pattern is empty */
818 if ((p1 = patlen) == 0)
821 /* code below fails (whenever i is unsigned) if pattern too long */
827 for (i = 0; i <= 255; i++)
829 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
830 delta[tolower(*p++)] = i;
833 * From now on, we want patlen - 1.
834 * In the loop below, p points to the end of the pattern,
835 * t points to the end of the text to be tested against the
836 * pattern, and i counts the amount of text remaining, not
837 * including the part to be tested.
840 p = (unsigned char *) pattern + p1;
841 t = (unsigned char *) text + p1;
842 i = textlen - patlen;
844 if (tolower(p[0]) == tolower(t[0])) {
845 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
846 return ((char *)t - p1);
849 j = delta[tolower(t[0])];
859 * bmstrcasestr() -- case-insensitive substring search
861 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
862 * The code is roughly based on the strstr() replacement from 'tin' written
865 char *bmstrcasestr(char *text, const char *pattern) {
869 if (!text) return(NULL);
870 if (!pattern) return(NULL);
872 textlen = strlen (text);
873 patlen = strlen (pattern);
875 return _bmstrcasestr_len(text, textlen, pattern, patlen);
878 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
879 return _bmstrcasestr_len(text, textlen, pattern, patlen);
886 * bmstrcasestr() -- case-insensitive substring search
888 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
889 * The code is roughly based on the strstr() replacement from 'tin' written
892 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
894 register unsigned char *p, *t;
895 register int i, j, *delta;
899 if (!text) return(NULL);
900 if (!pattern) return(NULL);
902 /* algorithm fails if pattern is empty */
903 if ((p1 = patlen) == 0)
906 /* code below fails (whenever i is unsigned) if pattern too long */
912 for (i = 0; i <= 255; i++)
914 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
915 delta[tolower(*p++)] = i;
918 * From now on, we want patlen - 1.
919 * In the loop below, p points to the end of the pattern,
920 * t points to the end of the text to be tested against the
921 * pattern, and i counts the amount of text remaining, not
922 * including the part to be tested.
925 p = (unsigned char *) pattern + p1;
926 t = (unsigned char *) text + p1;
927 i = textlen - patlen;
929 if (tolower(p[0]) == tolower(t[0])) {
930 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
931 return ((char *)t - p1);
934 j = delta[tolower(t[0])];
944 * bmstrcasestr() -- case-insensitive substring search
946 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
947 * The code is roughly based on the strstr() replacement from 'tin' written
950 const char *cbmstrcasestr(const char *text, const char *pattern) {
954 if (!text) return(NULL);
955 if (!pattern) return(NULL);
957 textlen = strlen (text);
958 patlen = strlen (pattern);
960 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
963 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
964 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
968 * Local replacement for controversial C library function that generates
969 * names for temporary files. Included to shut up compiler warnings.
971 void CtdlMakeTempFileName(char *name, int len) {
974 while (i++, i < 100) {
975 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
979 if (!access(name, F_OK)) {
988 * Determine whether the specified message number is contained within the specified set.
989 * Returns nonzero if the specified message number is in the specified message set string.
991 int is_msg_in_mset(const char *mset, long msgnum) {
994 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
998 * Now set it for all specified messages.
1000 num_sets = num_tokens(mset, ',');
1001 for (s=0; s<num_sets; ++s) {
1002 extract_token(setstr, mset, s, ',', sizeof setstr);
1004 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1005 if (num_tokens(setstr, ':') >= 2) {
1006 extract_token(histr, setstr, 1, ':', sizeof histr);
1007 if (!strcmp(histr, "*")) {
1008 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1012 strcpy(histr, lostr);
1017 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
1025 * searches for a pattern within a search string
1026 * returns position in string
1028 int pattern2(char *search, char *patn)
1032 len = strlen (search);
1033 plen = strlen (patn);
1034 for (a = 0; a < len; ++a) {
1035 if (!strncasecmp(&search[a], patn, plen))
1043 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1044 * buf - the string to modify
1045 * len - length of the string.
1047 void stripltlen(char *buf, int *len)
1050 if (*len == 0) return;
1051 while ((*len > delta) && (isspace(buf[delta]))){
1054 memmove (buf, &buf[delta], *len - delta + 1);
1057 if (*len == 0) return;
1058 while (isspace(buf[(*len) - 1])){
1059 buf[--(*len)] = '\0';
1065 * Convert all whitespace characters in a supplied string to underscores
1067 void convert_spaces_to_underscores(char *str)
1075 for (i=0; i<len; ++i) {
1076 if (isspace(str[i])) {
1084 * check whether the provided string needs to be qp encoded or not
1086 int CheckEncode(const char *pch, long len, const char *pche)
1090 while (pch < pche) {
1091 if (((unsigned char) *pch < 32) ||
1092 ((unsigned char) *pch > 126)) {