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