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