]> code.citadel.org Git - citadel.git/blob - libcitadel/lib/stringbuf.c
175abbc57a110f30dc76d5a40155f3a68006567d
[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  */
1823 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1824 {
1825         const char *pch, *pche;
1826         char *pt, *pte;
1827         int len;
1828         
1829         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1830                 return;
1831         if (PlainIn != NULL) {
1832                 len = strlen(PlainIn);
1833                 pch = PlainIn;
1834                 pche = pch + len;
1835         }
1836         else {
1837                 pch = In->buf;
1838                 pche = pch + In->BufUsed;
1839                 len = In->BufUsed;
1840         }
1841
1842         if (len == 0) 
1843                 return;
1844
1845         pt = OutBuf->buf + OutBuf->BufUsed;
1846         pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1847
1848         while (pch < pche) {
1849                 if (pt >= pte) {
1850                         IncreaseBuf(OutBuf, 1, -1);
1851                         pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1852                         pt = OutBuf->buf + OutBuf->BufUsed;
1853                 }
1854
1855                 *pt = HexList[(unsigned char)*pch][0];
1856                 pt ++;
1857                 *pt = HexList[(unsigned char)*pch][1];
1858                 pt ++; pch ++; OutBuf->BufUsed += 2;
1859         }
1860         *pt = '\0';
1861 }
1862
1863 /**
1864  * @ingroup StrBuf_DeEnCoder
1865  * @brief Append a string, escaping characters which have meaning in HTML.  
1866  *
1867  * @param Target        target buffer
1868  * @param Source        source buffer; set to NULL if you just have a C-String
1869  * @param PlainIn       Plain-C string to append; set to NULL if unused
1870  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
1871  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
1872  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
1873  */
1874 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1875 {
1876         const char *aptr, *eiptr;
1877         char *bptr, *eptr;
1878         long len;
1879
1880         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1881                 return -1;
1882
1883         if (PlainIn != NULL) {
1884                 aptr = PlainIn;
1885                 len = strlen(PlainIn);
1886                 eiptr = aptr + len;
1887         }
1888         else {
1889                 aptr = Source->buf;
1890                 eiptr = aptr + Source->BufUsed;
1891                 len = Source->BufUsed;
1892         }
1893
1894         if (len == 0) 
1895                 return -1;
1896
1897         bptr = Target->buf + Target->BufUsed;
1898         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1899
1900         while (aptr < eiptr){
1901                 if(bptr >= eptr) {
1902                         IncreaseBuf(Target, 1, -1);
1903                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1904                         bptr = Target->buf + Target->BufUsed;
1905                 }
1906                 if (*aptr == '<') {
1907                         memcpy(bptr, "&lt;", 4);
1908                         bptr += 4;
1909                         Target->BufUsed += 4;
1910                 }
1911                 else if (*aptr == '>') {
1912                         memcpy(bptr, "&gt;", 4);
1913                         bptr += 4;
1914                         Target->BufUsed += 4;
1915                 }
1916                 else if (*aptr == '&') {
1917                         memcpy(bptr, "&amp;", 5);
1918                         bptr += 5;
1919                         Target->BufUsed += 5;
1920                 }
1921                 else if (*aptr == '"') {
1922                         memcpy(bptr, "&quot;", 6);
1923                         bptr += 6;
1924                         Target->BufUsed += 6;
1925                 }
1926                 else if (*aptr == '\'') {
1927                         memcpy(bptr, "&#39;", 5);
1928                         bptr += 5;
1929                         Target->BufUsed += 5;
1930                 }
1931                 else if (*aptr == LB) {
1932                         *bptr = '<';
1933                         bptr ++;
1934                         Target->BufUsed ++;
1935                 }
1936                 else if (*aptr == RB) {
1937                         *bptr = '>';
1938                         bptr ++;
1939                         Target->BufUsed ++;
1940                 }
1941                 else if (*aptr == QU) {
1942                         *bptr ='"';
1943                         bptr ++;
1944                         Target->BufUsed ++;
1945                 }
1946                 else if ((*aptr == 32) && (nbsp == 1)) {
1947                         memcpy(bptr, "&nbsp;", 6);
1948                         bptr += 6;
1949                         Target->BufUsed += 6;
1950                 }
1951                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1952                         *bptr='\0';     /* nothing */
1953                 }
1954                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1955                         memcpy(bptr, "&lt;br/&gt;", 11);
1956                         bptr += 11;
1957                         Target->BufUsed += 11;
1958                 }
1959
1960
1961                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1962                         *bptr='\0';     /* nothing */
1963                 }
1964                 else{
1965                         *bptr = *aptr;
1966                         bptr++;
1967                         Target->BufUsed ++;
1968                 }
1969                 aptr ++;
1970         }
1971         *bptr = '\0';
1972         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1973                 return -1;
1974         return Target->BufUsed;
1975 }
1976
1977 /**
1978  * @ingroup StrBuf_DeEnCoder
1979  * @brief Append a string, escaping characters which have meaning in HTML.  
1980  * Converts linebreaks into blanks; escapes single quotes
1981  * @param Target        target buffer
1982  * @param Source        source buffer; set to NULL if you just have a C-String
1983  * @param PlainIn       Plain-C string to append; set to NULL if unused
1984  */
1985 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1986 {
1987         const char *aptr, *eiptr;
1988         char *tptr, *eptr;
1989         long len;
1990
1991         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1992                 return ;
1993
1994         if (PlainIn != NULL) {
1995                 aptr = PlainIn;
1996                 len = strlen(PlainIn);
1997                 eiptr = aptr + len;
1998         }
1999         else {
2000                 aptr = Source->buf;
2001                 eiptr = aptr + Source->BufUsed;
2002                 len = Source->BufUsed;
2003         }
2004
2005         if (len == 0) 
2006                 return;
2007
2008         eptr = Target->buf + Target->BufSize - 8; 
2009         tptr = Target->buf + Target->BufUsed;
2010         
2011         while (aptr < eiptr){
2012                 if(tptr >= eptr) {
2013                         IncreaseBuf(Target, 1, -1);
2014                         eptr = Target->buf + Target->BufSize - 8; 
2015                         tptr = Target->buf + Target->BufUsed;
2016                 }
2017                
2018                 if (*aptr == '\n') {
2019                         *tptr = ' ';
2020                         Target->BufUsed++;
2021                 }
2022                 else if (*aptr == '\r') {
2023                         *tptr = ' ';
2024                         Target->BufUsed++;
2025                 }
2026                 else if (*aptr == '\'') {
2027                         *(tptr++) = '&';
2028                         *(tptr++) = '#';
2029                         *(tptr++) = '3';
2030                         *(tptr++) = '9';
2031                         *tptr = ';';
2032                         Target->BufUsed += 5;
2033                 } else {
2034                         *tptr = *aptr;
2035                         Target->BufUsed++;
2036                 }
2037                 tptr++; aptr++;
2038         }
2039         *tptr = '\0';
2040 }
2041
2042
2043
2044 /**
2045  * @ingroup StrBuf_DeEnCoder
2046  * @brief Append a string, escaping characters which have meaning in ICAL.  
2047  * [\n,] 
2048  * @param Target        target buffer
2049  * @param Source        source buffer; set to NULL if you just have a C-String
2050  * @param PlainIn       Plain-C string to append; set to NULL if unused
2051  */
2052 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2053 {
2054         const char *aptr, *eiptr;
2055         char *tptr, *eptr;
2056         long len;
2057
2058         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2059                 return ;
2060
2061         if (PlainIn != NULL) {
2062                 aptr = PlainIn;
2063                 len = strlen(PlainIn);
2064                 eiptr = aptr + len;
2065         }
2066         else {
2067                 aptr = Source->buf;
2068                 eiptr = aptr + Source->BufUsed;
2069                 len = Source->BufUsed;
2070         }
2071
2072         if (len == 0) 
2073                 return;
2074
2075         eptr = Target->buf + Target->BufSize - 8; 
2076         tptr = Target->buf + Target->BufUsed;
2077         
2078         while (aptr < eiptr){
2079                 if(tptr + 3 >= eptr) {
2080                         IncreaseBuf(Target, 1, -1);
2081                         eptr = Target->buf + Target->BufSize - 8; 
2082                         tptr = Target->buf + Target->BufUsed;
2083                 }
2084                
2085                 if (*aptr == '\n') {
2086                         *tptr = '\\';
2087                         Target->BufUsed++;
2088                         tptr++;
2089                         *tptr = 'n';
2090                         Target->BufUsed++;
2091                 }
2092                 else if (*aptr == '\r') {
2093                         *tptr = '\\';
2094                         Target->BufUsed++;
2095                         tptr++;
2096                         *tptr = 'r';
2097                         Target->BufUsed++;
2098                 }
2099                 else if (*aptr == ',') {
2100                         *tptr = '\\';
2101                         Target->BufUsed++;
2102                         tptr++;
2103                         *tptr = ',';
2104                         Target->BufUsed++;
2105                 } else {
2106                         *tptr = *aptr;
2107                         Target->BufUsed++;
2108                 }
2109                 tptr++; aptr++;
2110         }
2111         *tptr = '\0';
2112 }
2113
2114 /**
2115  * @ingroup StrBuf_DeEnCoder
2116  * @brief Append a string, escaping characters which have meaning in JavaScript strings .  
2117  *
2118  * @param Target        target buffer
2119  * @param Source        source buffer; set to NULL if you just have a C-String
2120  * @param PlainIn       Plain-C string to append; set to NULL if unused
2121  * @returns size of result or -1
2122  */
2123 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2124 {
2125         const char *aptr, *eiptr;
2126         char *bptr, *eptr;
2127         long len;
2128
2129         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2130                 return -1;
2131
2132         if (PlainIn != NULL) {
2133                 aptr = PlainIn;
2134                 len = strlen(PlainIn);
2135                 eiptr = aptr + len;
2136         }
2137         else {
2138                 aptr = Source->buf;
2139                 eiptr = aptr + Source->BufUsed;
2140                 len = Source->BufUsed;
2141         }
2142
2143         if (len == 0) 
2144                 return -1;
2145
2146         bptr = Target->buf + Target->BufUsed;
2147         eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in...  */
2148
2149         while (aptr < eiptr){
2150                 if(bptr >= eptr) {
2151                         IncreaseBuf(Target, 1, -1);
2152                         eptr = Target->buf + Target->BufSize - 3; 
2153                         bptr = Target->buf + Target->BufUsed;
2154                 }
2155                 if (*aptr == '"') {
2156                         *bptr = '\\';
2157                         bptr ++;
2158                         *bptr = '"';
2159                         bptr ++;
2160                         Target->BufUsed += 2;
2161                 } else if (*aptr == '\\') {
2162                         *bptr = '\\';
2163                         bptr ++;
2164                         *bptr = '\\';
2165                         bptr ++;
2166                         Target->BufUsed += 2;
2167                 }
2168                 else{
2169                         *bptr = *aptr;
2170                         bptr++;
2171                         Target->BufUsed ++;
2172                 }
2173                 aptr ++;
2174         }
2175         *bptr = '\0';
2176         if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2177                 return -1;
2178         return Target->BufUsed;
2179 }
2180
2181 /**
2182  * @ingroup StrBuf_DeEnCoder
2183  * @brief Append a string, escaping characters which have meaning in HTML + json.  
2184  *
2185  * @param Target        target buffer
2186  * @param Source        source buffer; set to NULL if you just have a C-String
2187  * @param PlainIn       Plain-C string to append; set to NULL if unused
2188  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
2189  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
2190  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
2191  */
2192 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2193 {
2194         const char *aptr, *eiptr;
2195         char *bptr, *eptr;
2196         long len;
2197         int IsUtf8Sequence = 0;
2198
2199         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2200                 return -1;
2201
2202         if (PlainIn != NULL) {
2203                 aptr = PlainIn;
2204                 len = strlen(PlainIn);
2205                 eiptr = aptr + len;
2206         }
2207         else {
2208                 aptr = Source->buf;
2209                 eiptr = aptr + Source->BufUsed;
2210                 len = Source->BufUsed;
2211         }
2212
2213         if (len == 0) 
2214                 return -1;
2215
2216         bptr = Target->buf + Target->BufUsed;
2217         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
2218
2219         while (aptr < eiptr){
2220                 if(bptr >= eptr) {
2221                         IncreaseBuf(Target, 1, -1);
2222                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
2223                         bptr = Target->buf + Target->BufUsed;
2224                 }
2225                 if (*aptr == '<') {
2226                         memcpy(bptr, "&lt;", 4);
2227                         bptr += 4;
2228                         Target->BufUsed += 4;
2229                 }
2230                 else if (*aptr == '>') {
2231                         memcpy(bptr, "&gt;", 4);
2232                         bptr += 4;
2233                         Target->BufUsed += 4;
2234                 }
2235                 else if (*aptr == '&') {
2236                         memcpy(bptr, "&amp;", 5);
2237                         bptr += 5;
2238                         Target->BufUsed += 5;
2239                 }
2240                 else if (*aptr == LB) {
2241                         *bptr = '<';
2242                         bptr ++;
2243                         Target->BufUsed ++;
2244                 }
2245                 else if (*aptr == RB) {
2246                         *bptr = '>';
2247                         bptr ++;
2248                         Target->BufUsed ++;
2249                 }
2250                 else if ((*aptr == 32) && (nbsp == 1)) {
2251                         memcpy(bptr, "&nbsp;", 6);
2252                         bptr += 6;
2253                         Target->BufUsed += 6;
2254                 }
2255                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2256                         *bptr='\0';     /* nothing */
2257                 }
2258                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2259                         memcpy(bptr, "&lt;br/&gt;", 11);
2260                         bptr += 11;
2261                         Target->BufUsed += 11;
2262                 }
2263
2264                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2265                         *bptr='\0';     /* nothing */
2266                 }
2267
2268                 else if ((*aptr == '"') || (*aptr == QU)) {
2269                         *bptr = '\\';
2270                         bptr ++;
2271                         *bptr = '"';
2272                         bptr ++;
2273                         Target->BufUsed += 2;
2274                 } else if (*aptr == '\\') {
2275                         *bptr = '\\';
2276                         bptr ++;
2277                         *bptr = '\\';
2278                         bptr ++;
2279                         Target->BufUsed += 2;
2280                 }
2281                 else {
2282                         if (((unsigned char)*aptr) >= 0x20)
2283                         {
2284                                 IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2285
2286                                 *bptr = *aptr;
2287                                 Target->BufUsed ++;
2288                                 if (IsUtf8Sequence > 1) while (IsUtf8Sequence > 0){
2289                                                 if(bptr + IsUtf8Sequence >= 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 - 1;
2293                                                 }
2294                                         bptr++; aptr++;
2295                                                 IsUtf8Sequence --;
2296                                                 *bptr = *aptr;
2297                                                 Target->BufUsed ++;
2298                                         }
2299                                 bptr++;
2300                         }
2301
2302                 }
2303                 aptr ++;
2304         }
2305         *bptr = '\0';
2306         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2307                 return -1;
2308         return Target->BufUsed;
2309 }
2310
2311 /**
2312  * @ingroup StrBuf_DeEnCoder
2313  * @brief unhide special chars hidden to the HTML escaper
2314  * @param target buffer to put the unescaped string in
2315  * @param source buffer to unescape
2316  */
2317 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2318 {
2319         int a, b, len;
2320         char hex[3];
2321
2322         if (target != NULL)
2323                 FlushStrBuf(target);
2324
2325         if (source == NULL ||target == NULL)
2326         {
2327                 return;
2328         }
2329
2330         len = source->BufUsed;
2331         for (a = 0; a < len; ++a) {
2332                 if (target->BufUsed >= target->BufSize)
2333                         IncreaseBuf(target, 1, -1);
2334
2335                 if (source->buf[a] == '=') {
2336                         hex[0] = source->buf[a + 1];
2337                         hex[1] = source->buf[a + 2];
2338                         hex[2] = 0;
2339                         b = 0;
2340                         sscanf(hex, "%02x", &b);
2341                         target->buf[target->BufUsed] = b;
2342                         target->buf[++target->BufUsed] = 0;
2343                         a += 2;
2344                 }
2345                 else {
2346                         target->buf[target->BufUsed] = source->buf[a];
2347                         target->buf[++target->BufUsed] = 0;
2348                 }
2349         }
2350 }
2351
2352
2353 /**
2354  * @ingroup StrBuf_DeEnCoder
2355  * @brief hide special chars from the HTML escapers and friends
2356  * @param target buffer to put the escaped string in
2357  * @param source buffer to escape
2358  */
2359 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2360 {
2361         int i, len;
2362
2363         if (target != NULL)
2364                 FlushStrBuf(target);
2365
2366         if (source == NULL ||target == NULL)
2367         {
2368                 return;
2369         }
2370
2371         len = source->BufUsed;
2372         for (i=0; i<len; ++i) {
2373                 if (target->BufUsed + 4 >= target->BufSize)
2374                         IncreaseBuf(target, 1, -1);
2375                 if ( (isalnum(source->buf[i])) || 
2376                      (source->buf[i]=='-') || 
2377                      (source->buf[i]=='_') ) {
2378                         target->buf[target->BufUsed++] = source->buf[i];
2379                 }
2380                 else {
2381                         sprintf(&target->buf[target->BufUsed], 
2382                                 "=%02X", 
2383                                 (0xFF &source->buf[i]));
2384                         target->BufUsed += 3;
2385                 }
2386         }
2387         target->buf[target->BufUsed + 1] = '\0';
2388 }
2389
2390
2391 /*******************************************************************************
2392  *                      Quoted Printable de/encoding                           *
2393  *******************************************************************************/
2394
2395 /**
2396  * @ingroup StrBuf_DeEnCoder
2397  * @brief decode a buffer from base 64 encoding; destroys original
2398  * @param Buf Buffor to transform
2399  */
2400 int StrBufDecodeBase64(StrBuf *Buf)
2401 {
2402         char *xferbuf;
2403         size_t siz;
2404         if (Buf == NULL) return -1;
2405
2406         xferbuf = (char*) malloc(Buf->BufSize);
2407         *xferbuf = '\0';
2408         siz = CtdlDecodeBase64(xferbuf,
2409                                Buf->buf,
2410                                Buf->BufUsed);
2411         free(Buf->buf);
2412         Buf->buf = xferbuf;
2413         Buf->BufUsed = siz;
2414         return siz;
2415 }
2416
2417 /**
2418  * @ingroup StrBuf_DeEnCoder
2419  * @brief decode a buffer from base 64 encoding; destroys original
2420  * @param Buf Buffor to transform
2421  */
2422 int StrBufDecodeHex(StrBuf *Buf)
2423 {
2424         unsigned int ch;
2425         char *pch, *pche, *pchi;
2426
2427         if (Buf == NULL) return -1;
2428
2429         pch = pchi = Buf->buf;
2430         pche = pch + Buf->BufUsed;
2431
2432         while (pchi < pche){
2433                 ch = decode_hex(pchi);
2434                 *pch = ch;
2435                 pch ++;
2436                 pchi += 2;
2437         }
2438
2439         *pch = '\0';
2440         Buf->BufUsed = pch - Buf->buf;
2441         return Buf->BufUsed;
2442 }
2443
2444 /**
2445  * @ingroup StrBuf_DeEnCoder
2446  * @brief replace all chars >0x20 && < 0x7F with Mute
2447  * @param Mute char to put over invalid chars
2448  * @param Buf Buffor to transform
2449  */
2450 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2451 {
2452         unsigned char *pch;
2453
2454         if (Buf == NULL) return -1;
2455         pch = (unsigned char *)Buf->buf;
2456         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2457                 if ((*pch < 0x20) || (*pch > 0x7F))
2458                         *pch = Mute;
2459                 pch ++;
2460         }
2461         return Buf->BufUsed;
2462 }
2463
2464
2465 /**
2466  * @ingroup StrBuf_DeEnCoder
2467  * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2468  * @param Buf Buffer to translate
2469  * @param StripBlanks Reduce several blanks to one?
2470  */
2471 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2472 {
2473         int a, b;
2474         char hex[3];
2475         long len;
2476
2477         if (Buf == NULL)
2478                 return -1;
2479
2480         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2481                 Buf->buf[Buf->BufUsed - 1] = '\0';
2482                 Buf->BufUsed --;
2483         }
2484
2485         a = 0; 
2486         while (a < Buf->BufUsed) {
2487                 if (Buf->buf[a] == '+')
2488                         Buf->buf[a] = ' ';
2489                 else if (Buf->buf[a] == '%') {
2490                         /* don't let % chars through, rather truncate the input. */
2491                         if (a + 2 > Buf->BufUsed) {
2492                                 Buf->buf[a] = '\0';
2493                                 Buf->BufUsed = a;
2494                         }
2495                         else {                  
2496                                 hex[0] = Buf->buf[a + 1];
2497                                 hex[1] = Buf->buf[a + 2];
2498                                 hex[2] = 0;
2499                                 b = 0;
2500                                 sscanf(hex, "%02x", &b);
2501                                 Buf->buf[a] = (char) b;
2502                                 len = Buf->BufUsed - a - 2;
2503                                 if (len > 0)
2504                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2505                         
2506                                 Buf->BufUsed -=2;
2507                         }
2508                 }
2509                 a++;
2510         }
2511         return a;
2512 }
2513
2514
2515 /**
2516  * @ingroup StrBuf_DeEnCoder
2517  * @brief       RFC2047-encode a header field if necessary.
2518  *              If no non-ASCII characters are found, the string
2519  *              will be copied verbatim without encoding.
2520  *
2521  * @param       target          Target buffer.
2522  * @param       source          Source string to be encoded.
2523  * @returns     encoded length; -1 if non success.
2524  */
2525 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2526 {
2527         const char headerStr[] = "=?UTF-8?Q?";
2528         int need_to_encode = 0;
2529         int i = 0;
2530         unsigned char ch;
2531
2532         if ((source == NULL) || 
2533             (target == NULL))
2534             return -1;
2535
2536         while ((i < source->BufUsed) &&
2537                (!IsEmptyStr (&source->buf[i])) &&
2538                (need_to_encode == 0)) {
2539                 if (((unsigned char) source->buf[i] < 32) || 
2540                     ((unsigned char) source->buf[i] > 126)) {
2541                         need_to_encode = 1;
2542                 }
2543                 i++;
2544         }
2545
2546         if (!need_to_encode) {
2547                 if (*target == NULL) {
2548                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2549                 }
2550                 else {
2551                         FlushStrBuf(*target);
2552                         StrBufAppendBuf(*target, source, 0);
2553                 }
2554                 return (*target)->BufUsed;
2555         }
2556         if (*target == NULL)
2557                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2558         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2559                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2560         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2561         (*target)->BufUsed = sizeof(headerStr) - 1;
2562         for (i=0; (i < source->BufUsed); ++i) {
2563                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2564                         IncreaseBuf(*target, 1, 0);
2565                 ch = (unsigned char) source->buf[i];
2566                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2567                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2568                         (*target)->BufUsed += 3;
2569                 }
2570                 else {
2571                         (*target)->buf[(*target)->BufUsed] = ch;
2572                         (*target)->BufUsed++;
2573                 }
2574         }
2575         
2576         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2577                 IncreaseBuf(*target, 1, 0);
2578
2579         (*target)->buf[(*target)->BufUsed++] = '?';
2580         (*target)->buf[(*target)->BufUsed++] = '=';
2581         (*target)->buf[(*target)->BufUsed] = '\0';
2582         return (*target)->BufUsed;;
2583 }
2584
2585
2586
2587 static void AddRecipient(StrBuf *Target, 
2588                          StrBuf *UserName, 
2589                          StrBuf *EmailAddress, 
2590                          StrBuf *EncBuf)
2591 {
2592         int QuoteMe = 0;
2593
2594         if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2595         if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2596
2597         if (QuoteMe)  StrBufAppendBufPlain(Target, HKEY("\""), 0);
2598         StrBufRFC2047encode(&EncBuf, UserName);
2599         StrBufAppendBuf(Target, EncBuf, 0);
2600         if (QuoteMe)  StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2601         else          StrBufAppendBufPlain(Target, HKEY(" "), 0);
2602
2603         if (StrLength(EmailAddress) > 0){
2604                 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2605                 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2606                 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2607         }
2608 }
2609
2610
2611 /**
2612  * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2613  * \param Recp Source list of email recipients
2614  * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2615  * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2616  * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2617  * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2618  */
2619 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp, 
2620                                            StrBuf *UserName, 
2621                                            StrBuf *EmailAddress,
2622                                            StrBuf *EncBuf)
2623 {
2624         StrBuf *Target;
2625         int need_to_encode;
2626
2627         const char *pch, *pche;
2628         const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2629
2630         if ((Recp == NULL) || (StrLength(Recp) == 0))
2631                 return NULL;
2632
2633         need_to_encode = 0;
2634         pch = ChrPtr(Recp);
2635         pche = pch + StrLength(Recp);
2636
2637         if (!CheckEncode(pch, -1, pche))
2638                 return NewStrBufDup(Recp);
2639
2640         Target = NewStrBufPlain(NULL, StrLength(Recp));
2641
2642         while ((pch != NULL) && (pch < pche))
2643         {
2644                 int ColonOk = 0;
2645
2646                 while (isspace(*pch)) pch++;
2647                 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2648                 
2649                 if ((*pch == '"') || (*pch == '\'')) {
2650                         UserStart = pch + 1;
2651                         
2652                         UserEnd = strchr(UserStart, *pch);
2653                         if (UserEnd == NULL) 
2654                                 break; ///TODO: Userfeedback??
2655                         EmailStart = UserEnd + 1;
2656                         while (isspace(*EmailStart))
2657                                 EmailStart++;
2658                         if (UserEnd == UserStart) {
2659                                 UserStart = UserEnd = NULL;
2660                         }
2661                         
2662                         if (*EmailStart == '<') {
2663                                 EmailStart++;
2664                                 EmailEnd = strchr(EmailStart, '>');
2665                                 if (EmailEnd == NULL)
2666                                         EmailEnd = strchr(EmailStart, ',');
2667                                 
2668                         }
2669                         else {
2670                                 EmailEnd = strchr(EmailStart, ',');
2671                         }
2672                         if (EmailEnd == NULL)
2673                                 EmailEnd = pche;
2674                         pch = EmailEnd + 1;
2675                         ColonOk = 1;
2676                 }
2677                 else {
2678                         int gt = 0;
2679                         UserStart = pch;
2680                         EmailEnd = strchr(UserStart, ',');
2681                         if (EmailEnd == NULL) {
2682                                 EmailEnd = strchr(pch, '>');
2683                                 pch = NULL;
2684                                 if (EmailEnd != NULL) {
2685                                         gt = 1;
2686                                 }
2687                                 else {
2688                                         EmailEnd = pche;
2689                                 }
2690                         }
2691                         else {
2692
2693                                 pch = EmailEnd + 1;
2694                                 while ((EmailEnd > UserStart) && !gt &&
2695                                        ((*EmailEnd == ',') ||
2696                                         (*EmailEnd == '>') ||
2697                                         (isspace(*EmailEnd))))
2698                                 {
2699                                         if (*EmailEnd == '>')
2700                                                 gt = 1;
2701                                         else 
2702                                                 EmailEnd--;
2703                                 }
2704                                 if (EmailEnd == UserStart)
2705                                         break;
2706                         }
2707                         if (gt) {
2708                                 EmailStart = strchr(UserStart, '<');
2709                                 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2710                                         break;
2711                                 UserEnd = EmailStart;
2712
2713                                 while ((UserEnd > UserStart) && 
2714                                        isspace (*(UserEnd - 1)))
2715                                         UserEnd --;
2716                                 EmailStart ++;
2717                                 if (UserStart >= UserEnd)
2718                                         UserStart = UserEnd = NULL;
2719                                 At = strchr(EmailStart, '@');
2720                         }
2721                         else { /* this is a local recipient... no domain, just a realname */
2722                                 EmailStart = UserStart;
2723                                 At = strchr(EmailStart, '@');
2724                                 if (At == NULL) {
2725                                         UserEnd = EmailEnd;
2726                                         EmailEnd = NULL;
2727                                 }
2728                                 else {
2729                                         EmailStart = UserStart;
2730                                         UserStart = NULL;
2731                                 }
2732                         }
2733                 }
2734
2735                 if ((UserStart != NULL) && (UserEnd != NULL))
2736                         StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2737                 else if ((UserStart != NULL) && (UserEnd == NULL))
2738                         StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2739                 else
2740                         FlushStrBuf(UserName);
2741
2742                 if ((EmailStart != NULL) && (EmailEnd != NULL))
2743                         StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2744                 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2745                         StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2746                 else 
2747                         FlushStrBuf(EmailAddress);
2748
2749                 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2750
2751                 if (pch == NULL)
2752                         break;
2753                 
2754                 if ((pch != NULL) && (*pch == ','))
2755                         pch ++;
2756                 if (pch != NULL) while (isspace(*pch))
2757                         pch ++;
2758         }
2759         return Target;
2760 }
2761
2762
2763 /**
2764  * @ingroup StrBuf
2765  * @brief replaces all occurances of 'search' by 'replace'
2766  * @param buf Buffer to modify
2767  * @param search character to search
2768  * @param replace character to replace search by
2769  */
2770 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2771 {
2772         long i;
2773         if (buf == NULL)
2774                 return;
2775         for (i=0; i<buf->BufUsed; i++)
2776                 if (buf->buf[i] == search)
2777                         buf->buf[i] = replace;
2778
2779 }
2780
2781 /**
2782  * @ingroup StrBuf
2783  * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2784  * @param buf Buffer to modify
2785  */
2786 void StrBufToUnixLF(StrBuf *buf)
2787 {
2788         char *pche, *pchS, *pchT;
2789         if (buf == NULL)
2790                 return;
2791
2792         pche = buf->buf + buf->BufUsed;
2793         pchS = pchT = buf->buf;
2794         while (pchS < pche)
2795         {
2796                 if (*pchS == '\r')
2797                 {
2798                         pchS ++;
2799                         if (*pchS != '\n') {
2800                                 *pchT = '\n';
2801                                 pchT++;
2802                         }
2803                 }
2804                 *pchT = *pchS;
2805                 pchT++; pchS++;
2806         }
2807         *pchT = '\0';
2808         buf->BufUsed = pchT - buf->buf;
2809 }
2810
2811
2812 /*******************************************************************************
2813  *                 Iconv Wrapper; RFC822 de/encoding                           *
2814  *******************************************************************************/
2815
2816 /**
2817  * @ingroup StrBuf_DeEnCoder
2818  * @brief Wrapper around iconv_open()
2819  * Our version adds aliases for non-standard Microsoft charsets
2820  * such as 'MS950', aliasing them to names like 'CP950'
2821  *
2822  * @param tocode        Target encoding
2823  * @param fromcode      Source encoding
2824  * @param pic           anonimized pointer to iconv struct
2825  */
2826 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2827 {
2828 #ifdef HAVE_ICONV
2829         iconv_t ic = (iconv_t)(-1) ;
2830         ic = iconv_open(tocode, fromcode);
2831         if (ic == (iconv_t)(-1) ) {
2832                 char alias_fromcode[64];
2833                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2834                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2835                         alias_fromcode[0] = 'C';
2836                         alias_fromcode[1] = 'P';
2837                         ic = iconv_open(tocode, alias_fromcode);
2838                 }
2839         }
2840         *(iconv_t *)pic = ic;
2841 #endif
2842 }
2843
2844
2845 /**
2846  * @ingroup StrBuf_DeEnCoder
2847  * @brief find one chunk of a RFC822 encoded string
2848  * @param Buffer where to search
2849  * @param bptr where to start searching
2850  * @returns found position, NULL if none.
2851  */
2852 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2853 {
2854         const char * end;
2855         /* Find the next ?Q? */
2856         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2857                 return NULL;
2858
2859         end = strchr(bptr + 2, '?');
2860
2861         if (end == NULL)
2862                 return NULL;
2863
2864         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2865             (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
2866              ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) && 
2867             (*(end + 2) == '?')) {
2868                 /* skip on to the end of the cluster, the next ?= */
2869                 end = strstr(end + 3, "?=");
2870         }
2871         else
2872                 /* sort of half valid encoding, try to find an end. */
2873                 end = strstr(bptr, "?=");
2874         return end;
2875 }
2876
2877
2878
2879 /**
2880  * @ingroup StrBuf_DeEnCoder
2881  * @brief convert one buffer according to the preselected iconv pointer PIC
2882  * @param ConvertBuf buffer we need to translate
2883  * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2884  * @param pic Pointer to the iconv-session Object
2885  */
2886 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2887 {
2888 #ifdef HAVE_ICONV
2889         long trycount = 0;
2890         size_t siz;
2891         iconv_t ic;
2892         char *ibuf;                     /**< Buffer of characters to be converted */
2893         char *obuf;                     /**< Buffer for converted characters */
2894         size_t ibuflen;                 /**< Length of input buffer */
2895         size_t obuflen;                 /**< Length of output buffer */
2896
2897
2898         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2899         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2900                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2901 TRYAGAIN:
2902         ic = *(iconv_t*)pic;
2903         ibuf = ConvertBuf->buf;
2904         ibuflen = ConvertBuf->BufUsed;
2905         obuf = TmpBuf->buf;
2906         obuflen = TmpBuf->BufSize;
2907         
2908         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2909
2910         if (siz < 0) {
2911                 if (errno == E2BIG) {
2912                         trycount ++;                    
2913                         IncreaseBuf(TmpBuf, 0, 0);
2914                         if (trycount < 5) 
2915                                 goto TRYAGAIN;
2916
2917                 }
2918                 else if (errno == EILSEQ){ 
2919                         /* hm, invalid utf8 sequence... what to do now? */
2920                         /* An invalid multibyte sequence has been encountered in the input */
2921                 }
2922                 else if (errno == EINVAL) {
2923                         /* An incomplete multibyte sequence has been encountered in the input. */
2924                 }
2925
2926                 FlushStrBuf(TmpBuf);
2927         }
2928         else {
2929                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2930                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2931                 
2932                 /* little card game: wheres the red lady? */
2933                 SwapBuffers(ConvertBuf, TmpBuf);
2934                 FlushStrBuf(TmpBuf);
2935         }
2936 #endif
2937 }
2938
2939
2940 /**
2941  * @ingroup StrBuf_DeEnCoder
2942  * @brief catches one RFC822 encoded segment, and decodes it.
2943  * @param Target buffer to fill with result
2944  * @param DecodeMe buffer with stuff to process
2945  * @param SegmentStart points to our current segment in DecodeMe
2946  * @param SegmentEnd Points to the end of our current segment in DecodeMe
2947  * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2948  * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2949  * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2950  */
2951 inline static void DecodeSegment(StrBuf *Target, 
2952                                  const StrBuf *DecodeMe, 
2953                                  const char *SegmentStart, 
2954                                  const char *SegmentEnd, 
2955                                  StrBuf *ConvertBuf,
2956                                  StrBuf *ConvertBuf2, 
2957                                  StrBuf *FoundCharset)
2958 {
2959         StrBuf StaticBuf;
2960         char charset[128];
2961         char encoding[16];
2962 #ifdef HAVE_ICONV
2963         iconv_t ic = (iconv_t)(-1);
2964 #else
2965         void *ic = NULL;
2966 #endif
2967         /* Now we handle foreign character sets properly encoded
2968          * in RFC2047 format.
2969          */
2970         StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2971         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2972         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2973         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2974         if (FoundCharset != NULL) {
2975                 FlushStrBuf(FoundCharset);
2976                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2977         }
2978         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2979         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2980         
2981         *encoding = toupper(*encoding);
2982         if (*encoding == 'B') { /**< base64 */
2983                 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2984                         IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2985                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
2986                                                         ConvertBuf->buf, 
2987                                                         ConvertBuf->BufUsed);
2988         }
2989         else if (*encoding == 'Q') {    /**< quoted-printable */
2990                 long pos;
2991                 
2992                 pos = 0;
2993                 while (pos < ConvertBuf->BufUsed)
2994                 {
2995                         if (ConvertBuf->buf[pos] == '_') 
2996                                 ConvertBuf->buf[pos] = ' ';
2997                         pos++;
2998                 }
2999                 
3000                 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3001                         IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3002
3003                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3004                         ConvertBuf2->buf, 
3005                         ConvertBuf->buf,
3006                         ConvertBuf->BufUsed);
3007         }
3008         else {
3009                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3010         }
3011 #ifdef HAVE_ICONV
3012         ctdl_iconv_open("UTF-8", charset, &ic);
3013         if (ic != (iconv_t)(-1) ) {             
3014 #endif
3015                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3016                 StrBufAppendBuf(Target, ConvertBuf2, 0);
3017 #ifdef HAVE_ICONV
3018                 iconv_close(ic);
3019         }
3020         else {
3021                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3022         }
3023 #endif
3024 }
3025
3026 /**
3027  * @ingroup StrBuf_DeEnCoder
3028  * @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
3029  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3030  * @param Target where to put the decoded string to 
3031  * @param DecodeMe buffer with encoded string
3032  * @param DefaultCharset if we don't find one, which should we use?
3033  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3034  *        put it here for later use where no string might be known.
3035  */
3036 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3037 {
3038         StrBuf *ConvertBuf;
3039         StrBuf *ConvertBuf2;
3040         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3041         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3042         
3043         StrBuf_RFC822_2_Utf8(Target, 
3044                              DecodeMe, 
3045                              DefaultCharset, 
3046                              FoundCharset, 
3047                              ConvertBuf, 
3048                              ConvertBuf2);
3049         FreeStrBuf(&ConvertBuf);
3050         FreeStrBuf(&ConvertBuf2);
3051 }
3052
3053 /**
3054  * @ingroup StrBuf_DeEnCoder
3055  * @brief Handle subjects with RFC2047 encoding such as:
3056  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3057  * @param Target where to put the decoded string to 
3058  * @param DecodeMe buffer with encoded string
3059  * @param DefaultCharset if we don't find one, which should we use?
3060  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3061  *        put it here for later use where no string might be known.
3062  * @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3063  * @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3064  */
3065 void StrBuf_RFC822_2_Utf8(StrBuf *Target, 
3066                           const StrBuf *DecodeMe, 
3067                           const StrBuf* DefaultCharset, 
3068                           StrBuf *FoundCharset, 
3069                           StrBuf *ConvertBuf, 
3070                           StrBuf *ConvertBuf2)
3071 {
3072         StrBuf *DecodedInvalidBuf = NULL;
3073         const StrBuf *DecodeMee = DecodeMe;
3074         const char *start, *end, *next, *nextend, *ptr = NULL;
3075 #ifdef HAVE_ICONV
3076         iconv_t ic = (iconv_t)(-1) ;
3077 #endif
3078         const char *eptr;
3079         int passes = 0;
3080         int i, len;
3081         int illegal_non_rfc2047_encoding = 0;
3082
3083         /* Sometimes, badly formed messages contain strings which were simply
3084          *  written out directly in some foreign character set instead of
3085          *  using RFC2047 encoding.  This is illegal but we will attempt to
3086          *  handle it anyway by converting from a user-specified default
3087          *  charset to UTF-8 if we see any nonprintable characters.
3088          */
3089         
3090         len = StrLength(DecodeMe);
3091         for (i=0; i<DecodeMe->BufUsed; ++i) {
3092                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3093                         illegal_non_rfc2047_encoding = 1;
3094                         break;
3095                 }
3096         }
3097
3098         if ((illegal_non_rfc2047_encoding) &&
3099             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
3100             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3101         {
3102 #ifdef HAVE_ICONV
3103                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3104                 if (ic != (iconv_t)(-1) ) {
3105                         DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3106                         StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3107                         DecodeMee = DecodedInvalidBuf;
3108                         iconv_close(ic);
3109                 }
3110 #endif
3111         }
3112
3113         /* pre evaluate the first pair */
3114         nextend = end = NULL;
3115         len = StrLength(DecodeMee);
3116         start = strstr(DecodeMee->buf, "=?");
3117         eptr = DecodeMee->buf + DecodeMee->BufUsed;
3118         if (start != NULL) 
3119                 end = FindNextEnd (DecodeMee, start + 2);
3120         else {
3121                 StrBufAppendBuf(Target, DecodeMee, 0);
3122                 FreeStrBuf(&DecodedInvalidBuf);
3123                 return;
3124         }
3125
3126
3127         if (start != DecodeMee->buf) {
3128                 long nFront;
3129                 
3130                 nFront = start - DecodeMee->buf;
3131                 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3132                 len -= nFront;
3133         }
3134         /*
3135          * Since spammers will go to all sorts of absurd lengths to get their
3136          * messages through, there are LOTS of corrupt headers out there.
3137          * So, prevent a really badly formed RFC2047 header from throwing
3138          * this function into an infinite loop.
3139          */
3140         while ((start != NULL) && 
3141                (end != NULL) && 
3142                (start < eptr) && 
3143                (end < eptr) && 
3144                (passes < 20))
3145         {
3146                 passes++;
3147                 DecodeSegment(Target, 
3148                               DecodeMee, 
3149                               start, 
3150                               end, 
3151                               ConvertBuf,
3152                               ConvertBuf2,
3153                               FoundCharset);
3154                 
3155                 next = strstr(end, "=?");
3156                 nextend = NULL;
3157                 if ((next != NULL) && 
3158                     (next < eptr))
3159                         nextend = FindNextEnd(DecodeMee, next);
3160                 if (nextend == NULL)
3161                         next = NULL;
3162
3163                 /* did we find two partitions */
3164                 if ((next != NULL) && 
3165                     ((next - end) > 2))
3166                 {
3167                         ptr = end + 2;
3168                         while ((ptr < next) && 
3169                                (isspace(*ptr) ||
3170                                 (*ptr == '\r') ||
3171                                 (*ptr == '\n') || 
3172                                 (*ptr == '\t')))
3173                                 ptr ++;
3174                         /* 
3175                          * did we find a gab just filled with blanks?
3176                          * if not, copy its stuff over.
3177                          */
3178                         if (ptr != next)
3179                         {
3180                                 StrBufAppendBufPlain(Target, 
3181                                                      end + 2, 
3182                                                      next - end - 2,
3183                                                      0);
3184                         }
3185                 }
3186                 /* our next-pair is our new first pair now. */
3187                 ptr = end + 2;
3188                 start = next;
3189                 end = nextend;
3190         }
3191         end = ptr;
3192         nextend = DecodeMee->buf + DecodeMee->BufUsed;
3193         if ((end != NULL) && (end < nextend)) {
3194                 ptr = end;
3195                 while ( (ptr < nextend) &&
3196                         (isspace(*ptr) ||
3197                          (*ptr == '\r') ||
3198                          (*ptr == '\n') || 
3199                          (*ptr == '\t')))
3200                         ptr ++;
3201                 if (ptr < nextend)
3202                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
3203         }
3204         FreeStrBuf(&DecodedInvalidBuf);
3205 }
3206
3207 /*******************************************************************************
3208  *                   Manipulating UTF-8 Strings                                *
3209  *******************************************************************************/
3210
3211 /**
3212  * @ingroup StrBuf
3213  * @brief evaluate the length of an utf8 special character sequence
3214  * @param Char the character to examine
3215  * @returns width of utf8 chars in bytes
3216  */
3217 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3218 {
3219         int n = 1;
3220         char test = (1<<7);
3221         
3222         while ((n < 8) && ((test & *CharS) != 0)) {
3223                 test = test << 1;
3224                 n ++;
3225         }
3226         if ((n > 6) || ((CharE - CharS) < n))
3227                 n = 1;
3228         return n;
3229 }
3230
3231 /**
3232  * @ingroup StrBuf
3233  * @brief detect whether this char starts an utf-8 encoded char
3234  * @param Char character to inspect
3235  * @returns yes or no
3236  */
3237 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3238 {
3239 /** 11??.???? indicates an UTF8 Sequence. */
3240         return ((Char & 0xC0) != 0);
3241 }
3242
3243 /**
3244  * @ingroup StrBuf
3245  * @brief measure the number of glyphs in an UTF8 string...
3246  * @param Buf string to measure
3247  * @returns the number of glyphs in Buf
3248  */
3249 long StrBuf_Utf8StrLen(StrBuf *Buf)
3250 {
3251         int n = 0;
3252         int m = 0;
3253         char *aptr, *eptr;
3254
3255         if ((Buf == NULL) || (Buf->BufUsed == 0))
3256                 return 0;
3257         aptr = Buf->buf;
3258         eptr = Buf->buf + Buf->BufUsed;
3259         while ((aptr < eptr) && (*aptr != '\0')) {
3260                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3261                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3262                         while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3263                         n ++;
3264                 }
3265                 else {
3266                         n++;
3267                         aptr++;
3268                 }
3269         }
3270         return n;
3271 }
3272
3273 /**
3274  * @ingroup StrBuf
3275  * @brief cuts a string after maxlen glyphs
3276  * @param Buf string to cut to maxlen glyphs
3277  * @param maxlen how long may the string become?
3278  * @returns current length of the string
3279  */
3280 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3281 {
3282         char *aptr, *eptr;
3283         int n = 0, m = 0;
3284
3285         aptr = Buf->buf;
3286         eptr = Buf->buf + Buf->BufUsed;
3287         while ((aptr < eptr) && (*aptr != '\0')) {
3288                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3289                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3290                         while ((*aptr++ != '\0') && (m-- > 0));
3291                         n ++;
3292                 }
3293                 else {
3294                         n++;
3295                         aptr++;
3296                 }
3297                 if (n > maxlen) {
3298                         *aptr = '\0';
3299                         Buf->BufUsed = aptr - Buf->buf;
3300                         return Buf->BufUsed;
3301                 }                       
3302         }
3303         return Buf->BufUsed;
3304
3305 }
3306
3307
3308
3309
3310
3311 /*******************************************************************************
3312  *                               wrapping ZLib                                 *
3313  *******************************************************************************/
3314
3315 #ifdef HAVE_ZLIB
3316 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3317 #define OS_CODE 0x03    /*< unix */
3318
3319 /**
3320  * @ingroup StrBuf_DeEnCoder
3321  * @brief uses the same calling syntax as compress2(), but it
3322  *   creates a stream compatible with HTTP "Content-encoding: gzip"
3323  * @param dest compressed buffer
3324  * @param destLen length of the compresed data 
3325  * @param source source to encode
3326  * @param sourceLen length of source to encode 
3327  * @param level compression level
3328  */
3329 int ZEXPORT compress_gzip(Bytef * dest,
3330                           size_t * destLen,
3331                           const Bytef * source,
3332                           uLong sourceLen,     
3333                           int level)
3334 {
3335         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3336
3337         /* write gzip header */
3338         snprintf((char *) dest, *destLen, 
3339                  "%c%c%c%c%c%c%c%c%c%c",
3340                  gz_magic[0], gz_magic[1], Z_DEFLATED,
3341                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3342                  OS_CODE);
3343
3344         /* normal deflate */
3345         z_stream stream;
3346         int err;
3347         stream.next_in = (Bytef *) source;
3348         stream.avail_in = (uInt) sourceLen;
3349         stream.next_out = dest + 10L;   // after header
3350         stream.avail_out = (uInt) * destLen;
3351         if ((uLong) stream.avail_out != *destLen)
3352                 return Z_BUF_ERROR;
3353
3354         stream.zalloc = (alloc_func) 0;
3355         stream.zfree = (free_func) 0;
3356         stream.opaque = (voidpf) 0;
3357
3358         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3359                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3360         if (err != Z_OK)
3361                 return err;
3362
3363         err = deflate(&stream, Z_FINISH);
3364         if (err != Z_STREAM_END) {
3365                 deflateEnd(&stream);
3366                 return err == Z_OK ? Z_BUF_ERROR : err;
3367         }
3368         *destLen = stream.total_out + 10L;
3369
3370         /* write CRC and Length */
3371         uLong crc = crc32(0L, source, sourceLen);
3372         int n;
3373         for (n = 0; n < 4; ++n, ++*destLen) {
3374                 dest[*destLen] = (int) (crc & 0xff);
3375                 crc >>= 8;
3376         }
3377         uLong len = stream.total_in;
3378         for (n = 0; n < 4; ++n, ++*destLen) {
3379                 dest[*destLen] = (int) (len & 0xff);
3380                 len >>= 8;
3381         }
3382         err = deflateEnd(&stream);
3383         return err;
3384 }
3385 #endif
3386
3387
3388 /**
3389  * @ingroup StrBuf_DeEnCoder
3390  * @brief compress the buffer with gzip
3391  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3392  * @param Buf buffer whose content is to be gzipped
3393  */
3394 int CompressBuffer(StrBuf *Buf)
3395 {
3396 #ifdef HAVE_ZLIB
3397         char *compressed_data = NULL;
3398         size_t compressed_len, bufsize;
3399         int i = 0;
3400
3401         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
3402         compressed_data = malloc(compressed_len);
3403         
3404         if (compressed_data == NULL)
3405                 return -1;
3406         /* Flush some space after the used payload so valgrind shuts up... */
3407         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3408                 Buf->buf[Buf->BufUsed + i++] = '\0';
3409         if (compress_gzip((Bytef *) compressed_data,
3410                           &compressed_len,
3411                           (Bytef *) Buf->buf,
3412                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3413                 if (!Buf->ConstBuf)
3414                         free(Buf->buf);
3415                 Buf->buf = compressed_data;
3416                 Buf->BufUsed = compressed_len;
3417                 Buf->BufSize = bufsize;
3418                 /* Flush some space after the used payload so valgrind shuts up... */
3419                 i = 0;
3420                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3421                         Buf->buf[Buf->BufUsed + i++] = '\0';
3422                 return 1;
3423         } else {
3424                 free(compressed_data);
3425         }
3426 #endif  /* HAVE_ZLIB */
3427         return 0;
3428 }
3429
3430
3431
3432 /*******************************************************************************
3433  *           File I/O; Prefer buffered read since its faster!                  *
3434  *******************************************************************************/
3435
3436 /**
3437  * @ingroup StrBuf_IO
3438  * @brief Read a line from socket
3439  * flushes and closes the FD on error
3440  * @param buf the buffer to get the input to
3441  * @param fd pointer to the filedescriptor to read
3442  * @param append Append to an existing string or replace?
3443  * @param Error strerror() on error 
3444  * @returns numbers of chars read
3445  */
3446 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3447 {
3448         int len, rlen, slen;
3449
3450         if (!append)
3451                 FlushStrBuf(buf);
3452
3453         slen = len = buf->BufUsed;
3454         while (1) {
3455                 rlen = read(*fd, &buf->buf[len], 1);
3456                 if (rlen < 1) {
3457                         *Error = strerror(errno);
3458                         
3459                         close(*fd);
3460                         *fd = -1;
3461                         
3462                         return -1;
3463                 }
3464                 if (buf->buf[len] == '\n')
3465                         break;
3466                 if (buf->buf[len] != '\r')
3467                         len ++;
3468                 if (len + 2 >= buf->BufSize) {
3469                         buf->BufUsed = len;
3470                         buf->buf[len+1] = '\0';
3471                         IncreaseBuf(buf, 1, -1);
3472                 }
3473         }
3474         buf->BufUsed = len;
3475         buf->buf[len] = '\0';
3476         return len - slen;
3477 }
3478
3479 /**
3480  * @ingroup StrBuf_BufferedIO
3481  * @brief Read a line from socket
3482  * flushes and closes the FD on error
3483  * @param Line the line to read from the fd / I/O Buffer
3484  * @param buf the buffer to get the input to
3485  * @param fd pointer to the filedescriptor to read
3486  * @param timeout number of successless selects until we bail out
3487  * @param selectresolution how long to wait on each select
3488  * @param Error strerror() on error 
3489  * @returns numbers of chars read
3490  */
3491 int StrBufTCP_read_buffered_line(StrBuf *Line, 
3492                                  StrBuf *buf, 
3493                                  int *fd, 
3494                                  int timeout, 
3495                                  int selectresolution, 
3496                                  const char **Error)
3497 {
3498         int len, rlen;
3499         int nSuccessLess = 0;
3500         fd_set rfds;
3501         char *pch = NULL;
3502         int fdflags;
3503         int IsNonBlock;
3504         struct timeval tv;
3505
3506         if (buf->BufUsed > 0) {
3507                 pch = strchr(buf->buf, '\n');
3508                 if (pch != NULL) {
3509                         rlen = 0;
3510                         len = pch - buf->buf;
3511                         if (len > 0 && (*(pch - 1) == '\r') )
3512                                 rlen ++;
3513                         StrBufSub(Line, buf, 0, len - rlen);
3514                         StrBufCutLeft(buf, len + 1);
3515                         return len - rlen;
3516                 }
3517         }
3518         
3519         if (buf->BufSize - buf->BufUsed < 10)
3520                 IncreaseBuf(buf, 1, -1);
3521
3522         fdflags = fcntl(*fd, F_GETFL);
3523         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3524
3525         while ((nSuccessLess < timeout) && (pch == NULL)) {
3526                 if (IsNonBlock){
3527                         tv.tv_sec = selectresolution;
3528                         tv.tv_usec = 0;
3529                         
3530                         FD_ZERO(&rfds);
3531                         FD_SET(*fd, &rfds);
3532                         if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3533                                 *Error = strerror(errno);
3534                                 close (*fd);
3535                                 *fd = -1;
3536                                 return -1;
3537                         }
3538                 }
3539                 if (IsNonBlock && !  FD_ISSET(*fd, &rfds)) {
3540                         nSuccessLess ++;
3541                         continue;
3542                 }
3543                 rlen = read(*fd, 
3544                             &buf->buf[buf->BufUsed], 
3545                             buf->BufSize - buf->BufUsed - 1);
3546                 if (rlen < 1) {
3547                         *Error = strerror(errno);
3548                         close(*fd);
3549                         *fd = -1;
3550                         return -1;
3551                 }
3552                 else if (rlen > 0) {
3553                         nSuccessLess = 0;
3554                         buf->BufUsed += rlen;
3555                         buf->buf[buf->BufUsed] = '\0';
3556                         if (buf->BufUsed + 10 > buf->BufSize) {
3557                                 IncreaseBuf(buf, 1, -1);
3558                         }
3559                         pch = strchr(buf->buf, '\n');
3560                         continue;
3561                 }
3562                 
3563         }
3564         if (pch != NULL) {
3565                 rlen = 0;
3566                 len = pch - buf->buf;
3567                 if (len > 0 && (*(pch - 1) == '\r') )
3568                         rlen ++;
3569                 StrBufSub(Line, buf, 0, len - rlen);
3570                 StrBufCutLeft(buf, len + 1);
3571                 return len - rlen;
3572         }
3573         return -1;
3574
3575 }
3576
3577 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3578 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3579 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3580 /**
3581  * @ingroup StrBuf_BufferedIO
3582  * @brief Read a line from socket
3583  * flushes and closes the FD on error
3584  * @param Line where to append our Line read from the fd / I/O Buffer; 
3585  * @param IOBuf the buffer to get the input to; lifetime pair to FD
3586  * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3587  * @param fd pointer to the filedescriptor to read
3588  * @param timeout number of successless selects until we bail out
3589  * @param selectresolution how long to wait on each select
3590  * @param Error strerror() on error 
3591  * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3592  */
3593 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
3594                                       StrBuf *IOBuf, 
3595                                       const char **Pos,
3596                                       int *fd, 
3597                                       int timeout, 
3598                                       int selectresolution, 
3599                                       const char **Error)
3600 {
3601         const char *pche = NULL;
3602         const char *pos = NULL;
3603         const char *pLF;
3604         int len, rlen, retlen;
3605         int nSuccessLess = 0;
3606         fd_set rfds;
3607         const char *pch = NULL;
3608         int fdflags;
3609         int IsNonBlock;
3610         struct timeval tv;
3611         
3612         retlen = 0;
3613         if ((Line == NULL) ||
3614             (Pos == NULL) ||
3615             (IOBuf == NULL) ||
3616             (*fd == -1))
3617         {
3618                 if (Pos != NULL)
3619                         *Pos = NULL;
3620                 *Error = ErrRBLF_PreConditionFailed;
3621                 return -1;
3622         }
3623
3624         pos = *Pos;
3625         if ((IOBuf->BufUsed > 0) && 
3626             (pos != NULL) && 
3627             (pos < IOBuf->buf + IOBuf->BufUsed)) 
3628         {
3629                 char *pcht;
3630
3631                 pche = IOBuf->buf + IOBuf->BufUsed;
3632                 pch = pos;
3633                 pcht = Line->buf;
3634
3635                 while ((pch < pche) && (*pch != '\n'))
3636                 {
3637                         if (Line->BufUsed + 10 > Line->BufSize)
3638                         {
3639                                 long apos;
3640                                 apos = pcht - Line->buf;
3641                                 *pcht = '\0';
3642                                 IncreaseBuf(Line, 1, -1);
3643                                 pcht = Line->buf + apos;
3644                         }
3645                         *pcht++ = *pch++;
3646                         Line->BufUsed++;
3647                         retlen++;
3648                 }
3649
3650                 len = pch - pos;
3651                 if (len > 0 && (*(pch - 1) == '\r') )
3652                 {
3653                         retlen--;
3654                         len --;
3655                         pcht --;
3656                         Line->BufUsed --;
3657                 }
3658                 *pcht = '\0';
3659
3660                 if ((pch >= pche) || (*pch == '\0'))
3661                 {
3662                         FlushStrBuf(IOBuf);
3663                         *Pos = NULL;
3664                         pch = NULL;
3665                         pos = 0;
3666                 }
3667
3668                 if ((pch != NULL) && 
3669                     (pch <= pche)) 
3670                 {
3671                         if (pch + 1 >= pche) {
3672                                 *Pos = NULL;
3673                                 FlushStrBuf(IOBuf);
3674                         }
3675                         else
3676                                 *Pos = pch + 1;
3677                         
3678                         return retlen;
3679                 }
3680                 else 
3681                         FlushStrBuf(IOBuf);
3682         }
3683
3684         /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3685         
3686         if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3687                 IncreaseBuf(IOBuf, 1, -1);
3688
3689         fdflags = fcntl(*fd, F_GETFL);
3690         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3691
3692         pLF = NULL;
3693         while ((nSuccessLess < timeout) && 
3694                (pLF == NULL) &&
3695                (*fd != -1)) {
3696                 if (IsNonBlock)
3697                 {
3698                         tv.tv_sec = 1;
3699                         tv.tv_usec = 0;
3700                 
3701                         FD_ZERO(&rfds);
3702                         FD_SET(*fd, &rfds);
3703                         if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3704                                 *Error = strerror(errno);
3705                                 close (*fd);
3706                                 *fd = -1;
3707                                 if (*Error == NULL)
3708                                         *Error = ErrRBLF_SelectFailed;
3709                                 return -1;
3710                         }
3711                         if (! FD_ISSET(*fd, &rfds) != 0) {
3712                                 nSuccessLess ++;
3713                                 continue;
3714                         }
3715                 }
3716                 rlen = read(*fd, 
3717                             &IOBuf->buf[IOBuf->BufUsed], 
3718                             IOBuf->BufSize - IOBuf->BufUsed - 1);
3719                 if (rlen < 1) {
3720                         *Error = strerror(errno);
3721                         close(*fd);
3722                         *fd = -1;
3723                         return -1;
3724                 }
3725                 else if (rlen > 0) {
3726                         nSuccessLess = 0;
3727                         pLF = IOBuf->buf + IOBuf->BufUsed;
3728                         IOBuf->BufUsed += rlen;
3729                         IOBuf->buf[IOBuf->BufUsed] = '\0';
3730                         
3731                         pche = IOBuf->buf + IOBuf->BufUsed;
3732                         
3733                         while ((pLF < pche) && (*pLF != '\n'))
3734                                 pLF ++;
3735                         if ((pLF >= pche) || (*pLF == '\0'))
3736                                 pLF = NULL;
3737
3738                         if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3739                         {
3740                                 long apos = 0;
3741
3742                                 if (pLF != NULL) apos = pLF - IOBuf->buf;
3743                                 IncreaseBuf(IOBuf, 1, -1);      
3744                                 if (pLF != NULL) pLF = IOBuf->buf + apos;
3745                         }
3746
3747                         continue;
3748                 }
3749         }
3750         *Pos = NULL;
3751         if (pLF != NULL) {
3752                 pos = IOBuf->buf;
3753                 len = pLF - pos;
3754                 if (len > 0 && (*(pLF - 1) == '\r') )
3755                         len --;
3756                 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3757                 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3758                 {
3759                         FlushStrBuf(IOBuf);
3760                 }
3761                 else 
3762                         *Pos = pLF + 1;
3763                 return retlen + len;
3764         }
3765         *Error = ErrRBLF_NotEnoughSentFromServer;
3766         return -1;
3767
3768 }
3769
3770 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3771 /**
3772  * @ingroup StrBuf_IO
3773  * @brief Input binary data from socket
3774  * flushes and closes the FD on error
3775  * @param Buf the buffer to get the input to
3776  * @param fd pointer to the filedescriptor to read
3777  * @param append Append to an existing string or replace?
3778  * @param nBytes the maximal number of bytes to read
3779  * @param Error strerror() on error 
3780  * @returns numbers of chars read
3781  */
3782 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3783 {
3784         int fdflags;
3785         int len, rlen, slen;
3786         int nSuccessLess;
3787         int nRead = 0;
3788         char *ptr;
3789         int IsNonBlock;
3790         struct timeval tv;
3791         fd_set rfds;
3792
3793         if ((Buf == NULL) || (*fd == -1))
3794         {
3795                 *Error = ErrRBLF_BLOBPreConditionFailed;
3796                 return -1;
3797         }
3798         if (!append)
3799                 FlushStrBuf(Buf);
3800         if (Buf->BufUsed + nBytes >= Buf->BufSize)
3801                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3802
3803         ptr = Buf->buf + Buf->BufUsed;
3804
3805         slen = len = Buf->BufUsed;
3806
3807         fdflags = fcntl(*fd, F_GETFL);
3808         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3809         nSuccessLess = 0;
3810         while ((nRead < nBytes) && 
3811                (*fd != -1)) 
3812         {
3813                 if (IsNonBlock)
3814                 {
3815                         tv.tv_sec = 1;
3816                         tv.tv_usec = 0;
3817                 
3818                         FD_ZERO(&rfds);
3819                         FD_SET(*fd, &rfds);
3820                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3821                                 *Error = strerror(errno);
3822                                 close (*fd);
3823                                 *fd = -1;
3824                                 if (*Error == NULL)
3825                                         *Error = ErrRBLF_SelectFailed;
3826                                 return -1;
3827                         }
3828                         if (! FD_ISSET(*fd, &rfds) != 0) {
3829                                 nSuccessLess ++;
3830                                 continue;
3831                         }
3832                 }
3833
3834                 if ((rlen = read(*fd, 
3835                                  ptr,
3836                                  nBytes - nRead)) == -1) {
3837                         close(*fd);
3838                         *fd = -1;
3839                         *Error = strerror(errno);
3840                         return rlen;
3841                 }
3842                 nRead += rlen;
3843                 ptr += rlen;
3844                 Buf->BufUsed += rlen;
3845         }
3846         Buf->buf[Buf->BufUsed] = '\0';
3847         return nRead;
3848 }
3849
3850 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3851 const char *ErrRBB_too_many_selects        = "StrBufReadBLOBBuffered: to many selects; aborting.";
3852 /**
3853  * @ingroup StrBuf_BufferedIO
3854  * @brief Input binary data from socket
3855  * flushes and closes the FD on error
3856  * @param Blob put binary thing here
3857  * @param IOBuf the buffer to get the input to
3858  * @param Pos offset inside of IOBuf
3859  * @param fd pointer to the filedescriptor to read
3860  * @param append Append to an existing string or replace?
3861  * @param nBytes the maximal number of bytes to read
3862  * @param check whether we should search for '000\n' terminators in case of timeouts
3863  * @param Error strerror() on error 
3864  * @returns numbers of chars read
3865  */
3866 int StrBufReadBLOBBuffered(StrBuf *Blob, 
3867                            StrBuf *IOBuf, 
3868                            const char **Pos,
3869                            int *fd, 
3870                            int append, 
3871                            long nBytes, 
3872                            int check, 
3873                            const char **Error)
3874 {
3875         const char *pche;
3876         const char *pos;
3877         int fdflags;
3878         int len = 0;
3879         int rlen, slen;
3880         int nRead = 0;
3881         int nAlreadyRead = 0;
3882         int IsNonBlock;
3883         char *ptr;
3884         fd_set rfds;
3885         const char *pch;
3886         struct timeval tv;
3887         int nSuccessLess = 0;
3888         int MaxTries;
3889
3890         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3891         {
3892                 if (*Pos != NULL)
3893                         *Pos = NULL;
3894                 *Error = ErrRBB_BLOBFPreConditionFailed;
3895                 return -1;
3896         }
3897
3898         if (!append)
3899                 FlushStrBuf(Blob);
3900         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
3901                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3902         
3903         pos = *Pos;
3904
3905         if (pos != NULL)
3906                 len = pos - IOBuf->buf;
3907         rlen = IOBuf->BufUsed - len;
3908
3909
3910         if ((IOBuf->BufUsed > 0) && 
3911             (pos != NULL) && 
3912             (pos < IOBuf->buf + IOBuf->BufUsed)) 
3913         {
3914                 pche = IOBuf->buf + IOBuf->BufUsed;
3915                 pch = pos;
3916
3917                 if (rlen < nBytes) {
3918                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3919                         Blob->BufUsed += rlen;
3920                         Blob->buf[Blob->BufUsed] = '\0';
3921                         nAlreadyRead = nRead = rlen;
3922                         *Pos = NULL; 
3923                 }
3924                 if (rlen >= nBytes) {
3925                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3926                         Blob->BufUsed += nBytes;
3927                         Blob->buf[Blob->BufUsed] = '\0';
3928                         if (rlen == nBytes) {
3929                                 *Pos = NULL; 
3930                                 FlushStrBuf(IOBuf);
3931                         }
3932                         else 
3933                                 *Pos += nBytes;
3934                         return nBytes;
3935                 }
3936         }
3937
3938         FlushStrBuf(IOBuf);
3939         *Pos = NULL;
3940         if (IOBuf->BufSize < nBytes - nRead)
3941                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3942         ptr = IOBuf->buf;
3943
3944         slen = len = Blob->BufUsed;
3945
3946         fdflags = fcntl(*fd, F_GETFL);
3947         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3948         if (IsNonBlock)
3949                 MaxTries =   1000;
3950         else
3951                 MaxTries = 100000;
3952
3953         nBytes -= nRead;
3954         nRead = 0;
3955         while ((nSuccessLess < MaxTries) && 
3956                (nRead < nBytes) &&
3957                (*fd != -1)) {
3958                 if (IsNonBlock)
3959                 {
3960                         tv.tv_sec = 1;
3961                         tv.tv_usec = 0;
3962                 
3963                         FD_ZERO(&rfds);
3964                         FD_SET(*fd, &rfds);
3965                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3966                                 *Error = strerror(errno);
3967                                 close (*fd);
3968                                 *fd = -1;
3969                                 if (*Error == NULL)
3970                                         *Error = ErrRBLF_SelectFailed;
3971                                 return -1;
3972                         }
3973                         if (! FD_ISSET(*fd, &rfds) != 0) {
3974                                 nSuccessLess ++;
3975                                 continue;
3976                         }
3977                 }
3978                 rlen = read(*fd, 
3979                             ptr,
3980                             IOBuf->BufSize - (ptr - IOBuf->buf));
3981                 if (rlen == -1) {
3982                         close(*fd);
3983                         *fd = -1;
3984                         *Error = strerror(errno);
3985                         return rlen;
3986                 }
3987                 else if (rlen == 0){
3988                         if ((check == NNN_TERM) && 
3989                             (nRead > 5) &&
3990                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
3991                         {
3992                                 StrBufPlain(Blob, HKEY("\n000\n"));
3993                                 StrBufCutRight(Blob, 5);
3994                                 return Blob->BufUsed;
3995                         }
3996                         else if (!IsNonBlock) 
3997                                 nSuccessLess ++;
3998                         else if (nSuccessLess > MaxTries) {
3999                                 FlushStrBuf(IOBuf);
4000                                 *Error = ErrRBB_too_many_selects;
4001                                 return -1;
4002                         }
4003                 }
4004                 else if (rlen > 0) {
4005                         nSuccessLess = 0;
4006                         nRead += rlen;
4007                         ptr += rlen;
4008                         IOBuf->BufUsed += rlen;
4009                 }
4010         }
4011         if (nSuccessLess >= MaxTries) {
4012                 FlushStrBuf(IOBuf);
4013                 *Error = ErrRBB_too_many_selects;
4014                 return -1;
4015         }
4016
4017         if (nRead > nBytes) {
4018                 *Pos = IOBuf->buf + nBytes;
4019         }
4020         Blob->buf[Blob->BufUsed] = '\0';
4021         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
4022         if (*Pos == NULL) {
4023                 FlushStrBuf(IOBuf);
4024         }
4025         return nRead + nAlreadyRead;
4026 }
4027
4028 /**
4029  * @ingroup StrBuf_IO
4030  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
4031  * @param LineBuf your line will be copied here.
4032  * @param Buf BLOB with lines of text...
4033  * @param Ptr moved arround to keep the next-line across several iterations
4034  *        has to be &NULL on start; will be &NotNULL on end of buffer
4035  * @returns size of copied buffer
4036  */
4037 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
4038 {
4039         const char *aptr, *ptr, *eptr;
4040         char *optr, *xptr;
4041
4042         if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
4043                 *Ptr = StrBufNOTNULL;
4044                 return 0;
4045         }
4046
4047         FlushStrBuf(LineBuf);
4048         if (*Ptr==NULL)
4049                 ptr = aptr = Buf->buf;
4050         else
4051                 ptr = aptr = *Ptr;
4052
4053         optr = LineBuf->buf;
4054         eptr = Buf->buf + Buf->BufUsed;
4055         xptr = LineBuf->buf + LineBuf->BufSize - 1;
4056
4057         while ((ptr <= eptr) && 
4058                (*ptr != '\n') &&
4059                (*ptr != '\r') )
4060         {
4061                 *optr = *ptr;
4062                 optr++; ptr++;
4063                 if (optr == xptr) {
4064                         LineBuf->BufUsed = optr - LineBuf->buf;
4065                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
4066                         optr = LineBuf->buf + LineBuf->BufUsed;
4067                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
4068                 }
4069         }
4070
4071         if ((ptr >= eptr) && (optr > LineBuf->buf))
4072                 optr --;
4073         LineBuf->BufUsed = optr - LineBuf->buf;
4074         *optr = '\0';       
4075         if ((ptr <= eptr) && (*ptr == '\r'))
4076                 ptr ++;
4077         if ((ptr <= eptr) && (*ptr == '\n'))
4078                 ptr ++;
4079         
4080         if (ptr < eptr) {
4081                 *Ptr = ptr;
4082         }
4083         else {
4084                 *Ptr = StrBufNOTNULL;
4085         }
4086
4087         return Buf->BufUsed - (ptr - Buf->buf);
4088 }
4089
4090
4091 /**
4092  * @ingroup StrBuf_IO
4093  * @brief removes double slashes from pathnames
4094  * @param Dir directory string to filter
4095  * @param RemoveTrailingSlash allows / disallows trailing slashes
4096  */
4097 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
4098 {
4099         char *a, *b;
4100
4101         a = b = Dir->buf;
4102
4103         while (!IsEmptyStr(a)) {
4104                 if (*a == '/') {
4105                         while (*a == '/')
4106                                 a++;
4107                         *b = '/';
4108                         b++;
4109                 }
4110                 else {
4111                         *b = *a;
4112                         b++; a++;
4113                 }
4114         }
4115         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4116                 *b = '/';
4117                 b++;
4118         }
4119         *b = '\0';
4120         Dir->BufUsed = b - Dir->buf;
4121 }
4122
4123