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;
30 const char *StrBufNOTNULL = ((char*) NULL) - 1;
33 * Private Structure for the Stringbuffer
36 char *buf; /**< the pointer to the dynamic buffer */
37 long BufSize; /**< how many spcae do we optain */
38 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
39 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
43 char bt_lastinc [SIZ];
49 static void StrBufBacktrace(StrBuf *Buf, int which)
53 void *stack_frames[50];
58 pstart = pch = Buf->bt;
60 pstart = pch = Buf->bt_lastinc;
61 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
62 strings = backtrace_symbols(stack_frames, size);
63 for (i = 0; i < size; i++) {
65 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
67 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
78 * @brief Cast operator to Plain String
79 * Note: if the buffer is altered by StrBuf operations, this pointer may become
80 * invalid. So don't lean on it after altering the buffer!
81 * Since this operation is considered cheap, rather call it often than risking
82 * your pointer to become invalid!
83 * @param Str the string we want to get the c-string representation for
84 * @returns the Pointer to the Content. Don't mess with it!
86 inline const char *ChrPtr(const StrBuf *Str)
94 * @brief since we know strlen()'s result, provide it here.
95 * @param Str the string to return the length to
96 * @returns contentlength of the buffer
98 inline int StrLength(const StrBuf *Str)
100 return (Str != NULL) ? Str->BufUsed : 0;
104 * @brief local utility function to resize the buffer
105 * @param Buf the buffer whichs storage we should increase
106 * @param KeepOriginal should we copy the original buffer or just start over with a new one
107 * @param DestSize what should fit in after?
109 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
112 size_t NewSize = Buf->BufSize * 2;
118 while (NewSize <= DestSize)
121 NewBuf= (char*) malloc(NewSize);
125 if (KeepOriginal && (Buf->BufUsed > 0))
127 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
136 Buf->BufSize = NewSize;
139 #ifdef HAVE_BACKTRACE
140 StrBufBacktrace(Buf, 1);
147 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
148 * @param Buf Buffer to shrink (has to be empty)
149 * @param ThreshHold if the buffer is bigger then this, its readjusted
150 * @param NewSize if we Shrink it, how big are we going to be afterwards?
152 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
154 if (Buf->BufUsed > ThreshHold) {
156 Buf->buf = (char*) malloc(NewSize);
158 Buf->BufSize = NewSize;
163 * @brief shrink long term buffers to their real size so they don't waste memory
164 * @param Buf buffer to shrink
165 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
166 * @returns physical size of the buffer
168 long StrBufShrinkToFit(StrBuf *Buf, int Force)
171 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
173 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
174 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
175 Buf->BufSize = Buf->BufUsed + 1;
183 * @brief Allocate a new buffer with default buffer size
184 * @returns the new stringbuffer
186 StrBuf* NewStrBuf(void)
190 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
191 NewBuf->buf = (char*) malloc(BaseStrBufSize);
192 NewBuf->buf[0] = '\0';
193 NewBuf->BufSize = BaseStrBufSize;
195 NewBuf->ConstBuf = 0;
197 NewBuf->nIncreases = 0;
198 NewBuf->bt[0] = '\0';
199 NewBuf->bt_lastinc[0] = '\0';
200 #ifdef HAVE_BACKTRACE
201 StrBufBacktrace(NewBuf, 0);
208 * @brief Copy Constructor; returns a duplicate of CopyMe
209 * @params CopyMe Buffer to faxmilate
210 * @returns the new stringbuffer
212 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
219 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
220 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
221 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
222 NewBuf->BufUsed = CopyMe->BufUsed;
223 NewBuf->BufSize = CopyMe->BufSize;
224 NewBuf->ConstBuf = 0;
226 NewBuf->nIncreases = 0;
227 NewBuf->bt[0] = '\0';
228 NewBuf->bt_lastinc[0] = '\0';
229 #ifdef HAVE_BACKTRACE
230 StrBufBacktrace(NewBuf, 0);
237 * @brief create a new Buffer using an existing c-string
238 * this function should also be used if you want to pre-suggest
239 * the buffer size to allocate in conjunction with ptr == NULL
240 * @param ptr the c-string to copy; may be NULL to create a blank instance
241 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
242 * @returns the new stringbuffer
244 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
247 size_t Siz = BaseStrBufSize;
250 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
252 CopySize = strlen((ptr != NULL)?ptr:"");
256 while (Siz <= CopySize)
259 NewBuf->buf = (char*) malloc(Siz);
260 NewBuf->BufSize = Siz;
262 memcpy(NewBuf->buf, ptr, CopySize);
263 NewBuf->buf[CopySize] = '\0';
264 NewBuf->BufUsed = CopySize;
267 NewBuf->buf[0] = '\0';
270 NewBuf->ConstBuf = 0;
272 NewBuf->nIncreases = 0;
273 NewBuf->bt[0] = '\0';
274 NewBuf->bt_lastinc[0] = '\0';
275 #ifdef HAVE_BACKTRACE
276 StrBufBacktrace(NewBuf, 0);
283 * @brief Set an existing buffer from a c-string
284 * @param ptr c-string to put into
285 * @param nChars set to -1 if we should work 0-terminated
286 * @returns the new length of the string
288 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
290 size_t Siz = Buf->BufSize;
294 CopySize = strlen(ptr);
298 while (Siz <= CopySize)
301 if (Siz != Buf->BufSize)
302 IncreaseBuf(Buf, 0, Siz);
303 memcpy(Buf->buf, ptr, CopySize);
304 Buf->buf[CopySize] = '\0';
305 Buf->BufUsed = CopySize;
312 * @brief use strbuf as wrapper for a string constant for easy handling
313 * @param StringConstant a string to wrap
314 * @param SizeOfConstant should be sizeof(StringConstant)-1
316 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
320 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
321 NewBuf->buf = (char*) StringConstant;
322 NewBuf->BufSize = SizeOfStrConstant;
323 NewBuf->BufUsed = SizeOfStrConstant;
324 NewBuf->ConstBuf = 1;
326 NewBuf->nIncreases = 0;
327 NewBuf->bt[0] = '\0';
328 NewBuf->bt_lastinc[0] = '\0';
335 * @brief flush the content of a Buf; keep its struct
336 * @param buf Buffer to flush
338 int FlushStrBuf(StrBuf *buf)
350 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
351 * @param buf Buffer to wipe
353 int FLUSHStrBuf(StrBuf *buf)
359 if (buf->BufUsed > 0) {
360 memset(buf->buf, 0, buf->BufUsed);
367 int hFreeDbglog = -1;
370 * @brief Release a Buffer
371 * Its a double pointer, so it can NULL your pointer
372 * so fancy SIG11 appear instead of random results
373 * @param FreeMe Pointer Pointer to the buffer to free
375 void FreeStrBuf (StrBuf **FreeMe)
380 if (hFreeDbglog == -1){
381 pid_t pid = getpid();
383 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
384 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
386 if ((*FreeMe)->nIncreases > 0)
390 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
391 (*FreeMe)->nIncreases,
395 (*FreeMe)->bt_lastinc);
396 n = write(hFreeDbglog, buf, n);
402 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
405 n = write(hFreeDbglog, buf, n);
408 if (!(*FreeMe)->ConstBuf)
409 free((*FreeMe)->buf);
415 * @brief flatten a Buffer to the Char * we return
416 * Its a double pointer, so it can NULL your pointer
417 * so fancy SIG11 appear instead of random results
418 * The Callee then owns the buffer and is responsible for freeing it.
419 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
420 * @returns the pointer of the buffer; Callee owns the memory thereafter.
422 char *SmashStrBuf (StrBuf **SmashMe)
426 if (*SmashMe == NULL)
429 if (hFreeDbglog == -1){
430 pid_t pid = getpid();
432 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
433 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
435 if ((*SmashMe)->nIncreases > 0)
439 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
440 (*SmashMe)->nIncreases,
444 (*SmashMe)->bt_lastinc);
445 n = write(hFreeDbglog, buf, n);
451 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
453 (*SmashMe)->BufSize);
454 n = write(hFreeDbglog, buf, n);
457 Ret = (*SmashMe)->buf;
464 * @brief Release the buffer
465 * If you want put your StrBuf into a Hash, use this as Destructor.
466 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
468 void HFreeStrBuf (void *VFreeMe)
470 StrBuf *FreeMe = (StrBuf*)VFreeMe;
474 if (hFreeDbglog == -1){
475 pid_t pid = getpid();
477 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
478 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
480 if (FreeMe->nIncreases > 0)
484 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
490 write(hFreeDbglog, buf, n);
496 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
502 if (!FreeMe->ConstBuf)
508 * @brief Wrapper around atol
510 long StrTol(const StrBuf *Buf)
515 return atol(Buf->buf);
521 * @brief Wrapper around atoi
523 int StrToi(const StrBuf *Buf)
527 if (Buf->BufUsed > 0)
528 return atoi(Buf->buf);
534 * @brief Checks to see if the string is a pure number
536 int StrBufIsNumber(const StrBuf *Buf) {
541 strtoll(Buf->buf, &pEnd, 10);
542 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
548 * @brief modifies a Single char of the Buf
549 * You can point to it via char* or a zero-based integer
550 * @param ptr char* to zero; use NULL if unused
551 * @param nThChar zero based pointer into the string; use -1 if unused
552 * @param PeekValue The Character to place into the position
554 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
559 nThChar = ptr - Buf->buf;
560 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
562 Buf->buf[nThChar] = PeekValue;
567 * @brief Append a StringBuffer to the buffer
568 * @param Buf Buffer to modify
569 * @param AppendBuf Buffer to copy at the end of our buffer
570 * @param Offset Should we start copying from an offset?
572 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
574 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
577 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
580 AppendBuf->BufUsed + Buf->BufUsed);
582 memcpy(Buf->buf + Buf->BufUsed,
583 AppendBuf->buf + Offset,
584 AppendBuf->BufUsed - Offset);
585 Buf->BufUsed += AppendBuf->BufUsed - Offset;
586 Buf->buf[Buf->BufUsed] = '\0';
591 * @brief Append a C-String to the buffer
592 * @param Buf Buffer to modify
593 * @param AppendBuf Buffer to copy at the end of our buffer
594 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
595 * @param Offset Should we start copying from an offset?
597 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
600 long BufSizeRequired;
602 if ((AppendBuf == NULL) || (Buf == NULL))
606 aps = strlen(AppendBuf + Offset);
608 aps = AppendSize - Offset;
610 BufSizeRequired = Buf->BufUsed + aps + 1;
611 if (Buf->BufSize <= BufSizeRequired)
612 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
614 memcpy(Buf->buf + Buf->BufUsed,
618 Buf->buf[Buf->BufUsed] = '\0';
622 * @brief Callback for cURL to append the webserver reply to a buffer
623 * @params pre-defined by the cURL API; see man 3 curl for mre info
625 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
634 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
640 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
641 * @param outbuf the output buffer
642 * @param oblen the size of outbuf to sanitize
643 * @param strbuf the input buffer
645 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
647 const char *pch, *pche;
650 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
651 int eclen = sizeof(ec) -1;
653 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
655 if (PlainIn != NULL) {
656 len = strlen(PlainIn);
662 pche = pch + In->BufUsed;
669 pt = OutBuf->buf + OutBuf->BufUsed;
670 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
674 IncreaseBuf(OutBuf, 1, -1);
675 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
676 pt = OutBuf->buf + OutBuf->BufUsed;
680 for (b = 0; b < eclen; ++b) {
687 sprintf(pt,"%%%02X", *pch);
689 OutBuf->BufUsed += 3;
701 * @brief Append a string, escaping characters which have meaning in HTML.
703 * @param Target target buffer
704 * @param Source source buffer; set to NULL if you just have a C-String
705 * @param PlainIn Plain-C string to append; set to NULL if unused
706 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
707 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
708 * if set to 2, linebreaks are replaced by <br/>
710 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
712 const char *aptr, *eiptr;
716 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
719 if (PlainIn != NULL) {
721 len = strlen(PlainIn);
726 eiptr = aptr + Source->BufUsed;
727 len = Source->BufUsed;
733 bptr = Target->buf + Target->BufUsed;
734 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
736 while (aptr < eiptr){
738 IncreaseBuf(Target, 1, -1);
739 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
740 bptr = Target->buf + Target->BufUsed;
743 memcpy(bptr, "<", 4);
745 Target->BufUsed += 4;
747 else if (*aptr == '>') {
748 memcpy(bptr, ">", 4);
750 Target->BufUsed += 4;
752 else if (*aptr == '&') {
753 memcpy(bptr, "&", 5);
755 Target->BufUsed += 5;
757 else if (*aptr == '"') {
758 memcpy(bptr, """, 6);
760 Target->BufUsed += 6;
762 else if (*aptr == '\'') {
763 memcpy(bptr, "'", 5);
765 Target->BufUsed += 5;
767 else if (*aptr == LB) {
772 else if (*aptr == RB) {
777 else if (*aptr == QU) {
782 else if ((*aptr == 32) && (nbsp == 1)) {
783 memcpy(bptr, " ", 6);
785 Target->BufUsed += 6;
787 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
788 *bptr='\0'; /* nothing */
790 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
791 memcpy(bptr, "<br/>", 11);
793 Target->BufUsed += 11;
797 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
798 *bptr='\0'; /* nothing */
808 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
810 return Target->BufUsed;
814 * @brief Append a string, escaping characters which have meaning in HTML.
815 * Converts linebreaks into blanks; escapes single quotes
816 * @param Target target buffer
817 * @param Source source buffer; set to NULL if you just have a C-String
818 * @param PlainIn Plain-C string to append; set to NULL if unused
820 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
822 const char *aptr, *eiptr;
826 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
829 if (PlainIn != NULL) {
831 len = strlen(PlainIn);
836 eiptr = aptr + Source->BufUsed;
837 len = Source->BufUsed;
843 eptr = Target->buf + Target->BufSize - 8;
844 tptr = Target->buf + Target->BufUsed;
846 while (aptr < eiptr){
848 IncreaseBuf(Target, 1, -1);
849 eptr = Target->buf + Target->BufSize - 8;
850 tptr = Target->buf + Target->BufUsed;
857 else if (*aptr == '\r') {
861 else if (*aptr == '\'') {
867 Target->BufUsed += 5;
880 * @brief Append a string, escaping characters which have meaning in ICAL.
882 * @param Target target buffer
883 * @param Source source buffer; set to NULL if you just have a C-String
884 * @param PlainIn Plain-C string to append; set to NULL if unused
886 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
888 const char *aptr, *eiptr;
892 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
895 if (PlainIn != NULL) {
897 len = strlen(PlainIn);
902 eiptr = aptr + Source->BufUsed;
903 len = Source->BufUsed;
909 eptr = Target->buf + Target->BufSize - 8;
910 tptr = Target->buf + Target->BufUsed;
912 while (aptr < eiptr){
913 if(tptr + 3 >= eptr) {
914 IncreaseBuf(Target, 1, -1);
915 eptr = Target->buf + Target->BufSize - 8;
916 tptr = Target->buf + Target->BufUsed;
926 else if (*aptr == '\r') {
933 else if (*aptr == ',') {
949 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
951 * @param Target target buffer
952 * @param Source source buffer; set to NULL if you just have a C-String
953 * @param PlainIn Plain-C string to append; set to NULL if unused
954 * @returns size of result or -1
956 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
958 const char *aptr, *eiptr;
962 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
965 if (PlainIn != NULL) {
967 len = strlen(PlainIn);
972 eiptr = aptr + Source->BufUsed;
973 len = Source->BufUsed;
979 bptr = Target->buf + Target->BufUsed;
980 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
982 while (aptr < eiptr){
984 IncreaseBuf(Target, 1, -1);
985 eptr = Target->buf + Target->BufSize - 3;
986 bptr = Target->buf + Target->BufUsed;
993 Target->BufUsed += 2;
994 } else if (*aptr == '\\') {
999 Target->BufUsed += 2;
1009 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1011 return Target->BufUsed;
1015 * @brief extracts a substring from Source into dest
1016 * @param dest buffer to place substring into
1017 * @param Source string to copy substring from
1018 * @param Offset chars to skip from start
1019 * @param nChars number of chars to copy
1020 * @returns the number of chars copied; may be different from nChars due to the size of Source
1022 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1024 size_t NCharsRemain;
1025 if (Offset > Source->BufUsed)
1030 if (Offset + nChars < Source->BufUsed)
1032 if (nChars >= dest->BufSize)
1033 IncreaseBuf(dest, 0, nChars + 1);
1034 memcpy(dest->buf, Source->buf + Offset, nChars);
1035 dest->BufUsed = nChars;
1036 dest->buf[dest->BufUsed] = '\0';
1039 NCharsRemain = Source->BufUsed - Offset;
1040 if (NCharsRemain >= dest->BufSize)
1041 IncreaseBuf(dest, 0, NCharsRemain + 1);
1042 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1043 dest->BufUsed = NCharsRemain;
1044 dest->buf[dest->BufUsed] = '\0';
1045 return NCharsRemain;
1049 * @brief sprintf like function appending the formated string to the buffer
1050 * vsnprintf version to wrap into own calls
1051 * @param Buf Buffer to extend by format and @params
1052 * @param format printf alike format to add
1053 * @param ap va_list containing the items for format
1055 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1058 size_t BufSize = Buf->BufSize;
1059 size_t nWritten = Buf->BufSize + 1;
1060 size_t Offset = Buf->BufUsed;
1061 size_t newused = Offset + nWritten;
1063 while (newused >= BufSize) {
1065 nWritten = vsnprintf(Buf->buf + Offset,
1066 Buf->BufSize - Offset,
1069 newused = Offset + nWritten;
1070 if (newused >= Buf->BufSize) {
1071 IncreaseBuf(Buf, 1, newused);
1072 newused = Buf->BufSize + 1;
1075 Buf->BufUsed = Offset + nWritten;
1076 BufSize = Buf->BufSize;
1083 * @brief sprintf like function appending the formated string to the buffer
1084 * @param Buf Buffer to extend by format and @params
1085 * @param format printf alike format to add
1086 * @param ap va_list containing the items for format
1088 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1090 size_t BufSize = Buf->BufSize;
1091 size_t nWritten = Buf->BufSize + 1;
1092 size_t Offset = Buf->BufUsed;
1093 size_t newused = Offset + nWritten;
1096 while (newused >= BufSize) {
1097 va_start(arg_ptr, format);
1098 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1099 Buf->BufSize - Buf->BufUsed,
1102 newused = Buf->BufUsed + nWritten;
1103 if (newused >= Buf->BufSize) {
1104 IncreaseBuf(Buf, 1, newused);
1105 newused = Buf->BufSize + 1;
1108 Buf->BufUsed += nWritten;
1109 BufSize = Buf->BufSize;
1116 * @brief sprintf like function putting the formated string into the buffer
1117 * @param Buf Buffer to extend by format and @params
1118 * @param format printf alike format to add
1119 * @param ap va_list containing the items for format
1121 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1123 size_t nWritten = Buf->BufSize + 1;
1126 while (nWritten >= Buf->BufSize) {
1127 va_start(arg_ptr, format);
1128 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1130 if (nWritten >= Buf->BufSize) {
1131 IncreaseBuf(Buf, 0, 0);
1132 nWritten = Buf->BufSize + 1;
1135 Buf->BufUsed = nWritten ;
1141 * @brief Counts the numbmer of tokens in a buffer
1142 * @param Source String to count tokens in
1143 * @param tok Tokenizer char to count
1144 * @returns numbers of tokenizer chars found
1146 int StrBufNum_tokens(const StrBuf *source, char tok)
1150 return num_tokens(source->buf, tok);
1154 * remove_token() - a tokenizer that kills, maims, and destroys
1157 * @brief a string tokenizer
1158 * @param Source StringBuffer to read into
1159 * @param parmnum n'th @parameter to remove
1160 * @param separator tokenizer @param
1161 * @returns -1 if not found, else length of token.
1163 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1166 char *d, *s; /* dest, source */
1169 /* Find desired @parameter */
1171 while (count < parmnum) {
1172 /* End of string, bail! */
1177 if (*d == separator) {
1182 if (!d) return 0; /* @Parameter not found */
1184 /* Find next @parameter */
1186 while (*s && *s != separator) {
1189 if (*s == separator)
1193 /* Hack and slash */
1195 memmove(d, s, Source->BufUsed - (s - Source->buf));
1196 Source->BufUsed += ReducedBy;
1198 else if (d == Source->buf) {
1200 Source->BufUsed = 0;
1204 Source->BufUsed += ReducedBy;
1217 * @brief a string tokenizer
1218 * @param dest Destination StringBuffer
1219 * @param Source StringBuffer to read into
1220 * @param parmnum n'th @parameter to extract
1221 * @param separator tokenizer @param
1222 * @returns -1 if not found, else length of token.
1224 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1226 const char *s, *e; //* source * /
1227 int len = 0; //* running total length of extracted string * /
1228 int current_token = 0; //* token currently being processed * /
1231 dest->buf[0] = '\0';
1237 if ((Source == NULL) || (Source->BufUsed ==0)) {
1241 e = s + Source->BufUsed;
1244 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1246 while ((s<e) && !IsEmptyStr(s)) {
1247 if (*s == separator) {
1250 if (len >= dest->BufSize) {
1251 dest->BufUsed = len;
1252 if (IncreaseBuf(dest, 1, -1) < 0) {
1257 if ( (current_token == parmnum) &&
1258 (*s != separator)) {
1259 dest->buf[len] = *s;
1262 else if (current_token > parmnum) {
1268 dest->buf[len] = '\0';
1269 dest->BufUsed = len;
1271 if (current_token < parmnum) {
1272 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1275 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1284 * @brief a string tokenizer to fetch an integer
1285 * @param dest Destination StringBuffer
1286 * @param parmnum n'th @parameter to extract
1287 * @param separator tokenizer @param
1288 * @returns 0 if not found, else integer representation of the token
1290 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1300 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1307 * @brief a string tokenizer to fetch a long integer
1308 * @param dest Destination StringBuffer
1309 * @param parmnum n'th @parameter to extract
1310 * @param separator tokenizer @param
1311 * @returns 0 if not found, else long integer representation of the token
1313 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1323 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1331 * @brief a string tokenizer to fetch an unsigned long
1332 * @param dest Destination StringBuffer
1333 * @param parmnum n'th @parameter to extract
1334 * @param separator tokenizer @param
1335 * @returns 0 if not found, else unsigned long representation of the token
1337 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1348 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1352 return (unsigned long) atol(pnum);
1361 * @briefa string tokenizer; Bounds checker
1362 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1363 * @param Source our tokenbuffer
1364 * @param pStart the token iterator pointer to inspect
1365 * @returns whether the revolving pointer is inside of the search range
1367 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1369 if ((Source == NULL) ||
1370 (*pStart == StrBufNOTNULL) ||
1371 (Source->BufUsed == 0))
1375 if (*pStart == NULL)
1379 else if (*pStart > Source->buf + Source->BufUsed)
1383 else if (*pStart <= Source->buf)
1392 * @brief a string tokenizer
1393 * @param dest Destination StringBuffer
1394 * @param Source StringBuffer to read into
1395 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1396 * @param separator tokenizer @param
1397 * @returns -1 if not found, else length of token.
1399 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1401 const char *s; /* source */
1402 const char *EndBuffer; /* end stop of source buffer */
1403 int current_token = 0; /* token currently being processed */
1404 int len = 0; /* running total length of extracted string */
1406 if ((Source == NULL) ||
1407 (Source->BufUsed == 0) )
1409 *pStart = StrBufNOTNULL;
1413 EndBuffer = Source->buf + Source->BufUsed;
1417 dest->buf[0] = '\0';
1422 *pStart = EndBuffer + 1;
1426 if (*pStart == NULL)
1428 *pStart = Source->buf; /* we're starting to examine this buffer. */
1430 else if ((*pStart < Source->buf) ||
1431 (*pStart > EndBuffer ) )
1433 return -1; /* no more tokens to find. */
1437 /* start to find the next token */
1438 while ((s <= EndBuffer) &&
1439 (current_token == 0) )
1441 if (*s == separator)
1443 /* we found the next token */
1447 if (len >= dest->BufSize)
1449 /* our Dest-buffer isn't big enough, increase it. */
1450 dest->BufUsed = len;
1452 if (IncreaseBuf(dest, 1, -1) < 0) {
1453 /* WHUT? no more mem? bail out. */
1460 if ( (current_token == 0 ) && /* are we in our target token? */
1461 (!IsEmptyStr(s) ) &&
1462 (separator != *s) ) /* don't copy the token itself */
1464 dest->buf[len] = *s; /* Copy the payload */
1465 ++len; /* remember the bigger size. */
1471 /* did we reach the end? */
1472 if ((s > EndBuffer)) {
1473 EndBuffer = StrBufNOTNULL;
1474 *pStart = EndBuffer;
1477 *pStart = s; /* remember the position for the next run */
1480 /* sanitize our extracted token */
1481 dest->buf[len] = '\0';
1482 dest->BufUsed = len;
1489 * @brief a string tokenizer
1490 * @param dest Destination StringBuffer
1491 * @param Source StringBuffer to read into
1492 * @param pStart pointer to the end of the last token. Feed with NULL.
1493 * @param separator tokenizer @param
1494 * @returns -1 if not found, else length of token.
1496 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1498 const char *s, *EndBuffer; //* source * /
1499 int len = 0; //* running total length of extracted string * /
1500 int current_token = 0; //* token currently being processed * /
1502 if ((Source == NULL) ||
1503 (Source->BufUsed ==0)) {
1507 return Source->BufUsed;
1509 if (*pStart == NULL)
1510 *pStart = Source->buf;
1512 EndBuffer = Source->buf + Source->BufUsed;
1514 if ((*pStart < Source->buf) ||
1515 (*pStart > EndBuffer)) {
1523 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1525 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1526 if (*s == separator) {
1529 if (current_token >= nTokens) {
1541 * @brief a string tokenizer to fetch an integer
1542 * @param dest Destination StringBuffer
1543 * @param parmnum n'th @parameter to extract
1544 * @param separator tokenizer @param
1545 * @returns 0 if not found, else integer representation of the token
1547 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1557 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1564 * @brief a string tokenizer to fetch a long integer
1565 * @param dest Destination StringBuffer
1566 * @param parmnum n'th @parameter to extract
1567 * @param separator tokenizer @param
1568 * @returns 0 if not found, else long integer representation of the token
1570 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1580 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1588 * @brief a string tokenizer to fetch an unsigned long
1589 * @param dest Destination StringBuffer
1590 * @param parmnum n'th @parameter to extract
1591 * @param separator tokenizer @param
1592 * @returns 0 if not found, else unsigned long representation of the token
1594 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1605 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1609 return (unsigned long) atol(pnum);
1618 * @brief Read a line from socket
1619 * flushes and closes the FD on error
1620 * @param buf the buffer to get the input to
1621 * @param fd pointer to the filedescriptor to read
1622 * @param append Append to an existing string or replace?
1623 * @param Error strerror() on error
1624 * @returns numbers of chars read
1626 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1628 int len, rlen, slen;
1633 slen = len = buf->BufUsed;
1635 rlen = read(*fd, &buf->buf[len], 1);
1637 *Error = strerror(errno);
1644 if (buf->buf[len] == '\n')
1646 if (buf->buf[len] != '\r')
1648 if (len >= buf->BufSize) {
1650 buf->buf[len+1] = '\0';
1651 IncreaseBuf(buf, 1, -1);
1655 buf->buf[len] = '\0';
1660 * @brief Read a line from socket
1661 * flushes and closes the FD on error
1662 * @param buf the buffer to get the input to
1663 * @param fd pointer to the filedescriptor to read
1664 * @param append Append to an existing string or replace?
1665 * @param Error strerror() on error
1666 * @returns numbers of chars read
1668 int StrBufTCP_read_buffered_line(StrBuf *Line,
1672 int selectresolution,
1676 int nSuccessLess = 0;
1682 if (buf->BufUsed > 0) {
1683 pch = strchr(buf->buf, '\n');
1686 len = pch - buf->buf;
1687 if (len > 0 && (*(pch - 1) == '\r') )
1689 StrBufSub(Line, buf, 0, len - rlen);
1690 StrBufCutLeft(buf, len + 1);
1695 if (buf->BufSize - buf->BufUsed < 10)
1696 IncreaseBuf(buf, 1, -1);
1698 fdflags = fcntl(*fd, F_GETFL);
1699 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1702 while ((nSuccessLess < timeout) && (pch == NULL)) {
1703 tv.tv_sec = selectresolution;
1708 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1709 *Error = strerror(errno);
1714 if (FD_ISSET(*fd, &rfds)) {
1716 &buf->buf[buf->BufUsed],
1717 buf->BufSize - buf->BufUsed - 1);
1719 *Error = strerror(errno);
1724 else if (rlen > 0) {
1726 buf->BufUsed += rlen;
1727 buf->buf[buf->BufUsed] = '\0';
1728 if (buf->BufUsed + 10 > buf->BufSize) {
1729 IncreaseBuf(buf, 1, -1);
1731 pch = strchr(buf->buf, '\n');
1739 len = pch - buf->buf;
1740 if (len > 0 && (*(pch - 1) == '\r') )
1742 StrBufSub(Line, buf, 0, len - rlen);
1743 StrBufCutLeft(buf, len + 1);
1750 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1751 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1752 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1754 * @brief Read a line from socket
1755 * flushes and closes the FD on error
1756 * @param buf the buffer to get the input to
1757 * @param Pos pointer to the current read position, should be NULL initialized!
1758 * @param fd pointer to the filedescriptor to read
1759 * @param append Append to an existing string or replace?
1760 * @param Error strerror() on error
1761 * @returns numbers of chars read
1763 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1768 int selectresolution,
1771 const char *pche = NULL;
1772 const char *pos = NULL;
1774 int nSuccessLess = 0;
1776 const char *pch = NULL;
1781 if ((IOBuf->BufUsed > 0) &&
1783 (pos < IOBuf->buf + IOBuf->BufUsed))
1785 pche = IOBuf->buf + IOBuf->BufUsed;
1787 while ((pch < pche) && (*pch != '\n'))
1789 if ((pch >= pche) || (*pch == '\0'))
1791 if ((pch != NULL) &&
1796 if (len > 0 && (*(pch - 1) == '\r') )
1798 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1808 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1812 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1813 IncreaseBuf(IOBuf, 1, -1);
1816 fdflags = fcntl(*fd, F_GETFL);
1817 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1818 *Error = ErrRBLF_WrongFDFlags;
1823 while ((nSuccessLess < timeout) && (pch == NULL)) {
1824 tv.tv_sec = selectresolution;
1829 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1830 *Error = strerror(errno);
1834 *Error = ErrRBLF_SelectFailed;
1837 if (FD_ISSET(*fd, &rfds) != 0) {
1839 &IOBuf->buf[IOBuf->BufUsed],
1840 IOBuf->BufSize - IOBuf->BufUsed - 1);
1842 *Error = strerror(errno);
1847 else if (rlen > 0) {
1849 IOBuf->BufUsed += rlen;
1850 IOBuf->buf[IOBuf->BufUsed] = '\0';
1851 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1852 IncreaseBuf(IOBuf, 1, -1);
1855 pche = IOBuf->buf + IOBuf->BufUsed;
1857 while ((pch < pche) && (*pch != '\n'))
1859 if ((pch >= pche) || (*pch == '\0'))
1870 if (len > 0 && (*(pch - 1) == '\r') )
1872 StrBufSub(Line, IOBuf, 0, len - rlen);
1873 *Pos = pos + len + 1;
1876 *Error = ErrRBLF_NotEnoughSentFromServer;
1882 * @brief Input binary data from socket
1883 * flushes and closes the FD on error
1884 * @param buf the buffer to get the input to
1885 * @param fd pointer to the filedescriptor to read
1886 * @param append Append to an existing string or replace?
1887 * @param nBytes the maximal number of bytes to read
1888 * @param Error strerror() on error
1889 * @returns numbers of chars read
1891 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1895 int len, rlen, slen;
1899 if ((Buf == NULL) || (*fd == -1))
1903 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1904 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1906 ptr = Buf->buf + Buf->BufUsed;
1908 slen = len = Buf->BufUsed;
1910 fdflags = fcntl(*fd, F_GETFL);
1912 while (nRead < nBytes) {
1913 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1916 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1917 *Error = strerror(errno);
1922 if ((rlen = read(*fd,
1924 nBytes - nRead)) == -1) {
1927 *Error = strerror(errno);
1932 Buf->BufUsed += rlen;
1934 Buf->buf[Buf->BufUsed] = '\0';
1938 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1940 * @brief Input binary data from socket
1941 * flushes and closes the FD on error
1942 * @param buf the buffer to get the input to
1943 * @param fd pointer to the filedescriptor to read
1944 * @param append Append to an existing string or replace?
1945 * @param nBytes the maximal number of bytes to read
1946 * @param Error strerror() on error
1947 * @returns numbers of chars read
1949 int StrBufReadBLOBBuffered(StrBuf *Blob,
1970 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1974 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1975 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1980 len = pos - IOBuf->buf;
1981 rlen = IOBuf->BufUsed - len;
1984 if ((IOBuf->BufUsed > 0) &&
1986 (pos < IOBuf->buf + IOBuf->BufUsed))
1988 pche = IOBuf->buf + IOBuf->BufUsed;
1991 if (rlen < nBytes) {
1992 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1993 Blob->BufUsed += rlen;
1994 Blob->buf[Blob->BufUsed] = '\0';
1998 if (rlen >= nBytes) {
1999 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2000 Blob->BufUsed += nBytes;
2001 Blob->buf[Blob->BufUsed] = '\0';
2002 if (rlen == nBytes) {
2013 if (IOBuf->BufSize < nBytes - nRead)
2014 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2017 slen = len = Blob->BufUsed;
2019 fdflags = fcntl(*fd, F_GETFL);
2024 while (nRead < nBytes) {
2025 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
2028 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
2031 *Error = strerror(errno);
2042 *Error = strerror(errno);
2048 if ((check == NNN_TERM) &&
2050 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2052 StrBufPlain(Blob, HKEY("\n000\n"));
2053 StrBufCutRight(Blob, 5);
2054 return Blob->BufUsed;
2056 if (nSelects > 10) {
2058 *Error = ErrRBB_too_many_selects;
2065 IOBuf->BufUsed += rlen;
2068 if (nRead > nBytes) {
2069 *Pos = IOBuf->buf + nBytes;
2071 Blob->buf[Blob->BufUsed] = '\0';
2072 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2077 * @brief Cut nChars from the start of the string
2078 * @param Buf Buffer to modify
2079 * @param nChars how many chars should be skipped?
2081 void StrBufCutLeft(StrBuf *Buf, int nChars)
2083 if (nChars >= Buf->BufUsed) {
2087 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2088 Buf->BufUsed -= nChars;
2089 Buf->buf[Buf->BufUsed] = '\0';
2093 * @brief Cut the trailing n Chars from the string
2094 * @param Buf Buffer to modify
2095 * @param nChars how many chars should be trunkated?
2097 void StrBufCutRight(StrBuf *Buf, int nChars)
2099 if (nChars >= Buf->BufUsed) {
2103 Buf->BufUsed -= nChars;
2104 Buf->buf[Buf->BufUsed] = '\0';
2108 * @brief Cut the string after n Chars
2109 * @param Buf Buffer to modify
2110 * @param AfternChars after how many chars should we trunkate the string?
2111 * @param At if non-null and points inside of our string, cut it there.
2113 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2116 AfternChars = At - Buf->buf;
2119 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2121 Buf->BufUsed = AfternChars;
2122 Buf->buf[Buf->BufUsed] = '\0';
2127 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2128 * @param buf the string to modify
2129 * @param len length of the string.
2131 void StrBufTrim(StrBuf *Buf)
2134 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2136 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2139 if (delta > 0) StrBufCutLeft(Buf, delta);
2141 if (Buf->BufUsed == 0) return;
2142 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2145 Buf->buf[Buf->BufUsed] = '\0';
2149 * @brief uppercase the contents of a buffer
2150 * @param Buf the buffer to translate
2152 void StrBufUpCase(StrBuf *Buf)
2157 pche = pch + Buf->BufUsed;
2158 while (pch < pche) {
2159 *pch = toupper(*pch);
2166 * @brief lowercase the contents of a buffer
2167 * @param Buf the buffer to translate
2169 void StrBufLowerCase(StrBuf *Buf)
2174 pche = pch + Buf->BufUsed;
2175 while (pch < pche) {
2176 *pch = tolower(*pch);
2182 * @brief removes double slashes from pathnames
2183 * @param Dir directory string to filter
2184 * @param RemoveTrailingSlash allows / disallows trailing slashes
2186 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2192 while (!IsEmptyStr(a)) {
2204 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2209 Dir->BufUsed = b - Dir->buf;
2213 * @brief unhide special chars hidden to the HTML escaper
2214 * @param target buffer to put the unescaped string in
2215 * @param source buffer to unescape
2217 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2223 FlushStrBuf(target);
2225 if (source == NULL ||target == NULL)
2230 len = source->BufUsed;
2231 for (a = 0; a < len; ++a) {
2232 if (target->BufUsed >= target->BufSize)
2233 IncreaseBuf(target, 1, -1);
2235 if (source->buf[a] == '=') {
2236 hex[0] = source->buf[a + 1];
2237 hex[1] = source->buf[a + 2];
2240 sscanf(hex, "%02x", &b);
2241 target->buf[target->BufUsed] = b;
2242 target->buf[++target->BufUsed] = 0;
2246 target->buf[target->BufUsed] = source->buf[a];
2247 target->buf[++target->BufUsed] = 0;
2254 * @brief hide special chars from the HTML escapers and friends
2255 * @param target buffer to put the escaped string in
2256 * @param source buffer to escape
2258 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2263 FlushStrBuf(target);
2265 if (source == NULL ||target == NULL)
2270 len = source->BufUsed;
2271 for (i=0; i<len; ++i) {
2272 if (target->BufUsed + 4 >= target->BufSize)
2273 IncreaseBuf(target, 1, -1);
2274 if ( (isalnum(source->buf[i])) ||
2275 (source->buf[i]=='-') ||
2276 (source->buf[i]=='_') ) {
2277 target->buf[target->BufUsed++] = source->buf[i];
2280 sprintf(&target->buf[target->BufUsed],
2282 (0xFF &source->buf[i]));
2283 target->BufUsed += 3;
2286 target->buf[target->BufUsed + 1] = '\0';
2290 * @brief uses the same calling syntax as compress2(), but it
2291 * creates a stream compatible with HTTP "Content-encoding: gzip"
2294 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2295 #define OS_CODE 0x03 /*< unix */
2296 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2297 size_t * destLen, /*< length of the compresed data */
2298 const Bytef * source, /*< source to encode */
2299 uLong sourceLen, /*< length of source to encode */
2300 int level) /*< compression level */
2302 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2304 /* write gzip header */
2305 snprintf((char *) dest, *destLen,
2306 "%c%c%c%c%c%c%c%c%c%c",
2307 gz_magic[0], gz_magic[1], Z_DEFLATED,
2308 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2311 /* normal deflate */
2314 stream.next_in = (Bytef *) source;
2315 stream.avail_in = (uInt) sourceLen;
2316 stream.next_out = dest + 10L; // after header
2317 stream.avail_out = (uInt) * destLen;
2318 if ((uLong) stream.avail_out != *destLen)
2321 stream.zalloc = (alloc_func) 0;
2322 stream.zfree = (free_func) 0;
2323 stream.opaque = (voidpf) 0;
2325 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2326 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2330 err = deflate(&stream, Z_FINISH);
2331 if (err != Z_STREAM_END) {
2332 deflateEnd(&stream);
2333 return err == Z_OK ? Z_BUF_ERROR : err;
2335 *destLen = stream.total_out + 10L;
2337 /* write CRC and Length */
2338 uLong crc = crc32(0L, source, sourceLen);
2340 for (n = 0; n < 4; ++n, ++*destLen) {
2341 dest[*destLen] = (int) (crc & 0xff);
2344 uLong len = stream.total_in;
2345 for (n = 0; n < 4; ++n, ++*destLen) {
2346 dest[*destLen] = (int) (len & 0xff);
2349 err = deflateEnd(&stream);
2356 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2358 int CompressBuffer(StrBuf *Buf)
2361 char *compressed_data = NULL;
2362 size_t compressed_len, bufsize;
2365 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2366 compressed_data = malloc(compressed_len);
2368 if (compressed_data == NULL)
2370 /* Flush some space after the used payload so valgrind shuts up... */
2371 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2372 Buf->buf[Buf->BufUsed + i++] = '\0';
2373 if (compress_gzip((Bytef *) compressed_data,
2376 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2379 Buf->buf = compressed_data;
2380 Buf->BufUsed = compressed_len;
2381 Buf->BufSize = bufsize;
2382 /* Flush some space after the used payload so valgrind shuts up... */
2384 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2385 Buf->buf[Buf->BufUsed + i++] = '\0';
2388 free(compressed_data);
2390 #endif /* HAVE_ZLIB */
2395 * @brief decode a buffer from base 64 encoding; destroys original
2396 * @param Buf Buffor to transform
2398 int StrBufDecodeBase64(StrBuf *Buf)
2402 if (Buf == NULL) return -1;
2404 xferbuf = (char*) malloc(Buf->BufSize);
2405 siz = CtdlDecodeBase64(xferbuf,
2415 * @brief decode a buffer from base 64 encoding; destroys original
2416 * @param Buf Buffor to transform
2418 int StrBufDecodeHex(StrBuf *Buf)
2421 char *pch, *pche, *pchi;
2423 if (Buf == NULL) return -1;
2425 pch = pchi = Buf->buf;
2426 pche = pch + Buf->BufUsed;
2428 while (pchi < pche){
2429 ch = decode_hex(pchi);
2436 Buf->BufUsed = pch - Buf->buf;
2437 return Buf->BufUsed;
2441 * @brief replace all chars >0x20 && < 0x7F with Mute
2442 * @param Mute char to put over invalid chars
2443 * @param Buf Buffor to transform
2445 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2449 if (Buf == NULL) return -1;
2450 pch = (unsigned char *)Buf->buf;
2451 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2452 if ((*pch < 0x20) || (*pch > 0x7F))
2456 return Buf->BufUsed;
2461 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2462 * @param Buf Buffer to translate
2463 * @param StripBlanks Reduce several blanks to one?
2465 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2471 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2472 Buf->buf[Buf->BufUsed - 1] = '\0';
2477 while (a < Buf->BufUsed) {
2478 if (Buf->buf[a] == '+')
2480 else if (Buf->buf[a] == '%') {
2481 /* don't let % chars through, rather truncate the input. */
2482 if (a + 2 > Buf->BufUsed) {
2487 hex[0] = Buf->buf[a + 1];
2488 hex[1] = Buf->buf[a + 2];
2491 sscanf(hex, "%02x", &b);
2492 Buf->buf[a] = (char) b;
2493 len = Buf->BufUsed - a - 2;
2495 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2507 * @brief RFC2047-encode a header field if necessary.
2508 * If no non-ASCII characters are found, the string
2509 * will be copied verbatim without encoding.
2511 * @param target Target buffer.
2512 * @param source Source string to be encoded.
2513 * @returns encoded length; -1 if non success.
2515 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2517 const char headerStr[] = "=?UTF-8?Q?";
2518 int need_to_encode = 0;
2522 if ((source == NULL) ||
2526 while ((i < source->BufUsed) &&
2527 (!IsEmptyStr (&source->buf[i])) &&
2528 (need_to_encode == 0)) {
2529 if (((unsigned char) source->buf[i] < 32) ||
2530 ((unsigned char) source->buf[i] > 126)) {
2536 if (!need_to_encode) {
2537 if (*target == NULL) {
2538 *target = NewStrBufPlain(source->buf, source->BufUsed);
2541 FlushStrBuf(*target);
2542 StrBufAppendBuf(*target, source, 0);
2544 return (*target)->BufUsed;
2546 if (*target == NULL)
2547 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2548 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2549 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2550 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2551 (*target)->BufUsed = sizeof(headerStr) - 1;
2552 for (i=0; (i < source->BufUsed); ++i) {
2553 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2554 IncreaseBuf(*target, 1, 0);
2555 ch = (unsigned char) source->buf[i];
2556 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2557 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2558 (*target)->BufUsed += 3;
2561 (*target)->buf[(*target)->BufUsed] = ch;
2562 (*target)->BufUsed++;
2566 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2567 IncreaseBuf(*target, 1, 0);
2569 (*target)->buf[(*target)->BufUsed++] = '?';
2570 (*target)->buf[(*target)->BufUsed++] = '=';
2571 (*target)->buf[(*target)->BufUsed] = '\0';
2572 return (*target)->BufUsed;;
2576 * @brief replaces all occurances of 'search' by 'replace'
2577 * @param buf Buffer to modify
2578 * @param search character to search
2579 * @param relpace character to replace search by
2581 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2586 for (i=0; i<buf->BufUsed; i++)
2587 if (buf->buf[i] == search)
2588 buf->buf[i] = replace;
2595 * @brief Wrapper around iconv_open()
2596 * Our version adds aliases for non-standard Microsoft charsets
2597 * such as 'MS950', aliasing them to names like 'CP950'
2599 * @param tocode Target encoding
2600 * @param fromcode Source encoding
2602 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2605 iconv_t ic = (iconv_t)(-1) ;
2606 ic = iconv_open(tocode, fromcode);
2607 if (ic == (iconv_t)(-1) ) {
2608 char alias_fromcode[64];
2609 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2610 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2611 alias_fromcode[0] = 'C';
2612 alias_fromcode[1] = 'P';
2613 ic = iconv_open(tocode, alias_fromcode);
2616 *(iconv_t *)pic = ic;
2622 * @brief find one chunk of a RFC822 encoded string
2623 * @param Buffer where to search
2624 * @param bptr where to start searching
2625 * @returns found position, NULL if none.
2627 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2630 /* Find the next ?Q? */
2631 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2634 end = strchr(bptr + 2, '?');
2639 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2640 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2641 (*(end + 2) == '?')) {
2642 /* skip on to the end of the cluster, the next ?= */
2643 end = strstr(end + 3, "?=");
2646 /* sort of half valid encoding, try to find an end. */
2647 end = strstr(bptr, "?=");
2652 * @brief swaps the contents of two StrBufs
2653 * this is to be used to have cheap switched between a work-buffer and a target buffer
2654 * @param A First one
2655 * @param B second one
2657 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2661 memcpy(&C, A, sizeof(*A));
2662 memcpy(A, B, sizeof(*B));
2663 memcpy(B, &C, sizeof(C));
2669 * @brief convert one buffer according to the preselected iconv pointer PIC
2670 * @param ConvertBuf buffer we need to translate
2671 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2672 * @param pic Pointer to the iconv-session Object
2674 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2680 char *ibuf; /**< Buffer of characters to be converted */
2681 char *obuf; /**< Buffer for converted characters */
2682 size_t ibuflen; /**< Length of input buffer */
2683 size_t obuflen; /**< Length of output buffer */
2686 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2687 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2688 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2690 ic = *(iconv_t*)pic;
2691 ibuf = ConvertBuf->buf;
2692 ibuflen = ConvertBuf->BufUsed;
2694 obuflen = TmpBuf->BufSize;
2696 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2699 if (errno == E2BIG) {
2701 IncreaseBuf(TmpBuf, 0, 0);
2706 else if (errno == EILSEQ){
2707 /* hm, invalid utf8 sequence... what to do now? */
2708 /* An invalid multibyte sequence has been encountered in the input */
2710 else if (errno == EINVAL) {
2711 /* An incomplete multibyte sequence has been encountered in the input. */
2714 FlushStrBuf(TmpBuf);
2717 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2718 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2720 /* little card game: wheres the red lady? */
2721 SwapBuffers(ConvertBuf, TmpBuf);
2722 FlushStrBuf(TmpBuf);
2729 * @brief catches one RFC822 encoded segment, and decodes it.
2730 * @param Target buffer to fill with result
2731 * @param DecodeMe buffer with stuff to process
2732 * @param SegmentStart points to our current segment in DecodeMe
2733 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2734 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2735 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2736 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2738 inline static void DecodeSegment(StrBuf *Target,
2739 const StrBuf *DecodeMe,
2743 StrBuf *ConvertBuf2,
2744 StrBuf *FoundCharset)
2750 iconv_t ic = (iconv_t)(-1);
2752 /* Now we handle foreign character sets properly encoded
2753 * in RFC2047 format.
2755 StaticBuf.buf = SegmentStart;
2756 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2757 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2758 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2759 if (FoundCharset != NULL) {
2760 FlushStrBuf(FoundCharset);
2761 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2763 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2764 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2766 *encoding = toupper(*encoding);
2767 if (*encoding == 'B') { /**< base64 */
2768 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2770 ConvertBuf->BufUsed);
2772 else if (*encoding == 'Q') { /**< quoted-printable */
2776 while (pos < ConvertBuf->BufUsed)
2778 if (ConvertBuf->buf[pos] == '_')
2779 ConvertBuf->buf[pos] = ' ';
2783 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2786 ConvertBuf->BufUsed);
2789 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2792 ctdl_iconv_open("UTF-8", charset, &ic);
2793 if (ic != (iconv_t)(-1) ) {
2795 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2796 StrBufAppendBuf(Target, ConvertBuf2, 0);
2801 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2807 * @brief Handle subjects with RFC2047 encoding such as:
2808 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2809 * @param Target where to put the decoded string to
2810 * @param DecodeMe buffer with encoded string
2811 * @param DefaultCharset if we don't find one, which should we use?
2812 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2813 * put it here for later use where no string might be known.
2815 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2817 StrBuf *ConvertBuf, *ConvertBuf2;
2818 char *start, *end, *next, *nextend, *ptr = NULL;
2820 iconv_t ic = (iconv_t)(-1) ;
2825 int illegal_non_rfc2047_encoding = 0;
2827 /* Sometimes, badly formed messages contain strings which were simply
2828 * written out directly in some foreign character set instead of
2829 * using RFC2047 encoding. This is illegal but we will attempt to
2830 * handle it anyway by converting from a user-specified default
2831 * charset to UTF-8 if we see any nonprintable characters.
2834 len = StrLength(DecodeMe);
2835 for (i=0; i<DecodeMe->BufUsed; ++i) {
2836 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2837 illegal_non_rfc2047_encoding = 1;
2842 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2843 if ((illegal_non_rfc2047_encoding) &&
2844 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2845 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2848 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2849 if (ic != (iconv_t)(-1) ) {
2850 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2856 /* pre evaluate the first pair */
2857 nextend = end = NULL;
2858 len = StrLength(DecodeMe);
2859 start = strstr(DecodeMe->buf, "=?");
2860 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2862 end = FindNextEnd (DecodeMe, start);
2864 StrBufAppendBuf(Target, DecodeMe, 0);
2865 FreeStrBuf(&ConvertBuf);
2869 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2871 if (start != DecodeMe->buf) {
2874 nFront = start - DecodeMe->buf;
2875 StrBufAppendBufPlain(Target, DecodeMe->buf, nFront, 0);
2879 * Since spammers will go to all sorts of absurd lengths to get their
2880 * messages through, there are LOTS of corrupt headers out there.
2881 * So, prevent a really badly formed RFC2047 header from throwing
2882 * this function into an infinite loop.
2884 while ((start != NULL) &&
2891 DecodeSegment(Target,
2899 next = strstr(end, "=?");
2901 if ((next != NULL) &&
2903 nextend = FindNextEnd(DecodeMe, next);
2904 if (nextend == NULL)
2907 /* did we find two partitions */
2908 if ((next != NULL) &&
2912 while ((ptr < next) &&
2918 /* did we find a gab just filled with blanks? */
2921 long gap = next - start;
2926 /* now terminate the gab at the end */
2927 delta = (next - end) - 2; ////TODO: const!
2928 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2929 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2931 /* move next to its new location. */
2936 /* our next-pair is our new first pair now. */
2942 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2943 if ((end != NULL) && (end < nextend)) {
2945 while ( (ptr < nextend) &&
2952 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2954 FreeStrBuf(&ConvertBuf);
2955 FreeStrBuf(&ConvertBuf2);
2959 * @brief evaluate the length of an utf8 special character sequence
2960 * @param Char the character to examine
2961 * @returns width of utf8 chars in bytes
2963 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2968 while ((n < 8) && ((test & *CharS) != 0)) {
2972 if ((n > 6) || ((CharE - CharS) > n))
2978 * @brief detect whether this char starts an utf-8 encoded char
2979 * @param Char character to inspect
2980 * @returns yes or no
2982 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2984 /** 11??.???? indicates an UTF8 Sequence. */
2985 return ((Char & 0xC0) != 0);
2989 * @brief measure the number of glyphs in an UTF8 string...
2990 * @param str string to measure
2991 * @returns the length of str
2993 long StrBuf_Utf8StrLen(StrBuf *Buf)
2999 if ((Buf == NULL) || (Buf->BufUsed == 0))
3002 eptr = Buf->buf + Buf->BufUsed;
3003 while ((aptr < eptr) && (*aptr != '\0')) {
3004 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3005 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3006 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3019 * @brief cuts a string after maxlen glyphs
3020 * @param str string to cut to maxlen glyphs
3021 * @param maxlen how long may the string become?
3022 * @returns pointer to maxlen or the end of the string
3024 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3030 eptr = Buf->buf + Buf->BufUsed;
3031 while ((aptr < eptr) && (*aptr != '\0')) {
3032 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3033 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3034 while ((m-- > 0) && (*aptr++ != '\0'))
3043 Buf->BufUsed = aptr - Buf->buf;
3044 return Buf->BufUsed;
3047 return Buf->BufUsed;
3053 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3054 * @param LineBuf your line will be copied here.
3055 * @param Buf BLOB with lines of text...
3056 * @param Ptr moved arround to keep the next-line across several iterations
3057 * has to be &NULL on start; will be &NotNULL on end of buffer
3058 * @returns size of copied buffer
3060 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3062 const char *aptr, *ptr, *eptr;
3064 /////TODO: use NotNULL here too!
3069 ptr = aptr = Buf->buf;
3073 optr = LineBuf->buf;
3074 eptr = Buf->buf + Buf->BufUsed;
3075 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3077 while ((*ptr != '\n') &&
3084 LineBuf->BufUsed = optr - LineBuf->buf;
3085 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3086 optr = LineBuf->buf + LineBuf->BufUsed;
3087 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3090 LineBuf->BufUsed = optr - LineBuf->buf;
3099 return Buf->BufUsed - (ptr - Buf->buf);