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