cfe42730c4c79ff0c257d63e5288b7922ace6d5f
[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
220  * @brief swaps the contents of two StrBufs
221  * this is to be used to have cheap switched between a work-buffer and a target buffer 
222  * @param A First one
223  * @param B second one
224  */
225 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
226 {
227         StrBuf C;
228
229         memcpy(&C, A, sizeof(*A));
230         memcpy(A, B, sizeof(*B));
231         memcpy(B, &C, sizeof(C));
232
233 }
234
235 /** 
236  * @ingroup StrBuf_Cast
237  * @brief Cast operator to Plain String 
238  * @note if the buffer is altered by StrBuf operations, this pointer may become 
239  *  invalid. So don't lean on it after altering the buffer!
240  *  Since this operation is considered cheap, rather call it often than risking
241  *  your pointer to become invalid!
242  * @param Str the string we want to get the c-string representation for
243  * @returns the Pointer to the Content. Don't mess with it!
244  */
245 inline const char *ChrPtr(const StrBuf *Str)
246 {
247         if (Str == NULL)
248                 return "";
249         return Str->buf;
250 }
251
252 /**
253  * @ingroup StrBuf_Cast
254  * @brief since we know strlen()'s result, provide it here.
255  * @param Str the string to return the length to
256  * @returns contentlength of the buffer
257  */
258 inline int StrLength(const StrBuf *Str)
259 {
260         return (Str != NULL) ? Str->BufUsed : 0;
261 }
262
263 /**
264  * @ingroup StrBuf_DeConstructors
265  * @brief local utility function to resize the buffer
266  * @param Buf the buffer whichs storage we should increase
267  * @param KeepOriginal should we copy the original buffer or just start over with a new one
268  * @param DestSize what should fit in after?
269  */
270 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
271 {
272         char *NewBuf;
273         size_t NewSize = Buf->BufSize * 2;
274
275         if (Buf->ConstBuf)
276                 return -1;
277                 
278         if (DestSize > 0)
279                 while ((NewSize <= DestSize) && (NewSize != 0))
280                         NewSize *= 2;
281
282         if (NewSize == 0)
283                 return -1;
284
285         NewBuf= (char*) malloc(NewSize);
286         if (NewBuf == NULL)
287                 return -1;
288
289         if (KeepOriginal && (Buf->BufUsed > 0))
290         {
291                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
292         }
293         else
294         {
295                 NewBuf[0] = '\0';
296                 Buf->BufUsed = 0;
297         }
298         free (Buf->buf);
299         Buf->buf = NewBuf;
300         Buf->BufSize = NewSize;
301
302         dbg_IncreaseBuf(Buf);
303
304         return Buf->BufSize;
305 }
306
307 /**
308  * @ingroup StrBuf_DeConstructors
309  * @brief shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
310  * @param Buf Buffer to shrink (has to be empty)
311  * @param ThreshHold if the buffer is bigger then this, its readjusted
312  * @param NewSize if we Shrink it, how big are we going to be afterwards?
313  */
314 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
315 {
316         if ((Buf != NULL) && 
317             (Buf->BufUsed == 0) &&
318             (Buf->BufSize < ThreshHold)) {
319                 free(Buf->buf);
320                 Buf->buf = (char*) malloc(NewSize);
321                 Buf->BufUsed = 0;
322                 Buf->BufSize = NewSize;
323         }
324 }
325
326 /**
327  * @ingroup StrBuf_DeConstructors
328  * @brief shrink long term buffers to their real size so they don't waste memory
329  * @param Buf buffer to shrink
330  * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
331  * @returns physical size of the buffer
332  */
333 long StrBufShrinkToFit(StrBuf *Buf, int Force)
334 {
335         if (Buf == NULL)
336                 return -1;
337         if (Force || 
338             (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
339         {
340                 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
341                 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
342                 Buf->BufSize = Buf->BufUsed + 1;
343                 free(Buf->buf);
344                 Buf->buf = TmpBuf;
345         }
346         return Buf->BufUsed;
347 }
348
349 /**
350  * @ingroup StrBuf_DeConstructors
351  * @brief Allocate a new buffer with default buffer size
352  * @returns the new stringbuffer
353  */
354 StrBuf* NewStrBuf(void)
355 {
356         StrBuf *NewBuf;
357
358         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
359         NewBuf->buf = (char*) malloc(BaseStrBufSize);
360         NewBuf->buf[0] = '\0';
361         NewBuf->BufSize = BaseStrBufSize;
362         NewBuf->BufUsed = 0;
363         NewBuf->ConstBuf = 0;
364
365         dbg_Init (NewBuf);
366
367         return NewBuf;
368 }
369
370 /** 
371  * @ingroup StrBuf_DeConstructors
372  * @brief Copy Constructor; returns a duplicate of CopyMe
373  * @param CopyMe Buffer to faxmilate
374  * @returns the new stringbuffer
375  */
376 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
377 {
378         StrBuf *NewBuf;
379         
380         if (CopyMe == NULL)
381                 return NewStrBuf();
382
383         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
384         NewBuf->buf = (char*) malloc(CopyMe->BufSize);
385         memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
386         NewBuf->BufUsed = CopyMe->BufUsed;
387         NewBuf->BufSize = CopyMe->BufSize;
388         NewBuf->ConstBuf = 0;
389
390         dbg_Init(NewBuf);
391
392         return NewBuf;
393 }
394
395 /** 
396  * @ingroup StrBuf_DeConstructors
397  * @brief Copy Constructor; CreateRelpaceMe will contain CopyFlushMe afterwards.
398  * @param NoMe if non-NULL, we will use that buffer as value; KeepOriginal will abused as len.
399  * @param CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
400  * @param CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe 
401  * @param KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
402  * @returns the new stringbuffer
403  */
404 void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, const char *NoMe, int KeepOriginal)
405 {
406         StrBuf *NewBuf;
407         
408         if (CreateRelpaceMe == NULL)
409                 return;
410
411         if (NoMe != NULL)
412         {
413                 if (*CreateRelpaceMe != NULL)
414                         StrBufPlain(*CreateRelpaceMe, NoMe, KeepOriginal);
415                 else 
416                         *CreateRelpaceMe = NewStrBufPlain(NoMe, KeepOriginal);
417                 return;
418         }
419
420         if (CopyFlushMe == NULL)
421         {
422                 if (*CreateRelpaceMe != NULL)
423                         FlushStrBuf(*CreateRelpaceMe);
424                 else 
425                         *CreateRelpaceMe = NewStrBuf();
426                 return;
427         }
428
429         /* 
430          * Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
431          * else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
432          * be a big IO-Buffer...
433          */
434         if (KeepOriginal || (StrLength(CopyFlushMe) < 256))
435         {
436                 if (*CreateRelpaceMe == NULL)
437                 {
438                         *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
439                         dbg_Init(NewBuf);
440                 }
441                 else 
442                 {
443                         NewBuf = *CreateRelpaceMe;
444                         FlushStrBuf(NewBuf);
445                 }
446                 StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
447         }
448         else
449         {
450                 if (*CreateRelpaceMe == NULL)
451                 {
452                         *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
453                         dbg_Init(NewBuf);
454                 }
455                 else 
456                         NewBuf = *CreateRelpaceMe;
457                 SwapBuffers (NewBuf, CopyFlushMe);
458         }
459         if (!KeepOriginal)
460                 FlushStrBuf(CopyFlushMe);
461         return;
462 }
463
464 /**
465  * @ingroup StrBuf_DeConstructors
466  * @brief create a new Buffer using an existing c-string
467  * this function should also be used if you want to pre-suggest
468  * the buffer size to allocate in conjunction with ptr == NULL
469  * @param ptr the c-string to copy; may be NULL to create a blank instance
470  * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
471  * @returns the new stringbuffer
472  */
473 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
474 {
475         StrBuf *NewBuf;
476         size_t Siz = BaseStrBufSize;
477         size_t CopySize;
478
479         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
480         if (nChars < 0)
481                 CopySize = strlen((ptr != NULL)?ptr:"");
482         else
483                 CopySize = nChars;
484
485         while ((Siz <= CopySize) && (Siz != 0))
486                 Siz *= 2;
487
488         if (Siz == 0)
489         {
490                 return NULL;
491         }
492
493         NewBuf->buf = (char*) malloc(Siz);
494         if (NewBuf->buf == NULL)
495         {
496                 free(NewBuf);
497                 return NULL;
498         }
499         NewBuf->BufSize = Siz;
500         if (ptr != NULL) {
501                 memcpy(NewBuf->buf, ptr, CopySize);
502                 NewBuf->buf[CopySize] = '\0';
503                 NewBuf->BufUsed = CopySize;
504         }
505         else {
506                 NewBuf->buf[0] = '\0';
507                 NewBuf->BufUsed = 0;
508         }
509         NewBuf->ConstBuf = 0;
510
511         dbg_Init(NewBuf);
512
513         return NewBuf;
514 }
515
516 /**
517  * @ingroup StrBuf_DeConstructors
518  * @brief Set an existing buffer from a c-string
519  * @param Buf buffer to load
520  * @param ptr c-string to put into 
521  * @param nChars set to -1 if we should work 0-terminated
522  * @returns the new length of the string
523  */
524 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
525 {
526         size_t Siz;
527         size_t CopySize;
528
529         if (Buf == NULL)
530                 return -1;
531         if (ptr == NULL) {
532                 FlushStrBuf(Buf);
533                 return -1;
534         }
535
536         Siz = Buf->BufSize;
537
538         if (nChars < 0)
539                 CopySize = strlen(ptr);
540         else
541                 CopySize = nChars;
542
543         while ((Siz <= CopySize) && (Siz != 0))
544                 Siz *= 2;
545
546         if (Siz == 0) {
547                 FlushStrBuf(Buf);
548                 return -1;
549         }
550
551         if (Siz != Buf->BufSize)
552                 IncreaseBuf(Buf, 0, Siz);
553         memcpy(Buf->buf, ptr, CopySize);
554         Buf->buf[CopySize] = '\0';
555         Buf->BufUsed = CopySize;
556         Buf->ConstBuf = 0;
557         return CopySize;
558 }
559
560
561 /**
562  * @ingroup StrBuf_DeConstructors
563  * @brief use strbuf as wrapper for a string constant for easy handling
564  * @param StringConstant a string to wrap
565  * @param SizeOfStrConstant should be sizeof(StringConstant)-1
566  */
567 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
568 {
569         StrBuf *NewBuf;
570
571         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
572         NewBuf->buf = (char*) StringConstant;
573         NewBuf->BufSize = SizeOfStrConstant;
574         NewBuf->BufUsed = SizeOfStrConstant;
575         NewBuf->ConstBuf = 1;
576
577         dbg_Init(NewBuf);
578
579         return NewBuf;
580 }
581
582
583 /**
584  * @ingroup StrBuf_DeConstructors
585  * @brief flush the content of a Buf; keep its struct
586  * @param buf Buffer to flush
587  */
588 int FlushStrBuf(StrBuf *buf)
589 {
590         if (buf == NULL)
591                 return -1;
592         if (buf->ConstBuf)
593                 return -1;       
594         buf->buf[0] ='\0';
595         buf->BufUsed = 0;
596         return 0;
597 }
598
599 /**
600  * @ingroup StrBuf_DeConstructors
601  * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
602  * @param buf Buffer to wipe
603  */
604 int FLUSHStrBuf(StrBuf *buf)
605 {
606         if (buf == NULL)
607                 return -1;
608         if (buf->ConstBuf)
609                 return -1;
610         if (buf->BufUsed > 0) {
611                 memset(buf->buf, 0, buf->BufUsed);
612                 buf->BufUsed = 0;
613         }
614         return 0;
615 }
616
617 #ifdef SIZE_DEBUG
618 int hFreeDbglog = -1;
619 #endif
620 /**
621  * @ingroup StrBuf_DeConstructors
622  * @brief Release a Buffer
623  * Its a double pointer, so it can NULL your pointer
624  * so fancy SIG11 appear instead of random results
625  * @param FreeMe Pointer Pointer to the buffer to free
626  */
627 void FreeStrBuf (StrBuf **FreeMe)
628 {
629         if (*FreeMe == NULL)
630                 return;
631
632         dbg_FreeStrBuf(FreeMe, 'F');
633
634         if (!(*FreeMe)->ConstBuf) 
635                 free((*FreeMe)->buf);
636         free(*FreeMe);
637         *FreeMe = NULL;
638 }
639
640 /**
641  * @ingroup StrBuf_DeConstructors
642  * @brief flatten a Buffer to the Char * we return 
643  * Its a double pointer, so it can NULL your pointer
644  * so fancy SIG11 appear instead of random results
645  * The Callee then owns the buffer and is responsible for freeing it.
646  * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
647  * @returns the pointer of the buffer; Callee owns the memory thereafter.
648  */
649 char *SmashStrBuf (StrBuf **SmashMe)
650 {
651         char *Ret;
652
653         if ((SmashMe == NULL) || (*SmashMe == NULL))
654                 return NULL;
655         
656         dbg_FreeStrBuf(SmashMe, 'S');
657
658         Ret = (*SmashMe)->buf;
659         free(*SmashMe);
660         *SmashMe = NULL;
661         return Ret;
662 }
663
664 /**
665  * @ingroup StrBuf_DeConstructors
666  * @brief Release the buffer
667  * If you want put your StrBuf into a Hash, use this as Destructor.
668  * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
669  */
670 void HFreeStrBuf (void *VFreeMe)
671 {
672         StrBuf *FreeMe = (StrBuf*)VFreeMe;
673         if (FreeMe == NULL)
674                 return;
675
676         dbg_FreeStrBuf(SmashMe, 'H');
677
678         if (!FreeMe->ConstBuf) 
679                 free(FreeMe->buf);
680         free(FreeMe);
681 }
682
683
684 /*******************************************************************************
685  *                      Simple string transformations                          *
686  *******************************************************************************/
687
688 /**
689  * @ingroup StrBuf
690  * @brief Wrapper around atol
691  */
692 long StrTol(const StrBuf *Buf)
693 {
694         if (Buf == NULL)
695                 return 0;
696         if(Buf->BufUsed > 0)
697                 return atol(Buf->buf);
698         else
699                 return 0;
700 }
701
702 /**
703  * @ingroup StrBuf
704  * @brief Wrapper around atoi
705  */
706 int StrToi(const StrBuf *Buf)
707 {
708         if (Buf == NULL)
709                 return 0;
710         if (Buf->BufUsed > 0)
711                 return atoi(Buf->buf);
712         else
713                 return 0;
714 }
715
716 /**
717  * @ingroup StrBuf
718  * @brief Checks to see if the string is a pure number 
719  * @param Buf The buffer to inspect
720  * @returns 1 if its a pure number, 0, if not.
721  */
722 int StrBufIsNumber(const StrBuf *Buf) {
723         char * pEnd;
724         if ((Buf == NULL) || (Buf->BufUsed == 0)) {
725                 return 0;
726         }
727         strtoll(Buf->buf, &pEnd, 10);
728         if (pEnd == Buf->buf)
729                 return 0;
730         if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
731                 return 1;
732         if (Buf->buf == pEnd)
733                 return 0;
734         return 0;
735
736
737 /**
738  * @ingroup StrBuf_Filler
739  * @brief modifies a Single char of the Buf
740  * You can point to it via char* or a zero-based integer
741  * @param Buf The buffer to manipulate
742  * @param ptr char* to zero; use NULL if unused
743  * @param nThChar zero based pointer into the string; use -1 if unused
744  * @param PeekValue The Character to place into the position
745  */
746 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
747 {
748         if (Buf == NULL)
749                 return -1;
750         if (ptr != NULL)
751                 nThChar = ptr - Buf->buf;
752         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
753                 return -1;
754         Buf->buf[nThChar] = PeekValue;
755         return nThChar;
756 }
757
758 /**
759  * @ingroup StrBuf_Filler
760  * @brief modifies a range of chars of the Buf
761  * You can point to it via char* or a zero-based integer
762  * @param Buf The buffer to manipulate
763  * @param ptr char* to zero; use NULL if unused
764  * @param nThChar zero based pointer into the string; use -1 if unused
765  * @param nChars how many chars are to be flushed?
766  * @param PookValue The Character to place into that area
767  */
768 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
769 {
770         if (Buf == NULL)
771                 return -1;
772         if (ptr != NULL)
773                 nThChar = ptr - Buf->buf;
774         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
775                 return -1;
776         if (nThChar + nChars > Buf->BufUsed)
777                 nChars =  Buf->BufUsed - nThChar;
778
779         memset(Buf->buf + nThChar, PookValue, nChars);
780         /* just to be shure... */
781         Buf->buf[Buf->BufUsed] = 0;
782         return nChars;
783 }
784
785 /**
786  * @ingroup StrBuf_Filler
787  * @brief Append a StringBuffer to the buffer
788  * @param Buf Buffer to modify
789  * @param AppendBuf Buffer to copy at the end of our buffer
790  * @param Offset Should we start copying from an offset?
791  */
792 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
793 {
794         if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
795                 return;
796
797         if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
798                 IncreaseBuf(Buf, 
799                             (Buf->BufUsed > 0), 
800                             AppendBuf->BufUsed + Buf->BufUsed);
801
802         memcpy(Buf->buf + Buf->BufUsed, 
803                AppendBuf->buf + Offset, 
804                AppendBuf->BufUsed - Offset);
805         Buf->BufUsed += AppendBuf->BufUsed - Offset;
806         Buf->buf[Buf->BufUsed] = '\0';
807 }
808
809
810 /**
811  * @ingroup StrBuf_Filler
812  * @brief Append a C-String to the buffer
813  * @param Buf Buffer to modify
814  * @param AppendBuf Buffer to copy at the end of our buffer
815  * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
816  * @param Offset Should we start copying from an offset?
817  */
818 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
819 {
820         long aps;
821         long BufSizeRequired;
822
823         if ((AppendBuf == NULL) || (Buf == NULL))
824                 return;
825
826         if (AppendSize < 0 )
827                 aps = strlen(AppendBuf + Offset);
828         else
829                 aps = AppendSize - Offset;
830
831         BufSizeRequired = Buf->BufUsed + aps + 1;
832         if (Buf->BufSize <= BufSizeRequired)
833                 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
834
835         memcpy(Buf->buf + Buf->BufUsed, 
836                AppendBuf + Offset, 
837                aps);
838         Buf->BufUsed += aps;
839         Buf->buf[Buf->BufUsed] = '\0';
840 }
841
842 /**
843  * @ingroup StrBuf_Filler
844  * @brief sprintf like function appending the formated string to the buffer
845  * vsnprintf version to wrap into own calls
846  * @param Buf Buffer to extend by format and Params
847  * @param format printf alike format to add
848  * @param ap va_list containing the items for format
849  */
850 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
851 {
852         va_list apl;
853         size_t BufSize;
854         size_t nWritten;
855         size_t Offset;
856         size_t newused;
857
858         if ((Buf == NULL)  || (format == NULL))
859                 return;
860
861         BufSize = Buf->BufSize;
862         nWritten = Buf->BufSize + 1;
863         Offset = Buf->BufUsed;
864         newused = Offset + nWritten;
865         
866         while (newused >= BufSize) {
867                 va_copy(apl, ap);
868                 nWritten = vsnprintf(Buf->buf + Offset, 
869                                      Buf->BufSize - Offset, 
870                                      format, apl);
871                 va_end(apl);
872                 newused = Offset + nWritten;
873                 if (newused >= Buf->BufSize) {
874                         if (IncreaseBuf(Buf, 1, newused) == -1)
875                                 return; /* TODO: error handling? */
876                         newused = Buf->BufSize + 1;
877                 }
878                 else {
879                         Buf->BufUsed = Offset + nWritten;
880                         BufSize = Buf->BufSize;
881                 }
882
883         }
884 }
885
886 /**
887  * @ingroup StrBuf_Filler
888  * @brief sprintf like function appending the formated string to the buffer
889  * @param Buf Buffer to extend by format and Params
890  * @param format printf alike format to add
891  */
892 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
893 {
894         size_t BufSize;
895         size_t nWritten;
896         size_t Offset;
897         size_t newused;
898         va_list arg_ptr;
899         
900         if ((Buf == NULL)  || (format == NULL))
901                 return;
902
903         BufSize = Buf->BufSize;
904         nWritten = Buf->BufSize + 1;
905         Offset = Buf->BufUsed;
906         newused = Offset + nWritten;
907
908         while (newused >= BufSize) {
909                 va_start(arg_ptr, format);
910                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
911                                      Buf->BufSize - Buf->BufUsed, 
912                                      format, arg_ptr);
913                 va_end(arg_ptr);
914                 newused = Buf->BufUsed + nWritten;
915                 if (newused >= Buf->BufSize) {
916                         if (IncreaseBuf(Buf, 1, newused) == -1)
917                                 return; /* TODO: error handling? */
918                         newused = Buf->BufSize + 1;
919                 }
920                 else {
921                         Buf->BufUsed += nWritten;
922                         BufSize = Buf->BufSize;
923                 }
924
925         }
926 }
927
928 /**
929  * @ingroup StrBuf_Filler
930  * @brief sprintf like function putting the formated string into the buffer
931  * @param Buf Buffer to extend by format and Parameters
932  * @param format printf alike format to add
933  */
934 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
935 {
936         size_t nWritten;
937         va_list arg_ptr;
938         
939         if ((Buf == NULL)  || (format == NULL))
940                 return;
941
942         nWritten = Buf->BufSize + 1;
943         while (nWritten >= Buf->BufSize) {
944                 va_start(arg_ptr, format);
945                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
946                 va_end(arg_ptr);
947                 if (nWritten >= Buf->BufSize) {
948                         if (IncreaseBuf(Buf, 0, 0) == -1)
949                                 return; /* TODO: error handling? */
950                         nWritten = Buf->BufSize + 1;
951                         continue;
952                 }
953                 Buf->BufUsed = nWritten ;
954         }
955 }
956
957 /**
958  * @ingroup StrBuf_Filler
959  * @brief Callback for cURL to append the webserver reply to a buffer
960  * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
961  * @param size pre-defined by the cURL API; see man 3 curl for mre info
962  * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
963  * @param stream pre-defined by the cURL API; see man 3 curl for mre info
964  */
965 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
966 {
967
968         StrBuf *Target;
969
970         Target = stream;
971         if (ptr == NULL)
972                 return 0;
973
974         StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
975         return size * nmemb;
976 }
977
978
979 /**
980  * @ingroup StrBuf
981  * @brief extracts a substring from Source into dest
982  * @param dest buffer to place substring into
983  * @param Source string to copy substring from
984  * @param Offset chars to skip from start
985  * @param nChars number of chars to copy
986  * @returns the number of chars copied; may be different from nChars due to the size of Source
987  */
988 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
989 {
990         size_t NCharsRemain;
991         if (Offset > Source->BufUsed)
992         {
993                 if (dest != NULL)
994                         FlushStrBuf(dest);
995                 return 0;
996         }
997         if (Offset + nChars < Source->BufUsed)
998         {
999                 if (nChars >= dest->BufSize)
1000                         IncreaseBuf(dest, 0, nChars + 1);
1001                 memcpy(dest->buf, Source->buf + Offset, nChars);
1002                 dest->BufUsed = nChars;
1003                 dest->buf[dest->BufUsed] = '\0';
1004                 return nChars;
1005         }
1006         NCharsRemain = Source->BufUsed - Offset;
1007         if (NCharsRemain  >= dest->BufSize)
1008                 IncreaseBuf(dest, 0, NCharsRemain + 1);
1009         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1010         dest->BufUsed = NCharsRemain;
1011         dest->buf[dest->BufUsed] = '\0';
1012         return NCharsRemain;
1013 }
1014
1015 /**
1016  * @ingroup StrBuf
1017  * @brief Cut nChars from the start of the string
1018  * @param Buf Buffer to modify
1019  * @param nChars how many chars should be skipped?
1020  */
1021 void StrBufCutLeft(StrBuf *Buf, int nChars)
1022 {
1023         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1024         if (nChars >= Buf->BufUsed) {
1025                 FlushStrBuf(Buf);
1026                 return;
1027         }
1028         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1029         Buf->BufUsed -= nChars;
1030         Buf->buf[Buf->BufUsed] = '\0';
1031 }
1032
1033 /**
1034  * @ingroup StrBuf
1035  * @brief Cut the trailing n Chars from the string
1036  * @param Buf Buffer to modify
1037  * @param nChars how many chars should be trunkated?
1038  */
1039 void StrBufCutRight(StrBuf *Buf, int nChars)
1040 {
1041         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1042         if (nChars >= Buf->BufUsed) {
1043                 FlushStrBuf(Buf);
1044                 return;
1045         }
1046         Buf->BufUsed -= nChars;
1047         Buf->buf[Buf->BufUsed] = '\0';
1048 }
1049
1050 /**
1051  * @ingroup StrBuf
1052  * @brief Cut the string after n Chars
1053  * @param Buf Buffer to modify
1054  * @param AfternChars after how many chars should we trunkate the string?
1055  * @param At if non-null and points inside of our string, cut it there.
1056  */
1057 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1058 {
1059         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1060         if (At != NULL){
1061                 AfternChars = At - Buf->buf;
1062         }
1063
1064         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1065                 return;
1066         Buf->BufUsed = AfternChars;
1067         Buf->buf[Buf->BufUsed] = '\0';
1068 }
1069
1070
1071 /**
1072  * @ingroup StrBuf
1073  * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1074  * @param Buf the string to modify
1075  */
1076 void StrBufTrim(StrBuf *Buf)
1077 {
1078         int delta = 0;
1079         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1080
1081         while ((Buf->BufUsed > 0) &&
1082                isspace(Buf->buf[Buf->BufUsed - 1]))
1083         {
1084                 Buf->BufUsed --;
1085         }
1086         Buf->buf[Buf->BufUsed] = '\0';
1087
1088         if (Buf->BufUsed == 0) return;
1089
1090         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1091                 delta ++;
1092         }
1093         if (delta > 0) StrBufCutLeft(Buf, delta);
1094 }
1095 /**
1096  * @ingroup StrBuf
1097  * @brief changes all spaces in the string  (tab, linefeed...) to Blank (0x20)
1098  * @param Buf the string to modify
1099  */
1100 void StrBufSpaceToBlank(StrBuf *Buf)
1101 {
1102         char *pche, *pch;
1103
1104         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1105
1106         pch = Buf->buf;
1107         pche = pch + Buf->BufUsed;
1108         while (pch < pche) 
1109         {
1110                 if (isspace(*pch))
1111                         *pch = ' ';
1112                 pch ++;
1113         }
1114 }
1115
1116 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
1117 {
1118         const char *pBuff;
1119         const char *pLeft;
1120         const char *pRight;
1121
1122         if (Buf == NULL)
1123                 return;
1124         pLeft = pBuff = Buf->buf;
1125         while (pBuff != NULL) {
1126                 pLeft = pBuff;
1127                 pBuff = strchr(pBuff, leftboundary);
1128                 if (pBuff != NULL)
1129                         pBuff++;
1130         }
1131                 
1132         if (pLeft != NULL)
1133                 pBuff = pLeft;
1134         else
1135                 pBuff = Buf->buf;
1136         pRight = strchr(pBuff, rightboundary);
1137         if (pRight != NULL)
1138                 StrBufCutAt(Buf, 0, pRight);
1139         if (pLeft != NULL)
1140                 StrBufCutLeft(Buf, pLeft - Buf->buf);
1141 }
1142
1143
1144 /**
1145  * @ingroup StrBuf_Filler
1146  * @brief uppercase the contents of a buffer
1147  * @param Buf the buffer to translate
1148  */
1149 void StrBufUpCase(StrBuf *Buf) 
1150 {
1151         char *pch, *pche;
1152
1153         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1154
1155         pch = Buf->buf;
1156         pche = pch + Buf->BufUsed;
1157         while (pch < pche) {
1158                 *pch = toupper(*pch);
1159                 pch ++;
1160         }
1161 }
1162
1163
1164 /**
1165  * @ingroup StrBuf_Filler
1166  * @brief lowercase the contents of a buffer
1167  * @param Buf the buffer to translate
1168  */
1169 void StrBufLowerCase(StrBuf *Buf) 
1170 {
1171         char *pch, *pche;
1172
1173         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1174
1175         pch = Buf->buf;
1176         pche = pch + Buf->BufUsed;
1177         while (pch < pche) {
1178                 *pch = tolower(*pch);
1179                 pch ++;
1180         }
1181 }
1182
1183
1184 /*******************************************************************************
1185  *           a tokenizer that kills, maims, and destroys                       *
1186  *******************************************************************************/
1187
1188 /**
1189  * @ingroup StrBuf_Tokenizer
1190  * @brief Replace a token at a given place with a given length by another token with given length
1191  * @param Buf String where to work on
1192  * @param where where inside of the Buf is the search-token
1193  * @param HowLong How long is the token to be replaced
1194  * @param Repl Token to insert at 'where'
1195  * @param ReplLen Length of repl
1196  * @returns -1 if fail else length of resulting Buf
1197  */
1198 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong, 
1199                        const char *Repl, long ReplLen)
1200 {
1201
1202         if ((Buf == NULL) || 
1203             (where > Buf->BufUsed) ||
1204             (where + HowLong > Buf->BufUsed))
1205                 return -1;
1206
1207         if (where + ReplLen - HowLong > Buf->BufSize)
1208                 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1209                         return -1;
1210
1211         memmove(Buf->buf + where + ReplLen, 
1212                 Buf->buf + where + HowLong,
1213                 Buf->BufUsed - where - HowLong);
1214                                                 
1215         memcpy(Buf->buf + where, 
1216                Repl, ReplLen);
1217
1218         Buf->BufUsed += ReplLen - HowLong;
1219
1220         return Buf->BufUsed;
1221 }
1222
1223 /**
1224  * @ingroup StrBuf_Tokenizer
1225  * @brief Counts the numbmer of tokens in a buffer
1226  * @param source String to count tokens in
1227  * @param tok    Tokenizer char to count
1228  * @returns numbers of tokenizer chars found
1229  */
1230 int StrBufNum_tokens(const StrBuf *source, char tok)
1231 {
1232         char *pch, *pche;
1233         long NTokens;
1234         if ((source == NULL) || (source->BufUsed == 0))
1235                 return 0;
1236         if ((source->BufUsed == 1) && (*source->buf == tok))
1237                 return 2;
1238         NTokens = 1;
1239         pch = source->buf;
1240         pche = pch + source->BufUsed;
1241         while (pch < pche)
1242         {
1243                 if (*pch == tok)
1244                         NTokens ++;
1245                 pch ++;
1246         }
1247         return NTokens;
1248 }
1249
1250 /**
1251  * @ingroup StrBuf_Tokenizer
1252  * @brief a string tokenizer
1253  * @param Source StringBuffer to read into
1254  * @param parmnum n'th Parameter to remove
1255  * @param separator tokenizer character
1256  * @returns -1 if not found, else length of token.
1257  */
1258 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1259 {
1260         int ReducedBy;
1261         char *d, *s, *end;              /* dest, source */
1262         int count = 0;
1263
1264         /* Find desired @parameter */
1265         end = Source->buf + Source->BufUsed;
1266         d = Source->buf;
1267         while ((d <= end) && 
1268                (count < parmnum))
1269         {
1270                 /* End of string, bail! */
1271                 if (!*d) {
1272                         d = NULL;
1273                         break;
1274                 }
1275                 if (*d == separator) {
1276                         count++;
1277                 }
1278                 d++;
1279         }
1280         if ((d == NULL) || (d >= end))
1281                 return 0;               /* @Parameter not found */
1282
1283         /* Find next @parameter */
1284         s = d;
1285         while ((s <= end) && 
1286                (*s && *s != separator))
1287         {
1288                 s++;
1289         }
1290         if (*s == separator)
1291                 s++;
1292         ReducedBy = d - s;
1293
1294         /* Hack and slash */
1295         if (s >= end) {
1296                 return 0;
1297         }
1298         else if (*s) {
1299                 memmove(d, s, Source->BufUsed - (s - Source->buf));
1300                 Source->BufUsed += ReducedBy;
1301                 Source->buf[Source->BufUsed] = '\0';
1302         }
1303         else if (d == Source->buf) {
1304                 *d = 0;
1305                 Source->BufUsed = 0;
1306         }
1307         else {
1308                 *--d = '\0';
1309                 Source->BufUsed += ReducedBy;
1310         }
1311         /*
1312         while (*s) {
1313                 *d++ = *s++;
1314         }
1315         *d = 0;
1316         */
1317         return ReducedBy;
1318 }
1319
1320
1321 /**
1322  * @ingroup StrBuf_Tokenizer
1323  * @brief a string tokenizer
1324  * @param dest Destination StringBuffer
1325  * @param Source StringBuffer to read into
1326  * @param parmnum n'th Parameter to extract
1327  * @param separator tokenizer character
1328  * @returns -1 if not found, else length of token.
1329  */
1330 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1331 {
1332         const char *s, *e;              //* source * /
1333         int len = 0;                    //* running total length of extracted string * /
1334         int current_token = 0;          //* token currently being processed * /
1335          
1336         if (dest != NULL) {
1337                 dest->buf[0] = '\0';
1338                 dest->BufUsed = 0;
1339         }
1340         else
1341                 return(-1);
1342
1343         if ((Source == NULL) || (Source->BufUsed ==0)) {
1344                 return(-1);
1345         }
1346         s = Source->buf;
1347         e = s + Source->BufUsed;
1348
1349         //cit_backtrace();
1350         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1351
1352         while ((s < e) && !IsEmptyStr(s)) {
1353                 if (*s == separator) {
1354                         ++current_token;
1355                 }
1356                 if (len >= dest->BufSize) {
1357                         dest->BufUsed = len;
1358                         if (IncreaseBuf(dest, 1, -1) < 0) {
1359                                 dest->BufUsed --;
1360                                 break;
1361                         }
1362                 }
1363                 if ( (current_token == parmnum) && 
1364                      (*s != separator)) {
1365                         dest->buf[len] = *s;
1366                         ++len;
1367                 }
1368                 else if (current_token > parmnum) {
1369                         break;
1370                 }
1371                 ++s;
1372         }
1373         
1374         dest->buf[len] = '\0';
1375         dest->BufUsed = len;
1376                 
1377         if (current_token < parmnum) {
1378                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1379                 return(-1);
1380         }
1381         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1382         return(len);
1383 }
1384
1385
1386
1387
1388
1389 /**
1390  * @ingroup StrBuf_Tokenizer
1391  * @brief a string tokenizer to fetch an integer
1392  * @param Source String containing tokens
1393  * @param parmnum n'th Parameter to extract
1394  * @param separator tokenizer character
1395  * @returns 0 if not found, else integer representation of the token
1396  */
1397 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1398 {
1399         StrBuf tmp;
1400         char buf[64];
1401         
1402         tmp.buf = buf;
1403         buf[0] = '\0';
1404         tmp.BufSize = 64;
1405         tmp.BufUsed = 0;
1406         tmp.ConstBuf = 1;
1407         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1408                 return(atoi(buf));
1409         else
1410                 return 0;
1411 }
1412
1413 /**
1414  * @ingroup StrBuf_Tokenizer
1415  * @brief a string tokenizer to fetch a long integer
1416  * @param Source String containing tokens
1417  * @param parmnum n'th Parameter to extract
1418  * @param separator tokenizer character
1419  * @returns 0 if not found, else long integer representation of the token
1420  */
1421 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1422 {
1423         StrBuf tmp;
1424         char buf[64];
1425         
1426         tmp.buf = buf;
1427         buf[0] = '\0';
1428         tmp.BufSize = 64;
1429         tmp.BufUsed = 0;
1430         tmp.ConstBuf = 1;
1431         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1432                 return(atoi(buf));
1433         else
1434                 return 0;
1435 }
1436
1437
1438 /**
1439  * @ingroup StrBuf_Tokenizer
1440  * @brief a string tokenizer to fetch an unsigned long
1441  * @param Source String containing tokens
1442  * @param parmnum n'th Parameter to extract
1443  * @param separator tokenizer character
1444  * @returns 0 if not found, else unsigned long representation of the token
1445  */
1446 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1447 {
1448         StrBuf tmp;
1449         char buf[64];
1450         char *pnum;
1451         
1452         tmp.buf = buf;
1453         buf[0] = '\0';
1454         tmp.BufSize = 64;
1455         tmp.BufUsed = 0;
1456         tmp.ConstBuf = 1;
1457         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1458                 pnum = &buf[0];
1459                 if (*pnum == '-')
1460                         pnum ++;
1461                 return (unsigned long) atol(pnum);
1462         }
1463         else 
1464                 return 0;
1465 }
1466
1467
1468
1469 /**
1470  * @ingroup StrBuf_NextTokenizer
1471  * @brief a string tokenizer; Bounds checker
1472  *  function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1473  * @param Source our tokenbuffer
1474  * @param pStart the token iterator pointer to inspect
1475  * @returns whether the revolving pointer is inside of the search range
1476  */
1477 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1478 {
1479         if ((Source == NULL) || 
1480             (*pStart == StrBufNOTNULL) ||
1481             (Source->BufUsed == 0))
1482         {
1483                 return 0;
1484         }
1485         if (*pStart == NULL)
1486         {
1487                 return 1;
1488         }
1489         else if (*pStart > Source->buf + Source->BufUsed)
1490         {
1491                 return 0;
1492         }
1493         else if (*pStart <= Source->buf)
1494         {
1495                 return 0;
1496         }
1497
1498         return 1;
1499 }
1500
1501 /**
1502  * @ingroup StrBuf_NextTokenizer
1503  * @brief a string tokenizer
1504  * @param dest Destination StringBuffer
1505  * @param Source StringBuffer to read into
1506  * @param pStart pointer to the end of the last token. Feed with NULL on start.
1507  * @param separator tokenizer 
1508  * @returns -1 if not found, else length of token.
1509  */
1510 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1511 {
1512         const char *s;          /* source */
1513         const char *EndBuffer;  /* end stop of source buffer */
1514         int current_token = 0;  /* token currently being processed */
1515         int len = 0;            /* running total length of extracted string */
1516
1517         if ((Source          == NULL) || 
1518             (Source->BufUsed == 0)      ) 
1519         {
1520                 *pStart = StrBufNOTNULL;
1521                 if (dest != NULL)
1522                         FlushStrBuf(dest);
1523                 return -1;
1524         }
1525          
1526         EndBuffer = Source->buf + Source->BufUsed;
1527
1528         if (dest != NULL) 
1529         {
1530                 dest->buf[0] = '\0';
1531                 dest->BufUsed = 0;
1532         }
1533         else
1534         {
1535                 *pStart = EndBuffer + 1;
1536                 return -1;
1537         }
1538
1539         if (*pStart == NULL)
1540         {
1541                 *pStart = Source->buf; /* we're starting to examine this buffer. */
1542         }
1543         else if ((*pStart < Source->buf) || 
1544                  (*pStart > EndBuffer  )   ) 
1545         {
1546                 return -1; /* no more tokens to find. */
1547         }
1548
1549         s = *pStart;
1550         /* start to find the next token */
1551         while ((s <= EndBuffer)      && 
1552                (current_token == 0) ) 
1553         {
1554                 if (*s == separator) 
1555                 {
1556                         /* we found the next token */
1557                         ++current_token;
1558                 }
1559
1560                 if (len >= dest->BufSize) 
1561                 {
1562                         /* our Dest-buffer isn't big enough, increase it. */
1563                         dest->BufUsed = len;
1564
1565                         if (IncreaseBuf(dest, 1, -1) < 0) {
1566                                 /* WHUT? no more mem? bail out. */
1567                                 s = EndBuffer;
1568                                 dest->BufUsed --;
1569                                 break;
1570                         }
1571                 }
1572
1573                 if ( (current_token == 0 ) &&   /* are we in our target token? */
1574                      (!IsEmptyStr(s)     ) &&
1575                      (separator     != *s)    ) /* don't copy the token itself */
1576                 {
1577                         dest->buf[len] = *s;    /* Copy the payload */
1578                         ++len;                  /* remember the bigger size. */
1579                 }
1580
1581                 ++s;
1582         }
1583
1584         /* did we reach the end? */
1585         if ((s > EndBuffer)) {
1586                 EndBuffer = StrBufNOTNULL;
1587                 *pStart = EndBuffer;
1588         }
1589         else {
1590                 *pStart = s;  /* remember the position for the next run */
1591         }
1592
1593         /* sanitize our extracted token */
1594         dest->buf[len] = '\0';
1595         dest->BufUsed  = len;
1596
1597         return (len);
1598 }
1599
1600
1601 /**
1602  * @ingroup StrBuf_NextTokenizer
1603  * @brief a string tokenizer
1604  * @param Source StringBuffer to read from
1605  * @param pStart pointer to the end of the last token. Feed with NULL.
1606  * @param separator tokenizer character
1607  * @param nTokens number of tokens to fastforward over
1608  * @returns -1 if not found, else length of token.
1609  */
1610 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1611 {
1612         const char *s, *EndBuffer;      //* source * /
1613         int len = 0;                    //* running total length of extracted string * /
1614         int current_token = 0;          //* token currently being processed * /
1615
1616         if ((Source == NULL) || 
1617             (Source->BufUsed ==0)) {
1618                 return(-1);
1619         }
1620         if (nTokens == 0)
1621                 return Source->BufUsed;
1622
1623         if (*pStart == NULL)
1624                 *pStart = Source->buf;
1625
1626         EndBuffer = Source->buf + Source->BufUsed;
1627
1628         if ((*pStart < Source->buf) || 
1629             (*pStart >  EndBuffer)) {
1630                 return (-1);
1631         }
1632
1633
1634         s = *pStart;
1635
1636         //cit_backtrace();
1637         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1638
1639         while ((s < EndBuffer) && !IsEmptyStr(s)) {
1640                 if (*s == separator) {
1641                         ++current_token;
1642                 }
1643                 if (current_token >= nTokens) {
1644                         break;
1645                 }
1646                 ++s;
1647         }
1648         *pStart = s;
1649         (*pStart) ++;
1650
1651         return(len);
1652 }
1653
1654 /**
1655  * @ingroup StrBuf_NextTokenizer
1656  * @brief a string tokenizer to fetch an integer
1657  * @param Source StringBuffer to read from
1658  * @param pStart Cursor on the tokenstring
1659  * @param separator tokenizer character
1660  * @returns 0 if not found, else integer representation of the token
1661  */
1662 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1663 {
1664         StrBuf tmp;
1665         char buf[64];
1666         
1667         tmp.buf = buf;
1668         buf[0] = '\0';
1669         tmp.BufSize = 64;
1670         tmp.BufUsed = 0;
1671         tmp.ConstBuf = 1;
1672         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1673                 return(atoi(buf));
1674         else
1675                 return 0;
1676 }
1677
1678 /**
1679  * @ingroup StrBuf_NextTokenizer
1680  * @brief a string tokenizer to fetch a long integer
1681  * @param Source StringBuffer to read from
1682  * @param pStart Cursor on the tokenstring
1683  * @param separator tokenizer character
1684  * @returns 0 if not found, else long integer representation of the token
1685  */
1686 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1687 {
1688         StrBuf tmp;
1689         char buf[64];
1690         
1691         tmp.buf = buf;
1692         buf[0] = '\0';
1693         tmp.BufSize = 64;
1694         tmp.BufUsed = 0;
1695         tmp.ConstBuf = 1;
1696         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1697                 return(atoi(buf));
1698         else
1699                 return 0;
1700 }
1701
1702
1703 /**
1704  * @ingroup StrBuf_NextTokenizer
1705  * @brief a string tokenizer to fetch an unsigned long
1706  * @param Source StringBuffer to read from
1707  * @param pStart Cursor on the tokenstring
1708  * @param separator tokenizer character
1709  * @returns 0 if not found, else unsigned long representation of the token
1710  */
1711 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1712 {
1713         StrBuf tmp;
1714         char buf[64];
1715         char *pnum;
1716         
1717         tmp.buf = buf;
1718         buf[0] = '\0';
1719         tmp.BufSize = 64;
1720         tmp.BufUsed = 0;
1721         tmp.ConstBuf = 1;
1722         if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1723                 pnum = &buf[0];
1724                 if (*pnum == '-')
1725                         pnum ++;
1726                 return (unsigned long) atol(pnum);
1727         }
1728         else 
1729                 return 0;
1730 }
1731
1732
1733
1734
1735
1736 /*******************************************************************************
1737  *                             Escape Appending                                *
1738  *******************************************************************************/
1739
1740 /** 
1741  * @ingroup StrBuf_DeEnCoder
1742  * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1743  * @param OutBuf the output buffer
1744  * @param In Buffer to encode
1745  * @param PlainIn way in from plain old c strings
1746  */
1747 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1748 {
1749         const char *pch, *pche;
1750         char *pt, *pte;
1751         int len;
1752         
1753         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1754                 return;
1755         if (PlainIn != NULL) {
1756                 len = strlen(PlainIn);
1757                 pch = PlainIn;
1758                 pche = pch + len;
1759         }
1760         else {
1761                 pch = In->buf;
1762                 pche = pch + In->BufUsed;
1763                 len = In->BufUsed;
1764         }
1765
1766         if (len == 0) 
1767                 return;
1768
1769         pt = OutBuf->buf + OutBuf->BufUsed;
1770         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1771
1772         while (pch < pche) {
1773                 if (pt >= pte) {
1774                         IncreaseBuf(OutBuf, 1, -1);
1775                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1776                         pt = OutBuf->buf + OutBuf->BufUsed;
1777                 }
1778
1779                 if((*pch >= 'a' && *pch <= 'z') ||
1780                    (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1781                    (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1782                    (*pch == '!') || (*pch == '_') || 
1783                    (*pch == ',') || (*pch == '.'))
1784                 {
1785                         *(pt++) = *(pch++);
1786                         OutBuf->BufUsed++;
1787                 }                       
1788                 else {
1789                         *pt = '%';
1790                         *(pt + 1) = HexList[(unsigned char)*pch][0];
1791                         *(pt + 2) = HexList[(unsigned char)*pch][1];
1792                         pt += 3;
1793                         OutBuf->BufUsed += 3;
1794                         pch ++;
1795                 }
1796         }
1797         *pt = '\0';
1798 }
1799
1800 /** 
1801  * @ingroup StrBuf_DeEnCoder
1802  * @brief append a string in hex encoding to the buffer
1803  * @param OutBuf the output buffer
1804  * @param In Buffer to encode
1805  * @param PlainIn way in from plain old c strings
1806  * @param PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
1807  */
1808 void StrBufHexEscAppend(StrBuf *OutBuf, const StrBuf *In, const unsigned char *PlainIn, long PlainInLen)
1809 {
1810         const unsigned char *pch, *pche;
1811         char *pt, *pte;
1812         int len;
1813         
1814         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1815                 return;
1816         if (PlainIn != NULL) {
1817                 if (PlainInLen < 0)
1818                         len = strlen((const char*)PlainIn);
1819                 else
1820                         len = PlainInLen;
1821                 pch = PlainIn;
1822                 pche = pch + len;
1823         }
1824         else {
1825                 pch = (const unsigned char*)In->buf;
1826                 pche = pch + In->BufUsed;
1827                 len = In->BufUsed;
1828         }
1829
1830         if (len == 0) 
1831                 return;
1832
1833         pt = OutBuf->buf + OutBuf->BufUsed;
1834         pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1835
1836         while (pch < pche) {
1837                 if (pt >= pte) {
1838                         IncreaseBuf(OutBuf, 1, -1);
1839                         pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1840                         pt = OutBuf->buf + OutBuf->BufUsed;
1841                 }
1842
1843                 *pt = HexList[*pch][0];
1844                 pt ++;
1845                 *pt = HexList[*pch][1];
1846                 pt ++; pch ++; OutBuf->BufUsed += 2;
1847         }
1848         *pt = '\0';
1849 }
1850
1851 /** 
1852  * @ingroup StrBuf_DeEnCoder
1853  * @brief append a string in hex encoding to the buffer
1854  * @param OutBuf the output buffer
1855  * @param In Buffer to encode
1856  * @param PlainIn way in from plain old c strings
1857  */
1858 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1859 {
1860         StrBufHexEscAppend(OutBuf, In, (const unsigned char*) PlainIn, -1);
1861 }
1862
1863 /**
1864  * @ingroup StrBuf_DeEnCoder
1865  * @brief Append a string, escaping characters which have meaning in HTML.  
1866  *
1867  * @param Target        target buffer
1868  * @param Source        source buffer; set to NULL if you just have a C-String
1869  * @param PlainIn       Plain-C string to append; set to NULL if unused
1870  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
1871  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
1872  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
1873  */
1874 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1875 {
1876         const char *aptr, *eiptr;
1877         char *bptr, *eptr;
1878         long len;
1879
1880         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1881                 return -1;
1882
1883         if (PlainIn != NULL) {
1884                 aptr = PlainIn;
1885                 len = strlen(PlainIn);
1886                 eiptr = aptr + len;
1887         }
1888         else {
1889                 aptr = Source->buf;
1890                 eiptr = aptr + Source->BufUsed;
1891                 len = Source->BufUsed;
1892         }
1893
1894         if (len == 0) 
1895                 return -1;
1896
1897         bptr = Target->buf + Target->BufUsed;
1898         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1899
1900         while (aptr < eiptr){
1901                 if(bptr >= eptr) {
1902                         IncreaseBuf(Target, 1, -1);
1903                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
1904                         bptr = Target->buf + Target->BufUsed;
1905                 }
1906                 if (*aptr == '<') {
1907                         memcpy(bptr, "&lt;", 4);
1908                         bptr += 4;
1909                         Target->BufUsed += 4;
1910                 }
1911                 else if (*aptr == '>') {
1912                         memcpy(bptr, "&gt;", 4);
1913                         bptr += 4;
1914                         Target->BufUsed += 4;
1915                 }
1916                 else if (*aptr == '&') {
1917                         memcpy(bptr, "&amp;", 5);
1918                         bptr += 5;
1919                         Target->BufUsed += 5;
1920                 }
1921                 else if (*aptr == '"') {
1922                         memcpy(bptr, "&quot;", 6);
1923                         bptr += 6;
1924                         Target->BufUsed += 6;
1925                 }
1926                 else if (*aptr == '\'') {
1927                         memcpy(bptr, "&#39;", 5);
1928                         bptr += 5;
1929                         Target->BufUsed += 5;
1930                 }
1931                 else if (*aptr == LB) {
1932                         *bptr = '<';
1933                         bptr ++;
1934                         Target->BufUsed ++;
1935                 }
1936                 else if (*aptr == RB) {
1937                         *bptr = '>';
1938                         bptr ++;
1939                         Target->BufUsed ++;
1940                 }
1941                 else if (*aptr == QU) {
1942                         *bptr ='"';
1943                         bptr ++;
1944                         Target->BufUsed ++;
1945                 }
1946                 else if ((*aptr == 32) && (nbsp == 1)) {
1947                         memcpy(bptr, "&nbsp;", 6);
1948                         bptr += 6;
1949                         Target->BufUsed += 6;
1950                 }
1951                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1952                         *bptr='\0';     /* nothing */
1953                 }
1954                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1955                         memcpy(bptr, "&lt;br/&gt;", 11);
1956                         bptr += 11;
1957                         Target->BufUsed += 11;
1958                 }
1959
1960
1961                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1962                         *bptr='\0';     /* nothing */
1963                 }
1964                 else{
1965                         *bptr = *aptr;
1966                         bptr++;
1967                         Target->BufUsed ++;
1968                 }
1969                 aptr ++;
1970         }
1971         *bptr = '\0';
1972         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1973                 return -1;
1974         return Target->BufUsed;
1975 }
1976
1977 /**
1978  * @ingroup StrBuf_DeEnCoder
1979  * @brief Append a string, escaping characters which have meaning in HTML.  
1980  * Converts linebreaks into blanks; escapes single quotes
1981  * @param Target        target buffer
1982  * @param Source        source buffer; set to NULL if you just have a C-String
1983  * @param PlainIn       Plain-C string to append; set to NULL if unused
1984  */
1985 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1986 {
1987         const char *aptr, *eiptr;
1988         char *tptr, *eptr;
1989         long len;
1990
1991         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1992                 return ;
1993
1994         if (PlainIn != NULL) {
1995                 aptr = PlainIn;
1996                 len = strlen(PlainIn);
1997                 eiptr = aptr + len;
1998         }
1999         else {
2000                 aptr = Source->buf;
2001                 eiptr = aptr + Source->BufUsed;
2002                 len = Source->BufUsed;
2003         }
2004
2005         if (len == 0) 
2006                 return;
2007
2008         eptr = Target->buf + Target->BufSize - 8; 
2009         tptr = Target->buf + Target->BufUsed;
2010         
2011         while (aptr < eiptr){
2012                 if(tptr >= eptr) {
2013                         IncreaseBuf(Target, 1, -1);
2014                         eptr = Target->buf + Target->BufSize - 8; 
2015                         tptr = Target->buf + Target->BufUsed;
2016                 }
2017                
2018                 if (*aptr == '\n') {
2019                         *tptr = ' ';
2020                         Target->BufUsed++;
2021                 }
2022                 else if (*aptr == '\r') {
2023                         *tptr = ' ';
2024                         Target->BufUsed++;
2025                 }
2026                 else if (*aptr == '\'') {
2027                         *(tptr++) = '&';
2028                         *(tptr++) = '#';
2029                         *(tptr++) = '3';
2030                         *(tptr++) = '9';
2031                         *tptr = ';';
2032                         Target->BufUsed += 5;
2033                 } else {
2034                         *tptr = *aptr;
2035                         Target->BufUsed++;
2036                 }
2037                 tptr++; aptr++;
2038         }
2039         *tptr = '\0';
2040 }
2041
2042
2043
2044 /**
2045  * @ingroup StrBuf_DeEnCoder
2046  * @brief Append a string, escaping characters which have meaning in ICAL.  
2047  * [\n,] 
2048  * @param Target        target buffer
2049  * @param Source        source buffer; set to NULL if you just have a C-String
2050  * @param PlainIn       Plain-C string to append; set to NULL if unused
2051  */
2052 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2053 {
2054         const char *aptr, *eiptr;
2055         char *tptr, *eptr;
2056         long len;
2057
2058         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2059                 return ;
2060
2061         if (PlainIn != NULL) {
2062                 aptr = PlainIn;
2063                 len = strlen(PlainIn);
2064                 eiptr = aptr + len;
2065         }
2066         else {
2067                 aptr = Source->buf;
2068                 eiptr = aptr + Source->BufUsed;
2069                 len = Source->BufUsed;
2070         }
2071
2072         if (len == 0) 
2073                 return;
2074
2075         eptr = Target->buf + Target->BufSize - 8; 
2076         tptr = Target->buf + Target->BufUsed;
2077         
2078         while (aptr < eiptr){
2079                 if(tptr + 3 >= eptr) {
2080                         IncreaseBuf(Target, 1, -1);
2081                         eptr = Target->buf + Target->BufSize - 8; 
2082                         tptr = Target->buf + Target->BufUsed;
2083                 }
2084                
2085                 if (*aptr == '\n') {
2086                         *tptr = '\\';
2087                         Target->BufUsed++;
2088                         tptr++;
2089                         *tptr = 'n';
2090                         Target->BufUsed++;
2091                 }
2092                 else if (*aptr == '\r') {
2093                         *tptr = '\\';
2094                         Target->BufUsed++;
2095                         tptr++;
2096                         *tptr = 'r';
2097                         Target->BufUsed++;
2098                 }
2099                 else if (*aptr == ',') {
2100                         *tptr = '\\';
2101                         Target->BufUsed++;
2102                         tptr++;
2103                         *tptr = ',';
2104                         Target->BufUsed++;
2105                 } else {
2106                         *tptr = *aptr;
2107                         Target->BufUsed++;
2108                 }
2109                 tptr++; aptr++;
2110         }
2111         *tptr = '\0';
2112 }
2113
2114 /**
2115  * @ingroup StrBuf_DeEnCoder
2116  * @brief Append a string, escaping characters which have meaning in JavaScript strings .  
2117  *
2118  * @param Target        target buffer
2119  * @param Source        source buffer; set to NULL if you just have a C-String
2120  * @param PlainIn       Plain-C string to append; set to NULL if unused
2121  * @returns size of result or -1
2122  */
2123 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2124 {
2125         const char *aptr, *eiptr;
2126         char *bptr, *eptr;
2127         long len;
2128         int IsUtf8Sequence;
2129
2130         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2131                 return -1;
2132
2133         if (PlainIn != NULL) {
2134                 aptr = PlainIn;
2135                 len = strlen(PlainIn);
2136                 eiptr = aptr + len;
2137         }
2138         else {
2139                 aptr = Source->buf;
2140                 eiptr = aptr + Source->BufUsed;
2141                 len = Source->BufUsed;
2142         }
2143
2144         if (len == 0) 
2145                 return -1;
2146
2147         bptr = Target->buf + Target->BufUsed;
2148         eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in...  */
2149
2150         while (aptr < eiptr){
2151                 if(bptr >= eptr) {
2152                         IncreaseBuf(Target, 1, -1);
2153                         eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in...  */
2154                         bptr = Target->buf + Target->BufUsed;
2155                 }
2156                 switch (*aptr) {
2157                 case '\n':
2158                         memcpy(bptr, HKEY("\\n"));
2159                         bptr += 2;
2160                         Target->BufUsed += 2;                           
2161                         break;
2162                 case '\r':
2163                         memcpy(bptr, HKEY("\\r"));
2164                         bptr += 2;
2165                         Target->BufUsed += 2;
2166                         break;
2167                 case '"':
2168                         *bptr = '\\';
2169                         bptr ++;
2170                         *bptr = '"';
2171                         bptr ++;
2172                         Target->BufUsed += 2;
2173                         break;
2174                 case '\\':
2175                         if ((*(aptr + 1) == 'u') &&
2176                             isxdigit(*(aptr + 2)) &&
2177                             isxdigit(*(aptr + 3)) &&
2178                             isxdigit(*(aptr + 4)) &&
2179                             isxdigit(*(aptr + 5)))
2180                         { /* oh, a unicode escaper. let it pass through. */
2181                                 memcpy(bptr, aptr, 6);
2182                                 aptr += 5;
2183                                 bptr +=6;
2184                                 Target->BufUsed += 6;
2185                         }
2186                         else 
2187                         {
2188                                 *bptr = '\\';
2189                                 bptr ++;
2190                                 *bptr = '\\';
2191                                 bptr ++;
2192                                 Target->BufUsed += 2;
2193                         }
2194                         break;
2195                 case '\b':
2196                         *bptr = '\\';
2197                         bptr ++;
2198                         *bptr = 'b';
2199                         bptr ++;
2200                         Target->BufUsed += 2;
2201                         break;
2202                 case '\f':
2203                         *bptr = '\\';
2204                         bptr ++;
2205                         *bptr = 'f';
2206                         bptr ++;
2207                         Target->BufUsed += 2;
2208                         break;
2209                 case '\t':
2210                         *bptr = '\\';
2211                         bptr ++;
2212                         *bptr = 't';
2213                         bptr ++;
2214                         Target->BufUsed += 2;
2215                         break;
2216                 default:
2217                         IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2218                         while (IsUtf8Sequence > 0){
2219                                 *bptr = *aptr;
2220                                 Target->BufUsed ++;
2221                                 if (--IsUtf8Sequence)
2222                                         aptr++;
2223                                 bptr++;
2224                         }
2225                 }
2226                 aptr ++;
2227         }
2228         *bptr = '\0';
2229         if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2230                 return -1;
2231         return Target->BufUsed;
2232 }
2233
2234 /**
2235  * @ingroup StrBuf_DeEnCoder
2236  * @brief Append a string, escaping characters which have meaning in HTML + json.  
2237  *
2238  * @param Target        target buffer
2239  * @param Source        source buffer; set to NULL if you just have a C-String
2240  * @param PlainIn       Plain-C string to append; set to NULL if unused
2241  * @param nbsp          If nonzero, spaces are converted to non-breaking spaces.
2242  * @param nolinebreaks  if set to 1, linebreaks are removed from the string.
2243  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
2244  */
2245 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2246 {
2247         const char *aptr, *eiptr;
2248         char *bptr, *eptr;
2249         long len;
2250         int IsUtf8Sequence = 0;
2251
2252         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2253                 return -1;
2254
2255         if (PlainIn != NULL) {
2256                 aptr = PlainIn;
2257                 len = strlen(PlainIn);
2258                 eiptr = aptr + len;
2259         }
2260         else {
2261                 aptr = Source->buf;
2262                 eiptr = aptr + Source->BufUsed;
2263                 len = Source->BufUsed;
2264         }
2265
2266         if (len == 0) 
2267                 return -1;
2268
2269         bptr = Target->buf + Target->BufUsed;
2270         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
2271
2272         while (aptr < eiptr){
2273                 if(bptr >= eptr) {
2274                         IncreaseBuf(Target, 1, -1);
2275                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
2276                         bptr = Target->buf + Target->BufUsed;
2277                 }
2278                 switch (*aptr) {
2279                 case '<':
2280                         memcpy(bptr, HKEY("&lt;"));
2281                         bptr += 4;
2282                         Target->BufUsed += 4;
2283                         break;
2284                 case '>':
2285                         memcpy(bptr, HKEY("&gt;"));
2286                         bptr += 4;
2287                         Target->BufUsed += 4;
2288                         break;
2289                 case '&':
2290                         memcpy(bptr, HKEY("&amp;"));
2291                         bptr += 5;
2292                         Target->BufUsed += 5;
2293                         break;
2294                 case LB:
2295                         *bptr = '<';
2296                         bptr ++;
2297                         Target->BufUsed ++;
2298                         break;
2299                 case RB:
2300                         *bptr = '>';
2301                         bptr ++;
2302                         Target->BufUsed ++;
2303                         break;
2304                 case '\n':
2305                         switch (nolinebreaks) {
2306                         case 1:
2307                                 *bptr='\0';     /* nothing */
2308                                 break;
2309                         case 2:
2310                                 memcpy(bptr, HKEY("&lt;br/&gt;"));
2311                                 bptr += 11;
2312                                 Target->BufUsed += 11;
2313                                 break;
2314                         default:
2315                                 memcpy(bptr, HKEY("\\n"));
2316                                 bptr += 2;
2317                                 Target->BufUsed += 2;                           
2318                         }
2319                         break;
2320                 case '\r':
2321                         switch (nolinebreaks) {
2322                         case 1:
2323                         case 2:
2324                                 *bptr='\0';     /* nothing */
2325                                 break;
2326                         default:
2327                                 memcpy(bptr, HKEY("\\r"));
2328                                 bptr += 2;
2329                                 Target->BufUsed += 2;
2330                                 break;
2331                         }
2332                         break;
2333                 case '"':
2334                 case QU:
2335                         *bptr = '\\';
2336                         bptr ++;
2337                         *bptr = '"';
2338                         bptr ++;
2339                         Target->BufUsed += 2;
2340                         break;
2341                 case '\\':
2342                         if ((*(aptr + 1) == 'u') &&
2343                             isxdigit(*(aptr + 2)) &&
2344                             isxdigit(*(aptr + 3)) &&
2345                             isxdigit(*(aptr + 4)) &&
2346                             isxdigit(*(aptr + 5)))
2347                         { /* oh, a unicode escaper. let it pass through. */
2348                                 memcpy(bptr, aptr, 6);
2349                                 aptr += 5;
2350                                 bptr +=6;
2351                                 Target->BufUsed += 6;
2352                         }
2353                         else 
2354                         {
2355                                 *bptr = '\\';
2356                                 bptr ++;
2357                                 *bptr = '\\';
2358                                 bptr ++;
2359                                 Target->BufUsed += 2;
2360                         }
2361                         break;
2362                 case '\b':
2363                         *bptr = '\\';
2364                         bptr ++;
2365                         *bptr = 'b';
2366                         bptr ++;
2367                         Target->BufUsed += 2;
2368                         break;
2369                 case '\f':
2370                         *bptr = '\\';
2371                         bptr ++;
2372                         *bptr = 'f';
2373                         bptr ++;
2374                         Target->BufUsed += 2;
2375                         break;
2376                 case '\t':
2377                         *bptr = '\\';
2378                         bptr ++;
2379                         *bptr = 't';
2380                         bptr ++;
2381                         Target->BufUsed += 2;
2382                         break;
2383                 case  32:
2384                         if (nbsp == 1) {
2385                                 memcpy(bptr, HKEY("&nbsp;"));
2386                                 bptr += 6;
2387                                 Target->BufUsed += 6;
2388                                 break;
2389                         }
2390                 default:
2391                         IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2392                         while (IsUtf8Sequence > 0){
2393                                 *bptr = *aptr;
2394                                 Target->BufUsed ++;
2395                                 if (--IsUtf8Sequence)
2396                                         aptr++;
2397                                 bptr++;
2398                         }
2399                 }
2400                 aptr ++;
2401         }
2402         *bptr = '\0';
2403         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2404                 return -1;
2405         return Target->BufUsed;
2406 }
2407
2408 /**
2409  * @ingroup StrBuf_DeEnCoder
2410  * @brief unhide special chars hidden to the HTML escaper
2411  * @param target buffer to put the unescaped string in
2412  * @param source buffer to unescape
2413  */
2414 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
2415 {
2416         int a, b, len;
2417         char hex[3];
2418
2419         if (target != NULL)
2420                 FlushStrBuf(target);
2421
2422         if (source == NULL ||target == NULL)
2423         {
2424                 return;
2425         }
2426
2427         len = source->BufUsed;
2428         for (a = 0; a < len; ++a) {
2429                 if (target->BufUsed >= target->BufSize)
2430                         IncreaseBuf(target, 1, -1);
2431
2432                 if (source->buf[a] == '=') {
2433                         hex[0] = source->buf[a + 1];
2434                         hex[1] = source->buf[a + 2];
2435                         hex[2] = 0;
2436                         b = 0;
2437                         sscanf(hex, "%02x", &b);
2438                         target->buf[target->BufUsed] = b;
2439                         target->buf[++target->BufUsed] = 0;
2440                         a += 2;
2441                 }
2442                 else {
2443                         target->buf[target->BufUsed] = source->buf[a];
2444                         target->buf[++target->BufUsed] = 0;
2445                 }
2446         }
2447 }
2448
2449
2450 /**
2451  * @ingroup StrBuf_DeEnCoder
2452  * @brief hide special chars from the HTML escapers and friends
2453  * @param target buffer to put the escaped string in
2454  * @param source buffer to escape
2455  */
2456 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
2457 {
2458         int i, len;
2459
2460         if (target != NULL)
2461                 FlushStrBuf(target);
2462
2463         if (source == NULL ||target == NULL)
2464         {
2465                 return;
2466         }
2467
2468         len = source->BufUsed;
2469         for (i=0; i<len; ++i) {
2470                 if (target->BufUsed + 4 >= target->BufSize)
2471                         IncreaseBuf(target, 1, -1);
2472                 if ( (isalnum(source->buf[i])) || 
2473                      (source->buf[i]=='-') || 
2474                      (source->buf[i]=='_') ) {
2475                         target->buf[target->BufUsed++] = source->buf[i];
2476                 }
2477                 else {
2478                         sprintf(&target->buf[target->BufUsed], 
2479                                 "=%02X", 
2480                                 (0xFF &source->buf[i]));
2481                         target->BufUsed += 3;
2482                 }
2483         }
2484         target->buf[target->BufUsed + 1] = '\0';
2485 }
2486
2487
2488 /*******************************************************************************
2489  *                      Quoted Printable de/encoding                           *
2490  *******************************************************************************/
2491
2492 /**
2493  * @ingroup StrBuf_DeEnCoder
2494  * @brief decode a buffer from base 64 encoding; destroys original
2495  * @param Buf Buffor to transform
2496  */
2497 int StrBufDecodeBase64(StrBuf *Buf)
2498 {
2499         char *xferbuf;
2500         size_t siz;
2501         if (Buf == NULL) return -1;
2502
2503         xferbuf = (char*) malloc(Buf->BufSize);
2504         *xferbuf = '\0';
2505         siz = CtdlDecodeBase64(xferbuf,
2506                                Buf->buf,
2507                                Buf->BufUsed);
2508         free(Buf->buf);
2509         Buf->buf = xferbuf;
2510         Buf->BufUsed = siz;
2511         return siz;
2512 }
2513
2514 /**
2515  * @ingroup StrBuf_DeEnCoder
2516  * @brief decode a buffer from base 64 encoding; destroys original
2517  * @param Buf Buffor to transform
2518  */
2519 int StrBufDecodeHex(StrBuf *Buf)
2520 {
2521         unsigned int ch;
2522         char *pch, *pche, *pchi;
2523
2524         if (Buf == NULL) return -1;
2525
2526         pch = pchi = Buf->buf;
2527         pche = pch + Buf->BufUsed;
2528
2529         while (pchi < pche){
2530                 ch = decode_hex(pchi);
2531                 *pch = ch;
2532                 pch ++;
2533                 pchi += 2;
2534         }
2535
2536         *pch = '\0';
2537         Buf->BufUsed = pch - Buf->buf;
2538         return Buf->BufUsed;
2539 }
2540
2541 /**
2542  * @ingroup StrBuf_DeEnCoder
2543  * @brief replace all chars >0x20 && < 0x7F with Mute
2544  * @param Mute char to put over invalid chars
2545  * @param Buf Buffor to transform
2546  */
2547 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2548 {
2549         unsigned char *pch;
2550
2551         if (Buf == NULL) return -1;
2552         pch = (unsigned char *)Buf->buf;
2553         while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2554                 if ((*pch < 0x20) || (*pch > 0x7F))
2555                         *pch = Mute;
2556                 pch ++;
2557         }
2558         return Buf->BufUsed;
2559 }
2560
2561
2562 /**
2563  * @ingroup StrBuf_DeEnCoder
2564  * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2565  * @param Buf Buffer to translate
2566  * @param StripBlanks Reduce several blanks to one?
2567  */
2568 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2569 {
2570         int a, b;
2571         char hex[3];
2572         long len;
2573
2574         if (Buf == NULL)
2575                 return -1;
2576
2577         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2578                 Buf->buf[Buf->BufUsed - 1] = '\0';
2579                 Buf->BufUsed --;
2580         }
2581
2582         a = 0; 
2583         while (a < Buf->BufUsed) {
2584                 if (Buf->buf[a] == '+')
2585                         Buf->buf[a] = ' ';
2586                 else if (Buf->buf[a] == '%') {
2587                         /* don't let % chars through, rather truncate the input. */
2588                         if (a + 2 > Buf->BufUsed) {
2589                                 Buf->buf[a] = '\0';
2590                                 Buf->BufUsed = a;
2591                         }
2592                         else {                  
2593                                 hex[0] = Buf->buf[a + 1];
2594                                 hex[1] = Buf->buf[a + 2];
2595                                 hex[2] = 0;
2596                                 b = 0;
2597                                 sscanf(hex, "%02x", &b);
2598                                 Buf->buf[a] = (char) b;
2599                                 len = Buf->BufUsed - a - 2;
2600                                 if (len > 0)
2601                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2602                         
2603                                 Buf->BufUsed -=2;
2604                         }
2605                 }
2606                 a++;
2607         }
2608         return a;
2609 }
2610
2611
2612 /**
2613  * @ingroup StrBuf_DeEnCoder
2614  * @brief       RFC2047-encode a header field if necessary.
2615  *              If no non-ASCII characters are found, the string
2616  *              will be copied verbatim without encoding.
2617  *
2618  * @param       target          Target buffer.
2619  * @param       source          Source string to be encoded.
2620  * @returns     encoded length; -1 if non success.
2621  */
2622 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2623 {
2624         const char headerStr[] = "=?UTF-8?Q?";
2625         int need_to_encode = 0;
2626         int i = 0;
2627         unsigned char ch;
2628
2629         if ((source == NULL) || 
2630             (target == NULL))
2631             return -1;
2632
2633         while ((i < source->BufUsed) &&
2634                (!IsEmptyStr (&source->buf[i])) &&
2635                (need_to_encode == 0)) {
2636                 if (((unsigned char) source->buf[i] < 32) || 
2637                     ((unsigned char) source->buf[i] > 126)) {
2638                         need_to_encode = 1;
2639                 }
2640                 i++;
2641         }
2642
2643         if (!need_to_encode) {
2644                 if (*target == NULL) {
2645                         *target = NewStrBufPlain(source->buf, source->BufUsed);
2646                 }
2647                 else {
2648                         FlushStrBuf(*target);
2649                         StrBufAppendBuf(*target, source, 0);
2650                 }
2651                 return (*target)->BufUsed;
2652         }
2653         if (*target == NULL)
2654                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2655         else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2656                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2657         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2658         (*target)->BufUsed = sizeof(headerStr) - 1;
2659         for (i=0; (i < source->BufUsed); ++i) {
2660                 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2661                         IncreaseBuf(*target, 1, 0);
2662                 ch = (unsigned char) source->buf[i];
2663                 if ((ch  <  32) || 
2664                     (ch  > 126) || 
2665                     (ch ==  61) ||
2666                     (ch == '=') ||
2667                     (ch == '_') ||
2668                     (ch == '[') ||
2669                     (ch == ']')   )
2670                 {
2671                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2672                         (*target)->BufUsed += 3;
2673                 }
2674                 else {
2675                         if (ch == ' ')
2676                                 (*target)->buf[(*target)->BufUsed] = '_';
2677                         else
2678                                 (*target)->buf[(*target)->BufUsed] = ch;
2679                         (*target)->BufUsed++;
2680                 }
2681         }
2682         
2683         if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2684                 IncreaseBuf(*target, 1, 0);
2685
2686         (*target)->buf[(*target)->BufUsed++] = '?';
2687         (*target)->buf[(*target)->BufUsed++] = '=';
2688         (*target)->buf[(*target)->BufUsed] = '\0';
2689         return (*target)->BufUsed;;
2690 }
2691
2692
2693
2694 static void AddRecipient(StrBuf *Target, 
2695                          StrBuf *UserName, 
2696                          StrBuf *EmailAddress, 
2697                          StrBuf *EncBuf)
2698 {
2699         int QuoteMe = 0;
2700
2701         if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2702         if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2703
2704         if (QuoteMe)  StrBufAppendBufPlain(Target, HKEY("\""), 0);
2705         StrBufRFC2047encode(&EncBuf, UserName);
2706         StrBufAppendBuf(Target, EncBuf, 0);
2707         if (QuoteMe)  StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2708         else          StrBufAppendBufPlain(Target, HKEY(" "), 0);
2709
2710         if (StrLength(EmailAddress) > 0){
2711                 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2712                 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2713                 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2714         }
2715 }
2716
2717
2718 /**
2719  * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2720  * \param Recp Source list of email recipients
2721  * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2722  * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2723  * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2724  * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2725  */
2726 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp, 
2727                                            StrBuf *UserName, 
2728                                            StrBuf *EmailAddress,
2729                                            StrBuf *EncBuf)
2730 {
2731         StrBuf *Target;
2732         const char *pch, *pche;
2733         const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2734
2735         if ((Recp == NULL) || (StrLength(Recp) == 0))
2736                 return NULL;
2737
2738         pch = ChrPtr(Recp);
2739         pche = pch + StrLength(Recp);
2740
2741         if (!CheckEncode(pch, -1, pche))
2742                 return NewStrBufDup(Recp);
2743
2744         Target = NewStrBufPlain(NULL, StrLength(Recp));
2745
2746         while ((pch != NULL) && (pch < pche))
2747         {
2748                 while (isspace(*pch)) pch++;
2749                 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2750                 
2751                 if ((*pch == '"') || (*pch == '\'')) {
2752                         UserStart = pch + 1;
2753                         
2754                         UserEnd = strchr(UserStart, *pch);
2755                         if (UserEnd == NULL) 
2756                                 break; ///TODO: Userfeedback??
2757                         EmailStart = UserEnd + 1;
2758                         while (isspace(*EmailStart))
2759                                 EmailStart++;
2760                         if (UserEnd == UserStart) {
2761                                 UserStart = UserEnd = NULL;
2762                         }
2763                         
2764                         if (*EmailStart == '<') {
2765                                 EmailStart++;
2766                                 EmailEnd = strchr(EmailStart, '>');
2767                                 if (EmailEnd == NULL)
2768                                         EmailEnd = strchr(EmailStart, ',');
2769                                 
2770                         }
2771                         else {
2772                                 EmailEnd = strchr(EmailStart, ',');
2773                         }
2774                         if (EmailEnd == NULL)
2775                                 EmailEnd = pche;
2776                         pch = EmailEnd + 1;
2777                 }
2778                 else {
2779                         int gt = 0;
2780                         UserStart = pch;
2781                         EmailEnd = strchr(UserStart, ',');
2782                         if (EmailEnd == NULL) {
2783                                 EmailEnd = strchr(pch, '>');
2784                                 pch = NULL;
2785                                 if (EmailEnd != NULL) {
2786                                         gt = 1;
2787                                 }
2788                                 else {
2789                                         EmailEnd = pche;
2790                                 }
2791                         }
2792                         else {
2793
2794                                 pch = EmailEnd + 1;
2795                                 while ((EmailEnd > UserStart) && !gt &&
2796                                        ((*EmailEnd == ',') ||
2797                                         (*EmailEnd == '>') ||
2798                                         (isspace(*EmailEnd))))
2799                                 {
2800                                         if (*EmailEnd == '>')
2801                                                 gt = 1;
2802                                         else 
2803                                                 EmailEnd--;
2804                                 }
2805                                 if (EmailEnd == UserStart)
2806                                         break;
2807                         }
2808                         if (gt) {
2809                                 EmailStart = strchr(UserStart, '<');
2810                                 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2811                                         break;
2812                                 UserEnd = EmailStart;
2813
2814                                 while ((UserEnd > UserStart) && 
2815                                        isspace (*(UserEnd - 1)))
2816                                         UserEnd --;
2817                                 EmailStart ++;
2818                                 if (UserStart >= UserEnd)
2819                                         UserStart = UserEnd = NULL;
2820                                 At = strchr(EmailStart, '@');
2821                         }
2822                         else { /* this is a local recipient... no domain, just a realname */
2823                                 EmailStart = UserStart;
2824                                 At = strchr(EmailStart, '@');
2825                                 if (At == NULL) {
2826                                         UserEnd = EmailEnd;
2827                                         EmailEnd = NULL;
2828                                 }
2829                                 else {
2830                                         EmailStart = UserStart;
2831                                         UserStart = NULL;
2832                                 }
2833                         }
2834                 }
2835
2836                 if ((UserStart != NULL) && (UserEnd != NULL))
2837                         StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2838                 else if ((UserStart != NULL) && (UserEnd == NULL))
2839                         StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2840                 else
2841                         FlushStrBuf(UserName);
2842
2843                 if ((EmailStart != NULL) && (EmailEnd != NULL))
2844                         StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2845                 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2846                         StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2847                 else 
2848                         FlushStrBuf(EmailAddress);
2849
2850                 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2851
2852                 if (pch == NULL)
2853                         break;
2854                 
2855                 if ((pch != NULL) && (*pch == ','))
2856                         pch ++;
2857                 if (pch != NULL) while (isspace(*pch))
2858                         pch ++;
2859         }
2860         return Target;
2861 }
2862
2863
2864 /**
2865  * @ingroup StrBuf
2866  * @brief replaces all occurances of 'search' by 'replace'
2867  * @param buf Buffer to modify
2868  * @param search character to search
2869  * @param replace character to replace search by
2870  */
2871 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2872 {
2873         long i;
2874         if (buf == NULL)
2875                 return;
2876         for (i=0; i<buf->BufUsed; i++)
2877                 if (buf->buf[i] == search)
2878                         buf->buf[i] = replace;
2879
2880 }
2881
2882 /**
2883  * @ingroup StrBuf
2884  * @brief removes all \\r s from the string, or replaces them with \n if its not a combination of both.
2885  * @param buf Buffer to modify
2886  */
2887 void StrBufToUnixLF(StrBuf *buf)
2888 {
2889         char *pche, *pchS, *pchT;
2890         if (buf == NULL)
2891                 return;
2892
2893         pche = buf->buf + buf->BufUsed;
2894         pchS = pchT = buf->buf;
2895         while (pchS < pche)
2896         {
2897                 if (*pchS == '\r')
2898                 {
2899                         pchS ++;
2900                         if (*pchS != '\n') {
2901                                 *pchT = '\n';
2902                                 pchT++;
2903                         }
2904                 }
2905                 *pchT = *pchS;
2906                 pchT++; pchS++;
2907         }
2908         *pchT = '\0';
2909         buf->BufUsed = pchT - buf->buf;
2910 }
2911
2912
2913 /*******************************************************************************
2914  *                 Iconv Wrapper; RFC822 de/encoding                           *
2915  *******************************************************************************/
2916
2917 /**
2918  * @ingroup StrBuf_DeEnCoder
2919  * @brief Wrapper around iconv_open()
2920  * Our version adds aliases for non-standard Microsoft charsets
2921  * such as 'MS950', aliasing them to names like 'CP950'
2922  *
2923  * @param tocode        Target encoding
2924  * @param fromcode      Source encoding
2925  * @param pic           anonimized pointer to iconv struct
2926  */
2927 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2928 {
2929 #ifdef HAVE_ICONV
2930         iconv_t ic = (iconv_t)(-1) ;
2931         ic = iconv_open(tocode, fromcode);
2932         if (ic == (iconv_t)(-1) ) {
2933                 char alias_fromcode[64];
2934                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2935                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2936                         alias_fromcode[0] = 'C';
2937                         alias_fromcode[1] = 'P';
2938                         ic = iconv_open(tocode, alias_fromcode);
2939                 }
2940         }
2941         *(iconv_t *)pic = ic;
2942 #endif
2943 }
2944
2945
2946 /**
2947  * @ingroup StrBuf_DeEnCoder
2948  * @brief find one chunk of a RFC822 encoded string
2949  * @param Buffer where to search
2950  * @param bptr where to start searching
2951  * @returns found position, NULL if none.
2952  */
2953 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2954 {
2955         const char * end;
2956         /* Find the next ?Q? */
2957         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
2958                 return NULL;
2959
2960         end = strchr(bptr + 2, '?');
2961
2962         if (end == NULL)
2963                 return NULL;
2964
2965         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2966             (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
2967              ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) && 
2968             (*(end + 2) == '?')) {
2969                 /* skip on to the end of the cluster, the next ?= */
2970                 end = strstr(end + 3, "?=");
2971         }
2972         else
2973                 /* sort of half valid encoding, try to find an end. */
2974                 end = strstr(bptr, "?=");
2975         return end;
2976 }
2977
2978
2979
2980 /**
2981  * @ingroup StrBuf_DeEnCoder
2982  * @brief convert one buffer according to the preselected iconv pointer PIC
2983  * @param ConvertBuf buffer we need to translate
2984  * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2985  * @param pic Pointer to the iconv-session Object
2986  */
2987 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2988 {
2989 #ifdef HAVE_ICONV
2990         long trycount = 0;
2991         size_t siz;
2992         iconv_t ic;
2993         char *ibuf;                     /**< Buffer of characters to be converted */
2994         char *obuf;                     /**< Buffer for converted characters */
2995         size_t ibuflen;                 /**< Length of input buffer */
2996         size_t obuflen;                 /**< Length of output buffer */
2997
2998
2999         /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3000         if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3001                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3002 TRYAGAIN:
3003         ic = *(iconv_t*)pic;
3004         ibuf = ConvertBuf->buf;
3005         ibuflen = ConvertBuf->BufUsed;
3006         obuf = TmpBuf->buf;
3007         obuflen = TmpBuf->BufSize;
3008         
3009         siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3010
3011         if (siz < 0) {
3012                 if (errno == E2BIG) {
3013                         trycount ++;                    
3014                         IncreaseBuf(TmpBuf, 0, 0);
3015                         if (trycount < 5) 
3016                                 goto TRYAGAIN;
3017
3018                 }
3019                 else if (errno == EILSEQ){ 
3020                         /* hm, invalid utf8 sequence... what to do now? */
3021                         /* An invalid multibyte sequence has been encountered in the input */
3022                 }
3023                 else if (errno == EINVAL) {
3024                         /* An incomplete multibyte sequence has been encountered in the input. */
3025                 }
3026
3027                 FlushStrBuf(TmpBuf);
3028         }
3029         else {
3030                 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3031                 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3032                 
3033                 /* little card game: wheres the red lady? */
3034                 SwapBuffers(ConvertBuf, TmpBuf);
3035                 FlushStrBuf(TmpBuf);
3036         }
3037 #endif
3038 }
3039
3040
3041 /**
3042  * @ingroup StrBuf_DeEnCoder
3043  * @brief catches one RFC822 encoded segment, and decodes it.
3044  * @param Target buffer to fill with result
3045  * @param DecodeMe buffer with stuff to process
3046  * @param SegmentStart points to our current segment in DecodeMe
3047  * @param SegmentEnd Points to the end of our current segment in DecodeMe
3048  * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3049  * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3050  * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3051  */
3052 inline static void DecodeSegment(StrBuf *Target, 
3053                                  const StrBuf *DecodeMe, 
3054                                  const char *SegmentStart, 
3055                                  const char *SegmentEnd, 
3056                                  StrBuf *ConvertBuf,
3057                                  StrBuf *ConvertBuf2, 
3058                                  StrBuf *FoundCharset)
3059 {
3060         StrBuf StaticBuf;
3061         char charset[128];
3062         char encoding[16];
3063 #ifdef HAVE_ICONV
3064         iconv_t ic = (iconv_t)(-1);
3065 #else
3066         void *ic = NULL;
3067 #endif
3068         /* Now we handle foreign character sets properly encoded
3069          * in RFC2047 format.
3070          */
3071         StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
3072         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3073         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3074         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3075         if (FoundCharset != NULL) {
3076                 FlushStrBuf(FoundCharset);
3077                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3078         }
3079         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3080         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3081         
3082         *encoding = toupper(*encoding);
3083         if (*encoding == 'B') { /**< base64 */
3084                 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3085                         IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3086                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
3087                                                         ConvertBuf->buf, 
3088                                                         ConvertBuf->BufUsed);
3089         }
3090         else if (*encoding == 'Q') {    /**< quoted-printable */
3091                 long pos;
3092                 
3093                 pos = 0;
3094                 while (pos < ConvertBuf->BufUsed)
3095                 {
3096                         if (ConvertBuf->buf[pos] == '_') 
3097                                 ConvertBuf->buf[pos] = ' ';
3098                         pos++;
3099                 }
3100                 
3101                 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3102                         IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3103
3104                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3105                         ConvertBuf2->buf, 
3106                         ConvertBuf->buf,
3107                         ConvertBuf->BufUsed);
3108         }
3109         else {
3110                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3111         }
3112 #ifdef HAVE_ICONV
3113         ctdl_iconv_open("UTF-8", charset, &ic);
3114         if (ic != (iconv_t)(-1) ) {             
3115 #endif
3116                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3117                 StrBufAppendBuf(Target, ConvertBuf2, 0);
3118 #ifdef HAVE_ICONV
3119                 iconv_close(ic);
3120         }
3121         else {
3122                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3123         }
3124 #endif
3125 }
3126
3127 /**
3128  * @ingroup StrBuf_DeEnCoder
3129  * @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
3130  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3131  * @param Target where to put the decoded string to 
3132  * @param DecodeMe buffer with encoded string
3133  * @param DefaultCharset if we don't find one, which should we use?
3134  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3135  *        put it here for later use where no string might be known.
3136  */
3137 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3138 {
3139         StrBuf *ConvertBuf;
3140         StrBuf *ConvertBuf2;
3141         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3142         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3143         
3144         StrBuf_RFC822_2_Utf8(Target, 
3145                              DecodeMe, 
3146                              DefaultCharset, 
3147                              FoundCharset, 
3148                              ConvertBuf, 
3149                              ConvertBuf2);
3150         FreeStrBuf(&ConvertBuf);
3151         FreeStrBuf(&ConvertBuf2);
3152 }
3153
3154 /**
3155  * @ingroup StrBuf_DeEnCoder
3156  * @brief Handle subjects with RFC2047 encoding such as:
3157  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3158  * @param Target where to put the decoded string to 
3159  * @param DecodeMe buffer with encoded string
3160  * @param DefaultCharset if we don't find one, which should we use?
3161  * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
3162  *        put it here for later use where no string might be known.
3163  * @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3164  * @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3165  */
3166 void StrBuf_RFC822_2_Utf8(StrBuf *Target, 
3167                           const StrBuf *DecodeMe, 
3168                           const StrBuf* DefaultCharset, 
3169                           StrBuf *FoundCharset, 
3170                           StrBuf *ConvertBuf, 
3171                           StrBuf *ConvertBuf2)
3172 {
3173         StrBuf *DecodedInvalidBuf = NULL;
3174         const StrBuf *DecodeMee = DecodeMe;
3175         const char *start, *end, *next, *nextend, *ptr = NULL;
3176 #ifdef HAVE_ICONV
3177         iconv_t ic = (iconv_t)(-1) ;
3178 #endif
3179         const char *eptr;
3180         int passes = 0;
3181         int i, len;
3182         int illegal_non_rfc2047_encoding = 0;
3183
3184         /* Sometimes, badly formed messages contain strings which were simply
3185          *  written out directly in some foreign character set instead of
3186          *  using RFC2047 encoding.  This is illegal but we will attempt to
3187          *  handle it anyway by converting from a user-specified default
3188          *  charset to UTF-8 if we see any nonprintable characters.
3189          */
3190         
3191         len = StrLength(DecodeMe);
3192         for (i=0; i<DecodeMe->BufUsed; ++i) {
3193                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3194                         illegal_non_rfc2047_encoding = 1;
3195                         break;
3196                 }
3197         }
3198
3199         if ((illegal_non_rfc2047_encoding) &&
3200             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
3201             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3202         {
3203 #ifdef HAVE_ICONV
3204                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3205                 if (ic != (iconv_t)(-1) ) {
3206                         DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3207                         StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3208                         DecodeMee = DecodedInvalidBuf;
3209                         iconv_close(ic);
3210                 }
3211 #endif
3212         }
3213
3214         /* pre evaluate the first pair */
3215         nextend = end = NULL;
3216         len = StrLength(DecodeMee);
3217         start = strstr(DecodeMee->buf, "=?");
3218         eptr = DecodeMee->buf + DecodeMee->BufUsed;
3219         if (start != NULL) 
3220                 end = FindNextEnd (DecodeMee, start + 2);
3221         else {
3222                 StrBufAppendBuf(Target, DecodeMee, 0);
3223                 FreeStrBuf(&DecodedInvalidBuf);
3224                 return;
3225         }
3226
3227
3228         if (start != DecodeMee->buf) {
3229                 long nFront;
3230                 
3231                 nFront = start - DecodeMee->buf;
3232                 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3233                 len -= nFront;
3234         }
3235         /*
3236          * Since spammers will go to all sorts of absurd lengths to get their
3237          * messages through, there are LOTS of corrupt headers out there.
3238          * So, prevent a really badly formed RFC2047 header from throwing
3239          * this function into an infinite loop.
3240          */
3241         while ((start != NULL) && 
3242                (end != NULL) && 
3243                (start < eptr) && 
3244                (end < eptr) && 
3245                (passes < 20))
3246         {
3247                 passes++;
3248                 DecodeSegment(Target, 
3249                               DecodeMee, 
3250                               start, 
3251                               end, 
3252                               ConvertBuf,
3253                               ConvertBuf2,
3254                               FoundCharset);
3255                 
3256                 next = strstr(end, "=?");
3257                 nextend = NULL;
3258                 if ((next != NULL) && 
3259                     (next < eptr))
3260                         nextend = FindNextEnd(DecodeMee, next);
3261                 if (nextend == NULL)
3262                         next = NULL;
3263
3264                 /* did we find two partitions */
3265                 if ((next != NULL) && 
3266                     ((next - end) > 2))
3267                 {
3268                         ptr = end + 2;
3269                         while ((ptr < next) && 
3270                                (isspace(*ptr) ||
3271                                 (*ptr == '\r') ||
3272                                 (*ptr == '\n') || 
3273                                 (*ptr == '\t')))
3274                                 ptr ++;
3275                         /* 
3276                          * did we find a gab just filled with blanks?
3277                          * if not, copy its stuff over.
3278                          */
3279                         if (ptr != next)
3280                         {
3281                                 StrBufAppendBufPlain(Target, 
3282                                                      end + 2, 
3283                                                      next - end - 2,
3284                                                      0);
3285                         }
3286                 }
3287                 /* our next-pair is our new first pair now. */
3288                 ptr = end + 2;
3289                 start = next;
3290                 end = nextend;
3291         }
3292         end = ptr;
3293         nextend = DecodeMee->buf + DecodeMee->BufUsed;
3294         if ((end != NULL) && (end < nextend)) {
3295                 ptr = end;
3296                 while ( (ptr < nextend) &&
3297                         (isspace(*ptr) ||
3298                          (*ptr == '\r') ||
3299                          (*ptr == '\n') || 
3300                          (*ptr == '\t')))
3301                         ptr ++;
3302                 if (ptr < nextend)
3303                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
3304         }
3305         FreeStrBuf(&DecodedInvalidBuf);
3306 }
3307
3308 /*******************************************************************************
3309  *                   Manipulating UTF-8 Strings                                *
3310  *******************************************************************************/
3311
3312 /**
3313  * @ingroup StrBuf
3314  * @brief evaluate the length of an utf8 special character sequence
3315  * @param Char the character to examine
3316  * @returns width of utf8 chars in bytes; if the sequence is broken 0 is returned; 1 if its simply ASCII.
3317  */
3318 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3319 {
3320         int n = 0;
3321         unsigned char test = (1<<7);
3322
3323         if ((*CharS & 0xC0) != 0xC0) 
3324                 return 1;
3325
3326         while ((n < 8) && 
3327                ((test & ((unsigned char)*CharS)) != 0)) 
3328         {
3329                 test = test >> 1;
3330                 n ++;
3331         }
3332         if ((n > 6) || ((CharE - CharS) < n))
3333                 n = 0;
3334         return n;
3335 }
3336
3337 /**
3338  * @ingroup StrBuf
3339  * @brief detect whether this char starts an utf-8 encoded char
3340  * @param Char character to inspect
3341  * @returns yes or no
3342  */
3343 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3344 {
3345 /** 11??.???? indicates an UTF8 Sequence. */
3346         return ((Char & 0xC0) == 0xC0);
3347 }
3348
3349 /**
3350  * @ingroup StrBuf
3351  * @brief measure the number of glyphs in an UTF8 string...
3352  * @param Buf string to measure
3353  * @returns the number of glyphs in Buf
3354  */
3355 long StrBuf_Utf8StrLen(StrBuf *Buf)
3356 {
3357         int n = 0;
3358         int m = 0;
3359         char *aptr, *eptr;
3360
3361         if ((Buf == NULL) || (Buf->BufUsed == 0))
3362                 return 0;
3363         aptr = Buf->buf;
3364         eptr = Buf->buf + Buf->BufUsed;
3365         while ((aptr < eptr) && (*aptr != '\0')) {
3366                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3367                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3368                         while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3369                         n ++;
3370                 }
3371                 else {
3372                         n++;
3373                         aptr++;
3374                 }
3375         }
3376         return n;
3377 }
3378
3379 /**
3380  * @ingroup StrBuf
3381  * @brief cuts a string after maxlen glyphs
3382  * @param Buf string to cut to maxlen glyphs
3383  * @param maxlen how long may the string become?
3384  * @returns current length of the string
3385  */
3386 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3387 {
3388         char *aptr, *eptr;
3389         int n = 0, m = 0;
3390
3391         aptr = Buf->buf;
3392         eptr = Buf->buf + Buf->BufUsed;
3393         while ((aptr < eptr) && (*aptr != '\0')) {
3394                 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3395                         m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3396                         while ((*aptr++ != '\0') && (m-- > 0));
3397                         n ++;
3398                 }
3399                 else {
3400                         n++;
3401                         aptr++;
3402                 }
3403                 if (n > maxlen) {
3404                         *aptr = '\0';
3405                         Buf->BufUsed = aptr - Buf->buf;
3406                         return Buf->BufUsed;
3407                 }                       
3408         }
3409         return Buf->BufUsed;
3410
3411 }
3412
3413
3414
3415
3416
3417 /*******************************************************************************
3418  *                               wrapping ZLib                                 *
3419  *******************************************************************************/
3420
3421 #ifdef HAVE_ZLIB
3422 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3423 #define OS_CODE 0x03    /*< unix */
3424
3425 /**
3426  * @ingroup StrBuf_DeEnCoder
3427  * @brief uses the same calling syntax as compress2(), but it
3428  *   creates a stream compatible with HTTP "Content-encoding: gzip"
3429  * @param dest compressed buffer
3430  * @param destLen length of the compresed data 
3431  * @param source source to encode
3432  * @param sourceLen length of source to encode 
3433  * @param level compression level
3434  */
3435 int ZEXPORT compress_gzip(Bytef * dest,
3436                           size_t * destLen,
3437                           const Bytef * source,
3438                           uLong sourceLen,     
3439                           int level)
3440 {
3441         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3442
3443         /* write gzip header */
3444         snprintf((char *) dest, *destLen, 
3445                  "%c%c%c%c%c%c%c%c%c%c",
3446                  gz_magic[0], gz_magic[1], Z_DEFLATED,
3447                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3448                  OS_CODE);
3449
3450         /* normal deflate */
3451         z_stream stream;
3452         int err;
3453         stream.next_in = (Bytef *) source;
3454         stream.avail_in = (uInt) sourceLen;
3455         stream.next_out = dest + 10L;   // after header
3456         stream.avail_out = (uInt) * destLen;
3457         if ((uLong) stream.avail_out != *destLen)
3458                 return Z_BUF_ERROR;
3459
3460         stream.zalloc = (alloc_func) 0;
3461         stream.zfree = (free_func) 0;
3462         stream.opaque = (voidpf) 0;
3463
3464         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3465                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3466         if (err != Z_OK)
3467                 return err;
3468
3469         err = deflate(&stream, Z_FINISH);
3470         if (err != Z_STREAM_END) {
3471                 deflateEnd(&stream);
3472                 return err == Z_OK ? Z_BUF_ERROR : err;
3473         }
3474         *destLen = stream.total_out + 10L;
3475
3476         /* write CRC and Length */
3477         uLong crc = crc32(0L, source, sourceLen);
3478         int n;
3479         for (n = 0; n < 4; ++n, ++*destLen) {
3480                 dest[*destLen] = (int) (crc & 0xff);
3481                 crc >>= 8;
3482         }
3483         uLong len = stream.total_in;
3484         for (n = 0; n < 4; ++n, ++*destLen) {
3485                 dest[*destLen] = (int) (len & 0xff);
3486                 len >>= 8;
3487         }
3488         err = deflateEnd(&stream);
3489         return err;
3490 }
3491 #endif
3492
3493
3494 /**
3495  * @ingroup StrBuf_DeEnCoder
3496  * @brief compress the buffer with gzip
3497  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3498  * @param Buf buffer whose content is to be gzipped
3499  */
3500 int CompressBuffer(StrBuf *Buf)
3501 {
3502 #ifdef HAVE_ZLIB
3503         char *compressed_data = NULL;
3504         size_t compressed_len, bufsize;
3505         int i = 0;
3506
3507         bufsize = compressed_len = Buf->BufUsed +  (Buf->BufUsed / 100) + 100;
3508         compressed_data = malloc(compressed_len);
3509         
3510         if (compressed_data == NULL)
3511                 return -1;
3512         /* Flush some space after the used payload so valgrind shuts up... */
3513         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3514                 Buf->buf[Buf->BufUsed + i++] = '\0';
3515         if (compress_gzip((Bytef *) compressed_data,
3516                           &compressed_len,
3517                           (Bytef *) Buf->buf,
3518                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3519                 if (!Buf->ConstBuf)
3520                         free(Buf->buf);
3521                 Buf->buf = compressed_data;
3522                 Buf->BufUsed = compressed_len;
3523                 Buf->BufSize = bufsize;
3524                 /* Flush some space after the used payload so valgrind shuts up... */
3525                 i = 0;
3526                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3527                         Buf->buf[Buf->BufUsed + i++] = '\0';
3528                 return 1;
3529         } else {
3530                 free(compressed_data);
3531         }
3532 #endif  /* HAVE_ZLIB */
3533         return 0;
3534 }
3535
3536 /*******************************************************************************
3537  *           File I/O; Callbacks to libevent                                   *
3538  *******************************************************************************/
3539
3540 long StrBuf_read_one_chunk_callback (int fd, short event, IOBuffer *FB)
3541 {
3542         long bufremain = 0;
3543         int n;
3544         
3545         if ((FB == NULL) || (FB->Buf == NULL))
3546                 return -1;
3547
3548         /*
3549          * check whether the read pointer is somewhere in a range 
3550          * where a cut left is inexpensive
3551          */
3552
3553         if (FB->ReadWritePointer != NULL)
3554         {
3555                 long already_read;
3556                 
3557                 already_read = FB->ReadWritePointer - FB->Buf->buf;
3558                 bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3559
3560                 if (already_read != 0) {
3561                         long unread;
3562                         
3563                         unread = FB->Buf->BufUsed - already_read;
3564
3565                         /* else nothing to compact... */
3566                         if (unread == 0) {
3567                                 FB->ReadWritePointer = FB->Buf->buf;
3568                                 bufremain = FB->Buf->BufSize;                   
3569                         }
3570                         else if ((unread < 64) || 
3571                                  (bufremain < already_read))
3572                         {
3573                                 /* 
3574                                  * if its just a tiny bit remaining, or we run out of space... 
3575                                  * lets tidy up.
3576                                  */
3577                                 FB->Buf->BufUsed = unread;
3578                                 if (unread < already_read)
3579                                         memcpy(FB->Buf->buf, FB->ReadWritePointer, unread);
3580                                 else
3581                                         memmove(FB->Buf->buf, FB->ReadWritePointer, unread);
3582                                 FB->ReadWritePointer = FB->Buf->buf;
3583                                 bufremain = FB->Buf->BufSize - unread - 1;
3584                         }
3585                         else if (bufremain < (FB->Buf->BufSize / 10))
3586                         {
3587                                 /* get a bigger buffer */ 
3588
3589                                 IncreaseBuf(FB->Buf, 0, FB->Buf->BufUsed + 1);
3590
3591                                 FB->ReadWritePointer = FB->Buf->buf + unread;
3592
3593                                 bufremain = FB->Buf->BufSize - unread - 1;
3594 /*TODO: special increase function that won't copy the already read! */
3595                         }
3596                 }
3597                 else if (bufremain < 10) {
3598                         IncreaseBuf(FB->Buf, 1, FB->Buf->BufUsed + 10);
3599                         
3600                         FB->ReadWritePointer = FB->Buf->buf;
3601                         
3602                         bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3603                 }
3604                 
3605         }
3606         else {
3607                 FB->ReadWritePointer = FB->Buf->buf;
3608                 bufremain = FB->Buf->BufSize - 1;
3609         }
3610
3611         n = read(fd, FB->Buf->buf + FB->Buf->BufUsed, bufremain);
3612
3613         if (n > 0) {
3614                 FB->Buf->BufUsed += n;
3615                 FB->Buf->buf[FB->Buf->BufUsed] = '\0';
3616         }
3617         return n;
3618 }
3619
3620 int StrBuf_write_one_chunk_callback(int fd, short event, IOBuffer *FB)
3621 {
3622         long WriteRemain;
3623         int n;
3624
3625         if ((FB == NULL) || (FB->Buf == NULL))
3626                 return -1;
3627
3628         if (FB->ReadWritePointer != NULL)
3629         {
3630                 WriteRemain = FB->Buf->BufUsed - 
3631                         (FB->ReadWritePointer - 
3632                          FB->Buf->buf);
3633         }
3634         else {
3635                 FB->ReadWritePointer = FB->Buf->buf;
3636                 WriteRemain = FB->Buf->BufUsed;
3637         }
3638
3639         n = write(fd, FB->ReadWritePointer, WriteRemain);
3640         if (n > 0) {
3641                 FB->ReadWritePointer += n;
3642
3643                 if (FB->ReadWritePointer == 
3644                     FB->Buf->buf + FB->Buf->BufUsed)
3645                 {
3646                         FlushStrBuf(FB->Buf);
3647                         FB->ReadWritePointer = NULL;
3648                         return 0;
3649                 }
3650         // check whether we've got something to write
3651         // get the maximum chunk plus the pointer we can send
3652         // write whats there
3653         // if not all was sent, remember the send pointer for the next time
3654                 return FB->ReadWritePointer - FB->Buf->buf + FB->Buf->BufUsed;
3655         }
3656         return n;
3657 }
3658
3659 /**
3660  * @ingroup StrBuf_IO
3661  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3662  * @param LineBuf your line will be copied here.
3663  * @param FB BLOB with lines of text...
3664  * @param Ptr moved arround to keep the next-line across several iterations
3665  *        has to be &NULL on start; will be &NotNULL on end of buffer
3666  * @returns size of copied buffer
3667  */
3668 eReadState StrBufChunkSipLine(StrBuf *LineBuf, IOBuffer *FB)
3669 {
3670         const char *aptr, *ptr, *eptr;
3671         char *optr, *xptr;
3672
3673         if ((FB->Buf == NULL) || (FB->ReadWritePointer == StrBufNOTNULL)) {
3674                 FB->ReadWritePointer = StrBufNOTNULL;
3675                 return eReadFail;
3676         }
3677
3678         FlushStrBuf(LineBuf);
3679         if (FB->ReadWritePointer == NULL)
3680                 ptr = aptr = FB->Buf->buf;
3681         else
3682                 ptr = aptr = FB->ReadWritePointer;
3683
3684         optr = LineBuf->buf;
3685         eptr = FB->Buf->buf + FB->Buf->BufUsed;
3686         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3687
3688         while ((ptr <= eptr) && 
3689                (*ptr != '\n') &&
3690                (*ptr != '\r') )
3691         {
3692                 *optr = *ptr;
3693                 optr++; ptr++;
3694                 if (optr == xptr) {
3695                         LineBuf->BufUsed = optr - LineBuf->buf;
3696                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
3697                         optr = LineBuf->buf + LineBuf->BufUsed;
3698                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
3699                 }
3700         }
3701
3702         if (ptr >= eptr) {
3703                 if (optr > LineBuf->buf)
3704                         optr --;
3705                 if ((*(ptr - 1) != '\r') && (*(ptr - 1) != '\n')) {
3706                         LineBuf->BufUsed = optr - LineBuf->buf;
3707                         *optr = '\0';       
3708                         return eMustReadMore;
3709                 }
3710         }
3711         LineBuf->BufUsed = optr - LineBuf->buf;
3712         *optr = '\0';       
3713         if ((ptr <= eptr) && (*ptr == '\r'))
3714                 ptr ++;
3715         if ((ptr <= eptr) && (*ptr == '\n'))
3716                 ptr ++;
3717         
3718         if (ptr < eptr) {
3719                 FB->ReadWritePointer = ptr;
3720         }
3721         else {
3722                 FlushStrBuf(FB->Buf);
3723                 FB->ReadWritePointer = NULL;
3724         }
3725
3726         return eReadSuccess;
3727 }
3728
3729 /**
3730  * @ingroup StrBuf_CHUNKED_IO
3731  * @brief check whether the chunk-buffer has more data waiting or not.
3732  * @param FB Chunk-Buffer to inspect
3733  */
3734 eReadState StrBufCheckBuffer(IOBuffer *FB)
3735 {
3736         if (FB == NULL)
3737                 return eReadFail;
3738         if (FB->Buf->BufUsed == 0)
3739                 return eReadSuccess;
3740         if (FB->ReadWritePointer == NULL)
3741                 return eBufferNotEmpty;
3742         if (FB->Buf->buf + FB->Buf->BufUsed > FB->ReadWritePointer)
3743                 return eBufferNotEmpty;
3744         return eReadSuccess;
3745 }
3746
3747 /*******************************************************************************
3748  *           File I/O; Prefer buffered read since its faster!                  *
3749  *******************************************************************************/
3750
3751 /**
3752  * @ingroup StrBuf_IO
3753  * @brief Read a line from socket
3754  * flushes and closes the FD on error
3755  * @param buf the buffer to get the input to
3756  * @param fd pointer to the filedescriptor to read
3757  * @param append Append to an existing string or replace?
3758  * @param Error strerror() on error 
3759  * @returns numbers of chars read
3760  */
3761 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3762 {
3763         int len, rlen, slen;
3764
3765         if (!append)
3766                 FlushStrBuf(buf);
3767
3768         slen = len = buf->BufUsed;
3769         while (1) {
3770                 rlen = read(*fd, &buf->buf[len], 1);
3771                 if (rlen < 1) {
3772                         *Error = strerror(errno);
3773                         
3774                         close(*fd);
3775                         *fd = -1;
3776                         
3777                         return -1;
3778                 }
3779                 if (buf->buf[len] == '\n')
3780                         break;
3781                 if (buf->buf[len] != '\r')
3782                         len ++;
3783                 if (len + 2 >= buf->BufSize) {
3784                         buf->BufUsed = len;
3785                         buf->buf[len+1] = '\0';
3786                         IncreaseBuf(buf, 1, -1);
3787                 }
3788         }
3789         buf->BufUsed = len;
3790         buf->buf[len] = '\0';
3791         return len - slen;
3792 }
3793
3794 /**
3795  * @ingroup StrBuf_BufferedIO
3796  * @brief Read a line from socket
3797  * flushes and closes the FD on error
3798  * @param Line the line to read from the fd / I/O Buffer
3799  * @param buf the buffer to get the input to
3800  * @param fd pointer to the filedescriptor to read
3801  * @param timeout number of successless selects until we bail out
3802  * @param selectresolution how long to wait on each select
3803  * @param Error strerror() on error 
3804  * @returns numbers of chars read
3805  */
3806 int StrBufTCP_read_buffered_line(StrBuf *Line, 
3807                                  StrBuf *buf, 
3808                                  int *fd, 
3809                                  int timeout, 
3810                                  int selectresolution, 
3811                                  const char **Error)
3812 {
3813         int len, rlen;
3814         int nSuccessLess = 0;
3815         fd_set rfds;
3816         char *pch = NULL;
3817         int fdflags;
3818         int IsNonBlock;
3819         struct timeval tv;
3820
3821         if (buf->BufUsed > 0) {
3822                 pch = strchr(buf->buf, '\n');
3823                 if (pch != NULL) {
3824                         rlen = 0;
3825                         len = pch - buf->buf;
3826                         if (len > 0 && (*(pch - 1) == '\r') )
3827                                 rlen ++;
3828                         StrBufSub(Line, buf, 0, len - rlen);
3829                         StrBufCutLeft(buf, len + 1);
3830                         return len - rlen;
3831                 }
3832         }
3833         
3834         if (buf->BufSize - buf->BufUsed < 10)
3835                 IncreaseBuf(buf, 1, -1);
3836
3837         fdflags = fcntl(*fd, F_GETFL);
3838         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3839
3840         while ((nSuccessLess < timeout) && (pch == NULL)) {
3841                 if (IsNonBlock){
3842                         tv.tv_sec = selectresolution;
3843                         tv.tv_usec = 0;
3844                         
3845                         FD_ZERO(&rfds);
3846                         FD_SET(*fd, &rfds);
3847                         if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3848                                 *Error = strerror(errno);
3849                                 close (*fd);
3850                                 *fd = -1;
3851                                 return -1;
3852                         }
3853                 }
3854                 if (IsNonBlock && !  FD_ISSET(*fd, &rfds)) {
3855                         nSuccessLess ++;
3856                         continue;
3857                 }
3858                 rlen = read(*fd, 
3859                             &buf->buf[buf->BufUsed], 
3860                             buf->BufSize - buf->BufUsed - 1);
3861                 if (rlen < 1) {
3862                         *Error = strerror(errno);
3863                         close(*fd);
3864                         *fd = -1;
3865                         return -1;
3866                 }
3867                 else if (rlen > 0) {
3868                         nSuccessLess = 0;
3869                         buf->BufUsed += rlen;
3870                         buf->buf[buf->BufUsed] = '\0';
3871                         if (buf->BufUsed + 10 > buf->BufSize) {
3872                                 IncreaseBuf(buf, 1, -1);
3873                         }
3874                         pch = strchr(buf->buf, '\n');
3875                         continue;
3876                 }
3877                 
3878         }
3879         if (pch != NULL) {
3880                 rlen = 0;
3881                 len = pch - buf->buf;
3882                 if (len > 0 && (*(pch - 1) == '\r') )
3883                         rlen ++;
3884                 StrBufSub(Line, buf, 0, len - rlen);
3885                 StrBufCutLeft(buf, len + 1);
3886                 return len - rlen;
3887         }
3888         return -1;
3889
3890 }
3891
3892 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3893 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3894 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3895 /**
3896  * @ingroup StrBuf_BufferedIO
3897  * @brief Read a line from socket
3898  * flushes and closes the FD on error
3899  * @param Line where to append our Line read from the fd / I/O Buffer; 
3900  * @param IOBuf the buffer to get the input to; lifetime pair to FD
3901  * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3902  * @param fd pointer to the filedescriptor to read
3903  * @param timeout number of successless selects until we bail out
3904  * @param selectresolution how long to wait on each select
3905  * @param Error strerror() on error 
3906  * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3907  */
3908 int StrBufTCP_read_buffered_line_fast(StrBuf *Line, 
3909                                       StrBuf *IOBuf, 
3910                                       const char **Pos,
3911                                       int *fd, 
3912                                       int timeout, 
3913                                       int selectresolution, 
3914                                       const char **Error)
3915 {
3916         const char *pche = NULL;
3917         const char *pos = NULL;
3918         const char *pLF;
3919         int len, rlen, retlen;
3920         int nSuccessLess = 0;
3921         fd_set rfds;
3922         const char *pch = NULL;
3923         int fdflags;
3924         int IsNonBlock;
3925         struct timeval tv;
3926         
3927         retlen = 0;
3928         if ((Line == NULL) ||
3929             (Pos == NULL) ||
3930             (IOBuf == NULL) ||
3931             (*fd == -1))
3932         {
3933                 if (Pos != NULL)
3934                         *Pos = NULL;
3935                 *Error = ErrRBLF_PreConditionFailed;
3936                 return -1;
3937         }
3938
3939         pos = *Pos;
3940         if ((IOBuf->BufUsed > 0) && 
3941             (pos != NULL) && 
3942             (pos < IOBuf->buf + IOBuf->BufUsed)) 
3943         {
3944                 char *pcht;
3945
3946                 pche = IOBuf->buf + IOBuf->BufUsed;
3947                 pch = pos;
3948                 pcht = Line->buf;
3949
3950                 while ((pch < pche) && (*pch != '\n'))
3951                 {
3952                         if (Line->BufUsed + 10 > Line->BufSize)
3953                         {
3954                                 long apos;
3955                                 apos = pcht - Line->buf;
3956                                 *pcht = '\0';
3957                                 IncreaseBuf(Line, 1, -1);
3958                                 pcht = Line->buf + apos;
3959                         }
3960                         *pcht++ = *pch++;
3961                         Line->BufUsed++;
3962                         retlen++;
3963                 }
3964
3965                 len = pch - pos;
3966                 if (len > 0 && (*(pch - 1) == '\r') )
3967                 {
3968                         retlen--;
3969                         len --;
3970                         pcht --;
3971                         Line->BufUsed --;
3972                 }
3973                 *pcht = '\0';
3974
3975                 if ((pch >= pche) || (*pch == '\0'))
3976                 {
3977                         FlushStrBuf(IOBuf);
3978                         *Pos = NULL;
3979                         pch = NULL;
3980                         pos = 0;
3981                 }
3982
3983                 if ((pch != NULL) && 
3984                     (pch <= pche)) 
3985                 {
3986                         if (pch + 1 >= pche) {
3987                                 *Pos = NULL;
3988                                 FlushStrBuf(IOBuf);
3989                         }
3990                         else
3991                                 *Pos = pch + 1;
3992                         
3993                         return retlen;
3994                 }
3995                 else 
3996                         FlushStrBuf(IOBuf);
3997         }
3998
3999         /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
4000         
4001         if (IOBuf->BufSize - IOBuf->BufUsed < 10)
4002                 IncreaseBuf(IOBuf, 1, -1);
4003
4004         fdflags = fcntl(*fd, F_GETFL);
4005         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4006
4007         pLF = NULL;
4008         while ((nSuccessLess < timeout) && 
4009                (pLF == NULL) &&
4010                (*fd != -1)) {
4011                 if (IsNonBlock)
4012                 {
4013                         tv.tv_sec = 1;
4014                         tv.tv_usec = 0;
4015                 
4016                         FD_ZERO(&rfds);
4017                         FD_SET(*fd, &rfds);
4018                         if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
4019                                 *Error = strerror(errno);
4020                                 close (*fd);
4021                                 *fd = -1;
4022                                 if (*Error == NULL)
4023                                         *Error = ErrRBLF_SelectFailed;
4024                                 return -1;
4025                         }
4026                         if (! FD_ISSET(*fd, &rfds) != 0) {
4027                                 nSuccessLess ++;
4028                                 continue;
4029                         }
4030                 }
4031                 rlen = read(*fd, 
4032                             &IOBuf->buf[IOBuf->BufUsed], 
4033                             IOBuf->BufSize - IOBuf->BufUsed - 1);
4034                 if (rlen < 1) {
4035                         *Error = strerror(errno);
4036                         close(*fd);
4037                         *fd = -1;
4038                         return -1;
4039                 }
4040                 else if (rlen > 0) {
4041                         nSuccessLess = 0;
4042                         pLF = IOBuf->buf + IOBuf->BufUsed;
4043                         IOBuf->BufUsed += rlen;
4044                         IOBuf->buf[IOBuf->BufUsed] = '\0';
4045                         
4046                         pche = IOBuf->buf + IOBuf->BufUsed;
4047                         
4048                         while ((pLF < pche) && (*pLF != '\n'))
4049                                 pLF ++;
4050                         if ((pLF >= pche) || (*pLF == '\0'))
4051                                 pLF = NULL;
4052
4053                         if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
4054                         {
4055                                 long apos = 0;
4056
4057                                 if (pLF != NULL) apos = pLF - IOBuf->buf;
4058                                 IncreaseBuf(IOBuf, 1, -1);      
4059                                 if (pLF != NULL) pLF = IOBuf->buf + apos;
4060                         }
4061
4062                         continue;
4063                 }
4064         }
4065         *Pos = NULL;
4066         if (pLF != NULL) {
4067                 pos = IOBuf->buf;
4068                 len = pLF - pos;
4069                 if (len > 0 && (*(pLF - 1) == '\r') )
4070                         len --;
4071                 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
4072                 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
4073                 {
4074                         FlushStrBuf(IOBuf);
4075                 }
4076                 else 
4077                         *Pos = pLF + 1;
4078                 return retlen + len;
4079         }
4080         *Error = ErrRBLF_NotEnoughSentFromServer;
4081         return -1;
4082
4083 }
4084
4085 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
4086 /**
4087  * @ingroup StrBuf_IO
4088  * @brief Input binary data from socket
4089  * flushes and closes the FD on error
4090  * @param Buf the buffer to get the input to
4091  * @param fd pointer to the filedescriptor to read
4092  * @param append Append to an existing string or replace?
4093  * @param nBytes the maximal number of bytes to read
4094  * @param Error strerror() on error 
4095  * @returns numbers of chars read
4096  */
4097 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
4098 {
4099         int fdflags;
4100         int rlen;
4101         int nSuccessLess;
4102         int nRead = 0;
4103         char *ptr;
4104         int IsNonBlock;
4105         struct timeval tv;
4106         fd_set rfds;
4107
4108         if ((Buf == NULL) || (*fd == -1))
4109         {
4110                 *Error = ErrRBLF_BLOBPreConditionFailed;
4111                 return -1;
4112         }
4113         if (!append)
4114                 FlushStrBuf(Buf);
4115         if (Buf->BufUsed + nBytes >= Buf->BufSize)
4116                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
4117
4118         ptr = Buf->buf + Buf->BufUsed;
4119
4120         fdflags = fcntl(*fd, F_GETFL);
4121         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4122         nSuccessLess = 0;
4123         while ((nRead < nBytes) && 
4124                (*fd != -1)) 
4125         {
4126                 if (IsNonBlock)
4127                 {
4128                         tv.tv_sec = 1;
4129                         tv.tv_usec = 0;
4130                 
4131                         FD_ZERO(&rfds);
4132                         FD_SET(*fd, &rfds);
4133                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4134                                 *Error = strerror(errno);
4135                                 close (*fd);
4136                                 *fd = -1;
4137                                 if (*Error == NULL)
4138                                         *Error = ErrRBLF_SelectFailed;
4139                                 return -1;
4140                         }
4141                         if (! FD_ISSET(*fd, &rfds) != 0) {
4142                                 nSuccessLess ++;
4143                                 continue;
4144                         }
4145                 }
4146
4147                 if ((rlen = read(*fd, 
4148                                  ptr,
4149                                  nBytes - nRead)) == -1) {
4150                         close(*fd);
4151                         *fd = -1;
4152                         *Error = strerror(errno);
4153                         return rlen;
4154                 }
4155                 nRead += rlen;
4156                 ptr += rlen;
4157                 Buf->BufUsed += rlen;
4158         }
4159         Buf->buf[Buf->BufUsed] = '\0';
4160         return nRead;
4161 }
4162
4163 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
4164 const char *ErrRBB_too_many_selects        = "StrBufReadBLOBBuffered: to many selects; aborting.";
4165 /**
4166  * @ingroup StrBuf_BufferedIO
4167  * @brief Input binary data from socket
4168  * flushes and closes the FD on error
4169  * @param Blob put binary thing here
4170  * @param IOBuf the buffer to get the input to
4171  * @param Pos offset inside of IOBuf
4172  * @param fd pointer to the filedescriptor to read
4173  * @param append Append to an existing string or replace?
4174  * @param nBytes the maximal number of bytes to read
4175  * @param check whether we should search for '000\n' terminators in case of timeouts
4176  * @param Error strerror() on error 
4177  * @returns numbers of chars read
4178  */
4179 int StrBufReadBLOBBuffered(StrBuf *Blob, 
4180                            StrBuf *IOBuf, 
4181                            const char **Pos,
4182                            int *fd, 
4183                            int append, 
4184                            long nBytes, 
4185                            int check, 
4186                            const char **Error)
4187 {
4188         const char *pos;
4189         int fdflags;
4190         int len = 0;
4191         int rlen;
4192         int nRead = 0;
4193         int nAlreadyRead = 0;
4194         int IsNonBlock;
4195         char *ptr;
4196         fd_set rfds;
4197         struct timeval tv;
4198         int nSuccessLess = 0;
4199         int MaxTries;
4200
4201         if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
4202         {
4203                 if (*Pos != NULL)
4204                         *Pos = NULL;
4205                 *Error = ErrRBB_BLOBFPreConditionFailed;
4206                 return -1;
4207         }
4208
4209         if (!append)
4210                 FlushStrBuf(Blob);
4211         if (Blob->BufUsed + nBytes >= Blob->BufSize) 
4212                 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
4213         
4214         pos = *Pos;
4215
4216         if (pos != NULL)
4217                 len = pos - IOBuf->buf;
4218         rlen = IOBuf->BufUsed - len;
4219
4220
4221         if ((IOBuf->BufUsed > 0) && 
4222             (pos != NULL) && 
4223             (pos < IOBuf->buf + IOBuf->BufUsed)) 
4224         {
4225                 if (rlen < nBytes) {
4226                         memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
4227                         Blob->BufUsed += rlen;
4228                         Blob->buf[Blob->BufUsed] = '\0';
4229                         nAlreadyRead = nRead = rlen;
4230                         *Pos = NULL; 
4231                 }
4232                 if (rlen >= nBytes) {
4233                         memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
4234                         Blob->BufUsed += nBytes;
4235                         Blob->buf[Blob->BufUsed] = '\0';
4236                         if (rlen == nBytes) {
4237                                 *Pos = NULL; 
4238                                 FlushStrBuf(IOBuf);
4239                         }
4240                         else 
4241                                 *Pos += nBytes;
4242                         return nBytes;
4243                 }
4244         }
4245
4246         FlushStrBuf(IOBuf);
4247         *Pos = NULL;
4248         if (IOBuf->BufSize < nBytes - nRead)
4249                 IncreaseBuf(IOBuf, 0, nBytes - nRead);
4250         ptr = IOBuf->buf;
4251
4252         len = Blob->BufUsed;
4253
4254         fdflags = fcntl(*fd, F_GETFL);
4255         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4256         if (IsNonBlock)
4257                 MaxTries =   1000;
4258         else
4259                 MaxTries = 100000;
4260
4261         nBytes -= nRead;
4262         nRead = 0;
4263         while ((nSuccessLess < MaxTries) && 
4264                (nRead < nBytes) &&
4265                (*fd != -1)) {
4266                 if (IsNonBlock)
4267                 {
4268                         tv.tv_sec = 1;
4269                         tv.tv_usec = 0;
4270                 
4271                         FD_ZERO(&rfds);
4272                         FD_SET(*fd, &rfds);
4273                         if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4274                                 *Error = strerror(errno);
4275                                 close (*fd);
4276                                 *fd = -1;
4277                                 if (*Error == NULL)
4278                                         *Error = ErrRBLF_SelectFailed;
4279                                 return -1;
4280                         }
4281                         if (! FD_ISSET(*fd, &rfds) != 0) {
4282                                 nSuccessLess ++;
4283                                 continue;
4284                         }
4285                 }
4286                 rlen = read(*fd, 
4287                             ptr,
4288                             IOBuf->BufSize - (ptr - IOBuf->buf));
4289                 if (rlen == -1) {
4290                         close(*fd);
4291                         *fd = -1;
4292                         *Error = strerror(errno);
4293                         return rlen;
4294                 }
4295                 else if (rlen == 0){
4296                         if ((check == NNN_TERM) && 
4297                             (nRead > 5) &&
4298                             (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) 
4299                         {
4300                                 StrBufPlain(Blob, HKEY("\n000\n"));
4301                                 StrBufCutRight(Blob, 5);
4302                                 return Blob->BufUsed;
4303                         }
4304                         else if (!IsNonBlock) 
4305                                 nSuccessLess ++;
4306                         else if (nSuccessLess > MaxTries) {
4307                                 FlushStrBuf(IOBuf);
4308                                 *Error = ErrRBB_too_many_selects;
4309                                 return -1;
4310                         }
4311                 }
4312                 else if (rlen > 0) {
4313                         nSuccessLess = 0;
4314                         nRead += rlen;
4315                         ptr += rlen;
4316                         IOBuf->BufUsed += rlen;
4317                 }
4318         }
4319         if (nSuccessLess >= MaxTries) {
4320                 FlushStrBuf(IOBuf);
4321                 *Error = ErrRBB_too_many_selects;
4322                 return -1;
4323         }
4324
4325         if (nRead > nBytes) {
4326                 *Pos = IOBuf->buf + nBytes;
4327         }
4328         Blob->buf[Blob->BufUsed] = '\0';
4329         StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
4330         if (*Pos == NULL) {
4331                 FlushStrBuf(IOBuf);
4332         }
4333         return nRead + nAlreadyRead;
4334 }
4335
4336 /**
4337  * @ingroup StrBuf_IO
4338  * @brief extract a "next line" from Buf; Ptr to persist across several iterations
4339  * @param LineBuf your line will be copied here.
4340  * @param Buf BLOB with lines of text...
4341  * @param Ptr moved arround to keep the next-line across several iterations
4342  *        has to be &NULL on start; will be &NotNULL on end of buffer
4343  * @returns size of remaining buffer
4344  */
4345 int StrBufSipLine(StrBuf *LineBuf, const StrBuf *Buf, const char **Ptr)
4346 {
4347         const char *aptr, *ptr, *eptr;
4348         char *optr, *xptr;
4349
4350         if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
4351                 *Ptr = StrBufNOTNULL;
4352                 return 0;
4353         }
4354
4355         FlushStrBuf(LineBuf);
4356         if (*Ptr==NULL)
4357                 ptr = aptr = Buf->buf;
4358         else
4359                 ptr = aptr = *Ptr;
4360
4361         optr = LineBuf->buf;
4362         eptr = Buf->buf + Buf->BufUsed;
4363         xptr = LineBuf->buf + LineBuf->BufSize - 1;
4364
4365         while ((ptr <= eptr) && 
4366                (*ptr != '\n') &&
4367                (*ptr != '\r') )
4368         {
4369                 *optr = *ptr;
4370                 optr++; ptr++;
4371                 if (optr == xptr) {
4372                         LineBuf->BufUsed = optr - LineBuf->buf;
4373                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
4374                         optr = LineBuf->buf + LineBuf->BufUsed;
4375                         xptr = LineBuf->buf + LineBuf->BufSize - 1;
4376                 }
4377         }
4378
4379         if ((ptr >= eptr) && (optr > LineBuf->buf))
4380                 optr --;
4381         LineBuf->BufUsed = optr - LineBuf->buf;
4382         *optr = '\0';       
4383         if ((ptr <= eptr) && (*ptr == '\r'))
4384                 ptr ++;
4385         if ((ptr <= eptr) && (*ptr == '\n'))
4386                 ptr ++;
4387         
4388         if (ptr < eptr) {
4389                 *Ptr = ptr;
4390         }
4391         else {
4392                 *Ptr = StrBufNOTNULL;
4393         }
4394
4395         return Buf->BufUsed - (ptr - Buf->buf);
4396 }
4397
4398
4399 /**
4400  * @ingroup StrBuf_IO
4401  * @brief removes double slashes from pathnames
4402  * @param Dir directory string to filter
4403  * @param RemoveTrailingSlash allows / disallows trailing slashes
4404  */
4405 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
4406 {
4407         char *a, *b;
4408
4409         a = b = Dir->buf;
4410
4411         while (!IsEmptyStr(a)) {
4412                 if (*a == '/') {
4413                         while (*a == '/')
4414                                 a++;
4415                         *b = '/';
4416                         b++;
4417                 }
4418                 else {
4419                         *b = *a;
4420                         b++; a++;
4421                 }
4422         }
4423         if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4424                 *b = '/';
4425                 b++;
4426         }
4427         *b = '\0';
4428         Dir->BufUsed = b - Dir->buf;
4429 }
4430
4431