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