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 = 64;
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);
123 if (KeepOriginal && (Buf->BufUsed > 0))
125 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
134 Buf->BufSize = NewSize;
138 StrBufBacktrace(Buf, 1);
145 * \brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
146 * \param Buf Buffer to shrink (has to be empty)
147 * \param ThreshHold if the buffer is bigger then this, its readjusted
148 * \param NewSize if we Shrink it, how big are we going to be afterwards?
150 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
152 if (Buf->BufUsed > ThreshHold) {
154 Buf->buf = (char*) malloc(NewSize);
156 Buf->BufSize = NewSize;
161 * \brief shrink long term buffers to their real size so they don't waste memory
162 * \param Buf buffer to shrink
163 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
164 * \returns physical size of the buffer
166 long StrBufShrinkToFit(StrBuf *Buf, int Force)
169 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
171 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
172 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
173 Buf->BufSize = Buf->BufUsed + 1;
181 * Allocate a new buffer with default buffer size
182 * \returns the new stringbuffer
184 StrBuf* NewStrBuf(void)
188 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
189 NewBuf->buf = (char*) malloc(BaseStrBufSize);
190 NewBuf->buf[0] = '\0';
191 NewBuf->BufSize = BaseStrBufSize;
193 NewBuf->ConstBuf = 0;
195 NewBuf->nIncreases = 0;
196 NewBuf->bt[0] = '\0';
197 NewBuf->bt_lastinc[0] = '\0';
199 StrBufBacktrace(NewBuf, 0);
206 * \brief Copy Constructor; returns a duplicate of CopyMe
207 * \params CopyMe Buffer to faxmilate
208 * \returns the new stringbuffer
210 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
217 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
218 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
219 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
220 NewBuf->BufUsed = CopyMe->BufUsed;
221 NewBuf->BufSize = CopyMe->BufSize;
222 NewBuf->ConstBuf = 0;
224 NewBuf->nIncreases = 0;
225 NewBuf->bt[0] = '\0';
226 NewBuf->bt_lastinc[0] = '\0';
228 StrBufBacktrace(NewBuf, 0);
235 * \brief create a new Buffer using an existing c-string
236 * this function should also be used if you want to pre-suggest
237 * the buffer size to allocate in conjunction with ptr == NULL
238 * \param ptr the c-string to copy; may be NULL to create a blank instance
239 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
240 * \returns the new stringbuffer
242 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
245 size_t Siz = BaseStrBufSize;
248 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
250 CopySize = strlen((ptr != NULL)?ptr:"");
254 while (Siz <= CopySize)
257 NewBuf->buf = (char*) malloc(Siz);
258 NewBuf->BufSize = Siz;
260 memcpy(NewBuf->buf, ptr, CopySize);
261 NewBuf->buf[CopySize] = '\0';
262 NewBuf->BufUsed = CopySize;
265 NewBuf->buf[0] = '\0';
268 NewBuf->ConstBuf = 0;
270 NewBuf->nIncreases = 0;
271 NewBuf->bt[0] = '\0';
272 NewBuf->bt_lastinc[0] = '\0';
274 StrBufBacktrace(NewBuf, 0);
281 * \brief Set an existing buffer from a c-string
282 * \param ptr c-string to put into
283 * \param nChars set to -1 if we should work 0-terminated
284 * \returns the new length of the string
286 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
288 size_t Siz = Buf->BufSize;
292 CopySize = strlen(ptr);
296 while (Siz <= CopySize)
299 if (Siz != Buf->BufSize)
300 IncreaseBuf(Buf, 0, Siz);
301 memcpy(Buf->buf, ptr, CopySize);
302 Buf->buf[CopySize] = '\0';
303 Buf->BufUsed = CopySize;
310 * \brief use strbuf as wrapper for a string constant for easy handling
311 * \param StringConstant a string to wrap
312 * \param SizeOfConstant should be sizeof(StringConstant)-1
314 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
318 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
319 NewBuf->buf = (char*) StringConstant;
320 NewBuf->BufSize = SizeOfStrConstant;
321 NewBuf->BufUsed = SizeOfStrConstant;
322 NewBuf->ConstBuf = 1;
324 NewBuf->nIncreases = 0;
325 NewBuf->bt[0] = '\0';
326 NewBuf->bt_lastinc[0] = '\0';
333 * \brief flush the content of a Buf; keep its struct
334 * \param buf Buffer to flush
336 int FlushStrBuf(StrBuf *buf)
348 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
349 * \param buf Buffer to wipe
351 int FLUSHStrBuf(StrBuf *buf)
357 if (buf->BufUsed > 0) {
358 memset(buf->buf, 0, buf->BufUsed);
365 int hFreeDbglog = -1;
368 * \brief Release a Buffer
369 * Its a double pointer, so it can NULL your pointer
370 * so fancy SIG11 appear instead of random results
371 * \param FreeMe Pointer Pointer to the buffer to free
373 void FreeStrBuf (StrBuf **FreeMe)
378 if (hFreeDbglog == -1){
379 pid_t pid = getpid();
381 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
382 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
384 if ((*FreeMe)->nIncreases > 0)
388 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
389 (*FreeMe)->nIncreases,
393 (*FreeMe)->bt_lastinc);
394 n = write(hFreeDbglog, buf, n);
400 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
403 n = write(hFreeDbglog, buf, n);
406 if (!(*FreeMe)->ConstBuf)
407 free((*FreeMe)->buf);
413 * \brief Release the buffer
414 * If you want put your StrBuf into a Hash, use this as Destructor.
415 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
417 void HFreeStrBuf (void *VFreeMe)
419 StrBuf *FreeMe = (StrBuf*)VFreeMe;
423 if (hFreeDbglog == -1){
424 pid_t pid = getpid();
426 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
427 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
429 if (FreeMe->nIncreases > 0)
433 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
439 write(hFreeDbglog, buf, n);
445 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
451 if (!FreeMe->ConstBuf)
457 * \brief Wrapper around atol
459 long StrTol(const StrBuf *Buf)
464 return atol(Buf->buf);
470 * \brief Wrapper around atoi
472 int StrToi(const StrBuf *Buf)
476 if (Buf->BufUsed > 0)
477 return atoi(Buf->buf);
483 * \brief Checks to see if the string is a pure number
485 int StrBufIsNumber(const StrBuf *Buf) {
490 strtoll(Buf->buf, &pEnd, 10);
491 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
497 * \brief modifies a Single char of the Buf
498 * You can point to it via char* or a zero-based integer
499 * \param ptr char* to zero; use NULL if unused
500 * \param nThChar zero based pointer into the string; use -1 if unused
501 * \param PeekValue The Character to place into the position
503 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
508 nThChar = ptr - Buf->buf;
509 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
511 Buf->buf[nThChar] = PeekValue;
516 * \brief Append a StringBuffer to the buffer
517 * \param Buf Buffer to modify
518 * \param AppendBuf Buffer to copy at the end of our buffer
519 * \param Offset Should we start copying from an offset?
521 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
523 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
526 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
529 AppendBuf->BufUsed + Buf->BufUsed);
531 memcpy(Buf->buf + Buf->BufUsed,
532 AppendBuf->buf + Offset,
533 AppendBuf->BufUsed - Offset);
534 Buf->BufUsed += AppendBuf->BufUsed - Offset;
535 Buf->buf[Buf->BufUsed] = '\0';
540 * \brief Append a C-String to the buffer
541 * \param Buf Buffer to modify
542 * \param AppendBuf Buffer to copy at the end of our buffer
543 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
544 * \param Offset Should we start copying from an offset?
546 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
549 long BufSizeRequired;
551 if ((AppendBuf == NULL) || (Buf == NULL))
555 aps = strlen(AppendBuf + Offset);
557 aps = AppendSize - Offset;
559 BufSizeRequired = Buf->BufUsed + aps + 1;
560 if (Buf->BufSize <= BufSizeRequired)
561 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
563 memcpy(Buf->buf + Buf->BufUsed,
567 Buf->buf[Buf->BufUsed] = '\0';
571 * \brief Callback for cURL to append the webserver reply to a buffer
572 * params pre-defined by the cURL API; see man 3 curl for mre info
574 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
583 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
589 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
590 * \param outbuf the output buffer
591 * \param oblen the size of outbuf to sanitize
592 * \param strbuf the input buffer
594 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
596 const char *pch, *pche;
599 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
600 int eclen = sizeof(ec) -1;
602 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
604 if (PlainIn != NULL) {
605 len = strlen(PlainIn);
611 pche = pch + In->BufUsed;
618 pt = OutBuf->buf + OutBuf->BufUsed;
619 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
623 IncreaseBuf(OutBuf, 1, -1);
624 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
625 pt = OutBuf->buf + OutBuf->BufUsed;
629 for (b = 0; b < eclen; ++b) {
636 sprintf(pt,"%%%02X", *pch);
638 OutBuf->BufUsed += 3;
650 * \brief Append a string, escaping characters which have meaning in HTML.
652 * \param Target target buffer
653 * \param Source source buffer; set to NULL if you just have a C-String
654 * \param PlainIn Plain-C string to append; set to NULL if unused
655 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
656 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
657 * if set to 2, linebreaks are replaced by <br/>
659 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
661 const char *aptr, *eiptr;
665 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
668 if (PlainIn != NULL) {
670 len = strlen(PlainIn);
675 eiptr = aptr + Source->BufUsed;
676 len = Source->BufUsed;
682 bptr = Target->buf + Target->BufUsed;
683 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
685 while (aptr < eiptr){
687 IncreaseBuf(Target, 1, -1);
688 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
689 bptr = Target->buf + Target->BufUsed;
692 memcpy(bptr, "<", 4);
694 Target->BufUsed += 4;
696 else if (*aptr == '>') {
697 memcpy(bptr, ">", 4);
699 Target->BufUsed += 4;
701 else if (*aptr == '&') {
702 memcpy(bptr, "&", 5);
704 Target->BufUsed += 5;
706 else if (*aptr == '"') {
707 memcpy(bptr, """, 6);
709 Target->BufUsed += 6;
711 else if (*aptr == '\'') {
712 memcpy(bptr, "'", 5);
714 Target->BufUsed += 5;
716 else if (*aptr == LB) {
721 else if (*aptr == RB) {
726 else if (*aptr == QU) {
731 else if ((*aptr == 32) && (nbsp == 1)) {
732 memcpy(bptr, " ", 6);
734 Target->BufUsed += 6;
736 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
737 *bptr='\0'; /* nothing */
739 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
740 memcpy(bptr, "<br/>", 11);
742 Target->BufUsed += 11;
746 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
747 *bptr='\0'; /* nothing */
757 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
759 return Target->BufUsed;
763 * \brief Append a string, escaping characters which have meaning in HTML.
764 * Converts linebreaks into blanks; escapes single quotes
765 * \param Target target buffer
766 * \param Source source buffer; set to NULL if you just have a C-String
767 * \param PlainIn Plain-C string to append; set to NULL if unused
769 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
771 const char *aptr, *eiptr;
775 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
778 if (PlainIn != NULL) {
780 len = strlen(PlainIn);
785 eiptr = aptr + Source->BufUsed;
786 len = Source->BufUsed;
792 eptr = Target->buf + Target->BufSize - 8;
793 tptr = Target->buf + Target->BufUsed;
795 while (aptr < eiptr){
797 IncreaseBuf(Target, 1, -1);
798 eptr = Target->buf + Target->BufSize - 8;
799 tptr = Target->buf + Target->BufUsed;
806 else if (*aptr == '\r') {
810 else if (*aptr == '\'') {
816 Target->BufUsed += 5;
829 * \brief Append a string, escaping characters which have meaning in ICAL.
831 * \param Target target buffer
832 * \param Source source buffer; set to NULL if you just have a C-String
833 * \param PlainIn Plain-C string to append; set to NULL if unused
835 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
837 const char *aptr, *eiptr;
841 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
844 if (PlainIn != NULL) {
846 len = strlen(PlainIn);
851 eiptr = aptr + Source->BufUsed;
852 len = Source->BufUsed;
858 eptr = Target->buf + Target->BufSize - 8;
859 tptr = Target->buf + Target->BufUsed;
861 while (aptr < eiptr){
862 if(tptr + 3 >= eptr) {
863 IncreaseBuf(Target, 1, -1);
864 eptr = Target->buf + Target->BufSize - 8;
865 tptr = Target->buf + Target->BufUsed;
875 else if (*aptr == '\r') {
882 else if (*aptr == ',') {
898 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
900 * \param Target target buffer
901 * \param Source source buffer; set to NULL if you just have a C-String
902 * \param PlainIn Plain-C string to append; set to NULL if unused
904 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
906 const char *aptr, *eiptr;
910 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
913 if (PlainIn != NULL) {
915 len = strlen(PlainIn);
920 eiptr = aptr + Source->BufUsed;
921 len = Source->BufUsed;
927 bptr = Target->buf + Target->BufUsed;
928 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
930 while (aptr < eiptr){
932 IncreaseBuf(Target, 1, -1);
933 eptr = Target->buf + Target->BufSize - 3;
934 bptr = Target->buf + Target->BufUsed;
941 Target->BufUsed += 2;
942 } else if (*aptr == '\\') {
947 Target->BufUsed += 2;
957 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
959 return Target->BufUsed;
963 * \brief extracts a substring from Source into dest
964 * \param dest buffer to place substring into
965 * \param Source string to copy substring from
966 * \param Offset chars to skip from start
967 * \param nChars number of chars to copy
968 * \returns the number of chars copied; may be different from nChars due to the size of Source
970 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
973 if (Offset > Source->BufUsed)
978 if (Offset + nChars < Source->BufUsed)
980 if (nChars >= dest->BufSize)
981 IncreaseBuf(dest, 0, nChars + 1);
982 memcpy(dest->buf, Source->buf + Offset, nChars);
983 dest->BufUsed = nChars;
984 dest->buf[dest->BufUsed] = '\0';
987 NCharsRemain = Source->BufUsed - Offset;
988 if (NCharsRemain >= dest->BufSize)
989 IncreaseBuf(dest, 0, NCharsRemain + 1);
990 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
991 dest->BufUsed = NCharsRemain;
992 dest->buf[dest->BufUsed] = '\0';
997 * \brief sprintf like function appending the formated string to the buffer
998 * vsnprintf version to wrap into own calls
999 * \param Buf Buffer to extend by format and params
1000 * \param format printf alike format to add
1001 * \param ap va_list containing the items for format
1003 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1006 size_t BufSize = Buf->BufSize;
1007 size_t nWritten = Buf->BufSize + 1;
1008 size_t Offset = Buf->BufUsed;
1009 size_t newused = Offset + nWritten;
1011 while (newused >= BufSize) {
1013 nWritten = vsnprintf(Buf->buf + Offset,
1014 Buf->BufSize - Offset,
1017 newused = Offset + nWritten;
1018 if (newused >= Buf->BufSize) {
1019 IncreaseBuf(Buf, 1, newused);
1020 newused = Buf->BufSize + 1;
1023 Buf->BufUsed = Offset + nWritten;
1024 BufSize = Buf->BufSize;
1031 * \brief sprintf like function appending the formated string to the buffer
1032 * \param Buf Buffer to extend by format and params
1033 * \param format printf alike format to add
1034 * \param ap va_list containing the items for format
1036 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1038 size_t BufSize = Buf->BufSize;
1039 size_t nWritten = Buf->BufSize + 1;
1040 size_t Offset = Buf->BufUsed;
1041 size_t newused = Offset + nWritten;
1044 while (newused >= BufSize) {
1045 va_start(arg_ptr, format);
1046 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1047 Buf->BufSize - Buf->BufUsed,
1050 newused = Buf->BufUsed + nWritten;
1051 if (newused >= Buf->BufSize) {
1052 IncreaseBuf(Buf, 1, newused);
1053 newused = Buf->BufSize + 1;
1056 Buf->BufUsed += nWritten;
1057 BufSize = Buf->BufSize;
1064 * \brief sprintf like function putting the formated string into the buffer
1065 * \param Buf Buffer to extend by format and params
1066 * \param format printf alike format to add
1067 * \param ap va_list containing the items for format
1069 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1071 size_t nWritten = Buf->BufSize + 1;
1074 while (nWritten >= Buf->BufSize) {
1075 va_start(arg_ptr, format);
1076 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1078 if (nWritten >= Buf->BufSize) {
1079 IncreaseBuf(Buf, 0, 0);
1080 nWritten = Buf->BufSize + 1;
1083 Buf->BufUsed = nWritten ;
1089 * \brief Counts the numbmer of tokens in a buffer
1090 * \param Source String to count tokens in
1091 * \param tok Tokenizer char to count
1092 * \returns numbers of tokenizer chars found
1094 int StrBufNum_tokens(const StrBuf *source, char tok)
1098 return num_tokens(source->buf, tok);
1102 * remove_token() - a tokenizer that kills, maims, and destroys
1105 * \brief a string tokenizer
1106 * \param Source StringBuffer to read into
1107 * \param parmnum n'th parameter to remove
1108 * \param separator tokenizer param
1109 * \returns -1 if not found, else length of token.
1111 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1114 char *d, *s; /* dest, source */
1117 /* Find desired parameter */
1119 while (count < parmnum) {
1120 /* End of string, bail! */
1125 if (*d == separator) {
1130 if (!d) return 0; /* Parameter not found */
1132 /* Find next parameter */
1134 while (*s && *s != separator) {
1137 if (*s == separator)
1141 /* Hack and slash */
1143 memmove(d, s, Source->BufUsed - (s - Source->buf));
1144 Source->BufUsed += ReducedBy;
1146 else if (d == Source->buf) {
1148 Source->BufUsed = 0;
1152 Source->BufUsed += ReducedBy;
1165 * \brief a string tokenizer
1166 * \param dest Destination StringBuffer
1167 * \param Source StringBuffer to read into
1168 * \param parmnum n'th parameter to extract
1169 * \param separator tokenizer param
1170 * \returns -1 if not found, else length of token.
1172 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1174 const char *s, *e; //* source * /
1175 int len = 0; //* running total length of extracted string * /
1176 int current_token = 0; //* token currently being processed * /
1179 dest->buf[0] = '\0';
1185 if ((Source == NULL) || (Source->BufUsed ==0)) {
1189 e = s + Source->BufUsed;
1192 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1194 while ((s<e) && !IsEmptyStr(s)) {
1195 if (*s == separator) {
1198 if (len >= dest->BufSize) {
1199 dest->BufUsed = len;
1200 if (IncreaseBuf(dest, 1, -1) < 0) {
1205 if ( (current_token == parmnum) &&
1206 (*s != separator)) {
1207 dest->buf[len] = *s;
1210 else if (current_token > parmnum) {
1216 dest->buf[len] = '\0';
1217 dest->BufUsed = len;
1219 if (current_token < parmnum) {
1220 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1223 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1232 * \brief a string tokenizer to fetch an integer
1233 * \param dest Destination StringBuffer
1234 * \param parmnum n'th parameter to extract
1235 * \param separator tokenizer param
1236 * \returns 0 if not found, else integer representation of the token
1238 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1248 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1255 * \brief a string tokenizer to fetch a long integer
1256 * \param dest Destination StringBuffer
1257 * \param parmnum n'th parameter to extract
1258 * \param separator tokenizer param
1259 * \returns 0 if not found, else long integer representation of the token
1261 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1271 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1279 * \brief a string tokenizer to fetch an unsigned long
1280 * \param dest Destination StringBuffer
1281 * \param parmnum n'th parameter to extract
1282 * \param separator tokenizer param
1283 * \returns 0 if not found, else unsigned long representation of the token
1285 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1296 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1300 return (unsigned long) atol(pnum);
1309 * \briefa string tokenizer; Bounds checker
1310 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1311 * \param Source our tokenbuffer
1312 * \param pStart the token iterator pointer to inspect
1313 * \returns whether the revolving pointer is inside of the search range
1315 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1317 const char *Null = NULL;
1319 if ((Source == NULL) || (*pStart == Null))
1321 if (*pStart == NULL)
1323 else if (*pStart >= Source->buf + Source->BufUsed)
1325 else if (*pStart <= Source->buf)
1331 * \brief a string tokenizer
1332 * \param dest Destination StringBuffer
1333 * \param Source StringBuffer to read into
1334 * \param pStart pointer to the end of the last token. Feed with NULL on start.
1335 * \param separator tokenizer param
1336 * \returns -1 if not found, else length of token.
1338 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1340 const char *s; /* source */
1341 const char *EndBuffer; /* end stop of source buffer */
1342 int current_token = 0; /* token currently being processed */
1343 int len = 0; /* running total length of extracted string */
1345 if ((Source == NULL) ||
1346 (Source->BufUsed == 0) )
1349 (*pStart) --; /* move it to the end of all being via underflow */
1353 EndBuffer = Source->buf + Source->BufUsed;
1357 dest->buf[0] = '\0';
1362 *pStart = EndBuffer + 1;
1366 if (*pStart == NULL)
1368 *pStart = Source->buf; /* we're starting to examine this buffer. */
1370 else if ((*pStart < Source->buf) ||
1371 (*pStart > EndBuffer ) )
1373 return -1; /* no more tokens to find. */
1377 /* start to find the next token */
1378 while ((s < EndBuffer) && !IsEmptyStr(s))
1380 if (*s == separator)
1382 /* we found the next token */
1386 if (len >= dest->BufSize)
1388 /* our Dest-buffer isn't big enough, increase it. */
1389 dest->BufUsed = len;
1391 if (IncreaseBuf(dest, 1, -1) < 0) {
1392 /* WHUT? no more mem? bail out. */
1399 if ( (current_token == 0 ) && /* are we in our target token? */
1400 (separator != *s) ) /* don't copy the token itself */
1402 dest->buf[len] = *s; /* Copy the payload */
1403 ++len; /* remember the bigger size. */
1409 /* did we reach a \0 ? */
1410 if ((s >= EndBuffer) || IsEmptyStr(s)) {
1411 *pStart = EndBuffer + 1;
1414 *pStart = s; /* remember the position for the next run */
1415 (*pStart) ++; /* move behind the next token separator so
1416 * we don't see it next time */
1419 /* sanitize our extracted token */
1420 dest->buf[len] = '\0';
1421 dest->BufUsed = len;
1428 * \brief a string tokenizer
1429 * \param dest Destination StringBuffer
1430 * \param Source StringBuffer to read into
1431 * \param pStart pointer to the end of the last token. Feed with NULL.
1432 * \param separator tokenizer param
1433 * \returns -1 if not found, else length of token.
1435 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1437 const char *s, *EndBuffer; //* source * /
1438 int len = 0; //* running total length of extracted string * /
1439 int current_token = 0; //* token currently being processed * /
1441 if ((Source == NULL) ||
1442 (Source->BufUsed ==0)) {
1446 return Source->BufUsed;
1448 if (*pStart == NULL)
1449 *pStart = Source->buf;
1451 EndBuffer = Source->buf + Source->BufUsed;
1453 if ((*pStart < Source->buf) ||
1454 (*pStart > EndBuffer)) {
1462 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1464 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1465 if (*s == separator) {
1468 if (current_token >= nTokens) {
1480 * \brief a string tokenizer to fetch an integer
1481 * \param dest Destination StringBuffer
1482 * \param parmnum n'th parameter to extract
1483 * \param separator tokenizer param
1484 * \returns 0 if not found, else integer representation of the token
1486 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1496 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1503 * \brief a string tokenizer to fetch a long integer
1504 * \param dest Destination StringBuffer
1505 * \param parmnum n'th parameter to extract
1506 * \param separator tokenizer param
1507 * \returns 0 if not found, else long integer representation of the token
1509 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1519 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1527 * \brief a string tokenizer to fetch an unsigned long
1528 * \param dest Destination StringBuffer
1529 * \param parmnum n'th parameter to extract
1530 * \param separator tokenizer param
1531 * \returns 0 if not found, else unsigned long representation of the token
1533 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1544 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1548 return (unsigned long) atol(pnum);
1557 * \brief Read a line from socket
1558 * flushes and closes the FD on error
1559 * \param buf the buffer to get the input to
1560 * \param fd pointer to the filedescriptor to read
1561 * \param append Append to an existing string or replace?
1562 * \param Error strerror() on error
1563 * \returns numbers of chars read
1565 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1567 int len, rlen, slen;
1572 slen = len = buf->BufUsed;
1574 rlen = read(*fd, &buf->buf[len], 1);
1576 *Error = strerror(errno);
1583 if (buf->buf[len] == '\n')
1585 if (buf->buf[len] != '\r')
1587 if (len >= buf->BufSize) {
1589 buf->buf[len+1] = '\0';
1590 IncreaseBuf(buf, 1, -1);
1594 buf->buf[len] = '\0';
1599 * \brief Read a line from socket
1600 * flushes and closes the FD on error
1601 * \param buf the buffer to get the input to
1602 * \param fd pointer to the filedescriptor to read
1603 * \param append Append to an existing string or replace?
1604 * \param Error strerror() on error
1605 * \returns numbers of chars read
1607 int StrBufTCP_read_buffered_line(StrBuf *Line,
1611 int selectresolution,
1615 int nSuccessLess = 0;
1621 if (buf->BufUsed > 0) {
1622 pch = strchr(buf->buf, '\n');
1625 len = pch - buf->buf;
1626 if (len > 0 && (*(pch - 1) == '\r') )
1628 StrBufSub(Line, buf, 0, len - rlen);
1629 StrBufCutLeft(buf, len + 1);
1634 if (buf->BufSize - buf->BufUsed < 10)
1635 IncreaseBuf(buf, 1, -1);
1637 fdflags = fcntl(*fd, F_GETFL);
1638 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1641 while ((nSuccessLess < timeout) && (pch == NULL)) {
1642 tv.tv_sec = selectresolution;
1647 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1648 *Error = strerror(errno);
1653 if (FD_ISSET(*fd, &rfds)) {
1655 &buf->buf[buf->BufUsed],
1656 buf->BufSize - buf->BufUsed - 1);
1658 *Error = strerror(errno);
1663 else if (rlen > 0) {
1665 buf->BufUsed += rlen;
1666 buf->buf[buf->BufUsed] = '\0';
1667 if (buf->BufUsed + 10 > buf->BufSize) {
1668 IncreaseBuf(buf, 1, -1);
1670 pch = strchr(buf->buf, '\n');
1678 len = pch - buf->buf;
1679 if (len > 0 && (*(pch - 1) == '\r') )
1681 StrBufSub(Line, buf, 0, len - rlen);
1682 StrBufCutLeft(buf, len + 1);
1689 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1690 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1691 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1693 * \brief Read a line from socket
1694 * flushes and closes the FD on error
1695 * \param buf the buffer to get the input to
1696 * \param Pos pointer to the current read position, should be NULL initialized!
1697 * \param fd pointer to the filedescriptor to read
1698 * \param append Append to an existing string or replace?
1699 * \param Error strerror() on error
1700 * \returns numbers of chars read
1702 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1707 int selectresolution,
1710 const char *pche = NULL;
1711 const char *pos = NULL;
1713 int nSuccessLess = 0;
1715 const char *pch = NULL;
1720 if ((IOBuf->BufUsed > 0) &&
1722 (pos < IOBuf->buf + IOBuf->BufUsed))
1724 pche = IOBuf->buf + IOBuf->BufUsed;
1726 while ((pch < pche) && (*pch != '\n'))
1728 if ((pch >= pche) || (*pch == '\0'))
1730 if ((pch != NULL) &&
1735 if (len > 0 && (*(pch - 1) == '\r') )
1737 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1747 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1751 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1752 IncreaseBuf(IOBuf, 1, -1);
1755 fdflags = fcntl(*fd, F_GETFL);
1756 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1757 *Error = ErrRBLF_WrongFDFlags;
1762 while ((nSuccessLess < timeout) && (pch == NULL)) {
1763 tv.tv_sec = selectresolution;
1768 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1769 *Error = strerror(errno);
1773 *Error = ErrRBLF_SelectFailed;
1776 if (FD_ISSET(*fd, &rfds) != 0) {
1778 &IOBuf->buf[IOBuf->BufUsed],
1779 IOBuf->BufSize - IOBuf->BufUsed - 1);
1781 *Error = strerror(errno);
1786 else if (rlen > 0) {
1788 IOBuf->BufUsed += rlen;
1789 IOBuf->buf[IOBuf->BufUsed] = '\0';
1790 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1791 IncreaseBuf(IOBuf, 1, -1);
1794 pche = IOBuf->buf + IOBuf->BufUsed;
1796 while ((pch < pche) && (*pch != '\n'))
1798 if ((pch >= pche) || (*pch == '\0'))
1809 if (len > 0 && (*(pch - 1) == '\r') )
1811 StrBufSub(Line, IOBuf, 0, len - rlen);
1812 *Pos = pos + len + 1;
1815 *Error = ErrRBLF_NotEnoughSentFromServer;
1821 * \brief Input binary data from socket
1822 * flushes and closes the FD on error
1823 * \param buf the buffer to get the input to
1824 * \param fd pointer to the filedescriptor to read
1825 * \param append Append to an existing string or replace?
1826 * \param nBytes the maximal number of bytes to read
1827 * \param Error strerror() on error
1828 * \returns numbers of chars read
1830 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1834 int len, rlen, slen;
1838 if ((Buf == NULL) || (*fd == -1))
1842 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1843 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1845 ptr = Buf->buf + Buf->BufUsed;
1847 slen = len = Buf->BufUsed;
1849 fdflags = fcntl(*fd, F_GETFL);
1851 while (nRead < nBytes) {
1852 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1855 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1856 *Error = strerror(errno);
1861 if ((rlen = read(*fd,
1863 nBytes - nRead)) == -1) {
1866 *Error = strerror(errno);
1871 Buf->BufUsed += rlen;
1873 Buf->buf[Buf->BufUsed] = '\0';
1877 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1879 * \brief Input binary data from socket
1880 * flushes and closes the FD on error
1881 * \param buf the buffer to get the input to
1882 * \param fd pointer to the filedescriptor to read
1883 * \param append Append to an existing string or replace?
1884 * \param nBytes the maximal number of bytes to read
1885 * \param Error strerror() on error
1886 * \returns numbers of chars read
1888 int StrBufReadBLOBBuffered(StrBuf *Blob,
1909 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1913 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1914 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1919 len = pos - IOBuf->buf;
1920 rlen = IOBuf->BufUsed - len;
1923 if ((IOBuf->BufUsed > 0) &&
1925 (pos < IOBuf->buf + IOBuf->BufUsed))
1927 pche = IOBuf->buf + IOBuf->BufUsed;
1930 if (rlen < nBytes) {
1931 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1932 Blob->BufUsed += rlen;
1933 Blob->buf[Blob->BufUsed] = '\0';
1937 if (rlen >= nBytes) {
1938 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1939 Blob->BufUsed += nBytes;
1940 Blob->buf[Blob->BufUsed] = '\0';
1941 if (rlen == nBytes) {
1952 if (IOBuf->BufSize < nBytes - nRead)
1953 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1956 slen = len = Blob->BufUsed;
1958 fdflags = fcntl(*fd, F_GETFL);
1963 while (nRead < nBytes) {
1964 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1967 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1970 *Error = strerror(errno);
1981 *Error = strerror(errno);
1987 if ((check == NNN_TERM) &&
1989 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1991 StrBufPlain(Blob, HKEY("\n000\n"));
1992 StrBufCutRight(Blob, 5);
1993 return Blob->BufUsed;
1995 if (nSelects > 10) {
1997 *Error = ErrRBB_too_many_selects;
2004 IOBuf->BufUsed += rlen;
2007 if (nRead > nBytes) {
2008 *Pos = IOBuf->buf + nBytes;
2010 Blob->buf[Blob->BufUsed] = '\0';
2011 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2016 * \brief Cut nChars from the start of the string
2017 * \param Buf Buffer to modify
2018 * \param nChars how many chars should be skipped?
2020 void StrBufCutLeft(StrBuf *Buf, int nChars)
2022 if (nChars >= Buf->BufUsed) {
2026 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2027 Buf->BufUsed -= nChars;
2028 Buf->buf[Buf->BufUsed] = '\0';
2032 * \brief Cut the trailing n Chars from the string
2033 * \param Buf Buffer to modify
2034 * \param nChars how many chars should be trunkated?
2036 void StrBufCutRight(StrBuf *Buf, int nChars)
2038 if (nChars >= Buf->BufUsed) {
2042 Buf->BufUsed -= nChars;
2043 Buf->buf[Buf->BufUsed] = '\0';
2047 * \brief Cut the string after n Chars
2048 * \param Buf Buffer to modify
2049 * \param AfternChars after how many chars should we trunkate the string?
2050 * \param At if non-null and points inside of our string, cut it there.
2052 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2055 AfternChars = At - Buf->buf;
2058 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2060 Buf->BufUsed = AfternChars;
2061 Buf->buf[Buf->BufUsed] = '\0';
2066 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2067 * buf - the string to modify
2068 * len - length of the string.
2070 void StrBufTrim(StrBuf *Buf)
2073 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2075 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2078 if (delta > 0) StrBufCutLeft(Buf, delta);
2080 if (Buf->BufUsed == 0) return;
2081 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2084 Buf->buf[Buf->BufUsed] = '\0';
2088 void StrBufUpCase(StrBuf *Buf)
2093 pche = pch + Buf->BufUsed;
2094 while (pch < pche) {
2095 *pch = toupper(*pch);
2101 void StrBufLowerCase(StrBuf *Buf)
2106 pche = pch + Buf->BufUsed;
2107 while (pch < pche) {
2108 *pch = tolower(*pch);
2114 * \Brief removes double slashes from pathnames
2115 * \param Dir directory string to filter
2116 * \param RemoveTrailingSlash allows / disallows trailing slashes
2118 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2124 while (!IsEmptyStr(a)) {
2136 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2141 Dir->BufUsed = b - Dir->buf;
2145 * \brief unhide special chars hidden to the HTML escaper
2146 * \param target buffer to put the unescaped string in
2147 * \param source buffer to unescape
2149 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2155 FlushStrBuf(target);
2157 if (source == NULL ||target == NULL)
2162 len = source->BufUsed;
2163 for (a = 0; a < len; ++a) {
2164 if (target->BufUsed >= target->BufSize)
2165 IncreaseBuf(target, 1, -1);
2167 if (source->buf[a] == '=') {
2168 hex[0] = source->buf[a + 1];
2169 hex[1] = source->buf[a + 2];
2172 sscanf(hex, "%02x", &b);
2173 target->buf[target->BufUsed] = b;
2174 target->buf[++target->BufUsed] = 0;
2178 target->buf[target->BufUsed] = source->buf[a];
2179 target->buf[++target->BufUsed] = 0;
2186 * \brief hide special chars from the HTML escapers and friends
2187 * \param target buffer to put the escaped string in
2188 * \param source buffer to escape
2190 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2195 FlushStrBuf(target);
2197 if (source == NULL ||target == NULL)
2202 len = source->BufUsed;
2203 for (i=0; i<len; ++i) {
2204 if (target->BufUsed + 4 >= target->BufSize)
2205 IncreaseBuf(target, 1, -1);
2206 if ( (isalnum(source->buf[i])) ||
2207 (source->buf[i]=='-') ||
2208 (source->buf[i]=='_') ) {
2209 target->buf[target->BufUsed++] = source->buf[i];
2212 sprintf(&target->buf[target->BufUsed],
2214 (0xFF &source->buf[i]));
2215 target->BufUsed += 3;
2218 target->buf[target->BufUsed + 1] = '\0';
2222 * \brief uses the same calling syntax as compress2(), but it
2223 * creates a stream compatible with HTTP "Content-encoding: gzip"
2226 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2227 #define OS_CODE 0x03 /*< unix */
2228 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2229 size_t * destLen, /*< length of the compresed data */
2230 const Bytef * source, /*< source to encode */
2231 uLong sourceLen, /*< length of source to encode */
2232 int level) /*< compression level */
2234 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2236 /* write gzip header */
2237 snprintf((char *) dest, *destLen,
2238 "%c%c%c%c%c%c%c%c%c%c",
2239 gz_magic[0], gz_magic[1], Z_DEFLATED,
2240 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2243 /* normal deflate */
2246 stream.next_in = (Bytef *) source;
2247 stream.avail_in = (uInt) sourceLen;
2248 stream.next_out = dest + 10L; // after header
2249 stream.avail_out = (uInt) * destLen;
2250 if ((uLong) stream.avail_out != *destLen)
2253 stream.zalloc = (alloc_func) 0;
2254 stream.zfree = (free_func) 0;
2255 stream.opaque = (voidpf) 0;
2257 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2258 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2262 err = deflate(&stream, Z_FINISH);
2263 if (err != Z_STREAM_END) {
2264 deflateEnd(&stream);
2265 return err == Z_OK ? Z_BUF_ERROR : err;
2267 *destLen = stream.total_out + 10L;
2269 /* write CRC and Length */
2270 uLong crc = crc32(0L, source, sourceLen);
2272 for (n = 0; n < 4; ++n, ++*destLen) {
2273 dest[*destLen] = (int) (crc & 0xff);
2276 uLong len = stream.total_in;
2277 for (n = 0; n < 4; ++n, ++*destLen) {
2278 dest[*destLen] = (int) (len & 0xff);
2281 err = deflateEnd(&stream);
2288 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2290 int CompressBuffer(StrBuf *Buf)
2293 char *compressed_data = NULL;
2294 size_t compressed_len, bufsize;
2297 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2298 compressed_data = malloc(compressed_len);
2300 if (compressed_data == NULL)
2302 /* Flush some space after the used payload so valgrind shuts up... */
2303 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2304 Buf->buf[Buf->BufUsed + i++] = '\0';
2305 if (compress_gzip((Bytef *) compressed_data,
2308 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2311 Buf->buf = compressed_data;
2312 Buf->BufUsed = compressed_len;
2313 Buf->BufSize = bufsize;
2314 /* Flush some space after the used payload so valgrind shuts up... */
2316 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2317 Buf->buf[Buf->BufUsed + i++] = '\0';
2320 free(compressed_data);
2322 #endif /* HAVE_ZLIB */
2327 * \brief decode a buffer from base 64 encoding; destroys original
2328 * \param Buf Buffor to transform
2330 int StrBufDecodeBase64(StrBuf *Buf)
2334 if (Buf == NULL) return -1;
2336 xferbuf = (char*) malloc(Buf->BufSize);
2337 siz = CtdlDecodeBase64(xferbuf,
2347 * \brief decode a buffer from base 64 encoding; destroys original
2348 * \param Buf Buffor to transform
2350 int StrBufDecodeHex(StrBuf *Buf)
2353 char *pch, *pche, *pchi;
2355 if (Buf == NULL) return -1;
2357 pch = pchi = Buf->buf;
2358 pche = pch + Buf->BufUsed;
2360 while (pchi < pche){
2361 ch = decode_hex(pchi);
2368 Buf->BufUsed = pch - Buf->buf;
2369 return Buf->BufUsed;
2373 * \brief replace all chars >0x20 && < 0x7F with Mute
2374 * \param Mute char to put over invalid chars
2375 * \param Buf Buffor to transform
2377 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2381 if (Buf == NULL) return -1;
2382 pch = (unsigned char *)Buf->buf;
2383 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2384 if ((*pch < 0x20) || (*pch > 0x7F))
2388 return Buf->BufUsed;
2393 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2394 * \param Buf Buffer to translate
2395 * \param StripBlanks Reduce several blanks to one?
2397 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2403 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2404 Buf->buf[Buf->BufUsed - 1] = '\0';
2409 while (a < Buf->BufUsed) {
2410 if (Buf->buf[a] == '+')
2412 else if (Buf->buf[a] == '%') {
2413 /* don't let % chars through, rather truncate the input. */
2414 if (a + 2 > Buf->BufUsed) {
2419 hex[0] = Buf->buf[a + 1];
2420 hex[1] = Buf->buf[a + 2];
2423 sscanf(hex, "%02x", &b);
2424 Buf->buf[a] = (char) b;
2425 len = Buf->BufUsed - a - 2;
2427 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2439 * \brief RFC2047-encode a header field if necessary.
2440 * If no non-ASCII characters are found, the string
2441 * will be copied verbatim without encoding.
2443 * \param target Target buffer.
2444 * \param source Source string to be encoded.
2445 * \returns encoded length; -1 if non success.
2447 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2449 const char headerStr[] = "=?UTF-8?Q?";
2450 int need_to_encode = 0;
2454 if ((source == NULL) ||
2458 while ((i < source->BufUsed) &&
2459 (!IsEmptyStr (&source->buf[i])) &&
2460 (need_to_encode == 0)) {
2461 if (((unsigned char) source->buf[i] < 32) ||
2462 ((unsigned char) source->buf[i] > 126)) {
2468 if (!need_to_encode) {
2469 if (*target == NULL) {
2470 *target = NewStrBufPlain(source->buf, source->BufUsed);
2473 FlushStrBuf(*target);
2474 StrBufAppendBuf(*target, source, 0);
2476 return (*target)->BufUsed;
2478 if (*target == NULL)
2479 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2480 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2481 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2482 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2483 (*target)->BufUsed = sizeof(headerStr) - 1;
2484 for (i=0; (i < source->BufUsed); ++i) {
2485 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2486 IncreaseBuf(*target, 1, 0);
2487 ch = (unsigned char) source->buf[i];
2488 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2489 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2490 (*target)->BufUsed += 3;
2493 (*target)->buf[(*target)->BufUsed] = ch;
2494 (*target)->BufUsed++;
2498 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2499 IncreaseBuf(*target, 1, 0);
2501 (*target)->buf[(*target)->BufUsed++] = '?';
2502 (*target)->buf[(*target)->BufUsed++] = '=';
2503 (*target)->buf[(*target)->BufUsed] = '\0';
2504 return (*target)->BufUsed;;
2508 * \brief replaces all occurances of 'search' by 'replace'
2509 * \param buf Buffer to modify
2510 * \param search character to search
2511 * \param relpace character to replace search by
2513 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2518 for (i=0; i<buf->BufUsed; i++)
2519 if (buf->buf[i] == search)
2520 buf->buf[i] = replace;
2527 * Wrapper around iconv_open()
2528 * Our version adds aliases for non-standard Microsoft charsets
2529 * such as 'MS950', aliasing them to names like 'CP950'
2531 * tocode Target encoding
2532 * fromcode Source encoding
2534 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2537 iconv_t ic = (iconv_t)(-1) ;
2538 ic = iconv_open(tocode, fromcode);
2539 if (ic == (iconv_t)(-1) ) {
2540 char alias_fromcode[64];
2541 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2542 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2543 alias_fromcode[0] = 'C';
2544 alias_fromcode[1] = 'P';
2545 ic = iconv_open(tocode, alias_fromcode);
2548 *(iconv_t *)pic = ic;
2554 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2557 /* Find the next ?Q? */
2558 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2561 end = strchr(bptr + 2, '?');
2566 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2567 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2568 (*(end + 2) == '?')) {
2569 /* skip on to the end of the cluster, the next ?= */
2570 end = strstr(end + 3, "?=");
2573 /* sort of half valid encoding, try to find an end. */
2574 end = strstr(bptr, "?=");
2578 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2582 memcpy(&C, A, sizeof(*A));
2583 memcpy(A, B, sizeof(*B));
2584 memcpy(B, &C, sizeof(C));
2588 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2594 char *ibuf; /**< Buffer of characters to be converted */
2595 char *obuf; /**< Buffer for converted characters */
2596 size_t ibuflen; /**< Length of input buffer */
2597 size_t obuflen; /**< Length of output buffer */
2600 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2601 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2602 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2604 ic = *(iconv_t*)pic;
2605 ibuf = ConvertBuf->buf;
2606 ibuflen = ConvertBuf->BufUsed;
2608 obuflen = TmpBuf->BufSize;
2610 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2613 if (errno == E2BIG) {
2615 IncreaseBuf(TmpBuf, 0, 0);
2620 else if (errno == EILSEQ){
2621 /* hm, invalid utf8 sequence... what to do now? */
2622 /* An invalid multibyte sequence has been encountered in the input */
2624 else if (errno == EINVAL) {
2625 /* An incomplete multibyte sequence has been encountered in the input. */
2628 FlushStrBuf(TmpBuf);
2631 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2632 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2634 /* little card game: wheres the red lady? */
2635 SwapBuffers(ConvertBuf, TmpBuf);
2636 FlushStrBuf(TmpBuf);
2644 inline static void DecodeSegment(StrBuf *Target,
2645 const StrBuf *DecodeMe,
2649 StrBuf *ConvertBuf2,
2650 StrBuf *FoundCharset)
2656 iconv_t ic = (iconv_t)(-1);
2658 /* Now we handle foreign character sets properly encoded
2659 * in RFC2047 format.
2661 StaticBuf.buf = SegmentStart;
2662 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2663 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2664 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2665 if (FoundCharset != NULL) {
2666 FlushStrBuf(FoundCharset);
2667 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2669 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2670 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2672 *encoding = toupper(*encoding);
2673 if (*encoding == 'B') { /**< base64 */
2674 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2676 ConvertBuf->BufUsed);
2678 else if (*encoding == 'Q') { /**< quoted-printable */
2682 while (pos < ConvertBuf->BufUsed)
2684 if (ConvertBuf->buf[pos] == '_')
2685 ConvertBuf->buf[pos] = ' ';
2689 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2692 ConvertBuf->BufUsed);
2695 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2698 ctdl_iconv_open("UTF-8", charset, &ic);
2699 if (ic != (iconv_t)(-1) ) {
2701 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2702 StrBufAppendBuf(Target, ConvertBuf2, 0);
2707 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2712 * Handle subjects with RFC2047 encoding such as:
2713 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2715 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2717 StrBuf *ConvertBuf, *ConvertBuf2;
2718 char *start, *end, *next, *nextend, *ptr = NULL;
2720 iconv_t ic = (iconv_t)(-1) ;
2725 int illegal_non_rfc2047_encoding = 0;
2727 /* Sometimes, badly formed messages contain strings which were simply
2728 * written out directly in some foreign character set instead of
2729 * using RFC2047 encoding. This is illegal but we will attempt to
2730 * handle it anyway by converting from a user-specified default
2731 * charset to UTF-8 if we see any nonprintable characters.
2734 len = StrLength(DecodeMe);
2735 for (i=0; i<DecodeMe->BufUsed; ++i) {
2736 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2737 illegal_non_rfc2047_encoding = 1;
2742 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2743 if ((illegal_non_rfc2047_encoding) &&
2744 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2745 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2748 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2749 if (ic != (iconv_t)(-1) ) {
2750 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2756 /* pre evaluate the first pair */
2757 nextend = end = NULL;
2758 len = StrLength(DecodeMe);
2759 start = strstr(DecodeMe->buf, "=?");
2760 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2762 end = FindNextEnd (DecodeMe, start);
2764 StrBufAppendBuf(Target, DecodeMe, 0);
2765 FreeStrBuf(&ConvertBuf);
2769 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2771 if (start != DecodeMe->buf) {
2774 nFront = start - DecodeMe->buf;
2775 StrBufAppendBufPlain(Target, DecodeMe->buf, nFront, 0);
2779 * Since spammers will go to all sorts of absurd lengths to get their
2780 * messages through, there are LOTS of corrupt headers out there.
2781 * So, prevent a really badly formed RFC2047 header from throwing
2782 * this function into an infinite loop.
2784 while ((start != NULL) &&
2791 DecodeSegment(Target,
2799 next = strstr(end, "=?");
2801 if ((next != NULL) &&
2803 nextend = FindNextEnd(DecodeMe, next);
2804 if (nextend == NULL)
2807 /* did we find two partitions */
2808 if ((next != NULL) &&
2812 while ((ptr < next) &&
2818 /* did we find a gab just filled with blanks? */
2821 long gap = next - start;
2826 /* now terminate the gab at the end */
2827 delta = (next - end) - 2; ////TODO: const!
2828 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2829 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2831 /* move next to its new location. */
2836 /* our next-pair is our new first pair now. */
2842 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2843 if ((end != NULL) && (end < nextend)) {
2845 while ( (ptr < nextend) &&
2852 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2854 FreeStrBuf(&ConvertBuf);
2855 FreeStrBuf(&ConvertBuf2);
2859 * \brief evaluate the length of an utf8 special character sequence
2860 * \param Char the character to examine
2861 * \returns width of utf8 chars in bytes
2863 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2868 while ((n < 8) && ((test & *CharS) != 0)) {
2872 if ((n > 6) || ((CharE - CharS) > n))
2878 * \brief detect whether this char starts an utf-8 encoded char
2879 * \param Char character to inspect
2880 * \returns yes or no
2882 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2884 /** 11??.???? indicates an UTF8 Sequence. */
2885 return ((Char & 0xC0) != 0);
2889 * \brief measure the number of glyphs in an UTF8 string...
2890 * \param str string to measure
2891 * \returns the length of str
2893 long StrBuf_Utf8StrLen(StrBuf *Buf)
2899 if ((Buf == NULL) || (Buf->BufUsed == 0))
2902 eptr = Buf->buf + Buf->BufUsed;
2903 while ((aptr < eptr) && (*aptr != '\0')) {
2904 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2905 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2906 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2919 * \brief cuts a string after maxlen glyphs
2920 * \param str string to cut to maxlen glyphs
2921 * \param maxlen how long may the string become?
2922 * \returns pointer to maxlen or the end of the string
2924 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2930 eptr = Buf->buf + Buf->BufUsed;
2931 while ((aptr < eptr) && (*aptr != '\0')) {
2932 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2933 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2934 while ((m-- > 0) && (*aptr++ != '\0'))
2943 Buf->BufUsed = aptr - Buf->buf;
2944 return Buf->BufUsed;
2947 return Buf->BufUsed;
2953 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2955 const char *aptr, *ptr, *eptr;
2962 ptr = aptr = Buf->buf;
2966 optr = LineBuf->buf;
2967 eptr = Buf->buf + Buf->BufUsed;
2968 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2970 while ((*ptr != '\n') &&
2977 LineBuf->BufUsed = optr - LineBuf->buf;
2978 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2979 optr = LineBuf->buf + LineBuf->BufUsed;
2980 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2983 LineBuf->BufUsed = optr - LineBuf->buf;
2992 return Buf->BufUsed - (ptr - Buf->buf);