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