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