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