utf8ify_rfc822_string() is in libcitadel now
[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 striplt(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 {
287         const char *ptr;
288         int b;
289         b = 0;
290         ptr = st;
291         while (!IsEmptyStr(ptr))
292         {
293                 if (*ptr == ch)
294                         ++b;
295                 ptr ++;
296         }
297         return (b);
298 }
299
300
301 /*
302  * Determine whether the specified message number is contained within the
303  * specified sequence set.
304  */
305 int is_msg_in_sequence_set(const char *mset, long msgnum)
306 {
307         int num_sets;
308         int s;
309         char setstr[128], lostr[128], histr[128];
310         long lo, hi;
311
312         num_sets = num_tokens(mset, ',');
313         for (s=0; s<num_sets; ++s) {
314                 extract_token(setstr, mset, s, ',', sizeof setstr);
315
316                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
317                 if (num_tokens(setstr, ':') >= 2)
318                 {
319                         extract_token(histr, setstr, 1, ':', sizeof histr);
320                         if (!strcmp(histr, "*"))
321                         {
322                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
323                         }
324                 } 
325                 else
326                 {
327                         strcpy(histr, lostr);
328                 }
329                 lo = atol(lostr);
330                 hi = atol(histr);
331
332                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
333         }
334
335         return(0);
336 }
337
338 /* 
339  * Utility function to "readline" from memory
340  * start        Location in memory from which we are reading.
341  * buf          the buffer to place the string in.
342  * maxlen       Size of string buffer
343  * returns pointer to the source memory right after we stopped reading.
344  */
345 char *memreadline(char *start, char *buf, int maxlen)
346 {
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                         return ptr;
361                 }
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  * retlen       the length of the returned string
372  * returns a pointer to the source memory right after we stopped reading.
373  */
374 char *memreadlinelen(char *start, char *buf, int maxlen, int *retlen)
375 {
376         char ch;
377         char *ptr;
378         int len = 0;            /* tally our own length to avoid strlen() delays */
379
380         ptr = start;
381
382         while (1)
383         {
384                 ch = *ptr++;
385                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10))
386                 {
387                         buf[len++] = ch;
388                 }
389                 if ((ch == 10) || (ch == 0))
390                 {
391                         buf[len] = 0;
392                         *retlen = len;
393                         return ptr;
394                 }
395         }
396 }
397
398
399 /** 
400  * \brief Utility function to "readline" from memory
401  * \param start Location in memory from which we are reading.
402  * \param buf the buffer to place the string in.
403  * \param maxlen Size of string buffer
404  * \return Pointer to the source memory right after we stopped reading.
405  */
406 const char *cmemreadline(const char *start, char *buf, int maxlen)
407 {
408         char ch;
409         const char *ptr;
410         int len = 0;            /**< tally our own length to avoid strlen() delays */
411
412         ptr = start;
413
414         while (1) {
415                 ch = *ptr++;
416                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
417                         buf[len++] = ch;
418                 }
419                 if ((ch == 10) || (ch == 0)) {
420                         buf[len] = 0;
421                         return ptr;
422                 }
423         }
424 }
425
426
427 /** 
428  * \brief Utility function to "readline" from memory
429  * \param start Location in memory from which we are reading.
430  * \param buf the buffer to place the string in.
431  * \param maxlen Size of string buffer
432  * \param retlen the length of the returned string
433  * \return Pointer to the source memory right after we stopped reading.
434  */
435 const char *cmemreadlinelen(const char *start, char *buf, int maxlen, int *retlen)
436 {
437         char ch;
438         const char *ptr;
439         int len = 0;            /**< tally our own length to avoid strlen() delays */
440
441         ptr = start;
442
443         while (1) {
444                 ch = *ptr++;
445                 if ((len + 1 < (maxlen)) && (ch != 13) && (ch != 10)) {
446                         buf[len++] = ch;
447                 }
448                 if ((ch == 10) || (ch == 0)) {
449                         buf[len] = 0;
450                         *retlen = len;
451                         return ptr;
452                 }
453         }
454 }
455
456
457 /*
458  * Strip a boundarized substring out of a string (for example, remove
459  * parentheses and anything inside them).
460  */
461 int stripout(char *str, char leftboundary, char rightboundary) {
462         int a;
463         int lb = (-1);
464         int rb = (-1);
465
466         for (a = 0; a < strlen(str); ++a) {
467                 if (str[a] == leftboundary) lb = a;
468                 if (str[a] == rightboundary) rb = a;
469         }
470
471         if ( (lb > 0) && (rb > lb) ) {
472                 strcpy(&str[lb - 1], &str[rb + 1]);
473                 return 1;
474         }
475
476         else if ( (lb == 0) && (rb > lb) ) {
477                 strcpy(str, &str[rb + 1]);
478                 return 1;
479         }
480         return 0;
481 }
482
483
484 /*
485  * Reduce a string down to a boundarized substring (for example, remove
486  * parentheses and anything outside them).
487  */
488 long stripallbut(char *str, char leftboundary, char rightboundary) {
489         long len = 0;
490
491         char *lb = NULL;
492         char *rb = NULL;
493
494         lb = strrchr(str, leftboundary);
495         if (lb != NULL) {
496                 ++lb;
497                 rb = strchr(str, rightboundary);
498                 if ((rb != NULL) && (rb >= lb))  {
499                         *rb = 0;
500                         fflush(stderr);
501                         len = (long)rb - (long)lb;
502                         memmove(str, lb, len);
503                         str[len] = 0;
504                         return(len);
505                 }
506         }
507
508         return (long)strlen(str);
509 }
510
511
512 char *myfgets(char *s, int size, FILE *stream) {
513         char *ret = fgets(s, size, stream);
514         char *nl;
515
516         if (ret != NULL) {
517                 nl = strchr(s, '\n');
518
519                 if (nl != NULL)
520                         *nl = 0;
521         }
522
523         return ret;
524 }
525
526 /** 
527  * \brief Escape a string for feeding out as a URL.
528  * \param outbuf the output buffer
529  * \param oblen the size of outbuf to sanitize
530  * \param strbuf the input buffer
531  */
532 void urlesc(char *outbuf, size_t oblen, char *strbuf)
533 {
534         int a, b, c, len, eclen, olen;
535         char *ec = " +#&;`'|*?-~<>^()[]{}/$\"\\";
536
537         *outbuf = '\0';
538         len = strlen(strbuf);
539         eclen = strlen(ec);
540         olen = 0;
541         for (a = 0; a < len; ++a) {
542                 c = 0;
543                 for (b = 0; b < eclen; ++b) {
544                         if (strbuf[a] == ec[b])
545                                 c = 1;
546                 }
547                 if (c == 1) {
548                         snprintf(&outbuf[olen], oblen - olen, "%%%02x", strbuf[a]);
549                         olen += 3;
550                 }
551                 else 
552                         outbuf[olen ++] = strbuf[a];
553         }
554         outbuf[olen] = '\0';
555 }
556
557
558
559 /*
560  * In our world, we want strcpy() to be able to work with overlapping strings.
561  */
562 #ifdef strcpy
563 #undef strcpy
564 #endif
565 char *strcpy(char *dest, const char *src) {
566         memmove(dest, src, (strlen(src) + 1) );
567         return(dest);
568 }
569
570
571 /*
572  * Generate a new, globally unique UID parameter for a calendar etc. object
573  */
574 void generate_uuid(char *buf) {
575         static int seq = (-1);
576         static int no_kernel_uuid = 0;
577
578         /* If we are running on Linux then we have a kernelspace uuid generator available */
579
580         if (no_kernel_uuid == 0) {
581                 FILE *fp;
582                 fp = fopen("/proc/sys/kernel/random/uuid", "rb");
583                 if (fp) {
584                         int rv;
585                         rv = fread(buf, 36, 1, fp);
586                         fclose(fp);
587                         if (rv == 1) {
588                                 buf[36] = 0;
589                                 return;
590                         }
591                 }
592         }
593
594         /* If the kernel didn't provide us with a uuid, we generate a pseudo-random one */
595
596         no_kernel_uuid = 1;
597
598         if (seq == (-1)) {
599                 seq = (int)rand();
600         }
601         ++seq;
602         seq = (seq % 0x0FFF) ;
603
604         sprintf(buf, "%08lx-%04lx-4%03x-a%03x-%012lx",
605                 (long)time(NULL),
606                 (long)getpid(),
607                 seq,
608                 seq,
609                 (long)rand()
610         );
611 }
612
613 /*
614  * bmstrcasestr() -- case-insensitive substring search
615  *
616  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
617  * The code is roughly based on the strstr() replacement from 'tin' written
618  * by Urs Jannsen.
619  */
620 inline static char *_bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
621
622         register unsigned char *p, *t;
623         register int i, j, *delta;
624         register size_t p1;
625         int deltaspace[256];
626
627         if (!text) return(NULL);
628         if (!pattern) return(NULL);
629
630         /* algorithm fails if pattern is empty */
631         if ((p1 = patlen) == 0)
632                 return (text);
633
634         /* code below fails (whenever i is unsigned) if pattern too long */
635         if (p1 > textlen)
636                 return (NULL);
637
638         /* set up deltas */
639         delta = deltaspace;
640         for (i = 0; i <= 255; i++)
641                 delta[i] = p1;
642         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
643                 delta[tolower(*p++)] = i;
644
645         /*
646          * From now on, we want patlen - 1.
647          * In the loop below, p points to the end of the pattern,
648          * t points to the end of the text to be tested against the
649          * pattern, and i counts the amount of text remaining, not
650          * including the part to be tested.
651          */
652         p1--;
653         p = (unsigned char *) pattern + p1;
654         t = (unsigned char *) text + p1;
655         i = textlen - patlen;
656         while(1) {
657                 if (tolower(p[0]) == tolower(t[0])) {
658                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
659                                 return ((char *)t - p1);
660                         }
661                 }
662                 j = delta[tolower(t[0])];
663                 if (i < j)
664                         break;
665                 i -= j;
666                 t += j;
667         }
668         return (NULL);
669 }
670
671 /*
672  * bmstrcasestr() -- case-insensitive substring search
673  *
674  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
675  * The code is roughly based on the strstr() replacement from 'tin' written
676  * by Urs Jannsen.
677  */
678 char *bmstrcasestr(char *text, const char *pattern) {
679         size_t textlen;
680         size_t patlen;
681
682         if (!text) return(NULL);
683         if (!pattern) return(NULL);
684
685         textlen = strlen (text);
686         patlen = strlen (pattern);
687
688         return _bmstrcasestr_len(text, textlen, pattern, patlen);
689 }
690
691 char *bmstrcasestr_len(char *text, size_t textlen, const char *pattern, size_t patlen) {
692         return _bmstrcasestr_len(text, textlen, pattern, patlen);
693 }
694
695
696
697
698 /*
699  * bmstrcasestr() -- case-insensitive substring search
700  *
701  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
702  * The code is roughly based on the strstr() replacement from 'tin' written
703  * by Urs Jannsen.
704  */
705 inline static const char *_cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
706
707         register unsigned char *p, *t;
708         register int i, j, *delta;
709         register size_t p1;
710         int deltaspace[256];
711
712         if (!text) return(NULL);
713         if (!pattern) return(NULL);
714
715         /* algorithm fails if pattern is empty */
716         if ((p1 = patlen) == 0)
717                 return (text);
718
719         /* code below fails (whenever i is unsigned) if pattern too long */
720         if (p1 > textlen)
721                 return (NULL);
722
723         /* set up deltas */
724         delta = deltaspace;
725         for (i = 0; i <= 255; i++)
726                 delta[i] = p1;
727         for (p = (unsigned char *) pattern, i = p1; --i > 0;)
728                 delta[tolower(*p++)] = i;
729
730         /*
731          * From now on, we want patlen - 1.
732          * In the loop below, p points to the end of the pattern,
733          * t points to the end of the text to be tested against the
734          * pattern, and i counts the amount of text remaining, not
735          * including the part to be tested.
736          */
737         p1--;
738         p = (unsigned char *) pattern + p1;
739         t = (unsigned char *) text + p1;
740         i = textlen - patlen;
741         while(1) {
742                 if (tolower(p[0]) == tolower(t[0])) {
743                         if (strncasecmp ((const char *)(p - p1), (const char *)(t - p1), p1) == 0) {
744                                 return ((char *)t - p1);
745                         }
746                 }
747                 j = delta[tolower(t[0])];
748                 if (i < j)
749                         break;
750                 i -= j;
751                 t += j;
752         }
753         return (NULL);
754 }
755
756 /*
757  * bmstrcasestr() -- case-insensitive substring search
758  *
759  * This uses the Boyer-Moore search algorithm and is therefore quite fast.
760  * The code is roughly based on the strstr() replacement from 'tin' written
761  * by Urs Jannsen.
762  */
763 const char *cbmstrcasestr(const char *text, const char *pattern) {
764         size_t textlen;
765         size_t patlen;
766
767         if (!text) return(NULL);
768         if (!pattern) return(NULL);
769
770         textlen = strlen (text);
771         patlen = strlen (pattern);
772
773         return _cbmstrcasestr_len(text, textlen, pattern, patlen);
774 }
775
776 const char *cbmstrcasestr_len(const char *text, size_t textlen, const char *pattern, size_t patlen) {
777         return _cbmstrcasestr_len(text, textlen, pattern, patlen);
778 }
779
780 /*
781  * Local replacement for controversial C library function that generates
782  * names for temporary files.  Included to shut up compiler warnings.
783  */
784 void CtdlMakeTempFileName(char *name, int len) {
785         int i = 0;
786
787         while (i++, i < 100) {
788                 snprintf(name, len, "/tmp/ctdl.%04lx.%04x",
789                         (long)getpid(),
790                         rand()
791                 );
792                 if (!access(name, F_OK)) {
793                         return;
794                 }
795         }
796 }
797
798
799
800 /*
801  * Determine whether the specified message number is contained within the specified set.
802  * Returns nonzero if the specified message number is in the specified message set string.
803  */
804 int is_msg_in_mset(const char *mset, long msgnum) {
805         int num_sets;
806         int s;
807         char setstr[SIZ], lostr[SIZ], histr[SIZ];       /* was 1024 */
808         long lo, hi;
809
810         /*
811          * Now set it for all specified messages.
812          */
813         num_sets = num_tokens(mset, ',');
814         for (s=0; s<num_sets; ++s) {
815                 extract_token(setstr, mset, s, ',', sizeof setstr);
816
817                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
818                 if (num_tokens(setstr, ':') >= 2) {
819                         extract_token(histr, setstr, 1, ':', sizeof histr);
820                         if (!strcmp(histr, "*")) {
821                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
822                         }
823                 }
824                 else {
825                         strcpy(histr, lostr);
826                 }
827                 lo = atol(lostr);
828                 hi = atol(histr);
829
830                 if ((msgnum >= lo) && (msgnum <= hi)) return(1);
831         }
832
833         return(0);
834 }
835
836
837 /*
838  * searches for a pattern within a search string
839  * returns position in string
840  */
841 int pattern2(char *search, char *patn)
842 {
843         int a;
844         int len, plen;
845         len = strlen (search);
846         plen = strlen (patn);
847         for (a = 0; a < len; ++a) {
848                 if (!strncasecmp(&search[a], patn, plen))
849                         return (a);
850         }
851         return (-1);
852 }
853
854
855 /*
856  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
857  * buf - the string to modify
858  * len - length of the string. 
859  */
860 void stripltlen(char *buf, int *len)
861 {
862         int delta = 0;
863         if (*len == 0) return;
864         while ((*len > delta) && (isspace(buf[delta]))){
865                 delta ++;
866         }
867         memmove (buf, &buf[delta], *len - delta + 1);
868         (*len) -=delta;
869
870         if (*len == 0) return;
871         while (isspace(buf[(*len) - 1])){
872                 buf[--(*len)] = '\0';
873         }
874 }
875
876
877 /*
878  * Convert all whitespace characters in a supplied string to underscores
879  */
880 void convert_spaces_to_underscores(char *str)
881 {
882         int len;
883         int i;
884
885         if (!str) return;
886
887         len = strlen(str);
888         for (i=0; i<len; ++i) {
889                 if (isspace(str[i])) {
890                         str[i] = '_';
891                 }
892         }
893 }
894
895
896 /*
897  * check whether the provided string needs to be qp encoded or not
898  */
899 int CheckEncode(const char *pch, long len, const char *pche)
900 {
901         if (pche == NULL)
902                 pche = pch + len;
903         while (pch < pche) {
904                 if (((unsigned char) *pch < 32) || 
905                     ((unsigned char) *pch > 126)) {
906                         return 1;
907                 }
908                 pch++;
909         }
910         return 0;
911 }
912