8 #include <sys/select.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
13 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
28 int BaseStrBufSize = SIZ;
31 * Private Structure for the Stringbuffer
34 char *buf; /**< the pointer to the dynamic buffer */
35 long BufSize; /**< how many spcae do we optain */
36 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
37 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 char bt_lastinc [SIZ];
47 static void StrBufBacktrace(StrBuf *Buf, int which)
51 void *stack_frames[50];
56 pstart = pch = Buf->bt;
58 pstart = pch = Buf->bt_lastinc;
59 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
60 strings = backtrace_symbols(stack_frames, size);
61 for (i = 0; i < size; i++) {
63 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
65 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
76 * \Brief Cast operator to Plain String
77 * Note: if the buffer is altered by StrBuf operations, this pointer may become
78 * invalid. So don't lean on it after altering the buffer!
79 * Since this operation is considered cheap, rather call it often than risking
80 * your pointer to become invalid!
81 * \param Str the string we want to get the c-string representation for
82 * \returns the Pointer to the Content. Don't mess with it!
84 inline const char *ChrPtr(const StrBuf *Str)
92 * \brief since we know strlen()'s result, provide it here.
93 * \param Str the string to return the length to
94 * \returns contentlength of the buffer
96 inline int StrLength(const StrBuf *Str)
98 return (Str != NULL) ? Str->BufUsed : 0;
102 * \brief local utility function to resize the buffer
103 * \param Buf the buffer whichs storage we should increase
104 * \param KeepOriginal should we copy the original buffer or just start over with a new one
105 * \param DestSize what should fit in after?
107 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
110 size_t NewSize = Buf->BufSize * 2;
116 while (NewSize <= DestSize)
119 NewBuf= (char*) malloc(NewSize);
120 if (KeepOriginal && (Buf->BufUsed > 0))
122 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
131 Buf->BufSize = NewSize;
135 StrBufBacktrace(Buf, 1);
142 * \brief shrink long term buffers to their real size so they don't waste memory
143 * \param Buf buffer to shrink
144 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
145 * \returns physical size of the buffer
147 long StrBufShrinkToFit(StrBuf *Buf, int Force)
150 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
152 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
153 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
154 Buf->BufSize = Buf->BufUsed + 1;
162 * Allocate a new buffer with default buffer size
163 * \returns the new stringbuffer
165 StrBuf* NewStrBuf(void)
169 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
170 NewBuf->buf = (char*) malloc(BaseStrBufSize);
171 NewBuf->buf[0] = '\0';
172 NewBuf->BufSize = BaseStrBufSize;
174 NewBuf->ConstBuf = 0;
176 NewBuf->nIncreases = 0;
177 NewBuf->bt[0] = '\0';
178 NewBuf->bt_lastinc[0] = '\0';
180 StrBufBacktrace(NewBuf, 0);
187 * \brief Copy Constructor; returns a duplicate of CopyMe
188 * \params CopyMe Buffer to faxmilate
189 * \returns the new stringbuffer
191 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
198 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
199 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
200 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
201 NewBuf->BufUsed = CopyMe->BufUsed;
202 NewBuf->BufSize = CopyMe->BufSize;
203 NewBuf->ConstBuf = 0;
205 NewBuf->nIncreases = 0;
206 NewBuf->bt[0] = '\0';
207 NewBuf->bt_lastinc[0] = '\0';
209 StrBufBacktrace(NewBuf, 0);
216 * \brief create a new Buffer using an existing c-string
217 * this function should also be used if you want to pre-suggest
218 * the buffer size to allocate in conjunction with ptr == NULL
219 * \param ptr the c-string to copy; may be NULL to create a blank instance
220 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
221 * \returns the new stringbuffer
223 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
226 size_t Siz = BaseStrBufSize;
229 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
231 CopySize = strlen((ptr != NULL)?ptr:"");
235 while (Siz <= CopySize)
238 NewBuf->buf = (char*) malloc(Siz);
239 NewBuf->BufSize = Siz;
241 memcpy(NewBuf->buf, ptr, CopySize);
242 NewBuf->buf[CopySize] = '\0';
243 NewBuf->BufUsed = CopySize;
246 NewBuf->buf[0] = '\0';
249 NewBuf->ConstBuf = 0;
251 NewBuf->nIncreases = 0;
252 NewBuf->bt[0] = '\0';
253 NewBuf->bt_lastinc[0] = '\0';
255 StrBufBacktrace(NewBuf, 0);
262 * \brief Set an existing buffer from a c-string
263 * \param ptr c-string to put into
264 * \param nChars set to -1 if we should work 0-terminated
265 * \returns the new length of the string
267 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
269 size_t Siz = Buf->BufSize;
273 CopySize = strlen(ptr);
277 while (Siz <= CopySize)
280 if (Siz != Buf->BufSize)
281 IncreaseBuf(Buf, 0, Siz);
282 memcpy(Buf->buf, ptr, CopySize);
283 Buf->buf[CopySize] = '\0';
284 Buf->BufUsed = CopySize;
291 * \brief use strbuf as wrapper for a string constant for easy handling
292 * \param StringConstant a string to wrap
293 * \param SizeOfConstant should be sizeof(StringConstant)-1
295 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
299 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
300 NewBuf->buf = (char*) StringConstant;
301 NewBuf->BufSize = SizeOfStrConstant;
302 NewBuf->BufUsed = SizeOfStrConstant;
303 NewBuf->ConstBuf = 1;
305 NewBuf->nIncreases = 0;
306 NewBuf->bt[0] = '\0';
307 NewBuf->bt_lastinc[0] = '\0';
314 * \brief flush the content of a Buf; keep its struct
315 * \param buf Buffer to flush
317 int FlushStrBuf(StrBuf *buf)
329 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
330 * \param buf Buffer to wipe
332 int FLUSHStrBuf(StrBuf *buf)
338 if (buf->BufUsed > 0) {
339 memset(buf->buf, 0, buf->BufUsed);
346 int hFreeDbglog = -1;
349 * \brief Release a Buffer
350 * Its a double pointer, so it can NULL your pointer
351 * so fancy SIG11 appear instead of random results
352 * \param FreeMe Pointer Pointer to the buffer to free
354 void FreeStrBuf (StrBuf **FreeMe)
359 if (hFreeDbglog == -1){
360 pid_t pid = getpid();
362 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
363 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
365 if ((*FreeMe)->nIncreases > 0)
369 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
370 (*FreeMe)->nIncreases,
374 (*FreeMe)->bt_lastinc);
375 n = write(hFreeDbglog, buf, n);
381 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
384 n = write(hFreeDbglog, buf, n);
387 if (!(*FreeMe)->ConstBuf)
388 free((*FreeMe)->buf);
394 * \brief Release the buffer
395 * If you want put your StrBuf into a Hash, use this as Destructor.
396 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
398 void HFreeStrBuf (void *VFreeMe)
400 StrBuf *FreeMe = (StrBuf*)VFreeMe;
404 if (hFreeDbglog == -1){
405 pid_t pid = getpid();
407 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
408 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
410 if (FreeMe->nIncreases > 0)
414 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
420 write(hFreeDbglog, buf, n);
426 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
432 if (!FreeMe->ConstBuf)
438 * \brief Wrapper around atol
440 long StrTol(const StrBuf *Buf)
445 return atol(Buf->buf);
451 * \brief Wrapper around atoi
453 int StrToi(const StrBuf *Buf)
457 if (Buf->BufUsed > 0)
458 return atoi(Buf->buf);
464 * \brief Checks to see if the string is a pure number
466 int StrBufIsNumber(const StrBuf *Buf) {
471 strtoll(Buf->buf, &pEnd, 10);
472 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
478 * \brief modifies a Single char of the Buf
479 * You can point to it via char* or a zero-based integer
480 * \param ptr char* to zero; use NULL if unused
481 * \param nThChar zero based pointer into the string; use -1 if unused
482 * \param PeekValue The Character to place into the position
484 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
489 nThChar = ptr - Buf->buf;
490 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
492 Buf->buf[nThChar] = PeekValue;
497 * \brief Append a StringBuffer to the buffer
498 * \param Buf Buffer to modify
499 * \param AppendBuf Buffer to copy at the end of our buffer
500 * \param Offset Should we start copying from an offset?
502 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
504 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
507 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
510 AppendBuf->BufUsed + Buf->BufUsed);
512 memcpy(Buf->buf + Buf->BufUsed,
513 AppendBuf->buf + Offset,
514 AppendBuf->BufUsed - Offset);
515 Buf->BufUsed += AppendBuf->BufUsed - Offset;
516 Buf->buf[Buf->BufUsed] = '\0';
521 * \brief Append a C-String to the buffer
522 * \param Buf Buffer to modify
523 * \param AppendBuf Buffer to copy at the end of our buffer
524 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
525 * \param Offset Should we start copying from an offset?
527 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
530 long BufSizeRequired;
532 if ((AppendBuf == NULL) || (Buf == NULL))
536 aps = strlen(AppendBuf + Offset);
538 aps = AppendSize - Offset;
540 BufSizeRequired = Buf->BufUsed + aps + 1;
541 if (Buf->BufSize <= BufSizeRequired)
542 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
544 memcpy(Buf->buf + Buf->BufUsed,
548 Buf->buf[Buf->BufUsed] = '\0';
553 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
554 * \param outbuf the output buffer
555 * \param oblen the size of outbuf to sanitize
556 * \param strbuf the input buffer
558 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
560 const char *pch, *pche;
563 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
564 int eclen = sizeof(ec) -1;
566 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
568 if (PlainIn != NULL) {
569 len = strlen(PlainIn);
575 pche = pch + In->BufUsed;
582 pt = OutBuf->buf + OutBuf->BufUsed;
583 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
587 IncreaseBuf(OutBuf, 1, -1);
588 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
589 pt = OutBuf->buf + OutBuf->BufUsed;
593 for (b = 0; b < eclen; ++b) {
600 sprintf(pt,"%%%02X", *pch);
602 OutBuf->BufUsed += 3;
614 * \brief Append a string, escaping characters which have meaning in HTML.
616 * \param Target target buffer
617 * \param Source source buffer; set to NULL if you just have a C-String
618 * \param PlainIn Plain-C string to append; set to NULL if unused
619 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
620 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
621 * if set to 2, linebreaks are replaced by <br/>
623 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
625 const char *aptr, *eiptr;
629 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
632 if (PlainIn != NULL) {
634 len = strlen(PlainIn);
639 eiptr = aptr + Source->BufUsed;
640 len = Source->BufUsed;
646 bptr = Target->buf + Target->BufUsed;
647 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
649 while (aptr < eiptr){
651 IncreaseBuf(Target, 1, -1);
652 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
653 bptr = Target->buf + Target->BufUsed;
656 memcpy(bptr, "<", 4);
658 Target->BufUsed += 4;
660 else if (*aptr == '>') {
661 memcpy(bptr, ">", 4);
663 Target->BufUsed += 4;
665 else if (*aptr == '&') {
666 memcpy(bptr, "&", 5);
668 Target->BufUsed += 5;
670 else if (*aptr == '"') {
671 memcpy(bptr, """, 6);
673 Target->BufUsed += 6;
675 else if (*aptr == '\'') {
676 memcpy(bptr, "'", 5);
678 Target->BufUsed += 5;
680 else if (*aptr == LB) {
685 else if (*aptr == RB) {
690 else if (*aptr == QU) {
695 else if ((*aptr == 32) && (nbsp == 1)) {
696 memcpy(bptr, " ", 6);
698 Target->BufUsed += 6;
700 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
701 *bptr='\0'; /* nothing */
703 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
704 memcpy(bptr, "<br/>", 11);
706 Target->BufUsed += 11;
710 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
711 *bptr='\0'; /* nothing */
721 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
723 return Target->BufUsed;
727 * \brief Append a string, escaping characters which have meaning in HTML.
728 * Converts linebreaks into blanks; escapes single quotes
729 * \param Target target buffer
730 * \param Source source buffer; set to NULL if you just have a C-String
731 * \param PlainIn Plain-C string to append; set to NULL if unused
733 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
735 const char *aptr, *eiptr;
739 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
742 if (PlainIn != NULL) {
744 len = strlen(PlainIn);
749 eiptr = aptr + Source->BufUsed;
750 len = Source->BufUsed;
756 eptr = Target->buf + Target->BufSize - 8;
757 tptr = Target->buf + Target->BufUsed;
759 while (aptr < eiptr){
761 IncreaseBuf(Target, 1, -1);
762 eptr = Target->buf + Target->BufSize - 8;
763 tptr = Target->buf + Target->BufUsed;
770 else if (*aptr == '\r') {
774 else if (*aptr == '\'') {
780 Target->BufUsed += 5;
791 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
793 * \param Target target buffer
794 * \param Source source buffer; set to NULL if you just have a C-String
795 * \param PlainIn Plain-C string to append; set to NULL if unused
797 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
799 const char *aptr, *eiptr;
803 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
806 if (PlainIn != NULL) {
808 len = strlen(PlainIn);
813 eiptr = aptr + Source->BufUsed;
814 len = Source->BufUsed;
820 bptr = Target->buf + Target->BufUsed;
821 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
823 while (aptr < eiptr){
825 IncreaseBuf(Target, 1, -1);
826 eptr = Target->buf + Target->BufSize - 3;
827 bptr = Target->buf + Target->BufUsed;
829 else if (*aptr == '"') {
830 memcpy(bptr, "\\\"", 2);
832 Target->BufUsed += 2;
833 } else if (*aptr == '\\') {
834 memcpy(bptr, "\\\\", 2);
836 Target->BufUsed += 2;
846 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
848 return Target->BufUsed;
852 * \brief extracts a substring from Source into dest
853 * \param dest buffer to place substring into
854 * \param Source string to copy substring from
855 * \param Offset chars to skip from start
856 * \param nChars number of chars to copy
857 * \returns the number of chars copied; may be different from nChars due to the size of Source
859 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
862 if (Offset > Source->BufUsed)
867 if (Offset + nChars < Source->BufUsed)
869 if (nChars >= dest->BufSize)
870 IncreaseBuf(dest, 0, nChars + 1);
871 memcpy(dest->buf, Source->buf + Offset, nChars);
872 dest->BufUsed = nChars;
873 dest->buf[dest->BufUsed] = '\0';
876 NCharsRemain = Source->BufUsed - Offset;
877 if (NCharsRemain >= dest->BufSize)
878 IncreaseBuf(dest, 0, NCharsRemain + 1);
879 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
880 dest->BufUsed = NCharsRemain;
881 dest->buf[dest->BufUsed] = '\0';
886 * \brief sprintf like function appending the formated string to the buffer
887 * vsnprintf version to wrap into own calls
888 * \param Buf Buffer to extend by format and params
889 * \param format printf alike format to add
890 * \param ap va_list containing the items for format
892 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
895 size_t BufSize = Buf->BufSize;
896 size_t nWritten = Buf->BufSize + 1;
897 size_t Offset = Buf->BufUsed;
898 size_t newused = Offset + nWritten;
900 while (newused >= BufSize) {
902 nWritten = vsnprintf(Buf->buf + Offset,
903 Buf->BufSize - Offset,
906 newused = Offset + nWritten;
907 if (newused >= Buf->BufSize) {
908 IncreaseBuf(Buf, 1, newused);
909 newused = Buf->BufSize + 1;
912 Buf->BufUsed = Offset + nWritten;
913 BufSize = Buf->BufSize;
920 * \brief sprintf like function appending the formated string to the buffer
921 * \param Buf Buffer to extend by format and params
922 * \param format printf alike format to add
923 * \param ap va_list containing the items for format
925 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
927 size_t BufSize = Buf->BufSize;
928 size_t nWritten = Buf->BufSize + 1;
929 size_t Offset = Buf->BufUsed;
930 size_t newused = Offset + nWritten;
933 while (newused >= BufSize) {
934 va_start(arg_ptr, format);
935 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
936 Buf->BufSize - Buf->BufUsed,
939 newused = Buf->BufUsed + nWritten;
940 if (newused >= Buf->BufSize) {
941 IncreaseBuf(Buf, 1, newused);
942 newused = Buf->BufSize + 1;
945 Buf->BufUsed += nWritten;
946 BufSize = Buf->BufSize;
953 * \brief sprintf like function putting the formated string into the buffer
954 * \param Buf Buffer to extend by format and params
955 * \param format printf alike format to add
956 * \param ap va_list containing the items for format
958 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
960 size_t nWritten = Buf->BufSize + 1;
963 while (nWritten >= Buf->BufSize) {
964 va_start(arg_ptr, format);
965 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
967 if (nWritten >= Buf->BufSize) {
968 IncreaseBuf(Buf, 0, 0);
969 nWritten = Buf->BufSize + 1;
972 Buf->BufUsed = nWritten ;
978 * \brief Counts the numbmer of tokens in a buffer
979 * \param Source String to count tokens in
980 * \param tok Tokenizer char to count
981 * \returns numbers of tokenizer chars found
983 int StrBufNum_tokens(const StrBuf *source, char tok)
987 return num_tokens(source->buf, tok);
991 * remove_token() - a tokenizer that kills, maims, and destroys
994 * \brief a string tokenizer
995 * \param Source StringBuffer to read into
996 * \param parmnum n'th parameter to remove
997 * \param separator tokenizer param
998 * \returns -1 if not found, else length of token.
1000 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1003 char *d, *s; /* dest, source */
1006 /* Find desired parameter */
1008 while (count < parmnum) {
1009 /* End of string, bail! */
1014 if (*d == separator) {
1019 if (!d) return 0; /* Parameter not found */
1021 /* Find next parameter */
1023 while (*s && *s != separator) {
1026 if (*s == separator)
1030 /* Hack and slash */
1032 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1033 Source->BufUsed -= (ReducedBy + 1);
1035 else if (d == Source->buf) {
1037 Source->BufUsed = 0;
1041 Source->BufUsed -= (ReducedBy + 1);
1054 * \brief a string tokenizer
1055 * \param dest Destination StringBuffer
1056 * \param Source StringBuffer to read into
1057 * \param parmnum n'th parameter to extract
1058 * \param separator tokenizer param
1059 * \returns -1 if not found, else length of token.
1061 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1063 const char *s, *e; //* source * /
1064 int len = 0; //* running total length of extracted string * /
1065 int current_token = 0; //* token currently being processed * /
1068 dest->buf[0] = '\0';
1074 if ((Source == NULL) || (Source->BufUsed ==0)) {
1078 e = s + Source->BufUsed;
1081 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1083 while ((s<e) && !IsEmptyStr(s)) {
1084 if (*s == separator) {
1087 if (len >= dest->BufSize)
1088 if (!IncreaseBuf(dest, 1, -1))
1090 if ( (current_token == parmnum) &&
1091 (*s != separator)) {
1092 dest->buf[len] = *s;
1095 else if (current_token > parmnum) {
1101 dest->buf[len] = '\0';
1102 dest->BufUsed = len;
1104 if (current_token < parmnum) {
1105 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1108 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1117 * \brief a string tokenizer to fetch an integer
1118 * \param dest Destination StringBuffer
1119 * \param parmnum n'th parameter to extract
1120 * \param separator tokenizer param
1121 * \returns 0 if not found, else integer representation of the token
1123 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1133 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1140 * \brief a string tokenizer to fetch a long integer
1141 * \param dest Destination StringBuffer
1142 * \param parmnum n'th parameter to extract
1143 * \param separator tokenizer param
1144 * \returns 0 if not found, else long integer representation of the token
1146 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1156 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1164 * \brief a string tokenizer to fetch an unsigned long
1165 * \param dest Destination StringBuffer
1166 * \param parmnum n'th parameter to extract
1167 * \param separator tokenizer param
1168 * \returns 0 if not found, else unsigned long representation of the token
1170 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1181 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1185 return (unsigned long) atol(pnum);
1194 * \brief a string tokenizer
1195 * \param dest Destination StringBuffer
1196 * \param Source StringBuffer to read into
1197 * \param pStart pointer to the end of the last token. Feed with NULL.
1198 * \param separator tokenizer param
1199 * \returns -1 if not found, else length of token.
1201 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1203 const char *s, *EndBuffer; //* source * /
1204 int len = 0; //* running total length of extracted string * /
1205 int current_token = 0; //* token currently being processed * /
1208 dest->buf[0] = '\0';
1214 if ((Source == NULL) ||
1215 (Source->BufUsed ==0)) {
1218 if (*pStart == NULL)
1219 *pStart = Source->buf;
1221 EndBuffer = Source->buf + Source->BufUsed;
1223 if ((*pStart < Source->buf) ||
1224 (*pStart > EndBuffer)) {
1232 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1234 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1235 if (*s == separator) {
1238 if (len >= dest->BufSize)
1239 if (!IncreaseBuf(dest, 1, -1)) {
1240 *pStart = EndBuffer + 1;
1243 if ( (current_token == 0) &&
1244 (*s != separator)) {
1245 dest->buf[len] = *s;
1248 else if (current_token > 0) {
1257 dest->buf[len] = '\0';
1258 dest->BufUsed = len;
1259 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1260 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1266 * \brief a string tokenizer
1267 * \param dest Destination StringBuffer
1268 * \param Source StringBuffer to read into
1269 * \param pStart pointer to the end of the last token. Feed with NULL.
1270 * \param separator tokenizer param
1271 * \returns -1 if not found, else length of token.
1273 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1275 const char *s, *EndBuffer; //* source * /
1276 int len = 0; //* running total length of extracted string * /
1277 int current_token = 0; //* token currently being processed * /
1279 if ((Source == NULL) ||
1280 (Source->BufUsed ==0)) {
1284 return Source->BufUsed;
1286 if (*pStart == NULL)
1287 *pStart = Source->buf;
1289 EndBuffer = Source->buf + Source->BufUsed;
1291 if ((*pStart < Source->buf) ||
1292 (*pStart > EndBuffer)) {
1300 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1302 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1303 if (*s == separator) {
1306 if (current_token >= nTokens) {
1318 * \brief a string tokenizer to fetch an integer
1319 * \param dest Destination StringBuffer
1320 * \param parmnum n'th parameter to extract
1321 * \param separator tokenizer param
1322 * \returns 0 if not found, else integer representation of the token
1324 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1334 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1341 * \brief a string tokenizer to fetch a long integer
1342 * \param dest Destination StringBuffer
1343 * \param parmnum n'th parameter to extract
1344 * \param separator tokenizer param
1345 * \returns 0 if not found, else long integer representation of the token
1347 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1357 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1365 * \brief a string tokenizer to fetch an unsigned long
1366 * \param dest Destination StringBuffer
1367 * \param parmnum n'th parameter to extract
1368 * \param separator tokenizer param
1369 * \returns 0 if not found, else unsigned long representation of the token
1371 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1382 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1386 return (unsigned long) atol(pnum);
1395 * \brief Read a line from socket
1396 * flushes and closes the FD on error
1397 * \param buf the buffer to get the input to
1398 * \param fd pointer to the filedescriptor to read
1399 * \param append Append to an existing string or replace?
1400 * \param Error strerror() on error
1401 * \returns numbers of chars read
1403 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1405 int len, rlen, slen;
1410 slen = len = buf->BufUsed;
1412 rlen = read(*fd, &buf->buf[len], 1);
1414 *Error = strerror(errno);
1421 if (buf->buf[len] == '\n')
1423 if (buf->buf[len] != '\r')
1425 if (len >= buf->BufSize) {
1427 buf->buf[len+1] = '\0';
1428 IncreaseBuf(buf, 1, -1);
1432 buf->buf[len] = '\0';
1437 * \brief Read a line from socket
1438 * flushes and closes the FD on error
1439 * \param buf the buffer to get the input to
1440 * \param fd pointer to the filedescriptor to read
1441 * \param append Append to an existing string or replace?
1442 * \param Error strerror() on error
1443 * \returns numbers of chars read
1445 int StrBufTCP_read_buffered_line(StrBuf *Line,
1449 int selectresolution,
1453 int nSuccessLess = 0;
1459 if (buf->BufUsed > 0) {
1460 pch = strchr(buf->buf, '\n');
1463 len = pch - buf->buf;
1464 if (len > 0 && (*(pch - 1) == '\r') )
1466 StrBufSub(Line, buf, 0, len - rlen);
1467 StrBufCutLeft(buf, len + 1);
1472 if (buf->BufSize - buf->BufUsed < 10)
1473 IncreaseBuf(buf, 1, -1);
1475 fdflags = fcntl(*fd, F_GETFL);
1476 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1479 while ((nSuccessLess < timeout) && (pch == NULL)) {
1480 tv.tv_sec = selectresolution;
1485 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1486 *Error = strerror(errno);
1491 if (FD_ISSET(*fd, &rfds)) {
1493 &buf->buf[buf->BufUsed],
1494 buf->BufSize - buf->BufUsed - 1);
1496 *Error = strerror(errno);
1501 else if (rlen > 0) {
1503 buf->BufUsed += rlen;
1504 buf->buf[buf->BufUsed] = '\0';
1505 if (buf->BufUsed + 10 > buf->BufSize) {
1506 IncreaseBuf(buf, 1, -1);
1508 pch = strchr(buf->buf, '\n');
1516 len = pch - buf->buf;
1517 if (len > 0 && (*(pch - 1) == '\r') )
1519 StrBufSub(Line, buf, 0, len - rlen);
1520 StrBufCutLeft(buf, len + 1);
1528 * \brief Read a line from socket
1529 * flushes and closes the FD on error
1530 * \param buf the buffer to get the input to
1531 * \param Pos pointer to the current read position, should be NULL initialized!
1532 * \param fd pointer to the filedescriptor to read
1533 * \param append Append to an existing string or replace?
1534 * \param Error strerror() on error
1535 * \returns numbers of chars read
1537 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1542 int selectresolution,
1545 const char *pche = NULL;
1546 const char *pos = NULL;
1548 int nSuccessLess = 0;
1550 const char *pch = NULL;
1555 if ((IOBuf->BufUsed > 0) &&
1557 (pos < IOBuf->buf + IOBuf->BufUsed))
1559 pche = IOBuf->buf + IOBuf->BufUsed;
1561 while ((pch < pche) && (*pch != '\n'))
1563 if ((pch >= pche) || (*pch == '\0'))
1565 if ((pch != NULL) &&
1570 if (len > 0 && (*(pch - 1) == '\r') )
1572 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1582 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1586 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1587 IncreaseBuf(IOBuf, 1, -1);
1590 fdflags = fcntl(*fd, F_GETFL);
1591 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1595 while ((nSuccessLess < timeout) && (pch == NULL)) {
1596 tv.tv_sec = selectresolution;
1601 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1602 *Error = strerror(errno);
1607 if (FD_ISSET(*fd, &rfds) != 0) {
1609 &IOBuf->buf[IOBuf->BufUsed],
1610 IOBuf->BufSize - IOBuf->BufUsed - 1);
1612 *Error = strerror(errno);
1617 else if (rlen > 0) {
1619 IOBuf->BufUsed += rlen;
1620 IOBuf->buf[IOBuf->BufUsed] = '\0';
1621 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1622 IncreaseBuf(IOBuf, 1, -1);
1625 pche = IOBuf->buf + IOBuf->BufUsed;
1627 while ((pch < pche) && (*pch != '\n'))
1629 if ((pch >= pche) || (*pch == '\0'))
1640 if (len > 0 && (*(pch - 1) == '\r') )
1642 StrBufSub(Line, IOBuf, 0, len - rlen);
1643 *Pos = pos + len + 1;
1651 * \brief Input binary data from socket
1652 * flushes and closes the FD on error
1653 * \param buf the buffer to get the input to
1654 * \param fd pointer to the filedescriptor to read
1655 * \param append Append to an existing string or replace?
1656 * \param nBytes the maximal number of bytes to read
1657 * \param Error strerror() on error
1658 * \returns numbers of chars read
1660 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1664 int len, rlen, slen;
1668 if ((Buf == NULL) || (*fd == -1))
1672 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1673 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1675 ptr = Buf->buf + Buf->BufUsed;
1677 slen = len = Buf->BufUsed;
1679 fdflags = fcntl(*fd, F_GETFL);
1681 while (nRead < nBytes) {
1682 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1685 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1686 *Error = strerror(errno);
1691 if ((rlen = read(*fd,
1693 nBytes - nRead)) == -1) {
1696 *Error = strerror(errno);
1701 Buf->BufUsed += rlen;
1703 Buf->buf[Buf->BufUsed] = '\0';
1708 * \brief Input binary data from socket
1709 * flushes and closes the FD on error
1710 * \param buf the buffer to get the input to
1711 * \param fd pointer to the filedescriptor to read
1712 * \param append Append to an existing string or replace?
1713 * \param nBytes the maximal number of bytes to read
1714 * \param Error strerror() on error
1715 * \returns numbers of chars read
1717 int StrBufReadBLOBBuffered(StrBuf *Blob,
1738 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1742 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1743 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1748 len = pos - IOBuf->buf;
1749 rlen = IOBuf->BufUsed - len;
1752 if ((IOBuf->BufUsed > 0) &&
1754 (pos < IOBuf->buf + IOBuf->BufUsed))
1756 pche = IOBuf->buf + IOBuf->BufUsed;
1759 if (rlen < nBytes) {
1760 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1761 Blob->BufUsed += rlen;
1762 Blob->buf[Blob->BufUsed] = '\0';
1766 if (rlen >= nBytes) {
1767 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1768 Blob->BufUsed += nBytes;
1769 Blob->buf[Blob->BufUsed] = '\0';
1770 if (rlen == nBytes) {
1781 if (IOBuf->BufSize < nBytes - nRead)
1782 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1785 slen = len = Blob->BufUsed;
1787 fdflags = fcntl(*fd, F_GETFL);
1792 while (nRead < nBytes) {
1793 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1796 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1799 *Error = strerror(errno);
1810 *Error = strerror(errno);
1816 if ((check == NNN_TERM) &&
1818 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1820 StrBufPlain(Blob, HKEY("\n000\n"));
1821 StrBufCutRight(Blob, 5);
1822 return Blob->BufUsed;
1824 if (nSelects > 10) {
1832 IOBuf->BufUsed += rlen;
1835 if (nRead > nBytes) {
1836 *Pos = IOBuf->buf + nBytes;
1838 Blob->buf[Blob->BufUsed] = '\0';
1839 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1844 * \brief Cut nChars from the start of the string
1845 * \param Buf Buffer to modify
1846 * \param nChars how many chars should be skipped?
1848 void StrBufCutLeft(StrBuf *Buf, int nChars)
1850 if (nChars >= Buf->BufUsed) {
1854 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1855 Buf->BufUsed -= nChars;
1856 Buf->buf[Buf->BufUsed] = '\0';
1860 * \brief Cut the trailing n Chars from the string
1861 * \param Buf Buffer to modify
1862 * \param nChars how many chars should be trunkated?
1864 void StrBufCutRight(StrBuf *Buf, int nChars)
1866 if (nChars >= Buf->BufUsed) {
1870 Buf->BufUsed -= nChars;
1871 Buf->buf[Buf->BufUsed] = '\0';
1875 * \brief Cut the string after n Chars
1876 * \param Buf Buffer to modify
1877 * \param AfternChars after how many chars should we trunkate the string?
1878 * \param At if non-null and points inside of our string, cut it there.
1880 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1883 AfternChars = At - Buf->buf;
1886 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1888 Buf->BufUsed = AfternChars;
1889 Buf->buf[Buf->BufUsed] = '\0';
1894 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1895 * buf - the string to modify
1896 * len - length of the string.
1898 void StrBufTrim(StrBuf *Buf)
1901 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1903 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1906 if (delta > 0) StrBufCutLeft(Buf, delta);
1908 if (Buf->BufUsed == 0) return;
1909 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1912 Buf->buf[Buf->BufUsed] = '\0';
1916 void StrBufUpCase(StrBuf *Buf)
1921 pche = pch + Buf->BufUsed;
1922 while (pch < pche) {
1923 *pch = toupper(*pch);
1929 void StrBufLowerCase(StrBuf *Buf)
1934 pche = pch + Buf->BufUsed;
1935 while (pch < pche) {
1936 *pch = tolower(*pch);
1943 * \brief unhide special chars hidden to the HTML escaper
1944 * \param target buffer to put the unescaped string in
1945 * \param source buffer to unescape
1947 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1953 FlushStrBuf(target);
1955 if (source == NULL ||target == NULL)
1960 len = source->BufUsed;
1961 for (a = 0; a < len; ++a) {
1962 if (target->BufUsed >= target->BufSize)
1963 IncreaseBuf(target, 1, -1);
1965 if (source->buf[a] == '=') {
1966 hex[0] = source->buf[a + 1];
1967 hex[1] = source->buf[a + 2];
1970 sscanf(hex, "%02x", &b);
1971 target->buf[target->BufUsed] = b;
1972 target->buf[++target->BufUsed] = 0;
1976 target->buf[target->BufUsed] = source->buf[a];
1977 target->buf[++target->BufUsed] = 0;
1984 * \brief hide special chars from the HTML escapers and friends
1985 * \param target buffer to put the escaped string in
1986 * \param source buffer to escape
1988 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1993 FlushStrBuf(target);
1995 if (source == NULL ||target == NULL)
2000 len = source->BufUsed;
2001 for (i=0; i<len; ++i) {
2002 if (target->BufUsed + 4 >= target->BufSize)
2003 IncreaseBuf(target, 1, -1);
2004 if ( (isalnum(source->buf[i])) ||
2005 (source->buf[i]=='-') ||
2006 (source->buf[i]=='_') ) {
2007 target->buf[target->BufUsed++] = source->buf[i];
2010 sprintf(&target->buf[target->BufUsed],
2012 (0xFF &source->buf[i]));
2013 target->BufUsed += 3;
2016 target->buf[target->BufUsed + 1] = '\0';
2020 * \brief uses the same calling syntax as compress2(), but it
2021 * creates a stream compatible with HTTP "Content-encoding: gzip"
2024 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2025 #define OS_CODE 0x03 /*< unix */
2026 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2027 size_t * destLen, /*< length of the compresed data */
2028 const Bytef * source, /*< source to encode */
2029 uLong sourceLen, /*< length of source to encode */
2030 int level) /*< compression level */
2032 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2034 /* write gzip header */
2035 snprintf((char *) dest, *destLen,
2036 "%c%c%c%c%c%c%c%c%c%c",
2037 gz_magic[0], gz_magic[1], Z_DEFLATED,
2038 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2041 /* normal deflate */
2044 stream.next_in = (Bytef *) source;
2045 stream.avail_in = (uInt) sourceLen;
2046 stream.next_out = dest + 10L; // after header
2047 stream.avail_out = (uInt) * destLen;
2048 if ((uLong) stream.avail_out != *destLen)
2051 stream.zalloc = (alloc_func) 0;
2052 stream.zfree = (free_func) 0;
2053 stream.opaque = (voidpf) 0;
2055 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2056 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2060 err = deflate(&stream, Z_FINISH);
2061 if (err != Z_STREAM_END) {
2062 deflateEnd(&stream);
2063 return err == Z_OK ? Z_BUF_ERROR : err;
2065 *destLen = stream.total_out + 10L;
2067 /* write CRC and Length */
2068 uLong crc = crc32(0L, source, sourceLen);
2070 for (n = 0; n < 4; ++n, ++*destLen) {
2071 dest[*destLen] = (int) (crc & 0xff);
2074 uLong len = stream.total_in;
2075 for (n = 0; n < 4; ++n, ++*destLen) {
2076 dest[*destLen] = (int) (len & 0xff);
2079 err = deflateEnd(&stream);
2086 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2088 int CompressBuffer(StrBuf *Buf)
2091 char *compressed_data = NULL;
2092 size_t compressed_len, bufsize;
2095 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2096 compressed_data = malloc(compressed_len);
2098 /* Flush some space after the used payload so valgrind shuts up... */
2099 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2100 Buf->buf[Buf->BufUsed + i++] = '\0';
2101 if (compress_gzip((Bytef *) compressed_data,
2104 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2107 Buf->buf = compressed_data;
2108 Buf->BufUsed = compressed_len;
2109 Buf->BufSize = bufsize;
2110 /* Flush some space after the used payload so valgrind shuts up... */
2112 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2113 Buf->buf[Buf->BufUsed + i++] = '\0';
2116 free(compressed_data);
2118 #endif /* HAVE_ZLIB */
2123 * \brief decode a buffer from base 64 encoding; destroys original
2124 * \param Buf Buffor to transform
2126 int StrBufDecodeBase64(StrBuf *Buf)
2130 if (Buf == NULL) return -1;
2132 xferbuf = (char*) malloc(Buf->BufSize);
2133 siz = CtdlDecodeBase64(xferbuf,
2143 * \brief decode a buffer from base 64 encoding; destroys original
2144 * \param Buf Buffor to transform
2146 int StrBufDecodeHex(StrBuf *Buf)
2149 char *pch, *pche, *pchi;
2151 if (Buf == NULL) return -1;
2153 pch = pchi = Buf->buf;
2154 pche = pch + Buf->BufUsed;
2156 while (pchi < pche){
2157 ch = decode_hex(pchi);
2164 Buf->BufUsed = pch - Buf->buf;
2165 return Buf->BufUsed;
2169 * \brief replace all chars >0x20 && < 0x7F with Mute
2170 * \param Mute char to put over invalid chars
2171 * \param Buf Buffor to transform
2173 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2177 if (Buf == NULL) return -1;
2178 pch = (unsigned char *)Buf->buf;
2179 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2180 if ((*pch < 0x20) || (*pch > 0x7F))
2184 return Buf->BufUsed;
2189 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2190 * \param Buf Buffer to translate
2191 * \param StripBlanks Reduce several blanks to one?
2193 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2199 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2200 Buf->buf[Buf->BufUsed - 1] = '\0';
2205 while (a < Buf->BufUsed) {
2206 if (Buf->buf[a] == '+')
2208 else if (Buf->buf[a] == '%') {
2209 /* don't let % chars through, rather truncate the input. */
2210 if (a + 2 > Buf->BufUsed) {
2215 hex[0] = Buf->buf[a + 1];
2216 hex[1] = Buf->buf[a + 2];
2219 sscanf(hex, "%02x", &b);
2220 Buf->buf[a] = (char) b;
2221 len = Buf->BufUsed - a - 2;
2223 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2235 * \brief RFC2047-encode a header field if necessary.
2236 * If no non-ASCII characters are found, the string
2237 * will be copied verbatim without encoding.
2239 * \param target Target buffer.
2240 * \param source Source string to be encoded.
2241 * \returns encoded length; -1 if non success.
2243 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2245 const char headerStr[] = "=?UTF-8?Q?";
2246 int need_to_encode = 0;
2250 if ((source == NULL) ||
2254 while ((i < source->BufUsed) &&
2255 (!IsEmptyStr (&source->buf[i])) &&
2256 (need_to_encode == 0)) {
2257 if (((unsigned char) source->buf[i] < 32) ||
2258 ((unsigned char) source->buf[i] > 126)) {
2264 if (!need_to_encode) {
2265 if (*target == NULL) {
2266 *target = NewStrBufPlain(source->buf, source->BufUsed);
2269 FlushStrBuf(*target);
2270 StrBufAppendBuf(*target, source, 0);
2272 return (*target)->BufUsed;
2274 if (*target == NULL)
2275 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2276 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2277 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2278 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2279 (*target)->BufUsed = sizeof(headerStr) - 1;
2280 for (i=0; (i < source->BufUsed); ++i) {
2281 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2282 IncreaseBuf(*target, 1, 0);
2283 ch = (unsigned char) source->buf[i];
2284 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2285 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2286 (*target)->BufUsed += 3;
2289 (*target)->buf[(*target)->BufUsed] = ch;
2290 (*target)->BufUsed++;
2294 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2295 IncreaseBuf(*target, 1, 0);
2297 (*target)->buf[(*target)->BufUsed++] = '?';
2298 (*target)->buf[(*target)->BufUsed++] = '=';
2299 (*target)->buf[(*target)->BufUsed] = '\0';
2300 return (*target)->BufUsed;;
2304 * \brief replaces all occurances of 'search' by 'replace'
2305 * \param buf Buffer to modify
2306 * \param search character to search
2307 * \param relpace character to replace search by
2309 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2314 for (i=0; i<buf->BufUsed; i++)
2315 if (buf->buf[i] == search)
2316 buf->buf[i] = replace;
2323 * Wrapper around iconv_open()
2324 * Our version adds aliases for non-standard Microsoft charsets
2325 * such as 'MS950', aliasing them to names like 'CP950'
2327 * tocode Target encoding
2328 * fromcode Source encoding
2330 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2333 iconv_t ic = (iconv_t)(-1) ;
2334 ic = iconv_open(tocode, fromcode);
2335 if (ic == (iconv_t)(-1) ) {
2336 char alias_fromcode[64];
2337 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2338 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2339 alias_fromcode[0] = 'C';
2340 alias_fromcode[1] = 'P';
2341 ic = iconv_open(tocode, alias_fromcode);
2344 *(iconv_t *)pic = ic;
2350 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2353 /* Find the next ?Q? */
2354 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2357 end = strchr(bptr + 2, '?');
2362 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2363 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2364 (*(end + 2) == '?')) {
2365 /* skip on to the end of the cluster, the next ?= */
2366 end = strstr(end + 3, "?=");
2369 /* sort of half valid encoding, try to find an end. */
2370 end = strstr(bptr, "?=");
2375 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2380 char *ibuf; /**< Buffer of characters to be converted */
2381 char *obuf; /**< Buffer for converted characters */
2382 size_t ibuflen; /**< Length of input buffer */
2383 size_t obuflen; /**< Length of output buffer */
2386 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2387 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2389 ic = *(iconv_t*)pic;
2390 ibuf = ConvertBuf->buf;
2391 ibuflen = ConvertBuf->BufUsed;
2393 obuflen = TmpBuf->BufSize;
2395 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2397 /* little card game: wheres the red lady? */
2398 ibuf = ConvertBuf->buf;
2399 BufSize = ConvertBuf->BufSize;
2401 ConvertBuf->buf = TmpBuf->buf;
2402 ConvertBuf->BufSize = TmpBuf->BufSize;
2403 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2404 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2407 TmpBuf->BufSize = BufSize;
2408 TmpBuf->BufUsed = 0;
2409 TmpBuf->buf[0] = '\0';
2416 inline static void DecodeSegment(StrBuf *Target,
2417 const StrBuf *DecodeMe,
2421 StrBuf *ConvertBuf2,
2422 StrBuf *FoundCharset)
2428 iconv_t ic = (iconv_t)(-1);
2430 /* Now we handle foreign character sets properly encoded
2431 * in RFC2047 format.
2433 StaticBuf.buf = SegmentStart;
2434 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2435 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2436 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2437 if (FoundCharset != NULL) {
2438 FlushStrBuf(FoundCharset);
2439 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2441 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2442 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2444 *encoding = toupper(*encoding);
2445 if (*encoding == 'B') { /**< base64 */
2446 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2448 ConvertBuf->BufUsed);
2450 else if (*encoding == 'Q') { /**< quoted-printable */
2454 while (pos < ConvertBuf->BufUsed)
2456 if (ConvertBuf->buf[pos] == '_')
2457 ConvertBuf->buf[pos] = ' ';
2461 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2464 ConvertBuf->BufUsed);
2467 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2470 ctdl_iconv_open("UTF-8", charset, &ic);
2471 if (ic != (iconv_t)(-1) ) {
2473 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2474 StrBufAppendBuf(Target, ConvertBuf2, 0);
2479 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2484 * Handle subjects with RFC2047 encoding such as:
2485 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2487 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2489 StrBuf *ConvertBuf, *ConvertBuf2;
2490 char *start, *end, *next, *nextend, *ptr = NULL;
2492 iconv_t ic = (iconv_t)(-1) ;
2497 int illegal_non_rfc2047_encoding = 0;
2499 /* Sometimes, badly formed messages contain strings which were simply
2500 * written out directly in some foreign character set instead of
2501 * using RFC2047 encoding. This is illegal but we will attempt to
2502 * handle it anyway by converting from a user-specified default
2503 * charset to UTF-8 if we see any nonprintable characters.
2506 len = StrLength(DecodeMe);
2507 for (i=0; i<DecodeMe->BufUsed; ++i) {
2508 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2509 illegal_non_rfc2047_encoding = 1;
2514 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2515 if ((illegal_non_rfc2047_encoding) &&
2516 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2517 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2520 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2521 if (ic != (iconv_t)(-1) ) {
2522 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2528 /* pre evaluate the first pair */
2529 nextend = end = NULL;
2530 len = StrLength(DecodeMe);
2531 start = strstr(DecodeMe->buf, "=?");
2532 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2534 end = FindNextEnd (DecodeMe, start);
2536 StrBufAppendBuf(Target, DecodeMe, 0);
2537 FreeStrBuf(&ConvertBuf);
2541 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2543 if (start != DecodeMe->buf)
2544 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2546 * Since spammers will go to all sorts of absurd lengths to get their
2547 * messages through, there are LOTS of corrupt headers out there.
2548 * So, prevent a really badly formed RFC2047 header from throwing
2549 * this function into an infinite loop.
2551 while ((start != NULL) &&
2558 DecodeSegment(Target,
2566 next = strstr(end, "=?");
2568 if ((next != NULL) &&
2570 nextend = FindNextEnd(DecodeMe, next);
2571 if (nextend == NULL)
2574 /* did we find two partitions */
2575 if ((next != NULL) &&
2579 while ((ptr < next) &&
2585 /* did we find a gab just filled with blanks? */
2590 len - (next - start));
2592 /* now terminate the gab at the end */
2593 delta = (next - end) - 2; ////TODO: const!
2594 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2595 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2597 /* move next to its new location. */
2602 /* our next-pair is our new first pair now. */
2608 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2609 if ((end != NULL) && (end < nextend)) {
2611 while ( (ptr < nextend) &&
2618 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2620 FreeStrBuf(&ConvertBuf);
2621 FreeStrBuf(&ConvertBuf2);
2626 long StrBuf_Utf8StrLen(StrBuf *Buf)
2628 return Ctdl_Utf8StrLen(Buf->buf);
2631 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2635 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2636 if (CutAt != NULL) {
2637 Buf->BufUsed = CutAt - Buf->buf;
2638 Buf->buf[Buf->BufUsed] = '\0';
2640 return Buf->BufUsed;
2645 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2647 const char *aptr, *ptr, *eptr;
2654 ptr = aptr = Buf->buf;
2658 optr = LineBuf->buf;
2659 eptr = Buf->buf + Buf->BufUsed;
2660 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2662 while ((*ptr != '\n') &&
2669 LineBuf->BufUsed = optr - LineBuf->buf;
2670 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2671 optr = LineBuf->buf + LineBuf->BufUsed;
2672 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2675 LineBuf->BufUsed = optr - LineBuf->buf;
2684 return Buf->BufUsed - (ptr - Buf->buf);