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