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