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