* remove temporary debian file
[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 #define SHOW_ME_VAPPEND_PRINTF
11 #include <stdarg.h>
12 #include "libcitadel.h"
13
14 #ifdef HAVE_ICONV
15 #include <iconv.h>
16 #endif
17
18 #ifdef HAVE_ZLIB
19 #include <zlib.h>
20 #endif
21
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
29 /**
30  * Private Structure for the Stringbuffer
31  */
32 struct StrBuf {
33         char *buf;         /**< the pointer to the dynamic buffer */
34         long BufSize;      /**< how many spcae do we optain */
35         long BufUsed;      /**< StNumber of Chars used excluding the trailing \0 */
36         int ConstBuf;      /**< are we just a wrapper arround a static buffer and musn't we be changed? */
37 };
38
39
40 /** 
41  * \Brief Cast operator to Plain String 
42  * Note: if the buffer is altered by StrBuf operations, this pointer may become 
43  *  invalid. So don't lean on it after altering the buffer!
44  *  Since this operation is considered cheap, rather call it often than risking
45  *  your pointer to become invalid!
46  * \param Str the string we want to get the c-string representation for
47  * \returns the Pointer to the Content. Don't mess with it!
48  */
49 inline const char *ChrPtr(const StrBuf *Str)
50 {
51         if (Str == NULL)
52                 return "";
53         return Str->buf;
54 }
55
56 /**
57  * \brief since we know strlen()'s result, provide it here.
58  * \param Str the string to return the length to
59  * \returns contentlength of the buffer
60  */
61 inline int StrLength(const StrBuf *Str)
62 {
63         return (Str != NULL) ? Str->BufUsed : 0;
64 }
65
66 /**
67  * \brief local utility function to resize the buffer
68  * \param Buf the buffer whichs storage we should increase
69  * \param KeepOriginal should we copy the original buffer or just start over with a new one
70  * \param DestSize what should fit in after?
71  */
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
73 {
74         char *NewBuf;
75         size_t NewSize = Buf->BufSize * 2;
76
77         if (Buf->ConstBuf)
78                 return -1;
79                 
80         if (DestSize > 0)
81                 while (NewSize <= DestSize)
82                         NewSize *= 2;
83
84         NewBuf= (char*) malloc(NewSize);
85         if (KeepOriginal && (Buf->BufUsed > 0))
86         {
87                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
88         }
89         else
90         {
91                 NewBuf[0] = '\0';
92                 Buf->BufUsed = 0;
93         }
94         free (Buf->buf);
95         Buf->buf = NewBuf;
96         Buf->BufSize *= 2;
97         return Buf->BufSize;
98 }
99
100 /**
101  * Allocate a new buffer with default buffer size
102  * \returns the new stringbuffer
103  */
104 StrBuf* NewStrBuf(void)
105 {
106         StrBuf *NewBuf;
107
108         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109         NewBuf->buf = (char*) malloc(SIZ);
110         NewBuf->buf[0] = '\0';
111         NewBuf->BufSize = SIZ;
112         NewBuf->BufUsed = 0;
113         NewBuf->ConstBuf = 0;
114         return NewBuf;
115 }
116
117 /** 
118  * \brief Copy Constructor; returns a duplicate of CopyMe
119  * \params CopyMe Buffer to faxmilate
120  * \returns the new stringbuffer
121  */
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
123 {
124         StrBuf *NewBuf;
125         
126         if (CopyMe == NULL)
127                 return NewStrBuf();
128
129         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130         NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131         memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132         NewBuf->BufUsed = CopyMe->BufUsed;
133         NewBuf->BufSize = CopyMe->BufSize;
134         NewBuf->ConstBuf = 0;
135         return NewBuf;
136 }
137
138 /**
139  * \brief create a new Buffer using an existing c-string
140  * this function should also be used if you want to pre-suggest
141  * the buffer size to allocate in conjunction with ptr == NULL
142  * \param ptr the c-string to copy; may be NULL to create a blank instance
143  * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144  * \returns the new stringbuffer
145  */
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
147 {
148         StrBuf *NewBuf;
149         size_t Siz = SIZ;
150         size_t CopySize;
151
152         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
153         if (nChars < 0)
154                 CopySize = strlen((ptr != NULL)?ptr:"");
155         else
156                 CopySize = nChars;
157
158         while (Siz <= CopySize)
159                 Siz *= 2;
160
161         NewBuf->buf = (char*) malloc(Siz);
162         NewBuf->BufSize = Siz;
163         if (ptr != NULL) {
164                 memcpy(NewBuf->buf, ptr, CopySize);
165                 NewBuf->buf[CopySize] = '\0';
166                 NewBuf->BufUsed = CopySize;
167         }
168         else {
169                 NewBuf->buf[0] = '\0';
170                 NewBuf->BufUsed = 0;
171         }
172         NewBuf->ConstBuf = 0;
173         return NewBuf;
174 }
175
176 /**
177  * \brief Set an existing buffer from a c-string
178  * \param ptr c-string to put into 
179  * \param nChars set to -1 if we should work 0-terminated
180  * \returns the new length of the string
181  */
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
183 {
184         size_t Siz = Buf->BufSize;
185         size_t CopySize;
186
187         if (nChars < 0)
188                 CopySize = strlen(ptr);
189         else
190                 CopySize = nChars;
191
192         while (Siz <= CopySize)
193                 Siz *= 2;
194
195         if (Siz != Buf->BufSize)
196                 IncreaseBuf(Buf, 0, Siz);
197         memcpy(Buf->buf, ptr, CopySize);
198         Buf->buf[CopySize] = '\0';
199         Buf->BufUsed = CopySize;
200         Buf->ConstBuf = 0;
201         return CopySize;
202 }
203
204
205 /**
206  * \brief use strbuf as wrapper for a string constant for easy handling
207  * \param StringConstant a string to wrap
208  * \param SizeOfConstant should be sizeof(StringConstant)-1
209  */
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
211 {
212         StrBuf *NewBuf;
213
214         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215         NewBuf->buf = (char*) StringConstant;
216         NewBuf->BufSize = SizeOfStrConstant;
217         NewBuf->BufUsed = SizeOfStrConstant;
218         NewBuf->ConstBuf = 1;
219         return NewBuf;
220 }
221
222
223 /**
224  * \brief flush the content of a Buf; keep its struct
225  * \param buf Buffer to flush
226  */
227 int FlushStrBuf(StrBuf *buf)
228 {
229         if (buf == NULL)
230                 return -1;
231         if (buf->ConstBuf)
232                 return -1;       
233         buf->buf[0] ='\0';
234         buf->BufUsed = 0;
235         return 0;
236 }
237
238 /**
239  * \brief Release a Buffer
240  * Its a double pointer, so it can NULL your pointer
241  * so fancy SIG11 appear instead of random results
242  * \param FreeMe Pointer Pointer to the buffer to free
243  */
244 void FreeStrBuf (StrBuf **FreeMe)
245 {
246         if (*FreeMe == NULL)
247                 return;
248         if (!(*FreeMe)->ConstBuf) 
249                 free((*FreeMe)->buf);
250         free(*FreeMe);
251         *FreeMe = NULL;
252 }
253
254 /**
255  * \brief Release the buffer
256  * If you want put your StrBuf into a Hash, use this as Destructor.
257  * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
258  */
259 void HFreeStrBuf (void *VFreeMe)
260 {
261         StrBuf *FreeMe = (StrBuf*)VFreeMe;
262         if (FreeMe == NULL)
263                 return;
264         if (!FreeMe->ConstBuf) 
265                 free(FreeMe->buf);
266         free(FreeMe);
267 }
268
269 /**
270  * \brief Wrapper around atol
271  */
272 long StrTol(const StrBuf *Buf)
273 {
274         if (Buf == NULL)
275                 return 0;
276         if(Buf->BufUsed > 0)
277                 return atol(Buf->buf);
278         else
279                 return 0;
280 }
281
282 /**
283  * \brief Wrapper around atoi
284  */
285 int StrToi(const StrBuf *Buf)
286 {
287         if (Buf == NULL)
288                 return 0;
289         if (Buf->BufUsed > 0)
290                 return atoi(Buf->buf);
291         else
292                 return 0;
293 }
294 /**
295  * \brief Checks to see if the string is a pure number 
296  */
297 int StrBufIsNumber(const StrBuf *Buf) {
298   if (Buf == NULL) {
299         return 0;
300   }
301   char * pEnd;
302   strtoll(Buf->buf, &pEnd, 10);
303   if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
304     return 1;
305   }
306   return 0;
307
308 /**
309  * \brief modifies a Single char of the Buf
310  * You can point to it via char* or a zero-based integer
311  * \param ptr char* to zero; use NULL if unused
312  * \param nThChar zero based pointer into the string; use -1 if unused
313  * \param PeekValue The Character to place into the position
314  */
315 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
316 {
317         if (Buf == NULL)
318                 return -1;
319         if (ptr != NULL)
320                 nThChar = ptr - Buf->buf;
321         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
322                 return -1;
323         Buf->buf[nThChar] = PeekValue;
324         return nThChar;
325 }
326
327 /**
328  * \brief Append a StringBuffer to the buffer
329  * \param Buf Buffer to modify
330  * \param AppendBuf Buffer to copy at the end of our buffer
331  * \param Offset Should we start copying from an offset?
332  */
333 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
334 {
335         if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
336                 return;
337
338         if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
339                 IncreaseBuf(Buf, 
340                             (Buf->BufUsed > 0), 
341                             AppendBuf->BufUsed + Buf->BufUsed);
342
343         memcpy(Buf->buf + Buf->BufUsed, 
344                AppendBuf->buf + Offset, 
345                AppendBuf->BufUsed - Offset);
346         Buf->BufUsed += AppendBuf->BufUsed - Offset;
347         Buf->buf[Buf->BufUsed] = '\0';
348 }
349
350
351 /**
352  * \brief Append a C-String to the buffer
353  * \param Buf Buffer to modify
354  * \param AppendBuf Buffer to copy at the end of our buffer
355  * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
356  * \param Offset Should we start copying from an offset?
357  */
358 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
359 {
360         long aps;
361         long BufSizeRequired;
362
363         if ((AppendBuf == NULL) || (Buf == NULL))
364                 return;
365
366         if (AppendSize < 0 )
367                 aps = strlen(AppendBuf + Offset);
368         else
369                 aps = AppendSize - Offset;
370
371         BufSizeRequired = Buf->BufUsed + aps + 1;
372         if (Buf->BufSize <= BufSizeRequired)
373                 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
374
375         memcpy(Buf->buf + Buf->BufUsed, 
376                AppendBuf + Offset, 
377                aps);
378         Buf->BufUsed += aps;
379         Buf->buf[Buf->BufUsed] = '\0';
380 }
381
382
383 /** 
384  * \brief Escape a string for feeding out as a URL while appending it to a Buffer
385  * \param outbuf the output buffer
386  * \param oblen the size of outbuf to sanitize
387  * \param strbuf the input buffer
388  */
389 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
390 {
391         const char *pch, *pche;
392         char *pt, *pte;
393         int b, c, len;
394         const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
395         int eclen = sizeof(ec) -1;
396
397         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
398                 return;
399         if (PlainIn != NULL) {
400                 len = strlen(PlainIn);
401                 pch = PlainIn;
402                 pche = pch + len;
403         }
404         else {
405                 pch = In->buf;
406                 pche = pch + In->BufUsed;
407                 len = In->BufUsed;
408         }
409
410         if (len == 0) 
411                 return;
412
413         pt = OutBuf->buf + OutBuf->BufUsed;
414         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
415
416         while (pch < pche) {
417                 if (pt >= pte) {
418                         IncreaseBuf(OutBuf, 1, -1);
419                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
420                         pt = OutBuf->buf + OutBuf->BufUsed;
421                 }
422                 
423                 c = 0;
424                 for (b = 0; b < eclen; ++b) {
425                         if (*pch == ec[b]) {
426                                 c = 1;
427                                 b += eclen;
428                         }
429                 }
430                 if (c == 1) {
431                         sprintf(pt,"%%%02X", *pch);
432                         pt += 3;
433                         OutBuf->BufUsed += 3;
434                         pch ++;
435                 }
436                 else {
437                         *(pt++) = *(pch++);
438                         OutBuf->BufUsed++;
439                 }
440         }
441         *pt = '\0';
442 }
443
444 /*
445  * \brief Append a string, escaping characters which have meaning in HTML.  
446  *
447  * \param Target        target buffer
448  * \param Source        source buffer; set to NULL if you just have a C-String
449  * \param PlainIn       Plain-C string to append; set to NULL if unused
450  * \param nbsp          If nonzero, spaces are converted to non-breaking spaces.
451  * \param nolinebreaks  if set to 1, linebreaks are removed from the string.
452  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
453  */
454 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
455 {
456         const char *aptr, *eiptr;
457         char *bptr, *eptr;
458         long len;
459
460         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
461                 return -1;
462
463         if (PlainIn != NULL) {
464                 aptr = PlainIn;
465                 len = strlen(PlainIn);
466                 eiptr = aptr + len;
467         }
468         else {
469                 aptr = Source->buf;
470                 eiptr = aptr + Source->BufUsed;
471                 len = Source->BufUsed;
472         }
473
474         if (len == 0) 
475                 return -1;
476
477         bptr = Target->buf + Target->BufUsed;
478         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
479
480         while (aptr < eiptr){
481                 if(bptr >= eptr) {
482                         IncreaseBuf(Target, 1, -1);
483                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
484                         bptr = Target->buf + Target->BufUsed;
485                 }
486                 if (*aptr == '<') {
487                         memcpy(bptr, "&lt;", 4);
488                         bptr += 4;
489                         Target->BufUsed += 4;
490                 }
491                 else if (*aptr == '>') {
492                         memcpy(bptr, "&gt;", 4);
493                         bptr += 4;
494                         Target->BufUsed += 4;
495                 }
496                 else if (*aptr == '&') {
497                         memcpy(bptr, "&amp;", 5);
498                         bptr += 5;
499                         Target->BufUsed += 5;
500                 }
501                 else if (*aptr == '"') {
502                         memcpy(bptr, "&quot;", 6);
503                         bptr += 6;
504                         Target->BufUsed += 6;
505                 }
506                 else if (*aptr == '\'') {
507                         memcpy(bptr, "&#39;", 5);
508                         bptr += 5;
509                         Target->BufUsed += 5;
510                 }
511                 else if (*aptr == LB) {
512                         *bptr = '<';
513                         bptr ++;
514                         Target->BufUsed ++;
515                 }
516                 else if (*aptr == RB) {
517                         *bptr = '>';
518                         bptr ++;
519                         Target->BufUsed ++;
520                 }
521                 else if (*aptr == QU) {
522                         *bptr ='"';
523                         bptr ++;
524                         Target->BufUsed ++;
525                 }
526                 else if ((*aptr == 32) && (nbsp == 1)) {
527                         memcpy(bptr, "&nbsp;", 6);
528                         bptr += 6;
529                         Target->BufUsed += 6;
530                 }
531                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
532                         *bptr='\0';     /* nothing */
533                 }
534                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
535                         memcpy(bptr, "&lt;br/&gt;", 11);
536                         bptr += 11;
537                         Target->BufUsed += 11;
538                 }
539
540
541                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
542                         *bptr='\0';     /* nothing */
543                 }
544                 else{
545                         *bptr = *aptr;
546                         bptr++;
547                         Target->BufUsed ++;
548                 }
549                 aptr ++;
550         }
551         *bptr = '\0';
552         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
553                 return -1;
554         return Target->BufUsed;
555 }
556
557 /*
558  * \brief Append a string, escaping characters which have meaning in HTML.  
559  * Converts linebreaks into blanks; escapes single quotes
560  * \param Target        target buffer
561  * \param Source        source buffer; set to NULL if you just have a C-String
562  * \param PlainIn       Plain-C string to append; set to NULL if unused
563  */
564 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
565 {
566         const char *aptr, *eiptr;
567         char *tptr, *eptr;
568         long len;
569
570         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
571                 return ;
572
573         if (PlainIn != NULL) {
574                 aptr = PlainIn;
575                 len = strlen(PlainIn);
576                 eiptr = aptr + len;
577         }
578         else {
579                 aptr = Source->buf;
580                 eiptr = aptr + Source->BufUsed;
581                 len = Source->BufUsed;
582         }
583
584         if (len == 0) 
585                 return;
586
587         eptr = Target->buf + Target->BufSize - 8; 
588         tptr = Target->buf + Target->BufUsed;
589         
590         while (aptr < eiptr){
591                 if(tptr >= eptr) {
592                         IncreaseBuf(Target, 1, -1);
593                         eptr = Target->buf + Target->BufSize - 8; 
594                         tptr = Target->buf + Target->BufUsed;
595                 }
596                
597                 if (*aptr == '\n') {
598                         *tptr = ' ';
599                         Target->BufUsed++;
600                 }
601                 else if (*aptr == '\r') {
602                         *tptr = ' ';
603                         Target->BufUsed++;
604                 }
605                 else if (*aptr == '\'') {
606                         *(tptr++) = '&';
607                         *(tptr++) = '#';
608                         *(tptr++) = '3';
609                         *(tptr++) = '9';
610                         *tptr = ';';
611                         Target->BufUsed += 5;
612                 } else {
613                         *tptr = *aptr;
614                         Target->BufUsed++;
615                 }
616                 tptr++; aptr++;
617         }
618         *tptr = '\0';
619 }
620
621 /*
622  * \brief Append a string, escaping characters which have meaning in JavaScript strings .  
623  *
624  * \param Target        target buffer
625  * \param Source        source buffer; set to NULL if you just have a C-String
626  * \param PlainIn       Plain-C string to append; set to NULL if unused
627  */
628 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
629 {
630         const char *aptr, *eiptr;
631         char *bptr, *eptr;
632         long len;
633
634         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
635                 return -1;
636
637         if (PlainIn != NULL) {
638                 aptr = PlainIn;
639                 len = strlen(PlainIn);
640                 eiptr = aptr + len;
641         }
642         else {
643                 aptr = Source->buf;
644                 eiptr = aptr + Source->BufUsed;
645                 len = Source->BufUsed;
646         }
647
648         if (len == 0) 
649                 return -1;
650
651         bptr = Target->buf + Target->BufUsed;
652         eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in...  */
653
654         while (aptr < eiptr){
655                 if(bptr >= eptr) {
656                         IncreaseBuf(Target, 1, -1);
657                         eptr = Target->buf + Target->BufSize - 3; 
658                         bptr = Target->buf + Target->BufUsed;
659                 }
660                 else if (*aptr == '"') {
661                         memcpy(bptr, "\\\"", 2);
662                         bptr += 2;
663                         Target->BufUsed += 2;
664                 } else if (*aptr == '\\') {
665                   memcpy(bptr, "\\\\", 2);
666                   bptr += 2;
667                   Target->BufUsed += 2;
668                 }
669                 else{
670                         *bptr = *aptr;
671                         bptr++;
672                         Target->BufUsed ++;
673                 }
674                 aptr ++;
675         }
676         *bptr = '\0';
677         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
678                 return -1;
679         return Target->BufUsed;
680 }
681
682 /**
683  * \brief extracts a substring from Source into dest
684  * \param dest buffer to place substring into
685  * \param Source string to copy substring from
686  * \param Offset chars to skip from start
687  * \param nChars number of chars to copy
688  * \returns the number of chars copied; may be different from nChars due to the size of Source
689  */
690 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
691 {
692         size_t NCharsRemain;
693         if (Offset > Source->BufUsed)
694         {
695                 FlushStrBuf(dest);
696                 return 0;
697         }
698         if (Offset + nChars < Source->BufUsed)
699         {
700                 if (nChars >= dest->BufSize)
701                         IncreaseBuf(dest, 0, nChars + 1);
702                 memcpy(dest->buf, Source->buf + Offset, nChars);
703                 dest->BufUsed = nChars;
704                 dest->buf[dest->BufUsed] = '\0';
705                 return nChars;
706         }
707         NCharsRemain = Source->BufUsed - Offset;
708         if (NCharsRemain  >= dest->BufSize)
709                 IncreaseBuf(dest, 0, NCharsRemain + 1);
710         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
711         dest->BufUsed = NCharsRemain;
712         dest->buf[dest->BufUsed] = '\0';
713         return NCharsRemain;
714 }
715
716 /**
717  * \brief sprintf like function appending the formated string to the buffer
718  * vsnprintf version to wrap into own calls
719  * \param Buf Buffer to extend by format and params
720  * \param format printf alike format to add
721  * \param ap va_list containing the items for format
722  */
723 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
724 {
725         va_list apl;
726         size_t BufSize = Buf->BufSize;
727         size_t nWritten = Buf->BufSize + 1;
728         size_t Offset = Buf->BufUsed;
729         size_t newused = Offset + nWritten;
730         
731         while (newused >= BufSize) {
732                 va_copy(apl, ap);
733                 nWritten = vsnprintf(Buf->buf + Offset, 
734                                      Buf->BufSize - Offset, 
735                                      format, apl);
736                 va_end(apl);
737                 newused = Offset + nWritten;
738                 if (newused >= Buf->BufSize) {
739                         IncreaseBuf(Buf, 1, newused);
740                 }
741                 else {
742                         Buf->BufUsed = Offset + nWritten;
743                         BufSize = Buf->BufSize;
744                 }
745
746         }
747 }
748
749 /**
750  * \brief sprintf like function appending the formated string to the buffer
751  * \param Buf Buffer to extend by format and params
752  * \param format printf alike format to add
753  * \param ap va_list containing the items for format
754  */
755 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
756 {
757         size_t BufSize = Buf->BufSize;
758         size_t nWritten = Buf->BufSize + 1;
759         size_t Offset = Buf->BufUsed;
760         size_t newused = Offset + nWritten;
761         va_list arg_ptr;
762         
763         while (newused >= BufSize) {
764                 va_start(arg_ptr, format);
765                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
766                                      Buf->BufSize - Buf->BufUsed, 
767                                      format, arg_ptr);
768                 va_end(arg_ptr);
769                 newused = Buf->BufUsed + nWritten;
770                 if (newused >= Buf->BufSize) {
771                         IncreaseBuf(Buf, 1, newused);
772                 }
773                 else {
774                         Buf->BufUsed += nWritten;
775                         BufSize = Buf->BufSize;
776                 }
777
778         }
779 }
780
781 /**
782  * \brief sprintf like function putting the formated string into the buffer
783  * \param Buf Buffer to extend by format and params
784  * \param format printf alike format to add
785  * \param ap va_list containing the items for format
786  */
787 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
788 {
789         size_t nWritten = Buf->BufSize + 1;
790         va_list arg_ptr;
791         
792         while (nWritten >= Buf->BufSize) {
793                 va_start(arg_ptr, format);
794                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
795                 va_end(arg_ptr);
796                 Buf->BufUsed = nWritten ;
797                 if (nWritten >= Buf->BufSize)
798                         IncreaseBuf(Buf, 0, 0);
799         }
800 }
801
802
803 /**
804  * \brief Counts the numbmer of tokens in a buffer
805  * \param Source String to count tokens in
806  * \param tok    Tokenizer char to count
807  * \returns numbers of tokenizer chars found
808  */
809 inline int StrBufNum_tokens(const StrBuf *source, char tok)
810 {
811         if (source == NULL)
812                 return 0;
813         return num_tokens(source->buf, tok);
814 }
815
816 /*
817  * remove_token() - a tokenizer that kills, maims, and destroys
818  */
819 /**
820  * \brief a string tokenizer
821  * \param Source StringBuffer to read into
822  * \param parmnum n'th parameter to remove
823  * \param separator tokenizer param
824  * \returns -1 if not found, else length of token.
825  */
826 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
827 {
828         int ReducedBy;
829         char *d, *s;            /* dest, source */
830         int count = 0;
831
832         /* Find desired parameter */
833         d = Source->buf;
834         while (count < parmnum) {
835                 /* End of string, bail! */
836                 if (!*d) {
837                         d = NULL;
838                         break;
839                 }
840                 if (*d == separator) {
841                         count++;
842                 }
843                 d++;
844         }
845         if (!d) return 0;               /* Parameter not found */
846
847         /* Find next parameter */
848         s = d;
849         while (*s && *s != separator) {
850                 s++;
851         }
852         if (*s == separator)
853                 s++;
854         ReducedBy = d - s;
855
856         /* Hack and slash */
857         if (*s) {
858                 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
859                 Source->BufUsed -= (ReducedBy + 1);
860         }
861         else if (d == Source->buf) {
862                 *d = 0;
863                 Source->BufUsed = 0;
864         }
865         else {
866                 *--d = 0;
867                 Source->BufUsed -= (ReducedBy + 1);
868         }
869         /*
870         while (*s) {
871                 *d++ = *s++;
872         }
873         *d = 0;
874         */
875         return ReducedBy;
876 }
877
878
879 /**
880  * \brief a string tokenizer
881  * \param dest Destination StringBuffer
882  * \param Source StringBuffer to read into
883  * \param parmnum n'th parameter to extract
884  * \param separator tokenizer param
885  * \returns -1 if not found, else length of token.
886  */
887 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
888 {
889         const char *s, *e;              //* source * /
890         int len = 0;                    //* running total length of extracted string * /
891         int current_token = 0;          //* token currently being processed * /
892          
893         if (dest != NULL) {
894                 dest->buf[0] = '\0';
895                 dest->BufUsed = 0;
896         }
897         else
898                 return(-1);
899
900         if ((Source == NULL) || (Source->BufUsed ==0)) {
901                 return(-1);
902         }
903         s = Source->buf;
904         e = s + Source->BufUsed;
905
906         //cit_backtrace();
907         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
908
909         while ((s<e) && !IsEmptyStr(s)) {
910                 if (*s == separator) {
911                         ++current_token;
912                 }
913                 if (len >= dest->BufSize)
914                         if (!IncreaseBuf(dest, 1, -1))
915                                 break;
916                 if ( (current_token == parmnum) && 
917                      (*s != separator)) {
918                         dest->buf[len] = *s;
919                         ++len;
920                 }
921                 else if (current_token > parmnum) {
922                         break;
923                 }
924                 ++s;
925         }
926         
927         dest->buf[len] = '\0';
928         dest->BufUsed = len;
929                 
930         if (current_token < parmnum) {
931                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
932                 return(-1);
933         }
934         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
935         return(len);
936 }
937
938
939
940
941
942 /**
943  * \brief a string tokenizer to fetch an integer
944  * \param dest Destination StringBuffer
945  * \param parmnum n'th parameter to extract
946  * \param separator tokenizer param
947  * \returns 0 if not found, else integer representation of the token
948  */
949 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
950 {
951         StrBuf tmp;
952         char buf[64];
953         
954         tmp.buf = buf;
955         buf[0] = '\0';
956         tmp.BufSize = 64;
957         tmp.BufUsed = 0;
958         tmp.ConstBuf = 1;
959         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
960                 return(atoi(buf));
961         else
962                 return 0;
963 }
964
965 /**
966  * \brief a string tokenizer to fetch a long integer
967  * \param dest Destination StringBuffer
968  * \param parmnum n'th parameter to extract
969  * \param separator tokenizer param
970  * \returns 0 if not found, else long integer representation of the token
971  */
972 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
973 {
974         StrBuf tmp;
975         char buf[64];
976         
977         tmp.buf = buf;
978         buf[0] = '\0';
979         tmp.BufSize = 64;
980         tmp.BufUsed = 0;
981         tmp.ConstBuf = 1;
982         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
983                 return(atoi(buf));
984         else
985                 return 0;
986 }
987
988
989 /**
990  * \brief a string tokenizer to fetch an unsigned long
991  * \param dest Destination StringBuffer
992  * \param parmnum n'th parameter to extract
993  * \param separator tokenizer param
994  * \returns 0 if not found, else unsigned long representation of the token
995  */
996 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
997 {
998         StrBuf tmp;
999         char buf[64];
1000         char *pnum;
1001         
1002         tmp.buf = buf;
1003         buf[0] = '\0';
1004         tmp.BufSize = 64;
1005         tmp.BufUsed = 0;
1006         tmp.ConstBuf = 1;
1007         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1008                 pnum = &buf[0];
1009                 if (*pnum == '-')
1010                         pnum ++;
1011                 return (unsigned long) atol(pnum);
1012         }
1013         else 
1014                 return 0;
1015 }
1016
1017
1018
1019 /**
1020  * \brief a string tokenizer
1021  * \param dest Destination StringBuffer
1022  * \param Source StringBuffer to read into
1023  * \param pStart pointer to the end of the last token. Feed with NULL.
1024  * \param separator tokenizer param
1025  * \returns -1 if not found, else length of token.
1026  */
1027 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1028 {
1029         const char *s, *EndBuffer;      //* source * /
1030         int len = 0;                    //* running total length of extracted string * /
1031         int current_token = 0;          //* token currently being processed * /
1032          
1033         if (dest != NULL) {
1034                 dest->buf[0] = '\0';
1035                 dest->BufUsed = 0;
1036         }
1037         else
1038                 return(-1);
1039
1040         if ((Source == NULL) || 
1041             (Source->BufUsed ==0)) {
1042                 return(-1);
1043         }
1044         if (*pStart == NULL)
1045                 *pStart = Source->buf;
1046
1047         EndBuffer = Source->buf + Source->BufUsed;
1048
1049         if ((*pStart < Source->buf) || 
1050             (*pStart >  EndBuffer)) {
1051                 return (-1);
1052         }
1053
1054
1055         s = *pStart;
1056
1057         //cit_backtrace();
1058         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1059
1060         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1061                 if (*s == separator) {
1062                         ++current_token;
1063                 }
1064                 if (len >= dest->BufSize)
1065                         if (!IncreaseBuf(dest, 1, -1)) {
1066                                 *pStart = EndBuffer + 1;
1067                                 break;
1068                         }
1069                 if ( (current_token == 0) && 
1070                      (*s != separator)) {
1071                         dest->buf[len] = *s;
1072                         ++len;
1073                 }
1074                 else if (current_token > 0) {
1075                         *pStart = s;
1076                         break;
1077                 }
1078                 ++s;
1079         }
1080         *pStart = s;
1081         (*pStart) ++;
1082
1083         dest->buf[len] = '\0';
1084         dest->BufUsed = len;
1085                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1086         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1087         return(len);
1088 }
1089
1090
1091 /**
1092  * \brief a string tokenizer
1093  * \param dest Destination StringBuffer
1094  * \param Source StringBuffer to read into
1095  * \param pStart pointer to the end of the last token. Feed with NULL.
1096  * \param separator tokenizer param
1097  * \returns -1 if not found, else length of token.
1098  */
1099 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1100 {
1101         const char *s, *EndBuffer;      //* source * /
1102         int len = 0;                    //* running total length of extracted string * /
1103         int current_token = 0;          //* token currently being processed * /
1104
1105         if ((Source == NULL) || 
1106             (Source->BufUsed ==0)) {
1107                 return(-1);
1108         }
1109         if (nTokens == 0)
1110                 return Source->BufUsed;
1111
1112         if (*pStart == NULL)
1113                 *pStart = Source->buf;
1114
1115         EndBuffer = Source->buf + Source->BufUsed;
1116
1117         if ((*pStart < Source->buf) || 
1118             (*pStart >  EndBuffer)) {
1119                 return (-1);
1120         }
1121
1122
1123         s = *pStart;
1124
1125         //cit_backtrace();
1126         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1127
1128         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1129                 if (*s == separator) {
1130                         ++current_token;
1131                 }
1132                 if (current_token >= nTokens) {
1133                         break;
1134                 }
1135                 ++s;
1136         }
1137         *pStart = s;
1138         (*pStart) ++;
1139
1140         return(len);
1141 }
1142
1143 /**
1144  * \brief a string tokenizer to fetch an integer
1145  * \param dest Destination StringBuffer
1146  * \param parmnum n'th parameter to extract
1147  * \param separator tokenizer param
1148  * \returns 0 if not found, else integer representation of the token
1149  */
1150 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1151 {
1152         StrBuf tmp;
1153         char buf[64];
1154         
1155         tmp.buf = buf;
1156         buf[0] = '\0';
1157         tmp.BufSize = 64;
1158         tmp.BufUsed = 0;
1159         tmp.ConstBuf = 1;
1160         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1161                 return(atoi(buf));
1162         else
1163                 return 0;
1164 }
1165
1166 /**
1167  * \brief a string tokenizer to fetch a long integer
1168  * \param dest Destination StringBuffer
1169  * \param parmnum n'th parameter to extract
1170  * \param separator tokenizer param
1171  * \returns 0 if not found, else long integer representation of the token
1172  */
1173 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1174 {
1175         StrBuf tmp;
1176         char buf[64];
1177         
1178         tmp.buf = buf;
1179         buf[0] = '\0';
1180         tmp.BufSize = 64;
1181         tmp.BufUsed = 0;
1182         tmp.ConstBuf = 1;
1183         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1184                 return(atoi(buf));
1185         else
1186                 return 0;
1187 }
1188
1189
1190 /**
1191  * \brief a string tokenizer to fetch an unsigned long
1192  * \param dest Destination StringBuffer
1193  * \param parmnum n'th parameter to extract
1194  * \param separator tokenizer param
1195  * \returns 0 if not found, else unsigned long representation of the token
1196  */
1197 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1198 {
1199         StrBuf tmp;
1200         char buf[64];
1201         char *pnum;
1202         
1203         tmp.buf = buf;
1204         buf[0] = '\0';
1205         tmp.BufSize = 64;
1206         tmp.BufUsed = 0;
1207         tmp.ConstBuf = 1;
1208         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1209                 pnum = &buf[0];
1210                 if (*pnum == '-')
1211                         pnum ++;
1212                 return (unsigned long) atol(pnum);
1213         }
1214         else 
1215                 return 0;
1216 }
1217
1218
1219
1220 /**
1221  * \brief Read a line from socket
1222  * flushes and closes the FD on error
1223  * \param buf the buffer to get the input to
1224  * \param fd pointer to the filedescriptor to read
1225  * \param append Append to an existing string or replace?
1226  * \param Error strerror() on error 
1227  * \returns numbers of chars read
1228  */
1229 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1230 {
1231         int len, rlen, slen;
1232
1233         if (!append)
1234                 FlushStrBuf(buf);
1235
1236         slen = len = buf->BufUsed;
1237         while (1) {
1238                 rlen = read(*fd, &buf->buf[len], 1);
1239                 if (rlen < 1) {
1240                         *Error = strerror(errno);
1241                         
1242                         close(*fd);
1243                         *fd = -1;
1244                         
1245                         return -1;
1246                 }
1247                 if (buf->buf[len] == '\n')
1248                         break;
1249                 if (buf->buf[len] != '\r')
1250                         len ++;
1251                 if (len >= buf->BufSize) {
1252                         buf->BufUsed = len;
1253                         buf->buf[len+1] = '\0';
1254                         IncreaseBuf(buf, 1, -1);
1255                 }
1256         }
1257         buf->BufUsed = len;
1258         buf->buf[len] = '\0';
1259         return len - slen;
1260 }
1261
1262 /**
1263  * \brief Read a line from socket
1264  * flushes and closes the FD on error
1265  * \param buf the buffer to get the input to
1266  * \param fd pointer to the filedescriptor to read
1267  * \param append Append to an existing string or replace?
1268  * \param Error strerror() on error 
1269  * \returns numbers of chars read
1270  */
1271 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1272                                  StrBuf *buf, 
1273                                  int *fd, 
1274                                  int timeout, 
1275                                  int selectresolution, 
1276                                  const char **Error)
1277 {
1278         int len, rlen;
1279         int nSuccessLess = 0;
1280         fd_set rfds;
1281         char *pch = NULL;
1282         int fdflags;
1283         struct timeval tv;
1284
1285         if (buf->BufUsed > 0) {
1286                 pch = strchr(buf->buf, '\n');
1287                 if (pch != NULL) {
1288                         rlen = 0;
1289                         len = pch - buf->buf;
1290                         if (len > 0 && (*(pch - 1) == '\r') )
1291                                 rlen ++;
1292                         StrBufSub(Line, buf, 0, len - rlen);
1293                         StrBufCutLeft(buf, len + 1);
1294                         return len - rlen;
1295                 }
1296         }
1297         
1298         if (buf->BufSize - buf->BufUsed < 10)
1299                 IncreaseBuf(buf, 1, -1);
1300
1301         fdflags = fcntl(*fd, F_GETFL);
1302         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1303                 return -1;
1304
1305         while ((nSuccessLess < timeout) && (pch == NULL)) {
1306                 tv.tv_sec = selectresolution;
1307                 tv.tv_usec = 0;
1308                 
1309                 FD_ZERO(&rfds);
1310                 FD_SET(*fd, &rfds);
1311                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1312                         *Error = strerror(errno);
1313                         close (*fd);
1314                         *fd = -1;
1315                         return -1;
1316                 }               
1317                 if (FD_ISSET(*fd, &rfds)) {
1318                         rlen = read(*fd, 
1319                                     &buf->buf[buf->BufUsed], 
1320                                     buf->BufSize - buf->BufUsed - 1);
1321                         if (rlen < 1) {
1322                                 *Error = strerror(errno);
1323                                 close(*fd);
1324                                 *fd = -1;
1325                                 return -1;
1326                         }
1327                         else if (rlen > 0) {
1328                                 nSuccessLess = 0;
1329                                 buf->BufUsed += rlen;
1330                                 buf->buf[buf->BufUsed] = '\0';
1331                                 if (buf->BufUsed + 10 > buf->BufSize) {
1332                                         IncreaseBuf(buf, 1, -1);
1333                                 }
1334                                 pch = strchr(buf->buf, '\n');
1335                                 continue;
1336                         }
1337                 }
1338                 nSuccessLess ++;
1339         }
1340         if (pch != NULL) {
1341                 rlen = 0;
1342                 len = pch - buf->buf;
1343                 if (len > 0 && (*(pch - 1) == '\r') )
1344                         rlen ++;
1345                 StrBufSub(Line, buf, 0, len - rlen);
1346                 StrBufCutLeft(buf, len + 1);
1347                 return len - rlen;
1348         }
1349         return -1;
1350
1351 }
1352
1353 /**
1354  * \brief Input binary data from socket
1355  * flushes and closes the FD on error
1356  * \param buf the buffer to get the input to
1357  * \param fd pointer to the filedescriptor to read
1358  * \param append Append to an existing string or replace?
1359  * \param nBytes the maximal number of bytes to read
1360  * \param Error strerror() on error 
1361  * \returns numbers of chars read
1362  */
1363 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1364 {
1365         fd_set wset;
1366         int fdflags;
1367         int len, rlen, slen;
1368         int nRead = 0;
1369         char *ptr;
1370
1371         if ((Buf == NULL) || (*fd == -1))
1372                 return -1;
1373         if (!append)
1374                 FlushStrBuf(Buf);
1375         if (Buf->BufUsed + nBytes >= Buf->BufSize)
1376                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1377
1378         ptr = Buf->buf + Buf->BufUsed;
1379
1380         slen = len = Buf->BufUsed;
1381
1382         fdflags = fcntl(*fd, F_GETFL);
1383
1384         while (nRead < nBytes) {
1385                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1386                         FD_ZERO(&wset);
1387                         FD_SET(*fd, &wset);
1388                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1389                                 *Error = strerror(errno);
1390                                 return -1;
1391                         }
1392                 }
1393
1394                 if ((rlen = read(*fd, 
1395                                  ptr,
1396                                  nBytes - nRead)) == -1) {
1397                         close(*fd);
1398                         *fd = -1;
1399                         *Error = strerror(errno);
1400                         return rlen;
1401                 }
1402                 nRead += rlen;
1403                 ptr += rlen;
1404                 Buf->BufUsed += rlen;
1405         }
1406         Buf->buf[Buf->BufUsed] = '\0';
1407         return nRead;
1408 }
1409
1410 /**
1411  * \brief Cut nChars from the start of the string
1412  * \param Buf Buffer to modify
1413  * \param nChars how many chars should be skipped?
1414  */
1415 void StrBufCutLeft(StrBuf *Buf, int nChars)
1416 {
1417         if (nChars >= Buf->BufUsed) {
1418                 FlushStrBuf(Buf);
1419                 return;
1420         }
1421         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1422         Buf->BufUsed -= nChars;
1423         Buf->buf[Buf->BufUsed] = '\0';
1424 }
1425
1426 /**
1427  * \brief Cut the trailing n Chars from the string
1428  * \param Buf Buffer to modify
1429  * \param nChars how many chars should be trunkated?
1430  */
1431 void StrBufCutRight(StrBuf *Buf, int nChars)
1432 {
1433         if (nChars >= Buf->BufUsed) {
1434                 FlushStrBuf(Buf);
1435                 return;
1436         }
1437         Buf->BufUsed -= nChars;
1438         Buf->buf[Buf->BufUsed] = '\0';
1439 }
1440
1441 /**
1442  * \brief Cut the string after n Chars
1443  * \param Buf Buffer to modify
1444  * \param AfternChars after how many chars should we trunkate the string?
1445  * \param At if non-null and points inside of our string, cut it there.
1446  */
1447 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1448 {
1449         if (At != NULL){
1450                 AfternChars = At - Buf->buf;
1451         }
1452
1453         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1454                 return;
1455         Buf->BufUsed = AfternChars;
1456         Buf->buf[Buf->BufUsed] = '\0';
1457 }
1458
1459
1460 /*
1461  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1462  * buf - the string to modify
1463  * len - length of the string. 
1464  */
1465 void StrBufTrim(StrBuf *Buf)
1466 {
1467         int delta = 0;
1468         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1469
1470         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1471                 delta ++;
1472         }
1473         if (delta > 0) StrBufCutLeft(Buf, delta);
1474
1475         if (Buf->BufUsed == 0) return;
1476         while (isspace(Buf->buf[Buf->BufUsed - 1])){
1477                 Buf->BufUsed --;
1478         }
1479         Buf->buf[Buf->BufUsed] = '\0';
1480 }
1481
1482
1483 void StrBufUpCase(StrBuf *Buf) 
1484 {
1485         char *pch, *pche;
1486
1487         pch = Buf->buf;
1488         pche = pch + Buf->BufUsed;
1489         while (pch < pche) {
1490                 *pch = toupper(*pch);
1491                 pch ++;
1492         }
1493 }
1494
1495
1496 void StrBufLowerCase(StrBuf *Buf) 
1497 {
1498         char *pch, *pche;
1499
1500         pch = Buf->buf;
1501         pche = pch + Buf->BufUsed;
1502         while (pch < pche) {
1503                 *pch = tolower(*pch);
1504                 pch ++;
1505         }
1506 }
1507
1508
1509 /**
1510  * \brief unhide special chars hidden to the HTML escaper
1511  * \param target buffer to put the unescaped string in
1512  * \param source buffer to unescape
1513  */
1514 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
1515 {
1516         int a, b, len;
1517         char hex[3];
1518
1519         if (target != NULL)
1520                 FlushStrBuf(target);
1521
1522         if (source == NULL ||target == NULL)
1523         {
1524                 return;
1525         }
1526
1527         len = source->BufUsed;
1528         for (a = 0; a < len; ++a) {
1529                 if (target->BufUsed >= target->BufSize)
1530                         IncreaseBuf(target, 1, -1);
1531
1532                 if (source->buf[a] == '=') {
1533                         hex[0] = source->buf[a + 1];
1534                         hex[1] = source->buf[a + 2];
1535                         hex[2] = 0;
1536                         b = 0;
1537                         sscanf(hex, "%02x", &b);
1538                         target->buf[target->BufUsed] = b;
1539                         target->buf[++target->BufUsed] = 0;
1540                         a += 2;
1541                 }
1542                 else {
1543                         target->buf[target->BufUsed] = source->buf[a];
1544                         target->buf[++target->BufUsed] = 0;
1545                 }
1546         }
1547 }
1548
1549
1550 /**
1551  * \brief hide special chars from the HTML escapers and friends
1552  * \param target buffer to put the escaped string in
1553  * \param source buffer to escape
1554  */
1555 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
1556 {
1557         int i, len;
1558
1559         if (target != NULL)
1560                 FlushStrBuf(target);
1561
1562         if (source == NULL ||target == NULL)
1563         {
1564                 return;
1565         }
1566
1567         len = source->BufUsed;
1568         for (i=0; i<len; ++i) {
1569                 if (target->BufUsed + 4 >= target->BufSize)
1570                         IncreaseBuf(target, 1, -1);
1571                 if ( (isalnum(source->buf[i])) || 
1572                      (source->buf[i]=='-') || 
1573                      (source->buf[i]=='_') ) {
1574                         target->buf[target->BufUsed++] = source->buf[i];
1575                 }
1576                 else {
1577                         sprintf(&target->buf[target->BufUsed], 
1578                                 "=%02X", 
1579                                 (0xFF &source->buf[i]));
1580                         target->BufUsed += 3;
1581                 }
1582         }
1583         target->buf[target->BufUsed + 1] = '\0';
1584 }
1585
1586 /*
1587  * \brief uses the same calling syntax as compress2(), but it
1588  * creates a stream compatible with HTTP "Content-encoding: gzip"
1589  */
1590 #ifdef HAVE_ZLIB
1591 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1592 #define OS_CODE 0x03    /*< unix */
1593 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
1594                           size_t * destLen,     /*< length of the compresed data */
1595                           const Bytef * source, /*< source to encode */
1596                           uLong sourceLen,      /*< length of source to encode */
1597                           int level)            /*< compression level */
1598 {
1599         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1600
1601         /* write gzip header */
1602         snprintf((char *) dest, *destLen, 
1603                  "%c%c%c%c%c%c%c%c%c%c",
1604                  gz_magic[0], gz_magic[1], Z_DEFLATED,
1605                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1606                  OS_CODE);
1607
1608         /* normal deflate */
1609         z_stream stream;
1610         int err;
1611         stream.next_in = (Bytef *) source;
1612         stream.avail_in = (uInt) sourceLen;
1613         stream.next_out = dest + 10L;   // after header
1614         stream.avail_out = (uInt) * destLen;
1615         if ((uLong) stream.avail_out != *destLen)
1616                 return Z_BUF_ERROR;
1617
1618         stream.zalloc = (alloc_func) 0;
1619         stream.zfree = (free_func) 0;
1620         stream.opaque = (voidpf) 0;
1621
1622         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1623                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1624         if (err != Z_OK)
1625                 return err;
1626
1627         err = deflate(&stream, Z_FINISH);
1628         if (err != Z_STREAM_END) {
1629                 deflateEnd(&stream);
1630                 return err == Z_OK ? Z_BUF_ERROR : err;
1631         }
1632         *destLen = stream.total_out + 10L;
1633
1634         /* write CRC and Length */
1635         uLong crc = crc32(0L, source, sourceLen);
1636         int n;
1637         for (n = 0; n < 4; ++n, ++*destLen) {
1638                 dest[*destLen] = (int) (crc & 0xff);
1639                 crc >>= 8;
1640         }
1641         uLong len = stream.total_in;
1642         for (n = 0; n < 4; ++n, ++*destLen) {
1643                 dest[*destLen] = (int) (len & 0xff);
1644                 len >>= 8;
1645         }
1646         err = deflateEnd(&stream);
1647         return err;
1648 }
1649 #endif
1650
1651
1652 /**
1653  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1654  */
1655 int CompressBuffer(StrBuf *Buf)
1656 {
1657 #ifdef HAVE_ZLIB
1658         char *compressed_data = NULL;
1659         size_t compressed_len, bufsize;
1660         int i = 0;
1661         
1662         bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1663         compressed_data = malloc(compressed_len);
1664         
1665         /* Flush some space after the used payload so valgrind shuts up... */
1666         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1667                 Buf->buf[Buf->BufUsed + i++] = '\0';
1668         if (compress_gzip((Bytef *) compressed_data,
1669                           &compressed_len,
1670                           (Bytef *) Buf->buf,
1671                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1672                 if (!Buf->ConstBuf)
1673                         free(Buf->buf);
1674                 Buf->buf = compressed_data;
1675                 Buf->BufUsed = compressed_len;
1676                 Buf->BufSize = bufsize;
1677                 /* Flush some space after the used payload so valgrind shuts up... */
1678                 i = 0;
1679                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1680                         Buf->buf[Buf->BufUsed + i++] = '\0';
1681                 return 1;
1682         } else {
1683                 free(compressed_data);
1684         }
1685 #endif  /* HAVE_ZLIB */
1686         return 0;
1687 }
1688
1689 /**
1690  * \brief decode a buffer from base 64 encoding; destroys original
1691  * \param Buf Buffor to transform
1692  */
1693 int StrBufDecodeBase64(StrBuf *Buf)
1694 {
1695         char *xferbuf;
1696         size_t siz;
1697         if (Buf == NULL) return -1;
1698
1699         xferbuf = (char*) malloc(Buf->BufSize);
1700         siz = CtdlDecodeBase64(xferbuf,
1701                                Buf->buf,
1702                                Buf->BufUsed);
1703         free(Buf->buf);
1704         Buf->buf = xferbuf;
1705         Buf->BufUsed = siz;
1706         return siz;
1707 }
1708
1709 /**
1710  * \brief replace all chars >0x20 && < 0x7F with Mute
1711  * \param Mute char to put over invalid chars
1712  * \param Buf Buffor to transform
1713  */
1714 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
1715 {
1716         unsigned char *pch;
1717
1718         if (Buf == NULL) return -1;
1719         pch = (unsigned char *)Buf->buf;
1720         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
1721                 if ((*pch < 0x20) || (*pch > 0x7F))
1722                         *pch = Mute;
1723                 pch ++;
1724         }
1725         return Buf->BufUsed;
1726 }
1727
1728
1729 /**
1730  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
1731  * \param Buf Buffer to translate
1732  * \param StripBlanks Reduce several blanks to one?
1733  */
1734 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1735 {
1736         int a, b;
1737         char hex[3];
1738         long len;
1739
1740         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1741                 Buf->buf[Buf->BufUsed - 1] = '\0';
1742                 Buf->BufUsed --;
1743         }
1744
1745         a = 0; 
1746         while (a < Buf->BufUsed) {
1747                 if (Buf->buf[a] == '+')
1748                         Buf->buf[a] = ' ';
1749                 else if (Buf->buf[a] == '%') {
1750                         /* don't let % chars through, rather truncate the input. */
1751                         if (a + 2 > Buf->BufUsed) {
1752                                 Buf->buf[a] = '\0';
1753                                 Buf->BufUsed = a;
1754                         }
1755                         else {                  
1756                                 hex[0] = Buf->buf[a + 1];
1757                                 hex[1] = Buf->buf[a + 2];
1758                                 hex[2] = 0;
1759                                 b = 0;
1760                                 sscanf(hex, "%02x", &b);
1761                                 Buf->buf[a] = (char) b;
1762                                 len = Buf->BufUsed - a - 2;
1763                                 if (len > 0)
1764                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1765                         
1766                                 Buf->BufUsed -=2;
1767                         }
1768                 }
1769                 a++;
1770         }
1771         return a;
1772 }
1773
1774
1775 /**
1776  * \brief       RFC2047-encode a header field if necessary.
1777  *              If no non-ASCII characters are found, the string
1778  *              will be copied verbatim without encoding.
1779  *
1780  * \param       target          Target buffer.
1781  * \param       source          Source string to be encoded.
1782  * \returns     encoded length; -1 if non success.
1783  */
1784 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1785 {
1786         const char headerStr[] = "=?UTF-8?Q?";
1787         int need_to_encode = 0;
1788         int i = 0;
1789         unsigned char ch;
1790
1791         if ((source == NULL) || 
1792             (target == NULL))
1793             return -1;
1794
1795         while ((i < source->BufUsed) &&
1796                (!IsEmptyStr (&source->buf[i])) &&
1797                (need_to_encode == 0)) {
1798                 if (((unsigned char) source->buf[i] < 32) || 
1799                     ((unsigned char) source->buf[i] > 126)) {
1800                         need_to_encode = 1;
1801                 }
1802                 i++;
1803         }
1804
1805         if (!need_to_encode) {
1806                 if (*target == NULL) {
1807                         *target = NewStrBufPlain(source->buf, source->BufUsed);
1808                 }
1809                 else {
1810                         FlushStrBuf(*target);
1811                         StrBufAppendBuf(*target, source, 0);
1812                 }
1813                 return (*target)->BufUsed;
1814         }
1815         if (*target == NULL)
1816                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1817         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
1818                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1819         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1820         (*target)->BufUsed = sizeof(headerStr) - 1;
1821         for (i=0; (i < source->BufUsed); ++i) {
1822                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
1823                         IncreaseBuf(*target, 1, 0);
1824                 ch = (unsigned char) source->buf[i];
1825                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1826                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1827                         (*target)->BufUsed += 3;
1828                 }
1829                 else {
1830                         (*target)->buf[(*target)->BufUsed] = ch;
1831                         (*target)->BufUsed++;
1832                 }
1833         }
1834         
1835         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
1836                 IncreaseBuf(*target, 1, 0);
1837
1838         (*target)->buf[(*target)->BufUsed++] = '?';
1839         (*target)->buf[(*target)->BufUsed++] = '=';
1840         (*target)->buf[(*target)->BufUsed] = '\0';
1841         return (*target)->BufUsed;;
1842 }
1843
1844 /**
1845  * \brief replaces all occurances of 'search' by 'replace'
1846  * \param buf Buffer to modify
1847  * \param search character to search
1848  * \param relpace character to replace search by
1849  */
1850 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1851 {
1852         long i;
1853         if (buf == NULL)
1854                 return;
1855         for (i=0; i<buf->BufUsed; i++)
1856                 if (buf->buf[i] == search)
1857                         buf->buf[i] = replace;
1858
1859 }
1860
1861
1862
1863 /*
1864  * Wrapper around iconv_open()
1865  * Our version adds aliases for non-standard Microsoft charsets
1866  * such as 'MS950', aliasing them to names like 'CP950'
1867  *
1868  * tocode       Target encoding
1869  * fromcode     Source encoding
1870  */
1871 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1872 {
1873 #ifdef HAVE_ICONV
1874         iconv_t ic = (iconv_t)(-1) ;
1875         ic = iconv_open(tocode, fromcode);
1876         if (ic == (iconv_t)(-1) ) {
1877                 char alias_fromcode[64];
1878                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1879                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1880                         alias_fromcode[0] = 'C';
1881                         alias_fromcode[1] = 'P';
1882                         ic = iconv_open(tocode, alias_fromcode);
1883                 }
1884         }
1885         *(iconv_t *)pic = ic;
1886 #endif
1887 }
1888
1889
1890
1891 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1892 {
1893         char * end;
1894         /* Find the next ?Q? */
1895         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
1896                 return NULL;
1897
1898         end = strchr(bptr + 2, '?');
1899
1900         if (end == NULL)
1901                 return NULL;
1902
1903         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1904             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
1905             (*(end + 2) == '?')) {
1906                 /* skip on to the end of the cluster, the next ?= */
1907                 end = strstr(end + 3, "?=");
1908         }
1909         else
1910                 /* sort of half valid encoding, try to find an end. */
1911                 end = strstr(bptr, "?=");
1912         return end;
1913 }
1914
1915
1916 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1917 {
1918 #ifdef HAVE_ICONV
1919         int BufSize;
1920         iconv_t ic;
1921         char *ibuf;                     /**< Buffer of characters to be converted */
1922         char *obuf;                     /**< Buffer for converted characters */
1923         size_t ibuflen;                 /**< Length of input buffer */
1924         size_t obuflen;                 /**< Length of output buffer */
1925
1926
1927         if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
1928                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1929
1930         ic = *(iconv_t*)pic;
1931         ibuf = ConvertBuf->buf;
1932         ibuflen = ConvertBuf->BufUsed;
1933         obuf = TmpBuf->buf;
1934         obuflen = TmpBuf->BufSize;
1935         
1936         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1937
1938         /* little card game: wheres the red lady? */
1939         ibuf = ConvertBuf->buf;
1940         BufSize = ConvertBuf->BufSize;
1941
1942         ConvertBuf->buf = TmpBuf->buf;
1943         ConvertBuf->BufSize = TmpBuf->BufSize;
1944         ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1945         ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1946         
1947         TmpBuf->buf = ibuf;
1948         TmpBuf->BufSize = BufSize;
1949         TmpBuf->BufUsed = 0;
1950         TmpBuf->buf[0] = '\0';
1951 #endif
1952 }
1953
1954
1955
1956
1957 inline static void DecodeSegment(StrBuf *Target, 
1958                                  const StrBuf *DecodeMe, 
1959                                  char *SegmentStart, 
1960                                  char *SegmentEnd, 
1961                                  StrBuf *ConvertBuf,
1962                                  StrBuf *ConvertBuf2, 
1963                                  StrBuf *FoundCharset)
1964 {
1965         StrBuf StaticBuf;
1966         char charset[128];
1967         char encoding[16];
1968         iconv_t ic = (iconv_t)(-1);
1969
1970         /* Now we handle foreign character sets properly encoded
1971          * in RFC2047 format.
1972          */
1973         StaticBuf.buf = SegmentStart;
1974         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1975         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1976         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1977         if (FoundCharset != NULL) {
1978                 FlushStrBuf(FoundCharset);
1979                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1980         }
1981         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1982         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1983         
1984         *encoding = toupper(*encoding);
1985         if (*encoding == 'B') { /**< base64 */
1986                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
1987                                                         ConvertBuf->buf, 
1988                                                         ConvertBuf->BufUsed);
1989         }
1990         else if (*encoding == 'Q') {    /**< quoted-printable */
1991                 long pos;
1992                 
1993                 pos = 0;
1994                 while (pos < ConvertBuf->BufUsed)
1995                 {
1996                         if (ConvertBuf->buf[pos] == '_') 
1997                                 ConvertBuf->buf[pos] = ' ';
1998                         pos++;
1999                 }
2000                 
2001                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2002                         ConvertBuf2->buf, 
2003                         ConvertBuf->buf,
2004                         ConvertBuf->BufUsed);
2005         }
2006         else {
2007                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2008         }
2009
2010         ctdl_iconv_open("UTF-8", charset, &ic);
2011         if (ic != (iconv_t)(-1) ) {             
2012                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2013                 StrBufAppendBuf(Target, ConvertBuf2, 0);
2014                 iconv_close(ic);
2015         }
2016         else {
2017                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2018         }
2019 }
2020 /*
2021  * Handle subjects with RFC2047 encoding such as:
2022  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2023  */
2024 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2025 {
2026         StrBuf *ConvertBuf, *ConvertBuf2;
2027         char *start, *end, *next, *nextend, *ptr = NULL;
2028         iconv_t ic = (iconv_t)(-1) ;
2029         const char *eptr;
2030         int passes = 0;
2031         int i, len, delta;
2032         int illegal_non_rfc2047_encoding = 0;
2033
2034         /* Sometimes, badly formed messages contain strings which were simply
2035          *  written out directly in some foreign character set instead of
2036          *  using RFC2047 encoding.  This is illegal but we will attempt to
2037          *  handle it anyway by converting from a user-specified default
2038          *  charset to UTF-8 if we see any nonprintable characters.
2039          */
2040         
2041         len = StrLength(DecodeMe);
2042         for (i=0; i<DecodeMe->BufUsed; ++i) {
2043                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2044                         illegal_non_rfc2047_encoding = 1;
2045                         break;
2046                 }
2047         }
2048
2049         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2050         if ((illegal_non_rfc2047_encoding) &&
2051             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
2052             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2053         {
2054                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2055                 if (ic != (iconv_t)(-1) ) {
2056                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2057                         iconv_close(ic);
2058                 }
2059         }
2060
2061         /* pre evaluate the first pair */
2062         nextend = end = NULL;
2063         len = StrLength(DecodeMe);
2064         start = strstr(DecodeMe->buf, "=?");
2065         eptr = DecodeMe->buf + DecodeMe->BufUsed;
2066         if (start != NULL) 
2067                 end = FindNextEnd (DecodeMe, start);
2068         else {
2069                 StrBufAppendBuf(Target, DecodeMe, 0);
2070                 FreeStrBuf(&ConvertBuf);
2071                 return;
2072         }
2073
2074         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2075
2076         if (start != DecodeMe->buf)
2077                 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2078         /*
2079          * Since spammers will go to all sorts of absurd lengths to get their
2080          * messages through, there are LOTS of corrupt headers out there.
2081          * So, prevent a really badly formed RFC2047 header from throwing
2082          * this function into an infinite loop.
2083          */
2084         while ((start != NULL) && 
2085                (end != NULL) && 
2086                (start < eptr) && 
2087                (end < eptr) && 
2088                (passes < 20))
2089         {
2090                 passes++;
2091                 DecodeSegment(Target, 
2092                               DecodeMe, 
2093                               start, 
2094                               end, 
2095                               ConvertBuf,
2096                               ConvertBuf2,
2097                               FoundCharset);
2098                 
2099                 next = strstr(end, "=?");
2100                 nextend = NULL;
2101                 if ((next != NULL) && 
2102                     (next < eptr))
2103                         nextend = FindNextEnd(DecodeMe, next);
2104                 if (nextend == NULL)
2105                         next = NULL;
2106
2107                 /* did we find two partitions */
2108                 if ((next != NULL) && 
2109                     ((next - end) > 2))
2110                 {
2111                         ptr = end + 2;
2112                         while ((ptr < next) && 
2113                                (isspace(*ptr) ||
2114                                 (*ptr == '\r') ||
2115                                 (*ptr == '\n') || 
2116                                 (*ptr == '\t')))
2117                                 ptr ++;
2118                         /* did we find a gab just filled with blanks? */
2119                         if (ptr == next)
2120                         {
2121                                 memmove (end + 2,
2122                                          next,
2123                                          len - (next - start));
2124                                 
2125                                 /* now terminate the gab at the end */
2126                                 delta = (next - end) - 2; ////TODO: const! 
2127                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2128                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2129
2130                                 /* move next to its new location. */
2131                                 next -= delta;
2132                                 nextend -= delta;
2133                         }
2134                 }
2135                 /* our next-pair is our new first pair now. */
2136                 ptr = end + 2;
2137                 start = next;
2138                 end = nextend;
2139         }
2140         end = ptr;
2141         nextend = DecodeMe->buf + DecodeMe->BufUsed;
2142         if ((end != NULL) && (end < nextend)) {
2143                 ptr = end;
2144                 while ( (ptr < nextend) &&
2145                         (isspace(*ptr) ||
2146                          (*ptr == '\r') ||
2147                          (*ptr == '\n') || 
2148                          (*ptr == '\t')))
2149                         ptr ++;
2150                 if (ptr < nextend)
2151                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
2152         }
2153         FreeStrBuf(&ConvertBuf);
2154         FreeStrBuf(&ConvertBuf2);
2155 }
2156
2157
2158
2159 long StrBuf_Utf8StrLen(StrBuf *Buf)
2160 {
2161         return Ctdl_Utf8StrLen(Buf->buf);
2162 }
2163
2164 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2165 {
2166         char *CutAt;
2167
2168         CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2169         if (CutAt != NULL) {
2170                 Buf->BufUsed = CutAt - Buf->buf;
2171                 Buf->buf[Buf->BufUsed] = '\0';
2172         }
2173         return Buf->BufUsed;    
2174 }
2175
2176
2177
2178 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2179 {
2180         const char *aptr, *ptr, *eptr;
2181         char *optr, *xptr;
2182
2183         if (Buf == NULL)
2184                 return 0;
2185
2186         if (*Ptr==NULL)
2187                 ptr = aptr = Buf->buf;
2188         else
2189                 ptr = aptr = *Ptr;
2190
2191         optr = LineBuf->buf;
2192         eptr = Buf->buf + Buf->BufUsed;
2193         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2194
2195         while ((*ptr != '\n') &&
2196                (*ptr != '\r') &&
2197                (ptr < eptr))
2198         {
2199                 *optr = *ptr;
2200                 optr++; ptr++;
2201                 if (optr == xptr) {
2202                         LineBuf->BufUsed = optr - LineBuf->buf;
2203                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
2204                         optr = LineBuf->buf + LineBuf->BufUsed;
2205                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2206                 }
2207         }
2208         LineBuf->BufUsed = optr - LineBuf->buf;
2209         *optr = '\0';       
2210         if (*ptr == '\r')
2211                 ptr ++;
2212         if (*ptr == '\n')
2213                 ptr ++;
2214
2215         *Ptr = ptr;
2216
2217         return Buf->BufUsed - (ptr - Buf->buf);
2218 }