2 * A basic toolset containing miscellaneous functions for string manipluation,
3 * encoding/decoding, and a bunch of other stuff.
5 * Copyright (c) 1987-2017 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, 0);
323 destoffset = base64_encode_block(source, sourcelen, dest, &_state);
325 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state, 0);
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))
465 * Determine whether the specified message number is contained within the
466 * specified sequence set.
468 int is_msg_in_sequence_set(const char *mset, long msgnum) {
471 char setstr[128], lostr[128], histr[128];
474 num_sets = num_tokens(mset, ',');
475 for (s=0; s<num_sets; ++s) {
476 extract_token(setstr, mset, s, ',', sizeof setstr);
478 extract_token(lostr, setstr, 0, ':', sizeof lostr);
479 if (num_tokens(setstr, ':') >= 2) {
480 extract_token(histr, setstr, 1, ':', sizeof histr);
481 if (!strcmp(histr, "*")) {
482 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
486 strcpy(histr, lostr);
491 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
498 * \brief Utility function to "readline" from memory
499 * \param start Location in memory from which we are reading.
500 * \param buf the buffer to place the string in.
501 * \param maxlen Size of string buffer
502 * \return Pointer to the source memory right after we stopped reading.
504 char *memreadline(char *start, char *buf, int maxlen)
508 int len = 0; /**< tally our own length to avoid strlen() delays */
514 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
517 if ((ch == 10) || (ch == 0)) {
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 * \param retlen the length of the returned string
531 * \return Pointer to the source memory right after we stopped reading.
533 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
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)) {
556 * \brief Utility function to "readline" from memory
557 * \param start Location in memory from which we are reading.
558 * \param buf the buffer to place the string in.
559 * \param maxlen Size of string buffer
560 * \return Pointer to the source memory right after we stopped reading.
562 const char *cmemreadline(const char *start, char *buf, int maxlen)
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)) {
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 * \param retlen the length of the returned string
589 * \return Pointer to the source memory right after we stopped reading.
591 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
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)) {
616 * Strip a boundarized substring out of a string (for example, remove
617 * parentheses and anything inside them).
619 int stripout(char *str, char leftboundary, char rightboundary) {
624 for (a = 0; a < strlen(str); ++a) {
625 if (str[a] == leftboundary) lb = a;
626 if (str[a] == rightboundary) rb = a;
629 if ( (lb > 0) && (rb > lb) ) {
630 strcpy(&str[lb - 1], &str[rb + 1]);
634 else if ( (lb == 0) && (rb > lb) ) {
635 strcpy(str, &str[rb + 1]);
643 * Reduce a string down to a boundarized substring (for example, remove
644 * parentheses and anything outside them).
646 long stripallbut(char *str, char leftboundary, char rightboundary) {
652 lb = strrchr(str, leftboundary);
655 rb = strchr(str, rightboundary);
656 if ((rb != NULL) && (rb >= lb)) {
659 len = (long)rb - (long)lb;
660 memmove(str, lb, len);
666 return (long)strlen(str);
670 char *myfgets(char *s, int size, FILE *stream) {
671 char *ret = fgets(s, size, stream);
675 nl = strchr(s, '\n');
685 * \brief Escape a string for feeding out as a URL.
686 * \param outbuf the output buffer
687 * \param oblen the size of outbuf to sanitize
688 * \param strbuf the input buffer
690 void urlesc(char *outbuf, size_t oblen, char *strbuf)
692 int a, b, c, len, eclen, olen;
693 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
696 len = strlen(strbuf);
699 for (a = 0; a < len; ++a) {
701 for (b = 0; b < eclen; ++b) {
702 if (strbuf[a] == ec[b])
706 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
710 outbuf[olen ++] = strbuf[a];
718 * In our world, we want strcpy() to be able to work with overlapping strings.
723 char *strcpy(char *dest, const char *src) {
724 memmove(dest, src, (strlen(src) + 1) );
730 * Generate a new, globally unique UID parameter for a calendar etc. object
732 void generate_uuid(char *buf) {
733 static int seq = (-1);
734 static int no_kernel_uuid = 0;
736 /* If we are running on Linux then we have a kernelspace uuid generator available */
738 if (no_kernel_uuid == 0) {
740 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
743 rv = fread(buf, 36, 1, fp);
752 /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
760 seq = (seq % 0x0FFF) ;
762 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
772 * bmstrcasestr() -- case-insensitive substring search
774 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
775 * The code is roughly based on the strstr() replacement from 'tin' written
778 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
780 register unsigned char *p, *t;
781 register int i, j, *delta;
785 if (!text) return(NULL);
786 if (!pattern) return(NULL);
788 /* algorithm fails if pattern is empty */
789 if ((p1 = patlen) == 0)
792 /* code below fails (whenever i is unsigned) if pattern too long */
798 for (i = 0; i <= 255; i++)
800 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
801 delta[tolower(*p++)] = i;
804 * From now on, we want patlen - 1.
805 * In the loop below, p points to the end of the pattern,
806 * t points to the end of the text to be tested against the
807 * pattern, and i counts the amount of text remaining, not
808 * including the part to be tested.
811 p = (unsigned char *) pattern + p1;
812 t = (unsigned char *) text + p1;
813 i = textlen - patlen;
815 if (tolower(p[0]) == tolower(t[0])) {
816 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
817 return ((char *)t - p1);
820 j = delta[tolower(t[0])];
830 * bmstrcasestr() -- case-insensitive substring search
832 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
833 * The code is roughly based on the strstr() replacement from 'tin' written
836 char *bmstrcasestr(char *text, const char *pattern) {
840 if (!text) return(NULL);
841 if (!pattern) return(NULL);
843 textlen = strlen (text);
844 patlen = strlen (pattern);
846 return _bmstrcasestr_len(text, textlen, pattern, patlen);
849 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
850 return _bmstrcasestr_len(text, textlen, pattern, patlen);
857 * bmstrcasestr() -- case-insensitive substring search
859 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
860 * The code is roughly based on the strstr() replacement from 'tin' written
863 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
865 register unsigned char *p, *t;
866 register int i, j, *delta;
870 if (!text) return(NULL);
871 if (!pattern) return(NULL);
873 /* algorithm fails if pattern is empty */
874 if ((p1 = patlen) == 0)
877 /* code below fails (whenever i is unsigned) if pattern too long */
883 for (i = 0; i <= 255; i++)
885 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
886 delta[tolower(*p++)] = i;
889 * From now on, we want patlen - 1.
890 * In the loop below, p points to the end of the pattern,
891 * t points to the end of the text to be tested against the
892 * pattern, and i counts the amount of text remaining, not
893 * including the part to be tested.
896 p = (unsigned char *) pattern + p1;
897 t = (unsigned char *) text + p1;
898 i = textlen - patlen;
900 if (tolower(p[0]) == tolower(t[0])) {
901 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
902 return ((char *)t - p1);
905 j = delta[tolower(t[0])];
915 * bmstrcasestr() -- case-insensitive substring search
917 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
918 * The code is roughly based on the strstr() replacement from 'tin' written
921 const char *cbmstrcasestr(const char *text, const char *pattern) {
925 if (!text) return(NULL);
926 if (!pattern) return(NULL);
928 textlen = strlen (text);
929 patlen = strlen (pattern);
931 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
934 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
935 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
939 * Local replacement for controversial C library function that generates
940 * names for temporary files. Included to shut up compiler warnings.
942 void CtdlMakeTempFileName(char *name, int len) {
945 while (i++, i < 100) {
946 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
950 if (!access(name, F_OK)) {
959 * Determine whether the specified message number is contained within the specified set.
960 * Returns nonzero if the specified message number is in the specified message set string.
962 int is_msg_in_mset(const char *mset, long msgnum) {
965 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
969 * Now set it for all specified messages.
971 num_sets = num_tokens(mset, ',');
972 for (s=0; s<num_sets; ++s) {
973 extract_token(setstr, mset, s, ',', sizeof setstr);
975 extract_token(lostr, setstr, 0, ':', sizeof lostr);
976 if (num_tokens(setstr, ':') >= 2) {
977 extract_token(histr, setstr, 1, ':', sizeof histr);
978 if (!strcmp(histr, "*")) {
979 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
983 strcpy(histr, lostr);
988 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
996 * searches for a pattern within a search string
997 * returns position in string
999 int pattern2(char *search, char *patn)
1003 len = strlen (search);
1004 plen = strlen (patn);
1005 for (a = 0; a < len; ++a) {
1006 if (!strncasecmp(&search[a], patn, plen))
1014 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1015 * buf - the string to modify
1016 * len - length of the string.
1018 void stripltlen(char *buf, int *len)
1021 if (*len == 0) return;
1022 while ((*len > delta) && (isspace(buf[delta]))){
1025 memmove (buf, &buf[delta], *len - delta + 1);
1028 if (*len == 0) return;
1029 while (isspace(buf[(*len) - 1])){
1030 buf[--(*len)] = '\0';
1036 * Convert all whitespace characters in a supplied string to underscores
1038 void convert_spaces_to_underscores(char *str)
1046 for (i=0; i<len; ++i) {
1047 if (isspace(str[i])) {
1055 * check whether the provided string needs to be qp encoded or not
1057 int CheckEncode(const char *pch, long len, const char *pche)
1061 while (pch < pche) {
1062 if (((unsigned char) *pch < 32) ||
1063 ((unsigned char) *pch > 126)) {