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