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