]> code.citadel.org Git - citadel.git/blob - libcitadel/lib/stringbuf.c
* add function to shrink empty StrBufs so they don't permanently alloc unneeded sizes.
[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 = SIZ;
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 /** 
569  * \brief Escape a string for feeding out as a URL while appending it to a Buffer
570  * \param outbuf the output buffer
571  * \param oblen the size of outbuf to sanitize
572  * \param strbuf the input buffer
573  */
574 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
575 {
576         const char *pch, *pche;
577         char *pt, *pte;
578         int b, c, len;
579         const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
580         int eclen = sizeof(ec) -1;
581
582         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
583                 return;
584         if (PlainIn != NULL) {
585                 len = strlen(PlainIn);
586                 pch = PlainIn;
587                 pche = pch + len;
588         }
589         else {
590                 pch = In->buf;
591                 pche = pch + In->BufUsed;
592                 len = In->BufUsed;
593         }
594
595         if (len == 0) 
596                 return;
597
598         pt = OutBuf->buf + OutBuf->BufUsed;
599         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
600
601         while (pch < pche) {
602                 if (pt >= pte) {
603                         IncreaseBuf(OutBuf, 1, -1);
604                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
605                         pt = OutBuf->buf + OutBuf->BufUsed;
606                 }
607                 
608                 c = 0;
609                 for (b = 0; b < eclen; ++b) {
610                         if (*pch == ec[b]) {
611                                 c = 1;
612                                 b += eclen;
613                         }
614                 }
615                 if (c == 1) {
616                         sprintf(pt,"%%%02X", *pch);
617                         pt += 3;
618                         OutBuf->BufUsed += 3;
619                         pch ++;
620                 }
621                 else {
622                         *(pt++) = *(pch++);
623                         OutBuf->BufUsed++;
624                 }
625         }
626         *pt = '\0';
627 }
628
629 /*
630  * \brief Append a string, escaping characters which have meaning in HTML.  
631  *
632  * \param Target        target buffer
633  * \param Source        source buffer; set to NULL if you just have a C-String
634  * \param PlainIn       Plain-C string to append; set to NULL if unused
635  * \param nbsp          If nonzero, spaces are converted to non-breaking spaces.
636  * \param nolinebreaks  if set to 1, linebreaks are removed from the string.
637  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
638  */
639 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
640 {
641         const char *aptr, *eiptr;
642         char *bptr, *eptr;
643         long len;
644
645         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
646                 return -1;
647
648         if (PlainIn != NULL) {
649                 aptr = PlainIn;
650                 len = strlen(PlainIn);
651                 eiptr = aptr + len;
652         }
653         else {
654                 aptr = Source->buf;
655                 eiptr = aptr + Source->BufUsed;
656                 len = Source->BufUsed;
657         }
658
659         if (len == 0) 
660                 return -1;
661
662         bptr = Target->buf + Target->BufUsed;
663         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
664
665         while (aptr < eiptr){
666                 if(bptr >= eptr) {
667                         IncreaseBuf(Target, 1, -1);
668                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
669                         bptr = Target->buf + Target->BufUsed;
670                 }
671                 if (*aptr == '<') {
672                         memcpy(bptr, "&lt;", 4);
673                         bptr += 4;
674                         Target->BufUsed += 4;
675                 }
676                 else if (*aptr == '>') {
677                         memcpy(bptr, "&gt;", 4);
678                         bptr += 4;
679                         Target->BufUsed += 4;
680                 }
681                 else if (*aptr == '&') {
682                         memcpy(bptr, "&amp;", 5);
683                         bptr += 5;
684                         Target->BufUsed += 5;
685                 }
686                 else if (*aptr == '"') {
687                         memcpy(bptr, "&quot;", 6);
688                         bptr += 6;
689                         Target->BufUsed += 6;
690                 }
691                 else if (*aptr == '\'') {
692                         memcpy(bptr, "&#39;", 5);
693                         bptr += 5;
694                         Target->BufUsed += 5;
695                 }
696                 else if (*aptr == LB) {
697                         *bptr = '<';
698                         bptr ++;
699                         Target->BufUsed ++;
700                 }
701                 else if (*aptr == RB) {
702                         *bptr = '>';
703                         bptr ++;
704                         Target->BufUsed ++;
705                 }
706                 else if (*aptr == QU) {
707                         *bptr ='"';
708                         bptr ++;
709                         Target->BufUsed ++;
710                 }
711                 else if ((*aptr == 32) && (nbsp == 1)) {
712                         memcpy(bptr, "&nbsp;", 6);
713                         bptr += 6;
714                         Target->BufUsed += 6;
715                 }
716                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
717                         *bptr='\0';     /* nothing */
718                 }
719                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
720                         memcpy(bptr, "&lt;br/&gt;", 11);
721                         bptr += 11;
722                         Target->BufUsed += 11;
723                 }
724
725
726                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
727                         *bptr='\0';     /* nothing */
728                 }
729                 else{
730                         *bptr = *aptr;
731                         bptr++;
732                         Target->BufUsed ++;
733                 }
734                 aptr ++;
735         }
736         *bptr = '\0';
737         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
738                 return -1;
739         return Target->BufUsed;
740 }
741
742 /*
743  * \brief Append a string, escaping characters which have meaning in HTML.  
744  * Converts linebreaks into blanks; escapes single quotes
745  * \param Target        target buffer
746  * \param Source        source buffer; set to NULL if you just have a C-String
747  * \param PlainIn       Plain-C string to append; set to NULL if unused
748  */
749 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
750 {
751         const char *aptr, *eiptr;
752         char *tptr, *eptr;
753         long len;
754
755         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
756                 return ;
757
758         if (PlainIn != NULL) {
759                 aptr = PlainIn;
760                 len = strlen(PlainIn);
761                 eiptr = aptr + len;
762         }
763         else {
764                 aptr = Source->buf;
765                 eiptr = aptr + Source->BufUsed;
766                 len = Source->BufUsed;
767         }
768
769         if (len == 0) 
770                 return;
771
772         eptr = Target->buf + Target->BufSize - 8; 
773         tptr = Target->buf + Target->BufUsed;
774         
775         while (aptr < eiptr){
776                 if(tptr >= eptr) {
777                         IncreaseBuf(Target, 1, -1);
778                         eptr = Target->buf + Target->BufSize - 8; 
779                         tptr = Target->buf + Target->BufUsed;
780                 }
781                
782                 if (*aptr == '\n') {
783                         *tptr = ' ';
784                         Target->BufUsed++;
785                 }
786                 else if (*aptr == '\r') {
787                         *tptr = ' ';
788                         Target->BufUsed++;
789                 }
790                 else if (*aptr == '\'') {
791                         *(tptr++) = '&';
792                         *(tptr++) = '#';
793                         *(tptr++) = '3';
794                         *(tptr++) = '9';
795                         *tptr = ';';
796                         Target->BufUsed += 5;
797                 } else {
798                         *tptr = *aptr;
799                         Target->BufUsed++;
800                 }
801                 tptr++; aptr++;
802         }
803         *tptr = '\0';
804 }
805
806 /*
807  * \brief Append a string, escaping characters which have meaning in JavaScript strings .  
808  *
809  * \param Target        target buffer
810  * \param Source        source buffer; set to NULL if you just have a C-String
811  * \param PlainIn       Plain-C string to append; set to NULL if unused
812  */
813 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
814 {
815         const char *aptr, *eiptr;
816         char *bptr, *eptr;
817         long len;
818
819         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
820                 return -1;
821
822         if (PlainIn != NULL) {
823                 aptr = PlainIn;
824                 len = strlen(PlainIn);
825                 eiptr = aptr + len;
826         }
827         else {
828                 aptr = Source->buf;
829                 eiptr = aptr + Source->BufUsed;
830                 len = Source->BufUsed;
831         }
832
833         if (len == 0) 
834                 return -1;
835
836         bptr = Target->buf + Target->BufUsed;
837         eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in...  */
838
839         while (aptr < eiptr){
840                 if(bptr >= eptr) {
841                         IncreaseBuf(Target, 1, -1);
842                         eptr = Target->buf + Target->BufSize - 3; 
843                         bptr = Target->buf + Target->BufUsed;
844                 }
845                 else if (*aptr == '"') {
846                         memcpy(bptr, "\\\"", 2);
847                         bptr += 2;
848                         Target->BufUsed += 2;
849                 } else if (*aptr == '\\') {
850                         memcpy(bptr, "\\\\", 2);
851                         bptr += 2;
852                         Target->BufUsed += 2;
853                 }
854                 else{
855                         *bptr = *aptr;
856                         bptr++;
857                         Target->BufUsed ++;
858                 }
859                 aptr ++;
860         }
861         *bptr = '\0';
862         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
863                 return -1;
864         return Target->BufUsed;
865 }
866
867 /**
868  * \brief extracts a substring from Source into dest
869  * \param dest buffer to place substring into
870  * \param Source string to copy substring from
871  * \param Offset chars to skip from start
872  * \param nChars number of chars to copy
873  * \returns the number of chars copied; may be different from nChars due to the size of Source
874  */
875 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
876 {
877         size_t NCharsRemain;
878         if (Offset > Source->BufUsed)
879         {
880                 FlushStrBuf(dest);
881                 return 0;
882         }
883         if (Offset + nChars < Source->BufUsed)
884         {
885                 if (nChars >= dest->BufSize)
886                         IncreaseBuf(dest, 0, nChars + 1);
887                 memcpy(dest->buf, Source->buf + Offset, nChars);
888                 dest->BufUsed = nChars;
889                 dest->buf[dest->BufUsed] = '\0';
890                 return nChars;
891         }
892         NCharsRemain = Source->BufUsed - Offset;
893         if (NCharsRemain  >= dest->BufSize)
894                 IncreaseBuf(dest, 0, NCharsRemain + 1);
895         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
896         dest->BufUsed = NCharsRemain;
897         dest->buf[dest->BufUsed] = '\0';
898         return NCharsRemain;
899 }
900
901 /**
902  * \brief sprintf like function appending the formated string to the buffer
903  * vsnprintf version to wrap into own calls
904  * \param Buf Buffer to extend by format and params
905  * \param format printf alike format to add
906  * \param ap va_list containing the items for format
907  */
908 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
909 {
910         va_list apl;
911         size_t BufSize = Buf->BufSize;
912         size_t nWritten = Buf->BufSize + 1;
913         size_t Offset = Buf->BufUsed;
914         size_t newused = Offset + nWritten;
915         
916         while (newused >= BufSize) {
917                 va_copy(apl, ap);
918                 nWritten = vsnprintf(Buf->buf + Offset, 
919                                      Buf->BufSize - Offset, 
920                                      format, apl);
921                 va_end(apl);
922                 newused = Offset + nWritten;
923                 if (newused >= Buf->BufSize) {
924                         IncreaseBuf(Buf, 1, newused);
925                         newused = Buf->BufSize + 1;
926                 }
927                 else {
928                         Buf->BufUsed = Offset + nWritten;
929                         BufSize = Buf->BufSize;
930                 }
931
932         }
933 }
934
935 /**
936  * \brief sprintf like function appending the formated string to the buffer
937  * \param Buf Buffer to extend by format and params
938  * \param format printf alike format to add
939  * \param ap va_list containing the items for format
940  */
941 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
942 {
943         size_t BufSize = Buf->BufSize;
944         size_t nWritten = Buf->BufSize + 1;
945         size_t Offset = Buf->BufUsed;
946         size_t newused = Offset + nWritten;
947         va_list arg_ptr;
948         
949         while (newused >= BufSize) {
950                 va_start(arg_ptr, format);
951                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
952                                      Buf->BufSize - Buf->BufUsed, 
953                                      format, arg_ptr);
954                 va_end(arg_ptr);
955                 newused = Buf->BufUsed + nWritten;
956                 if (newused >= Buf->BufSize) {
957                         IncreaseBuf(Buf, 1, newused);
958                         newused = Buf->BufSize + 1;
959                 }
960                 else {
961                         Buf->BufUsed += nWritten;
962                         BufSize = Buf->BufSize;
963                 }
964
965         }
966 }
967
968 /**
969  * \brief sprintf like function putting the formated string into the buffer
970  * \param Buf Buffer to extend by format and params
971  * \param format printf alike format to add
972  * \param ap va_list containing the items for format
973  */
974 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
975 {
976         size_t nWritten = Buf->BufSize + 1;
977         va_list arg_ptr;
978         
979         while (nWritten >= Buf->BufSize) {
980                 va_start(arg_ptr, format);
981                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
982                 va_end(arg_ptr);
983                 if (nWritten >= Buf->BufSize) {
984                         IncreaseBuf(Buf, 0, 0);
985                         nWritten = Buf->BufSize + 1;
986                         continue;
987                 }
988                 Buf->BufUsed = nWritten ;
989         }
990 }
991
992
993 /**
994  * \brief Counts the numbmer of tokens in a buffer
995  * \param Source String to count tokens in
996  * \param tok    Tokenizer char to count
997  * \returns numbers of tokenizer chars found
998  */
999 int StrBufNum_tokens(const StrBuf *source, char tok)
1000 {
1001         if (source == NULL)
1002                 return 0;
1003         return num_tokens(source->buf, tok);
1004 }
1005
1006 /*
1007  * remove_token() - a tokenizer that kills, maims, and destroys
1008  */
1009 /**
1010  * \brief a string tokenizer
1011  * \param Source StringBuffer to read into
1012  * \param parmnum n'th parameter to remove
1013  * \param separator tokenizer param
1014  * \returns -1 if not found, else length of token.
1015  */
1016 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1017 {
1018         int ReducedBy;
1019         char *d, *s;            /* dest, source */
1020         int count = 0;
1021
1022         /* Find desired parameter */
1023         d = Source->buf;
1024         while (count < parmnum) {
1025                 /* End of string, bail! */
1026                 if (!*d) {
1027                         d = NULL;
1028                         break;
1029                 }
1030                 if (*d == separator) {
1031                         count++;
1032                 }
1033                 d++;
1034         }
1035         if (!d) return 0;               /* Parameter not found */
1036
1037         /* Find next parameter */
1038         s = d;
1039         while (*s && *s != separator) {
1040                 s++;
1041         }
1042         if (*s == separator)
1043                 s++;
1044         ReducedBy = d - s;
1045
1046         /* Hack and slash */
1047         if (*s) {
1048                 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1049                 Source->BufUsed -= (ReducedBy + 1);
1050         }
1051         else if (d == Source->buf) {
1052                 *d = 0;
1053                 Source->BufUsed = 0;
1054         }
1055         else {
1056                 *--d = 0;
1057                 Source->BufUsed -= (ReducedBy + 1);
1058         }
1059         /*
1060         while (*s) {
1061                 *d++ = *s++;
1062         }
1063         *d = 0;
1064         */
1065         return ReducedBy;
1066 }
1067
1068
1069 /**
1070  * \brief a string tokenizer
1071  * \param dest Destination StringBuffer
1072  * \param Source StringBuffer to read into
1073  * \param parmnum n'th parameter to extract
1074  * \param separator tokenizer param
1075  * \returns -1 if not found, else length of token.
1076  */
1077 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1078 {
1079         const char *s, *e;              //* source * /
1080         int len = 0;                    //* running total length of extracted string * /
1081         int current_token = 0;          //* token currently being processed * /
1082          
1083         if (dest != NULL) {
1084                 dest->buf[0] = '\0';
1085                 dest->BufUsed = 0;
1086         }
1087         else
1088                 return(-1);
1089
1090         if ((Source == NULL) || (Source->BufUsed ==0)) {
1091                 return(-1);
1092         }
1093         s = Source->buf;
1094         e = s + Source->BufUsed;
1095
1096         //cit_backtrace();
1097         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1098
1099         while ((s<e) && !IsEmptyStr(s)) {
1100                 if (*s == separator) {
1101                         ++current_token;
1102                 }
1103                 if (len >= dest->BufSize)
1104                         if (!IncreaseBuf(dest, 1, -1))
1105                                 break;
1106                 if ( (current_token == parmnum) && 
1107                      (*s != separator)) {
1108                         dest->buf[len] = *s;
1109                         ++len;
1110                 }
1111                 else if (current_token > parmnum) {
1112                         break;
1113                 }
1114                 ++s;
1115         }
1116         
1117         dest->buf[len] = '\0';
1118         dest->BufUsed = len;
1119                 
1120         if (current_token < parmnum) {
1121                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1122                 return(-1);
1123         }
1124         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1125         return(len);
1126 }
1127
1128
1129
1130
1131
1132 /**
1133  * \brief a string tokenizer to fetch an integer
1134  * \param dest Destination StringBuffer
1135  * \param parmnum n'th parameter to extract
1136  * \param separator tokenizer param
1137  * \returns 0 if not found, else integer representation of the token
1138  */
1139 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1140 {
1141         StrBuf tmp;
1142         char buf[64];
1143         
1144         tmp.buf = buf;
1145         buf[0] = '\0';
1146         tmp.BufSize = 64;
1147         tmp.BufUsed = 0;
1148         tmp.ConstBuf = 1;
1149         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1150                 return(atoi(buf));
1151         else
1152                 return 0;
1153 }
1154
1155 /**
1156  * \brief a string tokenizer to fetch a long integer
1157  * \param dest Destination StringBuffer
1158  * \param parmnum n'th parameter to extract
1159  * \param separator tokenizer param
1160  * \returns 0 if not found, else long integer representation of the token
1161  */
1162 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1163 {
1164         StrBuf tmp;
1165         char buf[64];
1166         
1167         tmp.buf = buf;
1168         buf[0] = '\0';
1169         tmp.BufSize = 64;
1170         tmp.BufUsed = 0;
1171         tmp.ConstBuf = 1;
1172         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1173                 return(atoi(buf));
1174         else
1175                 return 0;
1176 }
1177
1178
1179 /**
1180  * \brief a string tokenizer to fetch an unsigned long
1181  * \param dest Destination StringBuffer
1182  * \param parmnum n'th parameter to extract
1183  * \param separator tokenizer param
1184  * \returns 0 if not found, else unsigned long representation of the token
1185  */
1186 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1187 {
1188         StrBuf tmp;
1189         char buf[64];
1190         char *pnum;
1191         
1192         tmp.buf = buf;
1193         buf[0] = '\0';
1194         tmp.BufSize = 64;
1195         tmp.BufUsed = 0;
1196         tmp.ConstBuf = 1;
1197         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1198                 pnum = &buf[0];
1199                 if (*pnum == '-')
1200                         pnum ++;
1201                 return (unsigned long) atol(pnum);
1202         }
1203         else 
1204                 return 0;
1205 }
1206
1207
1208
1209 /**
1210  * \brief a string tokenizer
1211  * \param dest Destination StringBuffer
1212  * \param Source StringBuffer to read into
1213  * \param pStart pointer to the end of the last token. Feed with NULL.
1214  * \param separator tokenizer param
1215  * \returns -1 if not found, else length of token.
1216  */
1217 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1218 {
1219         const char *s, *EndBuffer;      //* source * /
1220         int len = 0;                    //* running total length of extracted string * /
1221         int current_token = 0;          //* token currently being processed * /
1222          
1223         if (dest != NULL) {
1224                 dest->buf[0] = '\0';
1225                 dest->BufUsed = 0;
1226         }
1227         else
1228                 return(-1);
1229
1230         if ((Source == NULL) || 
1231             (Source->BufUsed ==0)) {
1232                 return(-1);
1233         }
1234         if (*pStart == NULL)
1235                 *pStart = Source->buf;
1236
1237         EndBuffer = Source->buf + Source->BufUsed;
1238
1239         if ((*pStart < Source->buf) || 
1240             (*pStart >  EndBuffer)) {
1241                 return (-1);
1242         }
1243
1244
1245         s = *pStart;
1246
1247         //cit_backtrace();
1248         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1249
1250         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1251                 if (*s == separator) {
1252                         ++current_token;
1253                 }
1254                 if (len >= dest->BufSize)
1255                         if (!IncreaseBuf(dest, 1, -1)) {
1256                                 *pStart = EndBuffer + 1;
1257                                 break;
1258                         }
1259                 if ( (current_token == 0) && 
1260                      (*s != separator)) {
1261                         dest->buf[len] = *s;
1262                         ++len;
1263                 }
1264                 else if (current_token > 0) {
1265                         *pStart = s;
1266                         break;
1267                 }
1268                 ++s;
1269         }
1270         *pStart = s;
1271         (*pStart) ++;
1272
1273         dest->buf[len] = '\0';
1274         dest->BufUsed = len;
1275                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1276         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1277         return(len);
1278 }
1279
1280
1281 /**
1282  * \brief a string tokenizer
1283  * \param dest Destination StringBuffer
1284  * \param Source StringBuffer to read into
1285  * \param pStart pointer to the end of the last token. Feed with NULL.
1286  * \param separator tokenizer param
1287  * \returns -1 if not found, else length of token.
1288  */
1289 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1290 {
1291         const char *s, *EndBuffer;      //* source * /
1292         int len = 0;                    //* running total length of extracted string * /
1293         int current_token = 0;          //* token currently being processed * /
1294
1295         if ((Source == NULL) || 
1296             (Source->BufUsed ==0)) {
1297                 return(-1);
1298         }
1299         if (nTokens == 0)
1300                 return Source->BufUsed;
1301
1302         if (*pStart == NULL)
1303                 *pStart = Source->buf;
1304
1305         EndBuffer = Source->buf + Source->BufUsed;
1306
1307         if ((*pStart < Source->buf) || 
1308             (*pStart >  EndBuffer)) {
1309                 return (-1);
1310         }
1311
1312
1313         s = *pStart;
1314
1315         //cit_backtrace();
1316         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1317
1318         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1319                 if (*s == separator) {
1320                         ++current_token;
1321                 }
1322                 if (current_token >= nTokens) {
1323                         break;
1324                 }
1325                 ++s;
1326         }
1327         *pStart = s;
1328         (*pStart) ++;
1329
1330         return(len);
1331 }
1332
1333 /**
1334  * \brief a string tokenizer to fetch an integer
1335  * \param dest Destination StringBuffer
1336  * \param parmnum n'th parameter to extract
1337  * \param separator tokenizer param
1338  * \returns 0 if not found, else integer representation of the token
1339  */
1340 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1341 {
1342         StrBuf tmp;
1343         char buf[64];
1344         
1345         tmp.buf = buf;
1346         buf[0] = '\0';
1347         tmp.BufSize = 64;
1348         tmp.BufUsed = 0;
1349         tmp.ConstBuf = 1;
1350         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1351                 return(atoi(buf));
1352         else
1353                 return 0;
1354 }
1355
1356 /**
1357  * \brief a string tokenizer to fetch a long integer
1358  * \param dest Destination StringBuffer
1359  * \param parmnum n'th parameter to extract
1360  * \param separator tokenizer param
1361  * \returns 0 if not found, else long integer representation of the token
1362  */
1363 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1364 {
1365         StrBuf tmp;
1366         char buf[64];
1367         
1368         tmp.buf = buf;
1369         buf[0] = '\0';
1370         tmp.BufSize = 64;
1371         tmp.BufUsed = 0;
1372         tmp.ConstBuf = 1;
1373         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1374                 return(atoi(buf));
1375         else
1376                 return 0;
1377 }
1378
1379
1380 /**
1381  * \brief a string tokenizer to fetch an unsigned long
1382  * \param dest Destination StringBuffer
1383  * \param parmnum n'th parameter to extract
1384  * \param separator tokenizer param
1385  * \returns 0 if not found, else unsigned long representation of the token
1386  */
1387 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1388 {
1389         StrBuf tmp;
1390         char buf[64];
1391         char *pnum;
1392         
1393         tmp.buf = buf;
1394         buf[0] = '\0';
1395         tmp.BufSize = 64;
1396         tmp.BufUsed = 0;
1397         tmp.ConstBuf = 1;
1398         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1399                 pnum = &buf[0];
1400                 if (*pnum == '-')
1401                         pnum ++;
1402                 return (unsigned long) atol(pnum);
1403         }
1404         else 
1405                 return 0;
1406 }
1407
1408
1409
1410 /**
1411  * \brief Read a line from socket
1412  * flushes and closes the FD on error
1413  * \param buf the buffer to get the input to
1414  * \param fd pointer to the filedescriptor to read
1415  * \param append Append to an existing string or replace?
1416  * \param Error strerror() on error 
1417  * \returns numbers of chars read
1418  */
1419 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1420 {
1421         int len, rlen, slen;
1422
1423         if (!append)
1424                 FlushStrBuf(buf);
1425
1426         slen = len = buf->BufUsed;
1427         while (1) {
1428                 rlen = read(*fd, &buf->buf[len], 1);
1429                 if (rlen < 1) {
1430                         *Error = strerror(errno);
1431                         
1432                         close(*fd);
1433                         *fd = -1;
1434                         
1435                         return -1;
1436                 }
1437                 if (buf->buf[len] == '\n')
1438                         break;
1439                 if (buf->buf[len] != '\r')
1440                         len ++;
1441                 if (len >= buf->BufSize) {
1442                         buf->BufUsed = len;
1443                         buf->buf[len+1] = '\0';
1444                         IncreaseBuf(buf, 1, -1);
1445                 }
1446         }
1447         buf->BufUsed = len;
1448         buf->buf[len] = '\0';
1449         return len - slen;
1450 }
1451
1452 /**
1453  * \brief Read a line from socket
1454  * flushes and closes the FD on error
1455  * \param buf the buffer to get the input to
1456  * \param fd pointer to the filedescriptor to read
1457  * \param append Append to an existing string or replace?
1458  * \param Error strerror() on error 
1459  * \returns numbers of chars read
1460  */
1461 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1462                                  StrBuf *buf, 
1463                                  int *fd, 
1464                                  int timeout, 
1465                                  int selectresolution, 
1466                                  const char **Error)
1467 {
1468         int len, rlen;
1469         int nSuccessLess = 0;
1470         fd_set rfds;
1471         char *pch = NULL;
1472         int fdflags;
1473         struct timeval tv;
1474
1475         if (buf->BufUsed > 0) {
1476                 pch = strchr(buf->buf, '\n');
1477                 if (pch != NULL) {
1478                         rlen = 0;
1479                         len = pch - buf->buf;
1480                         if (len > 0 && (*(pch - 1) == '\r') )
1481                                 rlen ++;
1482                         StrBufSub(Line, buf, 0, len - rlen);
1483                         StrBufCutLeft(buf, len + 1);
1484                         return len - rlen;
1485                 }
1486         }
1487         
1488         if (buf->BufSize - buf->BufUsed < 10)
1489                 IncreaseBuf(buf, 1, -1);
1490
1491         fdflags = fcntl(*fd, F_GETFL);
1492         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1493                 return -1;
1494
1495         while ((nSuccessLess < timeout) && (pch == NULL)) {
1496                 tv.tv_sec = selectresolution;
1497                 tv.tv_usec = 0;
1498                 
1499                 FD_ZERO(&rfds);
1500                 FD_SET(*fd, &rfds);
1501                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1502                         *Error = strerror(errno);
1503                         close (*fd);
1504                         *fd = -1;
1505                         return -1;
1506                 }               
1507                 if (FD_ISSET(*fd, &rfds)) {
1508                         rlen = read(*fd, 
1509                                     &buf->buf[buf->BufUsed], 
1510                                     buf->BufSize - buf->BufUsed - 1);
1511                         if (rlen < 1) {
1512                                 *Error = strerror(errno);
1513                                 close(*fd);
1514                                 *fd = -1;
1515                                 return -1;
1516                         }
1517                         else if (rlen > 0) {
1518                                 nSuccessLess = 0;
1519                                 buf->BufUsed += rlen;
1520                                 buf->buf[buf->BufUsed] = '\0';
1521                                 if (buf->BufUsed + 10 > buf->BufSize) {
1522                                         IncreaseBuf(buf, 1, -1);
1523                                 }
1524                                 pch = strchr(buf->buf, '\n');
1525                                 continue;
1526                         }
1527                 }
1528                 nSuccessLess ++;
1529         }
1530         if (pch != NULL) {
1531                 rlen = 0;
1532                 len = pch - buf->buf;
1533                 if (len > 0 && (*(pch - 1) == '\r') )
1534                         rlen ++;
1535                 StrBufSub(Line, buf, 0, len - rlen);
1536                 StrBufCutLeft(buf, len + 1);
1537                 return len - rlen;
1538         }
1539         return -1;
1540
1541 }
1542
1543 /**
1544  * \brief Read a line from socket
1545  * flushes and closes the FD on error
1546  * \param buf the buffer to get the input to
1547  * \param Pos pointer to the current read position, should be NULL initialized!
1548  * \param fd pointer to the filedescriptor to read
1549  * \param append Append to an existing string or replace?
1550  * \param Error strerror() on error 
1551  * \returns numbers of chars read
1552  */
1553 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
1554                                       StrBuf *IOBuf, 
1555                                       const char **Pos,
1556                                       int *fd, 
1557                                       int timeout, 
1558                                       int selectresolution, 
1559                                       const char **Error)
1560 {
1561         const char *pche = NULL;
1562         const char *pos = NULL;
1563         int len, rlen;
1564         int nSuccessLess = 0;
1565         fd_set rfds;
1566         const char *pch = NULL;
1567         int fdflags;
1568         struct timeval tv;
1569         
1570         pos = *Pos;
1571         if ((IOBuf->BufUsed > 0) && 
1572             (pos != NULL) && 
1573             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1574         {
1575                 pche = IOBuf->buf + IOBuf->BufUsed;
1576                 pch = pos;
1577                 while ((pch < pche) && (*pch != '\n'))
1578                         pch ++;
1579                 if ((pch >= pche) || (*pch == '\0'))
1580                         pch = NULL;
1581                 if ((pch != NULL) && 
1582                     (pch <= pche)) 
1583                 {
1584                         rlen = 0;
1585                         len = pch - pos;
1586                         if (len > 0 && (*(pch - 1) == '\r') )
1587                                 rlen ++;
1588                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1589                         *Pos = pch + 1;
1590                         return len - rlen;
1591                 }
1592         }
1593         
1594         if (pos != NULL) {
1595                 if (pos > pche)
1596                         FlushStrBuf(IOBuf);
1597                 else 
1598                         StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1599                 *Pos = NULL;
1600         }
1601         
1602         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1603                 IncreaseBuf(IOBuf, 1, -1);
1604         }
1605
1606         fdflags = fcntl(*fd, F_GETFL);
1607         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1608                 return -1;
1609
1610         pch = NULL;
1611         while ((nSuccessLess < timeout) && (pch == NULL)) {
1612                 tv.tv_sec = selectresolution;
1613                 tv.tv_usec = 0;
1614                 
1615                 FD_ZERO(&rfds);
1616                 FD_SET(*fd, &rfds);
1617                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1618                         *Error = strerror(errno);
1619                         close (*fd);
1620                         *fd = -1;
1621                         return -1;
1622                 }               
1623                 if (FD_ISSET(*fd, &rfds) != 0) {
1624                         rlen = read(*fd, 
1625                                     &IOBuf->buf[IOBuf->BufUsed], 
1626                                     IOBuf->BufSize - IOBuf->BufUsed - 1);
1627                         if (rlen < 1) {
1628                                 *Error = strerror(errno);
1629                                 close(*fd);
1630                                 *fd = -1;
1631                                 return -1;
1632                         }
1633                         else if (rlen > 0) {
1634                                 nSuccessLess = 0;
1635                                 IOBuf->BufUsed += rlen;
1636                                 IOBuf->buf[IOBuf->BufUsed] = '\0';
1637                                 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1638                                         IncreaseBuf(IOBuf, 1, -1);
1639                                 }
1640
1641                                 pche = IOBuf->buf + IOBuf->BufUsed;
1642                                 pch = IOBuf->buf;
1643                                 while ((pch < pche) && (*pch != '\n'))
1644                                         pch ++;
1645                                 if ((pch >= pche) || (*pch == '\0'))
1646                                         pch = NULL;
1647                                 continue;
1648                         }
1649                 }
1650                 nSuccessLess ++;
1651         }
1652         if (pch != NULL) {
1653                 pos = IOBuf->buf;
1654                 rlen = 0;
1655                 len = pch - pos;
1656                 if (len > 0 && (*(pch - 1) == '\r') )
1657                         rlen ++;
1658                 StrBufSub(Line, IOBuf, 0, len - rlen);
1659                 *Pos = pos + len + 1;
1660                 return len - rlen;
1661         }
1662         return -1;
1663
1664 }
1665
1666 /**
1667  * \brief Input binary data from socket
1668  * flushes and closes the FD on error
1669  * \param buf the buffer to get the input to
1670  * \param fd pointer to the filedescriptor to read
1671  * \param append Append to an existing string or replace?
1672  * \param nBytes the maximal number of bytes to read
1673  * \param Error strerror() on error 
1674  * \returns numbers of chars read
1675  */
1676 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1677 {
1678         fd_set wset;
1679         int fdflags;
1680         int len, rlen, slen;
1681         int nRead = 0;
1682         char *ptr;
1683
1684         if ((Buf == NULL) || (*fd == -1))
1685                 return -1;
1686         if (!append)
1687                 FlushStrBuf(Buf);
1688         if (Buf->BufUsed + nBytes >= Buf->BufSize)
1689                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1690
1691         ptr = Buf->buf + Buf->BufUsed;
1692
1693         slen = len = Buf->BufUsed;
1694
1695         fdflags = fcntl(*fd, F_GETFL);
1696
1697         while (nRead < nBytes) {
1698                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1699                         FD_ZERO(&wset);
1700                         FD_SET(*fd, &wset);
1701                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1702                                 *Error = strerror(errno);
1703                                 return -1;
1704                         }
1705                 }
1706
1707                 if ((rlen = read(*fd, 
1708                                  ptr,
1709                                  nBytes - nRead)) == -1) {
1710                         close(*fd);
1711                         *fd = -1;
1712                         *Error = strerror(errno);
1713                         return rlen;
1714                 }
1715                 nRead += rlen;
1716                 ptr += rlen;
1717                 Buf->BufUsed += rlen;
1718         }
1719         Buf->buf[Buf->BufUsed] = '\0';
1720         return nRead;
1721 }
1722
1723 /**
1724  * \brief Input binary data from socket
1725  * flushes and closes the FD on error
1726  * \param buf the buffer to get the input to
1727  * \param fd pointer to the filedescriptor to read
1728  * \param append Append to an existing string or replace?
1729  * \param nBytes the maximal number of bytes to read
1730  * \param Error strerror() on error 
1731  * \returns numbers of chars read
1732  */
1733 int StrBufReadBLOBBuffered(StrBuf *Blob, 
1734                            StrBuf *IOBuf, 
1735                            const char **Pos,
1736                            int *fd, 
1737                            int append, 
1738                            long nBytes, 
1739                            int check, 
1740                            const char **Error)
1741 {
1742         const char *pche;
1743         const char *pos;
1744         int nSelects = 0;
1745         int SelRes;
1746         fd_set wset;
1747         int fdflags;
1748         int len = 0;
1749         int rlen, slen;
1750         int nRead = 0;
1751         char *ptr;
1752         const char *pch;
1753
1754         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1755                 return -1;
1756         if (!append)
1757                 FlushStrBuf(Blob);
1758         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
1759                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1760         
1761         pos = *Pos;
1762
1763         if (pos > 0)
1764                 len = pos - IOBuf->buf;
1765         rlen = IOBuf->BufUsed - len;
1766
1767
1768         if ((IOBuf->BufUsed > 0) && 
1769             (pos != NULL) && 
1770             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1771         {
1772                 pche = IOBuf->buf + IOBuf->BufUsed;
1773                 pch = pos;
1774
1775                 if (rlen < nBytes) {
1776                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1777                         Blob->BufUsed += rlen;
1778                         Blob->buf[Blob->BufUsed] = '\0';
1779                         nRead = rlen;
1780                         *Pos = NULL; 
1781                 }
1782                 if (rlen >= nBytes) {
1783                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1784                         Blob->BufUsed += nBytes;
1785                         Blob->buf[Blob->BufUsed] = '\0';
1786                         if (rlen == nBytes) {
1787                                 *Pos = NULL; 
1788                                 FlushStrBuf(IOBuf);
1789                         }
1790                         else 
1791                                 *Pos += nBytes;
1792                         return nBytes;
1793                 }
1794         }
1795
1796         FlushStrBuf(IOBuf);
1797         if (IOBuf->BufSize < nBytes - nRead)
1798                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1799         ptr = IOBuf->buf;
1800
1801         slen = len = Blob->BufUsed;
1802
1803         fdflags = fcntl(*fd, F_GETFL);
1804
1805         SelRes = 1;
1806         nBytes -= nRead;
1807         nRead = 0;
1808         while (nRead < nBytes) {
1809                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1810                         FD_ZERO(&wset);
1811                         FD_SET(*fd, &wset);
1812                         SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1813                 }
1814                 if (SelRes == -1) {
1815                         *Error = strerror(errno);
1816                         return -1;
1817                 }
1818                 else if (SelRes) {
1819                         nSelects = 0;
1820                         rlen = read(*fd, 
1821                                     ptr,
1822                                     nBytes - nRead);
1823                         if (rlen == -1) {
1824                                 close(*fd);
1825                                 *fd = -1;
1826                                 *Error = strerror(errno);
1827                                 return rlen;
1828                         }
1829                 }
1830                 else {
1831                         nSelects ++;
1832                         if ((check == NNN_TERM) && 
1833                             (nRead > 5) &&
1834                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
1835                         {
1836                                 StrBufPlain(Blob, HKEY("\n000\n"));
1837                                 StrBufCutRight(Blob, 5);
1838                                 return Blob->BufUsed;
1839                         }
1840                         if (nSelects > 10) {
1841                                 FlushStrBuf(IOBuf);
1842                                 return -1;
1843                         }
1844                 }
1845                 if (rlen > 0) {
1846                         nRead += rlen;
1847                         ptr += rlen;
1848                         IOBuf->BufUsed += rlen;
1849                 }
1850         }
1851         if (nRead > nBytes) {
1852                 *Pos = IOBuf->buf + nBytes;
1853         }
1854         Blob->buf[Blob->BufUsed] = '\0';
1855         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1856         return nRead;
1857 }
1858
1859 /**
1860  * \brief Cut nChars from the start of the string
1861  * \param Buf Buffer to modify
1862  * \param nChars how many chars should be skipped?
1863  */
1864 void StrBufCutLeft(StrBuf *Buf, int nChars)
1865 {
1866         if (nChars >= Buf->BufUsed) {
1867                 FlushStrBuf(Buf);
1868                 return;
1869         }
1870         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1871         Buf->BufUsed -= nChars;
1872         Buf->buf[Buf->BufUsed] = '\0';
1873 }
1874
1875 /**
1876  * \brief Cut the trailing n Chars from the string
1877  * \param Buf Buffer to modify
1878  * \param nChars how many chars should be trunkated?
1879  */
1880 void StrBufCutRight(StrBuf *Buf, int nChars)
1881 {
1882         if (nChars >= Buf->BufUsed) {
1883                 FlushStrBuf(Buf);
1884                 return;
1885         }
1886         Buf->BufUsed -= nChars;
1887         Buf->buf[Buf->BufUsed] = '\0';
1888 }
1889
1890 /**
1891  * \brief Cut the string after n Chars
1892  * \param Buf Buffer to modify
1893  * \param AfternChars after how many chars should we trunkate the string?
1894  * \param At if non-null and points inside of our string, cut it there.
1895  */
1896 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1897 {
1898         if (At != NULL){
1899                 AfternChars = At - Buf->buf;
1900         }
1901
1902         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1903                 return;
1904         Buf->BufUsed = AfternChars;
1905         Buf->buf[Buf->BufUsed] = '\0';
1906 }
1907
1908
1909 /*
1910  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1911  * buf - the string to modify
1912  * len - length of the string. 
1913  */
1914 void StrBufTrim(StrBuf *Buf)
1915 {
1916         int delta = 0;
1917         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1918
1919         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1920                 delta ++;
1921         }
1922         if (delta > 0) StrBufCutLeft(Buf, delta);
1923
1924         if (Buf->BufUsed == 0) return;
1925         while (isspace(Buf->buf[Buf->BufUsed - 1])){
1926                 Buf->BufUsed --;
1927         }
1928         Buf->buf[Buf->BufUsed] = '\0';
1929 }
1930
1931
1932 void StrBufUpCase(StrBuf *Buf) 
1933 {
1934         char *pch, *pche;
1935
1936         pch = Buf->buf;
1937         pche = pch + Buf->BufUsed;
1938         while (pch < pche) {
1939                 *pch = toupper(*pch);
1940                 pch ++;
1941         }
1942 }
1943
1944
1945 void StrBufLowerCase(StrBuf *Buf) 
1946 {
1947         char *pch, *pche;
1948
1949         pch = Buf->buf;
1950         pche = pch + Buf->BufUsed;
1951         while (pch < pche) {
1952                 *pch = tolower(*pch);
1953                 pch ++;
1954         }
1955 }
1956
1957
1958 /**
1959  * \brief unhide special chars hidden to the HTML escaper
1960  * \param target buffer to put the unescaped string in
1961  * \param source buffer to unescape
1962  */
1963 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
1964 {
1965         int a, b, len;
1966         char hex[3];
1967
1968         if (target != NULL)
1969                 FlushStrBuf(target);
1970
1971         if (source == NULL ||target == NULL)
1972         {
1973                 return;
1974         }
1975
1976         len = source->BufUsed;
1977         for (a = 0; a < len; ++a) {
1978                 if (target->BufUsed >= target->BufSize)
1979                         IncreaseBuf(target, 1, -1);
1980
1981                 if (source->buf[a] == '=') {
1982                         hex[0] = source->buf[a + 1];
1983                         hex[1] = source->buf[a + 2];
1984                         hex[2] = 0;
1985                         b = 0;
1986                         sscanf(hex, "%02x", &b);
1987                         target->buf[target->BufUsed] = b;
1988                         target->buf[++target->BufUsed] = 0;
1989                         a += 2;
1990                 }
1991                 else {
1992                         target->buf[target->BufUsed] = source->buf[a];
1993                         target->buf[++target->BufUsed] = 0;
1994                 }
1995         }
1996 }
1997
1998
1999 /**
2000  * \brief hide special chars from the HTML escapers and friends
2001  * \param target buffer to put the escaped string in
2002  * \param source buffer to escape
2003  */
2004 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2005 {
2006         int i, len;
2007
2008         if (target != NULL)
2009                 FlushStrBuf(target);
2010
2011         if (source == NULL ||target == NULL)
2012         {
2013                 return;
2014         }
2015
2016         len = source->BufUsed;
2017         for (i=0; i<len; ++i) {
2018                 if (target->BufUsed + 4 >= target->BufSize)
2019                         IncreaseBuf(target, 1, -1);
2020                 if ( (isalnum(source->buf[i])) || 
2021                      (source->buf[i]=='-') || 
2022                      (source->buf[i]=='_') ) {
2023                         target->buf[target->BufUsed++] = source->buf[i];
2024                 }
2025                 else {
2026                         sprintf(&target->buf[target->BufUsed], 
2027                                 "=%02X", 
2028                                 (0xFF &source->buf[i]));
2029                         target->BufUsed += 3;
2030                 }
2031         }
2032         target->buf[target->BufUsed + 1] = '\0';
2033 }
2034
2035 /*
2036  * \brief uses the same calling syntax as compress2(), but it
2037  * creates a stream compatible with HTTP "Content-encoding: gzip"
2038  */
2039 #ifdef HAVE_ZLIB
2040 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2041 #define OS_CODE 0x03    /*< unix */
2042 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
2043                           size_t * destLen,     /*< length of the compresed data */
2044                           const Bytef * source, /*< source to encode */
2045                           uLong sourceLen,      /*< length of source to encode */
2046                           int level)            /*< compression level */
2047 {
2048         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2049
2050         /* write gzip header */
2051         snprintf((char *) dest, *destLen, 
2052                  "%c%c%c%c%c%c%c%c%c%c",
2053                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2054                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2055                  OS_CODE);
2056
2057         /* normal deflate */
2058         z_stream stream;
2059         int err;
2060         stream.next_in = (Bytef *) source;
2061         stream.avail_in = (uInt) sourceLen;
2062         stream.next_out = dest + 10L;   // after header
2063         stream.avail_out = (uInt) * destLen;
2064         if ((uLong) stream.avail_out != *destLen)
2065                 return Z_BUF_ERROR;
2066
2067         stream.zalloc = (alloc_func) 0;
2068         stream.zfree = (free_func) 0;
2069         stream.opaque = (voidpf) 0;
2070
2071         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2072                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2073         if (err != Z_OK)
2074                 return err;
2075
2076         err = deflate(&stream, Z_FINISH);
2077         if (err != Z_STREAM_END) {
2078                 deflateEnd(&stream);
2079                 return err == Z_OK ? Z_BUF_ERROR : err;
2080         }
2081         *destLen = stream.total_out + 10L;
2082
2083         /* write CRC and Length */
2084         uLong crc = crc32(0L, source, sourceLen);
2085         int n;
2086         for (n = 0; n < 4; ++n, ++*destLen) {
2087                 dest[*destLen] = (int) (crc & 0xff);
2088                 crc >>= 8;
2089         }
2090         uLong len = stream.total_in;
2091         for (n = 0; n < 4; ++n, ++*destLen) {
2092                 dest[*destLen] = (int) (len & 0xff);
2093                 len >>= 8;
2094         }
2095         err = deflateEnd(&stream);
2096         return err;
2097 }
2098 #endif
2099
2100
2101 /**
2102  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2103  */
2104 int CompressBuffer(StrBuf *Buf)
2105 {
2106 #ifdef HAVE_ZLIB
2107         char *compressed_data = NULL;
2108         size_t compressed_len, bufsize;
2109         int i = 0;
2110         
2111         bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2112         compressed_data = malloc(compressed_len);
2113         
2114         /* Flush some space after the used payload so valgrind shuts up... */
2115         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2116                 Buf->buf[Buf->BufUsed + i++] = '\0';
2117         if (compress_gzip((Bytef *) compressed_data,
2118                           &compressed_len,
2119                           (Bytef *) Buf->buf,
2120                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2121                 if (!Buf->ConstBuf)
2122                         free(Buf->buf);
2123                 Buf->buf = compressed_data;
2124                 Buf->BufUsed = compressed_len;
2125                 Buf->BufSize = bufsize;
2126                 /* Flush some space after the used payload so valgrind shuts up... */
2127                 i = 0;
2128                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2129                         Buf->buf[Buf->BufUsed + i++] = '\0';
2130                 return 1;
2131         } else {
2132                 free(compressed_data);
2133         }
2134 #endif  /* HAVE_ZLIB */
2135         return 0;
2136 }
2137
2138 /**
2139  * \brief decode a buffer from base 64 encoding; destroys original
2140  * \param Buf Buffor to transform
2141  */
2142 int StrBufDecodeBase64(StrBuf *Buf)
2143 {
2144         char *xferbuf;
2145         size_t siz;
2146         if (Buf == NULL) return -1;
2147
2148         xferbuf = (char*) malloc(Buf->BufSize);
2149         siz = CtdlDecodeBase64(xferbuf,
2150                                Buf->buf,
2151                                Buf->BufUsed);
2152         free(Buf->buf);
2153         Buf->buf = xferbuf;
2154         Buf->BufUsed = siz;
2155         return siz;
2156 }
2157
2158 /**
2159  * \brief decode a buffer from base 64 encoding; destroys original
2160  * \param Buf Buffor to transform
2161  */
2162 int StrBufDecodeHex(StrBuf *Buf)
2163 {
2164         unsigned int ch;
2165         char *pch, *pche, *pchi;
2166
2167         if (Buf == NULL) return -1;
2168
2169         pch = pchi = Buf->buf;
2170         pche = pch + Buf->BufUsed;
2171
2172         while (pchi < pche){
2173                 ch = decode_hex(pchi);
2174                 *pch = ch;
2175                 pch ++;
2176                 pchi += 2;
2177         }
2178
2179         *pch = '\0';
2180         Buf->BufUsed = pch - Buf->buf;
2181         return Buf->BufUsed;
2182 }
2183
2184 /**
2185  * \brief replace all chars >0x20 && < 0x7F with Mute
2186  * \param Mute char to put over invalid chars
2187  * \param Buf Buffor to transform
2188  */
2189 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2190 {
2191         unsigned char *pch;
2192
2193         if (Buf == NULL) return -1;
2194         pch = (unsigned char *)Buf->buf;
2195         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2196                 if ((*pch < 0x20) || (*pch > 0x7F))
2197                         *pch = Mute;
2198                 pch ++;
2199         }
2200         return Buf->BufUsed;
2201 }
2202
2203
2204 /**
2205  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
2206  * \param Buf Buffer to translate
2207  * \param StripBlanks Reduce several blanks to one?
2208  */
2209 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2210 {
2211         int a, b;
2212         char hex[3];
2213         long len;
2214
2215         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2216                 Buf->buf[Buf->BufUsed - 1] = '\0';
2217                 Buf->BufUsed --;
2218         }
2219
2220         a = 0; 
2221         while (a < Buf->BufUsed) {
2222                 if (Buf->buf[a] == '+')
2223                         Buf->buf[a] = ' ';
2224                 else if (Buf->buf[a] == '%') {
2225                         /* don't let % chars through, rather truncate the input. */
2226                         if (a + 2 > Buf->BufUsed) {
2227                                 Buf->buf[a] = '\0';
2228                                 Buf->BufUsed = a;
2229                         }
2230                         else {                  
2231                                 hex[0] = Buf->buf[a + 1];
2232                                 hex[1] = Buf->buf[a + 2];
2233                                 hex[2] = 0;
2234                                 b = 0;
2235                                 sscanf(hex, "%02x", &b);
2236                                 Buf->buf[a] = (char) b;
2237                                 len = Buf->BufUsed - a - 2;
2238                                 if (len > 0)
2239                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2240                         
2241                                 Buf->BufUsed -=2;
2242                         }
2243                 }
2244                 a++;
2245         }
2246         return a;
2247 }
2248
2249
2250 /**
2251  * \brief       RFC2047-encode a header field if necessary.
2252  *              If no non-ASCII characters are found, the string
2253  *              will be copied verbatim without encoding.
2254  *
2255  * \param       target          Target buffer.
2256  * \param       source          Source string to be encoded.
2257  * \returns     encoded length; -1 if non success.
2258  */
2259 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2260 {
2261         const char headerStr[] = "=?UTF-8?Q?";
2262         int need_to_encode = 0;
2263         int i = 0;
2264         unsigned char ch;
2265
2266         if ((source == NULL) || 
2267             (target == NULL))
2268             return -1;
2269
2270         while ((i < source->BufUsed) &&
2271                (!IsEmptyStr (&source->buf[i])) &&
2272                (need_to_encode == 0)) {
2273                 if (((unsigned char) source->buf[i] < 32) || 
2274                     ((unsigned char) source->buf[i] > 126)) {
2275                         need_to_encode = 1;
2276                 }
2277                 i++;
2278         }
2279
2280         if (!need_to_encode) {
2281                 if (*target == NULL) {
2282                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2283                 }
2284                 else {
2285                         FlushStrBuf(*target);
2286                         StrBufAppendBuf(*target, source, 0);
2287                 }
2288                 return (*target)->BufUsed;
2289         }
2290         if (*target == NULL)
2291                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2292         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2293                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2294         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2295         (*target)->BufUsed = sizeof(headerStr) - 1;
2296         for (i=0; (i < source->BufUsed); ++i) {
2297                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2298                         IncreaseBuf(*target, 1, 0);
2299                 ch = (unsigned char) source->buf[i];
2300                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2301                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2302                         (*target)->BufUsed += 3;
2303                 }
2304                 else {
2305                         (*target)->buf[(*target)->BufUsed] = ch;
2306                         (*target)->BufUsed++;
2307                 }
2308         }
2309         
2310         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2311                 IncreaseBuf(*target, 1, 0);
2312
2313         (*target)->buf[(*target)->BufUsed++] = '?';
2314         (*target)->buf[(*target)->BufUsed++] = '=';
2315         (*target)->buf[(*target)->BufUsed] = '\0';
2316         return (*target)->BufUsed;;
2317 }
2318
2319 /**
2320  * \brief replaces all occurances of 'search' by 'replace'
2321  * \param buf Buffer to modify
2322  * \param search character to search
2323  * \param relpace character to replace search by
2324  */
2325 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2326 {
2327         long i;
2328         if (buf == NULL)
2329                 return;
2330         for (i=0; i<buf->BufUsed; i++)
2331                 if (buf->buf[i] == search)
2332                         buf->buf[i] = replace;
2333
2334 }
2335
2336
2337
2338 /*
2339  * Wrapper around iconv_open()
2340  * Our version adds aliases for non-standard Microsoft charsets
2341  * such as 'MS950', aliasing them to names like 'CP950'
2342  *
2343  * tocode       Target encoding
2344  * fromcode     Source encoding
2345  */
2346 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2347 {
2348 #ifdef HAVE_ICONV
2349         iconv_t ic = (iconv_t)(-1) ;
2350         ic = iconv_open(tocode, fromcode);
2351         if (ic == (iconv_t)(-1) ) {
2352                 char alias_fromcode[64];
2353                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2354                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2355                         alias_fromcode[0] = 'C';
2356                         alias_fromcode[1] = 'P';
2357                         ic = iconv_open(tocode, alias_fromcode);
2358                 }
2359         }
2360         *(iconv_t *)pic = ic;
2361 #endif
2362 }
2363
2364
2365
2366 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2367 {
2368         char * end;
2369         /* Find the next ?Q? */
2370         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2371                 return NULL;
2372
2373         end = strchr(bptr + 2, '?');
2374
2375         if (end == NULL)
2376                 return NULL;
2377
2378         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2379             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
2380             (*(end + 2) == '?')) {
2381                 /* skip on to the end of the cluster, the next ?= */
2382                 end = strstr(end + 3, "?=");
2383         }
2384         else
2385                 /* sort of half valid encoding, try to find an end. */
2386                 end = strstr(bptr, "?=");
2387         return end;
2388 }
2389
2390
2391 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2392 {
2393 #ifdef HAVE_ICONV
2394         int BufSize;
2395         iconv_t ic;
2396         char *ibuf;                     /**< Buffer of characters to be converted */
2397         char *obuf;                     /**< Buffer for converted characters */
2398         size_t ibuflen;                 /**< Length of input buffer */
2399         size_t obuflen;                 /**< Length of output buffer */
2400
2401
2402         if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2403                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2404
2405         ic = *(iconv_t*)pic;
2406         ibuf = ConvertBuf->buf;
2407         ibuflen = ConvertBuf->BufUsed;
2408         obuf = TmpBuf->buf;
2409         obuflen = TmpBuf->BufSize;
2410         
2411         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2412
2413         /* little card game: wheres the red lady? */
2414         ibuf = ConvertBuf->buf;
2415         BufSize = ConvertBuf->BufSize;
2416
2417         ConvertBuf->buf = TmpBuf->buf;
2418         ConvertBuf->BufSize = TmpBuf->BufSize;
2419         ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2420         ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2421         
2422         TmpBuf->buf = ibuf;
2423         TmpBuf->BufSize = BufSize;
2424         TmpBuf->BufUsed = 0;
2425         TmpBuf->buf[0] = '\0';
2426 #endif
2427 }
2428
2429
2430
2431
2432 inline static void DecodeSegment(StrBuf *Target, 
2433                                  const StrBuf *DecodeMe, 
2434                                  char *SegmentStart, 
2435                                  char *SegmentEnd, 
2436                                  StrBuf *ConvertBuf,
2437                                  StrBuf *ConvertBuf2, 
2438                                  StrBuf *FoundCharset)
2439 {
2440         StrBuf StaticBuf;
2441         char charset[128];
2442         char encoding[16];
2443 #ifdef HAVE_ICONV
2444         iconv_t ic = (iconv_t)(-1);
2445 #endif
2446         /* Now we handle foreign character sets properly encoded
2447          * in RFC2047 format.
2448          */
2449         StaticBuf.buf = SegmentStart;
2450         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2451         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2452         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2453         if (FoundCharset != NULL) {
2454                 FlushStrBuf(FoundCharset);
2455                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2456         }
2457         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2458         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2459         
2460         *encoding = toupper(*encoding);
2461         if (*encoding == 'B') { /**< base64 */
2462                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
2463                                                         ConvertBuf->buf, 
2464                                                         ConvertBuf->BufUsed);
2465         }
2466         else if (*encoding == 'Q') {    /**< quoted-printable */
2467                 long pos;
2468                 
2469                 pos = 0;
2470                 while (pos < ConvertBuf->BufUsed)
2471                 {
2472                         if (ConvertBuf->buf[pos] == '_') 
2473                                 ConvertBuf->buf[pos] = ' ';
2474                         pos++;
2475                 }
2476                 
2477                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2478                         ConvertBuf2->buf, 
2479                         ConvertBuf->buf,
2480                         ConvertBuf->BufUsed);
2481         }
2482         else {
2483                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2484         }
2485 #ifdef HAVE_ICONV
2486         ctdl_iconv_open("UTF-8", charset, &ic);
2487         if (ic != (iconv_t)(-1) ) {             
2488 #endif
2489                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2490                 StrBufAppendBuf(Target, ConvertBuf2, 0);
2491 #ifdef HAVE_ICONV
2492                 iconv_close(ic);
2493         }
2494         else {
2495                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2496         }
2497 #endif
2498 }
2499 /*
2500  * Handle subjects with RFC2047 encoding such as:
2501  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2502  */
2503 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2504 {
2505         StrBuf *ConvertBuf, *ConvertBuf2;
2506         char *start, *end, *next, *nextend, *ptr = NULL;
2507 #ifdef HAVE_ICONV
2508         iconv_t ic = (iconv_t)(-1) ;
2509 #endif
2510         const char *eptr;
2511         int passes = 0;
2512         int i, len, delta;
2513         int illegal_non_rfc2047_encoding = 0;
2514
2515         /* Sometimes, badly formed messages contain strings which were simply
2516          *  written out directly in some foreign character set instead of
2517          *  using RFC2047 encoding.  This is illegal but we will attempt to
2518          *  handle it anyway by converting from a user-specified default
2519          *  charset to UTF-8 if we see any nonprintable characters.
2520          */
2521         
2522         len = StrLength(DecodeMe);
2523         for (i=0; i<DecodeMe->BufUsed; ++i) {
2524                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2525                         illegal_non_rfc2047_encoding = 1;
2526                         break;
2527                 }
2528         }
2529
2530         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2531         if ((illegal_non_rfc2047_encoding) &&
2532             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
2533             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2534         {
2535 #ifdef HAVE_ICONV
2536                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2537                 if (ic != (iconv_t)(-1) ) {
2538                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2539                         iconv_close(ic);
2540                 }
2541 #endif
2542         }
2543
2544         /* pre evaluate the first pair */
2545         nextend = end = NULL;
2546         len = StrLength(DecodeMe);
2547         start = strstr(DecodeMe->buf, "=?");
2548         eptr = DecodeMe->buf + DecodeMe->BufUsed;
2549         if (start != NULL) 
2550                 end = FindNextEnd (DecodeMe, start);
2551         else {
2552                 StrBufAppendBuf(Target, DecodeMe, 0);
2553                 FreeStrBuf(&ConvertBuf);
2554                 return;
2555         }
2556
2557         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2558
2559         if (start != DecodeMe->buf)
2560                 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2561         /*
2562          * Since spammers will go to all sorts of absurd lengths to get their
2563          * messages through, there are LOTS of corrupt headers out there.
2564          * So, prevent a really badly formed RFC2047 header from throwing
2565          * this function into an infinite loop.
2566          */
2567         while ((start != NULL) && 
2568                (end != NULL) && 
2569                (start < eptr) && 
2570                (end < eptr) && 
2571                (passes < 20))
2572         {
2573                 passes++;
2574                 DecodeSegment(Target, 
2575                               DecodeMe, 
2576                               start, 
2577                               end, 
2578                               ConvertBuf,
2579                               ConvertBuf2,
2580                               FoundCharset);
2581                 
2582                 next = strstr(end, "=?");
2583                 nextend = NULL;
2584                 if ((next != NULL) && 
2585                     (next < eptr))
2586                         nextend = FindNextEnd(DecodeMe, next);
2587                 if (nextend == NULL)
2588                         next = NULL;
2589
2590                 /* did we find two partitions */
2591                 if ((next != NULL) && 
2592                     ((next - end) > 2))
2593                 {
2594                         ptr = end + 2;
2595                         while ((ptr < next) && 
2596                                (isspace(*ptr) ||
2597                                 (*ptr == '\r') ||
2598                                 (*ptr == '\n') || 
2599                                 (*ptr == '\t')))
2600                                 ptr ++;
2601                         /* did we find a gab just filled with blanks? */
2602                         if (ptr == next)
2603                         {
2604                                 memmove (end + 2,
2605                                          next,
2606                                          len - (next - start));
2607                                 
2608                                 /* now terminate the gab at the end */
2609                                 delta = (next - end) - 2; ////TODO: const! 
2610                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2611                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2612
2613                                 /* move next to its new location. */
2614                                 next -= delta;
2615                                 nextend -= delta;
2616                         }
2617                 }
2618                 /* our next-pair is our new first pair now. */
2619                 ptr = end + 2;
2620                 start = next;
2621                 end = nextend;
2622         }
2623         end = ptr;
2624         nextend = DecodeMe->buf + DecodeMe->BufUsed;
2625         if ((end != NULL) && (end < nextend)) {
2626                 ptr = end;
2627                 while ( (ptr < nextend) &&
2628                         (isspace(*ptr) ||
2629                          (*ptr == '\r') ||
2630                          (*ptr == '\n') || 
2631                          (*ptr == '\t')))
2632                         ptr ++;
2633                 if (ptr < nextend)
2634                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
2635         }
2636         FreeStrBuf(&ConvertBuf);
2637         FreeStrBuf(&ConvertBuf2);
2638 }
2639
2640
2641
2642 long StrBuf_Utf8StrLen(StrBuf *Buf)
2643 {
2644         return Ctdl_Utf8StrLen(Buf->buf);
2645 }
2646
2647 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2648 {
2649         char *CutAt;
2650
2651         CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2652         if (CutAt != NULL) {
2653                 Buf->BufUsed = CutAt - Buf->buf;
2654                 Buf->buf[Buf->BufUsed] = '\0';
2655         }
2656         return Buf->BufUsed;    
2657 }
2658
2659
2660
2661 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2662 {
2663         const char *aptr, *ptr, *eptr;
2664         char *optr, *xptr;
2665
2666         if (Buf == NULL)
2667                 return 0;
2668
2669         if (*Ptr==NULL)
2670                 ptr = aptr = Buf->buf;
2671         else
2672                 ptr = aptr = *Ptr;
2673
2674         optr = LineBuf->buf;
2675         eptr = Buf->buf + Buf->BufUsed;
2676         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2677
2678         while ((*ptr != '\n') &&
2679                (*ptr != '\r') &&
2680                (ptr < eptr))
2681         {
2682                 *optr = *ptr;
2683                 optr++; ptr++;
2684                 if (optr == xptr) {
2685                         LineBuf->BufUsed = optr - LineBuf->buf;
2686                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
2687                         optr = LineBuf->buf + LineBuf->BufUsed;
2688                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2689                 }
2690         }
2691         LineBuf->BufUsed = optr - LineBuf->buf;
2692         *optr = '\0';       
2693         if (*ptr == '\r')
2694                 ptr ++;
2695         if (*ptr == '\n')
2696                 ptr ++;
2697
2698         *Ptr = ptr;
2699
2700         return Buf->BufUsed - (ptr - Buf->buf);
2701 }