]> code.citadel.org Git - citadel.git/blob - libcitadel/lib/stringbuf.c
* if we do a half baked static strbuf for extracting numbers, we have to say its...
[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 #define SHOW_ME_VAPPEND_PRINTF
11 #include <stdarg.h>
12 #include "libcitadel.h"
13
14 #ifdef HAVE_ICONV
15 #include <iconv.h>
16 #endif
17
18 #ifdef HAVE_ZLIB
19 #include <zlib.h>
20 #endif
21
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
29 /**
30  * Private Structure for the Stringbuffer
31  */
32 struct StrBuf {
33         char *buf;         /**< the pointer to the dynamic buffer */
34         long BufSize;      /**< how many spcae do we optain */
35         long BufUsed;      /**< StNumber of Chars used excluding the trailing \0 */
36         int ConstBuf;      /**< are we just a wrapper arround a static buffer and musn't we be changed? */
37 };
38
39
40 /** 
41  * \Brief Cast operator to Plain String 
42  * Note: if the buffer is altered by StrBuf operations, this pointer may become 
43  *  invalid. So don't lean on it after altering the buffer!
44  *  Since this operation is considered cheap, rather call it often than risking
45  *  your pointer to become invalid!
46  * \param Str the string we want to get the c-string representation for
47  * \returns the Pointer to the Content. Don't mess with it!
48  */
49 inline const char *ChrPtr(const StrBuf *Str)
50 {
51         if (Str == NULL)
52                 return "";
53         return Str->buf;
54 }
55
56 /**
57  * \brief since we know strlen()'s result, provide it here.
58  * \param Str the string to return the length to
59  * \returns contentlength of the buffer
60  */
61 inline int StrLength(const StrBuf *Str)
62 {
63         return (Str != NULL) ? Str->BufUsed : 0;
64 }
65
66 /**
67  * \brief local utility function to resize the buffer
68  * \param Buf the buffer whichs storage we should increase
69  * \param KeepOriginal should we copy the original buffer or just start over with a new one
70  * \param DestSize what should fit in after?
71  */
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
73 {
74         char *NewBuf;
75         size_t NewSize = Buf->BufSize * 2;
76
77         if (Buf->ConstBuf)
78                 return -1;
79                 
80         if (DestSize > 0)
81                 while (NewSize <= DestSize)
82                         NewSize *= 2;
83
84         NewBuf= (char*) malloc(NewSize);
85         if (KeepOriginal && (Buf->BufUsed > 0))
86         {
87                 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
88         }
89         else
90         {
91                 NewBuf[0] = '\0';
92                 Buf->BufUsed = 0;
93         }
94         free (Buf->buf);
95         Buf->buf = NewBuf;
96         Buf->BufSize *= 2;
97         return Buf->BufSize;
98 }
99
100 /**
101  * Allocate a new buffer with default buffer size
102  * \returns the new stringbuffer
103  */
104 StrBuf* NewStrBuf(void)
105 {
106         StrBuf *NewBuf;
107
108         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109         NewBuf->buf = (char*) malloc(SIZ);
110         NewBuf->buf[0] = '\0';
111         NewBuf->BufSize = SIZ;
112         NewBuf->BufUsed = 0;
113         NewBuf->ConstBuf = 0;
114         return NewBuf;
115 }
116
117 /** 
118  * \brief Copy Constructor; returns a duplicate of CopyMe
119  * \params CopyMe Buffer to faxmilate
120  * \returns the new stringbuffer
121  */
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
123 {
124         StrBuf *NewBuf;
125         
126         if (CopyMe == NULL)
127                 return NewStrBuf();
128
129         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130         NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131         memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132         NewBuf->BufUsed = CopyMe->BufUsed;
133         NewBuf->BufSize = CopyMe->BufSize;
134         NewBuf->ConstBuf = 0;
135         return NewBuf;
136 }
137
138 /**
139  * \brief create a new Buffer using an existing c-string
140  * this function should also be used if you want to pre-suggest
141  * the buffer size to allocate in conjunction with ptr == NULL
142  * \param ptr the c-string to copy; may be NULL to create a blank instance
143  * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144  * \returns the new stringbuffer
145  */
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
147 {
148         StrBuf *NewBuf;
149         size_t Siz = SIZ;
150         size_t CopySize;
151
152         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
153         if (nChars < 0)
154                 CopySize = strlen((ptr != NULL)?ptr:"");
155         else
156                 CopySize = nChars;
157
158         while (Siz <= CopySize)
159                 Siz *= 2;
160
161         NewBuf->buf = (char*) malloc(Siz);
162         NewBuf->BufSize = Siz;
163         if (ptr != NULL) {
164                 memcpy(NewBuf->buf, ptr, CopySize);
165                 NewBuf->buf[CopySize] = '\0';
166                 NewBuf->BufUsed = CopySize;
167         }
168         else {
169                 NewBuf->buf[0] = '\0';
170                 NewBuf->BufUsed = 0;
171         }
172         NewBuf->ConstBuf = 0;
173         return NewBuf;
174 }
175
176 /**
177  * \brief Set an existing buffer from a c-string
178  * \param ptr c-string to put into 
179  * \param nChars set to -1 if we should work 0-terminated
180  * \returns the new length of the string
181  */
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
183 {
184         size_t Siz = Buf->BufSize;
185         size_t CopySize;
186
187         if (nChars < 0)
188                 CopySize = strlen(ptr);
189         else
190                 CopySize = nChars;
191
192         while (Siz <= CopySize)
193                 Siz *= 2;
194
195         if (Siz != Buf->BufSize)
196                 IncreaseBuf(Buf, 0, Siz);
197         memcpy(Buf->buf, ptr, CopySize);
198         Buf->buf[CopySize] = '\0';
199         Buf->BufUsed = CopySize;
200         Buf->ConstBuf = 0;
201         return CopySize;
202 }
203
204
205 /**
206  * \brief use strbuf as wrapper for a string constant for easy handling
207  * \param StringConstant a string to wrap
208  * \param SizeOfConstant should be sizeof(StringConstant)-1
209  */
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
211 {
212         StrBuf *NewBuf;
213
214         NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215         NewBuf->buf = (char*) StringConstant;
216         NewBuf->BufSize = SizeOfStrConstant;
217         NewBuf->BufUsed = SizeOfStrConstant;
218         NewBuf->ConstBuf = 1;
219         return NewBuf;
220 }
221
222
223 /**
224  * \brief flush the content of a Buf; keep its struct
225  * \param buf Buffer to flush
226  */
227 int FlushStrBuf(StrBuf *buf)
228 {
229         if (buf == NULL)
230                 return -1;
231         if (buf->ConstBuf)
232                 return -1;       
233         buf->buf[0] ='\0';
234         buf->BufUsed = 0;
235         return 0;
236 }
237
238 /**
239  * \brief Release a Buffer
240  * Its a double pointer, so it can NULL your pointer
241  * so fancy SIG11 appear instead of random results
242  * \param FreeMe Pointer Pointer to the buffer to free
243  */
244 void FreeStrBuf (StrBuf **FreeMe)
245 {
246         if (*FreeMe == NULL)
247                 return;
248         if (!(*FreeMe)->ConstBuf) 
249                 free((*FreeMe)->buf);
250         free(*FreeMe);
251         *FreeMe = NULL;
252 }
253
254 /**
255  * \brief Release the buffer
256  * If you want put your StrBuf into a Hash, use this as Destructor.
257  * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
258  */
259 void HFreeStrBuf (void *VFreeMe)
260 {
261         StrBuf *FreeMe = (StrBuf*)VFreeMe;
262         if (FreeMe == NULL)
263                 return;
264         if (!FreeMe->ConstBuf) 
265                 free(FreeMe->buf);
266         free(FreeMe);
267 }
268
269 /**
270  * \brief Wrapper around atol
271  */
272 long StrTol(const StrBuf *Buf)
273 {
274         if (Buf == NULL)
275                 return 0;
276         if(Buf->BufUsed > 0)
277                 return atol(Buf->buf);
278         else
279                 return 0;
280 }
281
282 /**
283  * \brief Wrapper around atoi
284  */
285 int StrToi(const StrBuf *Buf)
286 {
287         if (Buf == NULL)
288                 return 0;
289         if (Buf->BufUsed > 0)
290                 return atoi(Buf->buf);
291         else
292                 return 0;
293 }
294 /**
295  * \brief Checks to see if the string is a pure number 
296  */
297 int StrBufIsNumber(const StrBuf *Buf) {
298   if (Buf == NULL) {
299         return 0;
300   }
301   char * pEnd;
302   strtoll(Buf->buf, &pEnd, 10);
303   if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
304     return 1;
305   }
306   return 0;
307
308 /**
309  * \brief modifies a Single char of the Buf
310  * You can point to it via char* or a zero-based integer
311  * \param ptr char* to zero; use NULL if unused
312  * \param nThChar zero based pointer into the string; use -1 if unused
313  * \param PeekValue The Character to place into the position
314  */
315 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
316 {
317         if (Buf == NULL)
318                 return -1;
319         if (ptr != NULL)
320                 nThChar = ptr - Buf->buf;
321         if ((nThChar < 0) || (nThChar > Buf->BufUsed))
322                 return -1;
323         Buf->buf[nThChar] = PeekValue;
324         return nThChar;
325 }
326
327 /**
328  * \brief Append a StringBuffer to the buffer
329  * \param Buf Buffer to modify
330  * \param AppendBuf Buffer to copy at the end of our buffer
331  * \param Offset Should we start copying from an offset?
332  */
333 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
334 {
335   if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
336                 return;
337
338         if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
339                 IncreaseBuf(Buf, 
340                             (Buf->BufUsed > 0), 
341                             AppendBuf->BufUsed + Buf->BufUsed);
342
343         memcpy(Buf->buf + Buf->BufUsed, 
344                AppendBuf->buf + Offset, 
345                AppendBuf->BufUsed - Offset);
346         Buf->BufUsed += AppendBuf->BufUsed - Offset;
347         Buf->buf[Buf->BufUsed] = '\0';
348 }
349
350
351 /**
352  * \brief Append a C-String to the buffer
353  * \param Buf Buffer to modify
354  * \param AppendBuf Buffer to copy at the end of our buffer
355  * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
356  * \param Offset Should we start copying from an offset?
357  */
358 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
359 {
360         long aps;
361         long BufSizeRequired;
362
363         if ((AppendBuf == NULL) || (Buf == NULL))
364                 return;
365
366         if (AppendSize < 0 )
367                 aps = strlen(AppendBuf + Offset);
368         else
369                 aps = AppendSize - Offset;
370
371         BufSizeRequired = Buf->BufUsed + aps + 1;
372         if (Buf->BufSize <= BufSizeRequired)
373                 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
374
375         memcpy(Buf->buf + Buf->BufUsed, 
376                AppendBuf + Offset, 
377                aps);
378         Buf->BufUsed += aps;
379         Buf->buf[Buf->BufUsed] = '\0';
380 }
381
382
383 /** 
384  * \brief Escape a string for feeding out as a URL while appending it to a Buffer
385  * \param outbuf the output buffer
386  * \param oblen the size of outbuf to sanitize
387  * \param strbuf the input buffer
388  */
389 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
390 {
391         const char *pch, *pche;
392         char *pt, *pte;
393         int b, c, len;
394         const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
395         int eclen = sizeof(ec) -1;
396
397         if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
398                 return;
399         if (PlainIn != NULL) {
400                 len = strlen(PlainIn);
401                 pch = PlainIn;
402                 pche = pch + len;
403         }
404         else {
405                 pch = In->buf;
406                 pche = pch + In->BufUsed;
407                 len = In->BufUsed;
408         }
409
410         if (len == 0) 
411                 return;
412
413         pt = OutBuf->buf + OutBuf->BufUsed;
414         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
415
416         while (pch < pche) {
417                 if (pt >= pte) {
418                         IncreaseBuf(OutBuf, 1, -1);
419                         pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
420                         pt = OutBuf->buf + OutBuf->BufUsed;
421                 }
422                 
423                 c = 0;
424                 for (b = 0; b < eclen; ++b) {
425                         if (*pch == ec[b]) {
426                                 c = 1;
427                                 b += eclen;
428                         }
429                 }
430                 if (c == 1) {
431                         sprintf(pt,"%%%02X", *pch);
432                         pt += 3;
433                         OutBuf->BufUsed += 3;
434                         pch ++;
435                 }
436                 else {
437                         *(pt++) = *(pch++);
438                         OutBuf->BufUsed++;
439                 }
440         }
441         *pt = '\0';
442 }
443
444 /*
445  * \brief Append a string, escaping characters which have meaning in HTML.  
446  *
447  * \param Target        target buffer
448  * \param Source        source buffer; set to NULL if you just have a C-String
449  * \param PlainIn       Plain-C string to append; set to NULL if unused
450  * \param nbsp          If nonzero, spaces are converted to non-breaking spaces.
451  * \param nolinebreaks  if set to 1, linebreaks are removed from the string.
452  *                      if set to 2, linebreaks are replaced by &ltbr/&gt
453  */
454 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
455 {
456         const char *aptr, *eiptr;
457         char *bptr, *eptr;
458         long len;
459
460         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
461                 return -1;
462
463         if (PlainIn != NULL) {
464                 aptr = PlainIn;
465                 len = strlen(PlainIn);
466                 eiptr = aptr + len;
467         }
468         else {
469                 aptr = Source->buf;
470                 eiptr = aptr + Source->BufUsed;
471                 len = Source->BufUsed;
472         }
473
474         if (len == 0) 
475                 return -1;
476
477         bptr = Target->buf + Target->BufUsed;
478         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
479
480         while (aptr < eiptr){
481                 if(bptr >= eptr) {
482                         IncreaseBuf(Target, 1, -1);
483                         eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in...  */
484                         bptr = Target->buf + Target->BufUsed;
485                 }
486                 if (*aptr == '<') {
487                         memcpy(bptr, "&lt;", 4);
488                         bptr += 4;
489                         Target->BufUsed += 4;
490                 }
491                 else if (*aptr == '>') {
492                         memcpy(bptr, "&gt;", 4);
493                         bptr += 4;
494                         Target->BufUsed += 4;
495                 }
496                 else if (*aptr == '&') {
497                         memcpy(bptr, "&amp;", 5);
498                         bptr += 5;
499                         Target->BufUsed += 5;
500                 }
501                 else if (*aptr == '"') {
502                         memcpy(bptr, "&quot;", 6);
503                         bptr += 6;
504                         Target->BufUsed += 6;
505                 }
506                 else if (*aptr == '\'') {
507                         memcpy(bptr, "&#39;", 5);
508                         bptr += 5;
509                         Target->BufUsed += 5;
510                 }
511                 else if (*aptr == LB) {
512                         *bptr = '<';
513                         bptr ++;
514                         Target->BufUsed ++;
515                 }
516                 else if (*aptr == RB) {
517                         *bptr = '>';
518                         bptr ++;
519                         Target->BufUsed ++;
520                 }
521                 else if (*aptr == QU) {
522                         *bptr ='"';
523                         bptr ++;
524                         Target->BufUsed ++;
525                 }
526                 else if ((*aptr == 32) && (nbsp == 1)) {
527                         memcpy(bptr, "&nbsp;", 6);
528                         bptr += 6;
529                         Target->BufUsed += 6;
530                 }
531                 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
532                         *bptr='\0';     /* nothing */
533                 }
534                 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
535                         memcpy(bptr, "&lt;br/&gt;", 11);
536                         bptr += 11;
537                         Target->BufUsed += 11;
538                 }
539
540
541                 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
542                         *bptr='\0';     /* nothing */
543                 }
544                 else{
545                         *bptr = *aptr;
546                         bptr++;
547                         Target->BufUsed ++;
548                 }
549                 aptr ++;
550         }
551         *bptr = '\0';
552         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
553                 return -1;
554         return Target->BufUsed;
555 }
556
557 /*
558  * \brief Append a string, escaping characters which have meaning in HTML.  
559  * Converts linebreaks into blanks; escapes single quotes
560  * \param Target        target buffer
561  * \param Source        source buffer; set to NULL if you just have a C-String
562  * \param PlainIn       Plain-C string to append; set to NULL if unused
563  */
564 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
565 {
566         const char *aptr, *eiptr;
567         char *tptr, *eptr;
568         long len;
569
570         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
571                 return ;
572
573         if (PlainIn != NULL) {
574                 aptr = PlainIn;
575                 len = strlen(PlainIn);
576                 eiptr = aptr + len;
577         }
578         else {
579                 aptr = Source->buf;
580                 eiptr = aptr + Source->BufUsed;
581                 len = Source->BufUsed;
582         }
583
584         if (len == 0) 
585                 return;
586
587         eptr = Target->buf + Target->BufSize - 6; 
588         tptr = Target->buf + Target->BufUsed;
589         
590         while (aptr < eiptr){
591                 if(tptr >= eptr) {
592                         IncreaseBuf(Target, 1, -1);
593                         eptr = Target->buf + Target->BufSize - 6; 
594                         tptr = Target->buf + Target->BufUsed;
595                 }
596                
597                 if (*aptr == '\n') {
598                         *tptr = ' ';
599                         Target->BufUsed++;
600                 }
601                 else if (*aptr == '\r') {
602                         *tptr = ' ';
603                         Target->BufUsed++;
604                 }
605                 else if (*aptr == '\'') {
606                         *(tptr++) = '&';
607                         *(tptr++) = '#';
608                         *(tptr++) = '3';
609                         *(tptr++) = '9';
610                         *tptr = ';';
611                         Target->BufUsed += 5;
612                 } else {
613                         *tptr = *aptr;
614                         Target->BufUsed++;
615                 }
616                 tptr++; aptr++;
617         }
618         *tptr = '\0';
619 }
620
621 /*
622  * \brief Append a string, escaping characters which have meaning in JavaScript strings .  
623  *
624  * \param Target        target buffer
625  * \param Source        source buffer; set to NULL if you just have a C-String
626  * \param PlainIn       Plain-C string to append; set to NULL if unused
627  */
628 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
629 {
630         const char *aptr, *eiptr;
631         char *bptr, *eptr;
632         long len;
633
634         if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
635                 return -1;
636
637         if (PlainIn != NULL) {
638                 aptr = PlainIn;
639                 len = strlen(PlainIn);
640                 eiptr = aptr + len;
641         }
642         else {
643                 aptr = Source->buf;
644                 eiptr = aptr + Source->BufUsed;
645                 len = Source->BufUsed;
646         }
647
648         if (len == 0) 
649                 return -1;
650
651         bptr = Target->buf + Target->BufUsed;
652         eptr = Target->buf + Target->BufSize - 2; /* our biggest unit to put in...  */
653
654         while (aptr < eiptr){
655                 if(bptr >= eptr) {
656                         IncreaseBuf(Target, 1, -1);
657                         eptr = Target->buf + Target->BufSize - 2; 
658                         bptr = Target->buf + Target->BufUsed;
659                 }
660                 else if (*aptr == '"') {
661                         memcpy(bptr, "\\\"", 2);
662                         bptr += 2;
663                         Target->BufUsed += 2;
664                 } else if (*aptr == '\\') {
665                   memcpy(bptr, "\\\\", 2);
666                   bptr += 2;
667                   Target->BufUsed += 2;
668                 }
669                 else{
670                         *bptr = *aptr;
671                         bptr++;
672                         Target->BufUsed ++;
673                 }
674                 aptr ++;
675         }
676         *bptr = '\0';
677         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
678                 return -1;
679         return Target->BufUsed;
680 }
681
682 /**
683  * \brief extracts a substring from Source into dest
684  * \param dest buffer to place substring into
685  * \param Source string to copy substring from
686  * \param Offset chars to skip from start
687  * \param nChars number of chars to copy
688  * \returns the number of chars copied; may be different from nChars due to the size of Source
689  */
690 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
691 {
692         size_t NCharsRemain;
693         if (Offset > Source->BufUsed)
694         {
695                 FlushStrBuf(dest);
696                 return 0;
697         }
698         if (Offset + nChars < Source->BufUsed)
699         {
700                 if (nChars > dest->BufSize)
701                         IncreaseBuf(dest, 0, nChars + 1);
702                 memcpy(dest->buf, Source->buf + Offset, nChars);
703                 dest->BufUsed = nChars;
704                 dest->buf[dest->BufUsed] = '\0';
705                 return nChars;
706         }
707         NCharsRemain = Source->BufUsed - Offset;
708         if (NCharsRemain > dest->BufSize)
709                 IncreaseBuf(dest, 0, NCharsRemain + 1);
710         memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
711         dest->BufUsed = NCharsRemain;
712         dest->buf[dest->BufUsed] = '\0';
713         return NCharsRemain;
714 }
715
716 /**
717  * \brief sprintf like function appending the formated string to the buffer
718  * vsnprintf version to wrap into own calls
719  * \param Buf Buffer to extend by format and params
720  * \param format printf alike format to add
721  * \param ap va_list containing the items for format
722  */
723 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
724 {
725         va_list apl;
726         size_t BufSize = Buf->BufSize;
727         size_t nWritten = Buf->BufSize + 1;
728         size_t Offset = Buf->BufUsed;
729         size_t newused = Offset + nWritten;
730         
731         while (newused >= BufSize) {
732                 va_copy(apl, ap);
733                 nWritten = vsnprintf(Buf->buf + Offset, 
734                                      Buf->BufSize - Offset, 
735                                      format, apl);
736                 va_end(apl);
737                 newused = Offset + nWritten;
738                 if (newused >= Buf->BufSize) {
739                         IncreaseBuf(Buf, 1, newused);
740                 }
741                 else {
742                         Buf->BufUsed = Offset + nWritten;
743                         BufSize = Buf->BufSize;
744                 }
745
746         }
747 }
748
749 /**
750  * \brief sprintf like function appending the formated string to the buffer
751  * \param Buf Buffer to extend by format and params
752  * \param format printf alike format to add
753  * \param ap va_list containing the items for format
754  */
755 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
756 {
757         size_t BufSize = Buf->BufSize;
758         size_t nWritten = Buf->BufSize + 1;
759         size_t Offset = Buf->BufUsed;
760         size_t newused = Offset + nWritten;
761         va_list arg_ptr;
762         
763         while (newused >= BufSize) {
764                 va_start(arg_ptr, format);
765                 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, 
766                                      Buf->BufSize - Buf->BufUsed, 
767                                      format, arg_ptr);
768                 va_end(arg_ptr);
769                 newused = Buf->BufUsed + nWritten;
770                 if (newused >= Buf->BufSize) {
771                         IncreaseBuf(Buf, 1, newused);
772                 }
773                 else {
774                         Buf->BufUsed += nWritten;
775                         BufSize = Buf->BufSize;
776                 }
777
778         }
779 }
780
781 /**
782  * \brief sprintf like function putting the formated string into the buffer
783  * \param Buf Buffer to extend by format and params
784  * \param format printf alike format to add
785  * \param ap va_list containing the items for format
786  */
787 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
788 {
789         size_t nWritten = Buf->BufSize + 1;
790         va_list arg_ptr;
791         
792         while (nWritten >= Buf->BufSize) {
793                 va_start(arg_ptr, format);
794                 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
795                 va_end(arg_ptr);
796                 Buf->BufUsed = nWritten ;
797                 if (nWritten >= Buf->BufSize)
798                         IncreaseBuf(Buf, 0, 0);
799         }
800 }
801
802
803 /**
804  * \brief Counts the numbmer of tokens in a buffer
805  * \param Source String to count tokens in
806  * \param tok    Tokenizer char to count
807  * \returns numbers of tokenizer chars found
808  */
809 inline int StrBufNum_tokens(const StrBuf *source, char tok)
810 {
811         if (source == NULL)
812                 return 0;
813         return num_tokens(source->buf, tok);
814 }
815
816 /*
817  * remove_token() - a tokenizer that kills, maims, and destroys
818  */
819 /**
820  * \brief a string tokenizer
821  * \param Source StringBuffer to read into
822  * \param parmnum n'th parameter to remove
823  * \param separator tokenizer param
824  * \returns -1 if not found, else length of token.
825  */
826 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
827 {
828         int ReducedBy;
829         char *d, *s;            /* dest, source */
830         int count = 0;
831
832         /* Find desired parameter */
833         d = Source->buf;
834         while (count < parmnum) {
835                 /* End of string, bail! */
836                 if (!*d) {
837                         d = NULL;
838                         break;
839                 }
840                 if (*d == separator) {
841                         count++;
842                 }
843                 d++;
844         }
845         if (!d) return 0;               /* Parameter not found */
846
847         /* Find next parameter */
848         s = d;
849         while (*s && *s != separator) {
850                 s++;
851         }
852         if (*s == separator)
853                 s++;
854         ReducedBy = d - s;
855
856         /* Hack and slash */
857         if (*s) {
858                 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
859                 Source->BufUsed -= (ReducedBy + 1);
860         }
861         else if (d == Source->buf) {
862                 *d = 0;
863                 Source->BufUsed = 0;
864         }
865         else {
866                 *--d = 0;
867                 Source->BufUsed -= (ReducedBy + 1);
868         }
869         /*
870         while (*s) {
871                 *d++ = *s++;
872         }
873         *d = 0;
874         */
875         return ReducedBy;
876 }
877
878
879 /**
880  * \brief a string tokenizer
881  * \param dest Destination StringBuffer
882  * \param Source StringBuffer to read into
883  * \param parmnum n'th parameter to extract
884  * \param separator tokenizer param
885  * \returns -1 if not found, else length of token.
886  */
887 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
888 {
889         const char *s, *e;              //* source * /
890         int len = 0;                    //* running total length of extracted string * /
891         int current_token = 0;          //* token currently being processed * /
892          
893         if (dest != NULL) {
894                 dest->buf[0] = '\0';
895                 dest->BufUsed = 0;
896         }
897         else
898                 return(-1);
899
900         if ((Source == NULL) || (Source->BufUsed ==0)) {
901                 return(-1);
902         }
903         s = Source->buf;
904         e = s + Source->BufUsed;
905
906         //cit_backtrace();
907         //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
908
909         while ((s<e) && !IsEmptyStr(s)) {
910                 if (*s == separator) {
911                         ++current_token;
912                 }
913                 if (len >= dest->BufSize)
914                         if (!IncreaseBuf(dest, 1, -1))
915                                 break;
916                 if ( (current_token == parmnum) && 
917                      (*s != separator)) {
918                         dest->buf[len] = *s;
919                         ++len;
920                 }
921                 else if (current_token > parmnum) {
922                         break;
923                 }
924                 ++s;
925         }
926         
927         dest->buf[len] = '\0';
928         dest->BufUsed = len;
929                 
930         if (current_token < parmnum) {
931                 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
932                 return(-1);
933         }
934         //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
935         return(len);
936 }
937
938
939 /**
940  * \brief a string tokenizer to fetch an integer
941  * \param dest Destination StringBuffer
942  * \param parmnum n'th parameter to extract
943  * \param separator tokenizer param
944  * \returns 0 if not found, else integer representation of the token
945  */
946 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
947 {
948         StrBuf tmp;
949         char buf[64];
950         
951         tmp.buf = buf;
952         buf[0] = '\0';
953         tmp.BufSize = 64;
954         tmp.BufUsed = 0;
955         tmp.ConstBuf = 1;
956         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
957                 return(atoi(buf));
958         else
959                 return 0;
960 }
961
962 /**
963  * \brief a string tokenizer to fetch a long integer
964  * \param dest Destination StringBuffer
965  * \param parmnum n'th parameter to extract
966  * \param separator tokenizer param
967  * \returns 0 if not found, else long integer representation of the token
968  */
969 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
970 {
971         StrBuf tmp;
972         char buf[64];
973         
974         tmp.buf = buf;
975         buf[0] = '\0';
976         tmp.BufSize = 64;
977         tmp.BufUsed = 0;
978         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
979                 return(atoi(buf));
980         else
981                 return 0;
982 }
983
984
985 /**
986  * \brief a string tokenizer to fetch an unsigned long
987  * \param dest Destination StringBuffer
988  * \param parmnum n'th parameter to extract
989  * \param separator tokenizer param
990  * \returns 0 if not found, else unsigned long representation of the token
991  */
992 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
993 {
994         StrBuf tmp;
995         char buf[64];
996         char *pnum;
997         
998         tmp.buf = buf;
999         buf[0] = '\0';
1000         tmp.BufSize = 64;
1001         tmp.BufUsed = 0;
1002         if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1003                 pnum = &buf[0];
1004                 if (*pnum == '-')
1005                         pnum ++;
1006                 return (unsigned long) atol(pnum);
1007         }
1008         else 
1009                 return 0;
1010 }
1011
1012
1013
1014 /**
1015  * \brief Read a line from socket
1016  * flushes and closes the FD on error
1017  * \param buf the buffer to get the input to
1018  * \param fd pointer to the filedescriptor to read
1019  * \param append Append to an existing string or replace?
1020  * \param Error strerror() on error 
1021  * \returns numbers of chars read
1022  */
1023 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1024 {
1025         int len, rlen, slen;
1026
1027         if (!append)
1028                 FlushStrBuf(buf);
1029
1030         slen = len = buf->BufUsed;
1031         while (1) {
1032                 rlen = read(*fd, &buf->buf[len], 1);
1033                 if (rlen < 1) {
1034                         *Error = strerror(errno);
1035                         
1036                         close(*fd);
1037                         *fd = -1;
1038                         
1039                         return -1;
1040                 }
1041                 if (buf->buf[len] == '\n')
1042                         break;
1043                 if (buf->buf[len] != '\r')
1044                         len ++;
1045                 if (!(len < buf->BufSize)) {
1046                         buf->BufUsed = len;
1047                         buf->buf[len+1] = '\0';
1048                         IncreaseBuf(buf, 1, -1);
1049                 }
1050         }
1051         buf->BufUsed = len;
1052         buf->buf[len] = '\0';
1053         return len - slen;
1054 }
1055
1056 /**
1057  * \brief Read a line from socket
1058  * flushes and closes the FD on error
1059  * \param buf the buffer to get the input to
1060  * \param fd pointer to the filedescriptor to read
1061  * \param append Append to an existing string or replace?
1062  * \param Error strerror() on error 
1063  * \returns numbers of chars read
1064  */
1065 int StrBufTCP_read_buffered_line(StrBuf *Line, 
1066                                  StrBuf *buf, 
1067                                  int *fd, 
1068                                  int timeout, 
1069                                  int selectresolution, 
1070                                  const char **Error)
1071 {
1072         int len, rlen;
1073         int nSuccessLess = 0;
1074         fd_set rfds;
1075         char *pch = NULL;
1076         int fdflags;
1077         struct timeval tv;
1078
1079         if (buf->BufUsed > 0) {
1080                 pch = strchr(buf->buf, '\n');
1081                 if (pch != NULL) {
1082                         rlen = 0;
1083                         len = pch - buf->buf;
1084                         if (len > 0 && (*(pch - 1) == '\r') )
1085                                 rlen ++;
1086                         StrBufSub(Line, buf, 0, len - rlen);
1087                         StrBufCutLeft(buf, len + 1);
1088                         return len - rlen;
1089                 }
1090         }
1091         
1092         if (buf->BufSize - buf->BufUsed < 10)
1093                 IncreaseBuf(buf, 1, -1);
1094
1095         fdflags = fcntl(*fd, F_GETFL);
1096         if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1097                 return -1;
1098
1099         while ((nSuccessLess < timeout) && (pch == NULL)) {
1100                 tv.tv_sec = selectresolution;
1101                 tv.tv_usec = 0;
1102                 
1103                 FD_ZERO(&rfds);
1104                 FD_SET(*fd, &rfds);
1105                 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1106                         *Error = strerror(errno);
1107                         close (*fd);
1108                         *fd = -1;
1109                         return -1;
1110                 }               
1111                 if (FD_ISSET(*fd, &rfds)) {
1112                         rlen = read(*fd, 
1113                                     &buf->buf[buf->BufUsed], 
1114                                     buf->BufSize - buf->BufUsed - 1);
1115                         if (rlen < 1) {
1116                                 *Error = strerror(errno);
1117                                 close(*fd);
1118                                 *fd = -1;
1119                                 return -1;
1120                         }
1121                         else if (rlen > 0) {
1122                                 nSuccessLess = 0;
1123                                 buf->BufUsed += rlen;
1124                                 buf->buf[buf->BufUsed] = '\0';
1125                                 if (buf->BufUsed + 10 > buf->BufSize) {
1126                                         IncreaseBuf(buf, 1, -1);
1127                                 }
1128                                 pch = strchr(buf->buf, '\n');
1129                                 continue;
1130                         }
1131                 }
1132                 nSuccessLess ++;
1133         }
1134         if (pch != NULL) {
1135                 rlen = 0;
1136                 len = pch - buf->buf;
1137                 if (len > 0 && (*(pch - 1) == '\r') )
1138                         rlen ++;
1139                 StrBufSub(Line, buf, 0, len - rlen);
1140                 StrBufCutLeft(buf, len + 1);
1141                 return len - rlen;
1142         }
1143         return -1;
1144
1145 }
1146
1147 /**
1148  * \brief Input binary data from socket
1149  * flushes and closes the FD on error
1150  * \param buf the buffer to get the input to
1151  * \param fd pointer to the filedescriptor to read
1152  * \param append Append to an existing string or replace?
1153  * \param nBytes the maximal number of bytes to read
1154  * \param Error strerror() on error 
1155  * \returns numbers of chars read
1156  */
1157 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1158 {
1159         fd_set wset;
1160         int fdflags;
1161         int len, rlen, slen;
1162         int nRead = 0;
1163         char *ptr;
1164
1165         if ((Buf == NULL) || (*fd == -1))
1166                 return -1;
1167         if (!append)
1168                 FlushStrBuf(Buf);
1169         if (Buf->BufUsed + nBytes > Buf->BufSize)
1170                 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1171
1172         ptr = Buf->buf + Buf->BufUsed;
1173
1174         slen = len = Buf->BufUsed;
1175
1176         fdflags = fcntl(*fd, F_GETFL);
1177
1178         while (nRead < nBytes) {
1179                if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1180                         FD_ZERO(&wset);
1181                         FD_SET(*fd, &wset);
1182                         if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1183                                 *Error = strerror(errno);
1184                                 return -1;
1185                         }
1186                 }
1187
1188                 if ((rlen = read(*fd, 
1189                                  ptr,
1190                                  nBytes - nRead)) == -1) {
1191                         close(*fd);
1192                         *fd = -1;
1193                         *Error = strerror(errno);
1194                         return rlen;
1195                 }
1196                 nRead += rlen;
1197                 ptr += rlen;
1198                 Buf->BufUsed += rlen;
1199         }
1200         Buf->buf[Buf->BufUsed] = '\0';
1201         return nRead;
1202 }
1203
1204 /**
1205  * \brief Cut nChars from the start of the string
1206  * \param Buf Buffer to modify
1207  * \param nChars how many chars should be skipped?
1208  */
1209 void StrBufCutLeft(StrBuf *Buf, int nChars)
1210 {
1211         if (nChars >= Buf->BufUsed) {
1212                 FlushStrBuf(Buf);
1213                 return;
1214         }
1215         memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1216         Buf->BufUsed -= nChars;
1217         Buf->buf[Buf->BufUsed] = '\0';
1218 }
1219
1220 /**
1221  * \brief Cut the trailing n Chars from the string
1222  * \param Buf Buffer to modify
1223  * \param nChars how many chars should be trunkated?
1224  */
1225 void StrBufCutRight(StrBuf *Buf, int nChars)
1226 {
1227         if (nChars >= Buf->BufUsed) {
1228                 FlushStrBuf(Buf);
1229                 return;
1230         }
1231         Buf->BufUsed -= nChars;
1232         Buf->buf[Buf->BufUsed] = '\0';
1233 }
1234
1235 /**
1236  * \brief Cut the string after n Chars
1237  * \param Buf Buffer to modify
1238  * \param AfternChars after how many chars should we trunkate the string?
1239  * \param At if non-null and points inside of our string, cut it there.
1240  */
1241 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1242 {
1243         if (At != NULL){
1244                 AfternChars = At - Buf->buf;
1245         }
1246
1247         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1248                 return;
1249         Buf->BufUsed = AfternChars;
1250         Buf->buf[Buf->BufUsed] = '\0';
1251 }
1252
1253
1254 /*
1255  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1256  * buf - the string to modify
1257  * len - length of the string. 
1258  */
1259 void StrBufTrim(StrBuf *Buf)
1260 {
1261         int delta = 0;
1262         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1263
1264         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1265                 delta ++;
1266         }
1267         if (delta > 0) StrBufCutLeft(Buf, delta);
1268
1269         if (Buf->BufUsed == 0) return;
1270         while (isspace(Buf->buf[Buf->BufUsed - 1])){
1271                 Buf->BufUsed --;
1272         }
1273         Buf->buf[Buf->BufUsed] = '\0';
1274 }
1275
1276
1277 void StrBufUpCase(StrBuf *Buf) 
1278 {
1279         char *pch, *pche;
1280
1281         pch = Buf->buf;
1282         pche = pch + Buf->BufUsed;
1283         while (pch < pche) {
1284                 *pch = toupper(*pch);
1285                 pch ++;
1286         }
1287 }
1288
1289
1290 void StrBufLowerCase(StrBuf *Buf) 
1291 {
1292         char *pch, *pche;
1293
1294         pch = Buf->buf;
1295         pche = pch + Buf->BufUsed;
1296         while (pch < pche) {
1297                 *pch = tolower(*pch);
1298                 pch ++;
1299         }
1300 }
1301
1302
1303 /**
1304  * \brief unhide special chars hidden to the HTML escaper
1305  * \param target buffer to put the unescaped string in
1306  * \param source buffer to unescape
1307  */
1308 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
1309 {
1310         int a, b, len;
1311         char hex[3];
1312
1313         if (target != NULL)
1314                 FlushStrBuf(target);
1315
1316         if (source == NULL ||target == NULL)
1317         {
1318                 return;
1319         }
1320
1321         len = source->BufUsed;
1322         for (a = 0; a < len; ++a) {
1323                 if (target->BufUsed >= target->BufSize)
1324                         IncreaseBuf(target, 1, -1);
1325
1326                 if (source->buf[a] == '=') {
1327                         hex[0] = source->buf[a + 1];
1328                         hex[1] = source->buf[a + 2];
1329                         hex[2] = 0;
1330                         b = 0;
1331                         sscanf(hex, "%02x", &b);
1332                         target->buf[target->BufUsed] = b;
1333                         target->buf[++target->BufUsed] = 0;
1334                         a += 2;
1335                 }
1336                 else {
1337                         target->buf[target->BufUsed] = source->buf[a];
1338                         target->buf[++target->BufUsed] = 0;
1339                 }
1340         }
1341 }
1342
1343
1344 /**
1345  * \brief hide special chars from the HTML escapers and friends
1346  * \param target buffer to put the escaped string in
1347  * \param source buffer to escape
1348  */
1349 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
1350 {
1351         int i, len;
1352
1353         if (target != NULL)
1354                 FlushStrBuf(target);
1355
1356         if (source == NULL ||target == NULL)
1357         {
1358                 return;
1359         }
1360
1361         len = source->BufUsed;
1362         for (i=0; i<len; ++i) {
1363                 if (target->BufUsed + 4 >= target->BufSize)
1364                         IncreaseBuf(target, 1, -1);
1365                 if ( (isalnum(source->buf[i])) || 
1366                      (source->buf[i]=='-') || 
1367                      (source->buf[i]=='_') ) {
1368                         target->buf[target->BufUsed++] = source->buf[i];
1369                 }
1370                 else {
1371                         sprintf(&target->buf[target->BufUsed], 
1372                                 "=%02X", 
1373                                 (0xFF &source->buf[i]));
1374                         target->BufUsed += 3;
1375                 }
1376         }
1377         target->buf[target->BufUsed + 1] = '\0';
1378 }
1379
1380 /*
1381  * \brief uses the same calling syntax as compress2(), but it
1382  * creates a stream compatible with HTTP "Content-encoding: gzip"
1383  */
1384 #ifdef HAVE_ZLIB
1385 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1386 #define OS_CODE 0x03    /*< unix */
1387 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
1388                           size_t * destLen,     /*< length of the compresed data */
1389                           const Bytef * source, /*< source to encode */
1390                           uLong sourceLen,      /*< length of source to encode */
1391                           int level)            /*< compression level */
1392 {
1393         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1394
1395         /* write gzip header */
1396         snprintf((char *) dest, *destLen, 
1397                  "%c%c%c%c%c%c%c%c%c%c",
1398                  gz_magic[0], gz_magic[1], Z_DEFLATED,
1399                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1400                  OS_CODE);
1401
1402         /* normal deflate */
1403         z_stream stream;
1404         int err;
1405         stream.next_in = (Bytef *) source;
1406         stream.avail_in = (uInt) sourceLen;
1407         stream.next_out = dest + 10L;   // after header
1408         stream.avail_out = (uInt) * destLen;
1409         if ((uLong) stream.avail_out != *destLen)
1410                 return Z_BUF_ERROR;
1411
1412         stream.zalloc = (alloc_func) 0;
1413         stream.zfree = (free_func) 0;
1414         stream.opaque = (voidpf) 0;
1415
1416         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1417                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1418         if (err != Z_OK)
1419                 return err;
1420
1421         err = deflate(&stream, Z_FINISH);
1422         if (err != Z_STREAM_END) {
1423                 deflateEnd(&stream);
1424                 return err == Z_OK ? Z_BUF_ERROR : err;
1425         }
1426         *destLen = stream.total_out + 10L;
1427
1428         /* write CRC and Length */
1429         uLong crc = crc32(0L, source, sourceLen);
1430         int n;
1431         for (n = 0; n < 4; ++n, ++*destLen) {
1432                 dest[*destLen] = (int) (crc & 0xff);
1433                 crc >>= 8;
1434         }
1435         uLong len = stream.total_in;
1436         for (n = 0; n < 4; ++n, ++*destLen) {
1437                 dest[*destLen] = (int) (len & 0xff);
1438                 len >>= 8;
1439         }
1440         err = deflateEnd(&stream);
1441         return err;
1442 }
1443 #endif
1444
1445
1446 /**
1447  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1448  */
1449 int CompressBuffer(StrBuf *Buf)
1450 {
1451 #ifdef HAVE_ZLIB
1452         char *compressed_data = NULL;
1453         size_t compressed_len, bufsize;
1454         int i = 0;
1455         
1456         bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1457         compressed_data = malloc(compressed_len);
1458         
1459         /* Flush some space after the used payload so valgrind shuts up... */
1460         while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1461                 Buf->buf[Buf->BufUsed + i++] = '\0';
1462         if (compress_gzip((Bytef *) compressed_data,
1463                           &compressed_len,
1464                           (Bytef *) Buf->buf,
1465                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1466                 if (!Buf->ConstBuf)
1467                         free(Buf->buf);
1468                 Buf->buf = compressed_data;
1469                 Buf->BufUsed = compressed_len;
1470                 Buf->BufSize = bufsize;
1471                 /* Flush some space after the used payload so valgrind shuts up... */
1472                 i = 0;
1473                 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1474                         Buf->buf[Buf->BufUsed + i++] = '\0';
1475                 return 1;
1476         } else {
1477                 free(compressed_data);
1478         }
1479 #endif  /* HAVE_ZLIB */
1480         return 0;
1481 }
1482
1483 /**
1484  * \brief decode a buffer from base 64 encoding; destroys original
1485  * \param Buf Buffor to transform
1486  */
1487 int StrBufDecodeBase64(StrBuf *Buf)
1488 {
1489         char *xferbuf;
1490         size_t siz;
1491         if (Buf == NULL) return -1;
1492
1493         xferbuf = (char*) malloc(Buf->BufSize);
1494         siz = CtdlDecodeBase64(xferbuf,
1495                                Buf->buf,
1496                                Buf->BufUsed);
1497         free(Buf->buf);
1498         Buf->buf = xferbuf;
1499         Buf->BufUsed = siz;
1500         return siz;
1501 }
1502
1503 /**
1504  * \brief replace all chars >0x20 && < 0x7F with Mute
1505  * \param Mute char to put over invalid chars
1506  * \param Buf Buffor to transform
1507  */
1508 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
1509 {
1510         char *pch;
1511
1512         if (Buf == NULL) return -1;
1513         pch = Buf->buf;
1514         while (pch < Buf->buf + Buf->BufUsed) {
1515                 if ((*pch < 0x20) || (*pch > 0x7F))
1516                         *pch = Mute;
1517                 pch ++;
1518         }
1519         return Buf->BufUsed;
1520 }
1521
1522
1523 /**
1524  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
1525  * \param Buf Buffer to translate
1526  * \param StripBlanks Reduce several blanks to one?
1527  */
1528 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1529 {
1530         int a, b;
1531         char hex[3];
1532         long len;
1533
1534         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1535                 Buf->buf[Buf->BufUsed - 1] = '\0';
1536                 Buf->BufUsed --;
1537         }
1538
1539         a = 0; 
1540         while (a < Buf->BufUsed) {
1541                 if (Buf->buf[a] == '+')
1542                         Buf->buf[a] = ' ';
1543                 else if (Buf->buf[a] == '%') {
1544                         /* don't let % chars through, rather truncate the input. */
1545                         if (a + 2 > Buf->BufUsed) {
1546                                 Buf->buf[a] = '\0';
1547                                 Buf->BufUsed = a;
1548                         }
1549                         else {                  
1550                                 hex[0] = Buf->buf[a + 1];
1551                                 hex[1] = Buf->buf[a + 2];
1552                                 hex[2] = 0;
1553                                 b = 0;
1554                                 sscanf(hex, "%02x", &b);
1555                                 Buf->buf[a] = (char) b;
1556                                 len = Buf->BufUsed - a - 2;
1557                                 if (len > 0)
1558                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1559                         
1560                                 Buf->BufUsed -=2;
1561                         }
1562                 }
1563                 a++;
1564         }
1565         return a;
1566 }
1567
1568
1569 /**
1570  * \brief       RFC2047-encode a header field if necessary.
1571  *              If no non-ASCII characters are found, the string
1572  *              will be copied verbatim without encoding.
1573  *
1574  * \param       target          Target buffer.
1575  * \param       source          Source string to be encoded.
1576  * \returns     encoded length; -1 if non success.
1577  */
1578 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1579 {
1580         const char headerStr[] = "=?UTF-8?Q?";
1581         int need_to_encode = 0;
1582         int i = 0;
1583         unsigned char ch;
1584
1585         if ((source == NULL) || 
1586             (target == NULL))
1587             return -1;
1588
1589         while ((i < source->BufUsed) &&
1590                (!IsEmptyStr (&source->buf[i])) &&
1591                (need_to_encode == 0)) {
1592                 if (((unsigned char) source->buf[i] < 32) || 
1593                     ((unsigned char) source->buf[i] > 126)) {
1594                         need_to_encode = 1;
1595                 }
1596                 i++;
1597         }
1598
1599         if (!need_to_encode) {
1600                 if (*target == NULL) {
1601                         *target = NewStrBufPlain(source->buf, source->BufUsed);
1602                 }
1603                 else {
1604                         FlushStrBuf(*target);
1605                         StrBufAppendBuf(*target, source, 0);
1606                 }
1607                 return (*target)->BufUsed;
1608         }
1609         if (*target == NULL)
1610                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1611         else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1612                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1613         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1614         (*target)->BufUsed = sizeof(headerStr) - 1;
1615         for (i=0; (i < source->BufUsed); ++i) {
1616                 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1617                         IncreaseBuf(*target, 1, 0);
1618                 ch = (unsigned char) source->buf[i];
1619                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1620                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1621                         (*target)->BufUsed += 3;
1622                 }
1623                 else {
1624                         (*target)->buf[(*target)->BufUsed] = ch;
1625                         (*target)->BufUsed++;
1626                 }
1627         }
1628         
1629         if ((*target)->BufUsed + 4 > (*target)->BufSize)
1630                 IncreaseBuf(*target, 1, 0);
1631
1632         (*target)->buf[(*target)->BufUsed++] = '?';
1633         (*target)->buf[(*target)->BufUsed++] = '=';
1634         (*target)->buf[(*target)->BufUsed] = '\0';
1635         return (*target)->BufUsed;;
1636 }
1637
1638 /**
1639  * \brief replaces all occurances of 'search' by 'replace'
1640  * \param buf Buffer to modify
1641  * \param search character to search
1642  * \param relpace character to replace search by
1643  */
1644 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1645 {
1646         long i;
1647         if (buf == NULL)
1648                 return;
1649         for (i=0; i<buf->BufUsed; i++)
1650                 if (buf->buf[i] == search)
1651                         buf->buf[i] = replace;
1652
1653 }
1654
1655
1656
1657 /*
1658  * Wrapper around iconv_open()
1659  * Our version adds aliases for non-standard Microsoft charsets
1660  * such as 'MS950', aliasing them to names like 'CP950'
1661  *
1662  * tocode       Target encoding
1663  * fromcode     Source encoding
1664  */
1665 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1666 {
1667 #ifdef HAVE_ICONV
1668         iconv_t ic = (iconv_t)(-1) ;
1669         ic = iconv_open(tocode, fromcode);
1670         if (ic == (iconv_t)(-1) ) {
1671                 char alias_fromcode[64];
1672                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1673                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1674                         alias_fromcode[0] = 'C';
1675                         alias_fromcode[1] = 'P';
1676                         ic = iconv_open(tocode, alias_fromcode);
1677                 }
1678         }
1679         *(iconv_t *)pic = ic;
1680 #endif
1681 }
1682
1683
1684
1685 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1686 {
1687         char * end;
1688         /* Find the next ?Q? */
1689         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
1690                 return NULL;
1691
1692         end = strchr(bptr + 2, '?');
1693
1694         if (end == NULL)
1695                 return NULL;
1696
1697         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1698             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
1699             (*(end + 2) == '?')) {
1700                 /* skip on to the end of the cluster, the next ?= */
1701                 end = strstr(end + 3, "?=");
1702         }
1703         else
1704                 /* sort of half valid encoding, try to find an end. */
1705                 end = strstr(bptr, "?=");
1706         return end;
1707 }
1708
1709
1710 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1711 {
1712 #ifdef HAVE_ICONV
1713         int BufSize;
1714         iconv_t ic;
1715         char *ibuf;                     /**< Buffer of characters to be converted */
1716         char *obuf;                     /**< Buffer for converted characters */
1717         size_t ibuflen;                 /**< Length of input buffer */
1718         size_t obuflen;                 /**< Length of output buffer */
1719
1720
1721         if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1722                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1723
1724         ic = *(iconv_t*)pic;
1725         ibuf = ConvertBuf->buf;
1726         ibuflen = ConvertBuf->BufUsed;
1727         obuf = TmpBuf->buf;
1728         obuflen = TmpBuf->BufSize;
1729         
1730         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1731
1732         /* little card game: wheres the red lady? */
1733         ibuf = ConvertBuf->buf;
1734         BufSize = ConvertBuf->BufSize;
1735
1736         ConvertBuf->buf = TmpBuf->buf;
1737         ConvertBuf->BufSize = TmpBuf->BufSize;
1738         ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1739         ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1740         
1741         TmpBuf->buf = ibuf;
1742         TmpBuf->BufSize = BufSize;
1743         TmpBuf->BufUsed = 0;
1744         TmpBuf->buf[0] = '\0';
1745 #endif
1746 }
1747
1748
1749
1750
1751 inline static void DecodeSegment(StrBuf *Target, 
1752                                  const StrBuf *DecodeMe, 
1753                                  char *SegmentStart, 
1754                                  char *SegmentEnd, 
1755                                  StrBuf *ConvertBuf,
1756                                  StrBuf *ConvertBuf2, 
1757                                  StrBuf *FoundCharset)
1758 {
1759         StrBuf StaticBuf;
1760         char charset[128];
1761         char encoding[16];
1762         iconv_t ic = (iconv_t)(-1);
1763
1764         /* Now we handle foreign character sets properly encoded
1765          * in RFC2047 format.
1766          */
1767         StaticBuf.buf = SegmentStart;
1768         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1769         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1770         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1771         if (FoundCharset != NULL) {
1772                 FlushStrBuf(FoundCharset);
1773                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1774         }
1775         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1776         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1777         
1778         *encoding = toupper(*encoding);
1779         if (*encoding == 'B') { /**< base64 */
1780                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
1781                                                         ConvertBuf->buf, 
1782                                                         ConvertBuf->BufUsed);
1783         }
1784         else if (*encoding == 'Q') {    /**< quoted-printable */
1785                 long pos;
1786                 
1787                 pos = 0;
1788                 while (pos < ConvertBuf->BufUsed)
1789                 {
1790                         if (ConvertBuf->buf[pos] == '_') 
1791                                 ConvertBuf->buf[pos] = ' ';
1792                         pos++;
1793                 }
1794                 
1795                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1796                         ConvertBuf2->buf, 
1797                         ConvertBuf->buf,
1798                         ConvertBuf->BufUsed);
1799         }
1800         else {
1801                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1802         }
1803
1804         ctdl_iconv_open("UTF-8", charset, &ic);
1805         if (ic != (iconv_t)(-1) ) {             
1806                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1807                 StrBufAppendBuf(Target, ConvertBuf2, 0);
1808                 iconv_close(ic);
1809         }
1810         else {
1811                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1812         }
1813 }
1814 /*
1815  * Handle subjects with RFC2047 encoding such as:
1816  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1817  */
1818 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1819 {
1820         StrBuf *ConvertBuf, *ConvertBuf2;
1821         char *start, *end, *next, *nextend, *ptr = NULL;
1822         iconv_t ic = (iconv_t)(-1) ;
1823         const char *eptr;
1824         int passes = 0;
1825         int i, len, delta;
1826         int illegal_non_rfc2047_encoding = 0;
1827
1828         /* Sometimes, badly formed messages contain strings which were simply
1829          *  written out directly in some foreign character set instead of
1830          *  using RFC2047 encoding.  This is illegal but we will attempt to
1831          *  handle it anyway by converting from a user-specified default
1832          *  charset to UTF-8 if we see any nonprintable characters.
1833          */
1834         
1835         len = StrLength(DecodeMe);
1836         for (i=0; i<DecodeMe->BufUsed; ++i) {
1837                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1838                         illegal_non_rfc2047_encoding = 1;
1839                         break;
1840                 }
1841         }
1842
1843         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1844         if ((illegal_non_rfc2047_encoding) &&
1845             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
1846             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1847         {
1848                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1849                 if (ic != (iconv_t)(-1) ) {
1850                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1851                         iconv_close(ic);
1852                 }
1853         }
1854
1855         /* pre evaluate the first pair */
1856         nextend = end = NULL;
1857         len = StrLength(DecodeMe);
1858         start = strstr(DecodeMe->buf, "=?");
1859         eptr = DecodeMe->buf + DecodeMe->BufUsed;
1860         if (start != NULL) 
1861                 end = FindNextEnd (DecodeMe, start);
1862         else {
1863                 StrBufAppendBuf(Target, DecodeMe, 0);
1864                 FreeStrBuf(&ConvertBuf);
1865                 return;
1866         }
1867
1868         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1869
1870         if (start != DecodeMe->buf)
1871                 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1872         /*
1873          * Since spammers will go to all sorts of absurd lengths to get their
1874          * messages through, there are LOTS of corrupt headers out there.
1875          * So, prevent a really badly formed RFC2047 header from throwing
1876          * this function into an infinite loop.
1877          */
1878         while ((start != NULL) && 
1879                (end != NULL) && 
1880                (start < eptr) && 
1881                (end < eptr) && 
1882                (passes < 20))
1883         {
1884                 passes++;
1885                 DecodeSegment(Target, 
1886                               DecodeMe, 
1887                               start, 
1888                               end, 
1889                               ConvertBuf,
1890                               ConvertBuf2,
1891                               FoundCharset);
1892                 
1893                 next = strstr(end, "=?");
1894                 nextend = NULL;
1895                 if ((next != NULL) && 
1896                     (next < eptr))
1897                         nextend = FindNextEnd(DecodeMe, next);
1898                 if (nextend == NULL)
1899                         next = NULL;
1900
1901                 /* did we find two partitions */
1902                 if ((next != NULL) && 
1903                     ((next - end) > 2))
1904                 {
1905                         ptr = end + 2;
1906                         while ((ptr < next) && 
1907                                (isspace(*ptr) ||
1908                                 (*ptr == '\r') ||
1909                                 (*ptr == '\n') || 
1910                                 (*ptr == '\t')))
1911                                 ptr ++;
1912                         /* did we find a gab just filled with blanks? */
1913                         if (ptr == next)
1914                         {
1915                                 memmove (end + 2,
1916                                          next,
1917                                          len - (next - start));
1918                                 
1919                                 /* now terminate the gab at the end */
1920                                 delta = (next - end) - 2; ////TODO: const! 
1921                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1922                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1923
1924                                 /* move next to its new location. */
1925                                 next -= delta;
1926                                 nextend -= delta;
1927                         }
1928                 }
1929                 /* our next-pair is our new first pair now. */
1930                 ptr = end + 2;
1931                 start = next;
1932                 end = nextend;
1933         }
1934         end = ptr;
1935         nextend = DecodeMe->buf + DecodeMe->BufUsed;
1936         if ((end != NULL) && (end < nextend)) {
1937                 ptr = end;
1938                 while ( (ptr < nextend) &&
1939                         (isspace(*ptr) ||
1940                          (*ptr == '\r') ||
1941                          (*ptr == '\n') || 
1942                          (*ptr == '\t')))
1943                         ptr ++;
1944                 if (ptr < nextend)
1945                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
1946         }
1947         FreeStrBuf(&ConvertBuf);
1948         FreeStrBuf(&ConvertBuf2);
1949 }
1950
1951
1952
1953 long StrBuf_Utf8StrLen(StrBuf *Buf)
1954 {
1955         return Ctdl_Utf8StrLen(Buf->buf);
1956 }
1957
1958 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1959 {
1960         char *CutAt;
1961
1962         CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1963         if (CutAt != NULL) {
1964                 Buf->BufUsed = CutAt - Buf->buf;
1965                 Buf->buf[Buf->BufUsed] = '\0';
1966         }
1967         return Buf->BufUsed;    
1968 }
1969
1970
1971
1972 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1973 {
1974         const char *aptr, *ptr, *eptr;
1975         char *optr, *xptr;
1976
1977         if (Buf == NULL)
1978                 return 0;
1979
1980         if (*Ptr==NULL)
1981                 ptr = aptr = Buf->buf;
1982         else
1983                 ptr = aptr = *Ptr;
1984
1985         optr = LineBuf->buf;
1986         eptr = Buf->buf + Buf->BufUsed;
1987         xptr = LineBuf->buf + LineBuf->BufSize;
1988
1989         while ((*ptr != '\n') &&
1990                (*ptr != '\r') &&
1991                (ptr < eptr))
1992         {
1993                 *optr = *ptr;
1994                 optr++; ptr++;
1995                 if (optr == xptr) {
1996                         LineBuf->BufUsed = optr - LineBuf->buf;
1997                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
1998                         optr = LineBuf->buf + LineBuf->BufUsed;
1999                         xptr = LineBuf->buf + LineBuf->BufSize;
2000                 }
2001         }
2002         LineBuf->BufUsed = optr - LineBuf->buf;
2003         *optr = '\0';       
2004         if (*ptr == '\r')
2005                 ptr ++;
2006         if (*ptr == '\n')
2007                 ptr ++;
2008
2009         *Ptr = ptr;
2010
2011         return Buf->BufUsed - (ptr - Buf->buf);
2012 }