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