4eda91bffbb2f2af29734781884e59ab125df4f2
[citadel.git] / libcitadel / lib / tools.c
1 // A basic toolset containing miscellaneous functions for string manipluation,
2 // encoding/decoding, and a bunch of other stuff.
3 //
4 // Copyright (c) 1987-2023 by the citadel.org team
5 //
6 // This program is open source software.  Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
8
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <signal.h>
13 #include <sys/types.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <sys/stat.h>
17 #include <errno.h>
18 #include <limits.h>
19 #include <time.h>
20 #include "libcitadel.h"
21
22 #define TRUE  1
23 #define FALSE 0
24
25 typedef unsigned char byte;           // Byte type
26
27 // copy a string into a buffer of a known size. abort if we exceed the limits
28 //
29 // dest the targetbuffer
30 // src  the source string
31 // n    the size od dest
32 //
33 // returns the number of characters copied if dest is big enough, -n if not.
34 int safestrncpy(char *dest, const char *src, size_t n) {
35         int i = 0;
36
37         if (dest == NULL || src == NULL)
38         {
39                 fprintf(stderr, "safestrncpy: NULL argument\n");
40                 abort();
41         }
42
43         do {
44                 dest[i] = src[i];
45                 if (dest[i] == 0) return i;
46                 ++i;
47         } while (i<n);
48         dest[n - 1] = 0;
49         return -i;
50 }
51
52
53 // num_tokens()  -  discover number of parameters/tokens in a string
54 int num_tokens(const char *source, char tok) {
55         int count = 1;
56         const char *ptr = source;
57
58         if (source == NULL) {
59                 return (0);
60         }
61
62         while (*ptr != '\0') {
63                 if (*ptr++ == tok) {
64                         ++count;
65                 }
66         }
67         
68         return (count);
69 }
70
71
72 // extract_token() - a string tokenizer
73 // returns -1 if not found, or length of token.
74 long extract_token(char *dest, const char *source, int parmnum, char separator, int maxlen) {
75         const char *s;                  // source
76         int len = 0;                    // running total length of extracted string
77         int current_token = 0;          // token currently being processed
78
79         s = source;
80
81         if (dest == NULL) {
82                 return(-1);
83         }
84
85         dest[0] = 0;
86
87         if (s == NULL) {
88                 return(-1);
89         }
90         
91         maxlen--;
92
93         while (*s) {
94                 if (*s == separator) {
95                         ++current_token;
96                 }
97                 if ( (current_token == parmnum) && (*s != separator) && (len < maxlen) ) {
98                         dest[len] = *s;
99                         ++len;
100                 }
101                 else if ((current_token > parmnum) || (len >= maxlen)) {
102                         break;
103                 }
104                 ++s;
105         }
106
107         dest[len] = '\0';
108         if (current_token < parmnum) {
109                 return(-1);
110         }
111         return(len);
112 }
113
114
115 // remove_token() - a tokenizer that kills, maims, and destroys
116 void remove_token(char *source, int parmnum, char separator) {
117         char *d, *s;            // dest, source
118         int count = 0;
119
120         // Find desired parameter
121         d = source;
122         while (count < parmnum) {
123                 // End of string, bail!
124                 if (!*d) {
125                         d = NULL;
126                         break;
127                 }
128                 if (*d == separator) {
129                         count++;
130                 }
131                 d++;
132         }
133         if (!d) return;         // Parameter not found
134
135         // Find next parameter
136         s = d;
137         while (*s && *s != separator) {
138                 s++;
139         }
140
141         // Hack and slash
142         if (*s)
143                 strcpy(d, ++s);
144         else if (d == source)
145                 *d = 0;
146         else
147                 *--d = 0;
148 }
149
150
151 // extract_int()  -  extract an int parm without supplying a buffer
152 int extract_int(const char *source, int parmnum) {
153         char buf[32];
154         
155         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
156                 return(atoi(buf));
157         else
158                 return 0;
159 }
160
161
162 // extract_long()  -  extract an long parm without supplying a buffer
163 long extract_long(const char *source, int parmnum) {
164         char buf[32];
165         
166         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
167                 return(atol(buf));
168         else
169                 return 0;
170 }
171
172
173 // extract_unsigned_long() - extract an unsigned long parm
174 unsigned long extract_unsigned_long(const char *source, int parmnum) {
175         char buf[32];
176
177         if (extract_token(buf, source, parmnum, '|', sizeof buf) > 0)
178                 return strtoul(buf, NULL, 10);
179         else 
180                 return 0;
181 }
182
183
184 // if we send out non ascii subjects, we encode it this way.
185 char *rfc2047encode(const char *line, long length) {
186         const char *AlreadyEncoded;
187         char *result;
188         long end;
189 #define UTF8_HEADER "=?UTF-8?B?"
190
191         // check if we're already done
192         AlreadyEncoded = strstr(line, "=?");
193         if ((AlreadyEncoded != NULL) && ((strstr(AlreadyEncoded, "?B?") != NULL)|| (strstr(AlreadyEncoded, "?Q?") != NULL))) {
194                 return strdup(line);
195         }
196
197         result = (char*) malloc(sizeof(UTF8_HEADER) + 4 + length * 2);
198         strncpy (result, UTF8_HEADER, strlen (UTF8_HEADER));
199         CtdlEncodeBase64(result + strlen(UTF8_HEADER), line, length, BASE64_NO_LINEBREAKS);
200         end = strlen (result);
201         result[end]='?';
202         result[end+1]='=';
203         result[end+2]='\0';
204         return result;
205 }
206
207 // removes double slashes from pathnames
208 // allows / disallows trailing slashes
209 void StripSlashes(char *Dir, int TrailingSlash) {
210         char *a, *b;
211
212         a = b = Dir;
213
214         while (!IsEmptyStr(a)) {
215                 if (*a == '/') {
216                         while (*a == '/')
217                                 a++;
218                         *b = '/';
219                         b++;
220                 }
221                 else {
222                         *b = *a;
223                         b++; a++;
224                 }
225         }
226         if ((TrailingSlash) && (*(b - 1) != '/')){
227                 *b = '/';
228                 b++;
229         }
230         *b = '\0';
231
232 }
233
234
235 // Trim leading and trailing whitespace from a string
236 size_t string_trim(char *buf) {
237         char *first_nonspace = NULL;
238         char *last_nonspace = NULL;
239         char *ptr;
240         size_t new_len = 0;
241
242         if ((buf == NULL) || (*buf == '\0')) {
243                 return 0;
244         }
245
246         for (ptr=buf; *ptr!=0; ++ptr) {
247                 if (!isspace(*ptr)) {
248                         if (!first_nonspace) {
249                                 first_nonspace = ptr;
250                         }
251                         last_nonspace = ptr;
252                 }
253         }
254
255         if ((!first_nonspace) || (!last_nonspace)) {
256                 buf[0] = 0;
257                 return 0;
258         }
259
260         new_len = last_nonspace - first_nonspace + 1;
261         memmove(buf, first_nonspace, new_len);
262         buf[new_len] = 0;
263         return new_len;
264 }
265
266
267 // check for the presence of a character within a string (returns count)
268 // st   the string to examine
269 // ch   the char to search
270 // returns the number of times ch appears in st
271 int haschar(const char *st, int ch) {
272         const char *ptr;
273         int b;
274         b = 0;
275         ptr = st;
276         while (!IsEmptyStr(ptr))
277         {
278                 if (*ptr == ch)
279                         ++b;
280                 ptr ++;
281         }
282         return (b);
283 }
284
285
286 // Determine whether the specified message number is contained within the specified sequence set.
287 int is_msg_in_sequence_set(const char *mset, long msgnum) {
288         int num_sets;
289         int s;
290         char setstr[128], lostr[128], histr[128];
291         long lo, hi;
292
293         num_sets = num_tokens(mset, ',');
294         for (s=0; s<num_sets; ++s) {
295                 extract_token(setstr, mset, s, ',', sizeof setstr);
296
297                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
298                 if (num_tokens(setstr, ':') >= 2) {
299                         extract_token(histr, setstr, 1, ':', sizeof histr);
300                         if (!strcmp(histr, "*")) {
301                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
302                         }
303                 } 
304                 else {
305                         strcpy(histr, lostr);
306                 }
307                 lo = atol(lostr);
308                 hi = atol(histr);
309
310                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
311         }
312
313         return(0);
314 }
315
316 // Utility function to "readline" from memory
317 // start        Location in memory from which we are reading.
318 // buf          the buffer to place the string in.
319 // maxlen       Size of string buffer
320 // returns pointer to the source memory right after we stopped reading.
321 char *memreadline(char *start, char *buf, int maxlen) {
322         char ch;
323         char *ptr;
324         int len = 0;            // tally our own length to avoid strlen() delays
325
326         ptr = start;
327
328         while (1) {
329                 ch = *ptr++;
330                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
331                         buf[len++] = ch;
332                 }
333                 if ((ch == 10) || (ch == 0)) {
334                         buf[len] = 0;
335                         return ptr;
336                 }
337         }
338 }
339
340
341 // Utility function to "readline" from memory
342 // start        Location in memory from which we are reading.
343 // buf          the buffer to place the string in.
344 // maxlen       Size of string buffer
345 // retlen       the length of the returned string
346 // returns a pointer to the source memory right after we stopped reading.
347 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen) {
348         char ch;
349         char *ptr;
350         int len = 0;            // tally our own length to avoid strlen() delays
351
352         ptr = start;
353
354         while (1) {
355                 ch = *ptr++;
356                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
357                         buf[len++] = ch;
358                 }
359                 if ((ch == 10) || (ch == 0)) {
360                         buf[len] = 0;
361                         *retlen = len;
362                         return ptr;
363                 }
364         }
365 }
366
367
368 // Utility function to "readline" from memory
369 // start Location in memory from which we are reading.
370 // buf the buffer to place the string in.
371 // maxlen Size of string buffer
372 // return Pointer to the source memory right after we stopped reading.
373 const char *cmemreadline(const char *start, char *buf, int maxlen) {
374         char ch;
375         const char *ptr;
376         int len = 0;            // tally our own length to avoid strlen() delays
377
378         ptr = start;
379
380         while (1) {
381                 ch = *ptr++;
382                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
383                         buf[len++] = ch;
384                 }
385                 if ((ch == 10) || (ch == 0)) {
386                         buf[len] = 0;
387                         return ptr;
388                 }
389         }
390 }
391
392
393 // Utility function to "readline" from memory
394 // start Location in memory from which we are reading.
395 // buf the buffer to place the string in.
396 // maxlen Size of string buffer
397 // retlen the length of the returned string
398 // return Pointer to the source memory right after we stopped reading.
399 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen) {
400         char ch;
401         const char *ptr;
402         int len = 0;            // tally our own length to avoid strlen() delays
403
404         ptr = start;
405
406         while (1) {
407                 ch = *ptr++;
408                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
409                         buf[len++] = ch;
410                 }
411                 if ((ch == 10) || (ch == 0)) {
412                         buf[len] = 0;
413                         *retlen = len;
414                         return ptr;
415                 }
416         }
417 }
418
419
420 // Strip a boundarized substring out of a string (for example, remove parentheses and anything inside them).
421 int stripout(char *str, char leftboundary, char rightboundary) {
422         long lb = (-1);
423         long rb = (-1);
424
425         if (!str) {
426                 return 0;
427         }
428
429         for (int a = 0; str[a]; ++a) {
430                 if ((lb==-1) && (str[a] == leftboundary)) {
431                         lb = a;
432                 } else if (str[a] == rightboundary) {
433                         rb = a;
434                 }
435         }
436
437         if ((lb==-1) || (rb <= lb)) {
438                 return 0;
439         }
440
441         strcpy(str + lb, str + rb + 1);
442         return 1;
443 }
444
445 // Reduce a string down to a boundarized substring (for example, remove
446 // parentheses and anything outside them).
447 long stripallbut(char *str, char leftboundary, char rightboundary) {
448         long lb = (-1);
449         long rb = (-1);
450         long orig_len = 0;
451
452         if (!str) {
453                 return 0;
454         }
455
456         while (str[orig_len]) {
457                 if ((lb==-1) && (str[orig_len] == leftboundary)) {
458                         lb = orig_len;
459                 } else if (str[orig_len] == rightboundary) {
460                         rb = orig_len;
461                 }
462                 orig_len++;
463         }
464
465         if ((lb==-1) || (rb <= lb)) {
466                 return orig_len;
467         }
468
469         fflush(stderr);
470
471         long new_len = rb - lb - 1;
472         memmove(str, str + lb + 1, new_len);
473         str[new_len] = 0;
474         return new_len;
475 }
476
477 char *myfgets(char *s, int size, FILE *stream) {
478         char *ret = fgets(s, size, stream);
479         char *nl;
480
481         if (ret != NULL) {
482                 nl = strchr(s, '\n');
483
484                 if (nl != NULL)
485                         *nl = 0;
486         }
487
488         return ret;
489 }
490
491
492 // Escape a string for feeding out as a URL.
493 // outbuf the output buffer
494 // oblen the size of outbuf to sanitize
495 // strbuf the input buffer
496 void urlesc(char *outbuf, size_t oblen, char *strbuf) {
497         int a, b, c, len, eclen, olen;
498         char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
499
500         *outbuf = '\0';
501         len = strlen(strbuf);
502         eclen = strlen(ec);
503         olen = 0;
504         for (a = 0; a < len; ++a) {
505                 c = 0;
506                 for (b = 0; b < eclen; ++b) {
507                         if (strbuf[a] == ec[b])
508                                 c = 1;
509                 }
510                 if (c == 1) {
511                         snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
512                         olen += 3;
513                 }
514                 else 
515                         outbuf[olen ++] = strbuf[a];
516         }
517         outbuf[olen] = '\0';
518 }
519
520
521 // In our world, we want strcpy() to be able to work with overlapping strings.
522 #ifdef strcpy
523 #undef strcpy
524 #endif
525 char *strcpy(char *dest, const char *src) {
526         memmove(dest, src, (strlen(src) + 1) );
527         return(dest);
528 }
529
530
531 // Generate a new, globally unique UID parameter for a calendar etc. object
532 void generate_uuid(char *buf) {
533         static int seq = (-1);
534         static int no_kernel_uuid = 0;
535
536         // If we are running on Linux then we have a kernelspace uuid generator available
537
538         if (no_kernel_uuid == 0) {
539                 FILE *fp;
540                 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
541                 if (fp) {
542                         int rv;
543                         rv = fread(buf, 36, 1, fp);
544                         fclose(fp);
545                         if (rv == 1) {
546                                 buf[36] = 0;
547                                 return;
548                         }
549                 }
550         }
551
552         // If the kernel didn't provide us with a uuid, we generate a pseudo-random one
553
554         no_kernel_uuid = 1;
555
556         if (seq == (-1)) {
557                 seq = (int)rand();
558         }
559         ++seq;
560         seq = (seq % 0x0FFF) ;
561
562         sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
563                 (long)time(NULL),
564                 (long)getpid(),
565                 seq,
566                 seq,
567                 (long)rand()
568         );
569 }
570
571
572 // bmstrcasestr() -- case-insensitive substring search
573 //
574 // This uses the Boyer-Moore search algorithm and is therefore quite fast.
575 // The code is roughly based on the strstr() replacement from 'tin' written
576 // by Urs Jannsen.
577 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
578
579         register unsigned char *p, *t;
580         register int i, j, *delta;
581         register size_t p1;
582         int deltaspace[256];
583
584         if (!text) return(NULL);
585         if (!pattern) return(NULL);
586
587         // algorithm fails if pattern is empty
588         if ((p1 = patlen) == 0)
589                 return (text);
590
591         // code below fails (whenever i is unsigned) if pattern too long
592         if (p1 > textlen)
593                 return (NULL);
594
595         // set up deltas
596         delta = deltaspace;
597         for (i = 0; i <= 255; i++)
598                 delta[i] = p1;
599         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
600                 delta[tolower(*p++)] = i;
601
602         // From now on, we want patlen - 1.
603         // In the loop below, p points to the end of the pattern,
604         // t points to the end of the text to be tested against the
605         // pattern, and i counts the amount of text remaining, not
606         // including the part to be tested.
607         p1--;
608         p = (unsigned char *) pattern + p1;
609         t = (unsigned char *) text + p1;
610         i = textlen - patlen;
611         while(1) {
612                 if (tolower(p[0]) == tolower(t[0])) {
613                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
614                                 return ((char *)t - p1);
615                         }
616                 }
617                 j = delta[tolower(t[0])];
618                 if (i < j)
619                         break;
620                 i -= j;
621                 t += j;
622         }
623         return (NULL);
624 }
625
626
627 /*
628  * bmstrcasestr() -- case-insensitive substring search
629  *
630  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
631  * The code is roughly based on the strstr() replacement from 'tin' written
632  * by Urs Jannsen.
633  */
634 char *bmstrcasestr(char *text, const char *pattern) {
635         size_t textlen;
636         size_t patlen;
637
638         if (!text) return(NULL);
639         if (!pattern) return(NULL);
640
641         textlen = strlen (text);
642         patlen = strlen (pattern);
643
644         return _bmstrcasestr_len(text, textlen, pattern, patlen);
645 }
646
647 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
648         return _bmstrcasestr_len(text, textlen, pattern, patlen);
649 }
650
651
652 /*
653  * bmstrcasestr() -- case-insensitive substring search
654  *
655  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
656  * The code is roughly based on the strstr() replacement from 'tin' written
657  * by Urs Jannsen.
658  */
659 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
660
661         register unsigned char *p, *t;
662         register int i, j, *delta;
663         register size_t p1;
664         int deltaspace[256];
665
666         if (!text) return(NULL);
667         if (!pattern) return(NULL);
668
669         /* algorithm fails if pattern is empty */
670         if ((p1 = patlen) == 0)
671                 return (text);
672
673         /* code below fails (whenever i is unsigned) if pattern too long */
674         if (p1 > textlen)
675                 return (NULL);
676
677         /* set up deltas */
678         delta = deltaspace;
679         for (i = 0; i <= 255; i++)
680                 delta[i] = p1;
681         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
682                 delta[tolower(*p++)] = i;
683
684         /*
685          * From now on, we want patlen - 1.
686          * In the loop below, p points to the end of the pattern,
687          * t points to the end of the text to be tested against the
688          * pattern, and i counts the amount of text remaining, not
689          * including the part to be tested.
690          */
691         p1--;
692         p = (unsigned char *) pattern + p1;
693         t = (unsigned char *) text + p1;
694         i = textlen - patlen;
695         while(1) {
696                 if (tolower(p[0]) == tolower(t[0])) {
697                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
698                                 return ((char *)t - p1);
699                         }
700                 }
701                 j = delta[tolower(t[0])];
702                 if (i < j)
703                         break;
704                 i -= j;
705                 t += j;
706         }
707         return (NULL);
708 }
709
710
711 /*
712  * bmstrcasestr() -- case-insensitive substring search
713  *
714  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
715  * The code is roughly based on the strstr() replacement from 'tin' written
716  * by Urs Jannsen.
717  */
718 const char *cbmstrcasestr(const char *text, const char *pattern) {
719         size_t textlen;
720         size_t patlen;
721
722         if (!text) return(NULL);
723         if (!pattern) return(NULL);
724
725         textlen = strlen (text);
726         patlen = strlen (pattern);
727
728         return _cbmstrcasestr_len(text, textlen, pattern, patlen);
729 }
730
731
732 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
733         return _cbmstrcasestr_len(text, textlen, pattern, patlen);
734 }
735
736
737 /*
738  * Local replacement for controversial C library function that generates
739  * names for temporary files.  Included to shut up compiler warnings.
740  */
741 void CtdlMakeTempFileName(char *name, int len) {
742         int i = 0;
743
744         while (i++, i < 100) {
745                 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
746                         (long)getpid(),
747                         rand()
748                 );
749                 if (!access(name, F_OK)) {
750                         return;
751                 }
752         }
753 }
754
755
756 /*
757  * Determine whether the specified message number is contained within the specified set.
758  * Returns nonzero if the specified message number is in the specified message set string.
759  */
760 int is_msg_in_mset(const char *mset, long msgnum) {
761         int num_sets;
762         int s;
763         char setstr[SIZ], lostr[SIZ], histr[SIZ];
764         long lo, hi;
765
766         // Now set it for all specified messages.
767         num_sets = num_tokens(mset, ',');
768         for (s=0; s<num_sets; ++s) {
769                 extract_token(setstr, mset, s, ',', sizeof setstr);
770
771                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
772                 if (num_tokens(setstr, ':') >= 2) {
773                         extract_token(histr, setstr, 1, ':', sizeof histr);
774                         if (!strcmp(histr, "*")) {
775                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
776                         }
777                 }
778                 else {
779                         strcpy(histr, lostr);
780                 }
781                 lo = atol(lostr);
782                 hi = atol(histr);
783
784                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
785         }
786
787         return(0);
788 }
789
790
791 // searches for a pattern within a search string
792 // returns position in string
793 int pattern2(char *search, char *patn) {
794         int a;
795         int len, plen;
796         len = strlen (search);
797         plen = strlen (patn);
798         for (a = 0; a < len; ++a) {
799                 if (!strncasecmp(&search[a], patn, plen))
800                         return (a);
801         }
802         return (-1);
803 }
804
805
806 /*
807  * Convert all whitespace characters in a supplied string to underscores
808  */
809 void convert_spaces_to_underscores(char *str) {
810         int len;
811         int i;
812
813         if (!str) return;
814
815         len = strlen(str);
816         for (i=0; i<len; ++i) {
817                 if (isspace(str[i])) {
818                         str[i] = '_';
819                 }
820         }
821 }
822
823
824 /*
825  * check whether the provided string needs to be qp encoded or not
826  */
827 int CheckEncode(const char *pch, long len, const char *pche) {
828         if (pche == NULL)
829                 pche = pch + len;
830         while (pch < pche) {
831                 if (((unsigned char) *pch < 32) || 
832                     ((unsigned char) *pch > 126)) {
833                         return 1;
834                 }
835                 pch++;
836         }
837         return 0;
838 }
839