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;
299 base64_encodestate _state;
301 base64_init_encodestate(&_state);
304 sourceremaining = sourcelen;
308 while (sourceremaining > 0) {
309 destoffset += base64_encode_block(
310 &(source[sourceoffset]),
311 (readlength > sourceremaining ? sourceremaining : readlength),
314 sourceoffset += readlength;
315 sourceremaining -= readlength;
316 dest[destoffset++] = '\r';
317 dest[destoffset++] = '\n';
320 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state);
323 destoffset = base64_encode_block(source, sourcelen, dest, &_state);
325 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state);
327 dest[destoffset] = 0;
333 * Convert base64-encoded to binary. Returns the length of the decoded data.
334 * It will stop after reading 'length' bytes.
336 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
338 base64_decodestate _state;
341 base64_init_decodestate(&_state);
343 len = base64_decode_block(source, length, dest, &_state);
350 * if we send out non ascii subjects, we encode it this way.
352 char *rfc2047encode(const char *line, long length)
354 const char *AlreadyEncoded;
357 #define UTF8_HEADER "=?UTF-8?B?"
359 /* check if we're already done */
360 AlreadyEncoded = strstr(line, "=?");
361 if ((AlreadyEncoded != NULL) &&
362 ((strstr(AlreadyEncoded, "?B?") != NULL)||
363 (strstr(AlreadyEncoded, "?Q?") != NULL)))
368 result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
369 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
370 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
371 end = strlen (result);
379 * removes double slashes from pathnames
380 * allows / disallows trailing slashes
382 void StripSlashes(char *Dir, int TrailingSlash)
388 while (!IsEmptyStr(a)) {
400 if ((TrailingSlash) && (*(b - 1) != '/')){
409 * Strip leading and trailing spaces from a string
411 size_t striplt(char *buf) {
412 char *first_nonspace = NULL;
413 char *last_nonspace = NULL;
417 if ((buf == NULL) || (*buf == '\0')) {
421 for (ptr=buf; *ptr!=0; ++ptr) {
422 if (!isspace(*ptr)) {
423 if (!first_nonspace) {
424 first_nonspace = ptr;
430 if ((!first_nonspace) || (!last_nonspace)) {
435 new_len = last_nonspace - first_nonspace + 1;
436 memmove(buf, first_nonspace, new_len);
443 * \brief check for the presence of a character within a string (returns count)
444 * \param st the string to examine
445 * \param ch the char to search
446 * \return the number of times ch appears in st
448 int haschar(const char *st, int ch)
454 while (!IsEmptyStr(ptr))
468 * Format a date/time stamp for output
469 * seconds is whether to print the seconds
471 void fmt_date(char *buf, size_t n, time_t thetime, int seconds) {
473 char *teh_format = NULL;
476 localtime_r(&thetime, &tm);
479 teh_format = "%F %R:%S";
482 teh_format = "%F %R";
485 strftime(buf, n, teh_format, &tm);
491 * Determine whether the specified message number is contained within the
492 * specified sequence set.
494 int is_msg_in_sequence_set(const char *mset, long msgnum) {
497 char setstr[128], lostr[128], histr[128];
500 num_sets = num_tokens(mset, ',');
501 for (s=0; s<num_sets; ++s) {
502 extract_token(setstr, mset, s, ',', sizeof setstr);
504 extract_token(lostr, setstr, 0, ':', sizeof lostr);
505 if (num_tokens(setstr, ':') >= 2) {
506 extract_token(histr, setstr, 1, ':', sizeof histr);
507 if (!strcmp(histr, "*")) {
508 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
512 strcpy(histr, lostr);
517 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
524 * \brief Utility function to "readline" from memory
525 * \param start Location in memory from which we are reading.
526 * \param buf the buffer to place the string in.
527 * \param maxlen Size of string buffer
528 * \return Pointer to the source memory right after we stopped reading.
530 char *memreadline(char *start, char *buf, int maxlen)
534 int len = 0; /**< tally our own length to avoid strlen() delays */
540 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
543 if ((ch == 10) || (ch == 0)) {
552 * \brief Utility function to "readline" from memory
553 * \param start Location in memory from which we are reading.
554 * \param buf the buffer to place the string in.
555 * \param maxlen Size of string buffer
556 * \param retlen the length of the returned string
557 * \return Pointer to the source memory right after we stopped reading.
559 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
563 int len = 0; /**< tally our own length to avoid strlen() delays */
569 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
572 if ((ch == 10) || (ch == 0)) {
582 * \brief Utility function to "readline" from memory
583 * \param start Location in memory from which we are reading.
584 * \param buf the buffer to place the string in.
585 * \param maxlen Size of string buffer
586 * \return Pointer to the source memory right after we stopped reading.
588 const char *cmemreadline(const char *start, char *buf, int maxlen)
592 int len = 0; /**< tally our own length to avoid strlen() delays */
598 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
601 if ((ch == 10) || (ch == 0)) {
610 * \brief Utility function to "readline" from memory
611 * \param start Location in memory from which we are reading.
612 * \param buf the buffer to place the string in.
613 * \param maxlen Size of string buffer
614 * \param retlen the length of the returned string
615 * \return Pointer to the source memory right after we stopped reading.
617 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
621 int len = 0; /**< tally our own length to avoid strlen() delays */
627 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
630 if ((ch == 10) || (ch == 0)) {
642 * Strip a boundarized substring out of a string (for example, remove
643 * parentheses and anything inside them).
645 int stripout(char *str, char leftboundary, char rightboundary) {
650 for (a = 0; a < strlen(str); ++a) {
651 if (str[a] == leftboundary) lb = a;
652 if (str[a] == rightboundary) rb = a;
655 if ( (lb > 0) && (rb > lb) ) {
656 strcpy(&str[lb - 1], &str[rb + 1]);
660 else if ( (lb == 0) && (rb > lb) ) {
661 strcpy(str, &str[rb + 1]);
669 * Reduce a string down to a boundarized substring (for example, remove
670 * parentheses and anything outside them).
672 long stripallbut(char *str, char leftboundary, char rightboundary) {
678 lb = strrchr(str, leftboundary);
681 rb = strchr(str, rightboundary);
682 if ((rb != NULL) && (rb >= lb)) {
685 len = (long)rb - (long)lb;
686 memmove(str, lb, len);
692 return (long)strlen(str);
696 char *myfgets(char *s, int size, FILE *stream) {
697 char *ret = fgets(s, size, stream);
701 nl = strchr(s, '\n');
711 * \brief Escape a string for feeding out as a URL.
712 * \param outbuf the output buffer
713 * \param oblen the size of outbuf to sanitize
714 * \param strbuf the input buffer
716 void urlesc(char *outbuf, size_t oblen, char *strbuf)
718 int a, b, c, len, eclen, olen;
719 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
722 len = strlen(strbuf);
725 for (a = 0; a < len; ++a) {
727 for (b = 0; b < eclen; ++b) {
728 if (strbuf[a] == ec[b])
732 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
736 outbuf[olen ++] = strbuf[a];
744 * In our world, we want strcpy() to be able to work with overlapping strings.
749 char *strcpy(char *dest, const char *src) {
750 memmove(dest, src, (strlen(src) + 1) );
756 * Generate a new, globally unique UID parameter for a calendar etc. object
758 void generate_uuid(char *buf) {
759 static int seq = (-1);
760 static int no_kernel_uuid = 0;
762 /* If we are running on Linux then we have a kernelspace uuid generator available */
764 if (no_kernel_uuid == 0) {
766 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
769 rv = fread(buf, 36, 1, fp);
778 /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
786 seq = (seq % 0x0FFF) ;
788 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
798 * bmstrcasestr() -- case-insensitive substring search
800 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
801 * The code is roughly based on the strstr() replacement from 'tin' written
804 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
806 register unsigned char *p, *t;
807 register int i, j, *delta;
811 if (!text) return(NULL);
812 if (!pattern) return(NULL);
814 /* algorithm fails if pattern is empty */
815 if ((p1 = patlen) == 0)
818 /* code below fails (whenever i is unsigned) if pattern too long */
824 for (i = 0; i <= 255; i++)
826 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
827 delta[tolower(*p++)] = i;
830 * From now on, we want patlen - 1.
831 * In the loop below, p points to the end of the pattern,
832 * t points to the end of the text to be tested against the
833 * pattern, and i counts the amount of text remaining, not
834 * including the part to be tested.
837 p = (unsigned char *) pattern + p1;
838 t = (unsigned char *) text + p1;
839 i = textlen - patlen;
841 if (tolower(p[0]) == tolower(t[0])) {
842 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
843 return ((char *)t - p1);
846 j = delta[tolower(t[0])];
856 * bmstrcasestr() -- case-insensitive substring search
858 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
859 * The code is roughly based on the strstr() replacement from 'tin' written
862 char *bmstrcasestr(char *text, const char *pattern) {
866 if (!text) return(NULL);
867 if (!pattern) return(NULL);
869 textlen = strlen (text);
870 patlen = strlen (pattern);
872 return _bmstrcasestr_len(text, textlen, pattern, patlen);
875 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
876 return _bmstrcasestr_len(text, textlen, pattern, patlen);
883 * bmstrcasestr() -- case-insensitive substring search
885 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
886 * The code is roughly based on the strstr() replacement from 'tin' written
889 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
891 register unsigned char *p, *t;
892 register int i, j, *delta;
896 if (!text) return(NULL);
897 if (!pattern) return(NULL);
899 /* algorithm fails if pattern is empty */
900 if ((p1 = patlen) == 0)
903 /* code below fails (whenever i is unsigned) if pattern too long */
909 for (i = 0; i <= 255; i++)
911 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
912 delta[tolower(*p++)] = i;
915 * From now on, we want patlen - 1.
916 * In the loop below, p points to the end of the pattern,
917 * t points to the end of the text to be tested against the
918 * pattern, and i counts the amount of text remaining, not
919 * including the part to be tested.
922 p = (unsigned char *) pattern + p1;
923 t = (unsigned char *) text + p1;
924 i = textlen - patlen;
926 if (tolower(p[0]) == tolower(t[0])) {
927 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
928 return ((char *)t - p1);
931 j = delta[tolower(t[0])];
941 * bmstrcasestr() -- case-insensitive substring search
943 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
944 * The code is roughly based on the strstr() replacement from 'tin' written
947 const char *cbmstrcasestr(const char *text, const char *pattern) {
951 if (!text) return(NULL);
952 if (!pattern) return(NULL);
954 textlen = strlen (text);
955 patlen = strlen (pattern);
957 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
960 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
961 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
965 * Local replacement for controversial C library function that generates
966 * names for temporary files. Included to shut up compiler warnings.
968 void CtdlMakeTempFileName(char *name, int len) {
971 while (i++, i < 100) {
972 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
976 if (!access(name, F_OK)) {
985 * Determine whether the specified message number is contained within the specified set.
986 * Returns nonzero if the specified message number is in the specified message set string.
988 int is_msg_in_mset(const char *mset, long msgnum) {
991 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
995 * Now set it for all specified messages.
997 num_sets = num_tokens(mset, ',');
998 for (s=0; s<num_sets; ++s) {
999 extract_token(setstr, mset, s, ',', sizeof setstr);
1001 extract_token(lostr, setstr, 0, ':', sizeof lostr);
1002 if (num_tokens(setstr, ':') >= 2) {
1003 extract_token(histr, setstr, 1, ':', sizeof histr);
1004 if (!strcmp(histr, "*")) {
1005 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
1009 strcpy(histr, lostr);
1014 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
1022 * searches for a pattern within a search string
1023 * returns position in string
1025 int pattern2(char *search, char *patn)
1029 len = strlen (search);
1030 plen = strlen (patn);
1031 for (a = 0; a < len; ++a) {
1032 if (!strncasecmp(&search[a], patn, plen))
1040 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1041 * buf - the string to modify
1042 * len - length of the string.
1044 void stripltlen(char *buf, int *len)
1047 if (*len == 0) return;
1048 while ((*len > delta) && (isspace(buf[delta]))){
1051 memmove (buf, &buf[delta], *len - delta + 1);
1054 if (*len == 0) return;
1055 while (isspace(buf[(*len) - 1])){
1056 buf[--(*len)] = '\0';
1062 * Convert all whitespace characters in a supplied string to underscores
1064 void convert_spaces_to_underscores(char *str)
1072 for (i=0; i<len; ++i) {
1073 if (isspace(str[i])) {
1081 * check whether the provided string needs to be qp encoded or not
1083 int CheckEncode(const char *pch, long len, const char *pche)
1087 while (pch < pche) {
1088 if (((unsigned char) *pch < 32) ||
1089 ((unsigned char) *pch > 126)) {