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