* don't use sprintf while doing urlescappend; do it in place.
[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 #ifdef 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 const char *StrBufNOTNULL = ((char*) NULL) - 1;
31
32 /**
33  * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
34  * StrBuf is a versatile class, aiding the handling of dynamic strings
35  *  * reduce de/reallocations
36  *  * reduce the need to remeasure it
37  *  * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
38  *  * allow asyncroneous IO for line and Blob based operations
39  *  * reduce the use of memove in those
40  *  * Quick filling in several operations with append functions
41  */
42
43 /**
44  * @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
45  * @ingroup StrBuf
46  */
47
48 /**
49  * @defgroup StrBuf_Cast Cast operators to interact with char* based code
50  * @ingroup StrBuf
51  * use these operators to interfere with code demanding char*; 
52  * if you need to own the content, smash me. Avoid, since we loose the length information.
53  */
54
55 /**
56  * @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
57  * @ingroup StrBuf
58  * operations to get your Strings into a StrBuf, manipulating them, or appending
59  */
60 /**
61  * @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence 
62  * @ingroup StrBuf
63  * Quick tokenizer; demands of the user to pull its tokens in sequence
64  */
65
66 /**
67  * @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
68  * @ingroup StrBuf
69  * versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
70  */
71
72 /**
73  * @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
74  * @ingroup StrBuf
75  * File IO to fill StrBufs; Works with work-buffer shared across several calls;
76  * External Cursor to maintain the current read position inside of the buffer
77  * the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower) 
78  */
79
80 /**
81  * @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
82  * @ingroup StrBuf
83  * Slow I/O; avoid.
84  */
85
86 /**
87  * @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
88  * @ingroup StrBuf
89  * these functions translate the content of a buffer into another representation;
90  * some are combined Fillers and encoders
91  */
92
93 /**
94  * Private Structure for the Stringbuffer
95  */
96 struct StrBuf {
97         char *buf;         /**< the pointer to the dynamic buffer */
98         long BufSize;      /**< how many spcae do we optain */
99         long BufUsed;      /**< StNumber of Chars used excluding the trailing \\0 */
100         int ConstBuf;      /**< are we just a wrapper arround a static buffer and musn't we be changed? */
101 #ifdef SIZE_DEBUG
102         long nIncreases;   /**< for profiling; cound how many times we needed more */
103         char bt [SIZ];     /**< Stacktrace of last increase */
104         char bt_lastinc [SIZ]; /**< How much did we increase last time? */
105 #endif
106 };
107
108
109 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
110 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
111
112 #ifdef SIZE_DEBUG
113 #ifdef HAVE_BACKTRACE
114 static void StrBufBacktrace(StrBuf *Buf, int which)
115 {
116         int n;
117         char *pstart, *pch;
118         void *stack_frames[50];
119         size_t size, i;
120         char **strings;
121
122         if (which)
123                 pstart = pch = Buf->bt;
124         else
125                 pstart = pch = Buf->bt_lastinc;
126         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
127         strings = backtrace_symbols(stack_frames, size);
128         for (i = 0; i < size; i++) {
129                 if (strings != NULL)
130                         n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
131                 else
132                         n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
133                 pch += n;
134         }
135         free(strings);
136
137
138 }
139 #endif
140 #endif
141
142 /** 
143  * @ingroup StrBuf_Cast
144  * @brief Cast operator to Plain String 
145  * @note if the buffer is altered by StrBuf operations, this pointer may become 
146  *  invalid. So don't lean on it after altering the buffer!
147  *  Since this operation is considered cheap, rather call it often than risking
148  *  your pointer to become invalid!
149  * @param Str the string we want to get the c-string representation for
150  * @returns the Pointer to the Content. Don't mess with it!
151  */
152 inline const char *ChrPtr(const StrBuf *Str)
153 {
154         if (Str == NULL)
155                 return "";
156         return Str->buf;
157 }
158
159 /**
160  * @ingroup StrBuf_Cast
161  * @brief since we know strlen()'s result, provide it here.
162  * @param Str the string to return the length to
163  * @returns contentlength of the buffer
164  */
165 inline int StrLength(const StrBuf *Str)
166 {
167         return (Str != NULL) ? Str->BufUsed : 0;
168 }
169
170 /**
171  * @ingroup StrBuf_DeConstructors
172  * @brief local utility function to resize the buffer
173  * @param Buf the buffer whichs storage we should increase
174  * @param KeepOriginal should we copy the original buffer or just start over with a new one
175  * @param DestSize what should fit in after?
176  */
177 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
178 {
179         char *NewBuf;
180         size_t NewSize = Buf->BufSize * 2;
181
182         if (Buf->ConstBuf)
183                 return -1;
184                 
185         if (DestSize > 0)
186                 while (NewSize <= DestSize)
187                         NewSize *= 2;
188
189         NewBuf= (char*) malloc(NewSize);
190         if (NewBuf == NULL)
191                 return -1;
192
193         if (KeepOriginal && (Buf->BufUsed > 0))
194         {
195                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
196         }
197         else
198         {
199                 NewBuf[0] = '\0';
200                 Buf->BufUsed = 0;
201         }
202         free (Buf->buf);
203         Buf->buf = NewBuf;
204         Buf->BufSize = NewSize;
205 #ifdef SIZE_DEBUG
206         Buf->nIncreases++;
207 #ifdef HAVE_BACKTRACE
208         StrBufBacktrace(Buf, 1);
209 #endif
210 #endif
211         return Buf->BufSize;
212 }
213
214 /**
215  * @ingroup StrBuf_DeConstructors
216  * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
217  * @param Buf Buffer to shrink (has to be empty)
218  * @param ThreshHold if the buffer is bigger then this, its readjusted
219  * @param NewSize if we Shrink it, how big are we going to be afterwards?
220  */
221 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
222 {
223         if (Buf->BufUsed > ThreshHold) {
224                 free(Buf->buf);
225                 Buf->buf = (char*) malloc(NewSize);
226                 Buf->BufUsed = 0;
227                 Buf->BufSize = NewSize;
228         }
229 }
230
231 /**
232  * @ingroup StrBuf_DeConstructors
233  * @brief shrink long term buffers to their real size so they don't waste memory
234  * @param Buf buffer to shrink
235  * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
236  * @returns physical size of the buffer
237  */
238 long StrBufShrinkToFit(StrBuf *Buf, int Force)
239 {
240         if (Force || 
241             (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
242         {
243                 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
244                 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
245                 Buf->BufSize = Buf->BufUsed + 1;
246                 free(Buf->buf);
247                 Buf->buf = TmpBuf;
248         }
249         return Buf->BufUsed;
250 }
251
252 /**
253  * @ingroup StrBuf_DeConstructors
254  * @brief Allocate a new buffer with default buffer size
255  * @returns the new stringbuffer
256  */
257 StrBuf* NewStrBuf(void)
258 {
259         StrBuf *NewBuf;
260
261         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
262         NewBuf->buf = (char*) malloc(BaseStrBufSize);
263         NewBuf->buf[0] = '\0';
264         NewBuf->BufSize = BaseStrBufSize;
265         NewBuf->BufUsed = 0;
266         NewBuf->ConstBuf = 0;
267 #ifdef SIZE_DEBUG
268         NewBuf->nIncreases = 0;
269         NewBuf->bt[0] = '\0';
270         NewBuf->bt_lastinc[0] = '\0';
271 #ifdef HAVE_BACKTRACE
272         StrBufBacktrace(NewBuf, 0);
273 #endif
274 #endif
275         return NewBuf;
276 }
277
278 /** 
279  * @ingroup StrBuf_DeConstructors
280  * @brief Copy Constructor; returns a duplicate of CopyMe
281  * @param CopyMe Buffer to faxmilate
282  * @returns the new stringbuffer
283  */
284 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
285 {
286         StrBuf *NewBuf;
287         
288         if (CopyMe == NULL)
289                 return NewStrBuf();
290
291         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
292         NewBuf->buf = (char*) malloc(CopyMe->BufSize);
293         memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
294         NewBuf->BufUsed = CopyMe->BufUsed;
295         NewBuf->BufSize = CopyMe->BufSize;
296         NewBuf->ConstBuf = 0;
297 #ifdef SIZE_DEBUG
298         NewBuf->nIncreases = 0;
299         NewBuf->bt[0] = '\0';
300         NewBuf->bt_lastinc[0] = '\0';
301 #ifdef HAVE_BACKTRACE
302         StrBufBacktrace(NewBuf, 0);
303 #endif
304 #endif
305         return NewBuf;
306 }
307
308 /**
309  * @ingroup StrBuf_DeConstructors
310  * @brief create a new Buffer using an existing c-string
311  * this function should also be used if you want to pre-suggest
312  * the buffer size to allocate in conjunction with ptr == NULL
313  * @param ptr the c-string to copy; may be NULL to create a blank instance
314  * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
315  * @returns the new stringbuffer
316  */
317 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
318 {
319         StrBuf *NewBuf;
320         size_t Siz = BaseStrBufSize;
321         size_t CopySize;
322
323         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
324         if (nChars < 0)
325                 CopySize = strlen((ptr != NULL)?ptr:"");
326         else
327                 CopySize = nChars;
328
329         while (Siz <= CopySize)
330                 Siz *= 2;
331
332         NewBuf->buf = (char*) malloc(Siz);
333         NewBuf->BufSize = Siz;
334         if (ptr != NULL) {
335                 memcpy(NewBuf->buf, ptr, CopySize);
336                 NewBuf->buf[CopySize] = '\0';
337                 NewBuf->BufUsed = CopySize;
338         }
339         else {
340                 NewBuf->buf[0] = '\0';
341                 NewBuf->BufUsed = 0;
342         }
343         NewBuf->ConstBuf = 0;
344 #ifdef SIZE_DEBUG
345         NewBuf->nIncreases = 0;
346         NewBuf->bt[0] = '\0';
347         NewBuf->bt_lastinc[0] = '\0';
348 #ifdef HAVE_BACKTRACE
349         StrBufBacktrace(NewBuf, 0);
350 #endif
351 #endif
352         return NewBuf;
353 }
354
355 /**
356  * @ingroup StrBuf_DeConstructors
357  * @brief Set an existing buffer from a c-string
358  * @param Buf buffer to load
359  * @param ptr c-string to put into 
360  * @param nChars set to -1 if we should work 0-terminated
361  * @returns the new length of the string
362  */
363 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
364 {
365         size_t Siz = Buf->BufSize;
366         size_t CopySize;
367
368         if (nChars < 0)
369                 CopySize = strlen(ptr);
370         else
371                 CopySize = nChars;
372
373         while (Siz <= CopySize)
374                 Siz *= 2;
375
376         if (Siz != Buf->BufSize)
377                 IncreaseBuf(Buf, 0, Siz);
378         memcpy(Buf->buf, ptr, CopySize);
379         Buf->buf[CopySize] = '\0';
380         Buf->BufUsed = CopySize;
381         Buf->ConstBuf = 0;
382         return CopySize;
383 }
384
385
386 /**
387  * @ingroup StrBuf_DeConstructors
388  * @brief use strbuf as wrapper for a string constant for easy handling
389  * @param StringConstant a string to wrap
390  * @param SizeOfStrConstant should be sizeof(StringConstant)-1
391  */
392 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
393 {
394         StrBuf *NewBuf;
395
396         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
397         NewBuf->buf = (char*) StringConstant;
398         NewBuf->BufSize = SizeOfStrConstant;
399         NewBuf->BufUsed = SizeOfStrConstant;
400         NewBuf->ConstBuf = 1;
401 #ifdef SIZE_DEBUG
402         NewBuf->nIncreases = 0;
403         NewBuf->bt[0] = '\0';
404         NewBuf->bt_lastinc[0] = '\0';
405 #endif
406         return NewBuf;
407 }
408
409
410 /**
411  * @ingroup StrBuf_DeConstructors
412  * @brief flush the content of a Buf; keep its struct
413  * @param buf Buffer to flush
414  */
415 int FlushStrBuf(StrBuf *buf)
416 {
417         if (buf == NULL)
418                 return -1;
419         if (buf->ConstBuf)
420                 return -1;       
421         buf->buf[0] ='\0';
422         buf->BufUsed = 0;
423         return 0;
424 }
425
426 /**
427  * @ingroup StrBuf_DeConstructors
428  * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
429  * @param buf Buffer to wipe
430  */
431 int FLUSHStrBuf(StrBuf *buf)
432 {
433         if (buf == NULL)
434                 return -1;
435         if (buf->ConstBuf)
436                 return -1;
437         if (buf->BufUsed > 0) {
438                 memset(buf->buf, 0, buf->BufUsed);
439                 buf->BufUsed = 0;
440         }
441         return 0;
442 }
443
444 #ifdef SIZE_DEBUG
445 int hFreeDbglog = -1;
446 #endif
447 /**
448  * @ingroup StrBuf_DeConstructors
449  * @brief Release a Buffer
450  * Its a double pointer, so it can NULL your pointer
451  * so fancy SIG11 appear instead of random results
452  * @param FreeMe Pointer Pointer to the buffer to free
453  */
454 void FreeStrBuf (StrBuf **FreeMe)
455 {
456         if (*FreeMe == NULL)
457                 return;
458 #ifdef SIZE_DEBUG
459         if (hFreeDbglog == -1){
460                 pid_t pid = getpid();
461                 char path [SIZ];
462                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
463                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
464         }
465         if ((*FreeMe)->nIncreases > 0)
466         {
467                 char buf[SIZ * 3];
468                 long n;
469                 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
470                              (*FreeMe)->nIncreases,
471                              (*FreeMe)->BufUsed,
472                              (*FreeMe)->BufSize,
473                              (*FreeMe)->bt,
474                              (*FreeMe)->bt_lastinc);
475                 n = write(hFreeDbglog, buf, n);
476         }
477         else
478         {
479                 char buf[128];
480                 long n;
481                 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
482                              (*FreeMe)->BufUsed,
483                              (*FreeMe)->BufSize);
484                 n = write(hFreeDbglog, buf, n);
485         }
486 #endif
487         if (!(*FreeMe)->ConstBuf) 
488                 free((*FreeMe)->buf);
489         free(*FreeMe);
490         *FreeMe = NULL;
491 }
492
493 /**
494  * @ingroup StrBuf_DeConstructors
495  * @brief flatten a Buffer to the Char * we return 
496  * Its a double pointer, so it can NULL your pointer
497  * so fancy SIG11 appear instead of random results
498  * The Callee then owns the buffer and is responsible for freeing it.
499  * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
500  * @returns the pointer of the buffer; Callee owns the memory thereafter.
501  */
502 char *SmashStrBuf (StrBuf **SmashMe)
503 {
504         char *Ret;
505
506         if (*SmashMe == NULL)
507                 return NULL;
508 #ifdef SIZE_DEBUG
509         if (hFreeDbglog == -1){
510                 pid_t pid = getpid();
511                 char path [SIZ];
512                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
513                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
514         }
515         if ((*SmashMe)->nIncreases > 0)
516         {
517                 char buf[SIZ * 3];
518                 long n;
519                 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
520                              (*SmashMe)->nIncreases,
521                              (*SmashMe)->BufUsed,
522                              (*SmashMe)->BufSize,
523                              (*SmashMe)->bt,
524                              (*SmashMe)->bt_lastinc);
525                 n = write(hFreeDbglog, buf, n);
526         }
527         else
528         {
529                 char buf[128];
530                 long n;
531                 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
532                              (*SmashMe)->BufUsed,
533                              (*SmashMe)->BufSize);
534                 n = write(hFreeDbglog, buf, n);
535         }
536 #endif
537         Ret = (*SmashMe)->buf;
538         free(*SmashMe);
539         *SmashMe = NULL;
540         return Ret;
541 }
542
543 /**
544  * @ingroup StrBuf_DeConstructors
545  * @brief Release the buffer
546  * If you want put your StrBuf into a Hash, use this as Destructor.
547  * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
548  */
549 void HFreeStrBuf (void *VFreeMe)
550 {
551         StrBuf *FreeMe = (StrBuf*)VFreeMe;
552         if (FreeMe == NULL)
553                 return;
554 #ifdef SIZE_DEBUG
555         if (hFreeDbglog == -1){
556                 pid_t pid = getpid();
557                 char path [SIZ];
558                 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
559                 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
560         }
561         if (FreeMe->nIncreases > 0)
562         {
563                 char buf[SIZ * 3];
564                 long n;
565                 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
566                              FreeMe->nIncreases,
567                              FreeMe->BufUsed,
568                              FreeMe->BufSize,
569                              FreeMe->bt,
570                              FreeMe->bt_lastinc);
571                 write(hFreeDbglog, buf, n);
572         }
573         else
574         {
575                 char buf[128];
576                 long n;
577                 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
578                              FreeMe->nIncreases,
579                              FreeMe->BufUsed,
580                              FreeMe->BufSize);
581         }
582 #endif
583         if (!FreeMe->ConstBuf) 
584                 free(FreeMe->buf);
585         free(FreeMe);
586 }
587
588 /**
589  * @ingroup StrBuf
590  * @brief Wrapper around atol
591  */
592 long StrTol(const StrBuf *Buf)
593 {
594         if (Buf == NULL)
595                 return 0;
596         if(Buf->BufUsed > 0)
597                 return atol(Buf->buf);
598         else
599                 return 0;
600 }
601
602 /**
603  * @ingroup StrBuf
604  * @brief Wrapper around atoi
605  */
606 int StrToi(const StrBuf *Buf)
607 {
608         if (Buf == NULL)
609                 return 0;
610         if (Buf->BufUsed > 0)
611                 return atoi(Buf->buf);
612         else
613                 return 0;
614 }
615
616 /**
617  * @ingroup StrBuf
618  * @brief Checks to see if the string is a pure number 
619  */
620 int StrBufIsNumber(const StrBuf *Buf) {
621   char * pEnd;
622   if (Buf == NULL) {
623         return 0;
624   }
625   strtoll(Buf->buf, &pEnd, 10);
626   if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
627     return 1;
628   }
629   return 0;
630
631 /**
632  * @ingroup StrBuf
633  * @brief modifies a Single char of the Buf
634  * You can point to it via char* or a zero-based integer
635  * @param Buf The buffer to manipulate
636  * @param ptr char* to zero; use NULL if unused
637  * @param nThChar zero based pointer into the string; use -1 if unused
638  * @param PeekValue The Character to place into the position
639  */
640 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
641 {
642         if (Buf == NULL)
643                 return -1;
644         if (ptr != NULL)
645                 nThChar = ptr - Buf->buf;
646         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
647                 return -1;
648         Buf->buf[nThChar] = PeekValue;
649         return nThChar;
650 }
651
652 /**
653  * @ingroup StrBuf
654  * @brief Append a StringBuffer to the buffer
655  * @param Buf Buffer to modify
656  * @param AppendBuf Buffer to copy at the end of our buffer
657  * @param Offset Should we start copying from an offset?
658  */
659 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
660 {
661         if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
662                 return;
663
664         if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
665                 IncreaseBuf(Buf, 
666                             (Buf->BufUsed > 0), 
667                             AppendBuf->BufUsed + Buf->BufUsed);
668
669         memcpy(Buf->buf + Buf->BufUsed, 
670                AppendBuf->buf + Offset, 
671                AppendBuf->BufUsed - Offset);
672         Buf->BufUsed += AppendBuf->BufUsed - Offset;
673         Buf->buf[Buf->BufUsed] = '\0';
674 }
675
676
677 /**
678  * @ingroup StrBuf
679  * @brief Append a C-String to the buffer
680  * @param Buf Buffer to modify
681  * @param AppendBuf Buffer to copy at the end of our buffer
682  * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
683  * @param Offset Should we start copying from an offset?
684  */
685 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
686 {
687         long aps;
688         long BufSizeRequired;
689
690         if ((AppendBuf == NULL) || (Buf == NULL))
691                 return;
692
693         if (AppendSize < 0 )
694                 aps = strlen(AppendBuf + Offset);
695         else
696                 aps = AppendSize - Offset;
697
698         BufSizeRequired = Buf->BufUsed + aps + 1;
699         if (Buf->BufSize <= BufSizeRequired)
700                 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
701
702         memcpy(Buf->buf + Buf->BufUsed, 
703                AppendBuf + Offset, 
704                aps);
705         Buf->BufUsed += aps;
706         Buf->buf[Buf->BufUsed] = '\0';
707 }
708
709 /**
710  * @ingroup StrBuf
711  * @brief Callback for cURL to append the webserver reply to a buffer
712  * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
713  * @param size pre-defined by the cURL API; see man 3 curl for mre info
714  * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
715  * @param stream pre-defined by the cURL API; see man 3 curl for mre info
716  */
717 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
718 {
719
720         StrBuf *Target;
721
722         Target = stream;
723         if (ptr == NULL)
724                 return 0;
725
726         StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
727         return size * nmemb;
728 }
729
730
731 /** 
732  * @ingroup StrBuf_DeEnCoder
733  * @brief Escape a string for feeding out as a URL while appending it to a Buffer
734  * @param OutBuf the output buffer
735  * @param In Buffer to encode
736  * @param PlainIn way in from plain old c strings
737  */
738 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
739 {
740         const char *pch, *pche;
741         char *pt, *pte;
742         int b, c, len;
743         const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
744         int eclen = sizeof(ec) -1;
745
746         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
747                 return;
748         if (PlainIn != NULL) {
749                 len = strlen(PlainIn);
750                 pch = PlainIn;
751                 pche = pch + len;
752         }
753         else {
754                 pch = In->buf;
755                 pche = pch + In->BufUsed;
756                 len = In->BufUsed;
757         }
758
759         if (len == 0) 
760                 return;
761
762         pt = OutBuf->buf + OutBuf->BufUsed;
763         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
764
765         while (pch < pche) {
766                 if (pt >= pte) {
767                         IncreaseBuf(OutBuf, 1, -1);
768                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
769                         pt = OutBuf->buf + OutBuf->BufUsed;
770                 }
771                 
772                 c = 0;
773                 for (b = 0; b < eclen; ++b) {
774                         if (*pch == ec[b]) {
775                                 c = 1;
776                                 b += eclen;
777                         }
778                 }
779                 if (c == 1) {
780                         char ch;
781                         ch = *pch;
782                         *pt = '%';
783                         *(pt + 1) =  ((ch & 0xF0) > 0x90) ?
784                                 ('A' + ((ch & 0xF0) >> 4) - 0x0A) : 
785                                 ('0' + ((ch & 0xF0) >> 4)) ;
786                         *(pt + 2) =  ((ch & 0x0F) > 0x09) ?
787                                 ('A' + (ch & 0x0F) - 0x0A) : 
788                                 ('0' + (ch & 0x0F)) ;
789                         pt += 3;
790                         OutBuf->BufUsed += 3;
791                         pch ++;
792                 }
793                 else {
794                         *(pt++) = *(pch++);
795                         OutBuf->BufUsed++;
796                 }
797         }
798         *pt = '\0';
799 }
800
801 /**
802  * @ingroup StrBuf_DeEnCoder
803  * @brief Append a string, escaping characters which have meaning in HTML.  
804  *
805  * @param Target        target buffer
806  * @param Source        source buffer; set to NULL if you just have a C-String
807  * @param PlainIn       Plain-C string to append; set to NULL if unused
808  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
809  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
810  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
811  */
812 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
813 {
814         const char *aptr, *eiptr;
815         char *bptr, *eptr;
816         long len;
817
818         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
819                 return -1;
820
821         if (PlainIn != NULL) {
822                 aptr = PlainIn;
823                 len = strlen(PlainIn);
824                 eiptr = aptr + len;
825         }
826         else {
827                 aptr = Source->buf;
828                 eiptr = aptr + Source->BufUsed;
829                 len = Source->BufUsed;
830         }
831
832         if (len == 0) 
833                 return -1;
834
835         bptr = Target->buf + Target->BufUsed;
836         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
837
838         while (aptr < eiptr){
839                 if(bptr >= eptr) {
840                         IncreaseBuf(Target, 1, -1);
841                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
842                         bptr = Target->buf + Target->BufUsed;
843                 }
844                 if (*aptr == '<') {
845                         memcpy(bptr, "&lt;", 4);
846                         bptr += 4;
847                         Target->BufUsed += 4;
848                 }
849                 else if (*aptr == '>') {
850                         memcpy(bptr, "&gt;", 4);
851                         bptr += 4;
852                         Target->BufUsed += 4;
853                 }
854                 else if (*aptr == '&') {
855                         memcpy(bptr, "&amp;", 5);
856                         bptr += 5;
857                         Target->BufUsed += 5;
858                 }
859                 else if (*aptr == '"') {
860                         memcpy(bptr, "&quot;", 6);
861                         bptr += 6;
862                         Target->BufUsed += 6;
863                 }
864                 else if (*aptr == '\'') {
865                         memcpy(bptr, "&#39;", 5);
866                         bptr += 5;
867                         Target->BufUsed += 5;
868                 }
869                 else if (*aptr == LB) {
870                         *bptr = '<';
871                         bptr ++;
872                         Target->BufUsed ++;
873                 }
874                 else if (*aptr == RB) {
875                         *bptr = '>';
876                         bptr ++;
877                         Target->BufUsed ++;
878                 }
879                 else if (*aptr == QU) {
880                         *bptr ='"';
881                         bptr ++;
882                         Target->BufUsed ++;
883                 }
884                 else if ((*aptr == 32) && (nbsp == 1)) {
885                         memcpy(bptr, "&nbsp;", 6);
886                         bptr += 6;
887                         Target->BufUsed += 6;
888                 }
889                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
890                         *bptr='\0';     /* nothing */
891                 }
892                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
893                         memcpy(bptr, "&lt;br/&gt;", 11);
894                         bptr += 11;
895                         Target->BufUsed += 11;
896                 }
897
898
899                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
900                         *bptr='\0';     /* nothing */
901                 }
902                 else{
903                         *bptr = *aptr;
904                         bptr++;
905                         Target->BufUsed ++;
906                 }
907                 aptr ++;
908         }
909         *bptr = '\0';
910         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
911                 return -1;
912         return Target->BufUsed;
913 }
914
915 /**
916  * @ingroup StrBuf_DeEnCoder
917  * @brief Append a string, escaping characters which have meaning in HTML.  
918  * Converts linebreaks into blanks; escapes single quotes
919  * @param Target        target buffer
920  * @param Source        source buffer; set to NULL if you just have a C-String
921  * @param PlainIn       Plain-C string to append; set to NULL if unused
922  */
923 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
924 {
925         const char *aptr, *eiptr;
926         char *tptr, *eptr;
927         long len;
928
929         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
930                 return ;
931
932         if (PlainIn != NULL) {
933                 aptr = PlainIn;
934                 len = strlen(PlainIn);
935                 eiptr = aptr + len;
936         }
937         else {
938                 aptr = Source->buf;
939                 eiptr = aptr + Source->BufUsed;
940                 len = Source->BufUsed;
941         }
942
943         if (len == 0) 
944                 return;
945
946         eptr = Target->buf + Target->BufSize - 8; 
947         tptr = Target->buf + Target->BufUsed;
948         
949         while (aptr < eiptr){
950                 if(tptr >= eptr) {
951                         IncreaseBuf(Target, 1, -1);
952                         eptr = Target->buf + Target->BufSize - 8; 
953                         tptr = Target->buf + Target->BufUsed;
954                 }
955                
956                 if (*aptr == '\n') {
957                         *tptr = ' ';
958                         Target->BufUsed++;
959                 }
960                 else if (*aptr == '\r') {
961                         *tptr = ' ';
962                         Target->BufUsed++;
963                 }
964                 else if (*aptr == '\'') {
965                         *(tptr++) = '&';
966                         *(tptr++) = '#';
967                         *(tptr++) = '3';
968                         *(tptr++) = '9';
969                         *tptr = ';';
970                         Target->BufUsed += 5;
971                 } else {
972                         *tptr = *aptr;
973                         Target->BufUsed++;
974                 }
975                 tptr++; aptr++;
976         }
977         *tptr = '\0';
978 }
979
980
981
982 /**
983  * @ingroup StrBuf_DeEnCoder
984  * @brief Append a string, escaping characters which have meaning in ICAL.  
985  * [\n,] 
986  * @param Target        target buffer
987  * @param Source        source buffer; set to NULL if you just have a C-String
988  * @param PlainIn       Plain-C string to append; set to NULL if unused
989  */
990 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
991 {
992         const char *aptr, *eiptr;
993         char *tptr, *eptr;
994         long len;
995
996         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
997                 return ;
998
999         if (PlainIn != NULL) {
1000                 aptr = PlainIn;
1001                 len = strlen(PlainIn);
1002                 eiptr = aptr + len;
1003         }
1004         else {
1005                 aptr = Source->buf;
1006                 eiptr = aptr + Source->BufUsed;
1007                 len = Source->BufUsed;
1008         }
1009
1010         if (len == 0) 
1011                 return;
1012
1013         eptr = Target->buf + Target->BufSize - 8; 
1014         tptr = Target->buf + Target->BufUsed;
1015         
1016         while (aptr < eiptr){
1017                 if(tptr + 3 >= eptr) {
1018                         IncreaseBuf(Target, 1, -1);
1019                         eptr = Target->buf + Target->BufSize - 8; 
1020                         tptr = Target->buf + Target->BufUsed;
1021                 }
1022                
1023                 if (*aptr == '\n') {
1024                         *tptr = '\\';
1025                         Target->BufUsed++;
1026                         tptr++;
1027                         *tptr = 'n';
1028                         Target->BufUsed++;
1029                 }
1030                 else if (*aptr == '\r') {
1031                         *tptr = '\\';
1032                         Target->BufUsed++;
1033                         tptr++;
1034                         *tptr = 'r';
1035                         Target->BufUsed++;
1036                 }
1037                 else if (*aptr == ',') {
1038                         *tptr = '\\';
1039                         Target->BufUsed++;
1040                         tptr++;
1041                         *tptr = ',';
1042                         Target->BufUsed++;
1043                 } else {
1044                         *tptr = *aptr;
1045                         Target->BufUsed++;
1046                 }
1047                 tptr++; aptr++;
1048         }
1049         *tptr = '\0';
1050 }
1051
1052 /**
1053  * @ingroup StrBuf_DeEnCoder
1054  * @brief Append a string, escaping characters which have meaning in JavaScript strings .  
1055  *
1056  * @param Target        target buffer
1057  * @param Source        source buffer; set to NULL if you just have a C-String
1058  * @param PlainIn       Plain-C string to append; set to NULL if unused
1059  * @returns size of result or -1
1060  */
1061 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1062 {
1063         const char *aptr, *eiptr;
1064         char *bptr, *eptr;
1065         long len;
1066
1067         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1068                 return -1;
1069
1070         if (PlainIn != NULL) {
1071                 aptr = PlainIn;
1072                 len = strlen(PlainIn);
1073                 eiptr = aptr + len;
1074         }
1075         else {
1076                 aptr = Source->buf;
1077                 eiptr = aptr + Source->BufUsed;
1078                 len = Source->BufUsed;
1079         }
1080
1081         if (len == 0) 
1082                 return -1;
1083
1084         bptr = Target->buf + Target->BufUsed;
1085         eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in...  */
1086
1087         while (aptr < eiptr){
1088                 if(bptr >= eptr) {
1089                         IncreaseBuf(Target, 1, -1);
1090                         eptr = Target->buf + Target->BufSize - 3; 
1091                         bptr = Target->buf + Target->BufUsed;
1092                 }
1093                 if (*aptr == '"') {
1094                         *bptr = '\\';
1095                         bptr ++;
1096                         *bptr = '"';
1097                         bptr ++;
1098                         Target->BufUsed += 2;
1099                 } else if (*aptr == '\\') {
1100                         *bptr = '\\';
1101                         bptr ++;
1102                         *bptr = '\\';
1103                         bptr ++;
1104                         Target->BufUsed += 2;
1105                 }
1106                 else{
1107                         *bptr = *aptr;
1108                         bptr++;
1109                         Target->BufUsed ++;
1110                 }
1111                 aptr ++;
1112         }
1113         *bptr = '\0';
1114         if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1115                 return -1;
1116         return Target->BufUsed;
1117 }
1118
1119 /**
1120  * @ingroup StrBuf_DeEnCoder
1121  * @brief Append a string, escaping characters which have meaning in HTML + json.  
1122  *
1123  * @param Target        target buffer
1124  * @param Source        source buffer; set to NULL if you just have a C-String
1125  * @param PlainIn       Plain-C string to append; set to NULL if unused
1126  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
1127  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
1128  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
1129  */
1130 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1131 {
1132         const char *aptr, *eiptr;
1133         char *bptr, *eptr;
1134         long len;
1135         int IsUtf8Sequence = 0;
1136
1137         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1138                 return -1;
1139
1140         if (PlainIn != NULL) {
1141                 aptr = PlainIn;
1142                 len = strlen(PlainIn);
1143                 eiptr = aptr + len;
1144         }
1145         else {
1146                 aptr = Source->buf;
1147                 eiptr = aptr + Source->BufUsed;
1148                 len = Source->BufUsed;
1149         }
1150
1151         if (len == 0) 
1152                 return -1;
1153
1154         bptr = Target->buf + Target->BufUsed;
1155         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1156
1157         while (aptr < eiptr){
1158                 if(bptr >= eptr) {
1159                         IncreaseBuf(Target, 1, -1);
1160                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1161                         bptr = Target->buf + Target->BufUsed;
1162                 }
1163                 if (*aptr == '<') {
1164                         memcpy(bptr, "&lt;", 4);
1165                         bptr += 4;
1166                         Target->BufUsed += 4;
1167                 }
1168                 else if (*aptr == '>') {
1169                         memcpy(bptr, "&gt;", 4);
1170                         bptr += 4;
1171                         Target->BufUsed += 4;
1172                 }
1173                 else if (*aptr == '&') {
1174                         memcpy(bptr, "&amp;", 5);
1175                         bptr += 5;
1176                         Target->BufUsed += 5;
1177                 }
1178                 else if (*aptr == LB) {
1179                         *bptr = '<';
1180                         bptr ++;
1181                         Target->BufUsed ++;
1182                 }
1183                 else if (*aptr == RB) {
1184                         *bptr = '>';
1185                         bptr ++;
1186                         Target->BufUsed ++;
1187                 }
1188                 else if ((*aptr == 32) && (nbsp == 1)) {
1189                         memcpy(bptr, "&nbsp;", 6);
1190                         bptr += 6;
1191                         Target->BufUsed += 6;
1192                 }
1193                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1194                         *bptr='\0';     /* nothing */
1195                 }
1196                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1197                         memcpy(bptr, "&lt;br/&gt;", 11);
1198                         bptr += 11;
1199                         Target->BufUsed += 11;
1200                 }
1201
1202                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1203                         *bptr='\0';     /* nothing */
1204                 }
1205
1206                 else if ((*aptr == '"') || (*aptr == QU)) {
1207                         *bptr = '\\';
1208                         bptr ++;
1209                         *bptr = '"';
1210                         bptr ++;
1211                         Target->BufUsed += 2;
1212                 } else if (*aptr == '\\') {
1213                         *bptr = '\\';
1214                         bptr ++;
1215                         *bptr = '\\';
1216                         bptr ++;
1217                         Target->BufUsed += 2;
1218                 }
1219                 else {
1220                         if (IsUtf8Sequence != 0) {
1221                                 IsUtf8Sequence --;
1222                                 *bptr = *aptr;
1223                                 bptr++;
1224                                 Target->BufUsed ++;
1225                         }
1226                         else {
1227                                 if (*aptr >= 0x20)
1228                                 {
1229                                         IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1230
1231                                         *bptr = *aptr;
1232                                         bptr++;
1233                                         Target->BufUsed ++;
1234                                 }
1235                         }
1236
1237                 }
1238                 aptr ++;
1239         }
1240         *bptr = '\0';
1241         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1242                 return -1;
1243         return Target->BufUsed;
1244 }
1245
1246
1247 /**
1248  * @ingroup StrBuf
1249  * @brief extracts a substring from Source into dest
1250  * @param dest buffer to place substring into
1251  * @param Source string to copy substring from
1252  * @param Offset chars to skip from start
1253  * @param nChars number of chars to copy
1254  * @returns the number of chars copied; may be different from nChars due to the size of Source
1255  */
1256 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1257 {
1258         size_t NCharsRemain;
1259         if (Offset > Source->BufUsed)
1260         {
1261                 FlushStrBuf(dest);
1262                 return 0;
1263         }
1264         if (Offset + nChars < Source->BufUsed)
1265         {
1266                 if (nChars >= dest->BufSize)
1267                         IncreaseBuf(dest, 0, nChars + 1);
1268                 memcpy(dest->buf, Source->buf + Offset, nChars);
1269                 dest->BufUsed = nChars;
1270                 dest->buf[dest->BufUsed] = '\0';
1271                 return nChars;
1272         }
1273         NCharsRemain = Source->BufUsed - Offset;
1274         if (NCharsRemain  >= dest->BufSize)
1275                 IncreaseBuf(dest, 0, NCharsRemain + 1);
1276         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1277         dest->BufUsed = NCharsRemain;
1278         dest->buf[dest->BufUsed] = '\0';
1279         return NCharsRemain;
1280 }
1281
1282 /**
1283  * @ingroup StrBuf
1284  * @brief sprintf like function appending the formated string to the buffer
1285  * vsnprintf version to wrap into own calls
1286  * @param Buf Buffer to extend by format and Params
1287  * @param format printf alike format to add
1288  * @param ap va_list containing the items for format
1289  */
1290 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1291 {
1292         va_list apl;
1293         size_t BufSize;
1294         size_t nWritten;
1295         size_t Offset;
1296         size_t newused;
1297
1298         if ((Buf == NULL)  || (format == NULL))
1299                 return;
1300
1301         BufSize = Buf->BufSize;
1302         nWritten = Buf->BufSize + 1;
1303         Offset = Buf->BufUsed;
1304         newused = Offset + nWritten;
1305         
1306         while (newused >= BufSize) {
1307                 va_copy(apl, ap);
1308                 nWritten = vsnprintf(Buf->buf + Offset, 
1309                                      Buf->BufSize - Offset, 
1310                                      format, apl);
1311                 va_end(apl);
1312                 newused = Offset + nWritten;
1313                 if (newused >= Buf->BufSize) {
1314                         IncreaseBuf(Buf, 1, newused);
1315                         newused = Buf->BufSize + 1;
1316                 }
1317                 else {
1318                         Buf->BufUsed = Offset + nWritten;
1319                         BufSize = Buf->BufSize;
1320                 }
1321
1322         }
1323 }
1324
1325 /**
1326  * @ingroup StrBuf
1327  * @brief sprintf like function appending the formated string to the buffer
1328  * @param Buf Buffer to extend by format and Params
1329  * @param format printf alike format to add
1330  */
1331 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1332 {
1333         size_t BufSize;
1334         size_t nWritten;
1335         size_t Offset;
1336         size_t newused;
1337         va_list arg_ptr;
1338         
1339         if ((Buf == NULL)  || (format == NULL))
1340                 return;
1341
1342         BufSize = Buf->BufSize;
1343         nWritten = Buf->BufSize + 1;
1344         Offset = Buf->BufUsed;
1345         newused = Offset + nWritten;
1346
1347         while (newused >= BufSize) {
1348                 va_start(arg_ptr, format);
1349                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
1350                                      Buf->BufSize - Buf->BufUsed, 
1351                                      format, arg_ptr);
1352                 va_end(arg_ptr);
1353                 newused = Buf->BufUsed + nWritten;
1354                 if (newused >= Buf->BufSize) {
1355                         IncreaseBuf(Buf, 1, newused);
1356                         newused = Buf->BufSize + 1;
1357                 }
1358                 else {
1359                         Buf->BufUsed += nWritten;
1360                         BufSize = Buf->BufSize;
1361                 }
1362
1363         }
1364 }
1365
1366 /**
1367  * @ingroup StrBuf
1368  * @brief sprintf like function putting the formated string into the buffer
1369  * @param Buf Buffer to extend by format and Parameters
1370  * @param format printf alike format to add
1371  */
1372 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1373 {
1374         size_t nWritten;
1375         va_list arg_ptr;
1376         
1377         if ((Buf == NULL)  || (format == NULL))
1378                 return;
1379
1380         nWritten = Buf->BufSize + 1;
1381         while (nWritten >= Buf->BufSize) {
1382                 va_start(arg_ptr, format);
1383                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1384                 va_end(arg_ptr);
1385                 if (nWritten >= Buf->BufSize) {
1386                         IncreaseBuf(Buf, 0, 0);
1387                         nWritten = Buf->BufSize + 1;
1388                         continue;
1389                 }
1390                 Buf->BufUsed = nWritten ;
1391         }
1392 }
1393
1394
1395 /**
1396  * @ingroup StrBuf_Tokenizer
1397  * @brief Counts the numbmer of tokens in a buffer
1398  * @param source String to count tokens in
1399  * @param tok    Tokenizer char to count
1400  * @returns numbers of tokenizer chars found
1401  */
1402 int StrBufNum_tokens(const StrBuf *source, char tok)
1403 {
1404         if (source == NULL)
1405                 return 0;
1406         return num_tokens(source->buf, tok);
1407 }
1408
1409 /*
1410  * remove_token() - a tokenizer that kills, maims, and destroys
1411  */
1412 /**
1413  * @ingroup StrBuf_Tokenizer
1414  * @brief a string tokenizer
1415  * @param Source StringBuffer to read into
1416  * @param parmnum n'th Parameter to remove
1417  * @param separator tokenizer character
1418  * @returns -1 if not found, else length of token.
1419  */
1420 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1421 {
1422         int ReducedBy;
1423         char *d, *s, *end;              /* dest, source */
1424         int count = 0;
1425
1426         /* Find desired @parameter */
1427         end = Source->buf + Source->BufUsed;
1428         d = Source->buf;
1429         while ((count < parmnum) &&
1430                (d <= end))
1431         {
1432                 /* End of string, bail! */
1433                 if (!*d) {
1434                         d = NULL;
1435                         break;
1436                 }
1437                 if (*d == separator) {
1438                         count++;
1439                 }
1440                 d++;
1441         }
1442         if ((d == NULL) || (d >= end))
1443                 return 0;               /* @Parameter not found */
1444
1445         /* Find next @parameter */
1446         s = d;
1447         while ((*s && *s != separator) &&
1448                (s <= end))
1449         {
1450                 s++;
1451         }
1452         if (*s == separator)
1453                 s++;
1454         ReducedBy = d - s;
1455
1456         /* Hack and slash */
1457         if (*s) {
1458                 memmove(d, s, Source->BufUsed - (s - Source->buf));
1459                 Source->BufUsed += ReducedBy;
1460         }
1461         else if (d == Source->buf) {
1462                 *d = 0;
1463                 Source->BufUsed = 0;
1464         }
1465         else {
1466                 *--d = 0;
1467                 Source->BufUsed += ReducedBy;
1468         }
1469         /*
1470         while (*s) {
1471                 *d++ = *s++;
1472         }
1473         *d = 0;
1474         */
1475         return ReducedBy;
1476 }
1477
1478
1479 /**
1480  * @ingroup StrBuf_Tokenizer
1481  * @brief a string tokenizer
1482  * @param dest Destination StringBuffer
1483  * @param Source StringBuffer to read into
1484  * @param parmnum n'th Parameter to extract
1485  * @param separator tokenizer character
1486  * @returns -1 if not found, else length of token.
1487  */
1488 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1489 {
1490         const char *s, *e;              //* source * /
1491         int len = 0;                    //* running total length of extracted string * /
1492         int current_token = 0;          //* token currently being processed * /
1493          
1494         if (dest != NULL) {
1495                 dest->buf[0] = '\0';
1496                 dest->BufUsed = 0;
1497         }
1498         else
1499                 return(-1);
1500
1501         if ((Source == NULL) || (Source->BufUsed ==0)) {
1502                 return(-1);
1503         }
1504         s = Source->buf;
1505         e = s + Source->BufUsed;
1506
1507         //cit_backtrace();
1508         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1509
1510         while ((s<e) && !IsEmptyStr(s)) {
1511                 if (*s == separator) {
1512                         ++current_token;
1513                 }
1514                 if (len >= dest->BufSize) {
1515                         dest->BufUsed = len;
1516                         if (IncreaseBuf(dest, 1, -1) < 0) {
1517                                 dest->BufUsed --;
1518                                 break;
1519                         }
1520                 }
1521                 if ( (current_token == parmnum) && 
1522                      (*s != separator)) {
1523                         dest->buf[len] = *s;
1524                         ++len;
1525                 }
1526                 else if (current_token > parmnum) {
1527                         break;
1528                 }
1529                 ++s;
1530         }
1531         
1532         dest->buf[len] = '\0';
1533         dest->BufUsed = len;
1534                 
1535         if (current_token < parmnum) {
1536                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1537                 return(-1);
1538         }
1539         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1540         return(len);
1541 }
1542
1543
1544
1545
1546
1547 /**
1548  * @ingroup StrBuf_Tokenizer
1549  * @brief a string tokenizer to fetch an integer
1550  * @param Source String containing tokens
1551  * @param parmnum n'th Parameter to extract
1552  * @param separator tokenizer character
1553  * @returns 0 if not found, else integer representation of the token
1554  */
1555 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1556 {
1557         StrBuf tmp;
1558         char buf[64];
1559         
1560         tmp.buf = buf;
1561         buf[0] = '\0';
1562         tmp.BufSize = 64;
1563         tmp.BufUsed = 0;
1564         tmp.ConstBuf = 1;
1565         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1566                 return(atoi(buf));
1567         else
1568                 return 0;
1569 }
1570
1571 /**
1572  * @ingroup StrBuf_Tokenizer
1573  * @brief a string tokenizer to fetch a long integer
1574  * @param Source String containing tokens
1575  * @param parmnum n'th Parameter to extract
1576  * @param separator tokenizer character
1577  * @returns 0 if not found, else long integer representation of the token
1578  */
1579 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1580 {
1581         StrBuf tmp;
1582         char buf[64];
1583         
1584         tmp.buf = buf;
1585         buf[0] = '\0';
1586         tmp.BufSize = 64;
1587         tmp.BufUsed = 0;
1588         tmp.ConstBuf = 1;
1589         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1590                 return(atoi(buf));
1591         else
1592                 return 0;
1593 }
1594
1595
1596 /**
1597  * @ingroup StrBuf_Tokenizer
1598  * @brief a string tokenizer to fetch an unsigned long
1599  * @param Source String containing tokens
1600  * @param parmnum n'th Parameter to extract
1601  * @param separator tokenizer character
1602  * @returns 0 if not found, else unsigned long representation of the token
1603  */
1604 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1605 {
1606         StrBuf tmp;
1607         char buf[64];
1608         char *pnum;
1609         
1610         tmp.buf = buf;
1611         buf[0] = '\0';
1612         tmp.BufSize = 64;
1613         tmp.BufUsed = 0;
1614         tmp.ConstBuf = 1;
1615         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1616                 pnum = &buf[0];
1617                 if (*pnum == '-')
1618                         pnum ++;
1619                 return (unsigned long) atol(pnum);
1620         }
1621         else 
1622                 return 0;
1623 }
1624
1625
1626
1627 /**
1628  * @ingroup StrBuf_NextTokenizer
1629  * @brief a string tokenizer; Bounds checker
1630  *  function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1631  * @param Source our tokenbuffer
1632  * @param pStart the token iterator pointer to inspect
1633  * @returns whether the revolving pointer is inside of the search range
1634  */
1635 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1636 {
1637         if ((Source == NULL) || 
1638             (*pStart == StrBufNOTNULL) ||
1639             (Source->BufUsed == 0))
1640         {
1641                 return 0;
1642         }
1643         if (*pStart == NULL)
1644         {
1645                 return 1;
1646         }
1647         else if (*pStart > Source->buf + Source->BufUsed)
1648         {
1649                 return 0;
1650         }
1651         else if (*pStart <= Source->buf)
1652         {
1653                 return 0;
1654         }
1655
1656         return 1;
1657 }
1658
1659 /**
1660  * @ingroup StrBuf_NextTokenizer
1661  * @brief a string tokenizer
1662  * @param dest Destination StringBuffer
1663  * @param Source StringBuffer to read into
1664  * @param pStart pointer to the end of the last token. Feed with NULL on start.
1665  * @param separator tokenizer 
1666  * @returns -1 if not found, else length of token.
1667  */
1668 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1669 {
1670         const char *s;          /* source */
1671         const char *EndBuffer;  /* end stop of source buffer */
1672         int current_token = 0;  /* token currently being processed */
1673         int len = 0;            /* running total length of extracted string */
1674
1675         if ((Source          == NULL) || 
1676             (Source->BufUsed == 0)      ) 
1677         {
1678                 *pStart = StrBufNOTNULL;
1679                 return -1;
1680         }
1681          
1682         EndBuffer = Source->buf + Source->BufUsed;
1683
1684         if (dest != NULL) 
1685         {
1686                 dest->buf[0] = '\0';
1687                 dest->BufUsed = 0;
1688         }
1689         else
1690         {
1691                 *pStart = EndBuffer + 1;
1692                 return -1;
1693         }
1694
1695         if (*pStart == NULL)
1696         {
1697                 *pStart = Source->buf; /* we're starting to examine this buffer. */
1698         }
1699         else if ((*pStart < Source->buf) || 
1700                  (*pStart > EndBuffer  )   ) 
1701         {
1702                 return -1; /* no more tokens to find. */
1703         }
1704
1705         s = *pStart;
1706         /* start to find the next token */
1707         while ((s <= EndBuffer)      && 
1708                (current_token == 0) ) 
1709         {
1710                 if (*s == separator) 
1711                 {
1712                         /* we found the next token */
1713                         ++current_token;
1714                 }
1715
1716                 if (len >= dest->BufSize) 
1717                 {
1718                         /* our Dest-buffer isn't big enough, increase it. */
1719                         dest->BufUsed = len;
1720
1721                         if (IncreaseBuf(dest, 1, -1) < 0) {
1722                                 /* WHUT? no more mem? bail out. */
1723                                 s = EndBuffer;
1724                                 dest->BufUsed --;
1725                                 break;
1726                         }
1727                 }
1728
1729                 if ( (current_token == 0 ) &&   /* are we in our target token? */
1730                      (!IsEmptyStr(s)     ) &&
1731                      (separator     != *s)    ) /* don't copy the token itself */
1732                 {
1733                         dest->buf[len] = *s;    /* Copy the payload */
1734                         ++len;                  /* remember the bigger size. */
1735                 }
1736
1737                 ++s;
1738         }
1739
1740         /* did we reach the end? */
1741         if ((s > EndBuffer)) {
1742                 EndBuffer = StrBufNOTNULL;
1743                 *pStart = EndBuffer;
1744         }
1745         else {
1746                 *pStart = s;  /* remember the position for the next run */
1747         }
1748
1749         /* sanitize our extracted token */
1750         dest->buf[len] = '\0';
1751         dest->BufUsed  = len;
1752
1753         return (len);
1754 }
1755
1756
1757 /**
1758  * @ingroup StrBuf_NextTokenizer
1759  * @brief a string tokenizer
1760  * @param Source StringBuffer to read from
1761  * @param pStart pointer to the end of the last token. Feed with NULL.
1762  * @param separator tokenizer character
1763  * @param nTokens number of tokens to fastforward over
1764  * @returns -1 if not found, else length of token.
1765  */
1766 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1767 {
1768         const char *s, *EndBuffer;      //* source * /
1769         int len = 0;                    //* running total length of extracted string * /
1770         int current_token = 0;          //* token currently being processed * /
1771
1772         if ((Source == NULL) || 
1773             (Source->BufUsed ==0)) {
1774                 return(-1);
1775         }
1776         if (nTokens == 0)
1777                 return Source->BufUsed;
1778
1779         if (*pStart == NULL)
1780                 *pStart = Source->buf;
1781
1782         EndBuffer = Source->buf + Source->BufUsed;
1783
1784         if ((*pStart < Source->buf) || 
1785             (*pStart >  EndBuffer)) {
1786                 return (-1);
1787         }
1788
1789
1790         s = *pStart;
1791
1792         //cit_backtrace();
1793         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1794
1795         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1796                 if (*s == separator) {
1797                         ++current_token;
1798                 }
1799                 if (current_token >= nTokens) {
1800                         break;
1801                 }
1802                 ++s;
1803         }
1804         *pStart = s;
1805         (*pStart) ++;
1806
1807         return(len);
1808 }
1809
1810 /**
1811  * @ingroup StrBuf_NextTokenizer
1812  * @brief a string tokenizer to fetch an integer
1813  * @param Source StringBuffer to read from
1814  * @param pStart Cursor on the tokenstring
1815  * @param separator tokenizer character
1816  * @returns 0 if not found, else integer representation of the token
1817  */
1818 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1819 {
1820         StrBuf tmp;
1821         char buf[64];
1822         
1823         tmp.buf = buf;
1824         buf[0] = '\0';
1825         tmp.BufSize = 64;
1826         tmp.BufUsed = 0;
1827         tmp.ConstBuf = 1;
1828         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1829                 return(atoi(buf));
1830         else
1831                 return 0;
1832 }
1833
1834 /**
1835  * @ingroup StrBuf_NextTokenizer
1836  * @brief a string tokenizer to fetch a long integer
1837  * @param Source StringBuffer to read from
1838  * @param pStart Cursor on the tokenstring
1839  * @param separator tokenizer character
1840  * @returns 0 if not found, else long integer representation of the token
1841  */
1842 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1843 {
1844         StrBuf tmp;
1845         char buf[64];
1846         
1847         tmp.buf = buf;
1848         buf[0] = '\0';
1849         tmp.BufSize = 64;
1850         tmp.BufUsed = 0;
1851         tmp.ConstBuf = 1;
1852         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1853                 return(atoi(buf));
1854         else
1855                 return 0;
1856 }
1857
1858
1859 /**
1860  * @ingroup StrBuf_NextTokenizer
1861  * @brief a string tokenizer to fetch an unsigned long
1862  * @param Source StringBuffer to read from
1863  * @param pStart Cursor on the tokenstring
1864  * @param separator tokenizer character
1865  * @returns 0 if not found, else unsigned long representation of the token
1866  */
1867 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1868 {
1869         StrBuf tmp;
1870         char buf[64];
1871         char *pnum;
1872         
1873         tmp.buf = buf;
1874         buf[0] = '\0';
1875         tmp.BufSize = 64;
1876         tmp.BufUsed = 0;
1877         tmp.ConstBuf = 1;
1878         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1879                 pnum = &buf[0];
1880                 if (*pnum == '-')
1881                         pnum ++;
1882                 return (unsigned long) atol(pnum);
1883         }
1884         else 
1885                 return 0;
1886 }
1887
1888
1889
1890 /**
1891  * @ingroup StrBuf_IO
1892  * @brief Read a line from socket
1893  * flushes and closes the FD on error
1894  * @param buf the buffer to get the input to
1895  * @param fd pointer to the filedescriptor to read
1896  * @param append Append to an existing string or replace?
1897  * @param Error strerror() on error 
1898  * @returns numbers of chars read
1899  */
1900 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1901 {
1902         int len, rlen, slen;
1903
1904         if (!append)
1905                 FlushStrBuf(buf);
1906
1907         slen = len = buf->BufUsed;
1908         while (1) {
1909                 rlen = read(*fd, &buf->buf[len], 1);
1910                 if (rlen < 1) {
1911                         *Error = strerror(errno);
1912                         
1913                         close(*fd);
1914                         *fd = -1;
1915                         
1916                         return -1;
1917                 }
1918                 if (buf->buf[len] == '\n')
1919                         break;
1920                 if (buf->buf[len] != '\r')
1921                         len ++;
1922                 if (len + 2 >= buf->BufSize) {
1923                         buf->BufUsed = len;
1924                         buf->buf[len+1] = '\0';
1925                         IncreaseBuf(buf, 1, -1);
1926                 }
1927         }
1928         buf->BufUsed = len;
1929         buf->buf[len] = '\0';
1930         return len - slen;
1931 }
1932
1933 /**
1934  * @ingroup StrBuf_BufferedIO
1935  * @brief Read a line from socket
1936  * flushes and closes the FD on error
1937  * @param Line the line to read from the fd / I/O Buffer
1938  * @param buf the buffer to get the input to
1939  * @param fd pointer to the filedescriptor to read
1940  * @param timeout number of successless selects until we bail out
1941  * @param selectresolution how long to wait on each select
1942  * @param Error strerror() on error 
1943  * @returns numbers of chars read
1944  */
1945 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1946                                  StrBuf *buf, 
1947                                  int *fd, 
1948                                  int timeout, 
1949                                  int selectresolution, 
1950                                  const char **Error)
1951 {
1952         int len, rlen;
1953         int nSuccessLess = 0;
1954         fd_set rfds;
1955         char *pch = NULL;
1956         int fdflags;
1957         int IsNonBlock;
1958         struct timeval tv;
1959
1960         if (buf->BufUsed > 0) {
1961                 pch = strchr(buf->buf, '\n');
1962                 if (pch != NULL) {
1963                         rlen = 0;
1964                         len = pch - buf->buf;
1965                         if (len > 0 && (*(pch - 1) == '\r') )
1966                                 rlen ++;
1967                         StrBufSub(Line, buf, 0, len - rlen);
1968                         StrBufCutLeft(buf, len + 1);
1969                         return len - rlen;
1970                 }
1971         }
1972         
1973         if (buf->BufSize - buf->BufUsed < 10)
1974                 IncreaseBuf(buf, 1, -1);
1975
1976         fdflags = fcntl(*fd, F_GETFL);
1977         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1978
1979         while ((nSuccessLess < timeout) && (pch == NULL)) {
1980                 if (IsNonBlock){
1981                         tv.tv_sec = selectresolution;
1982                         tv.tv_usec = 0;
1983                         
1984                         FD_ZERO(&rfds);
1985                         FD_SET(*fd, &rfds);
1986                         if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1987                                 *Error = strerror(errno);
1988                                 close (*fd);
1989                                 *fd = -1;
1990                                 return -1;
1991                         }
1992                 }
1993                 if (IsNonBlock && !  FD_ISSET(*fd, &rfds)) {
1994                         nSuccessLess ++;
1995                         continue;
1996                 }
1997                 rlen = read(*fd, 
1998                             &buf->buf[buf->BufUsed], 
1999                             buf->BufSize - buf->BufUsed - 1);
2000                 if (rlen < 1) {
2001                         *Error = strerror(errno);
2002                         close(*fd);
2003                         *fd = -1;
2004                         return -1;
2005                 }
2006                 else if (rlen > 0) {
2007                         nSuccessLess = 0;
2008                         buf->BufUsed += rlen;
2009                         buf->buf[buf->BufUsed] = '\0';
2010                         if (buf->BufUsed + 10 > buf->BufSize) {
2011                                 IncreaseBuf(buf, 1, -1);
2012                         }
2013                         pch = strchr(buf->buf, '\n');
2014                         continue;
2015                 }
2016                 
2017         }
2018         if (pch != NULL) {
2019                 rlen = 0;
2020                 len = pch - buf->buf;
2021                 if (len > 0 && (*(pch - 1) == '\r') )
2022                         rlen ++;
2023                 StrBufSub(Line, buf, 0, len - rlen);
2024                 StrBufCutLeft(buf, len + 1);
2025                 return len - rlen;
2026         }
2027         return -1;
2028
2029 }
2030
2031 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
2032 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
2033 /**
2034  * @ingroup StrBuf_BufferedIO
2035  * @brief Read a line from socket
2036  * flushes and closes the FD on error
2037  * @param Line Line to read from the fd / I/O Buffer
2038  * @param IOBuf the buffer to get the input to
2039  * @param Pos pointer to the current read position, should be NULL initialized!
2040  * @param fd pointer to the filedescriptor to read
2041  * @param timeout number of successless selects until we bail out
2042  * @param selectresolution how long to wait on each select
2043  * @param Error strerror() on error 
2044  * @returns numbers of chars read
2045  */
2046 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
2047                                       StrBuf *IOBuf, 
2048                                       const char **Pos,
2049                                       int *fd, 
2050                                       int timeout, 
2051                                       int selectresolution, 
2052                                       const char **Error)
2053 {
2054         const char *pche = NULL;
2055         const char *pos = NULL;
2056         int len, rlen;
2057         int nSuccessLess = 0;
2058         fd_set rfds;
2059         const char *pch = NULL;
2060         int fdflags;
2061         int IsNonBlock;
2062         struct timeval tv;
2063         
2064         pos = *Pos;
2065         if ((IOBuf->BufUsed > 0) && 
2066             (pos != NULL) && 
2067             (pos < IOBuf->buf + IOBuf->BufUsed)) 
2068         {
2069                 pche = IOBuf->buf + IOBuf->BufUsed;
2070                 pch = pos;
2071                 while ((pch < pche) && (*pch != '\n'))
2072                         pch ++;
2073                 if ((pch >= pche) || (*pch == '\0'))
2074                         pch = NULL;
2075                 if ((pch != NULL) && 
2076                     (pch <= pche)) 
2077                 {
2078                         rlen = 0;
2079                         len = pch - pos;
2080                         if (len > 0 && (*(pch - 1) == '\r') )
2081                                 rlen ++;
2082                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
2083                         *Pos = pch + 1;
2084                         return len - rlen;
2085                 }
2086         }
2087         
2088         if (pos != NULL) {
2089                 if (pos > pche)
2090                         FlushStrBuf(IOBuf);
2091                 else 
2092                         StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
2093                 *Pos = NULL;
2094         }
2095         
2096         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
2097                 IncreaseBuf(IOBuf, 1, -1);
2098         }
2099
2100         fdflags = fcntl(*fd, F_GETFL);
2101         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2102
2103         pch = NULL;
2104         while ((nSuccessLess < timeout) && 
2105                (pch == NULL) &&
2106                (*fd != -1)) {
2107                 if (IsNonBlock)
2108                 {
2109                         tv.tv_sec = 1;
2110                         tv.tv_usec = 0;
2111                 
2112                         FD_ZERO(&rfds);
2113                         FD_SET(*fd, &rfds);
2114                         if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
2115                                 *Error = strerror(errno);
2116                                 close (*fd);
2117                                 *fd = -1;
2118                                 if (*Error == NULL)
2119                                         *Error = ErrRBLF_SelectFailed;
2120                                 return -1;
2121                         }
2122                         if (! FD_ISSET(*fd, &rfds) != 0) {
2123                                 nSuccessLess ++;
2124                                 continue;
2125                         }
2126                 }
2127                 rlen = read(*fd, 
2128                             &IOBuf->buf[IOBuf->BufUsed], 
2129                             IOBuf->BufSize - IOBuf->BufUsed - 1);
2130                 if (rlen < 1) {
2131                         *Error = strerror(errno);
2132                         close(*fd);
2133                         *fd = -1;
2134                         return -1;
2135                 }
2136                 else if (rlen > 0) {
2137                         nSuccessLess = 0;
2138                         IOBuf->BufUsed += rlen;
2139                         IOBuf->buf[IOBuf->BufUsed] = '\0';
2140                         if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
2141                                 IncreaseBuf(IOBuf, 1, -1);
2142                         }
2143                         
2144                         pche = IOBuf->buf + IOBuf->BufUsed;
2145                         pch = IOBuf->buf;
2146                         while ((pch < pche) && (*pch != '\n'))
2147                                 pch ++;
2148                         if ((pch >= pche) || (*pch == '\0'))
2149                                 pch = NULL;
2150                         continue;
2151                 }
2152         }
2153         if (pch != NULL) {
2154                 pos = IOBuf->buf;
2155                 rlen = 0;
2156                 len = pch - pos;
2157                 if (len > 0 && (*(pch - 1) == '\r') )
2158                         rlen ++;
2159                 StrBufSub(Line, IOBuf, 0, len - rlen);
2160                 *Pos = pos + len + 1;
2161                 return len - rlen;
2162         }
2163         *Error = ErrRBLF_NotEnoughSentFromServer;
2164         return -1;
2165
2166 }
2167
2168 /**
2169  * @ingroup StrBuf_IO
2170  * @brief Input binary data from socket
2171  * flushes and closes the FD on error
2172  * @param Buf the buffer to get the input to
2173  * @param fd pointer to the filedescriptor to read
2174  * @param append Append to an existing string or replace?
2175  * @param nBytes the maximal number of bytes to read
2176  * @param Error strerror() on error 
2177  * @returns numbers of chars read
2178  */
2179 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
2180 {
2181         int fdflags;
2182         int len, rlen, slen;
2183         int nSuccessLess;
2184         int nRead = 0;
2185         char *ptr;
2186         int IsNonBlock;
2187         struct timeval tv;
2188         fd_set rfds;
2189         if ((Buf == NULL) || (*fd == -1))
2190                 return -1;
2191         if (!append)
2192                 FlushStrBuf(Buf);
2193         if (Buf->BufUsed + nBytes >= Buf->BufSize)
2194                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
2195
2196         ptr = Buf->buf + Buf->BufUsed;
2197
2198         slen = len = Buf->BufUsed;
2199
2200         fdflags = fcntl(*fd, F_GETFL);
2201         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2202         nSuccessLess = 0;
2203         while ((nRead < nBytes) && 
2204                (*fd != -1)) 
2205         {
2206                 if (IsNonBlock)
2207                 {
2208                         tv.tv_sec = 1;
2209                         tv.tv_usec = 0;
2210                 
2211                         FD_ZERO(&rfds);
2212                         FD_SET(*fd, &rfds);
2213                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2214                                 *Error = strerror(errno);
2215                                 close (*fd);
2216                                 *fd = -1;
2217                                 if (*Error == NULL)
2218                                         *Error = ErrRBLF_SelectFailed;
2219                                 return -1;
2220                         }
2221                         if (! FD_ISSET(*fd, &rfds) != 0) {
2222                                 nSuccessLess ++;
2223                                 continue;
2224                         }
2225                 }
2226
2227                 if ((rlen = read(*fd, 
2228                                  ptr,
2229                                  nBytes - nRead)) == -1) {
2230                         close(*fd);
2231                         *fd = -1;
2232                         *Error = strerror(errno);
2233                         return rlen;
2234                 }
2235                 nRead += rlen;
2236                 ptr += rlen;
2237                 Buf->BufUsed += rlen;
2238         }
2239         Buf->buf[Buf->BufUsed] = '\0';
2240         return nRead;
2241 }
2242
2243 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
2244 /**
2245  * @ingroup StrBuf_BufferedIO
2246  * @brief Input binary data from socket
2247  * flushes and closes the FD on error
2248  * @param Blob put binary thing here
2249  * @param IOBuf the buffer to get the input to
2250  * @param Pos offset inside of IOBuf
2251  * @param fd pointer to the filedescriptor to read
2252  * @param append Append to an existing string or replace?
2253  * @param nBytes the maximal number of bytes to read
2254  * @param check whether we should search for '000\n' terminators in case of timeouts
2255  * @param Error strerror() on error 
2256  * @returns numbers of chars read
2257  */
2258 int StrBufReadBLOBBuffered(StrBuf *Blob, 
2259                            StrBuf *IOBuf, 
2260                            const char **Pos,
2261                            int *fd, 
2262                            int append, 
2263                            long nBytes, 
2264                            int check, 
2265                            const char **Error)
2266 {
2267         const char *pche;
2268         const char *pos;
2269         int nSelects = 0;
2270         int SelRes;
2271         int fdflags;
2272         int len = 0;
2273         int rlen, slen;
2274         int nRead = 0;
2275         int nAlreadyRead = 0;
2276         int IsNonBlock;
2277         char *ptr;
2278         fd_set rfds;
2279         const char *pch;
2280         struct timeval tv;
2281         int nSuccessLess;
2282
2283         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2284                 return -1;
2285         if (!append)
2286                 FlushStrBuf(Blob);
2287         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
2288                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2289         
2290         pos = *Pos;
2291
2292         if (pos > 0)
2293                 len = pos - IOBuf->buf;
2294         rlen = IOBuf->BufUsed - len;
2295
2296
2297         if ((IOBuf->BufUsed > 0) && 
2298             (pos != NULL) && 
2299             (pos < IOBuf->buf + IOBuf->BufUsed)) 
2300         {
2301                 pche = IOBuf->buf + IOBuf->BufUsed;
2302                 pch = pos;
2303
2304                 if (rlen < nBytes) {
2305                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2306                         Blob->BufUsed += rlen;
2307                         Blob->buf[Blob->BufUsed] = '\0';
2308                         nAlreadyRead = nRead = rlen;
2309                         *Pos = NULL; 
2310                 }
2311                 if (rlen >= nBytes) {
2312                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2313                         Blob->BufUsed += nBytes;
2314                         Blob->buf[Blob->BufUsed] = '\0';
2315                         if (rlen == nBytes) {
2316                                 *Pos = NULL; 
2317                                 FlushStrBuf(IOBuf);
2318                         }
2319                         else 
2320                                 *Pos += nBytes;
2321                         return nBytes;
2322                 }
2323         }
2324
2325         FlushStrBuf(IOBuf);
2326         if (IOBuf->BufSize < nBytes - nRead)
2327                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2328         ptr = IOBuf->buf;
2329
2330         slen = len = Blob->BufUsed;
2331
2332         fdflags = fcntl(*fd, F_GETFL);
2333         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2334
2335         SelRes = 1;
2336         nBytes -= nRead;
2337         nRead = 0;
2338         while ((nRead < nBytes) &&
2339                (*fd != -1)) {
2340                 if (IsNonBlock)
2341                 {
2342                         tv.tv_sec = 1;
2343                         tv.tv_usec = 0;
2344                 
2345                         FD_ZERO(&rfds);
2346                         FD_SET(*fd, &rfds);
2347                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2348                                 *Error = strerror(errno);
2349                                 close (*fd);
2350                                 *fd = -1;
2351                                 if (*Error == NULL)
2352                                         *Error = ErrRBLF_SelectFailed;
2353                                 return -1;
2354                         }
2355                         if (! FD_ISSET(*fd, &rfds) != 0) {
2356                                 nSuccessLess ++;
2357                                 continue;
2358                         }
2359                 }
2360                 nSuccessLess = 0;
2361                 rlen = read(*fd, 
2362                             ptr,
2363                             nBytes - nRead);
2364                 if (rlen == -1) {
2365                         close(*fd);
2366                         *fd = -1;
2367                         *Error = strerror(errno);
2368                         return rlen;
2369                 }
2370                 else if (rlen == 0){
2371                         nSuccessLess ++;
2372                         if ((check == NNN_TERM) && 
2373                             (nRead > 5) &&
2374                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
2375                         {
2376                                 StrBufPlain(Blob, HKEY("\n000\n"));
2377                                 StrBufCutRight(Blob, 5);
2378                                 return Blob->BufUsed;
2379                         }
2380                         if (nSelects > 10) {
2381                                 FlushStrBuf(IOBuf);
2382                                 *Error = ErrRBB_too_many_selects;
2383                                 return -1;
2384                         }
2385                 }
2386                 else if (rlen > 0) {
2387                         nRead += rlen;
2388                         ptr += rlen;
2389                         IOBuf->BufUsed += rlen;
2390                 }
2391         }
2392         if (nRead > nBytes) {
2393                 *Pos = IOBuf->buf + nBytes;
2394         }
2395         Blob->buf[Blob->BufUsed] = '\0';
2396         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2397         if (*Pos == NULL) {
2398                 FlushStrBuf(IOBuf);
2399         }
2400         return nRead + nAlreadyRead;
2401 }
2402
2403 /**
2404  * @ingroup StrBuf
2405  * @brief Cut nChars from the start of the string
2406  * @param Buf Buffer to modify
2407  * @param nChars how many chars should be skipped?
2408  */
2409 void StrBufCutLeft(StrBuf *Buf, int nChars)
2410 {
2411         if (nChars >= Buf->BufUsed) {
2412                 FlushStrBuf(Buf);
2413                 return;
2414         }
2415         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2416         Buf->BufUsed -= nChars;
2417         Buf->buf[Buf->BufUsed] = '\0';
2418 }
2419
2420 /**
2421  * @ingroup StrBuf
2422  * @brief Cut the trailing n Chars from the string
2423  * @param Buf Buffer to modify
2424  * @param nChars how many chars should be trunkated?
2425  */
2426 void StrBufCutRight(StrBuf *Buf, int nChars)
2427 {
2428         if (nChars >= Buf->BufUsed) {
2429                 FlushStrBuf(Buf);
2430                 return;
2431         }
2432         Buf->BufUsed -= nChars;
2433         Buf->buf[Buf->BufUsed] = '\0';
2434 }
2435
2436 /**
2437  * @ingroup StrBuf
2438  * @brief Cut the string after n Chars
2439  * @param Buf Buffer to modify
2440  * @param AfternChars after how many chars should we trunkate the string?
2441  * @param At if non-null and points inside of our string, cut it there.
2442  */
2443 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2444 {
2445         if (At != NULL){
2446                 AfternChars = At - Buf->buf;
2447         }
2448
2449         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2450                 return;
2451         Buf->BufUsed = AfternChars;
2452         Buf->buf[Buf->BufUsed] = '\0';
2453 }
2454
2455
2456 /**
2457  * @ingroup StrBuf
2458  * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2459  * @param Buf the string to modify
2460  */
2461 void StrBufTrim(StrBuf *Buf)
2462 {
2463         int delta = 0;
2464         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2465
2466         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2467                 delta ++;
2468         }
2469         if (delta > 0) StrBufCutLeft(Buf, delta);
2470
2471         if (Buf->BufUsed == 0) return;
2472         while (isspace(Buf->buf[Buf->BufUsed - 1])){
2473                 Buf->BufUsed --;
2474         }
2475         Buf->buf[Buf->BufUsed] = '\0';
2476 }
2477
2478 /**
2479  * @ingroup StrBuf
2480  * @brief uppercase the contents of a buffer
2481  * @param Buf the buffer to translate
2482  */
2483 void StrBufUpCase(StrBuf *Buf) 
2484 {
2485         char *pch, *pche;
2486
2487         pch = Buf->buf;
2488         pche = pch + Buf->BufUsed;
2489         while (pch < pche) {
2490                 *pch = toupper(*pch);
2491                 pch ++;
2492         }
2493 }
2494
2495
2496 /**
2497  * @ingroup StrBuf
2498  * @brief lowercase the contents of a buffer
2499  * @param Buf the buffer to translate
2500  */
2501 void StrBufLowerCase(StrBuf *Buf) 
2502 {
2503         char *pch, *pche;
2504
2505         pch = Buf->buf;
2506         pche = pch + Buf->BufUsed;
2507         while (pch < pche) {
2508                 *pch = tolower(*pch);
2509                 pch ++;
2510         }
2511 }
2512
2513 /**
2514  * @ingroup StrBuf
2515  * @brief removes double slashes from pathnames
2516  * @param Dir directory string to filter
2517  * @param RemoveTrailingSlash allows / disallows trailing slashes
2518  */
2519 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2520 {
2521         char *a, *b;
2522
2523         a = b = Dir->buf;
2524
2525         while (!IsEmptyStr(a)) {
2526                 if (*a == '/') {
2527                         while (*a == '/')
2528                                 a++;
2529                         *b = '/';
2530                         b++;
2531                 }
2532                 else {
2533                         *b = *a;
2534                         b++; a++;
2535                 }
2536         }
2537         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2538                 *b = '/';
2539                 b++;
2540         }
2541         *b = '\0';
2542         Dir->BufUsed = b - Dir->buf;
2543 }
2544
2545 /**
2546  * @ingroup StrBuf_DeEnCoder
2547  * @brief unhide special chars hidden to the HTML escaper
2548  * @param target buffer to put the unescaped string in
2549  * @param source buffer to unescape
2550  */
2551 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2552 {
2553         int a, b, len;
2554         char hex[3];
2555
2556         if (target != NULL)
2557                 FlushStrBuf(target);
2558
2559         if (source == NULL ||target == NULL)
2560         {
2561                 return;
2562         }
2563
2564         len = source->BufUsed;
2565         for (a = 0; a < len; ++a) {
2566                 if (target->BufUsed >= target->BufSize)
2567                         IncreaseBuf(target, 1, -1);
2568
2569                 if (source->buf[a] == '=') {
2570                         hex[0] = source->buf[a + 1];
2571                         hex[1] = source->buf[a + 2];
2572                         hex[2] = 0;
2573                         b = 0;
2574                         sscanf(hex, "%02x", &b);
2575                         target->buf[target->BufUsed] = b;
2576                         target->buf[++target->BufUsed] = 0;
2577                         a += 2;
2578                 }
2579                 else {
2580                         target->buf[target->BufUsed] = source->buf[a];
2581                         target->buf[++target->BufUsed] = 0;
2582                 }
2583         }
2584 }
2585
2586
2587 /**
2588  * @ingroup StrBuf_DeEnCoder
2589  * @brief hide special chars from the HTML escapers and friends
2590  * @param target buffer to put the escaped string in
2591  * @param source buffer to escape
2592  */
2593 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2594 {
2595         int i, len;
2596
2597         if (target != NULL)
2598                 FlushStrBuf(target);
2599
2600         if (source == NULL ||target == NULL)
2601         {
2602                 return;
2603         }
2604
2605         len = source->BufUsed;
2606         for (i=0; i<len; ++i) {
2607                 if (target->BufUsed + 4 >= target->BufSize)
2608                         IncreaseBuf(target, 1, -1);
2609                 if ( (isalnum(source->buf[i])) || 
2610                      (source->buf[i]=='-') || 
2611                      (source->buf[i]=='_') ) {
2612                         target->buf[target->BufUsed++] = source->buf[i];
2613                 }
2614                 else {
2615                         sprintf(&target->buf[target->BufUsed], 
2616                                 "=%02X", 
2617                                 (0xFF &source->buf[i]));
2618                         target->BufUsed += 3;
2619                 }
2620         }
2621         target->buf[target->BufUsed + 1] = '\0';
2622 }
2623
2624 #ifdef HAVE_ZLIB
2625 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2626 #define OS_CODE 0x03    /*< unix */
2627
2628 /**
2629  * @ingroup StrBuf_DeEnCoder
2630  * @brief uses the same calling syntax as compress2(), but it
2631  *   creates a stream compatible with HTTP "Content-encoding: gzip"
2632  * @param dest compressed buffer
2633  * @param destLen length of the compresed data 
2634  * @param source source to encode
2635  * @param sourceLen length of source to encode 
2636  * @param level compression level
2637  */
2638 int ZEXPORT compress_gzip(Bytef * dest,
2639                           size_t * destLen,
2640                           const Bytef * source,
2641                           uLong sourceLen,     
2642                           int level)
2643 {
2644         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2645
2646         /* write gzip header */
2647         snprintf((char *) dest, *destLen, 
2648                  "%c%c%c%c%c%c%c%c%c%c",
2649                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2650                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2651                  OS_CODE);
2652
2653         /* normal deflate */
2654         z_stream stream;
2655         int err;
2656         stream.next_in = (Bytef *) source;
2657         stream.avail_in = (uInt) sourceLen;
2658         stream.next_out = dest + 10L;   // after header
2659         stream.avail_out = (uInt) * destLen;
2660         if ((uLong) stream.avail_out != *destLen)
2661                 return Z_BUF_ERROR;
2662
2663         stream.zalloc = (alloc_func) 0;
2664         stream.zfree = (free_func) 0;
2665         stream.opaque = (voidpf) 0;
2666
2667         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2668                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2669         if (err != Z_OK)
2670                 return err;
2671
2672         err = deflate(&stream, Z_FINISH);
2673         if (err != Z_STREAM_END) {
2674                 deflateEnd(&stream);
2675                 return err == Z_OK ? Z_BUF_ERROR : err;
2676         }
2677         *destLen = stream.total_out + 10L;
2678
2679         /* write CRC and Length */
2680         uLong crc = crc32(0L, source, sourceLen);
2681         int n;
2682         for (n = 0; n < 4; ++n, ++*destLen) {
2683                 dest[*destLen] = (int) (crc & 0xff);
2684                 crc >>= 8;
2685         }
2686         uLong len = stream.total_in;
2687         for (n = 0; n < 4; ++n, ++*destLen) {
2688                 dest[*destLen] = (int) (len & 0xff);
2689                 len >>= 8;
2690         }
2691         err = deflateEnd(&stream);
2692         return err;
2693 }
2694 #endif
2695
2696
2697 /**
2698  * @ingroup StrBuf_DeEnCoder
2699  * @brief compress the buffer with gzip
2700  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2701  * @param Buf buffer whose content is to be gzipped
2702  */
2703 int CompressBuffer(StrBuf *Buf)
2704 {
2705 #ifdef HAVE_ZLIB
2706         char *compressed_data = NULL;
2707         size_t compressed_len, bufsize;
2708         int i = 0;
2709
2710         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
2711         compressed_data = malloc(compressed_len);
2712         
2713         if (compressed_data == NULL)
2714                 return -1;
2715         /* Flush some space after the used payload so valgrind shuts up... */
2716         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2717                 Buf->buf[Buf->BufUsed + i++] = '\0';
2718         if (compress_gzip((Bytef *) compressed_data,
2719                           &compressed_len,
2720                           (Bytef *) Buf->buf,
2721                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2722                 if (!Buf->ConstBuf)
2723                         free(Buf->buf);
2724                 Buf->buf = compressed_data;
2725                 Buf->BufUsed = compressed_len;
2726                 Buf->BufSize = bufsize;
2727                 /* Flush some space after the used payload so valgrind shuts up... */
2728                 i = 0;
2729                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2730                         Buf->buf[Buf->BufUsed + i++] = '\0';
2731                 return 1;
2732         } else {
2733                 free(compressed_data);
2734         }
2735 #endif  /* HAVE_ZLIB */
2736         return 0;
2737 }
2738
2739 /**
2740  * @ingroup StrBuf_DeEnCoder
2741  * @brief decode a buffer from base 64 encoding; destroys original
2742  * @param Buf Buffor to transform
2743  */
2744 int StrBufDecodeBase64(StrBuf *Buf)
2745 {
2746         char *xferbuf;
2747         size_t siz;
2748         if (Buf == NULL) return -1;
2749
2750         xferbuf = (char*) malloc(Buf->BufSize);
2751         siz = CtdlDecodeBase64(xferbuf,
2752                                Buf->buf,
2753                                Buf->BufUsed);
2754         free(Buf->buf);
2755         Buf->buf = xferbuf;
2756         Buf->BufUsed = siz;
2757         return siz;
2758 }
2759
2760 /**
2761  * @ingroup StrBuf_DeEnCoder
2762  * @brief decode a buffer from base 64 encoding; destroys original
2763  * @param Buf Buffor to transform
2764  */
2765 int StrBufDecodeHex(StrBuf *Buf)
2766 {
2767         unsigned int ch;
2768         char *pch, *pche, *pchi;
2769
2770         if (Buf == NULL) return -1;
2771
2772         pch = pchi = Buf->buf;
2773         pche = pch + Buf->BufUsed;
2774
2775         while (pchi < pche){
2776                 ch = decode_hex(pchi);
2777                 *pch = ch;
2778                 pch ++;
2779                 pchi += 2;
2780         }
2781
2782         *pch = '\0';
2783         Buf->BufUsed = pch - Buf->buf;
2784         return Buf->BufUsed;
2785 }
2786
2787 /**
2788  * @ingroup StrBuf_DeEnCoder
2789  * @brief replace all chars >0x20 && < 0x7F with Mute
2790  * @param Mute char to put over invalid chars
2791  * @param Buf Buffor to transform
2792  */
2793 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2794 {
2795         unsigned char *pch;
2796
2797         if (Buf == NULL) return -1;
2798         pch = (unsigned char *)Buf->buf;
2799         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2800                 if ((*pch < 0x20) || (*pch > 0x7F))
2801                         *pch = Mute;
2802                 pch ++;
2803         }
2804         return Buf->BufUsed;
2805 }
2806
2807
2808 /**
2809  * @ingroup StrBuf_DeEnCoder
2810  * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2811  * @param Buf Buffer to translate
2812  * @param StripBlanks Reduce several blanks to one?
2813  */
2814 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2815 {
2816         int a, b;
2817         char hex[3];
2818         long len;
2819
2820         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2821                 Buf->buf[Buf->BufUsed - 1] = '\0';
2822                 Buf->BufUsed --;
2823         }
2824
2825         a = 0; 
2826         while (a < Buf->BufUsed) {
2827                 if (Buf->buf[a] == '+')
2828                         Buf->buf[a] = ' ';
2829                 else if (Buf->buf[a] == '%') {
2830                         /* don't let % chars through, rather truncate the input. */
2831                         if (a + 2 > Buf->BufUsed) {
2832                                 Buf->buf[a] = '\0';
2833                                 Buf->BufUsed = a;
2834                         }
2835                         else {                  
2836                                 hex[0] = Buf->buf[a + 1];
2837                                 hex[1] = Buf->buf[a + 2];
2838                                 hex[2] = 0;
2839                                 b = 0;
2840                                 sscanf(hex, "%02x", &b);
2841                                 Buf->buf[a] = (char) b;
2842                                 len = Buf->BufUsed - a - 2;
2843                                 if (len > 0)
2844                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2845                         
2846                                 Buf->BufUsed -=2;
2847                         }
2848                 }
2849                 a++;
2850         }
2851         return a;
2852 }
2853
2854
2855 /**
2856  * @ingroup StrBuf_DeEnCoder
2857  * @brief       RFC2047-encode a header field if necessary.
2858  *              If no non-ASCII characters are found, the string
2859  *              will be copied verbatim without encoding.
2860  *
2861  * @param       target          Target buffer.
2862  * @param       source          Source string to be encoded.
2863  * @returns     encoded length; -1 if non success.
2864  */
2865 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2866 {
2867         const char headerStr[] = "=?UTF-8?Q?";
2868         int need_to_encode = 0;
2869         int i = 0;
2870         unsigned char ch;
2871
2872         if ((source == NULL) || 
2873             (target == NULL))
2874             return -1;
2875
2876         while ((i < source->BufUsed) &&
2877                (!IsEmptyStr (&source->buf[i])) &&
2878                (need_to_encode == 0)) {
2879                 if (((unsigned char) source->buf[i] < 32) || 
2880                     ((unsigned char) source->buf[i] > 126)) {
2881                         need_to_encode = 1;
2882                 }
2883                 i++;
2884         }
2885
2886         if (!need_to_encode) {
2887                 if (*target == NULL) {
2888                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2889                 }
2890                 else {
2891                         FlushStrBuf(*target);
2892                         StrBufAppendBuf(*target, source, 0);
2893                 }
2894                 return (*target)->BufUsed;
2895         }
2896         if (*target == NULL)
2897                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2898         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2899                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2900         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2901         (*target)->BufUsed = sizeof(headerStr) - 1;
2902         for (i=0; (i < source->BufUsed); ++i) {
2903                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2904                         IncreaseBuf(*target, 1, 0);
2905                 ch = (unsigned char) source->buf[i];
2906                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2907                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2908                         (*target)->BufUsed += 3;
2909                 }
2910                 else {
2911                         (*target)->buf[(*target)->BufUsed] = ch;
2912                         (*target)->BufUsed++;
2913                 }
2914         }
2915         
2916         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2917                 IncreaseBuf(*target, 1, 0);
2918
2919         (*target)->buf[(*target)->BufUsed++] = '?';
2920         (*target)->buf[(*target)->BufUsed++] = '=';
2921         (*target)->buf[(*target)->BufUsed] = '\0';
2922         return (*target)->BufUsed;;
2923 }
2924
2925 /**
2926  * @ingroup StrBuf
2927  * @brief replaces all occurances of 'search' by 'replace'
2928  * @param buf Buffer to modify
2929  * @param search character to search
2930  * @param replace character to replace search by
2931  */
2932 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2933 {
2934         long i;
2935         if (buf == NULL)
2936                 return;
2937         for (i=0; i<buf->BufUsed; i++)
2938                 if (buf->buf[i] == search)
2939                         buf->buf[i] = replace;
2940
2941 }
2942
2943
2944
2945 /**
2946  * @ingroup StrBuf_DeEnCoder
2947  * @brief Wrapper around iconv_open()
2948  * Our version adds aliases for non-standard Microsoft charsets
2949  * such as 'MS950', aliasing them to names like 'CP950'
2950  *
2951  * @param tocode        Target encoding
2952  * @param fromcode      Source encoding
2953  * @param pic           anonimized pointer to iconv struct
2954  */
2955 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2956 {
2957 #ifdef HAVE_ICONV
2958         iconv_t ic = (iconv_t)(-1) ;
2959         ic = iconv_open(tocode, fromcode);
2960         if (ic == (iconv_t)(-1) ) {
2961                 char alias_fromcode[64];
2962                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2963                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2964                         alias_fromcode[0] = 'C';
2965                         alias_fromcode[1] = 'P';
2966                         ic = iconv_open(tocode, alias_fromcode);
2967                 }
2968         }
2969         *(iconv_t *)pic = ic;
2970 #endif
2971 }
2972
2973
2974 /**
2975  * @ingroup StrBuf_DeEnCoder
2976  * @brief find one chunk of a RFC822 encoded string
2977  * @param Buffer where to search
2978  * @param bptr where to start searching
2979  * @returns found position, NULL if none.
2980  */
2981 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2982 {
2983         char * end;
2984         /* Find the next ?Q? */
2985         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2986                 return NULL;
2987
2988         end = strchr(bptr + 2, '?');
2989
2990         if (end == NULL)
2991                 return NULL;
2992
2993         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2994             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
2995             (*(end + 2) == '?')) {
2996                 /* skip on to the end of the cluster, the next ?= */
2997                 end = strstr(end + 3, "?=");
2998         }
2999         else
3000                 /* sort of half valid encoding, try to find an end. */
3001                 end = strstr(bptr, "?=");
3002         return end;
3003 }
3004
3005 /**
3006  * @ingroup StrBuf
3007  * @brief swaps the contents of two StrBufs
3008  * this is to be used to have cheap switched between a work-buffer and a target buffer 
3009  * @param A First one
3010  * @param B second one
3011  */
3012 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
3013 {
3014         StrBuf C;
3015
3016         memcpy(&C, A, sizeof(*A));
3017         memcpy(A, B, sizeof(*B));
3018         memcpy(B, &C, sizeof(C));
3019
3020 }
3021
3022
3023 /**
3024  * @ingroup StrBuf_DeEnCoder
3025  * @brief convert one buffer according to the preselected iconv pointer PIC
3026  * @param ConvertBuf buffer we need to translate
3027  * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3028  * @param pic Pointer to the iconv-session Object
3029  */
3030 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
3031 {
3032 #ifdef HAVE_ICONV
3033         long trycount = 0;
3034         size_t siz;
3035         iconv_t ic;
3036         char *ibuf;                     /**< Buffer of characters to be converted */
3037         char *obuf;                     /**< Buffer for converted characters */
3038         size_t ibuflen;                 /**< Length of input buffer */
3039         size_t obuflen;                 /**< Length of output buffer */
3040
3041
3042         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3043         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3044                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3045 TRYAGAIN:
3046         ic = *(iconv_t*)pic;
3047         ibuf = ConvertBuf->buf;
3048         ibuflen = ConvertBuf->BufUsed;
3049         obuf = TmpBuf->buf;
3050         obuflen = TmpBuf->BufSize;
3051         
3052         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3053
3054         if (siz < 0) {
3055                 if (errno == E2BIG) {
3056                         trycount ++;                    
3057                         IncreaseBuf(TmpBuf, 0, 0);
3058                         if (trycount < 5) 
3059                                 goto TRYAGAIN;
3060
3061                 }
3062                 else if (errno == EILSEQ){ 
3063                         /* hm, invalid utf8 sequence... what to do now? */
3064                         /* An invalid multibyte sequence has been encountered in the input */
3065                 }
3066                 else if (errno == EINVAL) {
3067                         /* An incomplete multibyte sequence has been encountered in the input. */
3068                 }
3069
3070                 FlushStrBuf(TmpBuf);
3071         }
3072         else {
3073                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3074                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3075                 
3076                 /* little card game: wheres the red lady? */
3077                 SwapBuffers(ConvertBuf, TmpBuf);
3078                 FlushStrBuf(TmpBuf);
3079         }
3080 #endif
3081 }
3082
3083
3084 /**
3085  * @ingroup StrBuf_DeEnCoder
3086  * @brief catches one RFC822 encoded segment, and decodes it.
3087  * @param Target buffer to fill with result
3088  * @param DecodeMe buffer with stuff to process
3089  * @param SegmentStart points to our current segment in DecodeMe
3090  * @param SegmentEnd Points to the end of our current segment in DecodeMe
3091  * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3092  * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3093  * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3094  */
3095 inline static void DecodeSegment(StrBuf *Target, 
3096                                  const StrBuf *DecodeMe, 
3097                                  char *SegmentStart, 
3098                                  char *SegmentEnd, 
3099                                  StrBuf *ConvertBuf,
3100                                  StrBuf *ConvertBuf2, 
3101                                  StrBuf *FoundCharset)
3102 {
3103         StrBuf StaticBuf;
3104         char charset[128];
3105         char encoding[16];
3106 #ifdef HAVE_ICONV
3107         iconv_t ic = (iconv_t)(-1);
3108 #else
3109         void *ic = NULL;
3110 #endif
3111         /* Now we handle foreign character sets properly encoded
3112          * in RFC2047 format.
3113          */
3114         StaticBuf.buf = SegmentStart;
3115         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3116         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3117         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3118         if (FoundCharset != NULL) {
3119                 FlushStrBuf(FoundCharset);
3120                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3121         }
3122         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3123         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3124         
3125         *encoding = toupper(*encoding);
3126         if (*encoding == 'B') { /**< base64 */
3127                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
3128                                                         ConvertBuf->buf, 
3129                                                         ConvertBuf->BufUsed);
3130         }
3131         else if (*encoding == 'Q') {    /**< quoted-printable */
3132                 long pos;
3133                 
3134                 pos = 0;
3135                 while (pos < ConvertBuf->BufUsed)
3136                 {
3137                         if (ConvertBuf->buf[pos] == '_') 
3138                                 ConvertBuf->buf[pos] = ' ';
3139                         pos++;
3140                 }
3141                 
3142                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3143                         ConvertBuf2->buf, 
3144                         ConvertBuf->buf,
3145                         ConvertBuf->BufUsed);
3146         }
3147         else {
3148                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3149         }
3150 #ifdef HAVE_ICONV
3151         ctdl_iconv_open("UTF-8", charset, &ic);
3152         if (ic != (iconv_t)(-1) ) {             
3153 #endif
3154                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3155                 StrBufAppendBuf(Target, ConvertBuf2, 0);
3156 #ifdef HAVE_ICONV
3157                 iconv_close(ic);
3158         }
3159         else {
3160                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3161         }
3162 #endif
3163 }
3164
3165 /**
3166  * @ingroup StrBuf_DeEnCoder
3167  * @brief Handle subjects with RFC2047 encoding such as:
3168  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3169  * @param Target where to put the decoded string to 
3170  * @param DecodeMe buffer with encoded string
3171  * @param DefaultCharset if we don't find one, which should we use?
3172  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3173  *        put it here for later use where no string might be known.
3174  */
3175 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3176 {
3177         StrBuf *DecodedInvalidBuf = NULL;
3178         StrBuf *ConvertBuf, *ConvertBuf2;
3179         const StrBuf *DecodeMee = DecodeMe;
3180         char *start, *end, *next, *nextend, *ptr = NULL;
3181 #ifdef HAVE_ICONV
3182         iconv_t ic = (iconv_t)(-1) ;
3183 #endif
3184         const char *eptr;
3185         int passes = 0;
3186         int i, len, delta;
3187         int illegal_non_rfc2047_encoding = 0;
3188
3189         /* Sometimes, badly formed messages contain strings which were simply
3190          *  written out directly in some foreign character set instead of
3191          *  using RFC2047 encoding.  This is illegal but we will attempt to
3192          *  handle it anyway by converting from a user-specified default
3193          *  charset to UTF-8 if we see any nonprintable characters.
3194          */
3195         
3196         len = StrLength(DecodeMe);
3197         for (i=0; i<DecodeMe->BufUsed; ++i) {
3198                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3199                         illegal_non_rfc2047_encoding = 1;
3200                         break;
3201                 }
3202         }
3203
3204         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3205         if ((illegal_non_rfc2047_encoding) &&
3206             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
3207             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3208         {
3209 #ifdef HAVE_ICONV
3210                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3211                 if (ic != (iconv_t)(-1) ) {
3212                         DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3213                         StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3214                         DecodeMee = DecodedInvalidBuf;
3215                         iconv_close(ic);
3216                 }
3217 #endif
3218         }
3219
3220         /* pre evaluate the first pair */
3221         nextend = end = NULL;
3222         len = StrLength(DecodeMee);
3223         start = strstr(DecodeMee->buf, "=?");
3224         eptr = DecodeMee->buf + DecodeMee->BufUsed;
3225         if (start != NULL) 
3226                 end = FindNextEnd (DecodeMee, start);
3227         else {
3228                 StrBufAppendBuf(Target, DecodeMee, 0);
3229                 FreeStrBuf(&ConvertBuf);
3230                 FreeStrBuf(&DecodedInvalidBuf);
3231                 return;
3232         }
3233
3234         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3235
3236         if (start != DecodeMee->buf) {
3237                 long nFront;
3238                 
3239                 nFront = start - DecodeMee->buf;
3240                 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3241                 len -= nFront;
3242         }
3243         /*
3244          * Since spammers will go to all sorts of absurd lengths to get their
3245          * messages through, there are LOTS of corrupt headers out there.
3246          * So, prevent a really badly formed RFC2047 header from throwing
3247          * this function into an infinite loop.
3248          */
3249         while ((start != NULL) && 
3250                (end != NULL) && 
3251                (start < eptr) && 
3252                (end < eptr) && 
3253                (passes < 20))
3254         {
3255                 passes++;
3256                 DecodeSegment(Target, 
3257                               DecodeMee, 
3258                               start, 
3259                               end, 
3260                               ConvertBuf,
3261                               ConvertBuf2,
3262                               FoundCharset);
3263                 
3264                 next = strstr(end, "=?");
3265                 nextend = NULL;
3266                 if ((next != NULL) && 
3267                     (next < eptr))
3268                         nextend = FindNextEnd(DecodeMee, next);
3269                 if (nextend == NULL)
3270                         next = NULL;
3271
3272                 /* did we find two partitions */
3273                 if ((next != NULL) && 
3274                     ((next - end) > 2))
3275                 {
3276                         ptr = end + 2;
3277                         while ((ptr < next) && 
3278                                (isspace(*ptr) ||
3279                                 (*ptr == '\r') ||
3280                                 (*ptr == '\n') || 
3281                                 (*ptr == '\t')))
3282                                 ptr ++;
3283                         /* did we find a gab just filled with blanks? */
3284                         if (ptr == next)
3285                         {
3286                                 long gap = next - start;
3287                                 memmove (end + 2,
3288                                          next,
3289                                          len - (gap));
3290                                 len -= gap;
3291                                 /* now terminate the gab at the end */
3292                                 delta = (next - end) - 2; ////TODO: const! 
3293                                 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3294                                 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3295
3296                                 /* move next to its new location. */
3297                                 next -= delta;
3298                                 nextend -= delta;
3299                         }
3300                 }
3301                 /* our next-pair is our new first pair now. */
3302                 ptr = end + 2;
3303                 start = next;
3304                 end = nextend;
3305         }
3306         end = ptr;
3307         nextend = DecodeMee->buf + DecodeMee->BufUsed;
3308         if ((end != NULL) && (end < nextend)) {
3309                 ptr = end;
3310                 while ( (ptr < nextend) &&
3311                         (isspace(*ptr) ||
3312                          (*ptr == '\r') ||
3313                          (*ptr == '\n') || 
3314                          (*ptr == '\t')))
3315                         ptr ++;
3316                 if (ptr < nextend)
3317                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
3318         }
3319         FreeStrBuf(&ConvertBuf);
3320         FreeStrBuf(&ConvertBuf2);
3321         FreeStrBuf(&DecodedInvalidBuf);
3322 }
3323
3324 /**
3325  * @ingroup StrBuf
3326  * @brief evaluate the length of an utf8 special character sequence
3327  * @param Char the character to examine
3328  * @returns width of utf8 chars in bytes
3329  */
3330 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3331 {
3332         int n = 1;
3333         char test = (1<<7);
3334         
3335         while ((n < 8) && ((test & *CharS) != 0)) {
3336                 test = test << 1;
3337                 n ++;
3338         }
3339         if ((n > 6) || ((CharE - CharS) > n))
3340                 n = 1;
3341         return n;
3342 }
3343
3344 /**
3345  * @ingroup StrBuf
3346  * @brief detect whether this char starts an utf-8 encoded char
3347  * @param Char character to inspect
3348  * @returns yes or no
3349  */
3350 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3351 {
3352 /** 11??.???? indicates an UTF8 Sequence. */
3353         return ((Char & 0xC0) != 0);
3354 }
3355
3356 /**
3357  * @ingroup StrBuf
3358  * @brief measure the number of glyphs in an UTF8 string...
3359  * @param Buf string to measure
3360  * @returns the number of glyphs in Buf
3361  */
3362 long StrBuf_Utf8StrLen(StrBuf *Buf)
3363 {
3364         int n = 0;
3365         int m = 0;
3366         char *aptr, *eptr;
3367
3368         if ((Buf == NULL) || (Buf->BufUsed == 0))
3369                 return 0;
3370         aptr = Buf->buf;
3371         eptr = Buf->buf + Buf->BufUsed;
3372         while ((aptr < eptr) && (*aptr != '\0')) {
3373                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3374                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3375                         while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3376                                 n ++;
3377                 }
3378                 else {
3379                         n++;
3380                         aptr++;
3381                 }
3382                         
3383         }
3384         return n;
3385 }
3386
3387 /**
3388  * @ingroup StrBuf
3389  * @brief cuts a string after maxlen glyphs
3390  * @param Buf string to cut to maxlen glyphs
3391  * @param maxlen how long may the string become?
3392  * @returns current length of the string
3393  */
3394 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3395 {
3396         char *aptr, *eptr;
3397         int n = 0, m = 0;
3398
3399         aptr = Buf->buf;
3400         eptr = Buf->buf + Buf->BufUsed;
3401         while ((aptr < eptr) && (*aptr != '\0')) {
3402                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3403                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3404                         while ((m-- > 0) && (*aptr++ != '\0'))
3405                                 n ++;
3406                 }
3407                 else {
3408                         n++;
3409                         aptr++;
3410                 }
3411                 if (n > maxlen) {
3412                         *aptr = '\0';
3413                         Buf->BufUsed = aptr - Buf->buf;
3414                         return Buf->BufUsed;
3415                 }                       
3416         }
3417         return Buf->BufUsed;
3418
3419 }
3420
3421
3422 /**
3423  * @ingroup StrBuf
3424  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3425  * @param LineBuf your line will be copied here.
3426  * @param Buf BLOB with lines of text...
3427  * @param Ptr moved arround to keep the next-line across several iterations
3428  *        has to be &NULL on start; will be &NotNULL on end of buffer
3429  * @returns size of copied buffer
3430  */
3431 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3432 {
3433         const char *aptr, *ptr, *eptr;
3434         char *optr, *xptr;
3435
3436         if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3437                 *Ptr = StrBufNOTNULL;
3438                 return 0;
3439         }
3440
3441         FlushStrBuf(LineBuf);
3442         if (*Ptr==NULL)
3443                 ptr = aptr = Buf->buf;
3444         else
3445                 ptr = aptr = *Ptr;
3446
3447         optr = LineBuf->buf;
3448         eptr = Buf->buf + Buf->BufUsed;
3449         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3450
3451         while ((ptr <= eptr) && 
3452                (*ptr != '\n') &&
3453                (*ptr != '\r') )
3454         {
3455                 *optr = *ptr;
3456                 optr++; ptr++;
3457                 if (optr == xptr) {
3458                         LineBuf->BufUsed = optr - LineBuf->buf;
3459                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
3460                         optr = LineBuf->buf + LineBuf->BufUsed;
3461                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3462                 }
3463         }
3464
3465         if ((ptr >= eptr) && (optr > LineBuf->buf))
3466                 optr --;
3467         LineBuf->BufUsed = optr - LineBuf->buf;
3468         *optr = '\0';       
3469         if ((ptr <= eptr) && (*ptr == '\r'))
3470                 ptr ++;
3471         if ((ptr <= eptr) && (*ptr == '\n'))
3472                 ptr ++;
3473         
3474         if (ptr < eptr) {
3475                 *Ptr = ptr;
3476         }
3477         else {
3478                 *Ptr = StrBufNOTNULL;
3479         }
3480
3481         return Buf->BufUsed - (ptr - Buf->buf);
3482 }