* add StrBufSmash() so functions demanding a non-const char* can better cooperate.
[citadel.git] / libcitadel / lib / stringbuf.c
1 #include "../sysdep.h"
2 #include <ctype.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <sys/select.h>
9 #include <fcntl.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
12 #include <stdarg.h>
13 #include "libcitadel.h"
14
15 #ifdef HAVE_ICONV
16 #include <iconv.h>
17 #endif
18
19 #if HAVE_BACKTRACE
20 #include <execinfo.h>
21 #endif
22
23 #ifdef HAVE_ZLIB
24 #include <zlib.h>
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26                           const Bytef * source, uLong sourceLen, int level);
27 #endif
28 int BaseStrBufSize = 64;
29
30 const char *StrBufNOTNULL = ((char*) NULL) - 1;
31
32 /**
33  * Private Structure for the Stringbuffer
34  */
35 struct StrBuf {
36         char *buf;         /**< the pointer to the dynamic buffer */
37         long BufSize;      /**< how many spcae do we optain */
38         long BufUsed;      /**< StNumber of Chars used excluding the trailing \0 */
39         int ConstBuf;      /**< are we just a wrapper arround a static buffer and musn't we be changed? */
40 #ifdef SIZE_DEBUG
41         long nIncreases;
42         char bt [SIZ];
43         char bt_lastinc [SIZ];
44 #endif
45 };
46
47 #ifdef SIZE_DEBUG
48 #if HAVE_BACKTRACE
49 static void StrBufBacktrace(StrBuf *Buf, int which)
50 {
51         int n;
52         char *pstart, *pch;
53         void *stack_frames[50];
54         size_t size, i;
55         char **strings;
56
57         if (which)
58                 pstart = pch = Buf->bt;
59         else
60                 pstart = pch = Buf->bt_lastinc;
61         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
62         strings = backtrace_symbols(stack_frames, size);
63         for (i = 0; i < size; i++) {
64                 if (strings != NULL)
65                         n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
66                 else
67                         n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
68                 pch += n;
69         }
70         free(strings);
71
72
73 }
74 #endif
75 #endif
76
77 /** 
78  * \Brief Cast operator to Plain String 
79  * Note: if the buffer is altered by StrBuf operations, this pointer may become 
80  *  invalid. So don't lean on it after altering the buffer!
81  *  Since this operation is considered cheap, rather call it often than risking
82  *  your pointer to become invalid!
83  * \param Str the string we want to get the c-string representation for
84  * \returns the Pointer to the Content. Don't mess with it!
85  */
86 inline const char *ChrPtr(const StrBuf *Str)
87 {
88         if (Str == NULL)
89                 return "";
90         return Str->buf;
91 }
92
93 /**
94  * \brief since we know strlen()'s result, provide it here.
95  * \param Str the string to return the length to
96  * \returns contentlength of the buffer
97  */
98 inline int StrLength(const StrBuf *Str)
99 {
100         return (Str != NULL) ? Str->BufUsed : 0;
101 }
102
103 /**
104  * \brief local utility function to resize the buffer
105  * \param Buf the buffer whichs storage we should increase
106  * \param KeepOriginal should we copy the original buffer or just start over with a new one
107  * \param DestSize what should fit in after?
108  */
109 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
110 {
111         char *NewBuf;
112         size_t NewSize = Buf->BufSize * 2;
113
114         if (Buf->ConstBuf)
115                 return -1;
116                 
117         if (DestSize > 0)
118                 while (NewSize <= DestSize)
119                         NewSize *= 2;
120
121         NewBuf= (char*) malloc(NewSize);
122         if (NewBuf == NULL)
123                 return -1;
124
125         if (KeepOriginal && (Buf->BufUsed > 0))
126         {
127                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
128         }
129         else
130         {
131                 NewBuf[0] = '\0';
132                 Buf->BufUsed = 0;
133         }
134         free (Buf->buf);
135         Buf->buf = NewBuf;
136         Buf->BufSize = NewSize;
137 #ifdef SIZE_DEBUG
138         Buf->nIncreases++;
139 #if HAVE_BACKTRACE
140         StrBufBacktrace(Buf, 1);
141 #endif
142 #endif
143         return Buf->BufSize;
144 }
145
146 /**
147  * \brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
148  * \param Buf Buffer to shrink (has to be empty)
149  * \param ThreshHold if the buffer is bigger then this, its readjusted
150  * \param NewSize if we Shrink it, how big are we going to be afterwards?
151  */
152 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
153 {
154         if (Buf->BufUsed > ThreshHold) {
155                 free(Buf->buf);
156                 Buf->buf = (char*) malloc(NewSize);
157                 Buf->BufUsed = 0;
158                 Buf->BufSize = NewSize;
159         }
160 }
161
162 /**
163  * \brief shrink long term buffers to their real size so they don't waste memory
164  * \param Buf buffer to shrink
165  * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
166  * \returns physical size of the buffer
167  */
168 long StrBufShrinkToFit(StrBuf *Buf, int Force)
169 {
170         if (Force || 
171             (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
172         {
173                 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
174                 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
175                 Buf->BufSize = Buf->BufUsed + 1;
176                 free(Buf->buf);
177                 Buf->buf = TmpBuf;
178         }
179         return Buf->BufUsed;
180 }
181
182 /**
183  * Allocate a new buffer with default buffer size
184  * \returns the new stringbuffer
185  */
186 StrBuf* NewStrBuf(void)
187 {
188         StrBuf *NewBuf;
189
190         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
191         NewBuf->buf = (char*) malloc(BaseStrBufSize);
192         NewBuf->buf[0] = '\0';
193         NewBuf->BufSize = BaseStrBufSize;
194         NewBuf->BufUsed = 0;
195         NewBuf->ConstBuf = 0;
196 #ifdef SIZE_DEBUG
197         NewBuf->nIncreases = 0;
198         NewBuf->bt[0] = '\0';
199         NewBuf->bt_lastinc[0] = '\0';
200 #if HAVE_BACKTRACE
201         StrBufBacktrace(NewBuf, 0);
202 #endif
203 #endif
204         return NewBuf;
205 }
206
207 /** 
208  * \brief Copy Constructor; returns a duplicate of CopyMe
209  * \params CopyMe Buffer to faxmilate
210  * \returns the new stringbuffer
211  */
212 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
213 {
214         StrBuf *NewBuf;
215         
216         if (CopyMe == NULL)
217                 return NewStrBuf();
218
219         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
220         NewBuf->buf = (char*) malloc(CopyMe->BufSize);
221         memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
222         NewBuf->BufUsed = CopyMe->BufUsed;
223         NewBuf->BufSize = CopyMe->BufSize;
224         NewBuf->ConstBuf = 0;
225 #ifdef SIZE_DEBUG
226         NewBuf->nIncreases = 0;
227         NewBuf->bt[0] = '\0';
228         NewBuf->bt_lastinc[0] = '\0';
229 #if HAVE_BACKTRACE
230         StrBufBacktrace(NewBuf, 0);
231 #endif
232 #endif
233         return NewBuf;
234 }
235
236 /**
237  * \brief create a new Buffer using an existing c-string
238  * this function should also be used if you want to pre-suggest
239  * the buffer size to allocate in conjunction with ptr == NULL
240  * \param ptr the c-string to copy; may be NULL to create a blank instance
241  * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
242  * \returns the new stringbuffer
243  */
244 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
245 {
246         StrBuf *NewBuf;
247         size_t Siz = BaseStrBufSize;
248         size_t CopySize;
249
250         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
251         if (nChars < 0)
252                 CopySize = strlen((ptr != NULL)?ptr:"");
253         else
254                 CopySize = nChars;
255
256         while (Siz <= CopySize)
257                 Siz *= 2;
258
259         NewBuf->buf = (char*) malloc(Siz);
260         NewBuf->BufSize = Siz;
261         if (ptr != NULL) {
262                 memcpy(NewBuf->buf, ptr, CopySize);
263                 NewBuf->buf[CopySize] = '\0';
264                 NewBuf->BufUsed = CopySize;
265         }
266         else {
267                 NewBuf->buf[0] = '\0';
268                 NewBuf->BufUsed = 0;
269         }
270         NewBuf->ConstBuf = 0;
271 #ifdef SIZE_DEBUG
272         NewBuf->nIncreases = 0;
273         NewBuf->bt[0] = '\0';
274         NewBuf->bt_lastinc[0] = '\0';
275 #if HAVE_BACKTRACE
276         StrBufBacktrace(NewBuf, 0);
277 #endif
278 #endif
279         return NewBuf;
280 }
281
282 /**
283  * \brief Set an existing buffer from a c-string
284  * \param ptr c-string to put into 
285  * \param nChars set to -1 if we should work 0-terminated
286  * \returns the new length of the string
287  */
288 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
289 {
290         size_t Siz = Buf->BufSize;
291         size_t CopySize;
292
293         if (nChars < 0)
294                 CopySize = strlen(ptr);
295         else
296                 CopySize = nChars;
297
298         while (Siz <= CopySize)
299                 Siz *= 2;
300
301         if (Siz != Buf->BufSize)
302                 IncreaseBuf(Buf, 0, Siz);
303         memcpy(Buf->buf, ptr, CopySize);
304         Buf->buf[CopySize] = '\0';
305         Buf->BufUsed = CopySize;
306         Buf->ConstBuf = 0;
307         return CopySize;
308 }
309
310
311 /**
312  * \brief use strbuf as wrapper for a string constant for easy handling
313  * \param StringConstant a string to wrap
314  * \param SizeOfConstant should be sizeof(StringConstant)-1
315  */
316 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
317 {
318         StrBuf *NewBuf;
319
320         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
321         NewBuf->buf = (char*) StringConstant;
322         NewBuf->BufSize = SizeOfStrConstant;
323         NewBuf->BufUsed = SizeOfStrConstant;
324         NewBuf->ConstBuf = 1;
325 #ifdef SIZE_DEBUG
326         NewBuf->nIncreases = 0;
327         NewBuf->bt[0] = '\0';
328         NewBuf->bt_lastinc[0] = '\0';
329 #endif
330         return NewBuf;
331 }
332
333
334 /**
335  * \brief flush the content of a Buf; keep its struct
336  * \param buf Buffer to flush
337  */
338 int FlushStrBuf(StrBuf *buf)
339 {
340         if (buf == NULL)
341                 return -1;
342         if (buf->ConstBuf)
343                 return -1;       
344         buf->buf[0] ='\0';
345         buf->BufUsed = 0;
346         return 0;
347 }
348
349 /**
350  * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
351  * \param buf Buffer to wipe
352  */
353 int FLUSHStrBuf(StrBuf *buf)
354 {
355         if (buf == NULL)
356                 return -1;
357         if (buf->ConstBuf)
358                 return -1;
359         if (buf->BufUsed > 0) {
360                 memset(buf->buf, 0, buf->BufUsed);
361                 buf->BufUsed = 0;
362         }
363         return 0;
364 }
365
366 #ifdef SIZE_DEBUG
367 int hFreeDbglog = -1;
368 #endif
369 /**
370  * \brief Release a Buffer
371  * Its a double pointer, so it can NULL your pointer
372  * so fancy SIG11 appear instead of random results
373  * \param FreeMe Pointer Pointer to the buffer to free
374  */
375 void FreeStrBuf (StrBuf **FreeMe)
376 {
377         if (*FreeMe == NULL)
378                 return;
379 #ifdef SIZE_DEBUG
380         if (hFreeDbglog == -1){
381                 pid_t pid = getpid();
382                 char path [SIZ];
383                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
384                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
385         }
386         if ((*FreeMe)->nIncreases > 0)
387         {
388                 char buf[SIZ * 3];
389                 long n;
390                 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
391                              (*FreeMe)->nIncreases,
392                              (*FreeMe)->BufUsed,
393                              (*FreeMe)->BufSize,
394                              (*FreeMe)->bt,
395                              (*FreeMe)->bt_lastinc);
396                 n = write(hFreeDbglog, buf, n);
397         }
398         else
399         {
400                 char buf[128];
401                 long n;
402                 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
403                              (*FreeMe)->BufUsed,
404                              (*FreeMe)->BufSize);
405                 n = write(hFreeDbglog, buf, n);
406         }
407 #endif
408         if (!(*FreeMe)->ConstBuf) 
409                 free((*FreeMe)->buf);
410         free(*FreeMe);
411         *FreeMe = NULL;
412 }
413
414 /**
415  * \brief flatten a Buffer to the Char * we return 
416  * Its a double pointer, so it can NULL your pointer
417  * so fancy SIG11 appear instead of random results
418  * The Calle then owns the buffer and is responsible for freeing it.
419  * \param SmashMe Pointer Pointer to the buffer to release Buf from and free
420  * \return the pointer of the buffer; Callee owns the memory thereafter.
421  */
422 char *SmashStrBuf (StrBuf **SmashMe)
423 {
424         char *Ret;
425
426         if (*SmashMe == NULL)
427                 return NULL;
428 #ifdef SIZE_DEBUG
429         if (hFreeDbglog == -1){
430                 pid_t pid = getpid();
431                 char path [SIZ];
432                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
433                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
434         }
435         if ((*SmashMe)->nIncreases > 0)
436         {
437                 char buf[SIZ * 3];
438                 long n;
439                 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
440                              (*SmashMe)->nIncreases,
441                              (*SmashMe)->BufUsed,
442                              (*SmashMe)->BufSize,
443                              (*SmashMe)->bt,
444                              (*SmashMe)->bt_lastinc);
445                 n = write(hFreeDbglog, buf, n);
446         }
447         else
448         {
449                 char buf[128];
450                 long n;
451                 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
452                              (*SmashMe)->BufUsed,
453                              (*SmashMe)->BufSize);
454                 n = write(hFreeDbglog, buf, n);
455         }
456 #endif
457         Ret = (*SmashMe)->buf;
458         free(*SmashMe);
459         *SmashMe = NULL;
460         return Ret;
461 }
462
463 /**
464  * \brief Release the buffer
465  * If you want put your StrBuf into a Hash, use this as Destructor.
466  * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
467  */
468 void HFreeStrBuf (void *VFreeMe)
469 {
470         StrBuf *FreeMe = (StrBuf*)VFreeMe;
471         if (FreeMe == NULL)
472                 return;
473 #ifdef SIZE_DEBUG
474         if (hFreeDbglog == -1){
475                 pid_t pid = getpid();
476                 char path [SIZ];
477                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
478                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
479         }
480         if (FreeMe->nIncreases > 0)
481         {
482                 char buf[SIZ * 3];
483                 long n;
484                 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
485                              FreeMe->nIncreases,
486                              FreeMe->BufUsed,
487                              FreeMe->BufSize,
488                              FreeMe->bt,
489                              FreeMe->bt_lastinc);
490                 write(hFreeDbglog, buf, n);
491         }
492         else
493         {
494                 char buf[128];
495                 long n;
496                 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
497                              FreeMe->nIncreases,
498                              FreeMe->BufUsed,
499                              FreeMe->BufSize);
500         }
501 #endif
502         if (!FreeMe->ConstBuf) 
503                 free(FreeMe->buf);
504         free(FreeMe);
505 }
506
507 /**
508  * \brief Wrapper around atol
509  */
510 long StrTol(const StrBuf *Buf)
511 {
512         if (Buf == NULL)
513                 return 0;
514         if(Buf->BufUsed > 0)
515                 return atol(Buf->buf);
516         else
517                 return 0;
518 }
519
520 /**
521  * \brief Wrapper around atoi
522  */
523 int StrToi(const StrBuf *Buf)
524 {
525         if (Buf == NULL)
526                 return 0;
527         if (Buf->BufUsed > 0)
528                 return atoi(Buf->buf);
529         else
530                 return 0;
531 }
532
533 /**
534  * \brief Checks to see if the string is a pure number 
535  */
536 int StrBufIsNumber(const StrBuf *Buf) {
537   char * pEnd;
538   if (Buf == NULL) {
539         return 0;
540   }
541   strtoll(Buf->buf, &pEnd, 10);
542   if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
543     return 1;
544   }
545   return 0;
546
547 /**
548  * \brief modifies a Single char of the Buf
549  * You can point to it via char* or a zero-based integer
550  * \param ptr char* to zero; use NULL if unused
551  * \param nThChar zero based pointer into the string; use -1 if unused
552  * \param PeekValue The Character to place into the position
553  */
554 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
555 {
556         if (Buf == NULL)
557                 return -1;
558         if (ptr != NULL)
559                 nThChar = ptr - Buf->buf;
560         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
561                 return -1;
562         Buf->buf[nThChar] = PeekValue;
563         return nThChar;
564 }
565
566 /**
567  * \brief Append a StringBuffer to the buffer
568  * \param Buf Buffer to modify
569  * \param AppendBuf Buffer to copy at the end of our buffer
570  * \param Offset Should we start copying from an offset?
571  */
572 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
573 {
574         if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
575                 return;
576
577         if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
578                 IncreaseBuf(Buf, 
579                             (Buf->BufUsed > 0), 
580                             AppendBuf->BufUsed + Buf->BufUsed);
581
582         memcpy(Buf->buf + Buf->BufUsed, 
583                AppendBuf->buf + Offset, 
584                AppendBuf->BufUsed - Offset);
585         Buf->BufUsed += AppendBuf->BufUsed - Offset;
586         Buf->buf[Buf->BufUsed] = '\0';
587 }
588
589
590 /**
591  * \brief Append a C-String to the buffer
592  * \param Buf Buffer to modify
593  * \param AppendBuf Buffer to copy at the end of our buffer
594  * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
595  * \param Offset Should we start copying from an offset?
596  */
597 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
598 {
599         long aps;
600         long BufSizeRequired;
601
602         if ((AppendBuf == NULL) || (Buf == NULL))
603                 return;
604
605         if (AppendSize < 0 )
606                 aps = strlen(AppendBuf + Offset);
607         else
608                 aps = AppendSize - Offset;
609
610         BufSizeRequired = Buf->BufUsed + aps + 1;
611         if (Buf->BufSize <= BufSizeRequired)
612                 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
613
614         memcpy(Buf->buf + Buf->BufUsed, 
615                AppendBuf + Offset, 
616                aps);
617         Buf->BufUsed += aps;
618         Buf->buf[Buf->BufUsed] = '\0';
619 }
620
621 /**
622  * \brief Callback for cURL to append the webserver reply to a buffer
623  * params pre-defined by the cURL API; see man 3 curl for mre info
624  */
625 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
626 {
627
628         StrBuf *Target;
629
630         Target = stream;
631         if (ptr == NULL)
632                 return 0;
633
634         StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
635         return size * nmemb;
636 }
637
638
639 /** 
640  * \brief Escape a string for feeding out as a URL while appending it to a Buffer
641  * \param outbuf the output buffer
642  * \param oblen the size of outbuf to sanitize
643  * \param strbuf the input buffer
644  */
645 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
646 {
647         const char *pch, *pche;
648         char *pt, *pte;
649         int b, c, len;
650         const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
651         int eclen = sizeof(ec) -1;
652
653         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
654                 return;
655         if (PlainIn != NULL) {
656                 len = strlen(PlainIn);
657                 pch = PlainIn;
658                 pche = pch + len;
659         }
660         else {
661                 pch = In->buf;
662                 pche = pch + In->BufUsed;
663                 len = In->BufUsed;
664         }
665
666         if (len == 0) 
667                 return;
668
669         pt = OutBuf->buf + OutBuf->BufUsed;
670         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
671
672         while (pch < pche) {
673                 if (pt >= pte) {
674                         IncreaseBuf(OutBuf, 1, -1);
675                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
676                         pt = OutBuf->buf + OutBuf->BufUsed;
677                 }
678                 
679                 c = 0;
680                 for (b = 0; b < eclen; ++b) {
681                         if (*pch == ec[b]) {
682                                 c = 1;
683                                 b += eclen;
684                         }
685                 }
686                 if (c == 1) {
687                         sprintf(pt,"%%%02X", *pch);
688                         pt += 3;
689                         OutBuf->BufUsed += 3;
690                         pch ++;
691                 }
692                 else {
693                         *(pt++) = *(pch++);
694                         OutBuf->BufUsed++;
695                 }
696         }
697         *pt = '\0';
698 }
699
700 /*
701  * \brief Append a string, escaping characters which have meaning in HTML.  
702  *
703  * \param Target        target buffer
704  * \param Source        source buffer; set to NULL if you just have a C-String
705  * \param PlainIn       Plain-C string to append; set to NULL if unused
706  * \param nbsp          If nonzero, spaces are converted to non-breaking spaces.
707  * \param nolinebreaks  if set to 1, linebreaks are removed from the string.
708  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
709  */
710 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
711 {
712         const char *aptr, *eiptr;
713         char *bptr, *eptr;
714         long len;
715
716         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
717                 return -1;
718
719         if (PlainIn != NULL) {
720                 aptr = PlainIn;
721                 len = strlen(PlainIn);
722                 eiptr = aptr + len;
723         }
724         else {
725                 aptr = Source->buf;
726                 eiptr = aptr + Source->BufUsed;
727                 len = Source->BufUsed;
728         }
729
730         if (len == 0) 
731                 return -1;
732
733         bptr = Target->buf + Target->BufUsed;
734         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
735
736         while (aptr < eiptr){
737                 if(bptr >= eptr) {
738                         IncreaseBuf(Target, 1, -1);
739                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
740                         bptr = Target->buf + Target->BufUsed;
741                 }
742                 if (*aptr == '<') {
743                         memcpy(bptr, "&lt;", 4);
744                         bptr += 4;
745                         Target->BufUsed += 4;
746                 }
747                 else if (*aptr == '>') {
748                         memcpy(bptr, "&gt;", 4);
749                         bptr += 4;
750                         Target->BufUsed += 4;
751                 }
752                 else if (*aptr == '&') {
753                         memcpy(bptr, "&amp;", 5);
754                         bptr += 5;
755                         Target->BufUsed += 5;
756                 }
757                 else if (*aptr == '"') {
758                         memcpy(bptr, "&quot;", 6);
759                         bptr += 6;
760                         Target->BufUsed += 6;
761                 }
762                 else if (*aptr == '\'') {
763                         memcpy(bptr, "&#39;", 5);
764                         bptr += 5;
765                         Target->BufUsed += 5;
766                 }
767                 else if (*aptr == LB) {
768                         *bptr = '<';
769                         bptr ++;
770                         Target->BufUsed ++;
771                 }
772                 else if (*aptr == RB) {
773                         *bptr = '>';
774                         bptr ++;
775                         Target->BufUsed ++;
776                 }
777                 else if (*aptr == QU) {
778                         *bptr ='"';
779                         bptr ++;
780                         Target->BufUsed ++;
781                 }
782                 else if ((*aptr == 32) && (nbsp == 1)) {
783                         memcpy(bptr, "&nbsp;", 6);
784                         bptr += 6;
785                         Target->BufUsed += 6;
786                 }
787                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
788                         *bptr='\0';     /* nothing */
789                 }
790                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
791                         memcpy(bptr, "&lt;br/&gt;", 11);
792                         bptr += 11;
793                         Target->BufUsed += 11;
794                 }
795
796
797                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
798                         *bptr='\0';     /* nothing */
799                 }
800                 else{
801                         *bptr = *aptr;
802                         bptr++;
803                         Target->BufUsed ++;
804                 }
805                 aptr ++;
806         }
807         *bptr = '\0';
808         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
809                 return -1;
810         return Target->BufUsed;
811 }
812
813 /*
814  * \brief Append a string, escaping characters which have meaning in HTML.  
815  * Converts linebreaks into blanks; escapes single quotes
816  * \param Target        target buffer
817  * \param Source        source buffer; set to NULL if you just have a C-String
818  * \param PlainIn       Plain-C string to append; set to NULL if unused
819  */
820 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
821 {
822         const char *aptr, *eiptr;
823         char *tptr, *eptr;
824         long len;
825
826         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
827                 return ;
828
829         if (PlainIn != NULL) {
830                 aptr = PlainIn;
831                 len = strlen(PlainIn);
832                 eiptr = aptr + len;
833         }
834         else {
835                 aptr = Source->buf;
836                 eiptr = aptr + Source->BufUsed;
837                 len = Source->BufUsed;
838         }
839
840         if (len == 0) 
841                 return;
842
843         eptr = Target->buf + Target->BufSize - 8; 
844         tptr = Target->buf + Target->BufUsed;
845         
846         while (aptr < eiptr){
847                 if(tptr >= eptr) {
848                         IncreaseBuf(Target, 1, -1);
849                         eptr = Target->buf + Target->BufSize - 8; 
850                         tptr = Target->buf + Target->BufUsed;
851                 }
852                
853                 if (*aptr == '\n') {
854                         *tptr = ' ';
855                         Target->BufUsed++;
856                 }
857                 else if (*aptr == '\r') {
858                         *tptr = ' ';
859                         Target->BufUsed++;
860                 }
861                 else if (*aptr == '\'') {
862                         *(tptr++) = '&';
863                         *(tptr++) = '#';
864                         *(tptr++) = '3';
865                         *(tptr++) = '9';
866                         *tptr = ';';
867                         Target->BufUsed += 5;
868                 } else {
869                         *tptr = *aptr;
870                         Target->BufUsed++;
871                 }
872                 tptr++; aptr++;
873         }
874         *tptr = '\0';
875 }
876
877
878
879 /*
880  * \brief Append a string, escaping characters which have meaning in ICAL.  
881  * [\n,] 
882  * \param Target        target buffer
883  * \param Source        source buffer; set to NULL if you just have a C-String
884  * \param PlainIn       Plain-C string to append; set to NULL if unused
885  */
886 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
887 {
888         const char *aptr, *eiptr;
889         char *tptr, *eptr;
890         long len;
891
892         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
893                 return ;
894
895         if (PlainIn != NULL) {
896                 aptr = PlainIn;
897                 len = strlen(PlainIn);
898                 eiptr = aptr + len;
899         }
900         else {
901                 aptr = Source->buf;
902                 eiptr = aptr + Source->BufUsed;
903                 len = Source->BufUsed;
904         }
905
906         if (len == 0) 
907                 return;
908
909         eptr = Target->buf + Target->BufSize - 8; 
910         tptr = Target->buf + Target->BufUsed;
911         
912         while (aptr < eiptr){
913                 if(tptr + 3 >= eptr) {
914                         IncreaseBuf(Target, 1, -1);
915                         eptr = Target->buf + Target->BufSize - 8; 
916                         tptr = Target->buf + Target->BufUsed;
917                 }
918                
919                 if (*aptr == '\n') {
920                         *tptr = '\\';
921                         Target->BufUsed++;
922                         tptr++;
923                         *tptr = 'n';
924                         Target->BufUsed++;
925                 }
926                 else if (*aptr == '\r') {
927                         *tptr = '\\';
928                         Target->BufUsed++;
929                         tptr++;
930                         *tptr = 'r';
931                         Target->BufUsed++;
932                 }
933                 else if (*aptr == ',') {
934                         *tptr = '\\';
935                         Target->BufUsed++;
936                         tptr++;
937                         *tptr = ',';
938                         Target->BufUsed++;
939                 } else {
940                         *tptr = *aptr;
941                         Target->BufUsed++;
942                 }
943                 tptr++; aptr++;
944         }
945         *tptr = '\0';
946 }
947
948 /*
949  * \brief Append a string, escaping characters which have meaning in JavaScript strings .  
950  *
951  * \param Target        target buffer
952  * \param Source        source buffer; set to NULL if you just have a C-String
953  * \param PlainIn       Plain-C string to append; set to NULL if unused
954  */
955 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
956 {
957         const char *aptr, *eiptr;
958         char *bptr, *eptr;
959         long len;
960
961         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
962                 return -1;
963
964         if (PlainIn != NULL) {
965                 aptr = PlainIn;
966                 len = strlen(PlainIn);
967                 eiptr = aptr + len;
968         }
969         else {
970                 aptr = Source->buf;
971                 eiptr = aptr + Source->BufUsed;
972                 len = Source->BufUsed;
973         }
974
975         if (len == 0) 
976                 return -1;
977
978         bptr = Target->buf + Target->BufUsed;
979         eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in...  */
980
981         while (aptr < eiptr){
982                 if(bptr >= eptr) {
983                         IncreaseBuf(Target, 1, -1);
984                         eptr = Target->buf + Target->BufSize - 3; 
985                         bptr = Target->buf + Target->BufUsed;
986                 }
987                 if (*aptr == '"') {
988                         *bptr = '\\';
989                         bptr ++;
990                         *bptr = '"';
991                         bptr ++;
992                         Target->BufUsed += 2;
993                 } else if (*aptr == '\\') {
994                         *bptr = '\\';
995                         bptr ++;
996                         *bptr = '\\';
997                         bptr ++;
998                         Target->BufUsed += 2;
999                 }
1000                 else{
1001                         *bptr = *aptr;
1002                         bptr++;
1003                         Target->BufUsed ++;
1004                 }
1005                 aptr ++;
1006         }
1007         *bptr = '\0';
1008         if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1009                 return -1;
1010         return Target->BufUsed;
1011 }
1012
1013 /**
1014  * \brief extracts a substring from Source into dest
1015  * \param dest buffer to place substring into
1016  * \param Source string to copy substring from
1017  * \param Offset chars to skip from start
1018  * \param nChars number of chars to copy
1019  * \returns the number of chars copied; may be different from nChars due to the size of Source
1020  */
1021 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1022 {
1023         size_t NCharsRemain;
1024         if (Offset > Source->BufUsed)
1025         {
1026                 FlushStrBuf(dest);
1027                 return 0;
1028         }
1029         if (Offset + nChars < Source->BufUsed)
1030         {
1031                 if (nChars >= dest->BufSize)
1032                         IncreaseBuf(dest, 0, nChars + 1);
1033                 memcpy(dest->buf, Source->buf + Offset, nChars);
1034                 dest->BufUsed = nChars;
1035                 dest->buf[dest->BufUsed] = '\0';
1036                 return nChars;
1037         }
1038         NCharsRemain = Source->BufUsed - Offset;
1039         if (NCharsRemain  >= dest->BufSize)
1040                 IncreaseBuf(dest, 0, NCharsRemain + 1);
1041         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1042         dest->BufUsed = NCharsRemain;
1043         dest->buf[dest->BufUsed] = '\0';
1044         return NCharsRemain;
1045 }
1046
1047 /**
1048  * \brief sprintf like function appending the formated string to the buffer
1049  * vsnprintf version to wrap into own calls
1050  * \param Buf Buffer to extend by format and params
1051  * \param format printf alike format to add
1052  * \param ap va_list containing the items for format
1053  */
1054 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1055 {
1056         va_list apl;
1057         size_t BufSize = Buf->BufSize;
1058         size_t nWritten = Buf->BufSize + 1;
1059         size_t Offset = Buf->BufUsed;
1060         size_t newused = Offset + nWritten;
1061         
1062         while (newused >= BufSize) {
1063                 va_copy(apl, ap);
1064                 nWritten = vsnprintf(Buf->buf + Offset, 
1065                                      Buf->BufSize - Offset, 
1066                                      format, apl);
1067                 va_end(apl);
1068                 newused = Offset + nWritten;
1069                 if (newused >= Buf->BufSize) {
1070                         IncreaseBuf(Buf, 1, newused);
1071                         newused = Buf->BufSize + 1;
1072                 }
1073                 else {
1074                         Buf->BufUsed = Offset + nWritten;
1075                         BufSize = Buf->BufSize;
1076                 }
1077
1078         }
1079 }
1080
1081 /**
1082  * \brief sprintf like function appending the formated string to the buffer
1083  * \param Buf Buffer to extend by format and params
1084  * \param format printf alike format to add
1085  * \param ap va_list containing the items for format
1086  */
1087 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1088 {
1089         size_t BufSize = Buf->BufSize;
1090         size_t nWritten = Buf->BufSize + 1;
1091         size_t Offset = Buf->BufUsed;
1092         size_t newused = Offset + nWritten;
1093         va_list arg_ptr;
1094         
1095         while (newused >= BufSize) {
1096                 va_start(arg_ptr, format);
1097                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
1098                                      Buf->BufSize - Buf->BufUsed, 
1099                                      format, arg_ptr);
1100                 va_end(arg_ptr);
1101                 newused = Buf->BufUsed + nWritten;
1102                 if (newused >= Buf->BufSize) {
1103                         IncreaseBuf(Buf, 1, newused);
1104                         newused = Buf->BufSize + 1;
1105                 }
1106                 else {
1107                         Buf->BufUsed += nWritten;
1108                         BufSize = Buf->BufSize;
1109                 }
1110
1111         }
1112 }
1113
1114 /**
1115  * \brief sprintf like function putting the formated string into the buffer
1116  * \param Buf Buffer to extend by format and params
1117  * \param format printf alike format to add
1118  * \param ap va_list containing the items for format
1119  */
1120 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1121 {
1122         size_t nWritten = Buf->BufSize + 1;
1123         va_list arg_ptr;
1124         
1125         while (nWritten >= Buf->BufSize) {
1126                 va_start(arg_ptr, format);
1127                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1128                 va_end(arg_ptr);
1129                 if (nWritten >= Buf->BufSize) {
1130                         IncreaseBuf(Buf, 0, 0);
1131                         nWritten = Buf->BufSize + 1;
1132                         continue;
1133                 }
1134                 Buf->BufUsed = nWritten ;
1135         }
1136 }
1137
1138
1139 /**
1140  * \brief Counts the numbmer of tokens in a buffer
1141  * \param Source String to count tokens in
1142  * \param tok    Tokenizer char to count
1143  * \returns numbers of tokenizer chars found
1144  */
1145 int StrBufNum_tokens(const StrBuf *source, char tok)
1146 {
1147         if (source == NULL)
1148                 return 0;
1149         return num_tokens(source->buf, tok);
1150 }
1151
1152 /*
1153  * remove_token() - a tokenizer that kills, maims, and destroys
1154  */
1155 /**
1156  * \brief a string tokenizer
1157  * \param Source StringBuffer to read into
1158  * \param parmnum n'th parameter to remove
1159  * \param separator tokenizer param
1160  * \returns -1 if not found, else length of token.
1161  */
1162 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1163 {
1164         int ReducedBy;
1165         char *d, *s;            /* dest, source */
1166         int count = 0;
1167
1168         /* Find desired parameter */
1169         d = Source->buf;
1170         while (count < parmnum) {
1171                 /* End of string, bail! */
1172                 if (!*d) {
1173                         d = NULL;
1174                         break;
1175                 }
1176                 if (*d == separator) {
1177                         count++;
1178                 }
1179                 d++;
1180         }
1181         if (!d) return 0;               /* Parameter not found */
1182
1183         /* Find next parameter */
1184         s = d;
1185         while (*s && *s != separator) {
1186                 s++;
1187         }
1188         if (*s == separator)
1189                 s++;
1190         ReducedBy = d - s;
1191
1192         /* Hack and slash */
1193         if (*s) {
1194                 memmove(d, s, Source->BufUsed - (s - Source->buf));
1195                 Source->BufUsed += ReducedBy;
1196         }
1197         else if (d == Source->buf) {
1198                 *d = 0;
1199                 Source->BufUsed = 0;
1200         }
1201         else {
1202                 *--d = 0;
1203                 Source->BufUsed += ReducedBy;
1204         }
1205         /*
1206         while (*s) {
1207                 *d++ = *s++;
1208         }
1209         *d = 0;
1210         */
1211         return ReducedBy;
1212 }
1213
1214
1215 /**
1216  * \brief a string tokenizer
1217  * \param dest Destination StringBuffer
1218  * \param Source StringBuffer to read into
1219  * \param parmnum n'th parameter to extract
1220  * \param separator tokenizer param
1221  * \returns -1 if not found, else length of token.
1222  */
1223 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1224 {
1225         const char *s, *e;              //* source * /
1226         int len = 0;                    //* running total length of extracted string * /
1227         int current_token = 0;          //* token currently being processed * /
1228          
1229         if (dest != NULL) {
1230                 dest->buf[0] = '\0';
1231                 dest->BufUsed = 0;
1232         }
1233         else
1234                 return(-1);
1235
1236         if ((Source == NULL) || (Source->BufUsed ==0)) {
1237                 return(-1);
1238         }
1239         s = Source->buf;
1240         e = s + Source->BufUsed;
1241
1242         //cit_backtrace();
1243         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1244
1245         while ((s<e) && !IsEmptyStr(s)) {
1246                 if (*s == separator) {
1247                         ++current_token;
1248                 }
1249                 if (len >= dest->BufSize) {
1250                         dest->BufUsed = len;
1251                         if (IncreaseBuf(dest, 1, -1) < 0) {
1252                                 dest->BufUsed --;
1253                                 break;
1254                         }
1255                 }
1256                 if ( (current_token == parmnum) && 
1257                      (*s != separator)) {
1258                         dest->buf[len] = *s;
1259                         ++len;
1260                 }
1261                 else if (current_token > parmnum) {
1262                         break;
1263                 }
1264                 ++s;
1265         }
1266         
1267         dest->buf[len] = '\0';
1268         dest->BufUsed = len;
1269                 
1270         if (current_token < parmnum) {
1271                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1272                 return(-1);
1273         }
1274         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1275         return(len);
1276 }
1277
1278
1279
1280
1281
1282 /**
1283  * \brief a string tokenizer to fetch an integer
1284  * \param dest Destination StringBuffer
1285  * \param parmnum n'th parameter to extract
1286  * \param separator tokenizer param
1287  * \returns 0 if not found, else integer representation of the token
1288  */
1289 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1290 {
1291         StrBuf tmp;
1292         char buf[64];
1293         
1294         tmp.buf = buf;
1295         buf[0] = '\0';
1296         tmp.BufSize = 64;
1297         tmp.BufUsed = 0;
1298         tmp.ConstBuf = 1;
1299         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1300                 return(atoi(buf));
1301         else
1302                 return 0;
1303 }
1304
1305 /**
1306  * \brief a string tokenizer to fetch a long integer
1307  * \param dest Destination StringBuffer
1308  * \param parmnum n'th parameter to extract
1309  * \param separator tokenizer param
1310  * \returns 0 if not found, else long integer representation of the token
1311  */
1312 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1313 {
1314         StrBuf tmp;
1315         char buf[64];
1316         
1317         tmp.buf = buf;
1318         buf[0] = '\0';
1319         tmp.BufSize = 64;
1320         tmp.BufUsed = 0;
1321         tmp.ConstBuf = 1;
1322         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1323                 return(atoi(buf));
1324         else
1325                 return 0;
1326 }
1327
1328
1329 /**
1330  * \brief a string tokenizer to fetch an unsigned long
1331  * \param dest Destination StringBuffer
1332  * \param parmnum n'th parameter to extract
1333  * \param separator tokenizer param
1334  * \returns 0 if not found, else unsigned long representation of the token
1335  */
1336 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1337 {
1338         StrBuf tmp;
1339         char buf[64];
1340         char *pnum;
1341         
1342         tmp.buf = buf;
1343         buf[0] = '\0';
1344         tmp.BufSize = 64;
1345         tmp.BufUsed = 0;
1346         tmp.ConstBuf = 1;
1347         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1348                 pnum = &buf[0];
1349                 if (*pnum == '-')
1350                         pnum ++;
1351                 return (unsigned long) atol(pnum);
1352         }
1353         else 
1354                 return 0;
1355 }
1356
1357
1358
1359 /**
1360  * \briefa string tokenizer; Bounds checker
1361  *  function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1362  * \param Source our tokenbuffer
1363  * \param pStart the token iterator pointer to inspect
1364  * \returns whether the revolving pointer is inside of the search range
1365  */
1366 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1367 {
1368         if ((Source == NULL) || 
1369             (*pStart == StrBufNOTNULL) ||
1370             (Source->BufUsed == 0))
1371         {
1372                 return 0;
1373         }
1374         if (*pStart == NULL)
1375         {
1376                 return 1;
1377         }
1378         else if (*pStart > Source->buf + Source->BufUsed)
1379         {
1380                 return 0;
1381         }
1382         else if (*pStart <= Source->buf)
1383         {
1384                 return 0;
1385         }
1386
1387         return 1;
1388 }
1389
1390 /**
1391  * \brief a string tokenizer
1392  * \param dest Destination StringBuffer
1393  * \param Source StringBuffer to read into
1394  * \param pStart pointer to the end of the last token. Feed with NULL on start.
1395  * \param separator tokenizer param
1396  * \returns -1 if not found, else length of token.
1397  */
1398 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1399 {
1400         const char *s;          /* source */
1401         const char *EndBuffer;  /* end stop of source buffer */
1402         int current_token = 0;  /* token currently being processed */
1403         int len = 0;            /* running total length of extracted string */
1404
1405         if ((Source          == NULL) || 
1406             (Source->BufUsed == 0)      ) 
1407         {
1408                 *pStart = StrBufNOTNULL;
1409                 return -1;
1410         }
1411          
1412         EndBuffer = Source->buf + Source->BufUsed;
1413
1414         if (dest != NULL) 
1415         {
1416                 dest->buf[0] = '\0';
1417                 dest->BufUsed = 0;
1418         }
1419         else
1420         {
1421                 *pStart = EndBuffer + 1;
1422                 return -1;
1423         }
1424
1425         if (*pStart == NULL)
1426         {
1427                 *pStart = Source->buf; /* we're starting to examine this buffer. */
1428         }
1429         else if ((*pStart < Source->buf) || 
1430                  (*pStart > EndBuffer  )   ) 
1431         {
1432                 return -1; /* no more tokens to find. */
1433         }
1434
1435         s = *pStart;
1436         /* start to find the next token */
1437         while ((s <= EndBuffer)      && 
1438                (current_token == 0) ) 
1439         {
1440                 if (*s == separator) 
1441                 {
1442                         /* we found the next token */
1443                         ++current_token;
1444                 }
1445
1446                 if (len >= dest->BufSize) 
1447                 {
1448                         /* our Dest-buffer isn't big enough, increase it. */
1449                         dest->BufUsed = len;
1450
1451                         if (IncreaseBuf(dest, 1, -1) < 0) {
1452                                 /* WHUT? no more mem? bail out. */
1453                                 s = EndBuffer;
1454                                 dest->BufUsed --;
1455                                 break;
1456                         }
1457                 }
1458
1459                 if ( (current_token == 0 ) &&   /* are we in our target token? */
1460                      (!IsEmptyStr(s)     ) &&
1461                      (separator     != *s)    ) /* don't copy the token itself */
1462                 {
1463                         dest->buf[len] = *s;    /* Copy the payload */
1464                         ++len;                  /* remember the bigger size. */
1465                 }
1466
1467                 ++s;
1468         }
1469
1470         /* did we reach the end? */
1471         if ((s > EndBuffer)) {
1472                 EndBuffer = StrBufNOTNULL;
1473                 *pStart = EndBuffer;
1474         }
1475         else {
1476                 *pStart = s;  /* remember the position for the next run */
1477         }
1478
1479         /* sanitize our extracted token */
1480         dest->buf[len] = '\0';
1481         dest->BufUsed  = len;
1482
1483         return (len);
1484 }
1485
1486
1487 /**
1488  * \brief a string tokenizer
1489  * \param dest Destination StringBuffer
1490  * \param Source StringBuffer to read into
1491  * \param pStart pointer to the end of the last token. Feed with NULL.
1492  * \param separator tokenizer param
1493  * \returns -1 if not found, else length of token.
1494  */
1495 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1496 {
1497         const char *s, *EndBuffer;      //* source * /
1498         int len = 0;                    //* running total length of extracted string * /
1499         int current_token = 0;          //* token currently being processed * /
1500
1501         if ((Source == NULL) || 
1502             (Source->BufUsed ==0)) {
1503                 return(-1);
1504         }
1505         if (nTokens == 0)
1506                 return Source->BufUsed;
1507
1508         if (*pStart == NULL)
1509                 *pStart = Source->buf;
1510
1511         EndBuffer = Source->buf + Source->BufUsed;
1512
1513         if ((*pStart < Source->buf) || 
1514             (*pStart >  EndBuffer)) {
1515                 return (-1);
1516         }
1517
1518
1519         s = *pStart;
1520
1521         //cit_backtrace();
1522         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1523
1524         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1525                 if (*s == separator) {
1526                         ++current_token;
1527                 }
1528                 if (current_token >= nTokens) {
1529                         break;
1530                 }
1531                 ++s;
1532         }
1533         *pStart = s;
1534         (*pStart) ++;
1535
1536         return(len);
1537 }
1538
1539 /**
1540  * \brief a string tokenizer to fetch an integer
1541  * \param dest Destination StringBuffer
1542  * \param parmnum n'th parameter to extract
1543  * \param separator tokenizer param
1544  * \returns 0 if not found, else integer representation of the token
1545  */
1546 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1547 {
1548         StrBuf tmp;
1549         char buf[64];
1550         
1551         tmp.buf = buf;
1552         buf[0] = '\0';
1553         tmp.BufSize = 64;
1554         tmp.BufUsed = 0;
1555         tmp.ConstBuf = 1;
1556         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1557                 return(atoi(buf));
1558         else
1559                 return 0;
1560 }
1561
1562 /**
1563  * \brief a string tokenizer to fetch a long integer
1564  * \param dest Destination StringBuffer
1565  * \param parmnum n'th parameter to extract
1566  * \param separator tokenizer param
1567  * \returns 0 if not found, else long integer representation of the token
1568  */
1569 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1570 {
1571         StrBuf tmp;
1572         char buf[64];
1573         
1574         tmp.buf = buf;
1575         buf[0] = '\0';
1576         tmp.BufSize = 64;
1577         tmp.BufUsed = 0;
1578         tmp.ConstBuf = 1;
1579         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1580                 return(atoi(buf));
1581         else
1582                 return 0;
1583 }
1584
1585
1586 /**
1587  * \brief a string tokenizer to fetch an unsigned long
1588  * \param dest Destination StringBuffer
1589  * \param parmnum n'th parameter to extract
1590  * \param separator tokenizer param
1591  * \returns 0 if not found, else unsigned long representation of the token
1592  */
1593 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1594 {
1595         StrBuf tmp;
1596         char buf[64];
1597         char *pnum;
1598         
1599         tmp.buf = buf;
1600         buf[0] = '\0';
1601         tmp.BufSize = 64;
1602         tmp.BufUsed = 0;
1603         tmp.ConstBuf = 1;
1604         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1605                 pnum = &buf[0];
1606                 if (*pnum == '-')
1607                         pnum ++;
1608                 return (unsigned long) atol(pnum);
1609         }
1610         else 
1611                 return 0;
1612 }
1613
1614
1615
1616 /**
1617  * \brief Read a line from socket
1618  * flushes and closes the FD on error
1619  * \param buf the buffer to get the input to
1620  * \param fd pointer to the filedescriptor to read
1621  * \param append Append to an existing string or replace?
1622  * \param Error strerror() on error 
1623  * \returns numbers of chars read
1624  */
1625 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1626 {
1627         int len, rlen, slen;
1628
1629         if (!append)
1630                 FlushStrBuf(buf);
1631
1632         slen = len = buf->BufUsed;
1633         while (1) {
1634                 rlen = read(*fd, &buf->buf[len], 1);
1635                 if (rlen < 1) {
1636                         *Error = strerror(errno);
1637                         
1638                         close(*fd);
1639                         *fd = -1;
1640                         
1641                         return -1;
1642                 }
1643                 if (buf->buf[len] == '\n')
1644                         break;
1645                 if (buf->buf[len] != '\r')
1646                         len ++;
1647                 if (len >= buf->BufSize) {
1648                         buf->BufUsed = len;
1649                         buf->buf[len+1] = '\0';
1650                         IncreaseBuf(buf, 1, -1);
1651                 }
1652         }
1653         buf->BufUsed = len;
1654         buf->buf[len] = '\0';
1655         return len - slen;
1656 }
1657
1658 /**
1659  * \brief Read a line from socket
1660  * flushes and closes the FD on error
1661  * \param buf the buffer to get the input to
1662  * \param fd pointer to the filedescriptor to read
1663  * \param append Append to an existing string or replace?
1664  * \param Error strerror() on error 
1665  * \returns numbers of chars read
1666  */
1667 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1668                                  StrBuf *buf, 
1669                                  int *fd, 
1670                                  int timeout, 
1671                                  int selectresolution, 
1672                                  const char **Error)
1673 {
1674         int len, rlen;
1675         int nSuccessLess = 0;
1676         fd_set rfds;
1677         char *pch = NULL;
1678         int fdflags;
1679         struct timeval tv;
1680
1681         if (buf->BufUsed > 0) {
1682                 pch = strchr(buf->buf, '\n');
1683                 if (pch != NULL) {
1684                         rlen = 0;
1685                         len = pch - buf->buf;
1686                         if (len > 0 && (*(pch - 1) == '\r') )
1687                                 rlen ++;
1688                         StrBufSub(Line, buf, 0, len - rlen);
1689                         StrBufCutLeft(buf, len + 1);
1690                         return len - rlen;
1691                 }
1692         }
1693         
1694         if (buf->BufSize - buf->BufUsed < 10)
1695                 IncreaseBuf(buf, 1, -1);
1696
1697         fdflags = fcntl(*fd, F_GETFL);
1698         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1699                 return -1;
1700
1701         while ((nSuccessLess < timeout) && (pch == NULL)) {
1702                 tv.tv_sec = selectresolution;
1703                 tv.tv_usec = 0;
1704                 
1705                 FD_ZERO(&rfds);
1706                 FD_SET(*fd, &rfds);
1707                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1708                         *Error = strerror(errno);
1709                         close (*fd);
1710                         *fd = -1;
1711                         return -1;
1712                 }               
1713                 if (FD_ISSET(*fd, &rfds)) {
1714                         rlen = read(*fd, 
1715                                     &buf->buf[buf->BufUsed], 
1716                                     buf->BufSize - buf->BufUsed - 1);
1717                         if (rlen < 1) {
1718                                 *Error = strerror(errno);
1719                                 close(*fd);
1720                                 *fd = -1;
1721                                 return -1;
1722                         }
1723                         else if (rlen > 0) {
1724                                 nSuccessLess = 0;
1725                                 buf->BufUsed += rlen;
1726                                 buf->buf[buf->BufUsed] = '\0';
1727                                 if (buf->BufUsed + 10 > buf->BufSize) {
1728                                         IncreaseBuf(buf, 1, -1);
1729                                 }
1730                                 pch = strchr(buf->buf, '\n');
1731                                 continue;
1732                         }
1733                 }
1734                 nSuccessLess ++;
1735         }
1736         if (pch != NULL) {
1737                 rlen = 0;
1738                 len = pch - buf->buf;
1739                 if (len > 0 && (*(pch - 1) == '\r') )
1740                         rlen ++;
1741                 StrBufSub(Line, buf, 0, len - rlen);
1742                 StrBufCutLeft(buf, len + 1);
1743                 return len - rlen;
1744         }
1745         return -1;
1746
1747 }
1748
1749 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1750 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1751 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1752 /**
1753  * \brief Read a line from socket
1754  * flushes and closes the FD on error
1755  * \param buf the buffer to get the input to
1756  * \param Pos pointer to the current read position, should be NULL initialized!
1757  * \param fd pointer to the filedescriptor to read
1758  * \param append Append to an existing string or replace?
1759  * \param Error strerror() on error 
1760  * \returns numbers of chars read
1761  */
1762 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
1763                                       StrBuf *IOBuf, 
1764                                       const char **Pos,
1765                                       int *fd, 
1766                                       int timeout, 
1767                                       int selectresolution, 
1768                                       const char **Error)
1769 {
1770         const char *pche = NULL;
1771         const char *pos = NULL;
1772         int len, rlen;
1773         int nSuccessLess = 0;
1774         fd_set rfds;
1775         const char *pch = NULL;
1776         int fdflags;
1777         struct timeval tv;
1778         
1779         pos = *Pos;
1780         if ((IOBuf->BufUsed > 0) && 
1781             (pos != NULL) && 
1782             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1783         {
1784                 pche = IOBuf->buf + IOBuf->BufUsed;
1785                 pch = pos;
1786                 while ((pch < pche) && (*pch != '\n'))
1787                         pch ++;
1788                 if ((pch >= pche) || (*pch == '\0'))
1789                         pch = NULL;
1790                 if ((pch != NULL) && 
1791                     (pch <= pche)) 
1792                 {
1793                         rlen = 0;
1794                         len = pch - pos;
1795                         if (len > 0 && (*(pch - 1) == '\r') )
1796                                 rlen ++;
1797                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1798                         *Pos = pch + 1;
1799                         return len - rlen;
1800                 }
1801         }
1802         
1803         if (pos != NULL) {
1804                 if (pos > pche)
1805                         FlushStrBuf(IOBuf);
1806                 else 
1807                         StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1808                 *Pos = NULL;
1809         }
1810         
1811         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1812                 IncreaseBuf(IOBuf, 1, -1);
1813         }
1814
1815         fdflags = fcntl(*fd, F_GETFL);
1816         if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1817                 *Error = ErrRBLF_WrongFDFlags;
1818                 return -1;
1819         }
1820
1821         pch = NULL;
1822         while ((nSuccessLess < timeout) && (pch == NULL)) {
1823                 tv.tv_sec = selectresolution;
1824                 tv.tv_usec = 0;
1825                 
1826                 FD_ZERO(&rfds);
1827                 FD_SET(*fd, &rfds);
1828                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1829                         *Error = strerror(errno);
1830                         close (*fd);
1831                         *fd = -1;
1832                         if (*Error == NULL)
1833                                 *Error = ErrRBLF_SelectFailed;
1834                         return -1;
1835                 }               
1836                 if (FD_ISSET(*fd, &rfds) != 0) {
1837                         rlen = read(*fd, 
1838                                     &IOBuf->buf[IOBuf->BufUsed], 
1839                                     IOBuf->BufSize - IOBuf->BufUsed - 1);
1840                         if (rlen < 1) {
1841                                 *Error = strerror(errno);
1842                                 close(*fd);
1843                                 *fd = -1;
1844                                 return -1;
1845                         }
1846                         else if (rlen > 0) {
1847                                 nSuccessLess = 0;
1848                                 IOBuf->BufUsed += rlen;
1849                                 IOBuf->buf[IOBuf->BufUsed] = '\0';
1850                                 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1851                                         IncreaseBuf(IOBuf, 1, -1);
1852                                 }
1853
1854                                 pche = IOBuf->buf + IOBuf->BufUsed;
1855                                 pch = IOBuf->buf;
1856                                 while ((pch < pche) && (*pch != '\n'))
1857                                         pch ++;
1858                                 if ((pch >= pche) || (*pch == '\0'))
1859                                         pch = NULL;
1860                                 continue;
1861                         }
1862                 }
1863                 nSuccessLess ++;
1864         }
1865         if (pch != NULL) {
1866                 pos = IOBuf->buf;
1867                 rlen = 0;
1868                 len = pch - pos;
1869                 if (len > 0 && (*(pch - 1) == '\r') )
1870                         rlen ++;
1871                 StrBufSub(Line, IOBuf, 0, len - rlen);
1872                 *Pos = pos + len + 1;
1873                 return len - rlen;
1874         }
1875         *Error = ErrRBLF_NotEnoughSentFromServer;
1876         return -1;
1877
1878 }
1879
1880 /**
1881  * \brief Input binary data from socket
1882  * flushes and closes the FD on error
1883  * \param buf the buffer to get the input to
1884  * \param fd pointer to the filedescriptor to read
1885  * \param append Append to an existing string or replace?
1886  * \param nBytes the maximal number of bytes to read
1887  * \param Error strerror() on error 
1888  * \returns numbers of chars read
1889  */
1890 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1891 {
1892         fd_set wset;
1893         int fdflags;
1894         int len, rlen, slen;
1895         int nRead = 0;
1896         char *ptr;
1897
1898         if ((Buf == NULL) || (*fd == -1))
1899                 return -1;
1900         if (!append)
1901                 FlushStrBuf(Buf);
1902         if (Buf->BufUsed + nBytes >= Buf->BufSize)
1903                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1904
1905         ptr = Buf->buf + Buf->BufUsed;
1906
1907         slen = len = Buf->BufUsed;
1908
1909         fdflags = fcntl(*fd, F_GETFL);
1910
1911         while (nRead < nBytes) {
1912                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1913                         FD_ZERO(&wset);
1914                         FD_SET(*fd, &wset);
1915                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1916                                 *Error = strerror(errno);
1917                                 return -1;
1918                         }
1919                 }
1920
1921                 if ((rlen = read(*fd, 
1922                                  ptr,
1923                                  nBytes - nRead)) == -1) {
1924                         close(*fd);
1925                         *fd = -1;
1926                         *Error = strerror(errno);
1927                         return rlen;
1928                 }
1929                 nRead += rlen;
1930                 ptr += rlen;
1931                 Buf->BufUsed += rlen;
1932         }
1933         Buf->buf[Buf->BufUsed] = '\0';
1934         return nRead;
1935 }
1936
1937 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1938 /**
1939  * \brief Input binary data from socket
1940  * flushes and closes the FD on error
1941  * \param buf the buffer to get the input to
1942  * \param fd pointer to the filedescriptor to read
1943  * \param append Append to an existing string or replace?
1944  * \param nBytes the maximal number of bytes to read
1945  * \param Error strerror() on error 
1946  * \returns numbers of chars read
1947  */
1948 int StrBufReadBLOBBuffered(StrBuf *Blob, 
1949                            StrBuf *IOBuf, 
1950                            const char **Pos,
1951                            int *fd, 
1952                            int append, 
1953                            long nBytes, 
1954                            int check, 
1955                            const char **Error)
1956 {
1957         const char *pche;
1958         const char *pos;
1959         int nSelects = 0;
1960         int SelRes;
1961         fd_set wset;
1962         int fdflags;
1963         int len = 0;
1964         int rlen, slen;
1965         int nRead = 0;
1966         char *ptr;
1967         const char *pch;
1968
1969         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1970                 return -1;
1971         if (!append)
1972                 FlushStrBuf(Blob);
1973         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
1974                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1975         
1976         pos = *Pos;
1977
1978         if (pos > 0)
1979                 len = pos - IOBuf->buf;
1980         rlen = IOBuf->BufUsed - len;
1981
1982
1983         if ((IOBuf->BufUsed > 0) && 
1984             (pos != NULL) && 
1985             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1986         {
1987                 pche = IOBuf->buf + IOBuf->BufUsed;
1988                 pch = pos;
1989
1990                 if (rlen < nBytes) {
1991                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1992                         Blob->BufUsed += rlen;
1993                         Blob->buf[Blob->BufUsed] = '\0';
1994                         nRead = rlen;
1995                         *Pos = NULL; 
1996                 }
1997                 if (rlen >= nBytes) {
1998                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1999                         Blob->BufUsed += nBytes;
2000                         Blob->buf[Blob->BufUsed] = '\0';
2001                         if (rlen == nBytes) {
2002                                 *Pos = NULL; 
2003                                 FlushStrBuf(IOBuf);
2004                         }
2005                         else 
2006                                 *Pos += nBytes;
2007                         return nBytes;
2008                 }
2009         }
2010
2011         FlushStrBuf(IOBuf);
2012         if (IOBuf->BufSize < nBytes - nRead)
2013                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2014         ptr = IOBuf->buf;
2015
2016         slen = len = Blob->BufUsed;
2017
2018         fdflags = fcntl(*fd, F_GETFL);
2019
2020         SelRes = 1;
2021         nBytes -= nRead;
2022         nRead = 0;
2023         while (nRead < nBytes) {
2024                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
2025                         FD_ZERO(&wset);
2026                         FD_SET(*fd, &wset);
2027                         SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
2028                 }
2029                 if (SelRes == -1) {
2030                         *Error = strerror(errno);
2031                         return -1;
2032                 }
2033                 else if (SelRes) {
2034                         nSelects = 0;
2035                         rlen = read(*fd, 
2036                                     ptr,
2037                                     nBytes - nRead);
2038                         if (rlen == -1) {
2039                                 close(*fd);
2040                                 *fd = -1;
2041                                 *Error = strerror(errno);
2042                                 return rlen;
2043                         }
2044                 }
2045                 else {
2046                         nSelects ++;
2047                         if ((check == NNN_TERM) && 
2048                             (nRead > 5) &&
2049                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
2050                         {
2051                                 StrBufPlain(Blob, HKEY("\n000\n"));
2052                                 StrBufCutRight(Blob, 5);
2053                                 return Blob->BufUsed;
2054                         }
2055                         if (nSelects > 10) {
2056                                 FlushStrBuf(IOBuf);
2057                                 *Error = ErrRBB_too_many_selects;
2058                                 return -1;
2059                         }
2060                 }
2061                 if (rlen > 0) {
2062                         nRead += rlen;
2063                         ptr += rlen;
2064                         IOBuf->BufUsed += rlen;
2065                 }
2066         }
2067         if (nRead > nBytes) {
2068                 *Pos = IOBuf->buf + nBytes;
2069         }
2070         Blob->buf[Blob->BufUsed] = '\0';
2071         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2072         return nRead;
2073 }
2074
2075 /**
2076  * \brief Cut nChars from the start of the string
2077  * \param Buf Buffer to modify
2078  * \param nChars how many chars should be skipped?
2079  */
2080 void StrBufCutLeft(StrBuf *Buf, int nChars)
2081 {
2082         if (nChars >= Buf->BufUsed) {
2083                 FlushStrBuf(Buf);
2084                 return;
2085         }
2086         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2087         Buf->BufUsed -= nChars;
2088         Buf->buf[Buf->BufUsed] = '\0';
2089 }
2090
2091 /**
2092  * \brief Cut the trailing n Chars from the string
2093  * \param Buf Buffer to modify
2094  * \param nChars how many chars should be trunkated?
2095  */
2096 void StrBufCutRight(StrBuf *Buf, int nChars)
2097 {
2098         if (nChars >= Buf->BufUsed) {
2099                 FlushStrBuf(Buf);
2100                 return;
2101         }
2102         Buf->BufUsed -= nChars;
2103         Buf->buf[Buf->BufUsed] = '\0';
2104 }
2105
2106 /**
2107  * \brief Cut the string after n Chars
2108  * \param Buf Buffer to modify
2109  * \param AfternChars after how many chars should we trunkate the string?
2110  * \param At if non-null and points inside of our string, cut it there.
2111  */
2112 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2113 {
2114         if (At != NULL){
2115                 AfternChars = At - Buf->buf;
2116         }
2117
2118         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2119                 return;
2120         Buf->BufUsed = AfternChars;
2121         Buf->buf[Buf->BufUsed] = '\0';
2122 }
2123
2124
2125 /*
2126  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2127  * buf - the string to modify
2128  * len - length of the string. 
2129  */
2130 void StrBufTrim(StrBuf *Buf)
2131 {
2132         int delta = 0;
2133         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2134
2135         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2136                 delta ++;
2137         }
2138         if (delta > 0) StrBufCutLeft(Buf, delta);
2139
2140         if (Buf->BufUsed == 0) return;
2141         while (isspace(Buf->buf[Buf->BufUsed - 1])){
2142                 Buf->BufUsed --;
2143         }
2144         Buf->buf[Buf->BufUsed] = '\0';
2145 }
2146
2147
2148 void StrBufUpCase(StrBuf *Buf) 
2149 {
2150         char *pch, *pche;
2151
2152         pch = Buf->buf;
2153         pche = pch + Buf->BufUsed;
2154         while (pch < pche) {
2155                 *pch = toupper(*pch);
2156                 pch ++;
2157         }
2158 }
2159
2160
2161 void StrBufLowerCase(StrBuf *Buf) 
2162 {
2163         char *pch, *pche;
2164
2165         pch = Buf->buf;
2166         pche = pch + Buf->BufUsed;
2167         while (pch < pche) {
2168                 *pch = tolower(*pch);
2169                 pch ++;
2170         }
2171 }
2172
2173 /**
2174  * \Brief removes double slashes from pathnames
2175  * \param Dir directory string to filter
2176  * \param RemoveTrailingSlash allows / disallows trailing slashes
2177  */
2178 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2179 {
2180         char *a, *b;
2181
2182         a = b = Dir->buf;
2183
2184         while (!IsEmptyStr(a)) {
2185                 if (*a == '/') {
2186                         while (*a == '/')
2187                                 a++;
2188                         *b = '/';
2189                         b++;
2190                 }
2191                 else {
2192                         *b = *a;
2193                         b++; a++;
2194                 }
2195         }
2196         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2197                 *b = '/';
2198                 b++;
2199         }
2200         *b = '\0';
2201         Dir->BufUsed = b - Dir->buf;
2202 }
2203
2204 /**
2205  * \brief unhide special chars hidden to the HTML escaper
2206  * \param target buffer to put the unescaped string in
2207  * \param source buffer to unescape
2208  */
2209 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2210 {
2211         int a, b, len;
2212         char hex[3];
2213
2214         if (target != NULL)
2215                 FlushStrBuf(target);
2216
2217         if (source == NULL ||target == NULL)
2218         {
2219                 return;
2220         }
2221
2222         len = source->BufUsed;
2223         for (a = 0; a < len; ++a) {
2224                 if (target->BufUsed >= target->BufSize)
2225                         IncreaseBuf(target, 1, -1);
2226
2227                 if (source->buf[a] == '=') {
2228                         hex[0] = source->buf[a + 1];
2229                         hex[1] = source->buf[a + 2];
2230                         hex[2] = 0;
2231                         b = 0;
2232                         sscanf(hex, "%02x", &b);
2233                         target->buf[target->BufUsed] = b;
2234                         target->buf[++target->BufUsed] = 0;
2235                         a += 2;
2236                 }
2237                 else {
2238                         target->buf[target->BufUsed] = source->buf[a];
2239                         target->buf[++target->BufUsed] = 0;
2240                 }
2241         }
2242 }
2243
2244
2245 /**
2246  * \brief hide special chars from the HTML escapers and friends
2247  * \param target buffer to put the escaped string in
2248  * \param source buffer to escape
2249  */
2250 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2251 {
2252         int i, len;
2253
2254         if (target != NULL)
2255                 FlushStrBuf(target);
2256
2257         if (source == NULL ||target == NULL)
2258         {
2259                 return;
2260         }
2261
2262         len = source->BufUsed;
2263         for (i=0; i<len; ++i) {
2264                 if (target->BufUsed + 4 >= target->BufSize)
2265                         IncreaseBuf(target, 1, -1);
2266                 if ( (isalnum(source->buf[i])) || 
2267                      (source->buf[i]=='-') || 
2268                      (source->buf[i]=='_') ) {
2269                         target->buf[target->BufUsed++] = source->buf[i];
2270                 }
2271                 else {
2272                         sprintf(&target->buf[target->BufUsed], 
2273                                 "=%02X", 
2274                                 (0xFF &source->buf[i]));
2275                         target->BufUsed += 3;
2276                 }
2277         }
2278         target->buf[target->BufUsed + 1] = '\0';
2279 }
2280
2281 /*
2282  * \brief uses the same calling syntax as compress2(), but it
2283  * creates a stream compatible with HTTP "Content-encoding: gzip"
2284  */
2285 #ifdef HAVE_ZLIB
2286 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2287 #define OS_CODE 0x03    /*< unix */
2288 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
2289                           size_t * destLen,     /*< length of the compresed data */
2290                           const Bytef * source, /*< source to encode */
2291                           uLong sourceLen,      /*< length of source to encode */
2292                           int level)            /*< compression level */
2293 {
2294         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2295
2296         /* write gzip header */
2297         snprintf((char *) dest, *destLen, 
2298                  "%c%c%c%c%c%c%c%c%c%c",
2299                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2300                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2301                  OS_CODE);
2302
2303         /* normal deflate */
2304         z_stream stream;
2305         int err;
2306         stream.next_in = (Bytef *) source;
2307         stream.avail_in = (uInt) sourceLen;
2308         stream.next_out = dest + 10L;   // after header
2309         stream.avail_out = (uInt) * destLen;
2310         if ((uLong) stream.avail_out != *destLen)
2311                 return Z_BUF_ERROR;
2312
2313         stream.zalloc = (alloc_func) 0;
2314         stream.zfree = (free_func) 0;
2315         stream.opaque = (voidpf) 0;
2316
2317         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2318                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2319         if (err != Z_OK)
2320                 return err;
2321
2322         err = deflate(&stream, Z_FINISH);
2323         if (err != Z_STREAM_END) {
2324                 deflateEnd(&stream);
2325                 return err == Z_OK ? Z_BUF_ERROR : err;
2326         }
2327         *destLen = stream.total_out + 10L;
2328
2329         /* write CRC and Length */
2330         uLong crc = crc32(0L, source, sourceLen);
2331         int n;
2332         for (n = 0; n < 4; ++n, ++*destLen) {
2333                 dest[*destLen] = (int) (crc & 0xff);
2334                 crc >>= 8;
2335         }
2336         uLong len = stream.total_in;
2337         for (n = 0; n < 4; ++n, ++*destLen) {
2338                 dest[*destLen] = (int) (len & 0xff);
2339                 len >>= 8;
2340         }
2341         err = deflateEnd(&stream);
2342         return err;
2343 }
2344 #endif
2345
2346
2347 /**
2348  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2349  */
2350 int CompressBuffer(StrBuf *Buf)
2351 {
2352 #ifdef HAVE_ZLIB
2353         char *compressed_data = NULL;
2354         size_t compressed_len, bufsize;
2355         int i = 0;
2356
2357         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
2358         compressed_data = malloc(compressed_len);
2359         
2360         if (compressed_data == NULL)
2361                 return -1;
2362         /* Flush some space after the used payload so valgrind shuts up... */
2363         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2364                 Buf->buf[Buf->BufUsed + i++] = '\0';
2365         if (compress_gzip((Bytef *) compressed_data,
2366                           &compressed_len,
2367                           (Bytef *) Buf->buf,
2368                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2369                 if (!Buf->ConstBuf)
2370                         free(Buf->buf);
2371                 Buf->buf = compressed_data;
2372                 Buf->BufUsed = compressed_len;
2373                 Buf->BufSize = bufsize;
2374                 /* Flush some space after the used payload so valgrind shuts up... */
2375                 i = 0;
2376                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2377                         Buf->buf[Buf->BufUsed + i++] = '\0';
2378                 return 1;
2379         } else {
2380                 free(compressed_data);
2381         }
2382 #endif  /* HAVE_ZLIB */
2383         return 0;
2384 }
2385
2386 /**
2387  * \brief decode a buffer from base 64 encoding; destroys original
2388  * \param Buf Buffor to transform
2389  */
2390 int StrBufDecodeBase64(StrBuf *Buf)
2391 {
2392         char *xferbuf;
2393         size_t siz;
2394         if (Buf == NULL) return -1;
2395
2396         xferbuf = (char*) malloc(Buf->BufSize);
2397         siz = CtdlDecodeBase64(xferbuf,
2398                                Buf->buf,
2399                                Buf->BufUsed);
2400         free(Buf->buf);
2401         Buf->buf = xferbuf;
2402         Buf->BufUsed = siz;
2403         return siz;
2404 }
2405
2406 /**
2407  * \brief decode a buffer from base 64 encoding; destroys original
2408  * \param Buf Buffor to transform
2409  */
2410 int StrBufDecodeHex(StrBuf *Buf)
2411 {
2412         unsigned int ch;
2413         char *pch, *pche, *pchi;
2414
2415         if (Buf == NULL) return -1;
2416
2417         pch = pchi = Buf->buf;
2418         pche = pch + Buf->BufUsed;
2419
2420         while (pchi < pche){
2421                 ch = decode_hex(pchi);
2422                 *pch = ch;
2423                 pch ++;
2424                 pchi += 2;
2425         }
2426
2427         *pch = '\0';
2428         Buf->BufUsed = pch - Buf->buf;
2429         return Buf->BufUsed;
2430 }
2431
2432 /**
2433  * \brief replace all chars >0x20 && < 0x7F with Mute
2434  * \param Mute char to put over invalid chars
2435  * \param Buf Buffor to transform
2436  */
2437 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2438 {
2439         unsigned char *pch;
2440
2441         if (Buf == NULL) return -1;
2442         pch = (unsigned char *)Buf->buf;
2443         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2444                 if ((*pch < 0x20) || (*pch > 0x7F))
2445                         *pch = Mute;
2446                 pch ++;
2447         }
2448         return Buf->BufUsed;
2449 }
2450
2451
2452 /**
2453  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
2454  * \param Buf Buffer to translate
2455  * \param StripBlanks Reduce several blanks to one?
2456  */
2457 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2458 {
2459         int a, b;
2460         char hex[3];
2461         long len;
2462
2463         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2464                 Buf->buf[Buf->BufUsed - 1] = '\0';
2465                 Buf->BufUsed --;
2466         }
2467
2468         a = 0; 
2469         while (a < Buf->BufUsed) {
2470                 if (Buf->buf[a] == '+')
2471                         Buf->buf[a] = ' ';
2472                 else if (Buf->buf[a] == '%') {
2473                         /* don't let % chars through, rather truncate the input. */
2474                         if (a + 2 > Buf->BufUsed) {
2475                                 Buf->buf[a] = '\0';
2476                                 Buf->BufUsed = a;
2477                         }
2478                         else {                  
2479                                 hex[0] = Buf->buf[a + 1];
2480                                 hex[1] = Buf->buf[a + 2];
2481                                 hex[2] = 0;
2482                                 b = 0;
2483                                 sscanf(hex, "%02x", &b);
2484                                 Buf->buf[a] = (char) b;
2485                                 len = Buf->BufUsed - a - 2;
2486                                 if (len > 0)
2487                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2488                         
2489                                 Buf->BufUsed -=2;
2490                         }
2491                 }
2492                 a++;
2493         }
2494         return a;
2495 }
2496
2497
2498 /**
2499  * \brief       RFC2047-encode a header field if necessary.
2500  *              If no non-ASCII characters are found, the string
2501  *              will be copied verbatim without encoding.
2502  *
2503  * \param       target          Target buffer.
2504  * \param       source          Source string to be encoded.
2505  * \returns     encoded length; -1 if non success.
2506  */
2507 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2508 {
2509         const char headerStr[] = "=?UTF-8?Q?";
2510         int need_to_encode = 0;
2511         int i = 0;
2512         unsigned char ch;
2513
2514         if ((source == NULL) || 
2515             (target == NULL))
2516             return -1;
2517
2518         while ((i < source->BufUsed) &&
2519                (!IsEmptyStr (&source->buf[i])) &&
2520                (need_to_encode == 0)) {
2521                 if (((unsigned char) source->buf[i] < 32) || 
2522                     ((unsigned char) source->buf[i] > 126)) {
2523                         need_to_encode = 1;
2524                 }
2525                 i++;
2526         }
2527
2528         if (!need_to_encode) {
2529                 if (*target == NULL) {
2530                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2531                 }
2532                 else {
2533                         FlushStrBuf(*target);
2534                         StrBufAppendBuf(*target, source, 0);
2535                 }
2536                 return (*target)->BufUsed;
2537         }
2538         if (*target == NULL)
2539                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2540         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2541                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2542         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2543         (*target)->BufUsed = sizeof(headerStr) - 1;
2544         for (i=0; (i < source->BufUsed); ++i) {
2545                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2546                         IncreaseBuf(*target, 1, 0);
2547                 ch = (unsigned char) source->buf[i];
2548                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2549                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2550                         (*target)->BufUsed += 3;
2551                 }
2552                 else {
2553                         (*target)->buf[(*target)->BufUsed] = ch;
2554                         (*target)->BufUsed++;
2555                 }
2556         }
2557         
2558         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2559                 IncreaseBuf(*target, 1, 0);
2560
2561         (*target)->buf[(*target)->BufUsed++] = '?';
2562         (*target)->buf[(*target)->BufUsed++] = '=';
2563         (*target)->buf[(*target)->BufUsed] = '\0';
2564         return (*target)->BufUsed;;
2565 }
2566
2567 /**
2568  * \brief replaces all occurances of 'search' by 'replace'
2569  * \param buf Buffer to modify
2570  * \param search character to search
2571  * \param relpace character to replace search by
2572  */
2573 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2574 {
2575         long i;
2576         if (buf == NULL)
2577                 return;
2578         for (i=0; i<buf->BufUsed; i++)
2579                 if (buf->buf[i] == search)
2580                         buf->buf[i] = replace;
2581
2582 }
2583
2584
2585
2586 /*
2587  * Wrapper around iconv_open()
2588  * Our version adds aliases for non-standard Microsoft charsets
2589  * such as 'MS950', aliasing them to names like 'CP950'
2590  *
2591  * tocode       Target encoding
2592  * fromcode     Source encoding
2593  */
2594 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2595 {
2596 #ifdef HAVE_ICONV
2597         iconv_t ic = (iconv_t)(-1) ;
2598         ic = iconv_open(tocode, fromcode);
2599         if (ic == (iconv_t)(-1) ) {
2600                 char alias_fromcode[64];
2601                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2602                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2603                         alias_fromcode[0] = 'C';
2604                         alias_fromcode[1] = 'P';
2605                         ic = iconv_open(tocode, alias_fromcode);
2606                 }
2607         }
2608         *(iconv_t *)pic = ic;
2609 #endif
2610 }
2611
2612
2613
2614 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2615 {
2616         char * end;
2617         /* Find the next ?Q? */
2618         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2619                 return NULL;
2620
2621         end = strchr(bptr + 2, '?');
2622
2623         if (end == NULL)
2624                 return NULL;
2625
2626         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2627             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
2628             (*(end + 2) == '?')) {
2629                 /* skip on to the end of the cluster, the next ?= */
2630                 end = strstr(end + 3, "?=");
2631         }
2632         else
2633                 /* sort of half valid encoding, try to find an end. */
2634                 end = strstr(bptr, "?=");
2635         return end;
2636 }
2637
2638 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2639 {
2640         StrBuf C;
2641
2642         memcpy(&C, A, sizeof(*A));
2643         memcpy(A, B, sizeof(*B));
2644         memcpy(B, &C, sizeof(C));
2645
2646 }
2647
2648 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2649 {
2650 #ifdef HAVE_ICONV
2651         long trycount = 0;
2652         size_t siz;
2653         iconv_t ic;
2654         char *ibuf;                     /**< Buffer of characters to be converted */
2655         char *obuf;                     /**< Buffer for converted characters */
2656         size_t ibuflen;                 /**< Length of input buffer */
2657         size_t obuflen;                 /**< Length of output buffer */
2658
2659
2660         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2661         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2662                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2663 TRYAGAIN:
2664         ic = *(iconv_t*)pic;
2665         ibuf = ConvertBuf->buf;
2666         ibuflen = ConvertBuf->BufUsed;
2667         obuf = TmpBuf->buf;
2668         obuflen = TmpBuf->BufSize;
2669         
2670         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2671
2672         if (siz < 0) {
2673                 if (errno == E2BIG) {
2674                         trycount ++;                    
2675                         IncreaseBuf(TmpBuf, 0, 0);
2676                         if (trycount < 5) 
2677                                 goto TRYAGAIN;
2678
2679                 }
2680                 else if (errno == EILSEQ){ 
2681                         /* hm, invalid utf8 sequence... what to do now? */
2682                         /* An invalid multibyte sequence has been encountered in the input */
2683                 }
2684                 else if (errno == EINVAL) {
2685                         /* An incomplete multibyte sequence has been encountered in the input. */
2686                 }
2687
2688                 FlushStrBuf(TmpBuf);
2689         }
2690         else {
2691                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2692                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2693                 
2694                 /* little card game: wheres the red lady? */
2695                 SwapBuffers(ConvertBuf, TmpBuf);
2696                 FlushStrBuf(TmpBuf);
2697         }
2698 #endif
2699 }
2700
2701
2702
2703
2704 inline static void DecodeSegment(StrBuf *Target, 
2705                                  const StrBuf *DecodeMe, 
2706                                  char *SegmentStart, 
2707                                  char *SegmentEnd, 
2708                                  StrBuf *ConvertBuf,
2709                                  StrBuf *ConvertBuf2, 
2710                                  StrBuf *FoundCharset)
2711 {
2712         StrBuf StaticBuf;
2713         char charset[128];
2714         char encoding[16];
2715 #ifdef HAVE_ICONV
2716         iconv_t ic = (iconv_t)(-1);
2717 #endif
2718         /* Now we handle foreign character sets properly encoded
2719          * in RFC2047 format.
2720          */
2721         StaticBuf.buf = SegmentStart;
2722         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2723         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2724         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2725         if (FoundCharset != NULL) {
2726                 FlushStrBuf(FoundCharset);
2727                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2728         }
2729         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2730         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2731         
2732         *encoding = toupper(*encoding);
2733         if (*encoding == 'B') { /**< base64 */
2734                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
2735                                                         ConvertBuf->buf, 
2736                                                         ConvertBuf->BufUsed);
2737         }
2738         else if (*encoding == 'Q') {    /**< quoted-printable */
2739                 long pos;
2740                 
2741                 pos = 0;
2742                 while (pos < ConvertBuf->BufUsed)
2743                 {
2744                         if (ConvertBuf->buf[pos] == '_') 
2745                                 ConvertBuf->buf[pos] = ' ';
2746                         pos++;
2747                 }
2748                 
2749                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2750                         ConvertBuf2->buf, 
2751                         ConvertBuf->buf,
2752                         ConvertBuf->BufUsed);
2753         }
2754         else {
2755                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2756         }
2757 #ifdef HAVE_ICONV
2758         ctdl_iconv_open("UTF-8", charset, &ic);
2759         if (ic != (iconv_t)(-1) ) {             
2760 #endif
2761                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2762                 StrBufAppendBuf(Target, ConvertBuf2, 0);
2763 #ifdef HAVE_ICONV
2764                 iconv_close(ic);
2765         }
2766         else {
2767                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2768         }
2769 #endif
2770 }
2771 /*
2772  * Handle subjects with RFC2047 encoding such as:
2773  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2774  */
2775 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2776 {
2777         StrBuf *ConvertBuf, *ConvertBuf2;
2778         char *start, *end, *next, *nextend, *ptr = NULL;
2779 #ifdef HAVE_ICONV
2780         iconv_t ic = (iconv_t)(-1) ;
2781 #endif
2782         const char *eptr;
2783         int passes = 0;
2784         int i, len, delta;
2785         int illegal_non_rfc2047_encoding = 0;
2786
2787         /* Sometimes, badly formed messages contain strings which were simply
2788          *  written out directly in some foreign character set instead of
2789          *  using RFC2047 encoding.  This is illegal but we will attempt to
2790          *  handle it anyway by converting from a user-specified default
2791          *  charset to UTF-8 if we see any nonprintable characters.
2792          */
2793         
2794         len = StrLength(DecodeMe);
2795         for (i=0; i<DecodeMe->BufUsed; ++i) {
2796                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2797                         illegal_non_rfc2047_encoding = 1;
2798                         break;
2799                 }
2800         }
2801
2802         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2803         if ((illegal_non_rfc2047_encoding) &&
2804             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
2805             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2806         {
2807 #ifdef HAVE_ICONV
2808                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2809                 if (ic != (iconv_t)(-1) ) {
2810                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2811                         iconv_close(ic);
2812                 }
2813 #endif
2814         }
2815
2816         /* pre evaluate the first pair */
2817         nextend = end = NULL;
2818         len = StrLength(DecodeMe);
2819         start = strstr(DecodeMe->buf, "=?");
2820         eptr = DecodeMe->buf + DecodeMe->BufUsed;
2821         if (start != NULL) 
2822                 end = FindNextEnd (DecodeMe, start);
2823         else {
2824                 StrBufAppendBuf(Target, DecodeMe, 0);
2825                 FreeStrBuf(&ConvertBuf);
2826                 return;
2827         }
2828
2829         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2830
2831         if (start != DecodeMe->buf) {
2832                 long nFront;
2833                 
2834                 nFront = start - DecodeMe->buf;
2835                 StrBufAppendBufPlain(Target, DecodeMe->buf, nFront, 0);
2836                 len -= nFront;
2837         }
2838         /*
2839          * Since spammers will go to all sorts of absurd lengths to get their
2840          * messages through, there are LOTS of corrupt headers out there.
2841          * So, prevent a really badly formed RFC2047 header from throwing
2842          * this function into an infinite loop.
2843          */
2844         while ((start != NULL) && 
2845                (end != NULL) && 
2846                (start < eptr) && 
2847                (end < eptr) && 
2848                (passes < 20))
2849         {
2850                 passes++;
2851                 DecodeSegment(Target, 
2852                               DecodeMe, 
2853                               start, 
2854                               end, 
2855                               ConvertBuf,
2856                               ConvertBuf2,
2857                               FoundCharset);
2858                 
2859                 next = strstr(end, "=?");
2860                 nextend = NULL;
2861                 if ((next != NULL) && 
2862                     (next < eptr))
2863                         nextend = FindNextEnd(DecodeMe, next);
2864                 if (nextend == NULL)
2865                         next = NULL;
2866
2867                 /* did we find two partitions */
2868                 if ((next != NULL) && 
2869                     ((next - end) > 2))
2870                 {
2871                         ptr = end + 2;
2872                         while ((ptr < next) && 
2873                                (isspace(*ptr) ||
2874                                 (*ptr == '\r') ||
2875                                 (*ptr == '\n') || 
2876                                 (*ptr == '\t')))
2877                                 ptr ++;
2878                         /* did we find a gab just filled with blanks? */
2879                         if (ptr == next)
2880                         {
2881                                 long gap = next - start;
2882                                 memmove (end + 2,
2883                                          next,
2884                                          len - (gap));
2885                                 len -= gap;
2886                                 /* now terminate the gab at the end */
2887                                 delta = (next - end) - 2; ////TODO: const! 
2888                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2889                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2890
2891                                 /* move next to its new location. */
2892                                 next -= delta;
2893                                 nextend -= delta;
2894                         }
2895                 }
2896                 /* our next-pair is our new first pair now. */
2897                 ptr = end + 2;
2898                 start = next;
2899                 end = nextend;
2900         }
2901         end = ptr;
2902         nextend = DecodeMe->buf + DecodeMe->BufUsed;
2903         if ((end != NULL) && (end < nextend)) {
2904                 ptr = end;
2905                 while ( (ptr < nextend) &&
2906                         (isspace(*ptr) ||
2907                          (*ptr == '\r') ||
2908                          (*ptr == '\n') || 
2909                          (*ptr == '\t')))
2910                         ptr ++;
2911                 if (ptr < nextend)
2912                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
2913         }
2914         FreeStrBuf(&ConvertBuf);
2915         FreeStrBuf(&ConvertBuf2);
2916 }
2917
2918 /**
2919  * \brief evaluate the length of an utf8 special character sequence
2920  * \param Char the character to examine
2921  * \returns width of utf8 chars in bytes
2922  */
2923 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2924 {
2925         int n = 1;
2926         char test = (1<<7);
2927         
2928         while ((n < 8) && ((test & *CharS) != 0)) {
2929                 test = test << 1;
2930                 n ++;
2931         }
2932         if ((n > 6) || ((CharE - CharS) > n))
2933                 n = 1;
2934         return n;
2935 }
2936
2937 /**
2938  * \brief detect whether this char starts an utf-8 encoded char
2939  * \param Char character to inspect
2940  * \returns yes or no
2941  */
2942 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2943 {
2944 /** 11??.???? indicates an UTF8 Sequence. */
2945         return ((Char & 0xC0) != 0);
2946 }
2947
2948 /**
2949  * \brief measure the number of glyphs in an UTF8 string...
2950  * \param str string to measure
2951  * \returns the length of str
2952  */
2953 long StrBuf_Utf8StrLen(StrBuf *Buf)
2954 {
2955         int n = 0;
2956         int m = 0;
2957         char *aptr, *eptr;
2958
2959         if ((Buf == NULL) || (Buf->BufUsed == 0))
2960                 return 0;
2961         aptr = Buf->buf;
2962         eptr = Buf->buf + Buf->BufUsed;
2963         while ((aptr < eptr) && (*aptr != '\0')) {
2964                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2965                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2966                         while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2967                                 n ++;
2968                 }
2969                 else {
2970                         n++;
2971                         aptr++;
2972                 }
2973                         
2974         }
2975         return n;
2976 }
2977
2978 /**
2979  * \brief cuts a string after maxlen glyphs
2980  * \param str string to cut to maxlen glyphs
2981  * \param maxlen how long may the string become?
2982  * \returns pointer to maxlen or the end of the string
2983  */
2984 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2985 {
2986         char *aptr, *eptr;
2987         int n = 0, m = 0;
2988
2989         aptr = Buf->buf;
2990         eptr = Buf->buf + Buf->BufUsed;
2991         while ((aptr < eptr) && (*aptr != '\0')) {
2992                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2993                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2994                         while ((m-- > 0) && (*aptr++ != '\0'))
2995                                 n ++;
2996                 }
2997                 else {
2998                         n++;
2999                         aptr++;
3000                 }
3001                 if (n > maxlen) {
3002                         *aptr = '\0';
3003                         Buf->BufUsed = aptr - Buf->buf;
3004                         return Buf->BufUsed;
3005                 }                       
3006         }
3007         return Buf->BufUsed;
3008
3009 }
3010
3011
3012
3013 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3014 {
3015         const char *aptr, *ptr, *eptr;
3016         char *optr, *xptr;
3017
3018         if (Buf == NULL)
3019                 return 0;
3020
3021         if (*Ptr==NULL)
3022                 ptr = aptr = Buf->buf;
3023         else
3024                 ptr = aptr = *Ptr;
3025
3026         optr = LineBuf->buf;
3027         eptr = Buf->buf + Buf->BufUsed;
3028         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3029
3030         while ((*ptr != '\n') &&
3031                (*ptr != '\r') &&
3032                (ptr < eptr))
3033         {
3034                 *optr = *ptr;
3035                 optr++; ptr++;
3036                 if (optr == xptr) {
3037                         LineBuf->BufUsed = optr - LineBuf->buf;
3038                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
3039                         optr = LineBuf->buf + LineBuf->BufUsed;
3040                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3041                 }
3042         }
3043         LineBuf->BufUsed = optr - LineBuf->buf;
3044         *optr = '\0';       
3045         if (*ptr == '\r')
3046                 ptr ++;
3047         if (*ptr == '\n')
3048                 ptr ++;
3049
3050         *Ptr = ptr;
3051
3052         return Buf->BufUsed - (ptr - Buf->buf);
3053 }