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