8 #include <sys/select.h>
10 #define SHOW_ME_VAPPEND_PRINTF
12 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
30 * Private Structure for the Stringbuffer
33 char *buf; /**< the pointer to the dynamic buffer */
34 long BufSize; /**< how many spcae do we optain */
35 long BufUsed; /**< StNumber 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? */
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!
49 inline const char *ChrPtr(const StrBuf *Str)
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
61 inline int StrLength(const StrBuf *Str)
63 return (Str != NULL) ? Str->BufUsed : 0;
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?
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
75 size_t NewSize = Buf->BufSize * 2;
81 while (NewSize <= DestSize)
84 NewBuf= (char*) malloc(NewSize);
85 if (KeepOriginal && (Buf->BufUsed > 0))
87 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
101 * Allocate a new buffer with default buffer size
102 * \returns the new stringbuffer
104 StrBuf* NewStrBuf(void)
108 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109 NewBuf->buf = (char*) malloc(SIZ);
110 NewBuf->buf[0] = '\0';
111 NewBuf->BufSize = SIZ;
113 NewBuf->ConstBuf = 0;
118 * \brief Copy Constructor; returns a duplicate of CopyMe
119 * \params CopyMe Buffer to faxmilate
120 * \returns the new stringbuffer
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
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;
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
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
152 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
154 CopySize = strlen((ptr != NULL)?ptr:"");
158 while (Siz <= CopySize)
161 NewBuf->buf = (char*) malloc(Siz);
162 NewBuf->BufSize = Siz;
164 memcpy(NewBuf->buf, ptr, CopySize);
165 NewBuf->buf[CopySize] = '\0';
166 NewBuf->BufUsed = CopySize;
169 NewBuf->buf[0] = '\0';
172 NewBuf->ConstBuf = 0;
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
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
184 size_t Siz = Buf->BufSize;
188 CopySize = strlen(ptr);
192 while (Siz <= CopySize)
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;
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
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) StringConstant;
216 NewBuf->BufSize = SizeOfStrConstant;
217 NewBuf->BufUsed = SizeOfStrConstant;
218 NewBuf->ConstBuf = 1;
224 * \brief flush the content of a Buf; keep its struct
225 * \param buf Buffer to flush
227 int FlushStrBuf(StrBuf *buf)
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
244 void FreeStrBuf (StrBuf **FreeMe)
248 if (!(*FreeMe)->ConstBuf)
249 free((*FreeMe)->buf);
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]
259 void HFreeStrBuf (void *VFreeMe)
261 StrBuf *FreeMe = (StrBuf*)VFreeMe;
264 if (!FreeMe->ConstBuf)
270 * \brief Wrapper around atol
272 long StrTol(const StrBuf *Buf)
277 return atol(Buf->buf);
283 * \brief Wrapper around atoi
285 int StrToi(const StrBuf *Buf)
289 if (Buf->BufUsed > 0)
290 return atoi(Buf->buf);
295 * \brief Checks to see if the string is a pure number
297 int StrBufIsNumber(const StrBuf *Buf) {
302 strtoll(Buf->buf, &pEnd, 10);
303 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
309 * \brief modifies a Single char of the Buf
310 * You can point to it via char* or a zero-based integer
311 * \param ptr char* to zero; use NULL if unused
312 * \param nThChar zero based pointer into the string; use -1 if unused
313 * \param PeekValue The Character to place into the position
315 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
320 nThChar = ptr - Buf->buf;
321 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
323 Buf->buf[nThChar] = PeekValue;
328 * \brief Append a StringBuffer to the buffer
329 * \param Buf Buffer to modify
330 * \param AppendBuf Buffer to copy at the end of our buffer
331 * \param Offset Should we start copying from an offset?
333 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
335 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
338 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
341 AppendBuf->BufUsed + Buf->BufUsed);
343 memcpy(Buf->buf + Buf->BufUsed,
344 AppendBuf->buf + Offset,
345 AppendBuf->BufUsed - Offset);
346 Buf->BufUsed += AppendBuf->BufUsed - Offset;
347 Buf->buf[Buf->BufUsed] = '\0';
352 * \brief Append a C-String to the buffer
353 * \param Buf Buffer to modify
354 * \param AppendBuf Buffer to copy at the end of our buffer
355 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
356 * \param Offset Should we start copying from an offset?
358 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
361 long BufSizeRequired;
363 if ((AppendBuf == NULL) || (Buf == NULL))
367 aps = strlen(AppendBuf + Offset);
369 aps = AppendSize - Offset;
371 BufSizeRequired = Buf->BufUsed + aps + 1;
372 if (Buf->BufSize <= BufSizeRequired)
373 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
375 memcpy(Buf->buf + Buf->BufUsed,
379 Buf->buf[Buf->BufUsed] = '\0';
384 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
385 * \param outbuf the output buffer
386 * \param oblen the size of outbuf to sanitize
387 * \param strbuf the input buffer
389 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
391 const char *pch, *pche;
394 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
395 int eclen = sizeof(ec) -1;
397 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
399 if (PlainIn != NULL) {
400 len = strlen(PlainIn);
406 pche = pch + In->BufUsed;
413 pt = OutBuf->buf + OutBuf->BufUsed;
414 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
418 IncreaseBuf(OutBuf, 1, -1);
419 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
420 pt = OutBuf->buf + OutBuf->BufUsed;
424 for (b = 0; b < eclen; ++b) {
431 sprintf(pt,"%%%02X", *pch);
433 OutBuf->BufUsed += 3;
445 * \brief Append a string, escaping characters which have meaning in HTML.
447 * \param Target target buffer
448 * \param Source source buffer; set to NULL if you just have a C-String
449 * \param PlainIn Plain-C string to append; set to NULL if unused
450 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
451 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
452 * if set to 2, linebreaks are replaced by <br/>
454 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
456 const char *aptr, *eiptr;
460 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
463 if (PlainIn != NULL) {
465 len = strlen(PlainIn);
470 eiptr = aptr + Source->BufUsed;
471 len = Source->BufUsed;
477 bptr = Target->buf + Target->BufUsed;
478 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
480 while (aptr < eiptr){
482 IncreaseBuf(Target, 1, -1);
483 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
484 bptr = Target->buf + Target->BufUsed;
487 memcpy(bptr, "<", 4);
489 Target->BufUsed += 4;
491 else if (*aptr == '>') {
492 memcpy(bptr, ">", 4);
494 Target->BufUsed += 4;
496 else if (*aptr == '&') {
497 memcpy(bptr, "&", 5);
499 Target->BufUsed += 5;
501 else if (*aptr == '"') {
502 memcpy(bptr, """, 6);
504 Target->BufUsed += 6;
506 else if (*aptr == '\'') {
507 memcpy(bptr, "'", 5);
509 Target->BufUsed += 5;
511 else if (*aptr == LB) {
516 else if (*aptr == RB) {
521 else if (*aptr == QU) {
526 else if ((*aptr == 32) && (nbsp == 1)) {
527 memcpy(bptr, " ", 6);
529 Target->BufUsed += 6;
531 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
532 *bptr='\0'; /* nothing */
534 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
535 memcpy(bptr, "<br/>", 11);
537 Target->BufUsed += 11;
541 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
542 *bptr='\0'; /* nothing */
552 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
554 return Target->BufUsed;
558 * \brief Append a string, escaping characters which have meaning in HTML.
559 * Converts linebreaks into blanks; escapes single quotes
560 * \param Target target buffer
561 * \param Source source buffer; set to NULL if you just have a C-String
562 * \param PlainIn Plain-C string to append; set to NULL if unused
564 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
566 const char *aptr, *eiptr;
570 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
573 if (PlainIn != NULL) {
575 len = strlen(PlainIn);
580 eiptr = aptr + Source->BufUsed;
581 len = Source->BufUsed;
587 eptr = Target->buf + Target->BufSize - 8;
588 tptr = Target->buf + Target->BufUsed;
590 while (aptr < eiptr){
592 IncreaseBuf(Target, 1, -1);
593 eptr = Target->buf + Target->BufSize - 8;
594 tptr = Target->buf + Target->BufUsed;
601 else if (*aptr == '\r') {
605 else if (*aptr == '\'') {
611 Target->BufUsed += 5;
622 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
624 * \param Target target buffer
625 * \param Source source buffer; set to NULL if you just have a C-String
626 * \param PlainIn Plain-C string to append; set to NULL if unused
628 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
630 const char *aptr, *eiptr;
634 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
637 if (PlainIn != NULL) {
639 len = strlen(PlainIn);
644 eiptr = aptr + Source->BufUsed;
645 len = Source->BufUsed;
651 bptr = Target->buf + Target->BufUsed;
652 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
654 while (aptr < eiptr){
656 IncreaseBuf(Target, 1, -1);
657 eptr = Target->buf + Target->BufSize - 3;
658 bptr = Target->buf + Target->BufUsed;
660 else if (*aptr == '"') {
661 memcpy(bptr, "\\\"", 2);
663 Target->BufUsed += 2;
664 } else if (*aptr == '\\') {
665 memcpy(bptr, "\\\\", 2);
667 Target->BufUsed += 2;
677 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
679 return Target->BufUsed;
683 * \brief extracts a substring from Source into dest
684 * \param dest buffer to place substring into
685 * \param Source string to copy substring from
686 * \param Offset chars to skip from start
687 * \param nChars number of chars to copy
688 * \returns the number of chars copied; may be different from nChars due to the size of Source
690 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
693 if (Offset > Source->BufUsed)
698 if (Offset + nChars < Source->BufUsed)
700 if (nChars >= dest->BufSize)
701 IncreaseBuf(dest, 0, nChars + 1);
702 memcpy(dest->buf, Source->buf + Offset, nChars);
703 dest->BufUsed = nChars;
704 dest->buf[dest->BufUsed] = '\0';
707 NCharsRemain = Source->BufUsed - Offset;
708 if (NCharsRemain >= dest->BufSize)
709 IncreaseBuf(dest, 0, NCharsRemain + 1);
710 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
711 dest->BufUsed = NCharsRemain;
712 dest->buf[dest->BufUsed] = '\0';
717 * \brief sprintf like function appending the formated string to the buffer
718 * vsnprintf version to wrap into own calls
719 * \param Buf Buffer to extend by format and params
720 * \param format printf alike format to add
721 * \param ap va_list containing the items for format
723 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
726 size_t BufSize = Buf->BufSize;
727 size_t nWritten = Buf->BufSize + 1;
728 size_t Offset = Buf->BufUsed;
729 size_t newused = Offset + nWritten;
731 while (newused >= BufSize) {
733 nWritten = vsnprintf(Buf->buf + Offset,
734 Buf->BufSize - Offset,
737 newused = Offset + nWritten;
738 if (newused >= Buf->BufSize) {
739 IncreaseBuf(Buf, 1, newused);
742 Buf->BufUsed = Offset + nWritten;
743 BufSize = Buf->BufSize;
750 * \brief sprintf like function appending the formated string to the buffer
751 * \param Buf Buffer to extend by format and params
752 * \param format printf alike format to add
753 * \param ap va_list containing the items for format
755 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
757 size_t BufSize = Buf->BufSize;
758 size_t nWritten = Buf->BufSize + 1;
759 size_t Offset = Buf->BufUsed;
760 size_t newused = Offset + nWritten;
763 while (newused >= BufSize) {
764 va_start(arg_ptr, format);
765 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
766 Buf->BufSize - Buf->BufUsed,
769 newused = Buf->BufUsed + nWritten;
770 if (newused >= Buf->BufSize) {
771 IncreaseBuf(Buf, 1, newused);
774 Buf->BufUsed += nWritten;
775 BufSize = Buf->BufSize;
782 * \brief sprintf like function putting the formated string into the buffer
783 * \param Buf Buffer to extend by format and params
784 * \param format printf alike format to add
785 * \param ap va_list containing the items for format
787 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
789 size_t nWritten = Buf->BufSize + 1;
792 while (nWritten >= Buf->BufSize) {
793 va_start(arg_ptr, format);
794 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
796 Buf->BufUsed = nWritten ;
797 if (nWritten >= Buf->BufSize)
798 IncreaseBuf(Buf, 0, 0);
804 * \brief Counts the numbmer of tokens in a buffer
805 * \param Source String to count tokens in
806 * \param tok Tokenizer char to count
807 * \returns numbers of tokenizer chars found
809 int StrBufNum_tokens(const StrBuf *source, char tok)
813 return num_tokens(source->buf, tok);
817 * remove_token() - a tokenizer that kills, maims, and destroys
820 * \brief a string tokenizer
821 * \param Source StringBuffer to read into
822 * \param parmnum n'th parameter to remove
823 * \param separator tokenizer param
824 * \returns -1 if not found, else length of token.
826 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
829 char *d, *s; /* dest, source */
832 /* Find desired parameter */
834 while (count < parmnum) {
835 /* End of string, bail! */
840 if (*d == separator) {
845 if (!d) return 0; /* Parameter not found */
847 /* Find next parameter */
849 while (*s && *s != separator) {
858 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
859 Source->BufUsed -= (ReducedBy + 1);
861 else if (d == Source->buf) {
867 Source->BufUsed -= (ReducedBy + 1);
880 * \brief a string tokenizer
881 * \param dest Destination StringBuffer
882 * \param Source StringBuffer to read into
883 * \param parmnum n'th parameter to extract
884 * \param separator tokenizer param
885 * \returns -1 if not found, else length of token.
887 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
889 const char *s, *e; //* source * /
890 int len = 0; //* running total length of extracted string * /
891 int current_token = 0; //* token currently being processed * /
900 if ((Source == NULL) || (Source->BufUsed ==0)) {
904 e = s + Source->BufUsed;
907 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
909 while ((s<e) && !IsEmptyStr(s)) {
910 if (*s == separator) {
913 if (len >= dest->BufSize)
914 if (!IncreaseBuf(dest, 1, -1))
916 if ( (current_token == parmnum) &&
921 else if (current_token > parmnum) {
927 dest->buf[len] = '\0';
930 if (current_token < parmnum) {
931 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
934 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
943 * \brief a string tokenizer to fetch an integer
944 * \param dest Destination StringBuffer
945 * \param parmnum n'th parameter to extract
946 * \param separator tokenizer param
947 * \returns 0 if not found, else integer representation of the token
949 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
959 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
966 * \brief a string tokenizer to fetch a long integer
967 * \param dest Destination StringBuffer
968 * \param parmnum n'th parameter to extract
969 * \param separator tokenizer param
970 * \returns 0 if not found, else long integer representation of the token
972 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
982 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
990 * \brief a string tokenizer to fetch an unsigned long
991 * \param dest Destination StringBuffer
992 * \param parmnum n'th parameter to extract
993 * \param separator tokenizer param
994 * \returns 0 if not found, else unsigned long representation of the token
996 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1007 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1011 return (unsigned long) atol(pnum);
1020 * \brief a string tokenizer
1021 * \param dest Destination StringBuffer
1022 * \param Source StringBuffer to read into
1023 * \param pStart pointer to the end of the last token. Feed with NULL.
1024 * \param separator tokenizer param
1025 * \returns -1 if not found, else length of token.
1027 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1029 const char *s, *EndBuffer; //* source * /
1030 int len = 0; //* running total length of extracted string * /
1031 int current_token = 0; //* token currently being processed * /
1034 dest->buf[0] = '\0';
1040 if ((Source == NULL) ||
1041 (Source->BufUsed ==0)) {
1044 if (*pStart == NULL)
1045 *pStart = Source->buf;
1047 EndBuffer = Source->buf + Source->BufUsed;
1049 if ((*pStart < Source->buf) ||
1050 (*pStart > EndBuffer)) {
1058 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1060 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1061 if (*s == separator) {
1064 if (len >= dest->BufSize)
1065 if (!IncreaseBuf(dest, 1, -1)) {
1066 *pStart = EndBuffer + 1;
1069 if ( (current_token == 0) &&
1070 (*s != separator)) {
1071 dest->buf[len] = *s;
1074 else if (current_token > 0) {
1083 dest->buf[len] = '\0';
1084 dest->BufUsed = len;
1085 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1086 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1092 * \brief a string tokenizer
1093 * \param dest Destination StringBuffer
1094 * \param Source StringBuffer to read into
1095 * \param pStart pointer to the end of the last token. Feed with NULL.
1096 * \param separator tokenizer param
1097 * \returns -1 if not found, else length of token.
1099 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1101 const char *s, *EndBuffer; //* source * /
1102 int len = 0; //* running total length of extracted string * /
1103 int current_token = 0; //* token currently being processed * /
1105 if ((Source == NULL) ||
1106 (Source->BufUsed ==0)) {
1110 return Source->BufUsed;
1112 if (*pStart == NULL)
1113 *pStart = Source->buf;
1115 EndBuffer = Source->buf + Source->BufUsed;
1117 if ((*pStart < Source->buf) ||
1118 (*pStart > EndBuffer)) {
1126 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1128 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1129 if (*s == separator) {
1132 if (current_token >= nTokens) {
1144 * \brief a string tokenizer to fetch an integer
1145 * \param dest Destination StringBuffer
1146 * \param parmnum n'th parameter to extract
1147 * \param separator tokenizer param
1148 * \returns 0 if not found, else integer representation of the token
1150 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1160 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1167 * \brief a string tokenizer to fetch a long integer
1168 * \param dest Destination StringBuffer
1169 * \param parmnum n'th parameter to extract
1170 * \param separator tokenizer param
1171 * \returns 0 if not found, else long integer representation of the token
1173 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1183 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1191 * \brief a string tokenizer to fetch an unsigned long
1192 * \param dest Destination StringBuffer
1193 * \param parmnum n'th parameter to extract
1194 * \param separator tokenizer param
1195 * \returns 0 if not found, else unsigned long representation of the token
1197 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1208 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1212 return (unsigned long) atol(pnum);
1221 * \brief Read a line from socket
1222 * flushes and closes the FD on error
1223 * \param buf the buffer to get the input to
1224 * \param fd pointer to the filedescriptor to read
1225 * \param append Append to an existing string or replace?
1226 * \param Error strerror() on error
1227 * \returns numbers of chars read
1229 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1231 int len, rlen, slen;
1236 slen = len = buf->BufUsed;
1238 rlen = read(*fd, &buf->buf[len], 1);
1240 *Error = strerror(errno);
1247 if (buf->buf[len] == '\n')
1249 if (buf->buf[len] != '\r')
1251 if (len >= buf->BufSize) {
1253 buf->buf[len+1] = '\0';
1254 IncreaseBuf(buf, 1, -1);
1258 buf->buf[len] = '\0';
1263 * \brief Read a line from socket
1264 * flushes and closes the FD on error
1265 * \param buf the buffer to get the input to
1266 * \param fd pointer to the filedescriptor to read
1267 * \param append Append to an existing string or replace?
1268 * \param Error strerror() on error
1269 * \returns numbers of chars read
1271 int StrBufTCP_read_buffered_line(StrBuf *Line,
1275 int selectresolution,
1279 int nSuccessLess = 0;
1285 if (buf->BufUsed > 0) {
1286 pch = strchr(buf->buf, '\n');
1289 len = pch - buf->buf;
1290 if (len > 0 && (*(pch - 1) == '\r') )
1292 StrBufSub(Line, buf, 0, len - rlen);
1293 StrBufCutLeft(buf, len + 1);
1298 if (buf->BufSize - buf->BufUsed < 10)
1299 IncreaseBuf(buf, 1, -1);
1301 fdflags = fcntl(*fd, F_GETFL);
1302 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1305 while ((nSuccessLess < timeout) && (pch == NULL)) {
1306 tv.tv_sec = selectresolution;
1311 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1312 *Error = strerror(errno);
1317 if (FD_ISSET(*fd, &rfds)) {
1319 &buf->buf[buf->BufUsed],
1320 buf->BufSize - buf->BufUsed - 1);
1322 *Error = strerror(errno);
1327 else if (rlen > 0) {
1329 buf->BufUsed += rlen;
1330 buf->buf[buf->BufUsed] = '\0';
1331 if (buf->BufUsed + 10 > buf->BufSize) {
1332 IncreaseBuf(buf, 1, -1);
1334 pch = strchr(buf->buf, '\n');
1342 len = pch - buf->buf;
1343 if (len > 0 && (*(pch - 1) == '\r') )
1345 StrBufSub(Line, buf, 0, len - rlen);
1346 StrBufCutLeft(buf, len + 1);
1354 * \brief Read a line from socket
1355 * flushes and closes the FD on error
1356 * \param buf the buffer to get the input to
1357 * \param Pos pointer to the current read position, should be NULL initialized!
1358 * \param fd pointer to the filedescriptor to read
1359 * \param append Append to an existing string or replace?
1360 * \param Error strerror() on error
1361 * \returns numbers of chars read
1363 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1368 int selectresolution,
1372 int nSuccessLess = 0;
1374 const char *pch = NULL;
1378 if ((buf->BufUsed > 0) && (Pos != NULL)) {
1381 pch = strchr(*Pos, '\n');
1385 if (len > 0 && (*(pch - 1) == '\r') )
1387 StrBufSub(Line, buf, (*Pos - buf->buf), len - rlen);
1394 StrBufCutLeft(buf, (*Pos - buf->buf));
1398 if (buf->BufSize - buf->BufUsed < 10)
1399 IncreaseBuf(buf, 1, -1);
1401 fdflags = fcntl(*fd, F_GETFL);
1402 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1405 while ((nSuccessLess < timeout) && (pch == NULL)) {
1406 tv.tv_sec = selectresolution;
1411 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1412 *Error = strerror(errno);
1417 if (FD_ISSET(*fd, &rfds)) {
1419 &buf->buf[buf->BufUsed],
1420 buf->BufSize - buf->BufUsed - 1);
1422 *Error = strerror(errno);
1427 else if (rlen > 0) {
1429 buf->BufUsed += rlen;
1430 buf->buf[buf->BufUsed] = '\0';
1431 if (buf->BufUsed + 10 > buf->BufSize) {
1432 IncreaseBuf(buf, 1, -1);
1434 pch = strchr(buf->buf, '\n');
1444 if (len > 0 && (*(pch - 1) == '\r') )
1446 StrBufSub(Line, buf, 0, len - rlen);
1447 *Pos = *Pos + len + 1;
1455 * \brief Input binary data from socket
1456 * flushes and closes the FD on error
1457 * \param buf the buffer to get the input to
1458 * \param fd pointer to the filedescriptor to read
1459 * \param append Append to an existing string or replace?
1460 * \param nBytes the maximal number of bytes to read
1461 * \param Error strerror() on error
1462 * \returns numbers of chars read
1464 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1468 int len, rlen, slen;
1472 if ((Buf == NULL) || (*fd == -1))
1476 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1477 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1479 ptr = Buf->buf + Buf->BufUsed;
1481 slen = len = Buf->BufUsed;
1483 fdflags = fcntl(*fd, F_GETFL);
1485 while (nRead < nBytes) {
1486 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1489 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1490 *Error = strerror(errno);
1495 if ((rlen = read(*fd,
1497 nBytes - nRead)) == -1) {
1500 *Error = strerror(errno);
1505 Buf->BufUsed += rlen;
1507 Buf->buf[Buf->BufUsed] = '\0';
1512 * \brief Input binary data from socket
1513 * flushes and closes the FD on error
1514 * \param buf the buffer to get the input to
1515 * \param fd pointer to the filedescriptor to read
1516 * \param append Append to an existing string or replace?
1517 * \param nBytes the maximal number of bytes to read
1518 * \param Error strerror() on error
1519 * \returns numbers of chars read
1521 int StrBufReadBLOBBuffered(StrBuf *Buf,
1523 const char **BufPos,
1531 int len, rlen, slen;
1535 if ((Buf == NULL) || (*fd == -1) || (IOBuf == NULL))
1539 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1540 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1543 len = *BufPos - IOBuf->buf;
1544 rlen = IOBuf->BufUsed - len;
1546 if ((IOBuf->BufUsed > 0) &&
1547 ((IOBuf->BufUsed - len > 0))) {
1548 if (rlen <= nBytes) {
1549 memcpy(Buf->buf + Buf->BufUsed, *BufPos, rlen);
1550 Buf->BufUsed += rlen;
1551 Buf->buf[Buf->BufUsed] = '\0';
1552 *BufPos = NULL; FlushStrBuf(IOBuf);
1554 if (nRead == nBytes)
1558 memcpy(Buf->buf + Buf->BufUsed, *BufPos, nBytes);
1559 Buf->BufUsed += nBytes;
1560 Buf->buf[Buf->BufUsed] = '\0';
1566 ptr = Buf->buf + Buf->BufUsed;
1568 slen = len = Buf->BufUsed;
1570 fdflags = fcntl(*fd, F_GETFL);
1572 while (nRead < nBytes) {
1573 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1576 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1577 *Error = strerror(errno);
1582 if ((rlen = read(*fd,
1584 nBytes - nRead)) == -1) {
1587 *Error = strerror(errno);
1592 Buf->BufUsed += rlen;
1594 Buf->buf[Buf->BufUsed] = '\0';
1599 * \brief Cut nChars from the start of the string
1600 * \param Buf Buffer to modify
1601 * \param nChars how many chars should be skipped?
1603 void StrBufCutLeft(StrBuf *Buf, int nChars)
1605 if (nChars >= Buf->BufUsed) {
1609 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1610 Buf->BufUsed -= nChars;
1611 Buf->buf[Buf->BufUsed] = '\0';
1615 * \brief Cut the trailing n Chars from the string
1616 * \param Buf Buffer to modify
1617 * \param nChars how many chars should be trunkated?
1619 void StrBufCutRight(StrBuf *Buf, int nChars)
1621 if (nChars >= Buf->BufUsed) {
1625 Buf->BufUsed -= nChars;
1626 Buf->buf[Buf->BufUsed] = '\0';
1630 * \brief Cut the string after n Chars
1631 * \param Buf Buffer to modify
1632 * \param AfternChars after how many chars should we trunkate the string?
1633 * \param At if non-null and points inside of our string, cut it there.
1635 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1638 AfternChars = At - Buf->buf;
1641 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1643 Buf->BufUsed = AfternChars;
1644 Buf->buf[Buf->BufUsed] = '\0';
1649 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1650 * buf - the string to modify
1651 * len - length of the string.
1653 void StrBufTrim(StrBuf *Buf)
1656 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1658 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1661 if (delta > 0) StrBufCutLeft(Buf, delta);
1663 if (Buf->BufUsed == 0) return;
1664 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1667 Buf->buf[Buf->BufUsed] = '\0';
1671 void StrBufUpCase(StrBuf *Buf)
1676 pche = pch + Buf->BufUsed;
1677 while (pch < pche) {
1678 *pch = toupper(*pch);
1684 void StrBufLowerCase(StrBuf *Buf)
1689 pche = pch + Buf->BufUsed;
1690 while (pch < pche) {
1691 *pch = tolower(*pch);
1698 * \brief unhide special chars hidden to the HTML escaper
1699 * \param target buffer to put the unescaped string in
1700 * \param source buffer to unescape
1702 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1708 FlushStrBuf(target);
1710 if (source == NULL ||target == NULL)
1715 len = source->BufUsed;
1716 for (a = 0; a < len; ++a) {
1717 if (target->BufUsed >= target->BufSize)
1718 IncreaseBuf(target, 1, -1);
1720 if (source->buf[a] == '=') {
1721 hex[0] = source->buf[a + 1];
1722 hex[1] = source->buf[a + 2];
1725 sscanf(hex, "%02x", &b);
1726 target->buf[target->BufUsed] = b;
1727 target->buf[++target->BufUsed] = 0;
1731 target->buf[target->BufUsed] = source->buf[a];
1732 target->buf[++target->BufUsed] = 0;
1739 * \brief hide special chars from the HTML escapers and friends
1740 * \param target buffer to put the escaped string in
1741 * \param source buffer to escape
1743 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1748 FlushStrBuf(target);
1750 if (source == NULL ||target == NULL)
1755 len = source->BufUsed;
1756 for (i=0; i<len; ++i) {
1757 if (target->BufUsed + 4 >= target->BufSize)
1758 IncreaseBuf(target, 1, -1);
1759 if ( (isalnum(source->buf[i])) ||
1760 (source->buf[i]=='-') ||
1761 (source->buf[i]=='_') ) {
1762 target->buf[target->BufUsed++] = source->buf[i];
1765 sprintf(&target->buf[target->BufUsed],
1767 (0xFF &source->buf[i]));
1768 target->BufUsed += 3;
1771 target->buf[target->BufUsed + 1] = '\0';
1775 * \brief uses the same calling syntax as compress2(), but it
1776 * creates a stream compatible with HTTP "Content-encoding: gzip"
1779 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1780 #define OS_CODE 0x03 /*< unix */
1781 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1782 size_t * destLen, /*< length of the compresed data */
1783 const Bytef * source, /*< source to encode */
1784 uLong sourceLen, /*< length of source to encode */
1785 int level) /*< compression level */
1787 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1789 /* write gzip header */
1790 snprintf((char *) dest, *destLen,
1791 "%c%c%c%c%c%c%c%c%c%c",
1792 gz_magic[0], gz_magic[1], Z_DEFLATED,
1793 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1796 /* normal deflate */
1799 stream.next_in = (Bytef *) source;
1800 stream.avail_in = (uInt) sourceLen;
1801 stream.next_out = dest + 10L; // after header
1802 stream.avail_out = (uInt) * destLen;
1803 if ((uLong) stream.avail_out != *destLen)
1806 stream.zalloc = (alloc_func) 0;
1807 stream.zfree = (free_func) 0;
1808 stream.opaque = (voidpf) 0;
1810 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1811 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1815 err = deflate(&stream, Z_FINISH);
1816 if (err != Z_STREAM_END) {
1817 deflateEnd(&stream);
1818 return err == Z_OK ? Z_BUF_ERROR : err;
1820 *destLen = stream.total_out + 10L;
1822 /* write CRC and Length */
1823 uLong crc = crc32(0L, source, sourceLen);
1825 for (n = 0; n < 4; ++n, ++*destLen) {
1826 dest[*destLen] = (int) (crc & 0xff);
1829 uLong len = stream.total_in;
1830 for (n = 0; n < 4; ++n, ++*destLen) {
1831 dest[*destLen] = (int) (len & 0xff);
1834 err = deflateEnd(&stream);
1841 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1843 int CompressBuffer(StrBuf *Buf)
1846 char *compressed_data = NULL;
1847 size_t compressed_len, bufsize;
1850 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1851 compressed_data = malloc(compressed_len);
1853 /* Flush some space after the used payload so valgrind shuts up... */
1854 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1855 Buf->buf[Buf->BufUsed + i++] = '\0';
1856 if (compress_gzip((Bytef *) compressed_data,
1859 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1862 Buf->buf = compressed_data;
1863 Buf->BufUsed = compressed_len;
1864 Buf->BufSize = bufsize;
1865 /* Flush some space after the used payload so valgrind shuts up... */
1867 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
1868 Buf->buf[Buf->BufUsed + i++] = '\0';
1871 free(compressed_data);
1873 #endif /* HAVE_ZLIB */
1878 * \brief decode a buffer from base 64 encoding; destroys original
1879 * \param Buf Buffor to transform
1881 int StrBufDecodeBase64(StrBuf *Buf)
1885 if (Buf == NULL) return -1;
1887 xferbuf = (char*) malloc(Buf->BufSize);
1888 siz = CtdlDecodeBase64(xferbuf,
1898 * \brief replace all chars >0x20 && < 0x7F with Mute
1899 * \param Mute char to put over invalid chars
1900 * \param Buf Buffor to transform
1902 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
1906 if (Buf == NULL) return -1;
1907 pch = (unsigned char *)Buf->buf;
1908 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
1909 if ((*pch < 0x20) || (*pch > 0x7F))
1913 return Buf->BufUsed;
1918 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1919 * \param Buf Buffer to translate
1920 * \param StripBlanks Reduce several blanks to one?
1922 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1928 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1929 Buf->buf[Buf->BufUsed - 1] = '\0';
1934 while (a < Buf->BufUsed) {
1935 if (Buf->buf[a] == '+')
1937 else if (Buf->buf[a] == '%') {
1938 /* don't let % chars through, rather truncate the input. */
1939 if (a + 2 > Buf->BufUsed) {
1944 hex[0] = Buf->buf[a + 1];
1945 hex[1] = Buf->buf[a + 2];
1948 sscanf(hex, "%02x", &b);
1949 Buf->buf[a] = (char) b;
1950 len = Buf->BufUsed - a - 2;
1952 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1964 * \brief RFC2047-encode a header field if necessary.
1965 * If no non-ASCII characters are found, the string
1966 * will be copied verbatim without encoding.
1968 * \param target Target buffer.
1969 * \param source Source string to be encoded.
1970 * \returns encoded length; -1 if non success.
1972 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1974 const char headerStr[] = "=?UTF-8?Q?";
1975 int need_to_encode = 0;
1979 if ((source == NULL) ||
1983 while ((i < source->BufUsed) &&
1984 (!IsEmptyStr (&source->buf[i])) &&
1985 (need_to_encode == 0)) {
1986 if (((unsigned char) source->buf[i] < 32) ||
1987 ((unsigned char) source->buf[i] > 126)) {
1993 if (!need_to_encode) {
1994 if (*target == NULL) {
1995 *target = NewStrBufPlain(source->buf, source->BufUsed);
1998 FlushStrBuf(*target);
1999 StrBufAppendBuf(*target, source, 0);
2001 return (*target)->BufUsed;
2003 if (*target == NULL)
2004 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2005 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2006 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2007 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2008 (*target)->BufUsed = sizeof(headerStr) - 1;
2009 for (i=0; (i < source->BufUsed); ++i) {
2010 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2011 IncreaseBuf(*target, 1, 0);
2012 ch = (unsigned char) source->buf[i];
2013 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2014 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2015 (*target)->BufUsed += 3;
2018 (*target)->buf[(*target)->BufUsed] = ch;
2019 (*target)->BufUsed++;
2023 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2024 IncreaseBuf(*target, 1, 0);
2026 (*target)->buf[(*target)->BufUsed++] = '?';
2027 (*target)->buf[(*target)->BufUsed++] = '=';
2028 (*target)->buf[(*target)->BufUsed] = '\0';
2029 return (*target)->BufUsed;;
2033 * \brief replaces all occurances of 'search' by 'replace'
2034 * \param buf Buffer to modify
2035 * \param search character to search
2036 * \param relpace character to replace search by
2038 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2043 for (i=0; i<buf->BufUsed; i++)
2044 if (buf->buf[i] == search)
2045 buf->buf[i] = replace;
2052 * Wrapper around iconv_open()
2053 * Our version adds aliases for non-standard Microsoft charsets
2054 * such as 'MS950', aliasing them to names like 'CP950'
2056 * tocode Target encoding
2057 * fromcode Source encoding
2059 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2062 iconv_t ic = (iconv_t)(-1) ;
2063 ic = iconv_open(tocode, fromcode);
2064 if (ic == (iconv_t)(-1) ) {
2065 char alias_fromcode[64];
2066 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2067 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2068 alias_fromcode[0] = 'C';
2069 alias_fromcode[1] = 'P';
2070 ic = iconv_open(tocode, alias_fromcode);
2073 *(iconv_t *)pic = ic;
2079 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2082 /* Find the next ?Q? */
2083 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2086 end = strchr(bptr + 2, '?');
2091 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2092 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2093 (*(end + 2) == '?')) {
2094 /* skip on to the end of the cluster, the next ?= */
2095 end = strstr(end + 3, "?=");
2098 /* sort of half valid encoding, try to find an end. */
2099 end = strstr(bptr, "?=");
2104 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2109 char *ibuf; /**< Buffer of characters to be converted */
2110 char *obuf; /**< Buffer for converted characters */
2111 size_t ibuflen; /**< Length of input buffer */
2112 size_t obuflen; /**< Length of output buffer */
2115 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2116 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2118 ic = *(iconv_t*)pic;
2119 ibuf = ConvertBuf->buf;
2120 ibuflen = ConvertBuf->BufUsed;
2122 obuflen = TmpBuf->BufSize;
2124 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2126 /* little card game: wheres the red lady? */
2127 ibuf = ConvertBuf->buf;
2128 BufSize = ConvertBuf->BufSize;
2130 ConvertBuf->buf = TmpBuf->buf;
2131 ConvertBuf->BufSize = TmpBuf->BufSize;
2132 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2133 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2136 TmpBuf->BufSize = BufSize;
2137 TmpBuf->BufUsed = 0;
2138 TmpBuf->buf[0] = '\0';
2145 inline static void DecodeSegment(StrBuf *Target,
2146 const StrBuf *DecodeMe,
2150 StrBuf *ConvertBuf2,
2151 StrBuf *FoundCharset)
2156 iconv_t ic = (iconv_t)(-1);
2158 /* Now we handle foreign character sets properly encoded
2159 * in RFC2047 format.
2161 StaticBuf.buf = SegmentStart;
2162 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2163 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2164 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2165 if (FoundCharset != NULL) {
2166 FlushStrBuf(FoundCharset);
2167 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2169 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2170 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2172 *encoding = toupper(*encoding);
2173 if (*encoding == 'B') { /**< base64 */
2174 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2176 ConvertBuf->BufUsed);
2178 else if (*encoding == 'Q') { /**< quoted-printable */
2182 while (pos < ConvertBuf->BufUsed)
2184 if (ConvertBuf->buf[pos] == '_')
2185 ConvertBuf->buf[pos] = ' ';
2189 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2192 ConvertBuf->BufUsed);
2195 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2198 ctdl_iconv_open("UTF-8", charset, &ic);
2199 if (ic != (iconv_t)(-1) ) {
2200 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2201 StrBufAppendBuf(Target, ConvertBuf2, 0);
2205 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2209 * Handle subjects with RFC2047 encoding such as:
2210 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2212 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2214 StrBuf *ConvertBuf, *ConvertBuf2;
2215 char *start, *end, *next, *nextend, *ptr = NULL;
2216 iconv_t ic = (iconv_t)(-1) ;
2220 int illegal_non_rfc2047_encoding = 0;
2222 /* Sometimes, badly formed messages contain strings which were simply
2223 * written out directly in some foreign character set instead of
2224 * using RFC2047 encoding. This is illegal but we will attempt to
2225 * handle it anyway by converting from a user-specified default
2226 * charset to UTF-8 if we see any nonprintable characters.
2229 len = StrLength(DecodeMe);
2230 for (i=0; i<DecodeMe->BufUsed; ++i) {
2231 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2232 illegal_non_rfc2047_encoding = 1;
2237 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2238 if ((illegal_non_rfc2047_encoding) &&
2239 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2240 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2242 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2243 if (ic != (iconv_t)(-1) ) {
2244 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2249 /* pre evaluate the first pair */
2250 nextend = end = NULL;
2251 len = StrLength(DecodeMe);
2252 start = strstr(DecodeMe->buf, "=?");
2253 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2255 end = FindNextEnd (DecodeMe, start);
2257 StrBufAppendBuf(Target, DecodeMe, 0);
2258 FreeStrBuf(&ConvertBuf);
2262 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2264 if (start != DecodeMe->buf)
2265 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2267 * Since spammers will go to all sorts of absurd lengths to get their
2268 * messages through, there are LOTS of corrupt headers out there.
2269 * So, prevent a really badly formed RFC2047 header from throwing
2270 * this function into an infinite loop.
2272 while ((start != NULL) &&
2279 DecodeSegment(Target,
2287 next = strstr(end, "=?");
2289 if ((next != NULL) &&
2291 nextend = FindNextEnd(DecodeMe, next);
2292 if (nextend == NULL)
2295 /* did we find two partitions */
2296 if ((next != NULL) &&
2300 while ((ptr < next) &&
2306 /* did we find a gab just filled with blanks? */
2311 len - (next - start));
2313 /* now terminate the gab at the end */
2314 delta = (next - end) - 2; ////TODO: const!
2315 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2316 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2318 /* move next to its new location. */
2323 /* our next-pair is our new first pair now. */
2329 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2330 if ((end != NULL) && (end < nextend)) {
2332 while ( (ptr < nextend) &&
2339 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2341 FreeStrBuf(&ConvertBuf);
2342 FreeStrBuf(&ConvertBuf2);
2347 long StrBuf_Utf8StrLen(StrBuf *Buf)
2349 return Ctdl_Utf8StrLen(Buf->buf);
2352 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2356 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2357 if (CutAt != NULL) {
2358 Buf->BufUsed = CutAt - Buf->buf;
2359 Buf->buf[Buf->BufUsed] = '\0';
2361 return Buf->BufUsed;
2366 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2368 const char *aptr, *ptr, *eptr;
2375 ptr = aptr = Buf->buf;
2379 optr = LineBuf->buf;
2380 eptr = Buf->buf + Buf->BufUsed;
2381 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2383 while ((*ptr != '\n') &&
2390 LineBuf->BufUsed = optr - LineBuf->buf;
2391 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2392 optr = LineBuf->buf + LineBuf->BufUsed;
2393 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2396 LineBuf->BufUsed = optr - LineBuf->buf;
2405 return Buf->BufUsed - (ptr - Buf->buf);