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