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