* fix IncreaseBuf
[citadel.git] / libcitadel / lib / stringbuf.c
1 #include "../sysdep.h"
2 #include <ctype.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <sys/select.h>
9 #include <fcntl.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
12 #include <stdarg.h>
13 #include "libcitadel.h"
14
15 #ifdef HAVE_ICONV
16 #include <iconv.h>
17 #endif
18
19 #if HAVE_BACKTRACE
20 #include <execinfo.h>
21 #endif
22
23 #ifdef HAVE_ZLIB
24 #include <zlib.h>
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26                           const Bytef * source, uLong sourceLen, int level);
27 #endif
28 int BaseStrBufSize = SIZ;
29
30 /**
31  * Private Structure for the Stringbuffer
32  */
33 struct StrBuf {
34         char *buf;         /**< the pointer to the dynamic buffer */
35         long BufSize;      /**< how many spcae do we optain */
36         long BufUsed;      /**< StNumber of Chars used excluding the trailing \0 */
37         int ConstBuf;      /**< are we just a wrapper arround a static buffer and musn't we be changed? */
38 #ifdef SIZE_DEBUG
39         long nIncreases;
40         char bt [SIZ];
41         char bt_lastinc [SIZ];
42 #endif
43 };
44
45 #ifdef SIZE_DEBUG
46 #if HAVE_BACKTRACE
47 static void StrBufBacktrace(StrBuf *Buf, int which)
48 {
49         int n;
50         char *pstart, *pch;
51         void *stack_frames[50];
52         size_t size, i;
53         char **strings;
54
55         if (which)
56                 pstart = pch = Buf->bt;
57         else
58                 pstart = pch = Buf->bt_lastinc;
59         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
60         strings = backtrace_symbols(stack_frames, size);
61         for (i = 0; i < size; i++) {
62                 if (strings != NULL)
63                         n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
64                 else
65                         n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
66                 pch += n;
67         }
68         free(strings);
69
70
71 }
72 #endif
73 #endif
74
75 /** 
76  * \Brief Cast operator to Plain String 
77  * Note: if the buffer is altered by StrBuf operations, this pointer may become 
78  *  invalid. So don't lean on it after altering the buffer!
79  *  Since this operation is considered cheap, rather call it often than risking
80  *  your pointer to become invalid!
81  * \param Str the string we want to get the c-string representation for
82  * \returns the Pointer to the Content. Don't mess with it!
83  */
84 inline const char *ChrPtr(const StrBuf *Str)
85 {
86         if (Str == NULL)
87                 return "";
88         return Str->buf;
89 }
90
91 /**
92  * \brief since we know strlen()'s result, provide it here.
93  * \param Str the string to return the length to
94  * \returns contentlength of the buffer
95  */
96 inline int StrLength(const StrBuf *Str)
97 {
98         return (Str != NULL) ? Str->BufUsed : 0;
99 }
100
101 /**
102  * \brief local utility function to resize the buffer
103  * \param Buf the buffer whichs storage we should increase
104  * \param KeepOriginal should we copy the original buffer or just start over with a new one
105  * \param DestSize what should fit in after?
106  */
107 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
108 {
109         char *NewBuf;
110         size_t NewSize = Buf->BufSize * 2;
111
112         if (Buf->ConstBuf)
113                 return -1;
114                 
115         if (DestSize > 0)
116                 while (NewSize <= DestSize)
117                         NewSize *= 2;
118
119         NewBuf= (char*) malloc(NewSize);
120         if (KeepOriginal && (Buf->BufUsed > 0))
121         {
122                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
123         }
124         else
125         {
126                 NewBuf[0] = '\0';
127                 Buf->BufUsed = 0;
128         }
129         free (Buf->buf);
130         Buf->buf = NewBuf;
131         Buf->BufSize = NewSize;
132 #ifdef SIZE_DEBUG
133         Buf->nIncreases++;
134 #if HAVE_BACKTRACE
135         StrBufBacktrace(Buf, 1);
136 #endif
137 #endif
138         return Buf->BufSize;
139 }
140
141 /**
142  * \brief shrink 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 *IOBuf, 
1534                                       const char **Pos,
1535                                       int *fd, 
1536                                       int timeout, 
1537                                       int selectresolution, 
1538                                       const char **Error)
1539 {
1540         const char *pche;
1541         const char *pos;
1542         int len, rlen;
1543         int nSuccessLess = 0;
1544         fd_set rfds;
1545         const char *pch = NULL;
1546         int fdflags;
1547         struct timeval tv;
1548         
1549         pos = *Pos;
1550         if ((IOBuf->BufUsed > 0) && 
1551             (pos != NULL) && 
1552             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1553         {
1554                 pche = IOBuf->buf + IOBuf->BufUsed;
1555                 pch = pos;
1556                 while ((pch < pche) && (*pch != '\n'))
1557                         pch ++;
1558                 if ((pch >= pche) || (*pch == '\0'))
1559                         pch = NULL;
1560                 if ((pch != NULL) && 
1561                     (pch <= pche)) 
1562                 {
1563                         rlen = 0;
1564                         len = pch - pos;
1565                         if (len > 0 && (*(pch - 1) == '\r') )
1566                                 rlen ++;
1567                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1568                         *Pos = pch + 1;
1569                         return len - rlen;
1570                 }
1571         }
1572         
1573         if (pos != NULL) {
1574                 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1575                 *Pos = NULL;
1576         }
1577         
1578         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1579                 IncreaseBuf(IOBuf, 1, -1);
1580         }
1581
1582         fdflags = fcntl(*fd, F_GETFL);
1583         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1584                 return -1;
1585
1586         while ((nSuccessLess < timeout) && (pch == NULL)) {
1587                 tv.tv_sec = selectresolution;
1588                 tv.tv_usec = 0;
1589                 
1590                 FD_ZERO(&rfds);
1591                 FD_SET(*fd, &rfds);
1592                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1593                         *Error = strerror(errno);
1594                         close (*fd);
1595                         *fd = -1;
1596                         return -1;
1597                 }               
1598                 if (FD_ISSET(*fd, &rfds) != 0) {
1599                         rlen = read(*fd, 
1600                                     &IOBuf->buf[IOBuf->BufUsed], 
1601                                     IOBuf->BufSize - IOBuf->BufUsed - 1);
1602                         if (rlen < 1) {
1603                                 *Error = strerror(errno);
1604                                 close(*fd);
1605                                 *fd = -1;
1606                                 return -1;
1607                         }
1608                         else if (rlen > 0) {
1609                                 nSuccessLess = 0;
1610                                 IOBuf->BufUsed += rlen;
1611                                 IOBuf->buf[IOBuf->BufUsed] = '\0';
1612                                 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1613                                         IncreaseBuf(IOBuf, 1, -1);
1614                                 }
1615                                 pch = strchr(IOBuf->buf, '\n');
1616                                 continue;
1617                         }
1618                 }
1619                 nSuccessLess ++;
1620         }
1621         if (pch != NULL) {
1622                 pos = IOBuf->buf;
1623                 rlen = 0;
1624                 len = pch - pos;
1625                 if (len > 0 && (*(pch - 1) == '\r') )
1626                         rlen ++;
1627                 StrBufSub(Line, IOBuf, 0, len - rlen);
1628                 *Pos = pos + len + 1;
1629                 return len - rlen;
1630         }
1631         return -1;
1632
1633 }
1634
1635 /**
1636  * \brief Input binary data from socket
1637  * flushes and closes the FD on error
1638  * \param buf the buffer to get the input to
1639  * \param fd pointer to the filedescriptor to read
1640  * \param append Append to an existing string or replace?
1641  * \param nBytes the maximal number of bytes to read
1642  * \param Error strerror() on error 
1643  * \returns numbers of chars read
1644  */
1645 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1646 {
1647         fd_set wset;
1648         int fdflags;
1649         int len, rlen, slen;
1650         int nRead = 0;
1651         char *ptr;
1652
1653         if ((Buf == NULL) || (*fd == -1))
1654                 return -1;
1655         if (!append)
1656                 FlushStrBuf(Buf);
1657         if (Buf->BufUsed + nBytes >= Buf->BufSize)
1658                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1659
1660         ptr = Buf->buf + Buf->BufUsed;
1661
1662         slen = len = Buf->BufUsed;
1663
1664         fdflags = fcntl(*fd, F_GETFL);
1665
1666         while (nRead < nBytes) {
1667                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1668                         FD_ZERO(&wset);
1669                         FD_SET(*fd, &wset);
1670                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1671                                 *Error = strerror(errno);
1672                                 return -1;
1673                         }
1674                 }
1675
1676                 if ((rlen = read(*fd, 
1677                                  ptr,
1678                                  nBytes - nRead)) == -1) {
1679                         close(*fd);
1680                         *fd = -1;
1681                         *Error = strerror(errno);
1682                         return rlen;
1683                 }
1684                 nRead += rlen;
1685                 ptr += rlen;
1686                 Buf->BufUsed += rlen;
1687         }
1688         Buf->buf[Buf->BufUsed] = '\0';
1689         return nRead;
1690 }
1691
1692 /**
1693  * \brief Input binary data from socket
1694  * flushes and closes the FD on error
1695  * \param buf the buffer to get the input to
1696  * \param fd pointer to the filedescriptor to read
1697  * \param append Append to an existing string or replace?
1698  * \param nBytes the maximal number of bytes to read
1699  * \param Error strerror() on error 
1700  * \returns numbers of chars read
1701  */
1702 int StrBufReadBLOBBuffered(StrBuf *Blob, 
1703                            StrBuf *IOBuf, 
1704                            const char **Pos,
1705                            int *fd, 
1706                            int append, 
1707                            long nBytes, 
1708                            int check, 
1709                            const char **Error)
1710 {
1711         const char *pche;
1712         const char *pos;
1713         int nSelects = 0;
1714         int SelRes;
1715         fd_set wset;
1716         int fdflags;
1717         int len = 0;
1718         int rlen, slen;
1719         int nRead = 0;
1720         char *ptr;
1721         const char *pch;
1722
1723         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1724                 return -1;
1725         if (!append)
1726                 FlushStrBuf(Blob);
1727         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
1728                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1729         
1730         pos = *Pos;
1731
1732         if (pos > 0)
1733                 len = pos - IOBuf->buf;
1734         rlen = IOBuf->BufUsed - len;
1735
1736
1737         if ((IOBuf->BufUsed > 0) && 
1738             (pos != NULL) && 
1739             (pos < IOBuf->buf + IOBuf->BufUsed)) 
1740         {
1741                 pche = IOBuf->buf + IOBuf->BufUsed;
1742                 pch = pos;
1743
1744                 if (rlen < nBytes) {
1745                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1746                         Blob->BufUsed += rlen;
1747                         Blob->buf[Blob->BufUsed] = '\0';
1748                         nRead = rlen;
1749                         *Pos = NULL; 
1750                 }
1751                 if (rlen >= nBytes) {
1752                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1753                         Blob->BufUsed += nBytes;
1754                         Blob->buf[Blob->BufUsed] = '\0';
1755                         if (rlen == nBytes) {
1756                                 *Pos = NULL; 
1757                                 FlushStrBuf(IOBuf);
1758                         }
1759                         else 
1760                                 *Pos += nBytes;
1761                         return nBytes;
1762                 }
1763         }
1764
1765         FlushStrBuf(IOBuf);
1766         if (IOBuf->BufSize < nBytes - nRead)
1767                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1768         ptr = IOBuf->buf;
1769
1770         slen = len = Blob->BufUsed;
1771
1772         fdflags = fcntl(*fd, F_GETFL);
1773
1774         SelRes = 1;
1775         nBytes -= nRead;
1776         nRead = 0;
1777         while (nRead < nBytes) {
1778                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1779                         FD_ZERO(&wset);
1780                         FD_SET(*fd, &wset);
1781                         SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1782                 }
1783                 if (SelRes == -1) {
1784                         *Error = strerror(errno);
1785                         return -1;
1786                 }
1787                 else if (SelRes) {
1788                         nSelects = 0;
1789                         rlen = read(*fd, 
1790                                     ptr,
1791                                     nBytes - nRead);
1792                         if (rlen == -1) {
1793                                 close(*fd);
1794                                 *fd = -1;
1795                                 *Error = strerror(errno);
1796                                 return rlen;
1797                         }
1798                 }
1799                 else {
1800                         nSelects ++;
1801                         if ((check == NNN_TERM) && 
1802                             (nRead > 5) &&
1803                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
1804                         {
1805                                 StrBufPlain(Blob, HKEY("\n000\n"));
1806                                 StrBufCutRight(Blob, 5);
1807                                 return Blob->BufUsed;
1808                         }
1809                         if (nSelects > 10) {
1810                                 FlushStrBuf(IOBuf);
1811                                 return -1;
1812                         }
1813                 }
1814                 if (rlen > 0) {
1815                         nRead += rlen;
1816                         ptr += rlen;
1817                         IOBuf->BufUsed += rlen;
1818                 }
1819         }
1820         if (nRead > nBytes) {
1821                 *Pos = IOBuf->buf + nBytes;
1822         }
1823         Blob->buf[Blob->BufUsed] = '\0';
1824         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1825         return nRead;
1826 }
1827
1828 /**
1829  * \brief Cut nChars from the start of the string
1830  * \param Buf Buffer to modify
1831  * \param nChars how many chars should be skipped?
1832  */
1833 void StrBufCutLeft(StrBuf *Buf, int nChars)
1834 {
1835         if (nChars >= Buf->BufUsed) {
1836                 FlushStrBuf(Buf);
1837                 return;
1838         }
1839         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1840         Buf->BufUsed -= nChars;
1841         Buf->buf[Buf->BufUsed] = '\0';
1842 }
1843
1844 /**
1845  * \brief Cut the trailing n Chars from the string
1846  * \param Buf Buffer to modify
1847  * \param nChars how many chars should be trunkated?
1848  */
1849 void StrBufCutRight(StrBuf *Buf, int nChars)
1850 {
1851         if (nChars >= Buf->BufUsed) {
1852                 FlushStrBuf(Buf);
1853                 return;
1854         }
1855         Buf->BufUsed -= nChars;
1856         Buf->buf[Buf->BufUsed] = '\0';
1857 }
1858
1859 /**
1860  * \brief Cut the string after n Chars
1861  * \param Buf Buffer to modify
1862  * \param AfternChars after how many chars should we trunkate the string?
1863  * \param At if non-null and points inside of our string, cut it there.
1864  */
1865 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1866 {
1867         if (At != NULL){
1868                 AfternChars = At - Buf->buf;
1869         }
1870
1871         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1872                 return;
1873         Buf->BufUsed = AfternChars;
1874         Buf->buf[Buf->BufUsed] = '\0';
1875 }
1876
1877
1878 /*
1879  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1880  * buf - the string to modify
1881  * len - length of the string. 
1882  */
1883 void StrBufTrim(StrBuf *Buf)
1884 {
1885         int delta = 0;
1886         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1887
1888         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1889                 delta ++;
1890         }
1891         if (delta > 0) StrBufCutLeft(Buf, delta);
1892
1893         if (Buf->BufUsed == 0) return;
1894         while (isspace(Buf->buf[Buf->BufUsed - 1])){
1895                 Buf->BufUsed --;
1896         }
1897         Buf->buf[Buf->BufUsed] = '\0';
1898 }
1899
1900
1901 void StrBufUpCase(StrBuf *Buf) 
1902 {
1903         char *pch, *pche;
1904
1905         pch = Buf->buf;
1906         pche = pch + Buf->BufUsed;
1907         while (pch < pche) {
1908                 *pch = toupper(*pch);
1909                 pch ++;
1910         }
1911 }
1912
1913
1914 void StrBufLowerCase(StrBuf *Buf) 
1915 {
1916         char *pch, *pche;
1917
1918         pch = Buf->buf;
1919         pche = pch + Buf->BufUsed;
1920         while (pch < pche) {
1921                 *pch = tolower(*pch);
1922                 pch ++;
1923         }
1924 }
1925
1926
1927 /**
1928  * \brief unhide special chars hidden to the HTML escaper
1929  * \param target buffer to put the unescaped string in
1930  * \param source buffer to unescape
1931  */
1932 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
1933 {
1934         int a, b, len;
1935         char hex[3];
1936
1937         if (target != NULL)
1938                 FlushStrBuf(target);
1939
1940         if (source == NULL ||target == NULL)
1941         {
1942                 return;
1943         }
1944
1945         len = source->BufUsed;
1946         for (a = 0; a < len; ++a) {
1947                 if (target->BufUsed >= target->BufSize)
1948                         IncreaseBuf(target, 1, -1);
1949
1950                 if (source->buf[a] == '=') {
1951                         hex[0] = source->buf[a + 1];
1952                         hex[1] = source->buf[a + 2];
1953                         hex[2] = 0;
1954                         b = 0;
1955                         sscanf(hex, "%02x", &b);
1956                         target->buf[target->BufUsed] = b;
1957                         target->buf[++target->BufUsed] = 0;
1958                         a += 2;
1959                 }
1960                 else {
1961                         target->buf[target->BufUsed] = source->buf[a];
1962                         target->buf[++target->BufUsed] = 0;
1963                 }
1964         }
1965 }
1966
1967
1968 /**
1969  * \brief hide special chars from the HTML escapers and friends
1970  * \param target buffer to put the escaped string in
1971  * \param source buffer to escape
1972  */
1973 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
1974 {
1975         int i, len;
1976
1977         if (target != NULL)
1978                 FlushStrBuf(target);
1979
1980         if (source == NULL ||target == NULL)
1981         {
1982                 return;
1983         }
1984
1985         len = source->BufUsed;
1986         for (i=0; i<len; ++i) {
1987                 if (target->BufUsed + 4 >= target->BufSize)
1988                         IncreaseBuf(target, 1, -1);
1989                 if ( (isalnum(source->buf[i])) || 
1990                      (source->buf[i]=='-') || 
1991                      (source->buf[i]=='_') ) {
1992                         target->buf[target->BufUsed++] = source->buf[i];
1993                 }
1994                 else {
1995                         sprintf(&target->buf[target->BufUsed], 
1996                                 "=%02X", 
1997                                 (0xFF &source->buf[i]));
1998                         target->BufUsed += 3;
1999                 }
2000         }
2001         target->buf[target->BufUsed + 1] = '\0';
2002 }
2003
2004 /*
2005  * \brief uses the same calling syntax as compress2(), but it
2006  * creates a stream compatible with HTTP "Content-encoding: gzip"
2007  */
2008 #ifdef HAVE_ZLIB
2009 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2010 #define OS_CODE 0x03    /*< unix */
2011 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
2012                           size_t * destLen,     /*< length of the compresed data */
2013                           const Bytef * source, /*< source to encode */
2014                           uLong sourceLen,      /*< length of source to encode */
2015                           int level)            /*< compression level */
2016 {
2017         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2018
2019         /* write gzip header */
2020         snprintf((char *) dest, *destLen, 
2021                  "%c%c%c%c%c%c%c%c%c%c",
2022                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2023                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2024                  OS_CODE);
2025
2026         /* normal deflate */
2027         z_stream stream;
2028         int err;
2029         stream.next_in = (Bytef *) source;
2030         stream.avail_in = (uInt) sourceLen;
2031         stream.next_out = dest + 10L;   // after header
2032         stream.avail_out = (uInt) * destLen;
2033         if ((uLong) stream.avail_out != *destLen)
2034                 return Z_BUF_ERROR;
2035
2036         stream.zalloc = (alloc_func) 0;
2037         stream.zfree = (free_func) 0;
2038         stream.opaque = (voidpf) 0;
2039
2040         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2041                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2042         if (err != Z_OK)
2043                 return err;
2044
2045         err = deflate(&stream, Z_FINISH);
2046         if (err != Z_STREAM_END) {
2047                 deflateEnd(&stream);
2048                 return err == Z_OK ? Z_BUF_ERROR : err;
2049         }
2050         *destLen = stream.total_out + 10L;
2051
2052         /* write CRC and Length */
2053         uLong crc = crc32(0L, source, sourceLen);
2054         int n;
2055         for (n = 0; n < 4; ++n, ++*destLen) {
2056                 dest[*destLen] = (int) (crc & 0xff);
2057                 crc >>= 8;
2058         }
2059         uLong len = stream.total_in;
2060         for (n = 0; n < 4; ++n, ++*destLen) {
2061                 dest[*destLen] = (int) (len & 0xff);
2062                 len >>= 8;
2063         }
2064         err = deflateEnd(&stream);
2065         return err;
2066 }
2067 #endif
2068
2069
2070 /**
2071  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2072  */
2073 int CompressBuffer(StrBuf *Buf)
2074 {
2075 #ifdef HAVE_ZLIB
2076         char *compressed_data = NULL;
2077         size_t compressed_len, bufsize;
2078         int i = 0;
2079         
2080         bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2081         compressed_data = malloc(compressed_len);
2082         
2083         /* Flush some space after the used payload so valgrind shuts up... */
2084         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2085                 Buf->buf[Buf->BufUsed + i++] = '\0';
2086         if (compress_gzip((Bytef *) compressed_data,
2087                           &compressed_len,
2088                           (Bytef *) Buf->buf,
2089                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2090                 if (!Buf->ConstBuf)
2091                         free(Buf->buf);
2092                 Buf->buf = compressed_data;
2093                 Buf->BufUsed = compressed_len;
2094                 Buf->BufSize = bufsize;
2095                 /* Flush some space after the used payload so valgrind shuts up... */
2096                 i = 0;
2097                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2098                         Buf->buf[Buf->BufUsed + i++] = '\0';
2099                 return 1;
2100         } else {
2101                 free(compressed_data);
2102         }
2103 #endif  /* HAVE_ZLIB */
2104         return 0;
2105 }
2106
2107 /**
2108  * \brief decode a buffer from base 64 encoding; destroys original
2109  * \param Buf Buffor to transform
2110  */
2111 int StrBufDecodeBase64(StrBuf *Buf)
2112 {
2113         char *xferbuf;
2114         size_t siz;
2115         if (Buf == NULL) return -1;
2116
2117         xferbuf = (char*) malloc(Buf->BufSize);
2118         siz = CtdlDecodeBase64(xferbuf,
2119                                Buf->buf,
2120                                Buf->BufUsed);
2121         free(Buf->buf);
2122         Buf->buf = xferbuf;
2123         Buf->BufUsed = siz;
2124         return siz;
2125 }
2126
2127 /**
2128  * \brief decode a buffer from base 64 encoding; destroys original
2129  * \param Buf Buffor to transform
2130  */
2131 int StrBufDecodeHex(StrBuf *Buf)
2132 {
2133         unsigned int ch;
2134         char *pch, *pche, *pchi;
2135
2136         if (Buf == NULL) return -1;
2137
2138         pch = pchi = Buf->buf;
2139         pche = pch + Buf->BufUsed;
2140
2141         while (pchi < pche){
2142                 ch = decode_hex(pchi);
2143                 *pch = ch;
2144                 pch ++;
2145                 pchi += 2;
2146         }
2147
2148         *pch = '\0';
2149         Buf->BufUsed = pch - Buf->buf;
2150         return Buf->BufUsed;
2151 }
2152
2153 /**
2154  * \brief replace all chars >0x20 && < 0x7F with Mute
2155  * \param Mute char to put over invalid chars
2156  * \param Buf Buffor to transform
2157  */
2158 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2159 {
2160         unsigned char *pch;
2161
2162         if (Buf == NULL) return -1;
2163         pch = (unsigned char *)Buf->buf;
2164         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2165                 if ((*pch < 0x20) || (*pch > 0x7F))
2166                         *pch = Mute;
2167                 pch ++;
2168         }
2169         return Buf->BufUsed;
2170 }
2171
2172
2173 /**
2174  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
2175  * \param Buf Buffer to translate
2176  * \param StripBlanks Reduce several blanks to one?
2177  */
2178 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2179 {
2180         int a, b;
2181         char hex[3];
2182         long len;
2183
2184         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2185                 Buf->buf[Buf->BufUsed - 1] = '\0';
2186                 Buf->BufUsed --;
2187         }
2188
2189         a = 0; 
2190         while (a < Buf->BufUsed) {
2191                 if (Buf->buf[a] == '+')
2192                         Buf->buf[a] = ' ';
2193                 else if (Buf->buf[a] == '%') {
2194                         /* don't let % chars through, rather truncate the input. */
2195                         if (a + 2 > Buf->BufUsed) {
2196                                 Buf->buf[a] = '\0';
2197                                 Buf->BufUsed = a;
2198                         }
2199                         else {                  
2200                                 hex[0] = Buf->buf[a + 1];
2201                                 hex[1] = Buf->buf[a + 2];
2202                                 hex[2] = 0;
2203                                 b = 0;
2204                                 sscanf(hex, "%02x", &b);
2205                                 Buf->buf[a] = (char) b;
2206                                 len = Buf->BufUsed - a - 2;
2207                                 if (len > 0)
2208                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2209                         
2210                                 Buf->BufUsed -=2;
2211                         }
2212                 }
2213                 a++;
2214         }
2215         return a;
2216 }
2217
2218
2219 /**
2220  * \brief       RFC2047-encode a header field if necessary.
2221  *              If no non-ASCII characters are found, the string
2222  *              will be copied verbatim without encoding.
2223  *
2224  * \param       target          Target buffer.
2225  * \param       source          Source string to be encoded.
2226  * \returns     encoded length; -1 if non success.
2227  */
2228 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2229 {
2230         const char headerStr[] = "=?UTF-8?Q?";
2231         int need_to_encode = 0;
2232         int i = 0;
2233         unsigned char ch;
2234
2235         if ((source == NULL) || 
2236             (target == NULL))
2237             return -1;
2238
2239         while ((i < source->BufUsed) &&
2240                (!IsEmptyStr (&source->buf[i])) &&
2241                (need_to_encode == 0)) {
2242                 if (((unsigned char) source->buf[i] < 32) || 
2243                     ((unsigned char) source->buf[i] > 126)) {
2244                         need_to_encode = 1;
2245                 }
2246                 i++;
2247         }
2248
2249         if (!need_to_encode) {
2250                 if (*target == NULL) {
2251                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2252                 }
2253                 else {
2254                         FlushStrBuf(*target);
2255                         StrBufAppendBuf(*target, source, 0);
2256                 }
2257                 return (*target)->BufUsed;
2258         }
2259         if (*target == NULL)
2260                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2261         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2262                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2263         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2264         (*target)->BufUsed = sizeof(headerStr) - 1;
2265         for (i=0; (i < source->BufUsed); ++i) {
2266                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2267                         IncreaseBuf(*target, 1, 0);
2268                 ch = (unsigned char) source->buf[i];
2269                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2270                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2271                         (*target)->BufUsed += 3;
2272                 }
2273                 else {
2274                         (*target)->buf[(*target)->BufUsed] = ch;
2275                         (*target)->BufUsed++;
2276                 }
2277         }
2278         
2279         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2280                 IncreaseBuf(*target, 1, 0);
2281
2282         (*target)->buf[(*target)->BufUsed++] = '?';
2283         (*target)->buf[(*target)->BufUsed++] = '=';
2284         (*target)->buf[(*target)->BufUsed] = '\0';
2285         return (*target)->BufUsed;;
2286 }
2287
2288 /**
2289  * \brief replaces all occurances of 'search' by 'replace'
2290  * \param buf Buffer to modify
2291  * \param search character to search
2292  * \param relpace character to replace search by
2293  */
2294 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2295 {
2296         long i;
2297         if (buf == NULL)
2298                 return;
2299         for (i=0; i<buf->BufUsed; i++)
2300                 if (buf->buf[i] == search)
2301                         buf->buf[i] = replace;
2302
2303 }
2304
2305
2306
2307 /*
2308  * Wrapper around iconv_open()
2309  * Our version adds aliases for non-standard Microsoft charsets
2310  * such as 'MS950', aliasing them to names like 'CP950'
2311  *
2312  * tocode       Target encoding
2313  * fromcode     Source encoding
2314  */
2315 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2316 {
2317 #ifdef HAVE_ICONV
2318         iconv_t ic = (iconv_t)(-1) ;
2319         ic = iconv_open(tocode, fromcode);
2320         if (ic == (iconv_t)(-1) ) {
2321                 char alias_fromcode[64];
2322                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2323                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2324                         alias_fromcode[0] = 'C';
2325                         alias_fromcode[1] = 'P';
2326                         ic = iconv_open(tocode, alias_fromcode);
2327                 }
2328         }
2329         *(iconv_t *)pic = ic;
2330 #endif
2331 }
2332
2333
2334
2335 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2336 {
2337         char * end;
2338         /* Find the next ?Q? */
2339         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2340                 return NULL;
2341
2342         end = strchr(bptr + 2, '?');
2343
2344         if (end == NULL)
2345                 return NULL;
2346
2347         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2348             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
2349             (*(end + 2) == '?')) {
2350                 /* skip on to the end of the cluster, the next ?= */
2351                 end = strstr(end + 3, "?=");
2352         }
2353         else
2354                 /* sort of half valid encoding, try to find an end. */
2355                 end = strstr(bptr, "?=");
2356         return end;
2357 }
2358
2359
2360 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2361 {
2362 #ifdef HAVE_ICONV
2363         int BufSize;
2364         iconv_t ic;
2365         char *ibuf;                     /**< Buffer of characters to be converted */
2366         char *obuf;                     /**< Buffer for converted characters */
2367         size_t ibuflen;                 /**< Length of input buffer */
2368         size_t obuflen;                 /**< Length of output buffer */
2369
2370
2371         if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2372                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2373
2374         ic = *(iconv_t*)pic;
2375         ibuf = ConvertBuf->buf;
2376         ibuflen = ConvertBuf->BufUsed;
2377         obuf = TmpBuf->buf;
2378         obuflen = TmpBuf->BufSize;
2379         
2380         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2381
2382         /* little card game: wheres the red lady? */
2383         ibuf = ConvertBuf->buf;
2384         BufSize = ConvertBuf->BufSize;
2385
2386         ConvertBuf->buf = TmpBuf->buf;
2387         ConvertBuf->BufSize = TmpBuf->BufSize;
2388         ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2389         ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2390         
2391         TmpBuf->buf = ibuf;
2392         TmpBuf->BufSize = BufSize;
2393         TmpBuf->BufUsed = 0;
2394         TmpBuf->buf[0] = '\0';
2395 #endif
2396 }
2397
2398
2399
2400
2401 inline static void DecodeSegment(StrBuf *Target, 
2402                                  const StrBuf *DecodeMe, 
2403                                  char *SegmentStart, 
2404                                  char *SegmentEnd, 
2405                                  StrBuf *ConvertBuf,
2406                                  StrBuf *ConvertBuf2, 
2407                                  StrBuf *FoundCharset)
2408 {
2409         StrBuf StaticBuf;
2410         char charset[128];
2411         char encoding[16];
2412 #ifdef HAVE_ICONV
2413         iconv_t ic = (iconv_t)(-1);
2414 #endif
2415         /* Now we handle foreign character sets properly encoded
2416          * in RFC2047 format.
2417          */
2418         StaticBuf.buf = SegmentStart;
2419         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2420         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2421         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2422         if (FoundCharset != NULL) {
2423                 FlushStrBuf(FoundCharset);
2424                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2425         }
2426         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2427         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2428         
2429         *encoding = toupper(*encoding);
2430         if (*encoding == 'B') { /**< base64 */
2431                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
2432                                                         ConvertBuf->buf, 
2433                                                         ConvertBuf->BufUsed);
2434         }
2435         else if (*encoding == 'Q') {    /**< quoted-printable */
2436                 long pos;
2437                 
2438                 pos = 0;
2439                 while (pos < ConvertBuf->BufUsed)
2440                 {
2441                         if (ConvertBuf->buf[pos] == '_') 
2442                                 ConvertBuf->buf[pos] = ' ';
2443                         pos++;
2444                 }
2445                 
2446                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2447                         ConvertBuf2->buf, 
2448                         ConvertBuf->buf,
2449                         ConvertBuf->BufUsed);
2450         }
2451         else {
2452                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2453         }
2454 #ifdef HAVE_ICONV
2455         ctdl_iconv_open("UTF-8", charset, &ic);
2456         if (ic != (iconv_t)(-1) ) {             
2457 #endif
2458                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2459                 StrBufAppendBuf(Target, ConvertBuf2, 0);
2460 #ifdef HAVE_ICONV
2461                 iconv_close(ic);
2462         }
2463         else {
2464                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2465         }
2466 #endif
2467 }
2468 /*
2469  * Handle subjects with RFC2047 encoding such as:
2470  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2471  */
2472 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2473 {
2474         StrBuf *ConvertBuf, *ConvertBuf2;
2475         char *start, *end, *next, *nextend, *ptr = NULL;
2476 #ifdef HAVE_ICONV
2477         iconv_t ic = (iconv_t)(-1) ;
2478 #endif
2479         const char *eptr;
2480         int passes = 0;
2481         int i, len, delta;
2482         int illegal_non_rfc2047_encoding = 0;
2483
2484         /* Sometimes, badly formed messages contain strings which were simply
2485          *  written out directly in some foreign character set instead of
2486          *  using RFC2047 encoding.  This is illegal but we will attempt to
2487          *  handle it anyway by converting from a user-specified default
2488          *  charset to UTF-8 if we see any nonprintable characters.
2489          */
2490         
2491         len = StrLength(DecodeMe);
2492         for (i=0; i<DecodeMe->BufUsed; ++i) {
2493                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2494                         illegal_non_rfc2047_encoding = 1;
2495                         break;
2496                 }
2497         }
2498
2499         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2500         if ((illegal_non_rfc2047_encoding) &&
2501             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
2502             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2503         {
2504 #ifdef HAVE_ICONV
2505                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2506                 if (ic != (iconv_t)(-1) ) {
2507                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2508                         iconv_close(ic);
2509                 }
2510 #endif
2511         }
2512
2513         /* pre evaluate the first pair */
2514         nextend = end = NULL;
2515         len = StrLength(DecodeMe);
2516         start = strstr(DecodeMe->buf, "=?");
2517         eptr = DecodeMe->buf + DecodeMe->BufUsed;
2518         if (start != NULL) 
2519                 end = FindNextEnd (DecodeMe, start);
2520         else {
2521                 StrBufAppendBuf(Target, DecodeMe, 0);
2522                 FreeStrBuf(&ConvertBuf);
2523                 return;
2524         }
2525
2526         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2527
2528         if (start != DecodeMe->buf)
2529                 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2530         /*
2531          * Since spammers will go to all sorts of absurd lengths to get their
2532          * messages through, there are LOTS of corrupt headers out there.
2533          * So, prevent a really badly formed RFC2047 header from throwing
2534          * this function into an infinite loop.
2535          */
2536         while ((start != NULL) && 
2537                (end != NULL) && 
2538                (start < eptr) && 
2539                (end < eptr) && 
2540                (passes < 20))
2541         {
2542                 passes++;
2543                 DecodeSegment(Target, 
2544                               DecodeMe, 
2545                               start, 
2546                               end, 
2547                               ConvertBuf,
2548                               ConvertBuf2,
2549                               FoundCharset);
2550                 
2551                 next = strstr(end, "=?");
2552                 nextend = NULL;
2553                 if ((next != NULL) && 
2554                     (next < eptr))
2555                         nextend = FindNextEnd(DecodeMe, next);
2556                 if (nextend == NULL)
2557                         next = NULL;
2558
2559                 /* did we find two partitions */
2560                 if ((next != NULL) && 
2561                     ((next - end) > 2))
2562                 {
2563                         ptr = end + 2;
2564                         while ((ptr < next) && 
2565                                (isspace(*ptr) ||
2566                                 (*ptr == '\r') ||
2567                                 (*ptr == '\n') || 
2568                                 (*ptr == '\t')))
2569                                 ptr ++;
2570                         /* did we find a gab just filled with blanks? */
2571                         if (ptr == next)
2572                         {
2573                                 memmove (end + 2,
2574                                          next,
2575                                          len - (next - start));
2576                                 
2577                                 /* now terminate the gab at the end */
2578                                 delta = (next - end) - 2; ////TODO: const! 
2579                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2580                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2581
2582                                 /* move next to its new location. */
2583                                 next -= delta;
2584                                 nextend -= delta;
2585                         }
2586                 }
2587                 /* our next-pair is our new first pair now. */
2588                 ptr = end + 2;
2589                 start = next;
2590                 end = nextend;
2591         }
2592         end = ptr;
2593         nextend = DecodeMe->buf + DecodeMe->BufUsed;
2594         if ((end != NULL) && (end < nextend)) {
2595                 ptr = end;
2596                 while ( (ptr < nextend) &&
2597                         (isspace(*ptr) ||
2598                          (*ptr == '\r') ||
2599                          (*ptr == '\n') || 
2600                          (*ptr == '\t')))
2601                         ptr ++;
2602                 if (ptr < nextend)
2603                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
2604         }
2605         FreeStrBuf(&ConvertBuf);
2606         FreeStrBuf(&ConvertBuf2);
2607 }
2608
2609
2610
2611 long StrBuf_Utf8StrLen(StrBuf *Buf)
2612 {
2613         return Ctdl_Utf8StrLen(Buf->buf);
2614 }
2615
2616 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2617 {
2618         char *CutAt;
2619
2620         CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2621         if (CutAt != NULL) {
2622                 Buf->BufUsed = CutAt - Buf->buf;
2623                 Buf->buf[Buf->BufUsed] = '\0';
2624         }
2625         return Buf->BufUsed;    
2626 }
2627
2628
2629
2630 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2631 {
2632         const char *aptr, *ptr, *eptr;
2633         char *optr, *xptr;
2634
2635         if (Buf == NULL)
2636                 return 0;
2637
2638         if (*Ptr==NULL)
2639                 ptr = aptr = Buf->buf;
2640         else
2641                 ptr = aptr = *Ptr;
2642
2643         optr = LineBuf->buf;
2644         eptr = Buf->buf + Buf->BufUsed;
2645         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2646
2647         while ((*ptr != '\n') &&
2648                (*ptr != '\r') &&
2649                (ptr < eptr))
2650         {
2651                 *optr = *ptr;
2652                 optr++; ptr++;
2653                 if (optr == xptr) {
2654                         LineBuf->BufUsed = optr - LineBuf->buf;
2655                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
2656                         optr = LineBuf->buf + LineBuf->BufUsed;
2657                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
2658                 }
2659         }
2660         LineBuf->BufUsed = optr - LineBuf->buf;
2661         *optr = '\0';       
2662         if (*ptr == '\r')
2663                 ptr ++;
2664         if (*ptr == '\n')
2665                 ptr ++;
2666
2667         *Ptr = ptr;
2668
2669         return Buf->BufUsed - (ptr - Buf->buf);
2670 }