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