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