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