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