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