* this way its fastest: range check whats allowed and mask the rest.
[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 (IsUtf8Sequence != 0) {
1230                                 IsUtf8Sequence --;
1231                                 *bptr = *aptr;
1232                                 bptr++;
1233                                 Target->BufUsed ++;
1234                         }
1235                         else {
1236                                 if (*aptr >= 0x20)
1237                                 {
1238                                         IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1239
1240                                         *bptr = *aptr;
1241                                         bptr++;
1242                                         Target->BufUsed ++;
1243                                 }
1244                         }
1245
1246                 }
1247                 aptr ++;
1248         }
1249         *bptr = '\0';
1250         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1251                 return -1;
1252         return Target->BufUsed;
1253 }
1254
1255
1256 /**
1257  * @ingroup StrBuf
1258  * @brief extracts a substring from Source into dest
1259  * @param dest buffer to place substring into
1260  * @param Source string to copy substring from
1261  * @param Offset chars to skip from start
1262  * @param nChars number of chars to copy
1263  * @returns the number of chars copied; may be different from nChars due to the size of Source
1264  */
1265 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1266 {
1267         size_t NCharsRemain;
1268         if (Offset > Source->BufUsed)
1269         {
1270                 FlushStrBuf(dest);
1271                 return 0;
1272         }
1273         if (Offset + nChars < Source->BufUsed)
1274         {
1275                 if (nChars >= dest->BufSize)
1276                         IncreaseBuf(dest, 0, nChars + 1);
1277                 memcpy(dest->buf, Source->buf + Offset, nChars);
1278                 dest->BufUsed = nChars;
1279                 dest->buf[dest->BufUsed] = '\0';
1280                 return nChars;
1281         }
1282         NCharsRemain = Source->BufUsed - Offset;
1283         if (NCharsRemain  >= dest->BufSize)
1284                 IncreaseBuf(dest, 0, NCharsRemain + 1);
1285         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1286         dest->BufUsed = NCharsRemain;
1287         dest->buf[dest->BufUsed] = '\0';
1288         return NCharsRemain;
1289 }
1290
1291 /**
1292  * @ingroup StrBuf
1293  * @brief sprintf like function appending the formated string to the buffer
1294  * vsnprintf version to wrap into own calls
1295  * @param Buf Buffer to extend by format and Params
1296  * @param format printf alike format to add
1297  * @param ap va_list containing the items for format
1298  */
1299 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1300 {
1301         va_list apl;
1302         size_t BufSize;
1303         size_t nWritten;
1304         size_t Offset;
1305         size_t newused;
1306
1307         if ((Buf == NULL)  || (format == NULL))
1308                 return;
1309
1310         BufSize = Buf->BufSize;
1311         nWritten = Buf->BufSize + 1;
1312         Offset = Buf->BufUsed;
1313         newused = Offset + nWritten;
1314         
1315         while (newused >= BufSize) {
1316                 va_copy(apl, ap);
1317                 nWritten = vsnprintf(Buf->buf + Offset, 
1318                                      Buf->BufSize - Offset, 
1319                                      format, apl);
1320                 va_end(apl);
1321                 newused = Offset + nWritten;
1322                 if (newused >= Buf->BufSize) {
1323                         IncreaseBuf(Buf, 1, newused);
1324                         newused = Buf->BufSize + 1;
1325                 }
1326                 else {
1327                         Buf->BufUsed = Offset + nWritten;
1328                         BufSize = Buf->BufSize;
1329                 }
1330
1331         }
1332 }
1333
1334 /**
1335  * @ingroup StrBuf
1336  * @brief sprintf like function appending the formated string to the buffer
1337  * @param Buf Buffer to extend by format and Params
1338  * @param format printf alike format to add
1339  */
1340 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1341 {
1342         size_t BufSize;
1343         size_t nWritten;
1344         size_t Offset;
1345         size_t newused;
1346         va_list arg_ptr;
1347         
1348         if ((Buf == NULL)  || (format == NULL))
1349                 return;
1350
1351         BufSize = Buf->BufSize;
1352         nWritten = Buf->BufSize + 1;
1353         Offset = Buf->BufUsed;
1354         newused = Offset + nWritten;
1355
1356         while (newused >= BufSize) {
1357                 va_start(arg_ptr, format);
1358                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
1359                                      Buf->BufSize - Buf->BufUsed, 
1360                                      format, arg_ptr);
1361                 va_end(arg_ptr);
1362                 newused = Buf->BufUsed + nWritten;
1363                 if (newused >= Buf->BufSize) {
1364                         IncreaseBuf(Buf, 1, newused);
1365                         newused = Buf->BufSize + 1;
1366                 }
1367                 else {
1368                         Buf->BufUsed += nWritten;
1369                         BufSize = Buf->BufSize;
1370                 }
1371
1372         }
1373 }
1374
1375 /**
1376  * @ingroup StrBuf
1377  * @brief sprintf like function putting the formated string into the buffer
1378  * @param Buf Buffer to extend by format and Parameters
1379  * @param format printf alike format to add
1380  */
1381 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1382 {
1383         size_t nWritten;
1384         va_list arg_ptr;
1385         
1386         if ((Buf == NULL)  || (format == NULL))
1387                 return;
1388
1389         nWritten = Buf->BufSize + 1;
1390         while (nWritten >= Buf->BufSize) {
1391                 va_start(arg_ptr, format);
1392                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1393                 va_end(arg_ptr);
1394                 if (nWritten >= Buf->BufSize) {
1395                         IncreaseBuf(Buf, 0, 0);
1396                         nWritten = Buf->BufSize + 1;
1397                         continue;
1398                 }
1399                 Buf->BufUsed = nWritten ;
1400         }
1401 }
1402
1403
1404 /**
1405  * @ingroup StrBuf_Tokenizer
1406  * @brief Counts the numbmer of tokens in a buffer
1407  * @param source String to count tokens in
1408  * @param tok    Tokenizer char to count
1409  * @returns numbers of tokenizer chars found
1410  */
1411 int StrBufNum_tokens(const StrBuf *source, char tok)
1412 {
1413         if (source == NULL)
1414                 return 0;
1415         return num_tokens(source->buf, tok);
1416 }
1417
1418 /*
1419  * remove_token() - a tokenizer that kills, maims, and destroys
1420  */
1421 /**
1422  * @ingroup StrBuf_Tokenizer
1423  * @brief a string tokenizer
1424  * @param Source StringBuffer to read into
1425  * @param parmnum n'th Parameter to remove
1426  * @param separator tokenizer character
1427  * @returns -1 if not found, else length of token.
1428  */
1429 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1430 {
1431         int ReducedBy;
1432         char *d, *s, *end;              /* dest, source */
1433         int count = 0;
1434
1435         /* Find desired @parameter */
1436         end = Source->buf + Source->BufUsed;
1437         d = Source->buf;
1438         while ((count < parmnum) &&
1439                (d <= end))
1440         {
1441                 /* End of string, bail! */
1442                 if (!*d) {
1443                         d = NULL;
1444                         break;
1445                 }
1446                 if (*d == separator) {
1447                         count++;
1448                 }
1449                 d++;
1450         }
1451         if ((d == NULL) || (d >= end))
1452                 return 0;               /* @Parameter not found */
1453
1454         /* Find next @parameter */
1455         s = d;
1456         while ((*s && *s != separator) &&
1457                (s <= end))
1458         {
1459                 s++;
1460         }
1461         if (*s == separator)
1462                 s++;
1463         ReducedBy = d - s;
1464
1465         /* Hack and slash */
1466         if (*s) {
1467                 memmove(d, s, Source->BufUsed - (s - Source->buf));
1468                 Source->BufUsed += ReducedBy;
1469         }
1470         else if (d == Source->buf) {
1471                 *d = 0;
1472                 Source->BufUsed = 0;
1473         }
1474         else {
1475                 *--d = 0;
1476                 Source->BufUsed += ReducedBy;
1477         }
1478         /*
1479         while (*s) {
1480                 *d++ = *s++;
1481         }
1482         *d = 0;
1483         */
1484         return ReducedBy;
1485 }
1486
1487
1488 /**
1489  * @ingroup StrBuf_Tokenizer
1490  * @brief a string tokenizer
1491  * @param dest Destination StringBuffer
1492  * @param Source StringBuffer to read into
1493  * @param parmnum n'th Parameter to extract
1494  * @param separator tokenizer character
1495  * @returns -1 if not found, else length of token.
1496  */
1497 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1498 {
1499         const char *s, *e;              //* source * /
1500         int len = 0;                    //* running total length of extracted string * /
1501         int current_token = 0;          //* token currently being processed * /
1502          
1503         if (dest != NULL) {
1504                 dest->buf[0] = '\0';
1505                 dest->BufUsed = 0;
1506         }
1507         else
1508                 return(-1);
1509
1510         if ((Source == NULL) || (Source->BufUsed ==0)) {
1511                 return(-1);
1512         }
1513         s = Source->buf;
1514         e = s + Source->BufUsed;
1515
1516         //cit_backtrace();
1517         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1518
1519         while ((s<e) && !IsEmptyStr(s)) {
1520                 if (*s == separator) {
1521                         ++current_token;
1522                 }
1523                 if (len >= dest->BufSize) {
1524                         dest->BufUsed = len;
1525                         if (IncreaseBuf(dest, 1, -1) < 0) {
1526                                 dest->BufUsed --;
1527                                 break;
1528                         }
1529                 }
1530                 if ( (current_token == parmnum) && 
1531                      (*s != separator)) {
1532                         dest->buf[len] = *s;
1533                         ++len;
1534                 }
1535                 else if (current_token > parmnum) {
1536                         break;
1537                 }
1538                 ++s;
1539         }
1540         
1541         dest->buf[len] = '\0';
1542         dest->BufUsed = len;
1543                 
1544         if (current_token < parmnum) {
1545                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1546                 return(-1);
1547         }
1548         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1549         return(len);
1550 }
1551
1552
1553
1554
1555
1556 /**
1557  * @ingroup StrBuf_Tokenizer
1558  * @brief a string tokenizer to fetch an integer
1559  * @param Source String containing tokens
1560  * @param parmnum n'th Parameter to extract
1561  * @param separator tokenizer character
1562  * @returns 0 if not found, else integer representation of the token
1563  */
1564 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1565 {
1566         StrBuf tmp;
1567         char buf[64];
1568         
1569         tmp.buf = buf;
1570         buf[0] = '\0';
1571         tmp.BufSize = 64;
1572         tmp.BufUsed = 0;
1573         tmp.ConstBuf = 1;
1574         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1575                 return(atoi(buf));
1576         else
1577                 return 0;
1578 }
1579
1580 /**
1581  * @ingroup StrBuf_Tokenizer
1582  * @brief a string tokenizer to fetch a long integer
1583  * @param Source String containing tokens
1584  * @param parmnum n'th Parameter to extract
1585  * @param separator tokenizer character
1586  * @returns 0 if not found, else long integer representation of the token
1587  */
1588 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1589 {
1590         StrBuf tmp;
1591         char buf[64];
1592         
1593         tmp.buf = buf;
1594         buf[0] = '\0';
1595         tmp.BufSize = 64;
1596         tmp.BufUsed = 0;
1597         tmp.ConstBuf = 1;
1598         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1599                 return(atoi(buf));
1600         else
1601                 return 0;
1602 }
1603
1604
1605 /**
1606  * @ingroup StrBuf_Tokenizer
1607  * @brief a string tokenizer to fetch an unsigned long
1608  * @param Source String containing tokens
1609  * @param parmnum n'th Parameter to extract
1610  * @param separator tokenizer character
1611  * @returns 0 if not found, else unsigned long representation of the token
1612  */
1613 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1614 {
1615         StrBuf tmp;
1616         char buf[64];
1617         char *pnum;
1618         
1619         tmp.buf = buf;
1620         buf[0] = '\0';
1621         tmp.BufSize = 64;
1622         tmp.BufUsed = 0;
1623         tmp.ConstBuf = 1;
1624         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1625                 pnum = &buf[0];
1626                 if (*pnum == '-')
1627                         pnum ++;
1628                 return (unsigned long) atol(pnum);
1629         }
1630         else 
1631                 return 0;
1632 }
1633
1634
1635
1636 /**
1637  * @ingroup StrBuf_NextTokenizer
1638  * @brief a string tokenizer; Bounds checker
1639  *  function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1640  * @param Source our tokenbuffer
1641  * @param pStart the token iterator pointer to inspect
1642  * @returns whether the revolving pointer is inside of the search range
1643  */
1644 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1645 {
1646         if ((Source == NULL) || 
1647             (*pStart == StrBufNOTNULL) ||
1648             (Source->BufUsed == 0))
1649         {
1650                 return 0;
1651         }
1652         if (*pStart == NULL)
1653         {
1654                 return 1;
1655         }
1656         else if (*pStart > Source->buf + Source->BufUsed)
1657         {
1658                 return 0;
1659         }
1660         else if (*pStart <= Source->buf)
1661         {
1662                 return 0;
1663         }
1664
1665         return 1;
1666 }
1667
1668 /**
1669  * @ingroup StrBuf_NextTokenizer
1670  * @brief a string tokenizer
1671  * @param dest Destination StringBuffer
1672  * @param Source StringBuffer to read into
1673  * @param pStart pointer to the end of the last token. Feed with NULL on start.
1674  * @param separator tokenizer 
1675  * @returns -1 if not found, else length of token.
1676  */
1677 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1678 {
1679         const char *s;          /* source */
1680         const char *EndBuffer;  /* end stop of source buffer */
1681         int current_token = 0;  /* token currently being processed */
1682         int len = 0;            /* running total length of extracted string */
1683
1684         if ((Source          == NULL) || 
1685             (Source->BufUsed == 0)      ) 
1686         {
1687                 *pStart = StrBufNOTNULL;
1688                 return -1;
1689         }
1690          
1691         EndBuffer = Source->buf + Source->BufUsed;
1692
1693         if (dest != NULL) 
1694         {
1695                 dest->buf[0] = '\0';
1696                 dest->BufUsed = 0;
1697         }
1698         else
1699         {
1700                 *pStart = EndBuffer + 1;
1701                 return -1;
1702         }
1703
1704         if (*pStart == NULL)
1705         {
1706                 *pStart = Source->buf; /* we're starting to examine this buffer. */
1707         }
1708         else if ((*pStart < Source->buf) || 
1709                  (*pStart > EndBuffer  )   ) 
1710         {
1711                 return -1; /* no more tokens to find. */
1712         }
1713
1714         s = *pStart;
1715         /* start to find the next token */
1716         while ((s <= EndBuffer)      && 
1717                (current_token == 0) ) 
1718         {
1719                 if (*s == separator) 
1720                 {
1721                         /* we found the next token */
1722                         ++current_token;
1723                 }
1724
1725                 if (len >= dest->BufSize) 
1726                 {
1727                         /* our Dest-buffer isn't big enough, increase it. */
1728                         dest->BufUsed = len;
1729
1730                         if (IncreaseBuf(dest, 1, -1) < 0) {
1731                                 /* WHUT? no more mem? bail out. */
1732                                 s = EndBuffer;
1733                                 dest->BufUsed --;
1734                                 break;
1735                         }
1736                 }
1737
1738                 if ( (current_token == 0 ) &&   /* are we in our target token? */
1739                      (!IsEmptyStr(s)     ) &&
1740                      (separator     != *s)    ) /* don't copy the token itself */
1741                 {
1742                         dest->buf[len] = *s;    /* Copy the payload */
1743                         ++len;                  /* remember the bigger size. */
1744                 }
1745
1746                 ++s;
1747         }
1748
1749         /* did we reach the end? */
1750         if ((s > EndBuffer)) {
1751                 EndBuffer = StrBufNOTNULL;
1752                 *pStart = EndBuffer;
1753         }
1754         else {
1755                 *pStart = s;  /* remember the position for the next run */
1756         }
1757
1758         /* sanitize our extracted token */
1759         dest->buf[len] = '\0';
1760         dest->BufUsed  = len;
1761
1762         return (len);
1763 }
1764
1765
1766 /**
1767  * @ingroup StrBuf_NextTokenizer
1768  * @brief a string tokenizer
1769  * @param Source StringBuffer to read from
1770  * @param pStart pointer to the end of the last token. Feed with NULL.
1771  * @param separator tokenizer character
1772  * @param nTokens number of tokens to fastforward over
1773  * @returns -1 if not found, else length of token.
1774  */
1775 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1776 {
1777         const char *s, *EndBuffer;      //* source * /
1778         int len = 0;                    //* running total length of extracted string * /
1779         int current_token = 0;          //* token currently being processed * /
1780
1781         if ((Source == NULL) || 
1782             (Source->BufUsed ==0)) {
1783                 return(-1);
1784         }
1785         if (nTokens == 0)
1786                 return Source->BufUsed;
1787
1788         if (*pStart == NULL)
1789                 *pStart = Source->buf;
1790
1791         EndBuffer = Source->buf + Source->BufUsed;
1792
1793         if ((*pStart < Source->buf) || 
1794             (*pStart >  EndBuffer)) {
1795                 return (-1);
1796         }
1797
1798
1799         s = *pStart;
1800
1801         //cit_backtrace();
1802         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1803
1804         while ((s<EndBuffer) && !IsEmptyStr(s)) {
1805                 if (*s == separator) {
1806                         ++current_token;
1807                 }
1808                 if (current_token >= nTokens) {
1809                         break;
1810                 }
1811                 ++s;
1812         }
1813         *pStart = s;
1814         (*pStart) ++;
1815
1816         return(len);
1817 }
1818
1819 /**
1820  * @ingroup StrBuf_NextTokenizer
1821  * @brief a string tokenizer to fetch an integer
1822  * @param Source StringBuffer to read from
1823  * @param pStart Cursor on the tokenstring
1824  * @param separator tokenizer character
1825  * @returns 0 if not found, else integer representation of the token
1826  */
1827 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1828 {
1829         StrBuf tmp;
1830         char buf[64];
1831         
1832         tmp.buf = buf;
1833         buf[0] = '\0';
1834         tmp.BufSize = 64;
1835         tmp.BufUsed = 0;
1836         tmp.ConstBuf = 1;
1837         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1838                 return(atoi(buf));
1839         else
1840                 return 0;
1841 }
1842
1843 /**
1844  * @ingroup StrBuf_NextTokenizer
1845  * @brief a string tokenizer to fetch a long integer
1846  * @param Source StringBuffer to read from
1847  * @param pStart Cursor on the tokenstring
1848  * @param separator tokenizer character
1849  * @returns 0 if not found, else long integer representation of the token
1850  */
1851 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1852 {
1853         StrBuf tmp;
1854         char buf[64];
1855         
1856         tmp.buf = buf;
1857         buf[0] = '\0';
1858         tmp.BufSize = 64;
1859         tmp.BufUsed = 0;
1860         tmp.ConstBuf = 1;
1861         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1862                 return(atoi(buf));
1863         else
1864                 return 0;
1865 }
1866
1867
1868 /**
1869  * @ingroup StrBuf_NextTokenizer
1870  * @brief a string tokenizer to fetch an unsigned long
1871  * @param Source StringBuffer to read from
1872  * @param pStart Cursor on the tokenstring
1873  * @param separator tokenizer character
1874  * @returns 0 if not found, else unsigned long representation of the token
1875  */
1876 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1877 {
1878         StrBuf tmp;
1879         char buf[64];
1880         char *pnum;
1881         
1882         tmp.buf = buf;
1883         buf[0] = '\0';
1884         tmp.BufSize = 64;
1885         tmp.BufUsed = 0;
1886         tmp.ConstBuf = 1;
1887         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1888                 pnum = &buf[0];
1889                 if (*pnum == '-')
1890                         pnum ++;
1891                 return (unsigned long) atol(pnum);
1892         }
1893         else 
1894                 return 0;
1895 }
1896
1897
1898
1899 /**
1900  * @ingroup StrBuf_IO
1901  * @brief Read a line from socket
1902  * flushes and closes the FD on error
1903  * @param buf the buffer to get the input to
1904  * @param fd pointer to the filedescriptor to read
1905  * @param append Append to an existing string or replace?
1906  * @param Error strerror() on error 
1907  * @returns numbers of chars read
1908  */
1909 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1910 {
1911         int len, rlen, slen;
1912
1913         if (!append)
1914                 FlushStrBuf(buf);
1915
1916         slen = len = buf->BufUsed;
1917         while (1) {
1918                 rlen = read(*fd, &buf->buf[len], 1);
1919                 if (rlen < 1) {
1920                         *Error = strerror(errno);
1921                         
1922                         close(*fd);
1923                         *fd = -1;
1924                         
1925                         return -1;
1926                 }
1927                 if (buf->buf[len] == '\n')
1928                         break;
1929                 if (buf->buf[len] != '\r')
1930                         len ++;
1931                 if (len + 2 >= buf->BufSize) {
1932                         buf->BufUsed = len;
1933                         buf->buf[len+1] = '\0';
1934                         IncreaseBuf(buf, 1, -1);
1935                 }
1936         }
1937         buf->BufUsed = len;
1938         buf->buf[len] = '\0';
1939         return len - slen;
1940 }
1941
1942 /**
1943  * @ingroup StrBuf_BufferedIO
1944  * @brief Read a line from socket
1945  * flushes and closes the FD on error
1946  * @param Line the line to read from the fd / I/O Buffer
1947  * @param buf the buffer to get the input to
1948  * @param fd pointer to the filedescriptor to read
1949  * @param timeout number of successless selects until we bail out
1950  * @param selectresolution how long to wait on each select
1951  * @param Error strerror() on error 
1952  * @returns numbers of chars read
1953  */
1954 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1955                                  StrBuf *buf, 
1956                                  int *fd, 
1957                                  int timeout, 
1958                                  int selectresolution, 
1959                                  const char **Error)
1960 {
1961         int len, rlen;
1962         int nSuccessLess = 0;
1963         fd_set rfds;
1964         char *pch = NULL;
1965         int fdflags;
1966         int IsNonBlock;
1967         struct timeval tv;
1968
1969         if (buf->BufUsed > 0) {
1970                 pch = strchr(buf->buf, '\n');
1971                 if (pch != NULL) {
1972                         rlen = 0;
1973                         len = pch - buf->buf;
1974                         if (len > 0 && (*(pch - 1) == '\r') )
1975                                 rlen ++;
1976                         StrBufSub(Line, buf, 0, len - rlen);
1977                         StrBufCutLeft(buf, len + 1);
1978                         return len - rlen;
1979                 }
1980         }
1981         
1982         if (buf->BufSize - buf->BufUsed < 10)
1983                 IncreaseBuf(buf, 1, -1);
1984
1985         fdflags = fcntl(*fd, F_GETFL);
1986         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1987
1988         while ((nSuccessLess < timeout) && (pch == NULL)) {
1989                 if (IsNonBlock){
1990                         tv.tv_sec = selectresolution;
1991                         tv.tv_usec = 0;
1992                         
1993                         FD_ZERO(&rfds);
1994                         FD_SET(*fd, &rfds);
1995                         if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1996                                 *Error = strerror(errno);
1997                                 close (*fd);
1998                                 *fd = -1;
1999                                 return -1;
2000                         }
2001                 }
2002                 if (IsNonBlock && !  FD_ISSET(*fd, &rfds)) {
2003                         nSuccessLess ++;
2004                         continue;
2005                 }
2006                 rlen = read(*fd, 
2007                             &buf->buf[buf->BufUsed], 
2008                             buf->BufSize - buf->BufUsed - 1);
2009                 if (rlen < 1) {
2010                         *Error = strerror(errno);
2011                         close(*fd);
2012                         *fd = -1;
2013                         return -1;
2014                 }
2015                 else if (rlen > 0) {
2016                         nSuccessLess = 0;
2017                         buf->BufUsed += rlen;
2018                         buf->buf[buf->BufUsed] = '\0';
2019                         if (buf->BufUsed + 10 > buf->BufSize) {
2020                                 IncreaseBuf(buf, 1, -1);
2021                         }
2022                         pch = strchr(buf->buf, '\n');
2023                         continue;
2024                 }
2025                 
2026         }
2027         if (pch != NULL) {
2028                 rlen = 0;
2029                 len = pch - buf->buf;
2030                 if (len > 0 && (*(pch - 1) == '\r') )
2031                         rlen ++;
2032                 StrBufSub(Line, buf, 0, len - rlen);
2033                 StrBufCutLeft(buf, len + 1);
2034                 return len - rlen;
2035         }
2036         return -1;
2037
2038 }
2039
2040 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
2041 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
2042 /**
2043  * @ingroup StrBuf_BufferedIO
2044  * @brief Read a line from socket
2045  * flushes and closes the FD on error
2046  * @param Line Line to read from the fd / I/O Buffer
2047  * @param IOBuf the buffer to get the input to
2048  * @param Pos pointer to the current read position, should be NULL initialized!
2049  * @param fd pointer to the filedescriptor to read
2050  * @param timeout number of successless selects until we bail out
2051  * @param selectresolution how long to wait on each select
2052  * @param Error strerror() on error 
2053  * @returns numbers of chars read
2054  */
2055 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
2056                                       StrBuf *IOBuf, 
2057                                       const char **Pos,
2058                                       int *fd, 
2059                                       int timeout, 
2060                                       int selectresolution, 
2061                                       const char **Error)
2062 {
2063         const char *pche = NULL;
2064         const char *pos = NULL;
2065         int len, rlen;
2066         int nSuccessLess = 0;
2067         fd_set rfds;
2068         const char *pch = NULL;
2069         int fdflags;
2070         int IsNonBlock;
2071         struct timeval tv;
2072         
2073         pos = *Pos;
2074         if ((IOBuf->BufUsed > 0) && 
2075             (pos != NULL) && 
2076             (pos < IOBuf->buf + IOBuf->BufUsed)) 
2077         {
2078                 pche = IOBuf->buf + IOBuf->BufUsed;
2079                 pch = pos;
2080                 while ((pch < pche) && (*pch != '\n'))
2081                         pch ++;
2082                 if ((pch >= pche) || (*pch == '\0'))
2083                         pch = NULL;
2084                 if ((pch != NULL) && 
2085                     (pch <= pche)) 
2086                 {
2087                         rlen = 0;
2088                         len = pch - pos;
2089                         if (len > 0 && (*(pch - 1) == '\r') )
2090                                 rlen ++;
2091                         StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
2092                         *Pos = pch + 1;
2093                         return len - rlen;
2094                 }
2095         }
2096         
2097         if (pos != NULL) {
2098                 if (pos > pche)
2099                         FlushStrBuf(IOBuf);
2100                 else 
2101                         StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
2102                 *Pos = NULL;
2103         }
2104         
2105         if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
2106                 IncreaseBuf(IOBuf, 1, -1);
2107         }
2108
2109         fdflags = fcntl(*fd, F_GETFL);
2110         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2111
2112         pch = NULL;
2113         while ((nSuccessLess < timeout) && 
2114                (pch == NULL) &&
2115                (*fd != -1)) {
2116                 if (IsNonBlock)
2117                 {
2118                         tv.tv_sec = 1;
2119                         tv.tv_usec = 0;
2120                 
2121                         FD_ZERO(&rfds);
2122                         FD_SET(*fd, &rfds);
2123                         if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
2124                                 *Error = strerror(errno);
2125                                 close (*fd);
2126                                 *fd = -1;
2127                                 if (*Error == NULL)
2128                                         *Error = ErrRBLF_SelectFailed;
2129                                 return -1;
2130                         }
2131                         if (! FD_ISSET(*fd, &rfds) != 0) {
2132                                 nSuccessLess ++;
2133                                 continue;
2134                         }
2135                 }
2136                 rlen = read(*fd, 
2137                             &IOBuf->buf[IOBuf->BufUsed], 
2138                             IOBuf->BufSize - IOBuf->BufUsed - 1);
2139                 if (rlen < 1) {
2140                         *Error = strerror(errno);
2141                         close(*fd);
2142                         *fd = -1;
2143                         return -1;
2144                 }
2145                 else if (rlen > 0) {
2146                         nSuccessLess = 0;
2147                         IOBuf->BufUsed += rlen;
2148                         IOBuf->buf[IOBuf->BufUsed] = '\0';
2149                         if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
2150                                 IncreaseBuf(IOBuf, 1, -1);
2151                         }
2152                         
2153                         pche = IOBuf->buf + IOBuf->BufUsed;
2154                         pch = IOBuf->buf;
2155                         while ((pch < pche) && (*pch != '\n'))
2156                                 pch ++;
2157                         if ((pch >= pche) || (*pch == '\0'))
2158                                 pch = NULL;
2159                         continue;
2160                 }
2161         }
2162         if (pch != NULL) {
2163                 pos = IOBuf->buf;
2164                 rlen = 0;
2165                 len = pch - pos;
2166                 if (len > 0 && (*(pch - 1) == '\r') )
2167                         rlen ++;
2168                 StrBufSub(Line, IOBuf, 0, len - rlen);
2169                 *Pos = pos + len + 1;
2170                 return len - rlen;
2171         }
2172         *Error = ErrRBLF_NotEnoughSentFromServer;
2173         return -1;
2174
2175 }
2176
2177 /**
2178  * @ingroup StrBuf_IO
2179  * @brief Input binary data from socket
2180  * flushes and closes the FD on error
2181  * @param Buf the buffer to get the input to
2182  * @param fd pointer to the filedescriptor to read
2183  * @param append Append to an existing string or replace?
2184  * @param nBytes the maximal number of bytes to read
2185  * @param Error strerror() on error 
2186  * @returns numbers of chars read
2187  */
2188 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
2189 {
2190         int fdflags;
2191         int len, rlen, slen;
2192         int nSuccessLess;
2193         int nRead = 0;
2194         char *ptr;
2195         int IsNonBlock;
2196         struct timeval tv;
2197         fd_set rfds;
2198         if ((Buf == NULL) || (*fd == -1))
2199                 return -1;
2200         if (!append)
2201                 FlushStrBuf(Buf);
2202         if (Buf->BufUsed + nBytes >= Buf->BufSize)
2203                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
2204
2205         ptr = Buf->buf + Buf->BufUsed;
2206
2207         slen = len = Buf->BufUsed;
2208
2209         fdflags = fcntl(*fd, F_GETFL);
2210         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2211         nSuccessLess = 0;
2212         while ((nRead < nBytes) && 
2213                (*fd != -1)) 
2214         {
2215                 if (IsNonBlock)
2216                 {
2217                         tv.tv_sec = 1;
2218                         tv.tv_usec = 0;
2219                 
2220                         FD_ZERO(&rfds);
2221                         FD_SET(*fd, &rfds);
2222                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2223                                 *Error = strerror(errno);
2224                                 close (*fd);
2225                                 *fd = -1;
2226                                 if (*Error == NULL)
2227                                         *Error = ErrRBLF_SelectFailed;
2228                                 return -1;
2229                         }
2230                         if (! FD_ISSET(*fd, &rfds) != 0) {
2231                                 nSuccessLess ++;
2232                                 continue;
2233                         }
2234                 }
2235
2236                 if ((rlen = read(*fd, 
2237                                  ptr,
2238                                  nBytes - nRead)) == -1) {
2239                         close(*fd);
2240                         *fd = -1;
2241                         *Error = strerror(errno);
2242                         return rlen;
2243                 }
2244                 nRead += rlen;
2245                 ptr += rlen;
2246                 Buf->BufUsed += rlen;
2247         }
2248         Buf->buf[Buf->BufUsed] = '\0';
2249         return nRead;
2250 }
2251
2252 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
2253 /**
2254  * @ingroup StrBuf_BufferedIO
2255  * @brief Input binary data from socket
2256  * flushes and closes the FD on error
2257  * @param Blob put binary thing here
2258  * @param IOBuf the buffer to get the input to
2259  * @param Pos offset inside of IOBuf
2260  * @param fd pointer to the filedescriptor to read
2261  * @param append Append to an existing string or replace?
2262  * @param nBytes the maximal number of bytes to read
2263  * @param check whether we should search for '000\n' terminators in case of timeouts
2264  * @param Error strerror() on error 
2265  * @returns numbers of chars read
2266  */
2267 int StrBufReadBLOBBuffered(StrBuf *Blob, 
2268                            StrBuf *IOBuf, 
2269                            const char **Pos,
2270                            int *fd, 
2271                            int append, 
2272                            long nBytes, 
2273                            int check, 
2274                            const char **Error)
2275 {
2276         const char *pche;
2277         const char *pos;
2278         int nSelects = 0;
2279         int SelRes;
2280         int fdflags;
2281         int len = 0;
2282         int rlen, slen;
2283         int nRead = 0;
2284         int nAlreadyRead = 0;
2285         int IsNonBlock;
2286         char *ptr;
2287         fd_set rfds;
2288         const char *pch;
2289         struct timeval tv;
2290         int nSuccessLess;
2291
2292         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2293                 return -1;
2294         if (!append)
2295                 FlushStrBuf(Blob);
2296         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
2297                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2298         
2299         pos = *Pos;
2300
2301         if (pos > 0)
2302                 len = pos - IOBuf->buf;
2303         rlen = IOBuf->BufUsed - len;
2304
2305
2306         if ((IOBuf->BufUsed > 0) && 
2307             (pos != NULL) && 
2308             (pos < IOBuf->buf + IOBuf->BufUsed)) 
2309         {
2310                 pche = IOBuf->buf + IOBuf->BufUsed;
2311                 pch = pos;
2312
2313                 if (rlen < nBytes) {
2314                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2315                         Blob->BufUsed += rlen;
2316                         Blob->buf[Blob->BufUsed] = '\0';
2317                         nAlreadyRead = nRead = rlen;
2318                         *Pos = NULL; 
2319                 }
2320                 if (rlen >= nBytes) {
2321                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2322                         Blob->BufUsed += nBytes;
2323                         Blob->buf[Blob->BufUsed] = '\0';
2324                         if (rlen == nBytes) {
2325                                 *Pos = NULL; 
2326                                 FlushStrBuf(IOBuf);
2327                         }
2328                         else 
2329                                 *Pos += nBytes;
2330                         return nBytes;
2331                 }
2332         }
2333
2334         FlushStrBuf(IOBuf);
2335         if (IOBuf->BufSize < nBytes - nRead)
2336                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2337         ptr = IOBuf->buf;
2338
2339         slen = len = Blob->BufUsed;
2340
2341         fdflags = fcntl(*fd, F_GETFL);
2342         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2343
2344         SelRes = 1;
2345         nBytes -= nRead;
2346         nRead = 0;
2347         while ((nRead < nBytes) &&
2348                (*fd != -1)) {
2349                 if (IsNonBlock)
2350                 {
2351                         tv.tv_sec = 1;
2352                         tv.tv_usec = 0;
2353                 
2354                         FD_ZERO(&rfds);
2355                         FD_SET(*fd, &rfds);
2356                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2357                                 *Error = strerror(errno);
2358                                 close (*fd);
2359                                 *fd = -1;
2360                                 if (*Error == NULL)
2361                                         *Error = ErrRBLF_SelectFailed;
2362                                 return -1;
2363                         }
2364                         if (! FD_ISSET(*fd, &rfds) != 0) {
2365                                 nSuccessLess ++;
2366                                 continue;
2367                         }
2368                 }
2369                 nSuccessLess = 0;
2370                 rlen = read(*fd, 
2371                             ptr,
2372                             nBytes - nRead);
2373                 if (rlen == -1) {
2374                         close(*fd);
2375                         *fd = -1;
2376                         *Error = strerror(errno);
2377                         return rlen;
2378                 }
2379                 else if (rlen == 0){
2380                         nSuccessLess ++;
2381                         if ((check == NNN_TERM) && 
2382                             (nRead > 5) &&
2383                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
2384                         {
2385                                 StrBufPlain(Blob, HKEY("\n000\n"));
2386                                 StrBufCutRight(Blob, 5);
2387                                 return Blob->BufUsed;
2388                         }
2389                         if (nSelects > 10) {
2390                                 FlushStrBuf(IOBuf);
2391                                 *Error = ErrRBB_too_many_selects;
2392                                 return -1;
2393                         }
2394                 }
2395                 else if (rlen > 0) {
2396                         nRead += rlen;
2397                         ptr += rlen;
2398                         IOBuf->BufUsed += rlen;
2399                 }
2400         }
2401         if (nRead > nBytes) {
2402                 *Pos = IOBuf->buf + nBytes;
2403         }
2404         Blob->buf[Blob->BufUsed] = '\0';
2405         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2406         if (*Pos == NULL) {
2407                 FlushStrBuf(IOBuf);
2408         }
2409         return nRead + nAlreadyRead;
2410 }
2411
2412 /**
2413  * @ingroup StrBuf
2414  * @brief Cut nChars from the start of the string
2415  * @param Buf Buffer to modify
2416  * @param nChars how many chars should be skipped?
2417  */
2418 void StrBufCutLeft(StrBuf *Buf, int nChars)
2419 {
2420         if (nChars >= Buf->BufUsed) {
2421                 FlushStrBuf(Buf);
2422                 return;
2423         }
2424         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2425         Buf->BufUsed -= nChars;
2426         Buf->buf[Buf->BufUsed] = '\0';
2427 }
2428
2429 /**
2430  * @ingroup StrBuf
2431  * @brief Cut the trailing n Chars from the string
2432  * @param Buf Buffer to modify
2433  * @param nChars how many chars should be trunkated?
2434  */
2435 void StrBufCutRight(StrBuf *Buf, int nChars)
2436 {
2437         if (nChars >= Buf->BufUsed) {
2438                 FlushStrBuf(Buf);
2439                 return;
2440         }
2441         Buf->BufUsed -= nChars;
2442         Buf->buf[Buf->BufUsed] = '\0';
2443 }
2444
2445 /**
2446  * @ingroup StrBuf
2447  * @brief Cut the string after n Chars
2448  * @param Buf Buffer to modify
2449  * @param AfternChars after how many chars should we trunkate the string?
2450  * @param At if non-null and points inside of our string, cut it there.
2451  */
2452 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2453 {
2454         if (At != NULL){
2455                 AfternChars = At - Buf->buf;
2456         }
2457
2458         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2459                 return;
2460         Buf->BufUsed = AfternChars;
2461         Buf->buf[Buf->BufUsed] = '\0';
2462 }
2463
2464
2465 /**
2466  * @ingroup StrBuf
2467  * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2468  * @param Buf the string to modify
2469  */
2470 void StrBufTrim(StrBuf *Buf)
2471 {
2472         int delta = 0;
2473         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2474
2475         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2476                 delta ++;
2477         }
2478         if (delta > 0) StrBufCutLeft(Buf, delta);
2479
2480         if (Buf->BufUsed == 0) return;
2481         while (isspace(Buf->buf[Buf->BufUsed - 1])){
2482                 Buf->BufUsed --;
2483         }
2484         Buf->buf[Buf->BufUsed] = '\0';
2485 }
2486
2487 /**
2488  * @ingroup StrBuf
2489  * @brief uppercase the contents of a buffer
2490  * @param Buf the buffer to translate
2491  */
2492 void StrBufUpCase(StrBuf *Buf) 
2493 {
2494         char *pch, *pche;
2495
2496         pch = Buf->buf;
2497         pche = pch + Buf->BufUsed;
2498         while (pch < pche) {
2499                 *pch = toupper(*pch);
2500                 pch ++;
2501         }
2502 }
2503
2504
2505 /**
2506  * @ingroup StrBuf
2507  * @brief lowercase the contents of a buffer
2508  * @param Buf the buffer to translate
2509  */
2510 void StrBufLowerCase(StrBuf *Buf) 
2511 {
2512         char *pch, *pche;
2513
2514         pch = Buf->buf;
2515         pche = pch + Buf->BufUsed;
2516         while (pch < pche) {
2517                 *pch = tolower(*pch);
2518                 pch ++;
2519         }
2520 }
2521
2522 /**
2523  * @ingroup StrBuf
2524  * @brief removes double slashes from pathnames
2525  * @param Dir directory string to filter
2526  * @param RemoveTrailingSlash allows / disallows trailing slashes
2527  */
2528 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2529 {
2530         char *a, *b;
2531
2532         a = b = Dir->buf;
2533
2534         while (!IsEmptyStr(a)) {
2535                 if (*a == '/') {
2536                         while (*a == '/')
2537                                 a++;
2538                         *b = '/';
2539                         b++;
2540                 }
2541                 else {
2542                         *b = *a;
2543                         b++; a++;
2544                 }
2545         }
2546         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2547                 *b = '/';
2548                 b++;
2549         }
2550         *b = '\0';
2551         Dir->BufUsed = b - Dir->buf;
2552 }
2553
2554 /**
2555  * @ingroup StrBuf_DeEnCoder
2556  * @brief unhide special chars hidden to the HTML escaper
2557  * @param target buffer to put the unescaped string in
2558  * @param source buffer to unescape
2559  */
2560 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2561 {
2562         int a, b, len;
2563         char hex[3];
2564
2565         if (target != NULL)
2566                 FlushStrBuf(target);
2567
2568         if (source == NULL ||target == NULL)
2569         {
2570                 return;
2571         }
2572
2573         len = source->BufUsed;
2574         for (a = 0; a < len; ++a) {
2575                 if (target->BufUsed >= target->BufSize)
2576                         IncreaseBuf(target, 1, -1);
2577
2578                 if (source->buf[a] == '=') {
2579                         hex[0] = source->buf[a + 1];
2580                         hex[1] = source->buf[a + 2];
2581                         hex[2] = 0;
2582                         b = 0;
2583                         sscanf(hex, "%02x", &b);
2584                         target->buf[target->BufUsed] = b;
2585                         target->buf[++target->BufUsed] = 0;
2586                         a += 2;
2587                 }
2588                 else {
2589                         target->buf[target->BufUsed] = source->buf[a];
2590                         target->buf[++target->BufUsed] = 0;
2591                 }
2592         }
2593 }
2594
2595
2596 /**
2597  * @ingroup StrBuf_DeEnCoder
2598  * @brief hide special chars from the HTML escapers and friends
2599  * @param target buffer to put the escaped string in
2600  * @param source buffer to escape
2601  */
2602 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2603 {
2604         int i, len;
2605
2606         if (target != NULL)
2607                 FlushStrBuf(target);
2608
2609         if (source == NULL ||target == NULL)
2610         {
2611                 return;
2612         }
2613
2614         len = source->BufUsed;
2615         for (i=0; i<len; ++i) {
2616                 if (target->BufUsed + 4 >= target->BufSize)
2617                         IncreaseBuf(target, 1, -1);
2618                 if ( (isalnum(source->buf[i])) || 
2619                      (source->buf[i]=='-') || 
2620                      (source->buf[i]=='_') ) {
2621                         target->buf[target->BufUsed++] = source->buf[i];
2622                 }
2623                 else {
2624                         sprintf(&target->buf[target->BufUsed], 
2625                                 "=%02X", 
2626                                 (0xFF &source->buf[i]));
2627                         target->BufUsed += 3;
2628                 }
2629         }
2630         target->buf[target->BufUsed + 1] = '\0';
2631 }
2632
2633 #ifdef HAVE_ZLIB
2634 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2635 #define OS_CODE 0x03    /*< unix */
2636
2637 /**
2638  * @ingroup StrBuf_DeEnCoder
2639  * @brief uses the same calling syntax as compress2(), but it
2640  *   creates a stream compatible with HTTP "Content-encoding: gzip"
2641  * @param dest compressed buffer
2642  * @param destLen length of the compresed data 
2643  * @param source source to encode
2644  * @param sourceLen length of source to encode 
2645  * @param level compression level
2646  */
2647 int ZEXPORT compress_gzip(Bytef * dest,
2648                           size_t * destLen,
2649                           const Bytef * source,
2650                           uLong sourceLen,     
2651                           int level)
2652 {
2653         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2654
2655         /* write gzip header */
2656         snprintf((char *) dest, *destLen, 
2657                  "%c%c%c%c%c%c%c%c%c%c",
2658                  gz_magic[0], gz_magic[1], Z_DEFLATED,
2659                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2660                  OS_CODE);
2661
2662         /* normal deflate */
2663         z_stream stream;
2664         int err;
2665         stream.next_in = (Bytef *) source;
2666         stream.avail_in = (uInt) sourceLen;
2667         stream.next_out = dest + 10L;   // after header
2668         stream.avail_out = (uInt) * destLen;
2669         if ((uLong) stream.avail_out != *destLen)
2670                 return Z_BUF_ERROR;
2671
2672         stream.zalloc = (alloc_func) 0;
2673         stream.zfree = (free_func) 0;
2674         stream.opaque = (voidpf) 0;
2675
2676         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2677                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2678         if (err != Z_OK)
2679                 return err;
2680
2681         err = deflate(&stream, Z_FINISH);
2682         if (err != Z_STREAM_END) {
2683                 deflateEnd(&stream);
2684                 return err == Z_OK ? Z_BUF_ERROR : err;
2685         }
2686         *destLen = stream.total_out + 10L;
2687
2688         /* write CRC and Length */
2689         uLong crc = crc32(0L, source, sourceLen);
2690         int n;
2691         for (n = 0; n < 4; ++n, ++*destLen) {
2692                 dest[*destLen] = (int) (crc & 0xff);
2693                 crc >>= 8;
2694         }
2695         uLong len = stream.total_in;
2696         for (n = 0; n < 4; ++n, ++*destLen) {
2697                 dest[*destLen] = (int) (len & 0xff);
2698                 len >>= 8;
2699         }
2700         err = deflateEnd(&stream);
2701         return err;
2702 }
2703 #endif
2704
2705
2706 /**
2707  * @ingroup StrBuf_DeEnCoder
2708  * @brief compress the buffer with gzip
2709  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2710  * @param Buf buffer whose content is to be gzipped
2711  */
2712 int CompressBuffer(StrBuf *Buf)
2713 {
2714 #ifdef HAVE_ZLIB
2715         char *compressed_data = NULL;
2716         size_t compressed_len, bufsize;
2717         int i = 0;
2718
2719         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
2720         compressed_data = malloc(compressed_len);
2721         
2722         if (compressed_data == NULL)
2723                 return -1;
2724         /* Flush some space after the used payload so valgrind shuts up... */
2725         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2726                 Buf->buf[Buf->BufUsed + i++] = '\0';
2727         if (compress_gzip((Bytef *) compressed_data,
2728                           &compressed_len,
2729                           (Bytef *) Buf->buf,
2730                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2731                 if (!Buf->ConstBuf)
2732                         free(Buf->buf);
2733                 Buf->buf = compressed_data;
2734                 Buf->BufUsed = compressed_len;
2735                 Buf->BufSize = bufsize;
2736                 /* Flush some space after the used payload so valgrind shuts up... */
2737                 i = 0;
2738                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2739                         Buf->buf[Buf->BufUsed + i++] = '\0';
2740                 return 1;
2741         } else {
2742                 free(compressed_data);
2743         }
2744 #endif  /* HAVE_ZLIB */
2745         return 0;
2746 }
2747
2748 /**
2749  * @ingroup StrBuf_DeEnCoder
2750  * @brief decode a buffer from base 64 encoding; destroys original
2751  * @param Buf Buffor to transform
2752  */
2753 int StrBufDecodeBase64(StrBuf *Buf)
2754 {
2755         char *xferbuf;
2756         size_t siz;
2757         if (Buf == NULL) return -1;
2758
2759         xferbuf = (char*) malloc(Buf->BufSize);
2760         siz = CtdlDecodeBase64(xferbuf,
2761                                Buf->buf,
2762                                Buf->BufUsed);
2763         free(Buf->buf);
2764         Buf->buf = xferbuf;
2765         Buf->BufUsed = siz;
2766         return siz;
2767 }
2768
2769 /**
2770  * @ingroup StrBuf_DeEnCoder
2771  * @brief decode a buffer from base 64 encoding; destroys original
2772  * @param Buf Buffor to transform
2773  */
2774 int StrBufDecodeHex(StrBuf *Buf)
2775 {
2776         unsigned int ch;
2777         char *pch, *pche, *pchi;
2778
2779         if (Buf == NULL) return -1;
2780
2781         pch = pchi = Buf->buf;
2782         pche = pch + Buf->BufUsed;
2783
2784         while (pchi < pche){
2785                 ch = decode_hex(pchi);
2786                 *pch = ch;
2787                 pch ++;
2788                 pchi += 2;
2789         }
2790
2791         *pch = '\0';
2792         Buf->BufUsed = pch - Buf->buf;
2793         return Buf->BufUsed;
2794 }
2795
2796 /**
2797  * @ingroup StrBuf_DeEnCoder
2798  * @brief replace all chars >0x20 && < 0x7F with Mute
2799  * @param Mute char to put over invalid chars
2800  * @param Buf Buffor to transform
2801  */
2802 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2803 {
2804         unsigned char *pch;
2805
2806         if (Buf == NULL) return -1;
2807         pch = (unsigned char *)Buf->buf;
2808         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2809                 if ((*pch < 0x20) || (*pch > 0x7F))
2810                         *pch = Mute;
2811                 pch ++;
2812         }
2813         return Buf->BufUsed;
2814 }
2815
2816
2817 /**
2818  * @ingroup StrBuf_DeEnCoder
2819  * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2820  * @param Buf Buffer to translate
2821  * @param StripBlanks Reduce several blanks to one?
2822  */
2823 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2824 {
2825         int a, b;
2826         char hex[3];
2827         long len;
2828
2829         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2830                 Buf->buf[Buf->BufUsed - 1] = '\0';
2831                 Buf->BufUsed --;
2832         }
2833
2834         a = 0; 
2835         while (a < Buf->BufUsed) {
2836                 if (Buf->buf[a] == '+')
2837                         Buf->buf[a] = ' ';
2838                 else if (Buf->buf[a] == '%') {
2839                         /* don't let % chars through, rather truncate the input. */
2840                         if (a + 2 > Buf->BufUsed) {
2841                                 Buf->buf[a] = '\0';
2842                                 Buf->BufUsed = a;
2843                         }
2844                         else {                  
2845                                 hex[0] = Buf->buf[a + 1];
2846                                 hex[1] = Buf->buf[a + 2];
2847                                 hex[2] = 0;
2848                                 b = 0;
2849                                 sscanf(hex, "%02x", &b);
2850                                 Buf->buf[a] = (char) b;
2851                                 len = Buf->BufUsed - a - 2;
2852                                 if (len > 0)
2853                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2854                         
2855                                 Buf->BufUsed -=2;
2856                         }
2857                 }
2858                 a++;
2859         }
2860         return a;
2861 }
2862
2863
2864 /**
2865  * @ingroup StrBuf_DeEnCoder
2866  * @brief       RFC2047-encode a header field if necessary.
2867  *              If no non-ASCII characters are found, the string
2868  *              will be copied verbatim without encoding.
2869  *
2870  * @param       target          Target buffer.
2871  * @param       source          Source string to be encoded.
2872  * @returns     encoded length; -1 if non success.
2873  */
2874 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2875 {
2876         const char headerStr[] = "=?UTF-8?Q?";
2877         int need_to_encode = 0;
2878         int i = 0;
2879         unsigned char ch;
2880
2881         if ((source == NULL) || 
2882             (target == NULL))
2883             return -1;
2884
2885         while ((i < source->BufUsed) &&
2886                (!IsEmptyStr (&source->buf[i])) &&
2887                (need_to_encode == 0)) {
2888                 if (((unsigned char) source->buf[i] < 32) || 
2889                     ((unsigned char) source->buf[i] > 126)) {
2890                         need_to_encode = 1;
2891                 }
2892                 i++;
2893         }
2894
2895         if (!need_to_encode) {
2896                 if (*target == NULL) {
2897                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2898                 }
2899                 else {
2900                         FlushStrBuf(*target);
2901                         StrBufAppendBuf(*target, source, 0);
2902                 }
2903                 return (*target)->BufUsed;
2904         }
2905         if (*target == NULL)
2906                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2907         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2908                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2909         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2910         (*target)->BufUsed = sizeof(headerStr) - 1;
2911         for (i=0; (i < source->BufUsed); ++i) {
2912                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2913                         IncreaseBuf(*target, 1, 0);
2914                 ch = (unsigned char) source->buf[i];
2915                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2916                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2917                         (*target)->BufUsed += 3;
2918                 }
2919                 else {
2920                         (*target)->buf[(*target)->BufUsed] = ch;
2921                         (*target)->BufUsed++;
2922                 }
2923         }
2924         
2925         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2926                 IncreaseBuf(*target, 1, 0);
2927
2928         (*target)->buf[(*target)->BufUsed++] = '?';
2929         (*target)->buf[(*target)->BufUsed++] = '=';
2930         (*target)->buf[(*target)->BufUsed] = '\0';
2931         return (*target)->BufUsed;;
2932 }
2933
2934 /**
2935  * @ingroup StrBuf
2936  * @brief replaces all occurances of 'search' by 'replace'
2937  * @param buf Buffer to modify
2938  * @param search character to search
2939  * @param replace character to replace search by
2940  */
2941 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2942 {
2943         long i;
2944         if (buf == NULL)
2945                 return;
2946         for (i=0; i<buf->BufUsed; i++)
2947                 if (buf->buf[i] == search)
2948                         buf->buf[i] = replace;
2949
2950 }
2951
2952
2953
2954 /**
2955  * @ingroup StrBuf_DeEnCoder
2956  * @brief Wrapper around iconv_open()
2957  * Our version adds aliases for non-standard Microsoft charsets
2958  * such as 'MS950', aliasing them to names like 'CP950'
2959  *
2960  * @param tocode        Target encoding
2961  * @param fromcode      Source encoding
2962  * @param pic           anonimized pointer to iconv struct
2963  */
2964 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2965 {
2966 #ifdef HAVE_ICONV
2967         iconv_t ic = (iconv_t)(-1) ;
2968         ic = iconv_open(tocode, fromcode);
2969         if (ic == (iconv_t)(-1) ) {
2970                 char alias_fromcode[64];
2971                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2972                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2973                         alias_fromcode[0] = 'C';
2974                         alias_fromcode[1] = 'P';
2975                         ic = iconv_open(tocode, alias_fromcode);
2976                 }
2977         }
2978         *(iconv_t *)pic = ic;
2979 #endif
2980 }
2981
2982
2983 /**
2984  * @ingroup StrBuf_DeEnCoder
2985  * @brief find one chunk of a RFC822 encoded string
2986  * @param Buffer where to search
2987  * @param bptr where to start searching
2988  * @returns found position, NULL if none.
2989  */
2990 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2991 {
2992         char * end;
2993         /* Find the next ?Q? */
2994         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2995                 return NULL;
2996
2997         end = strchr(bptr + 2, '?');
2998
2999         if (end == NULL)
3000                 return NULL;
3001
3002         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
3003             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
3004             (*(end + 2) == '?')) {
3005                 /* skip on to the end of the cluster, the next ?= */
3006                 end = strstr(end + 3, "?=");
3007         }
3008         else
3009                 /* sort of half valid encoding, try to find an end. */
3010                 end = strstr(bptr, "?=");
3011         return end;
3012 }
3013
3014 /**
3015  * @ingroup StrBuf
3016  * @brief swaps the contents of two StrBufs
3017  * this is to be used to have cheap switched between a work-buffer and a target buffer 
3018  * @param A First one
3019  * @param B second one
3020  */
3021 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
3022 {
3023         StrBuf C;
3024
3025         memcpy(&C, A, sizeof(*A));
3026         memcpy(A, B, sizeof(*B));
3027         memcpy(B, &C, sizeof(C));
3028
3029 }
3030
3031
3032 /**
3033  * @ingroup StrBuf_DeEnCoder
3034  * @brief convert one buffer according to the preselected iconv pointer PIC
3035  * @param ConvertBuf buffer we need to translate
3036  * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3037  * @param pic Pointer to the iconv-session Object
3038  */
3039 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
3040 {
3041 #ifdef HAVE_ICONV
3042         long trycount = 0;
3043         size_t siz;
3044         iconv_t ic;
3045         char *ibuf;                     /**< Buffer of characters to be converted */
3046         char *obuf;                     /**< Buffer for converted characters */
3047         size_t ibuflen;                 /**< Length of input buffer */
3048         size_t obuflen;                 /**< Length of output buffer */
3049
3050
3051         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3052         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3053                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3054 TRYAGAIN:
3055         ic = *(iconv_t*)pic;
3056         ibuf = ConvertBuf->buf;
3057         ibuflen = ConvertBuf->BufUsed;
3058         obuf = TmpBuf->buf;
3059         obuflen = TmpBuf->BufSize;
3060         
3061         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3062
3063         if (siz < 0) {
3064                 if (errno == E2BIG) {
3065                         trycount ++;                    
3066                         IncreaseBuf(TmpBuf, 0, 0);
3067                         if (trycount < 5) 
3068                                 goto TRYAGAIN;
3069
3070                 }
3071                 else if (errno == EILSEQ){ 
3072                         /* hm, invalid utf8 sequence... what to do now? */
3073                         /* An invalid multibyte sequence has been encountered in the input */
3074                 }
3075                 else if (errno == EINVAL) {
3076                         /* An incomplete multibyte sequence has been encountered in the input. */
3077                 }
3078
3079                 FlushStrBuf(TmpBuf);
3080         }
3081         else {
3082                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3083                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3084                 
3085                 /* little card game: wheres the red lady? */
3086                 SwapBuffers(ConvertBuf, TmpBuf);
3087                 FlushStrBuf(TmpBuf);
3088         }
3089 #endif
3090 }
3091
3092
3093 /**
3094  * @ingroup StrBuf_DeEnCoder
3095  * @brief catches one RFC822 encoded segment, and decodes it.
3096  * @param Target buffer to fill with result
3097  * @param DecodeMe buffer with stuff to process
3098  * @param SegmentStart points to our current segment in DecodeMe
3099  * @param SegmentEnd Points to the end of our current segment in DecodeMe
3100  * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3101  * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3102  * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3103  */
3104 inline static void DecodeSegment(StrBuf *Target, 
3105                                  const StrBuf *DecodeMe, 
3106                                  char *SegmentStart, 
3107                                  char *SegmentEnd, 
3108                                  StrBuf *ConvertBuf,
3109                                  StrBuf *ConvertBuf2, 
3110                                  StrBuf *FoundCharset)
3111 {
3112         StrBuf StaticBuf;
3113         char charset[128];
3114         char encoding[16];
3115 #ifdef HAVE_ICONV
3116         iconv_t ic = (iconv_t)(-1);
3117 #else
3118         void *ic = NULL;
3119 #endif
3120         /* Now we handle foreign character sets properly encoded
3121          * in RFC2047 format.
3122          */
3123         StaticBuf.buf = SegmentStart;
3124         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3125         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3126         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3127         if (FoundCharset != NULL) {
3128                 FlushStrBuf(FoundCharset);
3129                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3130         }
3131         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3132         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3133         
3134         *encoding = toupper(*encoding);
3135         if (*encoding == 'B') { /**< base64 */
3136                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
3137                                                         ConvertBuf->buf, 
3138                                                         ConvertBuf->BufUsed);
3139         }
3140         else if (*encoding == 'Q') {    /**< quoted-printable */
3141                 long pos;
3142                 
3143                 pos = 0;
3144                 while (pos < ConvertBuf->BufUsed)
3145                 {
3146                         if (ConvertBuf->buf[pos] == '_') 
3147                                 ConvertBuf->buf[pos] = ' ';
3148                         pos++;
3149                 }
3150                 
3151                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3152                         ConvertBuf2->buf, 
3153                         ConvertBuf->buf,
3154                         ConvertBuf->BufUsed);
3155         }
3156         else {
3157                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3158         }
3159 #ifdef HAVE_ICONV
3160         ctdl_iconv_open("UTF-8", charset, &ic);
3161         if (ic != (iconv_t)(-1) ) {             
3162 #endif
3163                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3164                 StrBufAppendBuf(Target, ConvertBuf2, 0);
3165 #ifdef HAVE_ICONV
3166                 iconv_close(ic);
3167         }
3168         else {
3169                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3170         }
3171 #endif
3172 }
3173
3174 /**
3175  * @ingroup StrBuf_DeEnCoder
3176  * @brief Handle subjects with RFC2047 encoding such as:
3177  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3178  * @param Target where to put the decoded string to 
3179  * @param DecodeMe buffer with encoded string
3180  * @param DefaultCharset if we don't find one, which should we use?
3181  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3182  *        put it here for later use where no string might be known.
3183  */
3184 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3185 {
3186         StrBuf *DecodedInvalidBuf = NULL;
3187         StrBuf *ConvertBuf, *ConvertBuf2;
3188         const StrBuf *DecodeMee = DecodeMe;
3189         char *start, *end, *next, *nextend, *ptr = NULL;
3190 #ifdef HAVE_ICONV
3191         iconv_t ic = (iconv_t)(-1) ;
3192 #endif
3193         const char *eptr;
3194         int passes = 0;
3195         int i, len, delta;
3196         int illegal_non_rfc2047_encoding = 0;
3197
3198         /* Sometimes, badly formed messages contain strings which were simply
3199          *  written out directly in some foreign character set instead of
3200          *  using RFC2047 encoding.  This is illegal but we will attempt to
3201          *  handle it anyway by converting from a user-specified default
3202          *  charset to UTF-8 if we see any nonprintable characters.
3203          */
3204         
3205         len = StrLength(DecodeMe);
3206         for (i=0; i<DecodeMe->BufUsed; ++i) {
3207                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3208                         illegal_non_rfc2047_encoding = 1;
3209                         break;
3210                 }
3211         }
3212
3213         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3214         if ((illegal_non_rfc2047_encoding) &&
3215             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
3216             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3217         {
3218 #ifdef HAVE_ICONV
3219                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3220                 if (ic != (iconv_t)(-1) ) {
3221                         DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3222                         StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3223                         DecodeMee = DecodedInvalidBuf;
3224                         iconv_close(ic);
3225                 }
3226 #endif
3227         }
3228
3229         /* pre evaluate the first pair */
3230         nextend = end = NULL;
3231         len = StrLength(DecodeMee);
3232         start = strstr(DecodeMee->buf, "=?");
3233         eptr = DecodeMee->buf + DecodeMee->BufUsed;
3234         if (start != NULL) 
3235                 end = FindNextEnd (DecodeMee, start);
3236         else {
3237                 StrBufAppendBuf(Target, DecodeMee, 0);
3238                 FreeStrBuf(&ConvertBuf);
3239                 FreeStrBuf(&DecodedInvalidBuf);
3240                 return;
3241         }
3242
3243         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3244
3245         if (start != DecodeMee->buf) {
3246                 long nFront;
3247                 
3248                 nFront = start - DecodeMee->buf;
3249                 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3250                 len -= nFront;
3251         }
3252         /*
3253          * Since spammers will go to all sorts of absurd lengths to get their
3254          * messages through, there are LOTS of corrupt headers out there.
3255          * So, prevent a really badly formed RFC2047 header from throwing
3256          * this function into an infinite loop.
3257          */
3258         while ((start != NULL) && 
3259                (end != NULL) && 
3260                (start < eptr) && 
3261                (end < eptr) && 
3262                (passes < 20))
3263         {
3264                 passes++;
3265                 DecodeSegment(Target, 
3266                               DecodeMee, 
3267                               start, 
3268                               end, 
3269                               ConvertBuf,
3270                               ConvertBuf2,
3271                               FoundCharset);
3272                 
3273                 next = strstr(end, "=?");
3274                 nextend = NULL;
3275                 if ((next != NULL) && 
3276                     (next < eptr))
3277                         nextend = FindNextEnd(DecodeMee, next);
3278                 if (nextend == NULL)
3279                         next = NULL;
3280
3281                 /* did we find two partitions */
3282                 if ((next != NULL) && 
3283                     ((next - end) > 2))
3284                 {
3285                         ptr = end + 2;
3286                         while ((ptr < next) && 
3287                                (isspace(*ptr) ||
3288                                 (*ptr == '\r') ||
3289                                 (*ptr == '\n') || 
3290                                 (*ptr == '\t')))
3291                                 ptr ++;
3292                         /* did we find a gab just filled with blanks? */
3293                         if (ptr == next)
3294                         {
3295                                 long gap = next - start;
3296                                 memmove (end + 2,
3297                                          next,
3298                                          len - (gap));
3299                                 len -= gap;
3300                                 /* now terminate the gab at the end */
3301                                 delta = (next - end) - 2; ////TODO: const! 
3302                                 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3303                                 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3304
3305                                 /* move next to its new location. */
3306                                 next -= delta;
3307                                 nextend -= delta;
3308                         }
3309                 }
3310                 /* our next-pair is our new first pair now. */
3311                 ptr = end + 2;
3312                 start = next;
3313                 end = nextend;
3314         }
3315         end = ptr;
3316         nextend = DecodeMee->buf + DecodeMee->BufUsed;
3317         if ((end != NULL) && (end < nextend)) {
3318                 ptr = end;
3319                 while ( (ptr < nextend) &&
3320                         (isspace(*ptr) ||
3321                          (*ptr == '\r') ||
3322                          (*ptr == '\n') || 
3323                          (*ptr == '\t')))
3324                         ptr ++;
3325                 if (ptr < nextend)
3326                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
3327         }
3328         FreeStrBuf(&ConvertBuf);
3329         FreeStrBuf(&ConvertBuf2);
3330         FreeStrBuf(&DecodedInvalidBuf);
3331 }
3332
3333 /**
3334  * @ingroup StrBuf
3335  * @brief evaluate the length of an utf8 special character sequence
3336  * @param Char the character to examine
3337  * @returns width of utf8 chars in bytes
3338  */
3339 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3340 {
3341         int n = 1;
3342         char test = (1<<7);
3343         
3344         while ((n < 8) && ((test & *CharS) != 0)) {
3345                 test = test << 1;
3346                 n ++;
3347         }
3348         if ((n > 6) || ((CharE - CharS) > n))
3349                 n = 1;
3350         return n;
3351 }
3352
3353 /**
3354  * @ingroup StrBuf
3355  * @brief detect whether this char starts an utf-8 encoded char
3356  * @param Char character to inspect
3357  * @returns yes or no
3358  */
3359 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3360 {
3361 /** 11??.???? indicates an UTF8 Sequence. */
3362         return ((Char & 0xC0) != 0);
3363 }
3364
3365 /**
3366  * @ingroup StrBuf
3367  * @brief measure the number of glyphs in an UTF8 string...
3368  * @param Buf string to measure
3369  * @returns the number of glyphs in Buf
3370  */
3371 long StrBuf_Utf8StrLen(StrBuf *Buf)
3372 {
3373         int n = 0;
3374         int m = 0;
3375         char *aptr, *eptr;
3376
3377         if ((Buf == NULL) || (Buf->BufUsed == 0))
3378                 return 0;
3379         aptr = Buf->buf;
3380         eptr = Buf->buf + Buf->BufUsed;
3381         while ((aptr < eptr) && (*aptr != '\0')) {
3382                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3383                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3384                         while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3385                                 n ++;
3386                 }
3387                 else {
3388                         n++;
3389                         aptr++;
3390                 }
3391                         
3392         }
3393         return n;
3394 }
3395
3396 /**
3397  * @ingroup StrBuf
3398  * @brief cuts a string after maxlen glyphs
3399  * @param Buf string to cut to maxlen glyphs
3400  * @param maxlen how long may the string become?
3401  * @returns current length of the string
3402  */
3403 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3404 {
3405         char *aptr, *eptr;
3406         int n = 0, m = 0;
3407
3408         aptr = Buf->buf;
3409         eptr = Buf->buf + Buf->BufUsed;
3410         while ((aptr < eptr) && (*aptr != '\0')) {
3411                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3412                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3413                         while ((m-- > 0) && (*aptr++ != '\0'))
3414                                 n ++;
3415                 }
3416                 else {
3417                         n++;
3418                         aptr++;
3419                 }
3420                 if (n > maxlen) {
3421                         *aptr = '\0';
3422                         Buf->BufUsed = aptr - Buf->buf;
3423                         return Buf->BufUsed;
3424                 }                       
3425         }
3426         return Buf->BufUsed;
3427
3428 }
3429
3430
3431 /**
3432  * @ingroup StrBuf
3433  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3434  * @param LineBuf your line will be copied here.
3435  * @param Buf BLOB with lines of text...
3436  * @param Ptr moved arround to keep the next-line across several iterations
3437  *        has to be &NULL on start; will be &NotNULL on end of buffer
3438  * @returns size of copied buffer
3439  */
3440 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3441 {
3442         const char *aptr, *ptr, *eptr;
3443         char *optr, *xptr;
3444
3445         if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3446                 *Ptr = StrBufNOTNULL;
3447                 return 0;
3448         }
3449
3450         FlushStrBuf(LineBuf);
3451         if (*Ptr==NULL)
3452                 ptr = aptr = Buf->buf;
3453         else
3454                 ptr = aptr = *Ptr;
3455
3456         optr = LineBuf->buf;
3457         eptr = Buf->buf + Buf->BufUsed;
3458         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3459
3460         while ((ptr <= eptr) && 
3461                (*ptr != '\n') &&
3462                (*ptr != '\r') )
3463         {
3464                 *optr = *ptr;
3465                 optr++; ptr++;
3466                 if (optr == xptr) {
3467                         LineBuf->BufUsed = optr - LineBuf->buf;
3468                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
3469                         optr = LineBuf->buf + LineBuf->BufUsed;
3470                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3471                 }
3472         }
3473
3474         if ((ptr >= eptr) && (optr > LineBuf->buf))
3475                 optr --;
3476         LineBuf->BufUsed = optr - LineBuf->buf;
3477         *optr = '\0';       
3478         if ((ptr <= eptr) && (*ptr == '\r'))
3479                 ptr ++;
3480         if ((ptr <= eptr) && (*ptr == '\n'))
3481                 ptr ++;
3482         
3483         if (ptr < eptr) {
3484                 *Ptr = ptr;
3485         }
3486         else {
3487                 *Ptr = StrBufNOTNULL;
3488         }
3489
3490         return Buf->BufUsed - (ptr - Buf->buf);
3491 }
3492