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