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)
70 fprintf(stderr, "safestrncpy: NULL argument\n");
76 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;
110 * extract_token() - a string tokenizer
111 * returns -1 if not found, or length of token.
113 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen)
115 const char *s; //* source * /
116 int len = 0; //* running total length of extracted string * /
117 int current_token = 0; //* token currently being processed * /
141 if ( (current_token == parmnum) && (*s != separator) && (len < maxlen) )
146 else if ((current_token > parmnum) || (len >= maxlen))
154 if (current_token < parmnum)
163 * remove_token() - a tokenizer that kills, maims, and destroys
165 void remove_token(char *source, int parmnum, char separator)
167 char *d, *s; /* dest, source */
170 /* Find desired parameter */
172 while (count < parmnum)
174 /* End of string, bail! */
185 if (!d) return; /* Parameter not found */
187 /* Find next parameter */
189 while (*s && *s != separator)
197 else if (d == source)
205 * extract_int() - extract an int parm w/o supplying a buffer
207 int extract_int(const char *source, int parmnum)
211 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
219 * extract_long() - extract an long parm w/o supplying a buffer
221 long extract_long(const char *source, int parmnum)
225 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
233 * extract_unsigned_long() - extract an unsigned long parm
235 unsigned long extract_unsigned_long(const char *source, int parmnum)
239 if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
240 return strtoul(buf, NULL, 10);
246 size_t CtdlEncodeBase64(char *dest, const char *source, size_t sourcelen, int linebreaks)
248 int breaklength = 68; // must be a multiple of 4
249 int readlength = 3 * breaklength / 4;
255 base64_encodestate _state;
257 base64_init_encodestate(&_state);
260 sourceremaining = sourcelen;
264 while (sourceremaining > 0) {
265 destoffset += base64_encode_block(
266 &(source[sourceoffset]),
267 (readlength > sourceremaining ? sourceremaining : readlength),
270 sourceoffset += readlength;
271 sourceremaining -= readlength;
272 dest[destoffset++] = '\r';
273 dest[destoffset++] = '\n';
276 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state, 0);
279 destoffset = base64_encode_block(source, sourcelen, dest, &_state);
281 destoffset += base64_encode_blockend(&(dest[destoffset]), &_state, 0);
283 dest[destoffset] = 0;
289 * Convert base64-encoded to binary. Returns the length of the decoded data.
290 * It will stop after reading 'length' bytes.
292 int CtdlDecodeBase64(char *dest, const char *source, size_t length)
294 base64_decodestate _state;
297 base64_init_decodestate(&_state);
299 len = base64_decode_block(source, length, dest, &_state);
306 * if we send out non ascii subjects, we encode it this way.
308 char *rfc2047encode(const char *line, long length)
310 const char *AlreadyEncoded;
313 #define UTF8_HEADER "=?UTF-8?B?"
315 /* check if we're already done */
316 AlreadyEncoded = strstr(line, "=?");
317 if ((AlreadyEncoded != NULL) &&
318 ((strstr(AlreadyEncoded, "?B?") != NULL)||
319 (strstr(AlreadyEncoded, "?Q?") != NULL)))
324 result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
325 strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
326 CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, 0);
327 end = strlen (result);
335 * removes double slashes from pathnames
336 * allows / disallows trailing slashes
338 void StripSlashes(char *Dir, int TrailingSlash)
344 while (!IsEmptyStr(a)) {
356 if ((TrailingSlash) && (*(b - 1) != '/')){
366 * Strip leading and trailing spaces from a string
368 size_t striplt(char *buf) {
369 char *first_nonspace = NULL;
370 char *last_nonspace = NULL;
374 if ((buf == NULL) || (*buf == '\0')) {
378 for (ptr=buf; *ptr!=0; ++ptr) {
379 if (!isspace(*ptr)) {
380 if (!first_nonspace) {
381 first_nonspace = ptr;
387 if ((!first_nonspace) || (!last_nonspace)) {
392 new_len = last_nonspace - first_nonspace + 1;
393 memmove(buf, first_nonspace, new_len);
400 * check for the presence of a character within a string (returns count)
401 * st the string to examine
402 * ch the char to search
403 * returns the number of times ch appears in st
405 int haschar(const char *st, int ch)
411 while (!IsEmptyStr(ptr))
422 * Determine whether the specified message number is contained within the
423 * specified sequence set.
425 int is_msg_in_sequence_set(const char *mset, long msgnum)
429 char setstr[128], lostr[128], histr[128];
432 num_sets = num_tokens(mset, ',');
433 for (s=0; s<num_sets; ++s) {
434 extract_token(setstr, mset, s, ',', sizeof setstr);
436 extract_token(lostr, setstr, 0, ':', sizeof lostr);
437 if (num_tokens(setstr, ':') >= 2)
439 extract_token(histr, setstr, 1, ':', sizeof histr);
440 if (!strcmp(histr, "*"))
442 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
447 strcpy(histr, lostr);
452 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
459 * Utility function to "readline" from memory
460 * start Location in memory from which we are reading.
461 * buf the buffer to place the string in.
462 * maxlen Size of string buffer
463 * returns pointer to the source memory right after we stopped reading.
465 char *memreadline(char *start, char *buf, int maxlen)
469 int len = 0; /* tally our own length to avoid strlen() delays */
475 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
478 if ((ch == 10) || (ch == 0)) {
487 * Utility function to "readline" from memory
488 * start Location in memory from which we are reading.
489 * buf the buffer to place the string in.
490 * maxlen Size of string buffer
491 * retlen the length of the returned string
492 * returns a pointer to the source memory right after we stopped reading.
494 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
498 int len = 0; /* tally our own length to avoid strlen() delays */
505 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10))
509 if ((ch == 10) || (ch == 0))
520 * \brief Utility function to "readline" from memory
521 * \param start Location in memory from which we are reading.
522 * \param buf the buffer to place the string in.
523 * \param maxlen Size of string buffer
524 * \return Pointer to the source memory right after we stopped reading.
526 const char *cmemreadline(const char *start, char *buf, int maxlen)
530 int len = 0; /**< tally our own length to avoid strlen() delays */
536 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
539 if ((ch == 10) || (ch == 0)) {
548 * \brief Utility function to "readline" from memory
549 * \param start Location in memory from which we are reading.
550 * \param buf the buffer to place the string in.
551 * \param maxlen Size of string buffer
552 * \param retlen the length of the returned string
553 * \return Pointer to the source memory right after we stopped reading.
555 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
559 int len = 0; /**< tally our own length to avoid strlen() delays */
565 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
568 if ((ch == 10) || (ch == 0)) {
580 * Strip a boundarized substring out of a string (for example, remove
581 * parentheses and anything inside them).
583 int stripout(char *str, char leftboundary, char rightboundary) {
588 for (a = 0; a < strlen(str); ++a) {
589 if (str[a] == leftboundary) lb = a;
590 if (str[a] == rightboundary) rb = a;
593 if ( (lb > 0) && (rb > lb) ) {
594 strcpy(&str[lb - 1], &str[rb + 1]);
598 else if ( (lb == 0) && (rb > lb) ) {
599 strcpy(str, &str[rb + 1]);
607 * Reduce a string down to a boundarized substring (for example, remove
608 * parentheses and anything outside them).
610 long stripallbut(char *str, char leftboundary, char rightboundary) {
616 lb = strrchr(str, leftboundary);
619 rb = strchr(str, rightboundary);
620 if ((rb != NULL) && (rb >= lb)) {
623 len = (long)rb - (long)lb;
624 memmove(str, lb, len);
630 return (long)strlen(str);
634 char *myfgets(char *s, int size, FILE *stream) {
635 char *ret = fgets(s, size, stream);
639 nl = strchr(s, '\n');
649 * \brief Escape a string for feeding out as a URL.
650 * \param outbuf the output buffer
651 * \param oblen the size of outbuf to sanitize
652 * \param strbuf the input buffer
654 void urlesc(char *outbuf, size_t oblen, char *strbuf)
656 int a, b, c, len, eclen, olen;
657 char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
660 len = strlen(strbuf);
663 for (a = 0; a < len; ++a) {
665 for (b = 0; b < eclen; ++b) {
666 if (strbuf[a] == ec[b])
670 snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
674 outbuf[olen ++] = strbuf[a];
682 * In our world, we want strcpy() to be able to work with overlapping strings.
687 char *strcpy(char *dest, const char *src) {
688 memmove(dest, src, (strlen(src) + 1) );
694 * Generate a new, globally unique UID parameter for a calendar etc. object
696 void generate_uuid(char *buf) {
697 static int seq = (-1);
698 static int no_kernel_uuid = 0;
700 /* If we are running on Linux then we have a kernelspace uuid generator available */
702 if (no_kernel_uuid == 0) {
704 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
707 rv = fread(buf, 36, 1, fp);
716 /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
724 seq = (seq % 0x0FFF) ;
726 sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
736 * bmstrcasestr() -- case-insensitive substring search
738 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
739 * The code is roughly based on the strstr() replacement from 'tin' written
742 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
744 register unsigned char *p, *t;
745 register int i, j, *delta;
749 if (!text) return(NULL);
750 if (!pattern) return(NULL);
752 /* algorithm fails if pattern is empty */
753 if ((p1 = patlen) == 0)
756 /* code below fails (whenever i is unsigned) if pattern too long */
762 for (i = 0; i <= 255; i++)
764 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
765 delta[tolower(*p++)] = i;
768 * From now on, we want patlen - 1.
769 * In the loop below, p points to the end of the pattern,
770 * t points to the end of the text to be tested against the
771 * pattern, and i counts the amount of text remaining, not
772 * including the part to be tested.
775 p = (unsigned char *) pattern + p1;
776 t = (unsigned char *) text + p1;
777 i = textlen - patlen;
779 if (tolower(p[0]) == tolower(t[0])) {
780 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
781 return ((char *)t - p1);
784 j = delta[tolower(t[0])];
794 * bmstrcasestr() -- case-insensitive substring search
796 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
797 * The code is roughly based on the strstr() replacement from 'tin' written
800 char *bmstrcasestr(char *text, const char *pattern) {
804 if (!text) return(NULL);
805 if (!pattern) return(NULL);
807 textlen = strlen (text);
808 patlen = strlen (pattern);
810 return _bmstrcasestr_len(text, textlen, pattern, patlen);
813 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
814 return _bmstrcasestr_len(text, textlen, pattern, patlen);
821 * bmstrcasestr() -- case-insensitive substring search
823 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
824 * The code is roughly based on the strstr() replacement from 'tin' written
827 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
829 register unsigned char *p, *t;
830 register int i, j, *delta;
834 if (!text) return(NULL);
835 if (!pattern) return(NULL);
837 /* algorithm fails if pattern is empty */
838 if ((p1 = patlen) == 0)
841 /* code below fails (whenever i is unsigned) if pattern too long */
847 for (i = 0; i <= 255; i++)
849 for (p = (unsigned char *) pattern, i = p1; --i > 0;)
850 delta[tolower(*p++)] = i;
853 * From now on, we want patlen - 1.
854 * In the loop below, p points to the end of the pattern,
855 * t points to the end of the text to be tested against the
856 * pattern, and i counts the amount of text remaining, not
857 * including the part to be tested.
860 p = (unsigned char *) pattern + p1;
861 t = (unsigned char *) text + p1;
862 i = textlen - patlen;
864 if (tolower(p[0]) == tolower(t[0])) {
865 if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
866 return ((char *)t - p1);
869 j = delta[tolower(t[0])];
879 * bmstrcasestr() -- case-insensitive substring search
881 * This uses the Boyer-Moore search algorithm and is therefore quite fast.
882 * The code is roughly based on the strstr() replacement from 'tin' written
885 const char *cbmstrcasestr(const char *text, const char *pattern) {
889 if (!text) return(NULL);
890 if (!pattern) return(NULL);
892 textlen = strlen (text);
893 patlen = strlen (pattern);
895 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
898 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
899 return _cbmstrcasestr_len(text, textlen, pattern, patlen);
903 * Local replacement for controversial C library function that generates
904 * names for temporary files. Included to shut up compiler warnings.
906 void CtdlMakeTempFileName(char *name, int len) {
909 while (i++, i < 100) {
910 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
914 if (!access(name, F_OK)) {
923 * Determine whether the specified message number is contained within the specified set.
924 * Returns nonzero if the specified message number is in the specified message set string.
926 int is_msg_in_mset(const char *mset, long msgnum) {
929 char setstr[SIZ], lostr[SIZ], histr[SIZ]; /* was 1024 */
933 * Now set it for all specified messages.
935 num_sets = num_tokens(mset, ',');
936 for (s=0; s<num_sets; ++s) {
937 extract_token(setstr, mset, s, ',', sizeof setstr);
939 extract_token(lostr, setstr, 0, ':', sizeof lostr);
940 if (num_tokens(setstr, ':') >= 2) {
941 extract_token(histr, setstr, 1, ':', sizeof histr);
942 if (!strcmp(histr, "*")) {
943 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
947 strcpy(histr, lostr);
952 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
960 * searches for a pattern within a search string
961 * returns position in string
963 int pattern2(char *search, char *patn)
967 len = strlen (search);
968 plen = strlen (patn);
969 for (a = 0; a < len; ++a) {
970 if (!strncasecmp(&search[a], patn, plen))
978 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
979 * buf - the string to modify
980 * len - length of the string.
982 void stripltlen(char *buf, int *len)
985 if (*len == 0) return;
986 while ((*len > delta) && (isspace(buf[delta]))){
989 memmove (buf, &buf[delta], *len - delta + 1);
992 if (*len == 0) return;
993 while (isspace(buf[(*len) - 1])){
994 buf[--(*len)] = '\0';
1000 * Convert all whitespace characters in a supplied string to underscores
1002 void convert_spaces_to_underscores(char *str)
1010 for (i=0; i<len; ++i) {
1011 if (isspace(str[i])) {
1019 * check whether the provided string needs to be qp encoded or not
1021 int CheckEncode(const char *pch, long len, const char *pche)
1025 while (pch < pche) {
1026 if (((unsigned char) *pch < 32) ||
1027 ((unsigned char) *pch > 126)) {