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