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