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