f5cfbbb374866a2d6e45499e0334420db600d4c0
[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  * \brief Cut the string after n Chars
1148  * \param Buf Buffer to modify
1149  * \param AfternChars after how many chars should we trunkate the string?
1150  * \param At if non-null and points inside of our string, cut it there.
1151  */
1152 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1153 {
1154         if (At != NULL){
1155                 AfternChars = At - Buf->buf;
1156         }
1157
1158         if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1159                 return;
1160         Buf->BufUsed = AfternChars;
1161         Buf->buf[Buf->BufUsed] = '\0';
1162 }
1163
1164
1165 /*
1166  * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1167  * buf - the string to modify
1168  * len - length of the string. 
1169  */
1170 void StrBufTrim(StrBuf *Buf)
1171 {
1172         int delta = 0;
1173         if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1174
1175         while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1176                 delta ++;
1177         }
1178         if (delta > 0) StrBufCutLeft(Buf, delta);
1179
1180         if (Buf->BufUsed == 0) return;
1181         while (isspace(Buf->buf[Buf->BufUsed - 1])){
1182                 Buf->BufUsed --;
1183         }
1184         Buf->buf[Buf->BufUsed] = '\0';
1185 }
1186
1187
1188 void StrBufUpCase(StrBuf *Buf) 
1189 {
1190         char *pch, *pche;
1191
1192         pch = Buf->buf;
1193         pche = pch + Buf->BufUsed;
1194         while (pch < pche) {
1195                 *pch = toupper(*pch);
1196                 pch ++;
1197         }
1198 }
1199
1200
1201 void StrBufLowerCase(StrBuf *Buf) 
1202 {
1203         char *pch, *pche;
1204
1205         pch = Buf->buf;
1206         pche = pch + Buf->BufUsed;
1207         while (pch < pche) {
1208                 *pch = tolower(*pch);
1209                 pch ++;
1210         }
1211 }
1212
1213
1214 /**
1215  * \brief unhide special chars hidden to the HTML escaper
1216  * \param target buffer to put the unescaped string in
1217  * \param source buffer to unescape
1218  */
1219 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) 
1220 {
1221         int a, b, len;
1222         char hex[3];
1223
1224         if (target != NULL)
1225                 FlushStrBuf(target);
1226
1227         if (source == NULL ||target == NULL)
1228         {
1229                 return;
1230         }
1231
1232         len = source->BufUsed;
1233         for (a = 0; a < len; ++a) {
1234                 if (target->BufUsed >= target->BufSize)
1235                         IncreaseBuf(target, 1, -1);
1236
1237                 if (source->buf[a] == '=') {
1238                         hex[0] = source->buf[a + 1];
1239                         hex[1] = source->buf[a + 2];
1240                         hex[2] = 0;
1241                         b = 0;
1242                         sscanf(hex, "%02x", &b);
1243                         target->buf[target->BufUsed] = b;
1244                         target->buf[++target->BufUsed] = 0;
1245                         a += 2;
1246                 }
1247                 else {
1248                         target->buf[target->BufUsed] = source->buf[a];
1249                         target->buf[++target->BufUsed] = 0;
1250                 }
1251         }
1252 }
1253
1254
1255 /**
1256  * \brief hide special chars from the HTML escapers and friends
1257  * \param target buffer to put the escaped string in
1258  * \param source buffer to escape
1259  */
1260 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) 
1261 {
1262         int i, len;
1263
1264         if (target != NULL)
1265                 FlushStrBuf(target);
1266
1267         if (source == NULL ||target == NULL)
1268         {
1269                 return;
1270         }
1271
1272         len = source->BufUsed;
1273         for (i=0; i<len; ++i) {
1274                 if (target->BufUsed + 4 >= target->BufSize)
1275                         IncreaseBuf(target, 1, -1);
1276                 if ( (isalnum(source->buf[i])) || 
1277                      (source->buf[i]=='-') || 
1278                      (source->buf[i]=='_') ) {
1279                         target->buf[target->BufUsed++] = source->buf[i];
1280                 }
1281                 else {
1282                         sprintf(&target->buf[target->BufUsed], 
1283                                 "=%02X", 
1284                                 (0xFF &source->buf[i]));
1285                         target->BufUsed += 3;
1286                 }
1287         }
1288         target->buf[target->BufUsed + 1] = '\0';
1289 }
1290
1291 /*
1292  * \brief uses the same calling syntax as compress2(), but it
1293  * creates a stream compatible with HTTP "Content-encoding: gzip"
1294  */
1295 #ifdef HAVE_ZLIB
1296 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1297 #define OS_CODE 0x03    /*< unix */
1298 int ZEXPORT compress_gzip(Bytef * dest,         /*< compressed buffer*/
1299                           size_t * destLen,     /*< length of the compresed data */
1300                           const Bytef * source, /*< source to encode */
1301                           uLong sourceLen,      /*< length of source to encode */
1302                           int level)            /*< compression level */
1303 {
1304         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1305
1306         /* write gzip header */
1307         snprintf((char *) dest, *destLen, 
1308                  "%c%c%c%c%c%c%c%c%c%c",
1309                  gz_magic[0], gz_magic[1], Z_DEFLATED,
1310                  0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1311                  OS_CODE);
1312
1313         /* normal deflate */
1314         z_stream stream;
1315         int err;
1316         stream.next_in = (Bytef *) source;
1317         stream.avail_in = (uInt) sourceLen;
1318         stream.next_out = dest + 10L;   // after header
1319         stream.avail_out = (uInt) * destLen;
1320         if ((uLong) stream.avail_out != *destLen)
1321                 return Z_BUF_ERROR;
1322
1323         stream.zalloc = (alloc_func) 0;
1324         stream.zfree = (free_func) 0;
1325         stream.opaque = (voidpf) 0;
1326
1327         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1328                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1329         if (err != Z_OK)
1330                 return err;
1331
1332         err = deflate(&stream, Z_FINISH);
1333         if (err != Z_STREAM_END) {
1334                 deflateEnd(&stream);
1335                 return err == Z_OK ? Z_BUF_ERROR : err;
1336         }
1337         *destLen = stream.total_out + 10L;
1338
1339         /* write CRC and Length */
1340         uLong crc = crc32(0L, source, sourceLen);
1341         int n;
1342         for (n = 0; n < 4; ++n, ++*destLen) {
1343                 dest[*destLen] = (int) (crc & 0xff);
1344                 crc >>= 8;
1345         }
1346         uLong len = stream.total_in;
1347         for (n = 0; n < 4; ++n, ++*destLen) {
1348                 dest[*destLen] = (int) (len & 0xff);
1349                 len >>= 8;
1350         }
1351         err = deflateEnd(&stream);
1352         return err;
1353 }
1354 #endif
1355
1356
1357 /**
1358  * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1359  */
1360 int CompressBuffer(StrBuf *Buf)
1361 {
1362 #ifdef HAVE_ZLIB
1363         char *compressed_data = NULL;
1364         size_t compressed_len, bufsize;
1365         
1366         bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1367         compressed_data = malloc(compressed_len);
1368         
1369         if (compress_gzip((Bytef *) compressed_data,
1370                           &compressed_len,
1371                           (Bytef *) Buf->buf,
1372                           (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1373                 if (!Buf->ConstBuf)
1374                         free(Buf->buf);
1375                 Buf->buf = compressed_data;
1376                 Buf->BufUsed = compressed_len;
1377                 Buf->BufSize = bufsize;
1378                 return 1;
1379         } else {
1380                 free(compressed_data);
1381         }
1382 #endif  /* HAVE_ZLIB */
1383         return 0;
1384 }
1385
1386 /**
1387  * \brief decode a buffer from base 64 encoding; destroys original
1388  * \param Buf Buffor to transform
1389  */
1390 int StrBufDecodeBase64(StrBuf *Buf)
1391 {
1392         char *xferbuf;
1393         size_t siz;
1394         if (Buf == NULL) return -1;
1395
1396         xferbuf = (char*) malloc(Buf->BufSize);
1397         siz = CtdlDecodeBase64(xferbuf,
1398                                Buf->buf,
1399                                Buf->BufUsed);
1400         free(Buf->buf);
1401         Buf->buf = xferbuf;
1402         Buf->BufUsed = siz;
1403         return siz;
1404 }
1405
1406
1407 /**
1408  * \brief  remove escaped strings from i.e. the url string (like %20 for blanks)
1409  * \param Buf Buffer to translate
1410  * \param StripBlanks Reduce several blanks to one?
1411  */
1412 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1413 {
1414         int a, b;
1415         char hex[3];
1416         long len;
1417
1418         while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1419                 Buf->buf[Buf->BufUsed - 1] = '\0';
1420                 Buf->BufUsed --;
1421         }
1422
1423         a = 0; 
1424         while (a < Buf->BufUsed) {
1425                 if (Buf->buf[a] == '+')
1426                         Buf->buf[a] = ' ';
1427                 else if (Buf->buf[a] == '%') {
1428                         /* don't let % chars through, rather truncate the input. */
1429                         if (a + 2 > Buf->BufUsed) {
1430                                 Buf->buf[a] = '\0';
1431                                 Buf->BufUsed = a;
1432                         }
1433                         else {                  
1434                                 hex[0] = Buf->buf[a + 1];
1435                                 hex[1] = Buf->buf[a + 2];
1436                                 hex[2] = 0;
1437                                 b = 0;
1438                                 sscanf(hex, "%02x", &b);
1439                                 Buf->buf[a] = (char) b;
1440                                 len = Buf->BufUsed - a - 2;
1441                                 if (len > 0)
1442                                         memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1443                         
1444                                 Buf->BufUsed -=2;
1445                         }
1446                 }
1447                 a++;
1448         }
1449         return a;
1450 }
1451
1452
1453 /**
1454  * \brief       RFC2047-encode a header field if necessary.
1455  *              If no non-ASCII characters are found, the string
1456  *              will be copied verbatim without encoding.
1457  *
1458  * \param       target          Target buffer.
1459  * \param       source          Source string to be encoded.
1460  * \returns     encoded length; -1 if non success.
1461  */
1462 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1463 {
1464         const char headerStr[] = "=?UTF-8?Q?";
1465         int need_to_encode = 0;
1466         int i = 0;
1467         unsigned char ch;
1468
1469         if ((source == NULL) || 
1470             (target == NULL))
1471             return -1;
1472
1473         while ((i < source->BufUsed) &&
1474                (!IsEmptyStr (&source->buf[i])) &&
1475                (need_to_encode == 0)) {
1476                 if (((unsigned char) source->buf[i] < 32) || 
1477                     ((unsigned char) source->buf[i] > 126)) {
1478                         need_to_encode = 1;
1479                 }
1480                 i++;
1481         }
1482
1483         if (!need_to_encode) {
1484                 if (*target == NULL) {
1485                         *target = NewStrBufPlain(source->buf, source->BufUsed);
1486                 }
1487                 else {
1488                         FlushStrBuf(*target);
1489                         StrBufAppendBuf(*target, source, 0);
1490                 }
1491                 return (*target)->BufUsed;
1492         }
1493         if (*target == NULL)
1494                 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1495         else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1496                 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1497         memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1498         (*target)->BufUsed = sizeof(headerStr) - 1;
1499         for (i=0; (i < source->BufUsed); ++i) {
1500                 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1501                         IncreaseBuf(*target, 1, 0);
1502                 ch = (unsigned char) source->buf[i];
1503                 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1504                         sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1505                         (*target)->BufUsed += 3;
1506                 }
1507                 else {
1508                         (*target)->buf[(*target)->BufUsed] = ch;
1509                         (*target)->BufUsed++;
1510                 }
1511         }
1512         
1513         if ((*target)->BufUsed + 4 > (*target)->BufSize)
1514                 IncreaseBuf(*target, 1, 0);
1515
1516         (*target)->buf[(*target)->BufUsed++] = '?';
1517         (*target)->buf[(*target)->BufUsed++] = '=';
1518         (*target)->buf[(*target)->BufUsed] = '\0';
1519         return (*target)->BufUsed;;
1520 }
1521
1522 /**
1523  * \brief replaces all occurances of 'search' by 'replace'
1524  * \param buf Buffer to modify
1525  * \param search character to search
1526  * \param relpace character to replace search by
1527  */
1528 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1529 {
1530         long i;
1531         if (buf == NULL)
1532                 return;
1533         for (i=0; i<buf->BufUsed; i++)
1534                 if (buf->buf[i] == search)
1535                         buf->buf[i] = replace;
1536
1537 }
1538
1539
1540
1541 /*
1542  * Wrapper around iconv_open()
1543  * Our version adds aliases for non-standard Microsoft charsets
1544  * such as 'MS950', aliasing them to names like 'CP950'
1545  *
1546  * tocode       Target encoding
1547  * fromcode     Source encoding
1548  */
1549 void  ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1550 {
1551 #ifdef HAVE_ICONV
1552         iconv_t ic = (iconv_t)(-1) ;
1553         ic = iconv_open(tocode, fromcode);
1554         if (ic == (iconv_t)(-1) ) {
1555                 char alias_fromcode[64];
1556                 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1557                         safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1558                         alias_fromcode[0] = 'C';
1559                         alias_fromcode[1] = 'P';
1560                         ic = iconv_open(tocode, alias_fromcode);
1561                 }
1562         }
1563         *(iconv_t *)pic = ic;
1564 #endif
1565 }
1566
1567
1568
1569 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1570 {
1571         char * end;
1572         /* Find the next ?Q? */
1573         if (Buf->BufUsed - (bptr - Buf->buf)  < 6)
1574                 return NULL;
1575
1576         end = strchr(bptr + 2, '?');
1577
1578         if (end == NULL)
1579                 return NULL;
1580
1581         if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1582             ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
1583             (*(end + 2) == '?')) {
1584                 /* skip on to the end of the cluster, the next ?= */
1585                 end = strstr(end + 3, "?=");
1586         }
1587         else
1588                 /* sort of half valid encoding, try to find an end. */
1589                 end = strstr(bptr, "?=");
1590         return end;
1591 }
1592
1593
1594 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1595 {
1596 #ifdef HAVE_ICONV
1597         int BufSize;
1598         iconv_t ic;
1599         char *ibuf;                     /**< Buffer of characters to be converted */
1600         char *obuf;                     /**< Buffer for converted characters */
1601         size_t ibuflen;                 /**< Length of input buffer */
1602         size_t obuflen;                 /**< Length of output buffer */
1603
1604
1605         if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1606                 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1607
1608         ic = *(iconv_t*)pic;
1609         ibuf = ConvertBuf->buf;
1610         ibuflen = ConvertBuf->BufUsed;
1611         obuf = TmpBuf->buf;
1612         obuflen = TmpBuf->BufSize;
1613         
1614         iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1615
1616         /* little card game: wheres the red lady? */
1617         ibuf = ConvertBuf->buf;
1618         BufSize = ConvertBuf->BufSize;
1619
1620         ConvertBuf->buf = TmpBuf->buf;
1621         ConvertBuf->BufSize = TmpBuf->BufSize;
1622         ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1623         ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1624         
1625         TmpBuf->buf = ibuf;
1626         TmpBuf->BufSize = BufSize;
1627         TmpBuf->BufUsed = 0;
1628         TmpBuf->buf[0] = '\0';
1629 #endif
1630 }
1631
1632
1633
1634
1635 inline static void DecodeSegment(StrBuf *Target, 
1636                                  const StrBuf *DecodeMe, 
1637                                  char *SegmentStart, 
1638                                  char *SegmentEnd, 
1639                                  StrBuf *ConvertBuf,
1640                                  StrBuf *ConvertBuf2, 
1641                                  StrBuf *FoundCharset)
1642 {
1643         StrBuf StaticBuf;
1644         char charset[128];
1645         char encoding[16];
1646         iconv_t ic = (iconv_t)(-1);
1647
1648         /* Now we handle foreign character sets properly encoded
1649          * in RFC2047 format.
1650          */
1651         StaticBuf.buf = SegmentStart;
1652         StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1653         StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1654         extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1655         if (FoundCharset != NULL) {
1656                 FlushStrBuf(FoundCharset);
1657                 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1658         }
1659         extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1660         StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1661         
1662         *encoding = toupper(*encoding);
1663         if (*encoding == 'B') { /**< base64 */
1664                 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
1665                                                         ConvertBuf->buf, 
1666                                                         ConvertBuf->BufUsed);
1667         }
1668         else if (*encoding == 'Q') {    /**< quoted-printable */
1669                 long pos;
1670                 
1671                 pos = 0;
1672                 while (pos < ConvertBuf->BufUsed)
1673                 {
1674                         if (ConvertBuf->buf[pos] == '_') 
1675                                 ConvertBuf->buf[pos] = ' ';
1676                         pos++;
1677                 }
1678                 
1679                 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1680                         ConvertBuf2->buf, 
1681                         ConvertBuf->buf,
1682                         ConvertBuf->BufUsed);
1683         }
1684         else {
1685                 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1686         }
1687
1688         ctdl_iconv_open("UTF-8", charset, &ic);
1689         if (ic != (iconv_t)(-1) ) {             
1690                 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1691                 StrBufAppendBuf(Target, ConvertBuf2, 0);
1692                 iconv_close(ic);
1693         }
1694         else {
1695                 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1696         }
1697 }
1698 /*
1699  * Handle subjects with RFC2047 encoding such as:
1700  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1701  */
1702 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1703 {
1704         StrBuf *ConvertBuf, *ConvertBuf2;
1705         char *start, *end, *next, *nextend, *ptr = NULL;
1706         iconv_t ic = (iconv_t)(-1) ;
1707         const char *eptr;
1708         int passes = 0;
1709         int i, len, delta;
1710         int illegal_non_rfc2047_encoding = 0;
1711
1712         /* Sometimes, badly formed messages contain strings which were simply
1713          *  written out directly in some foreign character set instead of
1714          *  using RFC2047 encoding.  This is illegal but we will attempt to
1715          *  handle it anyway by converting from a user-specified default
1716          *  charset to UTF-8 if we see any nonprintable characters.
1717          */
1718         
1719         len = StrLength(DecodeMe);
1720         for (i=0; i<DecodeMe->BufUsed; ++i) {
1721                 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1722                         illegal_non_rfc2047_encoding = 1;
1723                         break;
1724                 }
1725         }
1726
1727         ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1728         if ((illegal_non_rfc2047_encoding) &&
1729             (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
1730             (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1731         {
1732                 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1733                 if (ic != (iconv_t)(-1) ) {
1734                         StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1735                         iconv_close(ic);
1736                 }
1737         }
1738
1739         /* pre evaluate the first pair */
1740         nextend = end = NULL;
1741         len = StrLength(DecodeMe);
1742         start = strstr(DecodeMe->buf, "=?");
1743         eptr = DecodeMe->buf + DecodeMe->BufUsed;
1744         if (start != NULL) 
1745                 end = FindNextEnd (DecodeMe, start);
1746         else {
1747                 StrBufAppendBuf(Target, DecodeMe, 0);
1748                 FreeStrBuf(&ConvertBuf);
1749                 return;
1750         }
1751
1752         ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1753
1754         if (start != DecodeMe->buf)
1755                 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1756         /*
1757          * Since spammers will go to all sorts of absurd lengths to get their
1758          * messages through, there are LOTS of corrupt headers out there.
1759          * So, prevent a really badly formed RFC2047 header from throwing
1760          * this function into an infinite loop.
1761          */
1762         while ((start != NULL) && 
1763                (end != NULL) && 
1764                (start < eptr) && 
1765                (end < eptr) && 
1766                (passes < 20))
1767         {
1768                 passes++;
1769                 DecodeSegment(Target, 
1770                               DecodeMe, 
1771                               start, 
1772                               end, 
1773                               ConvertBuf,
1774                               ConvertBuf2,
1775                               FoundCharset);
1776                 
1777                 next = strstr(end, "=?");
1778                 nextend = NULL;
1779                 if ((next != NULL) && 
1780                     (next < eptr))
1781                         nextend = FindNextEnd(DecodeMe, next);
1782                 if (nextend == NULL)
1783                         next = NULL;
1784
1785                 /* did we find two partitions */
1786                 if ((next != NULL) && 
1787                     ((next - end) > 2))
1788                 {
1789                         ptr = end + 2;
1790                         while ((ptr < next) && 
1791                                (isspace(*ptr) ||
1792                                 (*ptr == '\r') ||
1793                                 (*ptr == '\n') || 
1794                                 (*ptr == '\t')))
1795                                 ptr ++;
1796                         /* did we find a gab just filled with blanks? */
1797                         if (ptr == next)
1798                         {
1799                                 memmove (end + 2,
1800                                          next,
1801                                          len - (next - start));
1802                                 
1803                                 /* now terminate the gab at the end */
1804                                 delta = (next - end) - 2; ////TODO: const! 
1805                                 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1806                                 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1807
1808                                 /* move next to its new location. */
1809                                 next -= delta;
1810                                 nextend -= delta;
1811                         }
1812                 }
1813                 /* our next-pair is our new first pair now. */
1814                 ptr = end + 2;
1815                 start = next;
1816                 end = nextend;
1817         }
1818         end = ptr;
1819         nextend = DecodeMe->buf + DecodeMe->BufUsed;
1820         if ((end != NULL) && (end < nextend)) {
1821                 ptr = end;
1822                 while ( (ptr < nextend) &&
1823                         (isspace(*ptr) ||
1824                          (*ptr == '\r') ||
1825                          (*ptr == '\n') || 
1826                          (*ptr == '\t')))
1827                         ptr ++;
1828                 if (ptr < nextend)
1829                         StrBufAppendBufPlain(Target, end, nextend - end, 0);
1830         }
1831         FreeStrBuf(&ConvertBuf);
1832         FreeStrBuf(&ConvertBuf2);
1833 }
1834
1835
1836
1837 long StrBuf_Utf8StrLen(StrBuf *Buf)
1838 {
1839         return Ctdl_Utf8StrLen(Buf->buf);
1840 }
1841
1842 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1843 {
1844         char *CutAt;
1845
1846         CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1847         if (CutAt != NULL) {
1848                 Buf->BufUsed = CutAt - Buf->buf;
1849                 Buf->buf[Buf->BufUsed] = '\0';
1850         }
1851         return Buf->BufUsed;    
1852 }
1853
1854
1855
1856 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1857 {
1858         const char *aptr, *ptr, *eptr;
1859         char *optr, *xptr;
1860
1861         if (Buf == NULL)
1862                 return 0;
1863
1864         if (*Ptr==NULL)
1865                 ptr = aptr = Buf->buf;
1866         else
1867                 ptr = aptr = *Ptr;
1868
1869         optr = LineBuf->buf;
1870         eptr = Buf->buf + Buf->BufUsed;
1871         xptr = LineBuf->buf + LineBuf->BufSize;
1872
1873         while ((*ptr != '\n') &&
1874                (*ptr != '\r') &&
1875                (ptr < eptr))
1876         {
1877                 *optr = *ptr;
1878                 optr++; ptr++;
1879                 if (optr == xptr) {
1880                         LineBuf->BufUsed = optr - LineBuf->buf;
1881                         IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
1882                         optr = LineBuf->buf + LineBuf->BufUsed;
1883                         xptr = LineBuf->buf + LineBuf->BufSize;
1884                 }
1885         }
1886         LineBuf->BufUsed = optr - LineBuf->buf;
1887         *optr = '\0';       
1888         if (*ptr == '\r')
1889                 ptr ++;
1890         if (*ptr == '\n')
1891                 ptr ++;
1892
1893         *Ptr = ptr;
1894
1895         return Buf->BufUsed - (ptr - Buf->buf);
1896 }