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