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