816c196e601de11d203baa381aaab902e4ec01e7
[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 = Buf->BufSize;
1059         size_t nWritten = Buf->BufSize + 1;
1060         size_t Offset = Buf->BufUsed;
1061         size_t newused = Offset + nWritten;
1062         
1063         while (newused >= BufSize) {
1064                 va_copy(apl, ap);
1065                 nWritten = vsnprintf(Buf->buf + Offset, 
1066                                      Buf->BufSize - Offset, 
1067                                      format, apl);
1068                 va_end(apl);
1069                 newused = Offset + nWritten;
1070                 if (newused >= Buf->BufSize) {
1071                         IncreaseBuf(Buf, 1, newused);
1072                         newused = Buf->BufSize + 1;
1073                 }
1074                 else {
1075                         Buf->BufUsed = Offset + nWritten;
1076                         BufSize = Buf->BufSize;
1077                 }
1078
1079         }
1080 }
1081
1082 /**
1083  * @brief sprintf like function appending the formated string to the buffer
1084  * @param Buf Buffer to extend by format and @params
1085  * @param format printf alike format to add
1086  * @param ap va_list containing the items for format
1087  */
1088 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1089 {
1090         size_t BufSize = Buf->BufSize;
1091         size_t nWritten = Buf->BufSize + 1;
1092         size_t Offset = Buf->BufUsed;
1093         size_t newused = Offset + nWritten;
1094         va_list arg_ptr;
1095         
1096         while (newused >= BufSize) {
1097                 va_start(arg_ptr, format);
1098                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
1099                                      Buf->BufSize - Buf->BufUsed, 
1100                                      format, arg_ptr);
1101                 va_end(arg_ptr);
1102                 newused = Buf->BufUsed + nWritten;
1103                 if (newused >= Buf->BufSize) {
1104                         IncreaseBuf(Buf, 1, newused);
1105                         newused = Buf->BufSize + 1;
1106                 }
1107                 else {
1108                         Buf->BufUsed += nWritten;
1109                         BufSize = Buf->BufSize;
1110                 }
1111
1112         }
1113 }
1114
1115 /**
1116  * @brief sprintf like function putting the formated string into the buffer
1117  * @param Buf Buffer to extend by format and @params
1118  * @param format printf alike format to add
1119  * @param ap va_list containing the items for format
1120  */
1121 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1122 {
1123         size_t nWritten = Buf->BufSize + 1;
1124         va_list arg_ptr;
1125         
1126         while (nWritten >= Buf->BufSize) {
1127                 va_start(arg_ptr, format);
1128                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1129                 va_end(arg_ptr);
1130                 if (nWritten >= Buf->BufSize) {
1131                         IncreaseBuf(Buf, 0, 0);
1132                         nWritten = Buf->BufSize + 1;
1133                         continue;
1134                 }
1135                 Buf->BufUsed = nWritten ;
1136         }
1137 }
1138
1139
1140 /**
1141  * @brief Counts the numbmer of tokens in a buffer
1142  * @param Source String to count tokens in
1143  * @param tok    Tokenizer char to count
1144  * @returns numbers of tokenizer chars found
1145  */
1146 int StrBufNum_tokens(const StrBuf *source, char tok)
1147 {
1148         if (source == NULL)
1149                 return 0;
1150         return num_tokens(source->buf, tok);
1151 }
1152
1153 /*
1154  * remove_token() - a tokenizer that kills, maims, and destroys
1155  */
1156 /**
1157  * @brief a string tokenizer
1158  * @param Source StringBuffer to read into
1159  * @param parmnum n'th @parameter to remove
1160  * @param separator tokenizer @param
1161  * @returns -1 if not found, else length of token.
1162  */
1163 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1164 {
1165         int ReducedBy;
1166         char *d, *s;            /* dest, source */
1167         int count = 0;
1168
1169         /* Find desired @parameter */
1170         d = Source->buf;
1171         while (count < parmnum) {
1172                 /* End of string, bail! */
1173                 if (!*d) {
1174                         d = NULL;
1175                         break;
1176                 }
1177                 if (*d == separator) {
1178                         count++;
1179                 }
1180                 d++;
1181         }
1182         if (!d) return 0;               /* @Parameter not found */
1183
1184         /* Find next @parameter */
1185         s = d;
1186         while (*s && *s != separator) {
1187                 s++;
1188         }
1189         if (*s == separator)
1190                 s++;
1191         ReducedBy = d - s;
1192
1193         /* Hack and slash */
1194         if (*s) {
1195                 memmove(d, s, Source->BufUsed - (s - Source->buf));
1196                 Source->BufUsed += ReducedBy;
1197         }
1198         else if (d == Source->buf) {
1199                 *d = 0;
1200                 Source->BufUsed = 0;
1201         }
1202         else {
1203                 *--d = 0;
1204                 Source->BufUsed += ReducedBy;
1205         }
1206         /*
1207         while (*s) {
1208                 *d++ = *s++;
1209         }
1210         *d = 0;
1211         */
1212         return ReducedBy;
1213 }
1214
1215
1216 /**
1217  * @brief a string tokenizer
1218  * @param dest Destination StringBuffer
1219  * @param Source StringBuffer to read into
1220  * @param parmnum n'th @parameter to extract
1221  * @param separator tokenizer @param
1222  * @returns -1 if not found, else length of token.
1223  */
1224 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1225 {
1226         const char *s, *e;              //* source * /
1227         int len = 0;                    //* running total length of extracted string * /
1228         int current_token = 0;          //* token currently being processed * /
1229          
1230         if (dest != NULL) {
1231                 dest->buf[0] = '\0';
1232                 dest->BufUsed = 0;
1233         }
1234         else
1235                 return(-1);
1236
1237         if ((Source == NULL) || (Source->BufUsed ==0)) {
1238                 return(-1);
1239         }
1240         s = Source->buf;
1241         e = s + Source->BufUsed;
1242
1243         //cit_backtrace();
1244         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1245
1246         while ((s<e) && !IsEmptyStr(s)) {
1247                 if (*s == separator) {
1248                         ++current_token;
1249                 }
1250                 if (len >= dest->BufSize) {
1251                         dest->BufUsed = len;
1252                         if (IncreaseBuf(dest, 1, -1) < 0) {
1253                                 dest->BufUsed --;
1254                                 break;
1255                         }
1256                 }
1257                 if ( (current_token == parmnum) && 
1258                      (*s != separator)) {
1259                         dest->buf[len] = *s;
1260                         ++len;
1261                 }
1262                 else if (current_token > parmnum) {
1263                         break;
1264                 }
1265                 ++s;
1266         }
1267         
1268         dest->buf[len] = '\0';
1269         dest->BufUsed = len;
1270                 
1271         if (current_token < parmnum) {
1272                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1273                 return(-1);
1274         }
1275         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1276         return(len);
1277 }
1278
1279
1280
1281
1282
1283 /**
1284  * @brief a string tokenizer to fetch an integer
1285  * @param dest Destination StringBuffer
1286  * @param parmnum n'th @parameter to extract
1287  * @param separator tokenizer @param
1288  * @returns 0 if not found, else integer representation of the token
1289  */
1290 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1291 {
1292         StrBuf tmp;
1293         char buf[64];
1294         
1295         tmp.buf = buf;
1296         buf[0] = '\0';
1297         tmp.BufSize = 64;
1298         tmp.BufUsed = 0;
1299         tmp.ConstBuf = 1;
1300         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1301                 return(atoi(buf));
1302         else
1303                 return 0;
1304 }
1305
1306 /**
1307  * @brief a string tokenizer to fetch a long integer
1308  * @param dest Destination StringBuffer
1309  * @param parmnum n'th @parameter to extract
1310  * @param separator tokenizer @param
1311  * @returns 0 if not found, else long integer representation of the token
1312  */
1313 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1314 {
1315         StrBuf tmp;
1316         char buf[64];
1317         
1318         tmp.buf = buf;
1319         buf[0] = '\0';
1320         tmp.BufSize = 64;
1321         tmp.BufUsed = 0;
1322         tmp.ConstBuf = 1;
1323         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1324                 return(atoi(buf));
1325         else
1326                 return 0;
1327 }
1328
1329
1330 /**
1331  * @brief a string tokenizer to fetch an unsigned long
1332  * @param dest Destination StringBuffer
1333  * @param parmnum n'th @parameter to extract
1334  * @param separator tokenizer @param
1335  * @returns 0 if not found, else unsigned long representation of the token
1336  */
1337 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1338 {
1339         StrBuf tmp;
1340         char buf[64];
1341         char *pnum;
1342         
1343         tmp.buf = buf;
1344         buf[0] = '\0';
1345         tmp.BufSize = 64;
1346         tmp.BufUsed = 0;
1347         tmp.ConstBuf = 1;
1348         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1349                 pnum = &buf[0];
1350                 if (*pnum == '-')
1351                         pnum ++;
1352                 return (unsigned long) atol(pnum);
1353         }
1354         else 
1355                 return 0;
1356 }
1357
1358
1359
1360 /**
1361  * @briefa string tokenizer; Bounds checker
1362  *  function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1363  * @param Source our tokenbuffer
1364  * @param pStart the token iterator pointer to inspect
1365  * @returns whether the revolving pointer is inside of the search range
1366  */
1367 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1368 {
1369         if ((Source == NULL) || 
1370             (*pStart == StrBufNOTNULL) ||
1371             (Source->BufUsed == 0))
1372         {
1373                 return 0;
1374         }
1375         if (*pStart == NULL)
1376         {
1377                 return 1;
1378         }
1379         else if (*pStart > Source->buf + Source->BufUsed)
1380         {
1381                 return 0;
1382         }
1383         else if (*pStart <= Source->buf)
1384         {
1385                 return 0;
1386         }
1387
1388         return 1;
1389 }
1390
1391 /**
1392  * @brief a string tokenizer
1393  * @param dest Destination StringBuffer
1394  * @param Source StringBuffer to read into
1395  * @param pStart pointer to the end of the last token. Feed with NULL on start.
1396  * @param separator tokenizer @param
1397  * @returns -1 if not found, else length of token.
1398  */
1399 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1400 {
1401         const char *s;          /* source */
1402         const char *EndBuffer;  /* end stop of source buffer */
1403         int current_token = 0;  /* token currently being processed */
1404         int len = 0;            /* running total length of extracted string */
1405
1406         if ((Source          == NULL) || 
1407             (Source->BufUsed == 0)      ) 
1408         {
1409                 *pStart = StrBufNOTNULL;
1410                 return -1;
1411         }
1412          
1413         EndBuffer = Source->buf + Source->BufUsed;
1414
1415         if (dest != NULL) 
1416         {
1417                 dest->buf[0] = '\0';
1418                 dest->BufUsed = 0;
1419         }
1420         else
1421         {
1422                 *pStart = EndBuffer + 1;
1423                 return -1;
1424         }
1425
1426         if (*pStart == NULL)
1427         {
1428                 *pStart = Source->buf; /* we're starting to examine this buffer. */
1429         }
1430         else if ((*pStart < Source->buf) || 
1431                  (*pStart > EndBuffer  )   ) 
1432         {
1433                 return -1; /* no more tokens to find. */
1434         }
1435
1436         s = *pStart;
1437         /* start to find the next token */
1438         while ((s <= EndBuffer)      && 
1439                (current_token == 0) ) 
1440         {
1441                 if (*s == separator) 
1442                 {
1443                         /* we found the next token */
1444                         ++current_token;
1445                 }
1446
1447                 if (len >= dest->BufSize) 
1448                 {
1449                         /* our Dest-buffer isn't big enough, increase it. */
1450                         dest->BufUsed = len;
1451
1452                         if (IncreaseBuf(dest, 1, -1) < 0) {
1453                                 /* WHUT? no more mem? bail out. */
1454                                 s = EndBuffer;
1455                                 dest->BufUsed --;
1456                                 break;
1457                         }
1458                 }
1459
1460                 if ( (current_token == 0 ) &&   /* are we in our target token? */
1461                      (!IsEmptyStr(s)     ) &&
1462                      (separator     != *s)    ) /* don't copy the token itself */
1463                 {
1464                         dest->buf[len] = *s;    /* Copy the payload */
1465                         ++len;                  /* remember the bigger size. */
1466                 }
1467
1468                 ++s;
1469         }
1470
1471         /* did we reach the end? */
1472         if ((s > EndBuffer)) {
1473                 EndBuffer = StrBufNOTNULL;
1474                 *pStart = EndBuffer;
1475         }
1476         else {
1477                 *pStart = s;  /* remember the position for the next run */
1478         }
1479
1480         /* sanitize our extracted token */
1481         dest->buf[len] = '\0';
1482         dest->BufUsed  = len;
1483
1484         return (len);
1485 }
1486
1487
1488 /**
1489  * @brief a string tokenizer
1490  * @param dest Destination StringBuffer
1491  * @param Source StringBuffer to read into
1492  * @param pStart pointer to the end of the last token. Feed with NULL.
1493  * @param separator tokenizer @param
1494  * @returns -1 if not found, else length of token.
1495  */
1496 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1497 {
1498         const char *s, *EndBuffer;      //* source * /
1499         int len = 0;                    //* running total length of extracted string * /
1500         int current_token = 0;          //* token currently being processed * /
1501
1502         if ((Source == NULL) || 
1503             (Source->BufUsed ==0)) {
1504                 return(-1);
1505         }
1506         if (nTokens == 0)
1507                 return Source->BufUsed;
1508
1509         if (*pStart == NULL)
1510                 *pStart = Source->buf;
1511
1512         EndBuffer = Source->buf + Source->BufUsed;
1513
1514         if ((*pStart < Source->buf) || 
1515             (*pStart >  EndBuffer)) {
1516                 return (-1);
1517         }
1518
1519
1520         s = *pStart;
1521
1522         //cit_backtrace();
1523         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1524
1525         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1526                 if (*s == separator) {
1527                         ++current_token;
1528                 }
1529                 if (current_token >= nTokens) {
1530                         break;
1531                 }
1532                 ++s;
1533         }
1534         *pStart = s;
1535         (*pStart) ++;
1536
1537         return(len);
1538 }
1539
1540 /**
1541  * @brief a string tokenizer to fetch an integer
1542  * @param dest Destination StringBuffer
1543  * @param parmnum n'th @parameter to extract
1544  * @param separator tokenizer @param
1545  * @returns 0 if not found, else integer representation of the token
1546  */
1547 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1548 {
1549         StrBuf tmp;
1550         char buf[64];
1551         
1552         tmp.buf = buf;
1553         buf[0] = '\0';
1554         tmp.BufSize = 64;
1555         tmp.BufUsed = 0;
1556         tmp.ConstBuf = 1;
1557         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1558                 return(atoi(buf));
1559         else
1560                 return 0;
1561 }
1562
1563 /**
1564  * @brief a string tokenizer to fetch a long integer
1565  * @param dest Destination StringBuffer
1566  * @param parmnum n'th @parameter to extract
1567  * @param separator tokenizer @param
1568  * @returns 0 if not found, else long integer representation of the token
1569  */
1570 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1571 {
1572         StrBuf tmp;
1573         char buf[64];
1574         
1575         tmp.buf = buf;
1576         buf[0] = '\0';
1577         tmp.BufSize = 64;
1578         tmp.BufUsed = 0;
1579         tmp.ConstBuf = 1;
1580         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1581                 return(atoi(buf));
1582         else
1583                 return 0;
1584 }
1585
1586
1587 /**
1588  * @brief a string tokenizer to fetch an unsigned long
1589  * @param dest Destination StringBuffer
1590  * @param parmnum n'th @parameter to extract
1591  * @param separator tokenizer @param
1592  * @returns 0 if not found, else unsigned long representation of the token
1593  */
1594 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1595 {
1596         StrBuf tmp;
1597         char buf[64];
1598         char *pnum;
1599         
1600         tmp.buf = buf;
1601         buf[0] = '\0';
1602         tmp.BufSize = 64;
1603         tmp.BufUsed = 0;
1604         tmp.ConstBuf = 1;
1605         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1606                 pnum = &buf[0];
1607                 if (*pnum == '-')
1608                         pnum ++;
1609                 return (unsigned long) atol(pnum);
1610         }
1611         else 
1612                 return 0;
1613 }
1614
1615
1616
1617 /**
1618  * @brief Read a line from socket
1619  * flushes and closes the FD on error
1620  * @param buf the buffer to get the input to
1621  * @param fd pointer to the filedescriptor to read
1622  * @param append Append to an existing string or replace?
1623  * @param Error strerror() on error 
1624  * @returns numbers of chars read
1625  */
1626 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1627 {
1628         int len, rlen, slen;
1629
1630         if (!append)
1631                 FlushStrBuf(buf);
1632
1633         slen = len = buf->BufUsed;
1634         while (1) {
1635                 rlen = read(*fd, &buf->buf[len], 1);
1636                 if (rlen < 1) {
1637                         *Error = strerror(errno);
1638                         
1639                         close(*fd);
1640                         *fd = -1;
1641                         
1642                         return -1;
1643                 }
1644                 if (buf->buf[len] == '\n')
1645                         break;
1646                 if (buf->buf[len] != '\r')
1647                         len ++;
1648                 if (len >= buf->BufSize) {
1649                         buf->BufUsed = len;
1650                         buf->buf[len+1] = '\0';
1651                         IncreaseBuf(buf, 1, -1);
1652                 }
1653         }
1654         buf->BufUsed = len;
1655         buf->buf[len] = '\0';
1656         return len - slen;
1657 }
1658
1659 /**
1660  * @brief Read a line from socket
1661  * flushes and closes the FD on error
1662  * @param buf the buffer to get the input to
1663  * @param fd pointer to the filedescriptor to read
1664  * @param append Append to an existing string or replace?
1665  * @param Error strerror() on error 
1666  * @returns numbers of chars read
1667  */
1668 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1669                                  StrBuf *buf, 
1670                                  int *fd, 
1671                                  int timeout, 
1672                                  int selectresolution, 
1673                                  const char **Error)
1674 {
1675         int len, rlen;
1676         int nSuccessLess = 0;
1677         fd_set rfds;
1678         char *pch = NULL;
1679         int fdflags;
1680         struct timeval tv;
1681
1682         if (buf->BufUsed > 0) {
1683                 pch = strchr(buf->buf, '\n');
1684                 if (pch != NULL) {
1685                         rlen = 0;
1686                         len = pch - buf->buf;
1687                         if (len > 0 && (*(pch - 1) == '\r') )
1688                                 rlen ++;
1689                         StrBufSub(Line, buf, 0, len - rlen);
1690                         StrBufCutLeft(buf, len + 1);
1691                         return len - rlen;
1692                 }
1693         }
1694         
1695         if (buf->BufSize - buf->BufUsed < 10)
1696                 IncreaseBuf(buf, 1, -1);
1697
1698         fdflags = fcntl(*fd, F_GETFL);
1699         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1700                 return -1;
1701
1702         while ((nSuccessLess < timeout) && (pch == NULL)) {
1703                 tv.tv_sec = selectresolution;
1704                 tv.tv_usec = 0;
1705                 
1706                 FD_ZERO(&rfds);
1707                 FD_SET(*fd, &rfds);
1708                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1709                         *Error = strerror(errno);
1710                         close (*fd);
1711                         *fd = -1;
1712                         return -1;
1713                 }               
1714                 if (FD_ISSET(*fd, &rfds)) {
1715                         rlen = read(*fd, 
1716                                     &buf->buf[buf->BufUsed], 
1717                                     buf->BufSize - buf->BufUsed - 1);
1718                         if (rlen < 1) {
1719                                 *Error = strerror(errno);
1720                                 close(*fd);
1721                                 *fd = -1;
1722                                 return -1;
1723                         }
1724                         else if (rlen > 0) {
1725                                 nSuccessLess = 0;
1726                                 buf->BufUsed += rlen;
1727                                 buf->buf[buf->BufUsed] = '\0';
1728                                 if (buf->BufUsed + 10 > buf->BufSize) {
1729                                         IncreaseBuf(buf, 1, -1);
1730                                 }
1731                                 pch = strchr(buf->buf, '\n');
1732                                 continue;
1733                         }
1734                 }
1735                 nSuccessLess ++;
1736         }
1737         if (pch != NULL) {
1738                 rlen = 0;
1739                 len = pch - buf->buf;
1740                 if (len > 0 && (*(pch - 1) == '\r') )
1741                         rlen ++;
1742                 StrBufSub(Line, buf, 0, len - rlen);
1743                 StrBufCutLeft(buf, len + 1);
1744                 return len - rlen;
1745         }
1746         return -1;
1747
1748 }
1749
1750 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1751 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1752 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1753 /**
1754  * @brief Read a line from socket
1755  * flushes and closes the FD on error
1756  * @param buf the buffer to get the input to
1757  * @param Pos pointer to the current read position, should be NULL initialized!
1758  * @param fd pointer to the filedescriptor to read
1759  * @param append Append to an existing string or replace?
1760  * @param Error strerror() on error 
1761  * @returns numbers of chars read
1762  */
1763 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
1764                                       StrBuf *IOBuf, 
1765                                       const char **Pos,
1766                                       int *fd, 
1767                                       int timeout, 
1768                                       int selectresolution, 
1769                                       const char **Error)
1770 {
1771         const char *pche = NULL;
1772         const char *pos = NULL;
1773         int len, rlen;
1774         int nSuccessLess = 0;
1775         fd_set rfds;
1776         const char *pch = NULL;
1777         int fdflags;
1778         struct timeval tv;
1779         
1780         pos = *Pos;
1781         if ((IOBuf->BufUsed > 0) && 
1782             (pos != NULL) && 
1783             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1784         {
1785                 pche = IOBuf->buf + IOBuf->BufUsed;
1786                 pch = pos;
1787                 while ((pch < pche) && (*pch != '\n'))
1788                         pch ++;
1789                 if ((pch >= pche) || (*pch == '\0'))
1790                         pch = NULL;
1791                 if ((pch != NULL) && 
1792                     (pch <= pche)) 
1793                 {
1794                         rlen = 0;
1795                         len = pch - pos;
1796                         if (len > 0 && (*(pch - 1) == '\r') )
1797                                 rlen ++;
1798                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1799                         *Pos = pch + 1;
1800                         return len - rlen;
1801                 }
1802         }
1803         
1804         if (pos != NULL) {
1805                 if (pos > pche)
1806                         FlushStrBuf(IOBuf);
1807                 else 
1808                         StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1809                 *Pos = NULL;
1810         }
1811         
1812         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1813                 IncreaseBuf(IOBuf, 1, -1);
1814         }
1815
1816         fdflags = fcntl(*fd, F_GETFL);
1817         if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1818                 *Error = ErrRBLF_WrongFDFlags;
1819                 return -1;
1820         }
1821
1822         pch = NULL;
1823         while ((nSuccessLess < timeout) && (pch == NULL)) {
1824                 tv.tv_sec = selectresolution;
1825                 tv.tv_usec = 0;
1826                 
1827                 FD_ZERO(&rfds);
1828                 FD_SET(*fd, &rfds);
1829                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1830                         *Error = strerror(errno);
1831                         close (*fd);
1832                         *fd = -1;
1833                         if (*Error == NULL)
1834                                 *Error = ErrRBLF_SelectFailed;
1835                         return -1;
1836                 }               
1837                 if (FD_ISSET(*fd, &rfds) != 0) {
1838                         rlen = read(*fd, 
1839                                     &IOBuf->buf[IOBuf->BufUsed], 
1840                                     IOBuf->BufSize - IOBuf->BufUsed - 1);
1841                         if (rlen < 1) {
1842                                 *Error = strerror(errno);
1843                                 close(*fd);
1844                                 *fd = -1;
1845                                 return -1;
1846                         }
1847                         else if (rlen > 0) {
1848                                 nSuccessLess = 0;
1849                                 IOBuf->BufUsed += rlen;
1850                                 IOBuf->buf[IOBuf->BufUsed] = '\0';
1851                                 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1852                                         IncreaseBuf(IOBuf, 1, -1);
1853                                 }
1854
1855                                 pche = IOBuf->buf + IOBuf->BufUsed;
1856                                 pch = IOBuf->buf;
1857                                 while ((pch < pche) && (*pch != '\n'))
1858                                         pch ++;
1859                                 if ((pch >= pche) || (*pch == '\0'))
1860                                         pch = NULL;
1861                                 continue;
1862                         }
1863                 }
1864                 nSuccessLess ++;
1865         }
1866         if (pch != NULL) {
1867                 pos = IOBuf->buf;
1868                 rlen = 0;
1869                 len = pch - pos;
1870                 if (len > 0 && (*(pch - 1) == '\r') )
1871                         rlen ++;
1872                 StrBufSub(Line, IOBuf, 0, len - rlen);
1873                 *Pos = pos + len + 1;
1874                 return len - rlen;
1875         }
1876         *Error = ErrRBLF_NotEnoughSentFromServer;
1877         return -1;
1878
1879 }
1880
1881 /**
1882  * @brief Input binary data from socket
1883  * flushes and closes the FD on error
1884  * @param buf the buffer to get the input to
1885  * @param fd pointer to the filedescriptor to read
1886  * @param append Append to an existing string or replace?
1887  * @param nBytes the maximal number of bytes to read
1888  * @param Error strerror() on error 
1889  * @returns numbers of chars read
1890  */
1891 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1892 {
1893         fd_set wset;
1894         int fdflags;
1895         int len, rlen, slen;
1896         int nRead = 0;
1897         char *ptr;
1898
1899         if ((Buf == NULL) || (*fd == -1))
1900                 return -1;
1901         if (!append)
1902                 FlushStrBuf(Buf);
1903         if (Buf->BufUsed + nBytes >= Buf->BufSize)
1904                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1905
1906         ptr = Buf->buf + Buf->BufUsed;
1907
1908         slen = len = Buf->BufUsed;
1909
1910         fdflags = fcntl(*fd, F_GETFL);
1911
1912         while (nRead < nBytes) {
1913                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1914                         FD_ZERO(&wset);
1915                         FD_SET(*fd, &wset);
1916                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1917                                 *Error = strerror(errno);
1918                                 return -1;
1919                         }
1920                 }
1921
1922                 if ((rlen = read(*fd, 
1923                                  ptr,
1924                                  nBytes - nRead)) == -1) {
1925                         close(*fd);
1926                         *fd = -1;
1927                         *Error = strerror(errno);
1928                         return rlen;
1929                 }
1930                 nRead += rlen;
1931                 ptr += rlen;
1932                 Buf->BufUsed += rlen;
1933         }
1934         Buf->buf[Buf->BufUsed] = '\0';
1935         return nRead;
1936 }
1937
1938 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1939 /**
1940  * @brief Input binary data from socket
1941  * flushes and closes the FD on error
1942  * @param buf the buffer to get the input to
1943  * @param fd pointer to the filedescriptor to read
1944  * @param append Append to an existing string or replace?
1945  * @param nBytes the maximal number of bytes to read
1946  * @param Error strerror() on error 
1947  * @returns numbers of chars read
1948  */
1949 int StrBufReadBLOBBuffered(StrBuf *Blob, 
1950                            StrBuf *IOBuf, 
1951                            const char **Pos,
1952                            int *fd, 
1953                            int append, 
1954                            long nBytes, 
1955                            int check, 
1956                            const char **Error)
1957 {
1958         const char *pche;
1959         const char *pos;
1960         int nSelects = 0;
1961         int SelRes;
1962         fd_set wset;
1963         int fdflags;
1964         int len = 0;
1965         int rlen, slen;
1966         int nRead = 0;
1967         int nAlreadyRead = 0;
1968         char *ptr;
1969         const char *pch;
1970
1971         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1972                 return -1;
1973         if (!append)
1974                 FlushStrBuf(Blob);
1975         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
1976                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1977         
1978         pos = *Pos;
1979
1980         if (pos > 0)
1981                 len = pos - IOBuf->buf;
1982         rlen = IOBuf->BufUsed - len;
1983
1984
1985         if ((IOBuf->BufUsed > 0) && 
1986             (pos != NULL) && 
1987             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1988         {
1989                 pche = IOBuf->buf + IOBuf->BufUsed;
1990                 pch = pos;
1991
1992                 if (rlen < nBytes) {
1993                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1994                         Blob->BufUsed += rlen;
1995                         Blob->buf[Blob->BufUsed] = '\0';
1996                         nAlreadyRead = nRead = rlen;
1997                         *Pos = NULL; 
1998                 }
1999                 if (rlen >= nBytes) {
2000                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2001                         Blob->BufUsed += nBytes;
2002                         Blob->buf[Blob->BufUsed] = '\0';
2003                         if (rlen == nBytes) {
2004                                 *Pos = NULL; 
2005                                 FlushStrBuf(IOBuf);
2006                         }
2007                         else 
2008                                 *Pos += nBytes;
2009                         return nBytes;
2010                 }
2011         }
2012
2013         FlushStrBuf(IOBuf);
2014         if (IOBuf->BufSize < nBytes - nRead)
2015                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2016         ptr = IOBuf->buf;
2017
2018         slen = len = Blob->BufUsed;
2019
2020         fdflags = fcntl(*fd, F_GETFL);
2021
2022         SelRes = 1;
2023         nBytes -= nRead;
2024         nRead = 0;
2025         while (nRead < nBytes) {
2026                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
2027                         FD_ZERO(&wset);
2028                         FD_SET(*fd, &wset);
2029                         SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
2030                 }
2031                 if (SelRes == -1) {
2032                         *Error = strerror(errno);
2033                         return -1;
2034                 }
2035                 else if (SelRes) {
2036                         nSelects = 0;
2037                         rlen = read(*fd, 
2038                                     ptr,
2039                                     nBytes - nRead);
2040                         if (rlen == -1) {
2041                                 close(*fd);
2042                                 *fd = -1;
2043                                 *Error = strerror(errno);
2044                                 return rlen;
2045                         }
2046                 }
2047                 else {
2048                         nSelects ++;
2049                         if ((check == NNN_TERM) && 
2050                             (nRead > 5) &&
2051                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
2052                         {
2053                                 StrBufPlain(Blob, HKEY("\n000\n"));
2054                                 StrBufCutRight(Blob, 5);
2055                                 return Blob->BufUsed;
2056                         }
2057                         if (nSelects > 10) {
2058                                 FlushStrBuf(IOBuf);
2059                                 *Error = ErrRBB_too_many_selects;
2060                                 return -1;
2061                         }
2062                 }
2063                 if (rlen > 0) {
2064                         nRead += rlen;
2065                         ptr += rlen;
2066                         IOBuf->BufUsed += rlen;
2067                 }
2068         }
2069         if (nRead > nBytes) {
2070                 *Pos = IOBuf->buf + nBytes;
2071         }
2072         Blob->buf[Blob->BufUsed] = '\0';
2073         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2074         if (*Pos == NULL) {
2075                 FlushStrBuf(IOBuf);
2076         }
2077         return nRead + nAlreadyRead;
2078 }
2079
2080 /**
2081  * @brief Cut nChars from the start of the string
2082  * @param Buf Buffer to modify
2083  * @param nChars how many chars should be skipped?
2084  */
2085 void StrBufCutLeft(StrBuf *Buf, int nChars)
2086 {
2087         if (nChars >= Buf->BufUsed) {
2088                 FlushStrBuf(Buf);
2089                 return;
2090         }
2091         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2092         Buf->BufUsed -= nChars;
2093         Buf->buf[Buf->BufUsed] = '\0';
2094 }
2095
2096 /**
2097  * @brief Cut the trailing n Chars from the string
2098  * @param Buf Buffer to modify
2099  * @param nChars how many chars should be trunkated?
2100  */
2101 void StrBufCutRight(StrBuf *Buf, int nChars)
2102 {
2103         if (nChars >= Buf->BufUsed) {
2104                 FlushStrBuf(Buf);
2105                 return;
2106         }
2107         Buf->BufUsed -= nChars;
2108         Buf->buf[Buf->BufUsed] = '\0';
2109 }
2110
2111 /**
2112  * @brief Cut the string after n Chars
2113  * @param Buf Buffer to modify
2114  * @param AfternChars after how many chars should we trunkate the string?
2115  * @param At if non-null and points inside of our string, cut it there.
2116  */
2117 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2118 {
2119         if (At != NULL){
2120                 AfternChars = At - Buf->buf;
2121         }
2122
2123         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2124                 return;
2125         Buf->BufUsed = AfternChars;
2126         Buf->buf[Buf->BufUsed] = '\0';
2127 }
2128
2129
2130 /**
2131  * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2132  * @param buf the string to modify
2133  * @param len length of the string. 
2134  */
2135 void StrBufTrim(StrBuf *Buf)
2136 {
2137         int delta = 0;
2138         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2139
2140         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2141                 delta ++;
2142         }
2143         if (delta > 0) StrBufCutLeft(Buf, delta);
2144
2145         if (Buf->BufUsed == 0) return;
2146         while (isspace(Buf->buf[Buf->BufUsed - 1])){
2147                 Buf->BufUsed --;
2148         }
2149         Buf->buf[Buf->BufUsed] = '\0';
2150 }
2151
2152 /**
2153  * @brief uppercase the contents of a buffer
2154  * @param Buf the buffer to translate
2155  */
2156 void StrBufUpCase(StrBuf *Buf) 
2157 {
2158         char *pch, *pche;
2159
2160         pch = Buf->buf;
2161         pche = pch + Buf->BufUsed;
2162         while (pch < pche) {
2163                 *pch = toupper(*pch);
2164                 pch ++;
2165         }
2166 }
2167
2168
2169 /**
2170  * @brief lowercase the contents of a buffer
2171  * @param Buf the buffer to translate
2172  */
2173 void StrBufLowerCase(StrBuf *Buf) 
2174 {
2175         char *pch, *pche;
2176
2177         pch = Buf->buf;
2178         pche = pch + Buf->BufUsed;
2179         while (pch < pche) {
2180                 *pch = tolower(*pch);
2181                 pch ++;
2182         }
2183 }
2184
2185 /**
2186  * @brief removes double slashes from pathnames
2187  * @param Dir directory string to filter
2188  * @param RemoveTrailingSlash allows / disallows trailing slashes
2189  */
2190 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2191 {
2192         char *a, *b;
2193
2194         a = b = Dir->buf;
2195
2196         while (!IsEmptyStr(a)) {
2197                 if (*a == '/') {
2198                         while (*a == '/')
2199                                 a++;
2200                         *b = '/';
2201                         b++;
2202                 }
2203                 else {
2204                         *b = *a;
2205                         b++; a++;
2206                 }
2207         }
2208         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2209                 *b = '/';
2210                 b++;
2211         }
2212         *b = '\0';
2213         Dir->BufUsed = b - Dir->buf;
2214 }
2215
2216 /**
2217  * @brief unhide special chars hidden to the HTML escaper
2218  * @param target buffer to put the unescaped string in
2219  * @param source buffer to unescape
2220  */
2221 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2222 {
2223         int a, b, len;
2224         char hex[3];
2225
2226         if (target != NULL)
2227                 FlushStrBuf(target);
2228
2229         if (source == NULL ||target == NULL)
2230         {
2231                 return;
2232         }
2233
2234         len = source->BufUsed;
2235         for (a = 0; a < len; ++a) {
2236                 if (target->BufUsed >= target->BufSize)
2237                         IncreaseBuf(target, 1, -1);
2238
2239                 if (source->buf[a] == '=') {
2240                         hex[0] = source->buf[a + 1];
2241                         hex[1] = source->buf[a + 2];
2242                         hex[2] = 0;
2243                         b = 0;
2244                         sscanf(hex, "%02x", &b);
2245                         target->buf[target->BufUsed] = b;
2246                         target->buf[++target->BufUsed] = 0;
2247                         a += 2;
2248                 }
2249                 else {
2250                         target->buf[target->BufUsed] = source->buf[a];
2251                         target->buf[++target->BufUsed] = 0;
2252                 }
2253         }
2254 }
2255
2256
2257 /**
2258  * @brief hide special chars from the HTML escapers and friends
2259  * @param target buffer to put the escaped string in
2260  * @param source buffer to escape
2261  */
2262 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2263 {
2264         int i, len;
2265
2266         if (target != NULL)
2267                 FlushStrBuf(target);
2268
2269         if (source == NULL ||target == NULL)
2270         {
2271                 return;
2272         }
2273
2274         len = source->BufUsed;
2275         for (i=0; i<len; ++i) {
2276                 if (target->BufUsed + 4 >= target->BufSize)
2277                         IncreaseBuf(target, 1, -1);
2278                 if ( (isalnum(source->buf[i])) || 
2279                      (source->buf[i]=='-') || 
2280                      (source->buf[i]=='_') ) {
2281                         target->buf[target->BufUsed++] = source->buf[i];
2282                 }
2283                 else {
2284                         sprintf(&target->buf[target->BufUsed], 
2285                                 "=%02X", 
2286                                 (0xFF &source->buf[i]));
2287                         target->BufUsed += 3;
2288                 }
2289         }
2290         target->buf[target->BufUsed + 1] = '\0';
2291 }
2292
2293 /**
2294  * @brief uses the same calling syntax as compress2(), but it
2295  *   creates a stream compatible with HTTP "Content-encoding: gzip"
2296  */
2297 #ifdef HAVE_ZLIB
2298 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2299 #define OS_CODE 0x03    /*< unix */
2300 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
2301                           size_t * destLen,     /*< length of the compresed data */
2302                           const Bytef * source, /*< source to encode */
2303                           uLong sourceLen,      /*< length of source to encode */
2304                           int level)            /*< compression level */
2305 {
2306         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2307
2308         /* write gzip header */
2309         snprintf((char *) dest, *destLen, 
2310                  "%c%c%c%c%c%c%c%c%c%c",
2311                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2312                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2313                  OS_CODE);
2314
2315         /* normal deflate */
2316         z_stream stream;
2317         int err;
2318         stream.next_in = (Bytef *) source;
2319         stream.avail_in = (uInt) sourceLen;
2320         stream.next_out = dest + 10L;   // after header
2321         stream.avail_out = (uInt) * destLen;
2322         if ((uLong) stream.avail_out != *destLen)
2323                 return Z_BUF_ERROR;
2324
2325         stream.zalloc = (alloc_func) 0;
2326         stream.zfree = (free_func) 0;
2327         stream.opaque = (voidpf) 0;
2328
2329         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2330                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2331         if (err != Z_OK)
2332                 return err;
2333
2334         err = deflate(&stream, Z_FINISH);
2335         if (err != Z_STREAM_END) {
2336                 deflateEnd(&stream);
2337                 return err == Z_OK ? Z_BUF_ERROR : err;
2338         }
2339         *destLen = stream.total_out + 10L;
2340
2341         /* write CRC and Length */
2342         uLong crc = crc32(0L, source, sourceLen);
2343         int n;
2344         for (n = 0; n < 4; ++n, ++*destLen) {
2345                 dest[*destLen] = (int) (crc & 0xff);
2346                 crc >>= 8;
2347         }
2348         uLong len = stream.total_in;
2349         for (n = 0; n < 4; ++n, ++*destLen) {
2350                 dest[*destLen] = (int) (len & 0xff);
2351                 len >>= 8;
2352         }
2353         err = deflateEnd(&stream);
2354         return err;
2355 }
2356 #endif
2357
2358
2359 /**
2360  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2361  */
2362 int CompressBuffer(StrBuf *Buf)
2363 {
2364 #ifdef HAVE_ZLIB
2365         char *compressed_data = NULL;
2366         size_t compressed_len, bufsize;
2367         int i = 0;
2368
2369         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
2370         compressed_data = malloc(compressed_len);
2371         
2372         if (compressed_data == NULL)
2373                 return -1;
2374         /* Flush some space after the used payload so valgrind shuts up... */
2375         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2376                 Buf->buf[Buf->BufUsed + i++] = '\0';
2377         if (compress_gzip((Bytef *) compressed_data,
2378                           &compressed_len,
2379                           (Bytef *) Buf->buf,
2380                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2381                 if (!Buf->ConstBuf)
2382                         free(Buf->buf);
2383                 Buf->buf = compressed_data;
2384                 Buf->BufUsed = compressed_len;
2385                 Buf->BufSize = bufsize;
2386                 /* Flush some space after the used payload so valgrind shuts up... */
2387                 i = 0;
2388                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2389                         Buf->buf[Buf->BufUsed + i++] = '\0';
2390                 return 1;
2391         } else {
2392                 free(compressed_data);
2393         }
2394 #endif  /* HAVE_ZLIB */
2395         return 0;
2396 }
2397
2398 /**
2399  * @brief decode a buffer from base 64 encoding; destroys original
2400  * @param Buf Buffor to transform
2401  */
2402 int StrBufDecodeBase64(StrBuf *Buf)
2403 {
2404         char *xferbuf;
2405         size_t siz;
2406         if (Buf == NULL) return -1;
2407
2408         xferbuf = (char*) malloc(Buf->BufSize);
2409         siz = CtdlDecodeBase64(xferbuf,
2410                                Buf->buf,
2411                                Buf->BufUsed);
2412         free(Buf->buf);
2413         Buf->buf = xferbuf;
2414         Buf->BufUsed = siz;
2415         return siz;
2416 }
2417
2418 /**
2419  * @brief decode a buffer from base 64 encoding; destroys original
2420  * @param Buf Buffor to transform
2421  */
2422 int StrBufDecodeHex(StrBuf *Buf)
2423 {
2424         unsigned int ch;
2425         char *pch, *pche, *pchi;
2426
2427         if (Buf == NULL) return -1;
2428
2429         pch = pchi = Buf->buf;
2430         pche = pch + Buf->BufUsed;
2431
2432         while (pchi < pche){
2433                 ch = decode_hex(pchi);
2434                 *pch = ch;
2435                 pch ++;
2436                 pchi += 2;
2437         }
2438
2439         *pch = '\0';
2440         Buf->BufUsed = pch - Buf->buf;
2441         return Buf->BufUsed;
2442 }
2443
2444 /**
2445  * @brief replace all chars >0x20 && < 0x7F with Mute
2446  * @param Mute char to put over invalid chars
2447  * @param Buf Buffor to transform
2448  */
2449 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2450 {
2451         unsigned char *pch;
2452
2453         if (Buf == NULL) return -1;
2454         pch = (unsigned char *)Buf->buf;
2455         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2456                 if ((*pch < 0x20) || (*pch > 0x7F))
2457                         *pch = Mute;
2458                 pch ++;
2459         }
2460         return Buf->BufUsed;
2461 }
2462
2463
2464 /**
2465  * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2466  * @param Buf Buffer to translate
2467  * @param StripBlanks Reduce several blanks to one?
2468  */
2469 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2470 {
2471         int a, b;
2472         char hex[3];
2473         long len;
2474
2475         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2476                 Buf->buf[Buf->BufUsed - 1] = '\0';
2477                 Buf->BufUsed --;
2478         }
2479
2480         a = 0; 
2481         while (a < Buf->BufUsed) {
2482                 if (Buf->buf[a] == '+')
2483                         Buf->buf[a] = ' ';
2484                 else if (Buf->buf[a] == '%') {
2485                         /* don't let % chars through, rather truncate the input. */
2486                         if (a + 2 > Buf->BufUsed) {
2487                                 Buf->buf[a] = '\0';
2488                                 Buf->BufUsed = a;
2489                         }
2490                         else {                  
2491                                 hex[0] = Buf->buf[a + 1];
2492                                 hex[1] = Buf->buf[a + 2];
2493                                 hex[2] = 0;
2494                                 b = 0;
2495                                 sscanf(hex, "%02x", &b);
2496                                 Buf->buf[a] = (char) b;
2497                                 len = Buf->BufUsed - a - 2;
2498                                 if (len > 0)
2499                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2500                         
2501                                 Buf->BufUsed -=2;
2502                         }
2503                 }
2504                 a++;
2505         }
2506         return a;
2507 }
2508
2509
2510 /**
2511  * @brief       RFC2047-encode a header field if necessary.
2512  *              If no non-ASCII characters are found, the string
2513  *              will be copied verbatim without encoding.
2514  *
2515  * @param       target          Target buffer.
2516  * @param       source          Source string to be encoded.
2517  * @returns     encoded length; -1 if non success.
2518  */
2519 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2520 {
2521         const char headerStr[] = "=?UTF-8?Q?";
2522         int need_to_encode = 0;
2523         int i = 0;
2524         unsigned char ch;
2525
2526         if ((source == NULL) || 
2527             (target == NULL))
2528             return -1;
2529
2530         while ((i < source->BufUsed) &&
2531                (!IsEmptyStr (&source->buf[i])) &&
2532                (need_to_encode == 0)) {
2533                 if (((unsigned char) source->buf[i] < 32) || 
2534                     ((unsigned char) source->buf[i] > 126)) {
2535                         need_to_encode = 1;
2536                 }
2537                 i++;
2538         }
2539
2540         if (!need_to_encode) {
2541                 if (*target == NULL) {
2542                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2543                 }
2544                 else {
2545                         FlushStrBuf(*target);
2546                         StrBufAppendBuf(*target, source, 0);
2547                 }
2548                 return (*target)->BufUsed;
2549         }
2550         if (*target == NULL)
2551                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2552         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2553                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2554         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2555         (*target)->BufUsed = sizeof(headerStr) - 1;
2556         for (i=0; (i < source->BufUsed); ++i) {
2557                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2558                         IncreaseBuf(*target, 1, 0);
2559                 ch = (unsigned char) source->buf[i];
2560                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2561                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2562                         (*target)->BufUsed += 3;
2563                 }
2564                 else {
2565                         (*target)->buf[(*target)->BufUsed] = ch;
2566                         (*target)->BufUsed++;
2567                 }
2568         }
2569         
2570         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2571                 IncreaseBuf(*target, 1, 0);
2572
2573         (*target)->buf[(*target)->BufUsed++] = '?';
2574         (*target)->buf[(*target)->BufUsed++] = '=';
2575         (*target)->buf[(*target)->BufUsed] = '\0';
2576         return (*target)->BufUsed;;
2577 }
2578
2579 /**
2580  * @brief replaces all occurances of 'search' by 'replace'
2581  * @param buf Buffer to modify
2582  * @param search character to search
2583  * @param relpace character to replace search by
2584  */
2585 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2586 {
2587         long i;
2588         if (buf == NULL)
2589                 return;
2590         for (i=0; i<buf->BufUsed; i++)
2591                 if (buf->buf[i] == search)
2592                         buf->buf[i] = replace;
2593
2594 }
2595
2596
2597
2598 /**
2599  * @brief Wrapper around iconv_open()
2600  * Our version adds aliases for non-standard Microsoft charsets
2601  * such as 'MS950', aliasing them to names like 'CP950'
2602  *
2603  * @param tocode        Target encoding
2604  * @param fromcode      Source encoding
2605  */
2606 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2607 {
2608 #ifdef HAVE_ICONV
2609         iconv_t ic = (iconv_t)(-1) ;
2610         ic = iconv_open(tocode, fromcode);
2611         if (ic == (iconv_t)(-1) ) {
2612                 char alias_fromcode[64];
2613                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2614                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2615                         alias_fromcode[0] = 'C';
2616                         alias_fromcode[1] = 'P';
2617                         ic = iconv_open(tocode, alias_fromcode);
2618                 }
2619         }
2620         *(iconv_t *)pic = ic;
2621 #endif
2622 }
2623
2624
2625 /**
2626  * @brief find one chunk of a RFC822 encoded string
2627  * @param Buffer where to search
2628  * @param bptr where to start searching
2629  * @returns found position, NULL if none.
2630  */
2631 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2632 {
2633         char * end;
2634         /* Find the next ?Q? */
2635         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2636                 return NULL;
2637
2638         end = strchr(bptr + 2, '?');
2639
2640         if (end == NULL)
2641                 return NULL;
2642
2643         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2644             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
2645             (*(end + 2) == '?')) {
2646                 /* skip on to the end of the cluster, the next ?= */
2647                 end = strstr(end + 3, "?=");
2648         }
2649         else
2650                 /* sort of half valid encoding, try to find an end. */
2651                 end = strstr(bptr, "?=");
2652         return end;
2653 }
2654
2655 /**
2656  * @brief swaps the contents of two StrBufs
2657  * this is to be used to have cheap switched between a work-buffer and a target buffer 
2658  * @param A First one
2659  * @param B second one
2660  */
2661 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2662 {
2663         StrBuf C;
2664
2665         memcpy(&C, A, sizeof(*A));
2666         memcpy(A, B, sizeof(*B));
2667         memcpy(B, &C, sizeof(C));
2668
2669 }
2670
2671
2672 /**
2673  * @brief convert one buffer according to the preselected iconv pointer PIC
2674  * @param ConvertBuf buffer we need to translate
2675  * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2676  * @param pic Pointer to the iconv-session Object
2677  */
2678 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2679 {
2680 #ifdef HAVE_ICONV
2681         long trycount = 0;
2682         size_t siz;
2683         iconv_t ic;
2684         char *ibuf;                     /**< Buffer of characters to be converted */
2685         char *obuf;                     /**< Buffer for converted characters */
2686         size_t ibuflen;                 /**< Length of input buffer */
2687         size_t obuflen;                 /**< Length of output buffer */
2688
2689
2690         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2691         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2692                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2693 TRYAGAIN:
2694         ic = *(iconv_t*)pic;
2695         ibuf = ConvertBuf->buf;
2696         ibuflen = ConvertBuf->BufUsed;
2697         obuf = TmpBuf->buf;
2698         obuflen = TmpBuf->BufSize;
2699         
2700         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2701
2702         if (siz < 0) {
2703                 if (errno == E2BIG) {
2704                         trycount ++;                    
2705                         IncreaseBuf(TmpBuf, 0, 0);
2706                         if (trycount < 5) 
2707                                 goto TRYAGAIN;
2708
2709                 }
2710                 else if (errno == EILSEQ){ 
2711                         /* hm, invalid utf8 sequence... what to do now? */
2712                         /* An invalid multibyte sequence has been encountered in the input */
2713                 }
2714                 else if (errno == EINVAL) {
2715                         /* An incomplete multibyte sequence has been encountered in the input. */
2716                 }
2717
2718                 FlushStrBuf(TmpBuf);
2719         }
2720         else {
2721                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2722                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2723                 
2724                 /* little card game: wheres the red lady? */
2725                 SwapBuffers(ConvertBuf, TmpBuf);
2726                 FlushStrBuf(TmpBuf);
2727         }
2728 #endif
2729 }
2730
2731
2732 /**
2733  * @brief catches one RFC822 encoded segment, and decodes it.
2734  * @param Target buffer to fill with result
2735  * @param DecodeMe buffer with stuff to process
2736  * @param SegmentStart points to our current segment in DecodeMe
2737  * @param SegmentEnd Points to the end of our current segment in DecodeMe
2738  * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2739  * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2740  * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2741  */
2742 inline static void DecodeSegment(StrBuf *Target, 
2743                                  const StrBuf *DecodeMe, 
2744                                  char *SegmentStart, 
2745                                  char *SegmentEnd, 
2746                                  StrBuf *ConvertBuf,
2747                                  StrBuf *ConvertBuf2, 
2748                                  StrBuf *FoundCharset)
2749 {
2750         StrBuf StaticBuf;
2751         char charset[128];
2752         char encoding[16];
2753 #ifdef HAVE_ICONV
2754         iconv_t ic = (iconv_t)(-1);
2755 #endif
2756         /* Now we handle foreign character sets properly encoded
2757          * in RFC2047 format.
2758          */
2759         StaticBuf.buf = SegmentStart;
2760         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2761         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2762         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2763         if (FoundCharset != NULL) {
2764                 FlushStrBuf(FoundCharset);
2765                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2766         }
2767         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2768         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2769         
2770         *encoding = toupper(*encoding);
2771         if (*encoding == 'B') { /**< base64 */
2772                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
2773                                                         ConvertBuf->buf, 
2774                                                         ConvertBuf->BufUsed);
2775         }
2776         else if (*encoding == 'Q') {    /**< quoted-printable */
2777                 long pos;
2778                 
2779                 pos = 0;
2780                 while (pos < ConvertBuf->BufUsed)
2781                 {
2782                         if (ConvertBuf->buf[pos] == '_') 
2783                                 ConvertBuf->buf[pos] = ' ';
2784                         pos++;
2785                 }
2786                 
2787                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2788                         ConvertBuf2->buf, 
2789                         ConvertBuf->buf,
2790                         ConvertBuf->BufUsed);
2791         }
2792         else {
2793                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2794         }
2795 #ifdef HAVE_ICONV
2796         ctdl_iconv_open("UTF-8", charset, &ic);
2797         if (ic != (iconv_t)(-1) ) {             
2798 #endif
2799                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2800                 StrBufAppendBuf(Target, ConvertBuf2, 0);
2801 #ifdef HAVE_ICONV
2802                 iconv_close(ic);
2803         }
2804         else {
2805                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2806         }
2807 #endif
2808 }
2809
2810 /**
2811  * @brief Handle subjects with RFC2047 encoding such as:
2812  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2813  * @param Target where to put the decoded string to 
2814  * @param DecodeMe buffer with encoded string
2815  * @param DefaultCharset if we don't find one, which should we use?
2816  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
2817  *        put it here for later use where no string might be known.
2818  */
2819 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2820 {
2821         StrBuf *DecodedInvalidBuf = NULL;
2822         StrBuf *ConvertBuf, *ConvertBuf2;
2823         const StrBuf *DecodeMee = DecodeMe;
2824         char *start, *end, *next, *nextend, *ptr = NULL;
2825 #ifdef HAVE_ICONV
2826         iconv_t ic = (iconv_t)(-1) ;
2827 #endif
2828         const char *eptr;
2829         int passes = 0;
2830         int i, len, delta;
2831         int illegal_non_rfc2047_encoding = 0;
2832
2833         /* Sometimes, badly formed messages contain strings which were simply
2834          *  written out directly in some foreign character set instead of
2835          *  using RFC2047 encoding.  This is illegal but we will attempt to
2836          *  handle it anyway by converting from a user-specified default
2837          *  charset to UTF-8 if we see any nonprintable characters.
2838          */
2839         
2840         len = StrLength(DecodeMe);
2841         for (i=0; i<DecodeMe->BufUsed; ++i) {
2842                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2843                         illegal_non_rfc2047_encoding = 1;
2844                         break;
2845                 }
2846         }
2847
2848         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2849         if ((illegal_non_rfc2047_encoding) &&
2850             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
2851             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2852         {
2853 #ifdef HAVE_ICONV
2854                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2855                 if (ic != (iconv_t)(-1) ) {
2856                         DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2857                         StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2858                         DecodeMee = DecodedInvalidBuf;
2859                         iconv_close(ic);
2860                 }
2861 #endif
2862         }
2863
2864         /* pre evaluate the first pair */
2865         nextend = end = NULL;
2866         len = StrLength(DecodeMee);
2867         start = strstr(DecodeMee->buf, "=?");
2868         eptr = DecodeMee->buf + DecodeMee->BufUsed;
2869         if (start != NULL) 
2870                 end = FindNextEnd (DecodeMee, start);
2871         else {
2872                 StrBufAppendBuf(Target, DecodeMee, 0);
2873                 FreeStrBuf(&ConvertBuf);
2874                 FreeStrBuf(&DecodedInvalidBuf);
2875                 return;
2876         }
2877
2878         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2879
2880         if (start != DecodeMee->buf) {
2881                 long nFront;
2882                 
2883                 nFront = start - DecodeMee->buf;
2884                 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2885                 len -= nFront;
2886         }
2887         /*
2888          * Since spammers will go to all sorts of absurd lengths to get their
2889          * messages through, there are LOTS of corrupt headers out there.
2890          * So, prevent a really badly formed RFC2047 header from throwing
2891          * this function into an infinite loop.
2892          */
2893         while ((start != NULL) && 
2894                (end != NULL) && 
2895                (start < eptr) && 
2896                (end < eptr) && 
2897                (passes < 20))
2898         {
2899                 passes++;
2900                 DecodeSegment(Target, 
2901                               DecodeMee, 
2902                               start, 
2903                               end, 
2904                               ConvertBuf,
2905                               ConvertBuf2,
2906                               FoundCharset);
2907                 
2908                 next = strstr(end, "=?");
2909                 nextend = NULL;
2910                 if ((next != NULL) && 
2911                     (next < eptr))
2912                         nextend = FindNextEnd(DecodeMee, next);
2913                 if (nextend == NULL)
2914                         next = NULL;
2915
2916                 /* did we find two partitions */
2917                 if ((next != NULL) && 
2918                     ((next - end) > 2))
2919                 {
2920                         ptr = end + 2;
2921                         while ((ptr < next) && 
2922                                (isspace(*ptr) ||
2923                                 (*ptr == '\r') ||
2924                                 (*ptr == '\n') || 
2925                                 (*ptr == '\t')))
2926                                 ptr ++;
2927                         /* did we find a gab just filled with blanks? */
2928                         if (ptr == next)
2929                         {
2930                                 long gap = next - start;
2931                                 memmove (end + 2,
2932                                          next,
2933                                          len - (gap));
2934                                 len -= gap;
2935                                 /* now terminate the gab at the end */
2936                                 delta = (next - end) - 2; ////TODO: const! 
2937                                 ((StrBuf*)DecodeMee)->BufUsed -= delta;
2938                                 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
2939
2940                                 /* move next to its new location. */
2941                                 next -= delta;
2942                                 nextend -= delta;
2943                         }
2944                 }
2945                 /* our next-pair is our new first pair now. */
2946                 ptr = end + 2;
2947                 start = next;
2948                 end = nextend;
2949         }
2950         end = ptr;
2951         nextend = DecodeMee->buf + DecodeMee->BufUsed;
2952         if ((end != NULL) && (end < nextend)) {
2953                 ptr = end;
2954                 while ( (ptr < nextend) &&
2955                         (isspace(*ptr) ||
2956                          (*ptr == '\r') ||
2957                          (*ptr == '\n') || 
2958                          (*ptr == '\t')))
2959                         ptr ++;
2960                 if (ptr < nextend)
2961                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
2962         }
2963         FreeStrBuf(&ConvertBuf);
2964         FreeStrBuf(&ConvertBuf2);
2965         FreeStrBuf(&DecodedInvalidBuf);
2966 }
2967
2968 /**
2969  * @brief evaluate the length of an utf8 special character sequence
2970  * @param Char the character to examine
2971  * @returns width of utf8 chars in bytes
2972  */
2973 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2974 {
2975         int n = 1;
2976         char test = (1<<7);
2977         
2978         while ((n < 8) && ((test & *CharS) != 0)) {
2979                 test = test << 1;
2980                 n ++;
2981         }
2982         if ((n > 6) || ((CharE - CharS) > n))
2983                 n = 1;
2984         return n;
2985 }
2986
2987 /**
2988  * @brief detect whether this char starts an utf-8 encoded char
2989  * @param Char character to inspect
2990  * @returns yes or no
2991  */
2992 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2993 {
2994 /** 11??.???? indicates an UTF8 Sequence. */
2995         return ((Char & 0xC0) != 0);
2996 }
2997
2998 /**
2999  * @brief measure the number of glyphs in an UTF8 string...
3000  * @param str string to measure
3001  * @returns the length of str
3002  */
3003 long StrBuf_Utf8StrLen(StrBuf *Buf)
3004 {
3005         int n = 0;
3006         int m = 0;
3007         char *aptr, *eptr;
3008
3009         if ((Buf == NULL) || (Buf->BufUsed == 0))
3010                 return 0;
3011         aptr = Buf->buf;
3012         eptr = Buf->buf + Buf->BufUsed;
3013         while ((aptr < eptr) && (*aptr != '\0')) {
3014                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3015                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3016                         while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3017                                 n ++;
3018                 }
3019                 else {
3020                         n++;
3021                         aptr++;
3022                 }
3023                         
3024         }
3025         return n;
3026 }
3027
3028 /**
3029  * @brief cuts a string after maxlen glyphs
3030  * @param str string to cut to maxlen glyphs
3031  * @param maxlen how long may the string become?
3032  * @returns pointer to maxlen or the end of the string
3033  */
3034 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3035 {
3036         char *aptr, *eptr;
3037         int n = 0, m = 0;
3038
3039         aptr = Buf->buf;
3040         eptr = Buf->buf + Buf->BufUsed;
3041         while ((aptr < eptr) && (*aptr != '\0')) {
3042                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3043                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3044                         while ((m-- > 0) && (*aptr++ != '\0'))
3045                                 n ++;
3046                 }
3047                 else {
3048                         n++;
3049                         aptr++;
3050                 }
3051                 if (n > maxlen) {
3052                         *aptr = '\0';
3053                         Buf->BufUsed = aptr - Buf->buf;
3054                         return Buf->BufUsed;
3055                 }                       
3056         }
3057         return Buf->BufUsed;
3058
3059 }
3060
3061
3062 /**
3063  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3064  * @param LineBuf your line will be copied here.
3065  * @param Buf BLOB with lines of text...
3066  * @param Ptr moved arround to keep the next-line across several iterations
3067  *        has to be &NULL on start; will be &NotNULL on end of buffer
3068  * @returns size of copied buffer
3069  */
3070 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3071 {
3072         const char *aptr, *ptr, *eptr;
3073         char *optr, *xptr;
3074
3075         if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3076                 *Ptr = StrBufNOTNULL;
3077                 return 0;
3078         }
3079
3080         FlushStrBuf(LineBuf);
3081         if (*Ptr==NULL)
3082                 ptr = aptr = Buf->buf;
3083         else
3084                 ptr = aptr = *Ptr;
3085
3086         optr = LineBuf->buf;
3087         eptr = Buf->buf + Buf->BufUsed;
3088         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3089
3090         while ((ptr <= eptr) && 
3091                (*ptr != '\n') &&
3092                (*ptr != '\r') )
3093         {
3094                 *optr = *ptr;
3095                 optr++; ptr++;
3096                 if (optr == xptr) {
3097                         LineBuf->BufUsed = optr - LineBuf->buf;
3098                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
3099                         optr = LineBuf->buf + LineBuf->BufUsed;
3100                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3101                 }
3102         }
3103
3104         if ((ptr >= eptr) && (optr > LineBuf->buf))
3105                 optr --;
3106         LineBuf->BufUsed = optr - LineBuf->buf;
3107         *optr = '\0';       
3108         if ((ptr <= eptr) && (*ptr == '\r'))
3109                 ptr ++;
3110         if ((ptr <= eptr) && (*ptr == '\n'))
3111                 ptr ++;
3112         
3113         if (ptr < eptr) {
3114                 *Ptr = ptr;
3115         }
3116         else {
3117                 *Ptr = StrBufNOTNULL;
3118         }
3119
3120         return Buf->BufUsed - (ptr - Buf->buf);
3121 }