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