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 * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
34 * StrBuf is a versatile class, aiding the handling of dynamic strings
35 * * reduce de/reallocations
36 * * reduce the need to remeasure it
37 * * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
38 * * allow asyncroneous IO for line and Blob based operations
39 * * reduce the use of memove in those
40 * * Quick filling in several operations with append functions
44 * @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
49 * @defgroup StrBuf_Cast Cast operators to interact with char* based code
51 * use these operators to interfere with code demanding char*;
52 * if you need to own the content, smash me. Avoid, since we loose the length information.
56 * @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
58 * operations to get your Strings into a StrBuf, manipulating them, or appending
61 * @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence
63 * Quick tokenizer; demands of the user to pull its tokens in sequence
67 * @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
69 * versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
73 * @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
75 * File IO to fill StrBufs; Works with work-buffer shared across several calls;
76 * External Cursor to maintain the current read position inside of the buffer
77 * the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower)
81 * @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
87 * @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
89 * these functions translate the content of a buffer into another representation;
90 * some are combined Fillers and encoders
94 * Private Structure for the Stringbuffer
97 char *buf; /**< the pointer to the dynamic buffer */
98 long BufSize; /**< how many spcae do we optain */
99 long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
100 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
102 long nIncreases; /**< for profiling; cound how many times we needed more */
103 char bt [SIZ]; /**< Stacktrace of last increase */
104 char bt_lastinc [SIZ]; /**< How much did we increase last time? */
109 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
110 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
113 #ifdef HAVE_BACKTRACE
114 static void StrBufBacktrace(StrBuf *Buf, int which)
118 void *stack_frames[50];
123 pstart = pch = Buf->bt;
125 pstart = pch = Buf->bt_lastinc;
126 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
127 strings = backtrace_symbols(stack_frames, size);
128 for (i = 0; i < size; i++) {
130 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
132 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
143 * @ingroup StrBuf_Cast
144 * @brief Cast operator to Plain String
145 * @note if the buffer is altered by StrBuf operations, this pointer may become
146 * invalid. So don't lean on it after altering the buffer!
147 * Since this operation is considered cheap, rather call it often than risking
148 * your pointer to become invalid!
149 * @param Str the string we want to get the c-string representation for
150 * @returns the Pointer to the Content. Don't mess with it!
152 inline const char *ChrPtr(const StrBuf *Str)
160 * @ingroup StrBuf_Cast
161 * @brief since we know strlen()'s result, provide it here.
162 * @param Str the string to return the length to
163 * @returns contentlength of the buffer
165 inline int StrLength(const StrBuf *Str)
167 return (Str != NULL) ? Str->BufUsed : 0;
171 * @ingroup StrBuf_DeConstructors
172 * @brief local utility function to resize the buffer
173 * @param Buf the buffer whichs storage we should increase
174 * @param KeepOriginal should we copy the original buffer or just start over with a new one
175 * @param DestSize what should fit in after?
177 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
180 size_t NewSize = Buf->BufSize * 2;
186 while (NewSize <= DestSize)
189 NewBuf= (char*) malloc(NewSize);
193 if (KeepOriginal && (Buf->BufUsed > 0))
195 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
204 Buf->BufSize = NewSize;
207 #ifdef HAVE_BACKTRACE
208 StrBufBacktrace(Buf, 1);
215 * @ingroup StrBuf_DeConstructors
216 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
217 * @param Buf Buffer to shrink (has to be empty)
218 * @param ThreshHold if the buffer is bigger then this, its readjusted
219 * @param NewSize if we Shrink it, how big are we going to be afterwards?
221 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
223 if (Buf->BufUsed > ThreshHold) {
225 Buf->buf = (char*) malloc(NewSize);
227 Buf->BufSize = NewSize;
232 * @ingroup StrBuf_DeConstructors
233 * @brief shrink long term buffers to their real size so they don't waste memory
234 * @param Buf buffer to shrink
235 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
236 * @returns physical size of the buffer
238 long StrBufShrinkToFit(StrBuf *Buf, int Force)
241 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
243 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
244 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
245 Buf->BufSize = Buf->BufUsed + 1;
253 * @ingroup StrBuf_DeConstructors
254 * @brief Allocate a new buffer with default buffer size
255 * @returns the new stringbuffer
257 StrBuf* NewStrBuf(void)
261 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
262 NewBuf->buf = (char*) malloc(BaseStrBufSize);
263 NewBuf->buf[0] = '\0';
264 NewBuf->BufSize = BaseStrBufSize;
266 NewBuf->ConstBuf = 0;
268 NewBuf->nIncreases = 0;
269 NewBuf->bt[0] = '\0';
270 NewBuf->bt_lastinc[0] = '\0';
271 #ifdef HAVE_BACKTRACE
272 StrBufBacktrace(NewBuf, 0);
279 * @ingroup StrBuf_DeConstructors
280 * @brief Copy Constructor; returns a duplicate of CopyMe
281 * @param CopyMe Buffer to faxmilate
282 * @returns the new stringbuffer
284 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
291 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
292 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
293 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
294 NewBuf->BufUsed = CopyMe->BufUsed;
295 NewBuf->BufSize = CopyMe->BufSize;
296 NewBuf->ConstBuf = 0;
298 NewBuf->nIncreases = 0;
299 NewBuf->bt[0] = '\0';
300 NewBuf->bt_lastinc[0] = '\0';
301 #ifdef HAVE_BACKTRACE
302 StrBufBacktrace(NewBuf, 0);
309 * @ingroup StrBuf_DeConstructors
310 * @brief create a new Buffer using an existing c-string
311 * this function should also be used if you want to pre-suggest
312 * the buffer size to allocate in conjunction with ptr == NULL
313 * @param ptr the c-string to copy; may be NULL to create a blank instance
314 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
315 * @returns the new stringbuffer
317 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
320 size_t Siz = BaseStrBufSize;
323 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
325 CopySize = strlen((ptr != NULL)?ptr:"");
329 while (Siz <= CopySize)
332 NewBuf->buf = (char*) malloc(Siz);
333 NewBuf->BufSize = Siz;
335 memcpy(NewBuf->buf, ptr, CopySize);
336 NewBuf->buf[CopySize] = '\0';
337 NewBuf->BufUsed = CopySize;
340 NewBuf->buf[0] = '\0';
343 NewBuf->ConstBuf = 0;
345 NewBuf->nIncreases = 0;
346 NewBuf->bt[0] = '\0';
347 NewBuf->bt_lastinc[0] = '\0';
348 #ifdef HAVE_BACKTRACE
349 StrBufBacktrace(NewBuf, 0);
356 * @ingroup StrBuf_DeConstructors
357 * @brief Set an existing buffer from a c-string
358 * @param Buf buffer to load
359 * @param ptr c-string to put into
360 * @param nChars set to -1 if we should work 0-terminated
361 * @returns the new length of the string
363 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
365 size_t Siz = Buf->BufSize;
369 CopySize = strlen(ptr);
373 while (Siz <= CopySize)
376 if (Siz != Buf->BufSize)
377 IncreaseBuf(Buf, 0, Siz);
378 memcpy(Buf->buf, ptr, CopySize);
379 Buf->buf[CopySize] = '\0';
380 Buf->BufUsed = CopySize;
387 * @ingroup StrBuf_DeConstructors
388 * @brief use strbuf as wrapper for a string constant for easy handling
389 * @param StringConstant a string to wrap
390 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
392 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
396 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
397 NewBuf->buf = (char*) StringConstant;
398 NewBuf->BufSize = SizeOfStrConstant;
399 NewBuf->BufUsed = SizeOfStrConstant;
400 NewBuf->ConstBuf = 1;
402 NewBuf->nIncreases = 0;
403 NewBuf->bt[0] = '\0';
404 NewBuf->bt_lastinc[0] = '\0';
411 * @ingroup StrBuf_DeConstructors
412 * @brief flush the content of a Buf; keep its struct
413 * @param buf Buffer to flush
415 int FlushStrBuf(StrBuf *buf)
427 * @ingroup StrBuf_DeConstructors
428 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
429 * @param buf Buffer to wipe
431 int FLUSHStrBuf(StrBuf *buf)
437 if (buf->BufUsed > 0) {
438 memset(buf->buf, 0, buf->BufUsed);
445 int hFreeDbglog = -1;
448 * @ingroup StrBuf_DeConstructors
449 * @brief Release a Buffer
450 * Its a double pointer, so it can NULL your pointer
451 * so fancy SIG11 appear instead of random results
452 * @param FreeMe Pointer Pointer to the buffer to free
454 void FreeStrBuf (StrBuf **FreeMe)
459 if (hFreeDbglog == -1){
460 pid_t pid = getpid();
462 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
463 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
465 if ((*FreeMe)->nIncreases > 0)
469 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
470 (*FreeMe)->nIncreases,
474 (*FreeMe)->bt_lastinc);
475 n = write(hFreeDbglog, buf, n);
481 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
484 n = write(hFreeDbglog, buf, n);
487 if (!(*FreeMe)->ConstBuf)
488 free((*FreeMe)->buf);
494 * @ingroup StrBuf_DeConstructors
495 * @brief flatten a Buffer to the Char * we return
496 * Its a double pointer, so it can NULL your pointer
497 * so fancy SIG11 appear instead of random results
498 * The Callee then owns the buffer and is responsible for freeing it.
499 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
500 * @returns the pointer of the buffer; Callee owns the memory thereafter.
502 char *SmashStrBuf (StrBuf **SmashMe)
506 if (*SmashMe == NULL)
509 if (hFreeDbglog == -1){
510 pid_t pid = getpid();
512 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
513 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
515 if ((*SmashMe)->nIncreases > 0)
519 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
520 (*SmashMe)->nIncreases,
524 (*SmashMe)->bt_lastinc);
525 n = write(hFreeDbglog, buf, n);
531 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
533 (*SmashMe)->BufSize);
534 n = write(hFreeDbglog, buf, n);
537 Ret = (*SmashMe)->buf;
544 * @ingroup StrBuf_DeConstructors
545 * @brief Release the buffer
546 * If you want put your StrBuf into a Hash, use this as Destructor.
547 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
549 void HFreeStrBuf (void *VFreeMe)
551 StrBuf *FreeMe = (StrBuf*)VFreeMe;
555 if (hFreeDbglog == -1){
556 pid_t pid = getpid();
558 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
559 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
561 if (FreeMe->nIncreases > 0)
565 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
571 write(hFreeDbglog, buf, n);
577 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
583 if (!FreeMe->ConstBuf)
590 * @brief Wrapper around atol
592 long StrTol(const StrBuf *Buf)
597 return atol(Buf->buf);
604 * @brief Wrapper around atoi
606 int StrToi(const StrBuf *Buf)
610 if (Buf->BufUsed > 0)
611 return atoi(Buf->buf);
618 * @brief Checks to see if the string is a pure number
620 int StrBufIsNumber(const StrBuf *Buf) {
625 strtoll(Buf->buf, &pEnd, 10);
626 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
633 * @brief modifies a Single char of the Buf
634 * You can point to it via char* or a zero-based integer
635 * @param Buf The buffer to manipulate
636 * @param ptr char* to zero; use NULL if unused
637 * @param nThChar zero based pointer into the string; use -1 if unused
638 * @param PeekValue The Character to place into the position
640 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
645 nThChar = ptr - Buf->buf;
646 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
648 Buf->buf[nThChar] = PeekValue;
654 * @brief Append a StringBuffer to the buffer
655 * @param Buf Buffer to modify
656 * @param AppendBuf Buffer to copy at the end of our buffer
657 * @param Offset Should we start copying from an offset?
659 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
661 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
664 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
667 AppendBuf->BufUsed + Buf->BufUsed);
669 memcpy(Buf->buf + Buf->BufUsed,
670 AppendBuf->buf + Offset,
671 AppendBuf->BufUsed - Offset);
672 Buf->BufUsed += AppendBuf->BufUsed - Offset;
673 Buf->buf[Buf->BufUsed] = '\0';
679 * @brief Append a C-String to the buffer
680 * @param Buf Buffer to modify
681 * @param AppendBuf Buffer to copy at the end of our buffer
682 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
683 * @param Offset Should we start copying from an offset?
685 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
688 long BufSizeRequired;
690 if ((AppendBuf == NULL) || (Buf == NULL))
694 aps = strlen(AppendBuf + Offset);
696 aps = AppendSize - Offset;
698 BufSizeRequired = Buf->BufUsed + aps + 1;
699 if (Buf->BufSize <= BufSizeRequired)
700 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
702 memcpy(Buf->buf + Buf->BufUsed,
706 Buf->buf[Buf->BufUsed] = '\0';
711 * @brief Callback for cURL to append the webserver reply to a buffer
712 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
713 * @param size pre-defined by the cURL API; see man 3 curl for mre info
714 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
715 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
717 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
726 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
732 * @ingroup StrBuf_DeEnCoder
733 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
734 * @param OutBuf the output buffer
735 * @param In Buffer to encode
736 * @param PlainIn way in from plain old c strings
738 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
740 const char *pch, *pche;
743 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
744 int eclen = sizeof(ec) -1;
746 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
748 if (PlainIn != NULL) {
749 len = strlen(PlainIn);
755 pche = pch + In->BufUsed;
762 pt = OutBuf->buf + OutBuf->BufUsed;
763 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
767 IncreaseBuf(OutBuf, 1, -1);
768 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
769 pt = OutBuf->buf + OutBuf->BufUsed;
773 for (b = 0; b < eclen; ++b) {
783 *(pt + 1) = ((ch & 0xF0) > 0x90) ?
784 ('A' + ((ch & 0xF0) >> 4) - 0x0A) :
785 ('0' + ((ch & 0xF0) >> 4)) ;
786 *(pt + 2) = ((ch & 0x0F) > 0x09) ?
787 ('A' + (ch & 0x0F) - 0x0A) :
788 ('0' + (ch & 0x0F)) ;
790 OutBuf->BufUsed += 3;
802 * @ingroup StrBuf_DeEnCoder
803 * @brief Append a string, escaping characters which have meaning in HTML.
805 * @param Target target buffer
806 * @param Source source buffer; set to NULL if you just have a C-String
807 * @param PlainIn Plain-C string to append; set to NULL if unused
808 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
809 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
810 * if set to 2, linebreaks are replaced by <br/>
812 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
814 const char *aptr, *eiptr;
818 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
821 if (PlainIn != NULL) {
823 len = strlen(PlainIn);
828 eiptr = aptr + Source->BufUsed;
829 len = Source->BufUsed;
835 bptr = Target->buf + Target->BufUsed;
836 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
838 while (aptr < eiptr){
840 IncreaseBuf(Target, 1, -1);
841 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
842 bptr = Target->buf + Target->BufUsed;
845 memcpy(bptr, "<", 4);
847 Target->BufUsed += 4;
849 else if (*aptr == '>') {
850 memcpy(bptr, ">", 4);
852 Target->BufUsed += 4;
854 else if (*aptr == '&') {
855 memcpy(bptr, "&", 5);
857 Target->BufUsed += 5;
859 else if (*aptr == '"') {
860 memcpy(bptr, """, 6);
862 Target->BufUsed += 6;
864 else if (*aptr == '\'') {
865 memcpy(bptr, "'", 5);
867 Target->BufUsed += 5;
869 else if (*aptr == LB) {
874 else if (*aptr == RB) {
879 else if (*aptr == QU) {
884 else if ((*aptr == 32) && (nbsp == 1)) {
885 memcpy(bptr, " ", 6);
887 Target->BufUsed += 6;
889 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
890 *bptr='\0'; /* nothing */
892 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
893 memcpy(bptr, "<br/>", 11);
895 Target->BufUsed += 11;
899 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
900 *bptr='\0'; /* nothing */
910 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
912 return Target->BufUsed;
916 * @ingroup StrBuf_DeEnCoder
917 * @brief Append a string, escaping characters which have meaning in HTML.
918 * Converts linebreaks into blanks; escapes single quotes
919 * @param Target target buffer
920 * @param Source source buffer; set to NULL if you just have a C-String
921 * @param PlainIn Plain-C string to append; set to NULL if unused
923 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
925 const char *aptr, *eiptr;
929 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
932 if (PlainIn != NULL) {
934 len = strlen(PlainIn);
939 eiptr = aptr + Source->BufUsed;
940 len = Source->BufUsed;
946 eptr = Target->buf + Target->BufSize - 8;
947 tptr = Target->buf + Target->BufUsed;
949 while (aptr < eiptr){
951 IncreaseBuf(Target, 1, -1);
952 eptr = Target->buf + Target->BufSize - 8;
953 tptr = Target->buf + Target->BufUsed;
960 else if (*aptr == '\r') {
964 else if (*aptr == '\'') {
970 Target->BufUsed += 5;
983 * @ingroup StrBuf_DeEnCoder
984 * @brief Append a string, escaping characters which have meaning in ICAL.
986 * @param Target target buffer
987 * @param Source source buffer; set to NULL if you just have a C-String
988 * @param PlainIn Plain-C string to append; set to NULL if unused
990 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
992 const char *aptr, *eiptr;
996 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
999 if (PlainIn != NULL) {
1001 len = strlen(PlainIn);
1006 eiptr = aptr + Source->BufUsed;
1007 len = Source->BufUsed;
1013 eptr = Target->buf + Target->BufSize - 8;
1014 tptr = Target->buf + Target->BufUsed;
1016 while (aptr < eiptr){
1017 if(tptr + 3 >= eptr) {
1018 IncreaseBuf(Target, 1, -1);
1019 eptr = Target->buf + Target->BufSize - 8;
1020 tptr = Target->buf + Target->BufUsed;
1023 if (*aptr == '\n') {
1030 else if (*aptr == '\r') {
1037 else if (*aptr == ',') {
1053 * @ingroup StrBuf_DeEnCoder
1054 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1056 * @param Target target buffer
1057 * @param Source source buffer; set to NULL if you just have a C-String
1058 * @param PlainIn Plain-C string to append; set to NULL if unused
1059 * @returns size of result or -1
1061 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1063 const char *aptr, *eiptr;
1067 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1070 if (PlainIn != NULL) {
1072 len = strlen(PlainIn);
1077 eiptr = aptr + Source->BufUsed;
1078 len = Source->BufUsed;
1084 bptr = Target->buf + Target->BufUsed;
1085 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1087 while (aptr < eiptr){
1089 IncreaseBuf(Target, 1, -1);
1090 eptr = Target->buf + Target->BufSize - 3;
1091 bptr = Target->buf + Target->BufUsed;
1098 Target->BufUsed += 2;
1099 } else if (*aptr == '\\') {
1104 Target->BufUsed += 2;
1114 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1116 return Target->BufUsed;
1120 * @ingroup StrBuf_DeEnCoder
1121 * @brief Append a string, escaping characters which have meaning in HTML + json.
1123 * @param Target target buffer
1124 * @param Source source buffer; set to NULL if you just have a C-String
1125 * @param PlainIn Plain-C string to append; set to NULL if unused
1126 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1127 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1128 * if set to 2, linebreaks are replaced by <br/>
1130 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1132 const char *aptr, *eiptr;
1135 int IsUtf8Sequence = 0;
1137 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1140 if (PlainIn != NULL) {
1142 len = strlen(PlainIn);
1147 eiptr = aptr + Source->BufUsed;
1148 len = Source->BufUsed;
1154 bptr = Target->buf + Target->BufUsed;
1155 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1157 while (aptr < eiptr){
1159 IncreaseBuf(Target, 1, -1);
1160 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1161 bptr = Target->buf + Target->BufUsed;
1164 memcpy(bptr, "<", 4);
1166 Target->BufUsed += 4;
1168 else if (*aptr == '>') {
1169 memcpy(bptr, ">", 4);
1171 Target->BufUsed += 4;
1173 else if (*aptr == '&') {
1174 memcpy(bptr, "&", 5);
1176 Target->BufUsed += 5;
1178 else if (*aptr == LB) {
1183 else if (*aptr == RB) {
1188 else if ((*aptr == 32) && (nbsp == 1)) {
1189 memcpy(bptr, " ", 6);
1191 Target->BufUsed += 6;
1193 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1194 *bptr='\0'; /* nothing */
1196 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1197 memcpy(bptr, "<br/>", 11);
1199 Target->BufUsed += 11;
1202 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1203 *bptr='\0'; /* nothing */
1206 else if ((*aptr == '"') || (*aptr == QU)) {
1211 Target->BufUsed += 2;
1212 } else if (*aptr == '\\') {
1217 Target->BufUsed += 2;
1220 if (IsUtf8Sequence != 0) {
1229 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1241 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1243 return Target->BufUsed;
1249 * @brief extracts a substring from Source into dest
1250 * @param dest buffer to place substring into
1251 * @param Source string to copy substring from
1252 * @param Offset chars to skip from start
1253 * @param nChars number of chars to copy
1254 * @returns the number of chars copied; may be different from nChars due to the size of Source
1256 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1258 size_t NCharsRemain;
1259 if (Offset > Source->BufUsed)
1264 if (Offset + nChars < Source->BufUsed)
1266 if (nChars >= dest->BufSize)
1267 IncreaseBuf(dest, 0, nChars + 1);
1268 memcpy(dest->buf, Source->buf + Offset, nChars);
1269 dest->BufUsed = nChars;
1270 dest->buf[dest->BufUsed] = '\0';
1273 NCharsRemain = Source->BufUsed - Offset;
1274 if (NCharsRemain >= dest->BufSize)
1275 IncreaseBuf(dest, 0, NCharsRemain + 1);
1276 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1277 dest->BufUsed = NCharsRemain;
1278 dest->buf[dest->BufUsed] = '\0';
1279 return NCharsRemain;
1284 * @brief sprintf like function appending the formated string to the buffer
1285 * vsnprintf version to wrap into own calls
1286 * @param Buf Buffer to extend by format and Params
1287 * @param format printf alike format to add
1288 * @param ap va_list containing the items for format
1290 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1298 if ((Buf == NULL) || (format == NULL))
1301 BufSize = Buf->BufSize;
1302 nWritten = Buf->BufSize + 1;
1303 Offset = Buf->BufUsed;
1304 newused = Offset + nWritten;
1306 while (newused >= BufSize) {
1308 nWritten = vsnprintf(Buf->buf + Offset,
1309 Buf->BufSize - Offset,
1312 newused = Offset + nWritten;
1313 if (newused >= Buf->BufSize) {
1314 IncreaseBuf(Buf, 1, newused);
1315 newused = Buf->BufSize + 1;
1318 Buf->BufUsed = Offset + nWritten;
1319 BufSize = Buf->BufSize;
1327 * @brief sprintf like function appending the formated string to the buffer
1328 * @param Buf Buffer to extend by format and Params
1329 * @param format printf alike format to add
1331 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1339 if ((Buf == NULL) || (format == NULL))
1342 BufSize = Buf->BufSize;
1343 nWritten = Buf->BufSize + 1;
1344 Offset = Buf->BufUsed;
1345 newused = Offset + nWritten;
1347 while (newused >= BufSize) {
1348 va_start(arg_ptr, format);
1349 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1350 Buf->BufSize - Buf->BufUsed,
1353 newused = Buf->BufUsed + nWritten;
1354 if (newused >= Buf->BufSize) {
1355 IncreaseBuf(Buf, 1, newused);
1356 newused = Buf->BufSize + 1;
1359 Buf->BufUsed += nWritten;
1360 BufSize = Buf->BufSize;
1368 * @brief sprintf like function putting the formated string into the buffer
1369 * @param Buf Buffer to extend by format and Parameters
1370 * @param format printf alike format to add
1372 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1377 if ((Buf == NULL) || (format == NULL))
1380 nWritten = Buf->BufSize + 1;
1381 while (nWritten >= Buf->BufSize) {
1382 va_start(arg_ptr, format);
1383 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1385 if (nWritten >= Buf->BufSize) {
1386 IncreaseBuf(Buf, 0, 0);
1387 nWritten = Buf->BufSize + 1;
1390 Buf->BufUsed = nWritten ;
1396 * @ingroup StrBuf_Tokenizer
1397 * @brief Counts the numbmer of tokens in a buffer
1398 * @param source String to count tokens in
1399 * @param tok Tokenizer char to count
1400 * @returns numbers of tokenizer chars found
1402 int StrBufNum_tokens(const StrBuf *source, char tok)
1406 return num_tokens(source->buf, tok);
1410 * remove_token() - a tokenizer that kills, maims, and destroys
1413 * @ingroup StrBuf_Tokenizer
1414 * @brief a string tokenizer
1415 * @param Source StringBuffer to read into
1416 * @param parmnum n'th Parameter to remove
1417 * @param separator tokenizer character
1418 * @returns -1 if not found, else length of token.
1420 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1423 char *d, *s, *end; /* dest, source */
1426 /* Find desired @parameter */
1427 end = Source->buf + Source->BufUsed;
1429 while ((count < parmnum) &&
1432 /* End of string, bail! */
1437 if (*d == separator) {
1442 if ((d == NULL) || (d >= end))
1443 return 0; /* @Parameter not found */
1445 /* Find next @parameter */
1447 while ((*s && *s != separator) &&
1452 if (*s == separator)
1456 /* Hack and slash */
1458 memmove(d, s, Source->BufUsed - (s - Source->buf));
1459 Source->BufUsed += ReducedBy;
1461 else if (d == Source->buf) {
1463 Source->BufUsed = 0;
1467 Source->BufUsed += ReducedBy;
1480 * @ingroup StrBuf_Tokenizer
1481 * @brief a string tokenizer
1482 * @param dest Destination StringBuffer
1483 * @param Source StringBuffer to read into
1484 * @param parmnum n'th Parameter to extract
1485 * @param separator tokenizer character
1486 * @returns -1 if not found, else length of token.
1488 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1490 const char *s, *e; //* source * /
1491 int len = 0; //* running total length of extracted string * /
1492 int current_token = 0; //* token currently being processed * /
1495 dest->buf[0] = '\0';
1501 if ((Source == NULL) || (Source->BufUsed ==0)) {
1505 e = s + Source->BufUsed;
1508 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1510 while ((s<e) && !IsEmptyStr(s)) {
1511 if (*s == separator) {
1514 if (len >= dest->BufSize) {
1515 dest->BufUsed = len;
1516 if (IncreaseBuf(dest, 1, -1) < 0) {
1521 if ( (current_token == parmnum) &&
1522 (*s != separator)) {
1523 dest->buf[len] = *s;
1526 else if (current_token > parmnum) {
1532 dest->buf[len] = '\0';
1533 dest->BufUsed = len;
1535 if (current_token < parmnum) {
1536 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1539 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1548 * @ingroup StrBuf_Tokenizer
1549 * @brief a string tokenizer to fetch an integer
1550 * @param Source String containing tokens
1551 * @param parmnum n'th Parameter to extract
1552 * @param separator tokenizer character
1553 * @returns 0 if not found, else integer representation of the token
1555 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1565 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1572 * @ingroup StrBuf_Tokenizer
1573 * @brief a string tokenizer to fetch a long integer
1574 * @param Source String containing tokens
1575 * @param parmnum n'th Parameter to extract
1576 * @param separator tokenizer character
1577 * @returns 0 if not found, else long integer representation of the token
1579 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1589 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1597 * @ingroup StrBuf_Tokenizer
1598 * @brief a string tokenizer to fetch an unsigned long
1599 * @param Source String containing tokens
1600 * @param parmnum n'th Parameter to extract
1601 * @param separator tokenizer character
1602 * @returns 0 if not found, else unsigned long representation of the token
1604 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1615 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1619 return (unsigned long) atol(pnum);
1628 * @ingroup StrBuf_NextTokenizer
1629 * @brief a string tokenizer; Bounds checker
1630 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1631 * @param Source our tokenbuffer
1632 * @param pStart the token iterator pointer to inspect
1633 * @returns whether the revolving pointer is inside of the search range
1635 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1637 if ((Source == NULL) ||
1638 (*pStart == StrBufNOTNULL) ||
1639 (Source->BufUsed == 0))
1643 if (*pStart == NULL)
1647 else if (*pStart > Source->buf + Source->BufUsed)
1651 else if (*pStart <= Source->buf)
1660 * @ingroup StrBuf_NextTokenizer
1661 * @brief a string tokenizer
1662 * @param dest Destination StringBuffer
1663 * @param Source StringBuffer to read into
1664 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1665 * @param separator tokenizer
1666 * @returns -1 if not found, else length of token.
1668 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1670 const char *s; /* source */
1671 const char *EndBuffer; /* end stop of source buffer */
1672 int current_token = 0; /* token currently being processed */
1673 int len = 0; /* running total length of extracted string */
1675 if ((Source == NULL) ||
1676 (Source->BufUsed == 0) )
1678 *pStart = StrBufNOTNULL;
1682 EndBuffer = Source->buf + Source->BufUsed;
1686 dest->buf[0] = '\0';
1691 *pStart = EndBuffer + 1;
1695 if (*pStart == NULL)
1697 *pStart = Source->buf; /* we're starting to examine this buffer. */
1699 else if ((*pStart < Source->buf) ||
1700 (*pStart > EndBuffer ) )
1702 return -1; /* no more tokens to find. */
1706 /* start to find the next token */
1707 while ((s <= EndBuffer) &&
1708 (current_token == 0) )
1710 if (*s == separator)
1712 /* we found the next token */
1716 if (len >= dest->BufSize)
1718 /* our Dest-buffer isn't big enough, increase it. */
1719 dest->BufUsed = len;
1721 if (IncreaseBuf(dest, 1, -1) < 0) {
1722 /* WHUT? no more mem? bail out. */
1729 if ( (current_token == 0 ) && /* are we in our target token? */
1730 (!IsEmptyStr(s) ) &&
1731 (separator != *s) ) /* don't copy the token itself */
1733 dest->buf[len] = *s; /* Copy the payload */
1734 ++len; /* remember the bigger size. */
1740 /* did we reach the end? */
1741 if ((s > EndBuffer)) {
1742 EndBuffer = StrBufNOTNULL;
1743 *pStart = EndBuffer;
1746 *pStart = s; /* remember the position for the next run */
1749 /* sanitize our extracted token */
1750 dest->buf[len] = '\0';
1751 dest->BufUsed = len;
1758 * @ingroup StrBuf_NextTokenizer
1759 * @brief a string tokenizer
1760 * @param Source StringBuffer to read from
1761 * @param pStart pointer to the end of the last token. Feed with NULL.
1762 * @param separator tokenizer character
1763 * @param nTokens number of tokens to fastforward over
1764 * @returns -1 if not found, else length of token.
1766 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1768 const char *s, *EndBuffer; //* source * /
1769 int len = 0; //* running total length of extracted string * /
1770 int current_token = 0; //* token currently being processed * /
1772 if ((Source == NULL) ||
1773 (Source->BufUsed ==0)) {
1777 return Source->BufUsed;
1779 if (*pStart == NULL)
1780 *pStart = Source->buf;
1782 EndBuffer = Source->buf + Source->BufUsed;
1784 if ((*pStart < Source->buf) ||
1785 (*pStart > EndBuffer)) {
1793 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1795 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1796 if (*s == separator) {
1799 if (current_token >= nTokens) {
1811 * @ingroup StrBuf_NextTokenizer
1812 * @brief a string tokenizer to fetch an integer
1813 * @param Source StringBuffer to read from
1814 * @param pStart Cursor on the tokenstring
1815 * @param separator tokenizer character
1816 * @returns 0 if not found, else integer representation of the token
1818 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1828 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1835 * @ingroup StrBuf_NextTokenizer
1836 * @brief a string tokenizer to fetch a long integer
1837 * @param Source StringBuffer to read from
1838 * @param pStart Cursor on the tokenstring
1839 * @param separator tokenizer character
1840 * @returns 0 if not found, else long integer representation of the token
1842 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1852 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1860 * @ingroup StrBuf_NextTokenizer
1861 * @brief a string tokenizer to fetch an unsigned long
1862 * @param Source StringBuffer to read from
1863 * @param pStart Cursor on the tokenstring
1864 * @param separator tokenizer character
1865 * @returns 0 if not found, else unsigned long representation of the token
1867 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1878 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1882 return (unsigned long) atol(pnum);
1891 * @ingroup StrBuf_IO
1892 * @brief Read a line from socket
1893 * flushes and closes the FD on error
1894 * @param buf the buffer to get the input to
1895 * @param fd pointer to the filedescriptor to read
1896 * @param append Append to an existing string or replace?
1897 * @param Error strerror() on error
1898 * @returns numbers of chars read
1900 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1902 int len, rlen, slen;
1907 slen = len = buf->BufUsed;
1909 rlen = read(*fd, &buf->buf[len], 1);
1911 *Error = strerror(errno);
1918 if (buf->buf[len] == '\n')
1920 if (buf->buf[len] != '\r')
1922 if (len + 2 >= buf->BufSize) {
1924 buf->buf[len+1] = '\0';
1925 IncreaseBuf(buf, 1, -1);
1929 buf->buf[len] = '\0';
1934 * @ingroup StrBuf_BufferedIO
1935 * @brief Read a line from socket
1936 * flushes and closes the FD on error
1937 * @param Line the line to read from the fd / I/O Buffer
1938 * @param buf the buffer to get the input to
1939 * @param fd pointer to the filedescriptor to read
1940 * @param timeout number of successless selects until we bail out
1941 * @param selectresolution how long to wait on each select
1942 * @param Error strerror() on error
1943 * @returns numbers of chars read
1945 int StrBufTCP_read_buffered_line(StrBuf *Line,
1949 int selectresolution,
1953 int nSuccessLess = 0;
1960 if (buf->BufUsed > 0) {
1961 pch = strchr(buf->buf, '\n');
1964 len = pch - buf->buf;
1965 if (len > 0 && (*(pch - 1) == '\r') )
1967 StrBufSub(Line, buf, 0, len - rlen);
1968 StrBufCutLeft(buf, len + 1);
1973 if (buf->BufSize - buf->BufUsed < 10)
1974 IncreaseBuf(buf, 1, -1);
1976 fdflags = fcntl(*fd, F_GETFL);
1977 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1979 while ((nSuccessLess < timeout) && (pch == NULL)) {
1981 tv.tv_sec = selectresolution;
1986 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1987 *Error = strerror(errno);
1993 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
1998 &buf->buf[buf->BufUsed],
1999 buf->BufSize - buf->BufUsed - 1);
2001 *Error = strerror(errno);
2006 else if (rlen > 0) {
2008 buf->BufUsed += rlen;
2009 buf->buf[buf->BufUsed] = '\0';
2010 if (buf->BufUsed + 10 > buf->BufSize) {
2011 IncreaseBuf(buf, 1, -1);
2013 pch = strchr(buf->buf, '\n');
2020 len = pch - buf->buf;
2021 if (len > 0 && (*(pch - 1) == '\r') )
2023 StrBufSub(Line, buf, 0, len - rlen);
2024 StrBufCutLeft(buf, len + 1);
2031 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
2032 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
2034 * @ingroup StrBuf_BufferedIO
2035 * @brief Read a line from socket
2036 * flushes and closes the FD on error
2037 * @param Line Line to read from the fd / I/O Buffer
2038 * @param IOBuf the buffer to get the input to
2039 * @param Pos pointer to the current read position, should be NULL initialized!
2040 * @param fd pointer to the filedescriptor to read
2041 * @param timeout number of successless selects until we bail out
2042 * @param selectresolution how long to wait on each select
2043 * @param Error strerror() on error
2044 * @returns numbers of chars read
2046 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
2051 int selectresolution,
2054 const char *pche = NULL;
2055 const char *pos = NULL;
2057 int nSuccessLess = 0;
2059 const char *pch = NULL;
2065 if ((IOBuf->BufUsed > 0) &&
2067 (pos < IOBuf->buf + IOBuf->BufUsed))
2069 pche = IOBuf->buf + IOBuf->BufUsed;
2071 while ((pch < pche) && (*pch != '\n'))
2073 if ((pch >= pche) || (*pch == '\0'))
2075 if ((pch != NULL) &&
2080 if (len > 0 && (*(pch - 1) == '\r') )
2082 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
2092 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
2096 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
2097 IncreaseBuf(IOBuf, 1, -1);
2100 fdflags = fcntl(*fd, F_GETFL);
2101 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2104 while ((nSuccessLess < timeout) &&
2114 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
2115 *Error = strerror(errno);
2119 *Error = ErrRBLF_SelectFailed;
2122 if (! FD_ISSET(*fd, &rfds) != 0) {
2128 &IOBuf->buf[IOBuf->BufUsed],
2129 IOBuf->BufSize - IOBuf->BufUsed - 1);
2131 *Error = strerror(errno);
2136 else if (rlen > 0) {
2138 IOBuf->BufUsed += rlen;
2139 IOBuf->buf[IOBuf->BufUsed] = '\0';
2140 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
2141 IncreaseBuf(IOBuf, 1, -1);
2144 pche = IOBuf->buf + IOBuf->BufUsed;
2146 while ((pch < pche) && (*pch != '\n'))
2148 if ((pch >= pche) || (*pch == '\0'))
2157 if (len > 0 && (*(pch - 1) == '\r') )
2159 StrBufSub(Line, IOBuf, 0, len - rlen);
2160 *Pos = pos + len + 1;
2163 *Error = ErrRBLF_NotEnoughSentFromServer;
2169 * @ingroup StrBuf_IO
2170 * @brief Input binary data from socket
2171 * flushes and closes the FD on error
2172 * @param Buf the buffer to get the input to
2173 * @param fd pointer to the filedescriptor to read
2174 * @param append Append to an existing string or replace?
2175 * @param nBytes the maximal number of bytes to read
2176 * @param Error strerror() on error
2177 * @returns numbers of chars read
2179 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
2182 int len, rlen, slen;
2189 if ((Buf == NULL) || (*fd == -1))
2193 if (Buf->BufUsed + nBytes >= Buf->BufSize)
2194 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
2196 ptr = Buf->buf + Buf->BufUsed;
2198 slen = len = Buf->BufUsed;
2200 fdflags = fcntl(*fd, F_GETFL);
2201 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2203 while ((nRead < nBytes) &&
2213 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2214 *Error = strerror(errno);
2218 *Error = ErrRBLF_SelectFailed;
2221 if (! FD_ISSET(*fd, &rfds) != 0) {
2227 if ((rlen = read(*fd,
2229 nBytes - nRead)) == -1) {
2232 *Error = strerror(errno);
2237 Buf->BufUsed += rlen;
2239 Buf->buf[Buf->BufUsed] = '\0';
2243 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
2245 * @ingroup StrBuf_BufferedIO
2246 * @brief Input binary data from socket
2247 * flushes and closes the FD on error
2248 * @param Blob put binary thing here
2249 * @param IOBuf the buffer to get the input to
2250 * @param Pos offset inside of IOBuf
2251 * @param fd pointer to the filedescriptor to read
2252 * @param append Append to an existing string or replace?
2253 * @param nBytes the maximal number of bytes to read
2254 * @param check whether we should search for '000\n' terminators in case of timeouts
2255 * @param Error strerror() on error
2256 * @returns numbers of chars read
2258 int StrBufReadBLOBBuffered(StrBuf *Blob,
2275 int nAlreadyRead = 0;
2283 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2287 if (Blob->BufUsed + nBytes >= Blob->BufSize)
2288 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2293 len = pos - IOBuf->buf;
2294 rlen = IOBuf->BufUsed - len;
2297 if ((IOBuf->BufUsed > 0) &&
2299 (pos < IOBuf->buf + IOBuf->BufUsed))
2301 pche = IOBuf->buf + IOBuf->BufUsed;
2304 if (rlen < nBytes) {
2305 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2306 Blob->BufUsed += rlen;
2307 Blob->buf[Blob->BufUsed] = '\0';
2308 nAlreadyRead = nRead = rlen;
2311 if (rlen >= nBytes) {
2312 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2313 Blob->BufUsed += nBytes;
2314 Blob->buf[Blob->BufUsed] = '\0';
2315 if (rlen == nBytes) {
2326 if (IOBuf->BufSize < nBytes - nRead)
2327 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2330 slen = len = Blob->BufUsed;
2332 fdflags = fcntl(*fd, F_GETFL);
2333 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2338 while ((nRead < nBytes) &&
2347 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2348 *Error = strerror(errno);
2352 *Error = ErrRBLF_SelectFailed;
2355 if (! FD_ISSET(*fd, &rfds) != 0) {
2367 *Error = strerror(errno);
2370 else if (rlen == 0){
2372 if ((check == NNN_TERM) &&
2374 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2376 StrBufPlain(Blob, HKEY("\n000\n"));
2377 StrBufCutRight(Blob, 5);
2378 return Blob->BufUsed;
2380 if (nSelects > 10) {
2382 *Error = ErrRBB_too_many_selects;
2386 else if (rlen > 0) {
2389 IOBuf->BufUsed += rlen;
2392 if (nRead > nBytes) {
2393 *Pos = IOBuf->buf + nBytes;
2395 Blob->buf[Blob->BufUsed] = '\0';
2396 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2400 return nRead + nAlreadyRead;
2405 * @brief Cut nChars from the start of the string
2406 * @param Buf Buffer to modify
2407 * @param nChars how many chars should be skipped?
2409 void StrBufCutLeft(StrBuf *Buf, int nChars)
2411 if (nChars >= Buf->BufUsed) {
2415 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2416 Buf->BufUsed -= nChars;
2417 Buf->buf[Buf->BufUsed] = '\0';
2422 * @brief Cut the trailing n Chars from the string
2423 * @param Buf Buffer to modify
2424 * @param nChars how many chars should be trunkated?
2426 void StrBufCutRight(StrBuf *Buf, int nChars)
2428 if (nChars >= Buf->BufUsed) {
2432 Buf->BufUsed -= nChars;
2433 Buf->buf[Buf->BufUsed] = '\0';
2438 * @brief Cut the string after n Chars
2439 * @param Buf Buffer to modify
2440 * @param AfternChars after how many chars should we trunkate the string?
2441 * @param At if non-null and points inside of our string, cut it there.
2443 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2446 AfternChars = At - Buf->buf;
2449 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2451 Buf->BufUsed = AfternChars;
2452 Buf->buf[Buf->BufUsed] = '\0';
2458 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2459 * @param Buf the string to modify
2461 void StrBufTrim(StrBuf *Buf)
2464 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2466 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2469 if (delta > 0) StrBufCutLeft(Buf, delta);
2471 if (Buf->BufUsed == 0) return;
2472 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2475 Buf->buf[Buf->BufUsed] = '\0';
2480 * @brief uppercase the contents of a buffer
2481 * @param Buf the buffer to translate
2483 void StrBufUpCase(StrBuf *Buf)
2488 pche = pch + Buf->BufUsed;
2489 while (pch < pche) {
2490 *pch = toupper(*pch);
2498 * @brief lowercase the contents of a buffer
2499 * @param Buf the buffer to translate
2501 void StrBufLowerCase(StrBuf *Buf)
2506 pche = pch + Buf->BufUsed;
2507 while (pch < pche) {
2508 *pch = tolower(*pch);
2515 * @brief removes double slashes from pathnames
2516 * @param Dir directory string to filter
2517 * @param RemoveTrailingSlash allows / disallows trailing slashes
2519 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2525 while (!IsEmptyStr(a)) {
2537 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2542 Dir->BufUsed = b - Dir->buf;
2546 * @ingroup StrBuf_DeEnCoder
2547 * @brief unhide special chars hidden to the HTML escaper
2548 * @param target buffer to put the unescaped string in
2549 * @param source buffer to unescape
2551 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2557 FlushStrBuf(target);
2559 if (source == NULL ||target == NULL)
2564 len = source->BufUsed;
2565 for (a = 0; a < len; ++a) {
2566 if (target->BufUsed >= target->BufSize)
2567 IncreaseBuf(target, 1, -1);
2569 if (source->buf[a] == '=') {
2570 hex[0] = source->buf[a + 1];
2571 hex[1] = source->buf[a + 2];
2574 sscanf(hex, "%02x", &b);
2575 target->buf[target->BufUsed] = b;
2576 target->buf[++target->BufUsed] = 0;
2580 target->buf[target->BufUsed] = source->buf[a];
2581 target->buf[++target->BufUsed] = 0;
2588 * @ingroup StrBuf_DeEnCoder
2589 * @brief hide special chars from the HTML escapers and friends
2590 * @param target buffer to put the escaped string in
2591 * @param source buffer to escape
2593 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2598 FlushStrBuf(target);
2600 if (source == NULL ||target == NULL)
2605 len = source->BufUsed;
2606 for (i=0; i<len; ++i) {
2607 if (target->BufUsed + 4 >= target->BufSize)
2608 IncreaseBuf(target, 1, -1);
2609 if ( (isalnum(source->buf[i])) ||
2610 (source->buf[i]=='-') ||
2611 (source->buf[i]=='_') ) {
2612 target->buf[target->BufUsed++] = source->buf[i];
2615 sprintf(&target->buf[target->BufUsed],
2617 (0xFF &source->buf[i]));
2618 target->BufUsed += 3;
2621 target->buf[target->BufUsed + 1] = '\0';
2625 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2626 #define OS_CODE 0x03 /*< unix */
2629 * @ingroup StrBuf_DeEnCoder
2630 * @brief uses the same calling syntax as compress2(), but it
2631 * creates a stream compatible with HTTP "Content-encoding: gzip"
2632 * @param dest compressed buffer
2633 * @param destLen length of the compresed data
2634 * @param source source to encode
2635 * @param sourceLen length of source to encode
2636 * @param level compression level
2638 int ZEXPORT compress_gzip(Bytef * dest,
2640 const Bytef * source,
2644 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2646 /* write gzip header */
2647 snprintf((char *) dest, *destLen,
2648 "%c%c%c%c%c%c%c%c%c%c",
2649 gz_magic[0], gz_magic[1], Z_DEFLATED,
2650 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2653 /* normal deflate */
2656 stream.next_in = (Bytef *) source;
2657 stream.avail_in = (uInt) sourceLen;
2658 stream.next_out = dest + 10L; // after header
2659 stream.avail_out = (uInt) * destLen;
2660 if ((uLong) stream.avail_out != *destLen)
2663 stream.zalloc = (alloc_func) 0;
2664 stream.zfree = (free_func) 0;
2665 stream.opaque = (voidpf) 0;
2667 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2668 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2672 err = deflate(&stream, Z_FINISH);
2673 if (err != Z_STREAM_END) {
2674 deflateEnd(&stream);
2675 return err == Z_OK ? Z_BUF_ERROR : err;
2677 *destLen = stream.total_out + 10L;
2679 /* write CRC and Length */
2680 uLong crc = crc32(0L, source, sourceLen);
2682 for (n = 0; n < 4; ++n, ++*destLen) {
2683 dest[*destLen] = (int) (crc & 0xff);
2686 uLong len = stream.total_in;
2687 for (n = 0; n < 4; ++n, ++*destLen) {
2688 dest[*destLen] = (int) (len & 0xff);
2691 err = deflateEnd(&stream);
2698 * @ingroup StrBuf_DeEnCoder
2699 * @brief compress the buffer with gzip
2700 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2701 * @param Buf buffer whose content is to be gzipped
2703 int CompressBuffer(StrBuf *Buf)
2706 char *compressed_data = NULL;
2707 size_t compressed_len, bufsize;
2710 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2711 compressed_data = malloc(compressed_len);
2713 if (compressed_data == NULL)
2715 /* Flush some space after the used payload so valgrind shuts up... */
2716 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2717 Buf->buf[Buf->BufUsed + i++] = '\0';
2718 if (compress_gzip((Bytef *) compressed_data,
2721 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2724 Buf->buf = compressed_data;
2725 Buf->BufUsed = compressed_len;
2726 Buf->BufSize = bufsize;
2727 /* Flush some space after the used payload so valgrind shuts up... */
2729 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2730 Buf->buf[Buf->BufUsed + i++] = '\0';
2733 free(compressed_data);
2735 #endif /* HAVE_ZLIB */
2740 * @ingroup StrBuf_DeEnCoder
2741 * @brief decode a buffer from base 64 encoding; destroys original
2742 * @param Buf Buffor to transform
2744 int StrBufDecodeBase64(StrBuf *Buf)
2748 if (Buf == NULL) return -1;
2750 xferbuf = (char*) malloc(Buf->BufSize);
2751 siz = CtdlDecodeBase64(xferbuf,
2761 * @ingroup StrBuf_DeEnCoder
2762 * @brief decode a buffer from base 64 encoding; destroys original
2763 * @param Buf Buffor to transform
2765 int StrBufDecodeHex(StrBuf *Buf)
2768 char *pch, *pche, *pchi;
2770 if (Buf == NULL) return -1;
2772 pch = pchi = Buf->buf;
2773 pche = pch + Buf->BufUsed;
2775 while (pchi < pche){
2776 ch = decode_hex(pchi);
2783 Buf->BufUsed = pch - Buf->buf;
2784 return Buf->BufUsed;
2788 * @ingroup StrBuf_DeEnCoder
2789 * @brief replace all chars >0x20 && < 0x7F with Mute
2790 * @param Mute char to put over invalid chars
2791 * @param Buf Buffor to transform
2793 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2797 if (Buf == NULL) return -1;
2798 pch = (unsigned char *)Buf->buf;
2799 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2800 if ((*pch < 0x20) || (*pch > 0x7F))
2804 return Buf->BufUsed;
2809 * @ingroup StrBuf_DeEnCoder
2810 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2811 * @param Buf Buffer to translate
2812 * @param StripBlanks Reduce several blanks to one?
2814 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2820 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2821 Buf->buf[Buf->BufUsed - 1] = '\0';
2826 while (a < Buf->BufUsed) {
2827 if (Buf->buf[a] == '+')
2829 else if (Buf->buf[a] == '%') {
2830 /* don't let % chars through, rather truncate the input. */
2831 if (a + 2 > Buf->BufUsed) {
2836 hex[0] = Buf->buf[a + 1];
2837 hex[1] = Buf->buf[a + 2];
2840 sscanf(hex, "%02x", &b);
2841 Buf->buf[a] = (char) b;
2842 len = Buf->BufUsed - a - 2;
2844 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2856 * @ingroup StrBuf_DeEnCoder
2857 * @brief RFC2047-encode a header field if necessary.
2858 * If no non-ASCII characters are found, the string
2859 * will be copied verbatim without encoding.
2861 * @param target Target buffer.
2862 * @param source Source string to be encoded.
2863 * @returns encoded length; -1 if non success.
2865 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2867 const char headerStr[] = "=?UTF-8?Q?";
2868 int need_to_encode = 0;
2872 if ((source == NULL) ||
2876 while ((i < source->BufUsed) &&
2877 (!IsEmptyStr (&source->buf[i])) &&
2878 (need_to_encode == 0)) {
2879 if (((unsigned char) source->buf[i] < 32) ||
2880 ((unsigned char) source->buf[i] > 126)) {
2886 if (!need_to_encode) {
2887 if (*target == NULL) {
2888 *target = NewStrBufPlain(source->buf, source->BufUsed);
2891 FlushStrBuf(*target);
2892 StrBufAppendBuf(*target, source, 0);
2894 return (*target)->BufUsed;
2896 if (*target == NULL)
2897 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2898 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2899 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2900 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2901 (*target)->BufUsed = sizeof(headerStr) - 1;
2902 for (i=0; (i < source->BufUsed); ++i) {
2903 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2904 IncreaseBuf(*target, 1, 0);
2905 ch = (unsigned char) source->buf[i];
2906 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2907 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2908 (*target)->BufUsed += 3;
2911 (*target)->buf[(*target)->BufUsed] = ch;
2912 (*target)->BufUsed++;
2916 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2917 IncreaseBuf(*target, 1, 0);
2919 (*target)->buf[(*target)->BufUsed++] = '?';
2920 (*target)->buf[(*target)->BufUsed++] = '=';
2921 (*target)->buf[(*target)->BufUsed] = '\0';
2922 return (*target)->BufUsed;;
2927 * @brief replaces all occurances of 'search' by 'replace'
2928 * @param buf Buffer to modify
2929 * @param search character to search
2930 * @param replace character to replace search by
2932 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2937 for (i=0; i<buf->BufUsed; i++)
2938 if (buf->buf[i] == search)
2939 buf->buf[i] = replace;
2946 * @ingroup StrBuf_DeEnCoder
2947 * @brief Wrapper around iconv_open()
2948 * Our version adds aliases for non-standard Microsoft charsets
2949 * such as 'MS950', aliasing them to names like 'CP950'
2951 * @param tocode Target encoding
2952 * @param fromcode Source encoding
2953 * @param pic anonimized pointer to iconv struct
2955 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2958 iconv_t ic = (iconv_t)(-1) ;
2959 ic = iconv_open(tocode, fromcode);
2960 if (ic == (iconv_t)(-1) ) {
2961 char alias_fromcode[64];
2962 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2963 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2964 alias_fromcode[0] = 'C';
2965 alias_fromcode[1] = 'P';
2966 ic = iconv_open(tocode, alias_fromcode);
2969 *(iconv_t *)pic = ic;
2975 * @ingroup StrBuf_DeEnCoder
2976 * @brief find one chunk of a RFC822 encoded string
2977 * @param Buffer where to search
2978 * @param bptr where to start searching
2979 * @returns found position, NULL if none.
2981 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2984 /* Find the next ?Q? */
2985 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2988 end = strchr(bptr + 2, '?');
2993 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2994 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2995 (*(end + 2) == '?')) {
2996 /* skip on to the end of the cluster, the next ?= */
2997 end = strstr(end + 3, "?=");
3000 /* sort of half valid encoding, try to find an end. */
3001 end = strstr(bptr, "?=");
3007 * @brief swaps the contents of two StrBufs
3008 * this is to be used to have cheap switched between a work-buffer and a target buffer
3009 * @param A First one
3010 * @param B second one
3012 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
3016 memcpy(&C, A, sizeof(*A));
3017 memcpy(A, B, sizeof(*B));
3018 memcpy(B, &C, sizeof(C));
3024 * @ingroup StrBuf_DeEnCoder
3025 * @brief convert one buffer according to the preselected iconv pointer PIC
3026 * @param ConvertBuf buffer we need to translate
3027 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3028 * @param pic Pointer to the iconv-session Object
3030 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
3036 char *ibuf; /**< Buffer of characters to be converted */
3037 char *obuf; /**< Buffer for converted characters */
3038 size_t ibuflen; /**< Length of input buffer */
3039 size_t obuflen; /**< Length of output buffer */
3042 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3043 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3044 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3046 ic = *(iconv_t*)pic;
3047 ibuf = ConvertBuf->buf;
3048 ibuflen = ConvertBuf->BufUsed;
3050 obuflen = TmpBuf->BufSize;
3052 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3055 if (errno == E2BIG) {
3057 IncreaseBuf(TmpBuf, 0, 0);
3062 else if (errno == EILSEQ){
3063 /* hm, invalid utf8 sequence... what to do now? */
3064 /* An invalid multibyte sequence has been encountered in the input */
3066 else if (errno == EINVAL) {
3067 /* An incomplete multibyte sequence has been encountered in the input. */
3070 FlushStrBuf(TmpBuf);
3073 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3074 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3076 /* little card game: wheres the red lady? */
3077 SwapBuffers(ConvertBuf, TmpBuf);
3078 FlushStrBuf(TmpBuf);
3085 * @ingroup StrBuf_DeEnCoder
3086 * @brief catches one RFC822 encoded segment, and decodes it.
3087 * @param Target buffer to fill with result
3088 * @param DecodeMe buffer with stuff to process
3089 * @param SegmentStart points to our current segment in DecodeMe
3090 * @param SegmentEnd Points to the end of our current segment in DecodeMe
3091 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3092 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3093 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3095 inline static void DecodeSegment(StrBuf *Target,
3096 const StrBuf *DecodeMe,
3100 StrBuf *ConvertBuf2,
3101 StrBuf *FoundCharset)
3107 iconv_t ic = (iconv_t)(-1);
3111 /* Now we handle foreign character sets properly encoded
3112 * in RFC2047 format.
3114 StaticBuf.buf = SegmentStart;
3115 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3116 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3117 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3118 if (FoundCharset != NULL) {
3119 FlushStrBuf(FoundCharset);
3120 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3122 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3123 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3125 *encoding = toupper(*encoding);
3126 if (*encoding == 'B') { /**< base64 */
3127 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
3129 ConvertBuf->BufUsed);
3131 else if (*encoding == 'Q') { /**< quoted-printable */
3135 while (pos < ConvertBuf->BufUsed)
3137 if (ConvertBuf->buf[pos] == '_')
3138 ConvertBuf->buf[pos] = ' ';
3142 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3145 ConvertBuf->BufUsed);
3148 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3151 ctdl_iconv_open("UTF-8", charset, &ic);
3152 if (ic != (iconv_t)(-1) ) {
3154 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3155 StrBufAppendBuf(Target, ConvertBuf2, 0);
3160 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3166 * @ingroup StrBuf_DeEnCoder
3167 * @brief Handle subjects with RFC2047 encoding such as:
3168 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3169 * @param Target where to put the decoded string to
3170 * @param DecodeMe buffer with encoded string
3171 * @param DefaultCharset if we don't find one, which should we use?
3172 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3173 * put it here for later use where no string might be known.
3175 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3177 StrBuf *DecodedInvalidBuf = NULL;
3178 StrBuf *ConvertBuf, *ConvertBuf2;
3179 const StrBuf *DecodeMee = DecodeMe;
3180 char *start, *end, *next, *nextend, *ptr = NULL;
3182 iconv_t ic = (iconv_t)(-1) ;
3187 int illegal_non_rfc2047_encoding = 0;
3189 /* Sometimes, badly formed messages contain strings which were simply
3190 * written out directly in some foreign character set instead of
3191 * using RFC2047 encoding. This is illegal but we will attempt to
3192 * handle it anyway by converting from a user-specified default
3193 * charset to UTF-8 if we see any nonprintable characters.
3196 len = StrLength(DecodeMe);
3197 for (i=0; i<DecodeMe->BufUsed; ++i) {
3198 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3199 illegal_non_rfc2047_encoding = 1;
3204 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3205 if ((illegal_non_rfc2047_encoding) &&
3206 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3207 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3210 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3211 if (ic != (iconv_t)(-1) ) {
3212 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3213 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3214 DecodeMee = DecodedInvalidBuf;
3220 /* pre evaluate the first pair */
3221 nextend = end = NULL;
3222 len = StrLength(DecodeMee);
3223 start = strstr(DecodeMee->buf, "=?");
3224 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3226 end = FindNextEnd (DecodeMee, start);
3228 StrBufAppendBuf(Target, DecodeMee, 0);
3229 FreeStrBuf(&ConvertBuf);
3230 FreeStrBuf(&DecodedInvalidBuf);
3234 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3236 if (start != DecodeMee->buf) {
3239 nFront = start - DecodeMee->buf;
3240 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3244 * Since spammers will go to all sorts of absurd lengths to get their
3245 * messages through, there are LOTS of corrupt headers out there.
3246 * So, prevent a really badly formed RFC2047 header from throwing
3247 * this function into an infinite loop.
3249 while ((start != NULL) &&
3256 DecodeSegment(Target,
3264 next = strstr(end, "=?");
3266 if ((next != NULL) &&
3268 nextend = FindNextEnd(DecodeMee, next);
3269 if (nextend == NULL)
3272 /* did we find two partitions */
3273 if ((next != NULL) &&
3277 while ((ptr < next) &&
3283 /* did we find a gab just filled with blanks? */
3286 long gap = next - start;
3291 /* now terminate the gab at the end */
3292 delta = (next - end) - 2; ////TODO: const!
3293 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3294 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3296 /* move next to its new location. */
3301 /* our next-pair is our new first pair now. */
3307 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3308 if ((end != NULL) && (end < nextend)) {
3310 while ( (ptr < nextend) &&
3317 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3319 FreeStrBuf(&ConvertBuf);
3320 FreeStrBuf(&ConvertBuf2);
3321 FreeStrBuf(&DecodedInvalidBuf);
3326 * @brief evaluate the length of an utf8 special character sequence
3327 * @param Char the character to examine
3328 * @returns width of utf8 chars in bytes
3330 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3335 while ((n < 8) && ((test & *CharS) != 0)) {
3339 if ((n > 6) || ((CharE - CharS) > n))
3346 * @brief detect whether this char starts an utf-8 encoded char
3347 * @param Char character to inspect
3348 * @returns yes or no
3350 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3352 /** 11??.???? indicates an UTF8 Sequence. */
3353 return ((Char & 0xC0) != 0);
3358 * @brief measure the number of glyphs in an UTF8 string...
3359 * @param Buf string to measure
3360 * @returns the number of glyphs in Buf
3362 long StrBuf_Utf8StrLen(StrBuf *Buf)
3368 if ((Buf == NULL) || (Buf->BufUsed == 0))
3371 eptr = Buf->buf + Buf->BufUsed;
3372 while ((aptr < eptr) && (*aptr != '\0')) {
3373 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3374 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3375 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3389 * @brief cuts a string after maxlen glyphs
3390 * @param Buf string to cut to maxlen glyphs
3391 * @param maxlen how long may the string become?
3392 * @returns current length of the string
3394 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3400 eptr = Buf->buf + Buf->BufUsed;
3401 while ((aptr < eptr) && (*aptr != '\0')) {
3402 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3403 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3404 while ((m-- > 0) && (*aptr++ != '\0'))
3413 Buf->BufUsed = aptr - Buf->buf;
3414 return Buf->BufUsed;
3417 return Buf->BufUsed;
3424 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3425 * @param LineBuf your line will be copied here.
3426 * @param Buf BLOB with lines of text...
3427 * @param Ptr moved arround to keep the next-line across several iterations
3428 * has to be &NULL on start; will be &NotNULL on end of buffer
3429 * @returns size of copied buffer
3431 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3433 const char *aptr, *ptr, *eptr;
3436 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3437 *Ptr = StrBufNOTNULL;
3441 FlushStrBuf(LineBuf);
3443 ptr = aptr = Buf->buf;
3447 optr = LineBuf->buf;
3448 eptr = Buf->buf + Buf->BufUsed;
3449 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3451 while ((ptr <= eptr) &&
3458 LineBuf->BufUsed = optr - LineBuf->buf;
3459 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3460 optr = LineBuf->buf + LineBuf->BufUsed;
3461 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3465 if ((ptr >= eptr) && (optr > LineBuf->buf))
3467 LineBuf->BufUsed = optr - LineBuf->buf;
3469 if ((ptr <= eptr) && (*ptr == '\r'))
3471 if ((ptr <= eptr) && (*ptr == '\n'))
3478 *Ptr = StrBufNOTNULL;
3481 return Buf->BufUsed - (ptr - Buf->buf);