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