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;
32 const char HexList[256][3] = {
33 "00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
34 "10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
35 "20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
36 "30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
37 "40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
38 "50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
39 "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
40 "70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
41 "80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
42 "90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
43 "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
44 "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
45 "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
46 "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
47 "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
48 "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};
51 * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
52 * StrBuf is a versatile class, aiding the handling of dynamic strings
53 * * reduce de/reallocations
54 * * reduce the need to remeasure it
55 * * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
56 * * allow asyncroneous IO for line and Blob based operations
57 * * reduce the use of memove in those
58 * * Quick filling in several operations with append functions
62 * @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
67 * @defgroup StrBuf_Cast Cast operators to interact with char* based code
69 * use these operators to interfere with code demanding char*;
70 * if you need to own the content, smash me. Avoid, since we loose the length information.
74 * @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
76 * operations to get your Strings into a StrBuf, manipulating them, or appending
79 * @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence
81 * Quick tokenizer; demands of the user to pull its tokens in sequence
85 * @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
87 * versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
91 * @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
93 * File IO to fill StrBufs; Works with work-buffer shared across several calls;
94 * External Cursor to maintain the current read position inside of the buffer
95 * the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower)
99 * @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
105 * @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
107 * these functions translate the content of a buffer into another representation;
108 * some are combined Fillers and encoders
112 * Private Structure for the Stringbuffer
115 char *buf; /**< the pointer to the dynamic buffer */
116 long BufSize; /**< how many spcae do we optain */
117 long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
118 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
120 long nIncreases; /**< for profiling; cound how many times we needed more */
121 char bt [SIZ]; /**< Stacktrace of last increase */
122 char bt_lastinc [SIZ]; /**< How much did we increase last time? */
127 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
128 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
131 #ifdef HAVE_BACKTRACE
132 static void StrBufBacktrace(StrBuf *Buf, int which)
136 void *stack_frames[50];
141 pstart = pch = Buf->bt;
143 pstart = pch = Buf->bt_lastinc;
144 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
145 strings = backtrace_symbols(stack_frames, size);
146 for (i = 0; i < size; i++) {
148 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
150 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
161 * @ingroup StrBuf_Cast
162 * @brief Cast operator to Plain String
163 * @note if the buffer is altered by StrBuf operations, this pointer may become
164 * invalid. So don't lean on it after altering the buffer!
165 * Since this operation is considered cheap, rather call it often than risking
166 * your pointer to become invalid!
167 * @param Str the string we want to get the c-string representation for
168 * @returns the Pointer to the Content. Don't mess with it!
170 inline const char *ChrPtr(const StrBuf *Str)
178 * @ingroup StrBuf_Cast
179 * @brief since we know strlen()'s result, provide it here.
180 * @param Str the string to return the length to
181 * @returns contentlength of the buffer
183 inline int StrLength(const StrBuf *Str)
185 return (Str != NULL) ? Str->BufUsed : 0;
189 * @ingroup StrBuf_DeConstructors
190 * @brief local utility function to resize the buffer
191 * @param Buf the buffer whichs storage we should increase
192 * @param KeepOriginal should we copy the original buffer or just start over with a new one
193 * @param DestSize what should fit in after?
195 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
198 size_t NewSize = Buf->BufSize * 2;
204 while (NewSize <= DestSize)
207 NewBuf= (char*) malloc(NewSize);
211 if (KeepOriginal && (Buf->BufUsed > 0))
213 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
222 Buf->BufSize = NewSize;
225 #ifdef HAVE_BACKTRACE
226 StrBufBacktrace(Buf, 1);
233 * @ingroup StrBuf_DeConstructors
234 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
235 * @param Buf Buffer to shrink (has to be empty)
236 * @param ThreshHold if the buffer is bigger then this, its readjusted
237 * @param NewSize if we Shrink it, how big are we going to be afterwards?
239 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
241 if (Buf->BufUsed > ThreshHold) {
243 Buf->buf = (char*) malloc(NewSize);
245 Buf->BufSize = NewSize;
250 * @ingroup StrBuf_DeConstructors
251 * @brief shrink long term buffers to their real size so they don't waste memory
252 * @param Buf buffer to shrink
253 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
254 * @returns physical size of the buffer
256 long StrBufShrinkToFit(StrBuf *Buf, int Force)
259 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
261 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
262 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
263 Buf->BufSize = Buf->BufUsed + 1;
271 * @ingroup StrBuf_DeConstructors
272 * @brief Allocate a new buffer with default buffer size
273 * @returns the new stringbuffer
275 StrBuf* NewStrBuf(void)
279 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
280 NewBuf->buf = (char*) malloc(BaseStrBufSize);
281 NewBuf->buf[0] = '\0';
282 NewBuf->BufSize = BaseStrBufSize;
284 NewBuf->ConstBuf = 0;
286 NewBuf->nIncreases = 0;
287 NewBuf->bt[0] = '\0';
288 NewBuf->bt_lastinc[0] = '\0';
289 #ifdef HAVE_BACKTRACE
290 StrBufBacktrace(NewBuf, 0);
297 * @ingroup StrBuf_DeConstructors
298 * @brief Copy Constructor; returns a duplicate of CopyMe
299 * @param CopyMe Buffer to faxmilate
300 * @returns the new stringbuffer
302 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
309 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
310 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
311 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
312 NewBuf->BufUsed = CopyMe->BufUsed;
313 NewBuf->BufSize = CopyMe->BufSize;
314 NewBuf->ConstBuf = 0;
316 NewBuf->nIncreases = 0;
317 NewBuf->bt[0] = '\0';
318 NewBuf->bt_lastinc[0] = '\0';
319 #ifdef HAVE_BACKTRACE
320 StrBufBacktrace(NewBuf, 0);
327 * @ingroup StrBuf_DeConstructors
328 * @brief create a new Buffer using an existing c-string
329 * this function should also be used if you want to pre-suggest
330 * the buffer size to allocate in conjunction with ptr == NULL
331 * @param ptr the c-string to copy; may be NULL to create a blank instance
332 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
333 * @returns the new stringbuffer
335 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
338 size_t Siz = BaseStrBufSize;
341 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
343 CopySize = strlen((ptr != NULL)?ptr:"");
347 while (Siz <= CopySize)
350 NewBuf->buf = (char*) malloc(Siz);
351 NewBuf->BufSize = Siz;
353 memcpy(NewBuf->buf, ptr, CopySize);
354 NewBuf->buf[CopySize] = '\0';
355 NewBuf->BufUsed = CopySize;
358 NewBuf->buf[0] = '\0';
361 NewBuf->ConstBuf = 0;
363 NewBuf->nIncreases = 0;
364 NewBuf->bt[0] = '\0';
365 NewBuf->bt_lastinc[0] = '\0';
366 #ifdef HAVE_BACKTRACE
367 StrBufBacktrace(NewBuf, 0);
374 * @ingroup StrBuf_DeConstructors
375 * @brief Set an existing buffer from a c-string
376 * @param Buf buffer to load
377 * @param ptr c-string to put into
378 * @param nChars set to -1 if we should work 0-terminated
379 * @returns the new length of the string
381 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
383 size_t Siz = Buf->BufSize;
387 CopySize = strlen(ptr);
391 while (Siz <= CopySize)
394 if (Siz != Buf->BufSize)
395 IncreaseBuf(Buf, 0, Siz);
396 memcpy(Buf->buf, ptr, CopySize);
397 Buf->buf[CopySize] = '\0';
398 Buf->BufUsed = CopySize;
405 * @ingroup StrBuf_DeConstructors
406 * @brief use strbuf as wrapper for a string constant for easy handling
407 * @param StringConstant a string to wrap
408 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
410 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
414 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
415 NewBuf->buf = (char*) StringConstant;
416 NewBuf->BufSize = SizeOfStrConstant;
417 NewBuf->BufUsed = SizeOfStrConstant;
418 NewBuf->ConstBuf = 1;
420 NewBuf->nIncreases = 0;
421 NewBuf->bt[0] = '\0';
422 NewBuf->bt_lastinc[0] = '\0';
429 * @ingroup StrBuf_DeConstructors
430 * @brief flush the content of a Buf; keep its struct
431 * @param buf Buffer to flush
433 int FlushStrBuf(StrBuf *buf)
445 * @ingroup StrBuf_DeConstructors
446 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
447 * @param buf Buffer to wipe
449 int FLUSHStrBuf(StrBuf *buf)
455 if (buf->BufUsed > 0) {
456 memset(buf->buf, 0, buf->BufUsed);
463 int hFreeDbglog = -1;
466 * @ingroup StrBuf_DeConstructors
467 * @brief Release a Buffer
468 * Its a double pointer, so it can NULL your pointer
469 * so fancy SIG11 appear instead of random results
470 * @param FreeMe Pointer Pointer to the buffer to free
472 void FreeStrBuf (StrBuf **FreeMe)
477 if (hFreeDbglog == -1){
478 pid_t pid = getpid();
480 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
481 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
483 if ((*FreeMe)->nIncreases > 0)
487 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
488 (*FreeMe)->nIncreases,
492 (*FreeMe)->bt_lastinc);
493 n = write(hFreeDbglog, buf, n);
499 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
502 n = write(hFreeDbglog, buf, n);
505 if (!(*FreeMe)->ConstBuf)
506 free((*FreeMe)->buf);
512 * @ingroup StrBuf_DeConstructors
513 * @brief flatten a Buffer to the Char * we return
514 * Its a double pointer, so it can NULL your pointer
515 * so fancy SIG11 appear instead of random results
516 * The Callee then owns the buffer and is responsible for freeing it.
517 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
518 * @returns the pointer of the buffer; Callee owns the memory thereafter.
520 char *SmashStrBuf (StrBuf **SmashMe)
524 if (*SmashMe == NULL)
527 if (hFreeDbglog == -1){
528 pid_t pid = getpid();
530 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
531 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
533 if ((*SmashMe)->nIncreases > 0)
537 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
538 (*SmashMe)->nIncreases,
542 (*SmashMe)->bt_lastinc);
543 n = write(hFreeDbglog, buf, n);
549 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
551 (*SmashMe)->BufSize);
552 n = write(hFreeDbglog, buf, n);
555 Ret = (*SmashMe)->buf;
562 * @ingroup StrBuf_DeConstructors
563 * @brief Release the buffer
564 * If you want put your StrBuf into a Hash, use this as Destructor.
565 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
567 void HFreeStrBuf (void *VFreeMe)
569 StrBuf *FreeMe = (StrBuf*)VFreeMe;
573 if (hFreeDbglog == -1){
574 pid_t pid = getpid();
576 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
577 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
579 if (FreeMe->nIncreases > 0)
583 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
589 write(hFreeDbglog, buf, n);
595 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
601 if (!FreeMe->ConstBuf)
608 * @brief Wrapper around atol
610 long StrTol(const StrBuf *Buf)
615 return atol(Buf->buf);
622 * @brief Wrapper around atoi
624 int StrToi(const StrBuf *Buf)
628 if (Buf->BufUsed > 0)
629 return atoi(Buf->buf);
636 * @brief Checks to see if the string is a pure number
638 int StrBufIsNumber(const StrBuf *Buf) {
643 strtoll(Buf->buf, &pEnd, 10);
644 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
651 * @brief modifies a Single char of the Buf
652 * You can point to it via char* or a zero-based integer
653 * @param Buf The buffer to manipulate
654 * @param ptr char* to zero; use NULL if unused
655 * @param nThChar zero based pointer into the string; use -1 if unused
656 * @param PeekValue The Character to place into the position
658 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
663 nThChar = ptr - Buf->buf;
664 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
666 Buf->buf[nThChar] = PeekValue;
672 * @brief Append a StringBuffer to the buffer
673 * @param Buf Buffer to modify
674 * @param AppendBuf Buffer to copy at the end of our buffer
675 * @param Offset Should we start copying from an offset?
677 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
679 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
682 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
685 AppendBuf->BufUsed + Buf->BufUsed);
687 memcpy(Buf->buf + Buf->BufUsed,
688 AppendBuf->buf + Offset,
689 AppendBuf->BufUsed - Offset);
690 Buf->BufUsed += AppendBuf->BufUsed - Offset;
691 Buf->buf[Buf->BufUsed] = '\0';
697 * @brief Append a C-String to the buffer
698 * @param Buf Buffer to modify
699 * @param AppendBuf Buffer to copy at the end of our buffer
700 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
701 * @param Offset Should we start copying from an offset?
703 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
706 long BufSizeRequired;
708 if ((AppendBuf == NULL) || (Buf == NULL))
712 aps = strlen(AppendBuf + Offset);
714 aps = AppendSize - Offset;
716 BufSizeRequired = Buf->BufUsed + aps + 1;
717 if (Buf->BufSize <= BufSizeRequired)
718 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
720 memcpy(Buf->buf + Buf->BufUsed,
724 Buf->buf[Buf->BufUsed] = '\0';
729 * @brief Callback for cURL to append the webserver reply to a buffer
730 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
731 * @param size pre-defined by the cURL API; see man 3 curl for mre info
732 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
733 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
735 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
744 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
750 * @ingroup StrBuf_DeEnCoder
751 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
752 * @param OutBuf the output buffer
753 * @param In Buffer to encode
754 * @param PlainIn way in from plain old c strings
756 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
758 const char *pch, *pche;
762 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
764 if (PlainIn != NULL) {
765 len = strlen(PlainIn);
771 pche = pch + In->BufUsed;
778 pt = OutBuf->buf + OutBuf->BufUsed;
779 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
783 IncreaseBuf(OutBuf, 1, -1);
784 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
785 pt = OutBuf->buf + OutBuf->BufUsed;
788 if((*pch >= 'a' && *pch <= 'z') ||
789 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
790 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
791 (*pch == '!') || (*pch == '_') ||
792 (*pch == ',') || (*pch == '.') ||
800 *(pt + 1) = HexList[(unsigned char)*pch][0];
801 *(pt + 2) = HexList[(unsigned char)*pch][1];
803 OutBuf->BufUsed += 3;
811 * @ingroup StrBuf_DeEnCoder
812 * @brief Append a string, escaping characters which have meaning in HTML.
814 * @param Target target buffer
815 * @param Source source buffer; set to NULL if you just have a C-String
816 * @param PlainIn Plain-C string to append; set to NULL if unused
817 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
818 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
819 * if set to 2, linebreaks are replaced by <br/>
821 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
823 const char *aptr, *eiptr;
827 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
830 if (PlainIn != NULL) {
832 len = strlen(PlainIn);
837 eiptr = aptr + Source->BufUsed;
838 len = Source->BufUsed;
844 bptr = Target->buf + Target->BufUsed;
845 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
847 while (aptr < eiptr){
849 IncreaseBuf(Target, 1, -1);
850 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
851 bptr = Target->buf + Target->BufUsed;
854 memcpy(bptr, "<", 4);
856 Target->BufUsed += 4;
858 else if (*aptr == '>') {
859 memcpy(bptr, ">", 4);
861 Target->BufUsed += 4;
863 else if (*aptr == '&') {
864 memcpy(bptr, "&", 5);
866 Target->BufUsed += 5;
868 else if (*aptr == '"') {
869 memcpy(bptr, """, 6);
871 Target->BufUsed += 6;
873 else if (*aptr == '\'') {
874 memcpy(bptr, "'", 5);
876 Target->BufUsed += 5;
878 else if (*aptr == LB) {
883 else if (*aptr == RB) {
888 else if (*aptr == QU) {
893 else if ((*aptr == 32) && (nbsp == 1)) {
894 memcpy(bptr, " ", 6);
896 Target->BufUsed += 6;
898 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
899 *bptr='\0'; /* nothing */
901 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
902 memcpy(bptr, "<br/>", 11);
904 Target->BufUsed += 11;
908 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
909 *bptr='\0'; /* nothing */
919 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
921 return Target->BufUsed;
925 * @ingroup StrBuf_DeEnCoder
926 * @brief Append a string, escaping characters which have meaning in HTML.
927 * Converts linebreaks into blanks; escapes single quotes
928 * @param Target target buffer
929 * @param Source source buffer; set to NULL if you just have a C-String
930 * @param PlainIn Plain-C string to append; set to NULL if unused
932 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
934 const char *aptr, *eiptr;
938 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
941 if (PlainIn != NULL) {
943 len = strlen(PlainIn);
948 eiptr = aptr + Source->BufUsed;
949 len = Source->BufUsed;
955 eptr = Target->buf + Target->BufSize - 8;
956 tptr = Target->buf + Target->BufUsed;
958 while (aptr < eiptr){
960 IncreaseBuf(Target, 1, -1);
961 eptr = Target->buf + Target->BufSize - 8;
962 tptr = Target->buf + Target->BufUsed;
969 else if (*aptr == '\r') {
973 else if (*aptr == '\'') {
979 Target->BufUsed += 5;
992 * @ingroup StrBuf_DeEnCoder
993 * @brief Append a string, escaping characters which have meaning in ICAL.
995 * @param Target target buffer
996 * @param Source source buffer; set to NULL if you just have a C-String
997 * @param PlainIn Plain-C string to append; set to NULL if unused
999 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1001 const char *aptr, *eiptr;
1005 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1008 if (PlainIn != NULL) {
1010 len = strlen(PlainIn);
1015 eiptr = aptr + Source->BufUsed;
1016 len = Source->BufUsed;
1022 eptr = Target->buf + Target->BufSize - 8;
1023 tptr = Target->buf + Target->BufUsed;
1025 while (aptr < eiptr){
1026 if(tptr + 3 >= eptr) {
1027 IncreaseBuf(Target, 1, -1);
1028 eptr = Target->buf + Target->BufSize - 8;
1029 tptr = Target->buf + Target->BufUsed;
1032 if (*aptr == '\n') {
1039 else if (*aptr == '\r') {
1046 else if (*aptr == ',') {
1062 * @ingroup StrBuf_DeEnCoder
1063 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1065 * @param Target target buffer
1066 * @param Source source buffer; set to NULL if you just have a C-String
1067 * @param PlainIn Plain-C string to append; set to NULL if unused
1068 * @returns size of result or -1
1070 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1072 const char *aptr, *eiptr;
1076 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1079 if (PlainIn != NULL) {
1081 len = strlen(PlainIn);
1086 eiptr = aptr + Source->BufUsed;
1087 len = Source->BufUsed;
1093 bptr = Target->buf + Target->BufUsed;
1094 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1096 while (aptr < eiptr){
1098 IncreaseBuf(Target, 1, -1);
1099 eptr = Target->buf + Target->BufSize - 3;
1100 bptr = Target->buf + Target->BufUsed;
1107 Target->BufUsed += 2;
1108 } else if (*aptr == '\\') {
1113 Target->BufUsed += 2;
1123 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1125 return Target->BufUsed;
1129 * @ingroup StrBuf_DeEnCoder
1130 * @brief Append a string, escaping characters which have meaning in HTML + json.
1132 * @param Target target buffer
1133 * @param Source source buffer; set to NULL if you just have a C-String
1134 * @param PlainIn Plain-C string to append; set to NULL if unused
1135 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1136 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1137 * if set to 2, linebreaks are replaced by <br/>
1139 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1141 const char *aptr, *eiptr;
1144 int IsUtf8Sequence = 0;
1146 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1149 if (PlainIn != NULL) {
1151 len = strlen(PlainIn);
1156 eiptr = aptr + Source->BufUsed;
1157 len = Source->BufUsed;
1163 bptr = Target->buf + Target->BufUsed;
1164 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1166 while (aptr < eiptr){
1168 IncreaseBuf(Target, 1, -1);
1169 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1170 bptr = Target->buf + Target->BufUsed;
1173 memcpy(bptr, "<", 4);
1175 Target->BufUsed += 4;
1177 else if (*aptr == '>') {
1178 memcpy(bptr, ">", 4);
1180 Target->BufUsed += 4;
1182 else if (*aptr == '&') {
1183 memcpy(bptr, "&", 5);
1185 Target->BufUsed += 5;
1187 else if (*aptr == LB) {
1192 else if (*aptr == RB) {
1197 else if ((*aptr == 32) && (nbsp == 1)) {
1198 memcpy(bptr, " ", 6);
1200 Target->BufUsed += 6;
1202 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1203 *bptr='\0'; /* nothing */
1205 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1206 memcpy(bptr, "<br/>", 11);
1208 Target->BufUsed += 11;
1211 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1212 *bptr='\0'; /* nothing */
1215 else if ((*aptr == '"') || (*aptr == QU)) {
1220 Target->BufUsed += 2;
1221 } else if (*aptr == '\\') {
1226 Target->BufUsed += 2;
1229 if (((unsigned char)*aptr) >= 0x20)
1231 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1235 while (IsUtf8Sequence > 1){
1236 if(bptr + IsUtf8Sequence >= eptr) {
1237 IncreaseBuf(Target, 1, -1);
1238 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1239 bptr = Target->buf + Target->BufUsed - 1;
1253 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1255 return Target->BufUsed;
1261 * @brief extracts a substring from Source into dest
1262 * @param dest buffer to place substring into
1263 * @param Source string to copy substring from
1264 * @param Offset chars to skip from start
1265 * @param nChars number of chars to copy
1266 * @returns the number of chars copied; may be different from nChars due to the size of Source
1268 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1270 size_t NCharsRemain;
1271 if (Offset > Source->BufUsed)
1276 if (Offset + nChars < Source->BufUsed)
1278 if (nChars >= dest->BufSize)
1279 IncreaseBuf(dest, 0, nChars + 1);
1280 memcpy(dest->buf, Source->buf + Offset, nChars);
1281 dest->BufUsed = nChars;
1282 dest->buf[dest->BufUsed] = '\0';
1285 NCharsRemain = Source->BufUsed - Offset;
1286 if (NCharsRemain >= dest->BufSize)
1287 IncreaseBuf(dest, 0, NCharsRemain + 1);
1288 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1289 dest->BufUsed = NCharsRemain;
1290 dest->buf[dest->BufUsed] = '\0';
1291 return NCharsRemain;
1296 * @brief sprintf like function appending the formated string to the buffer
1297 * vsnprintf version to wrap into own calls
1298 * @param Buf Buffer to extend by format and Params
1299 * @param format printf alike format to add
1300 * @param ap va_list containing the items for format
1302 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1310 if ((Buf == NULL) || (format == NULL))
1313 BufSize = Buf->BufSize;
1314 nWritten = Buf->BufSize + 1;
1315 Offset = Buf->BufUsed;
1316 newused = Offset + nWritten;
1318 while (newused >= BufSize) {
1320 nWritten = vsnprintf(Buf->buf + Offset,
1321 Buf->BufSize - Offset,
1324 newused = Offset + nWritten;
1325 if (newused >= Buf->BufSize) {
1326 IncreaseBuf(Buf, 1, newused);
1327 newused = Buf->BufSize + 1;
1330 Buf->BufUsed = Offset + nWritten;
1331 BufSize = Buf->BufSize;
1339 * @brief sprintf like function appending the formated string to the buffer
1340 * @param Buf Buffer to extend by format and Params
1341 * @param format printf alike format to add
1343 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1351 if ((Buf == NULL) || (format == NULL))
1354 BufSize = Buf->BufSize;
1355 nWritten = Buf->BufSize + 1;
1356 Offset = Buf->BufUsed;
1357 newused = Offset + nWritten;
1359 while (newused >= BufSize) {
1360 va_start(arg_ptr, format);
1361 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1362 Buf->BufSize - Buf->BufUsed,
1365 newused = Buf->BufUsed + nWritten;
1366 if (newused >= Buf->BufSize) {
1367 IncreaseBuf(Buf, 1, newused);
1368 newused = Buf->BufSize + 1;
1371 Buf->BufUsed += nWritten;
1372 BufSize = Buf->BufSize;
1380 * @brief sprintf like function putting the formated string into the buffer
1381 * @param Buf Buffer to extend by format and Parameters
1382 * @param format printf alike format to add
1384 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1389 if ((Buf == NULL) || (format == NULL))
1392 nWritten = Buf->BufSize + 1;
1393 while (nWritten >= Buf->BufSize) {
1394 va_start(arg_ptr, format);
1395 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1397 if (nWritten >= Buf->BufSize) {
1398 IncreaseBuf(Buf, 0, 0);
1399 nWritten = Buf->BufSize + 1;
1402 Buf->BufUsed = nWritten ;
1408 * @ingroup StrBuf_Tokenizer
1409 * @brief Counts the numbmer of tokens in a buffer
1410 * @param source String to count tokens in
1411 * @param tok Tokenizer char to count
1412 * @returns numbers of tokenizer chars found
1414 int StrBufNum_tokens(const StrBuf *source, char tok)
1418 return num_tokens(source->buf, tok);
1422 * remove_token() - a tokenizer that kills, maims, and destroys
1425 * @ingroup StrBuf_Tokenizer
1426 * @brief a string tokenizer
1427 * @param Source StringBuffer to read into
1428 * @param parmnum n'th Parameter to remove
1429 * @param separator tokenizer character
1430 * @returns -1 if not found, else length of token.
1432 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1435 char *d, *s, *end; /* dest, source */
1438 /* Find desired @parameter */
1439 end = Source->buf + Source->BufUsed;
1441 while ((d <= end) &&
1444 /* End of string, bail! */
1449 if (*d == separator) {
1454 if ((d == NULL) || (d >= end))
1455 return 0; /* @Parameter not found */
1457 /* Find next @parameter */
1459 while ((s <= end) &&
1460 (*s && *s != separator))
1464 if (*s == separator)
1468 /* Hack and slash */
1473 memmove(d, s, Source->BufUsed - (s - Source->buf));
1474 Source->BufUsed += ReducedBy;
1475 Source->buf[Source->BufUsed] = '\0';
1477 else if (d == Source->buf) {
1479 Source->BufUsed = 0;
1483 Source->BufUsed += ReducedBy;
1496 * @ingroup StrBuf_Tokenizer
1497 * @brief a string tokenizer
1498 * @param dest Destination StringBuffer
1499 * @param Source StringBuffer to read into
1500 * @param parmnum n'th Parameter to extract
1501 * @param separator tokenizer character
1502 * @returns -1 if not found, else length of token.
1504 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1506 const char *s, *e; //* source * /
1507 int len = 0; //* running total length of extracted string * /
1508 int current_token = 0; //* token currently being processed * /
1511 dest->buf[0] = '\0';
1517 if ((Source == NULL) || (Source->BufUsed ==0)) {
1521 e = s + Source->BufUsed;
1524 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1526 while ((s<e) && !IsEmptyStr(s)) {
1527 if (*s == separator) {
1530 if (len >= dest->BufSize) {
1531 dest->BufUsed = len;
1532 if (IncreaseBuf(dest, 1, -1) < 0) {
1537 if ( (current_token == parmnum) &&
1538 (*s != separator)) {
1539 dest->buf[len] = *s;
1542 else if (current_token > parmnum) {
1548 dest->buf[len] = '\0';
1549 dest->BufUsed = len;
1551 if (current_token < parmnum) {
1552 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1555 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1564 * @ingroup StrBuf_Tokenizer
1565 * @brief a string tokenizer to fetch an integer
1566 * @param Source String containing tokens
1567 * @param parmnum n'th Parameter to extract
1568 * @param separator tokenizer character
1569 * @returns 0 if not found, else integer representation of the token
1571 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1581 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1588 * @ingroup StrBuf_Tokenizer
1589 * @brief a string tokenizer to fetch a long integer
1590 * @param Source String containing tokens
1591 * @param parmnum n'th Parameter to extract
1592 * @param separator tokenizer character
1593 * @returns 0 if not found, else long integer representation of the token
1595 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1605 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1613 * @ingroup StrBuf_Tokenizer
1614 * @brief a string tokenizer to fetch an unsigned long
1615 * @param Source String containing tokens
1616 * @param parmnum n'th Parameter to extract
1617 * @param separator tokenizer character
1618 * @returns 0 if not found, else unsigned long representation of the token
1620 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1631 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1635 return (unsigned long) atol(pnum);
1644 * @ingroup StrBuf_NextTokenizer
1645 * @brief a string tokenizer; Bounds checker
1646 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1647 * @param Source our tokenbuffer
1648 * @param pStart the token iterator pointer to inspect
1649 * @returns whether the revolving pointer is inside of the search range
1651 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1653 if ((Source == NULL) ||
1654 (*pStart == StrBufNOTNULL) ||
1655 (Source->BufUsed == 0))
1659 if (*pStart == NULL)
1663 else if (*pStart > Source->buf + Source->BufUsed)
1667 else if (*pStart <= Source->buf)
1676 * @ingroup StrBuf_NextTokenizer
1677 * @brief a string tokenizer
1678 * @param dest Destination StringBuffer
1679 * @param Source StringBuffer to read into
1680 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1681 * @param separator tokenizer
1682 * @returns -1 if not found, else length of token.
1684 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1686 const char *s; /* source */
1687 const char *EndBuffer; /* end stop of source buffer */
1688 int current_token = 0; /* token currently being processed */
1689 int len = 0; /* running total length of extracted string */
1691 if ((Source == NULL) ||
1692 (Source->BufUsed == 0) )
1694 *pStart = StrBufNOTNULL;
1698 EndBuffer = Source->buf + Source->BufUsed;
1702 dest->buf[0] = '\0';
1707 *pStart = EndBuffer + 1;
1711 if (*pStart == NULL)
1713 *pStart = Source->buf; /* we're starting to examine this buffer. */
1715 else if ((*pStart < Source->buf) ||
1716 (*pStart > EndBuffer ) )
1718 return -1; /* no more tokens to find. */
1722 /* start to find the next token */
1723 while ((s <= EndBuffer) &&
1724 (current_token == 0) )
1726 if (*s == separator)
1728 /* we found the next token */
1732 if (len >= dest->BufSize)
1734 /* our Dest-buffer isn't big enough, increase it. */
1735 dest->BufUsed = len;
1737 if (IncreaseBuf(dest, 1, -1) < 0) {
1738 /* WHUT? no more mem? bail out. */
1745 if ( (current_token == 0 ) && /* are we in our target token? */
1746 (!IsEmptyStr(s) ) &&
1747 (separator != *s) ) /* don't copy the token itself */
1749 dest->buf[len] = *s; /* Copy the payload */
1750 ++len; /* remember the bigger size. */
1756 /* did we reach the end? */
1757 if ((s > EndBuffer)) {
1758 EndBuffer = StrBufNOTNULL;
1759 *pStart = EndBuffer;
1762 *pStart = s; /* remember the position for the next run */
1765 /* sanitize our extracted token */
1766 dest->buf[len] = '\0';
1767 dest->BufUsed = len;
1774 * @ingroup StrBuf_NextTokenizer
1775 * @brief a string tokenizer
1776 * @param Source StringBuffer to read from
1777 * @param pStart pointer to the end of the last token. Feed with NULL.
1778 * @param separator tokenizer character
1779 * @param nTokens number of tokens to fastforward over
1780 * @returns -1 if not found, else length of token.
1782 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1784 const char *s, *EndBuffer; //* source * /
1785 int len = 0; //* running total length of extracted string * /
1786 int current_token = 0; //* token currently being processed * /
1788 if ((Source == NULL) ||
1789 (Source->BufUsed ==0)) {
1793 return Source->BufUsed;
1795 if (*pStart == NULL)
1796 *pStart = Source->buf;
1798 EndBuffer = Source->buf + Source->BufUsed;
1800 if ((*pStart < Source->buf) ||
1801 (*pStart > EndBuffer)) {
1809 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1811 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1812 if (*s == separator) {
1815 if (current_token >= nTokens) {
1827 * @ingroup StrBuf_NextTokenizer
1828 * @brief a string tokenizer to fetch an integer
1829 * @param Source StringBuffer to read from
1830 * @param pStart Cursor on the tokenstring
1831 * @param separator tokenizer character
1832 * @returns 0 if not found, else integer representation of the token
1834 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1844 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1851 * @ingroup StrBuf_NextTokenizer
1852 * @brief a string tokenizer to fetch a long integer
1853 * @param Source StringBuffer to read from
1854 * @param pStart Cursor on the tokenstring
1855 * @param separator tokenizer character
1856 * @returns 0 if not found, else long integer representation of the token
1858 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1868 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1876 * @ingroup StrBuf_NextTokenizer
1877 * @brief a string tokenizer to fetch an unsigned long
1878 * @param Source StringBuffer to read from
1879 * @param pStart Cursor on the tokenstring
1880 * @param separator tokenizer character
1881 * @returns 0 if not found, else unsigned long representation of the token
1883 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1894 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1898 return (unsigned long) atol(pnum);
1907 * @ingroup StrBuf_IO
1908 * @brief Read a line from socket
1909 * flushes and closes the FD on error
1910 * @param buf the buffer to get the input to
1911 * @param fd pointer to the filedescriptor to read
1912 * @param append Append to an existing string or replace?
1913 * @param Error strerror() on error
1914 * @returns numbers of chars read
1916 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1918 int len, rlen, slen;
1923 slen = len = buf->BufUsed;
1925 rlen = read(*fd, &buf->buf[len], 1);
1927 *Error = strerror(errno);
1934 if (buf->buf[len] == '\n')
1936 if (buf->buf[len] != '\r')
1938 if (len + 2 >= buf->BufSize) {
1940 buf->buf[len+1] = '\0';
1941 IncreaseBuf(buf, 1, -1);
1945 buf->buf[len] = '\0';
1950 * @ingroup StrBuf_BufferedIO
1951 * @brief Read a line from socket
1952 * flushes and closes the FD on error
1953 * @param Line the line to read from the fd / I/O Buffer
1954 * @param buf the buffer to get the input to
1955 * @param fd pointer to the filedescriptor to read
1956 * @param timeout number of successless selects until we bail out
1957 * @param selectresolution how long to wait on each select
1958 * @param Error strerror() on error
1959 * @returns numbers of chars read
1961 int StrBufTCP_read_buffered_line(StrBuf *Line,
1965 int selectresolution,
1969 int nSuccessLess = 0;
1976 if (buf->BufUsed > 0) {
1977 pch = strchr(buf->buf, '\n');
1980 len = pch - buf->buf;
1981 if (len > 0 && (*(pch - 1) == '\r') )
1983 StrBufSub(Line, buf, 0, len - rlen);
1984 StrBufCutLeft(buf, len + 1);
1989 if (buf->BufSize - buf->BufUsed < 10)
1990 IncreaseBuf(buf, 1, -1);
1992 fdflags = fcntl(*fd, F_GETFL);
1993 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1995 while ((nSuccessLess < timeout) && (pch == NULL)) {
1997 tv.tv_sec = selectresolution;
2002 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
2003 *Error = strerror(errno);
2009 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
2014 &buf->buf[buf->BufUsed],
2015 buf->BufSize - buf->BufUsed - 1);
2017 *Error = strerror(errno);
2022 else if (rlen > 0) {
2024 buf->BufUsed += rlen;
2025 buf->buf[buf->BufUsed] = '\0';
2026 if (buf->BufUsed + 10 > buf->BufSize) {
2027 IncreaseBuf(buf, 1, -1);
2029 pch = strchr(buf->buf, '\n');
2036 len = pch - buf->buf;
2037 if (len > 0 && (*(pch - 1) == '\r') )
2039 StrBufSub(Line, buf, 0, len - rlen);
2040 StrBufCutLeft(buf, len + 1);
2047 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
2048 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
2049 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
2051 * @ingroup StrBuf_BufferedIO
2052 * @brief Read a line from socket
2053 * flushes and closes the FD on error
2054 * @param Line Line to read from the fd / I/O Buffer
2055 * @param IOBuf the buffer to get the input to
2056 * @param Pos pointer to the current read position, should be NULL initialized!
2057 * @param fd pointer to the filedescriptor to read
2058 * @param timeout number of successless selects until we bail out
2059 * @param selectresolution how long to wait on each select
2060 * @param Error strerror() on error
2061 * @returns numbers of chars read
2063 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
2068 int selectresolution,
2071 const char *pche = NULL;
2072 const char *pos = NULL;
2074 int nSuccessLess = 0;
2076 const char *pch = NULL;
2081 if ((Line == NULL) ||
2085 *Error = ErrRBLF_PreConditionFailed;
2090 if ((IOBuf->BufUsed > 0) &&
2092 (pos < IOBuf->buf + IOBuf->BufUsed))
2094 pche = IOBuf->buf + IOBuf->BufUsed;
2096 while ((pch < pche) && (*pch != '\n'))
2098 if ((pch >= pche) || (*pch == '\0'))
2100 if ((pch != NULL) &&
2105 if (len > 0 && (*(pch - 1) == '\r') )
2107 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
2117 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
2121 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
2122 IncreaseBuf(IOBuf, 1, -1);
2125 fdflags = fcntl(*fd, F_GETFL);
2126 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2129 while ((nSuccessLess < timeout) &&
2139 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
2140 *Error = strerror(errno);
2144 *Error = ErrRBLF_SelectFailed;
2147 if (! FD_ISSET(*fd, &rfds) != 0) {
2153 &IOBuf->buf[IOBuf->BufUsed],
2154 IOBuf->BufSize - IOBuf->BufUsed - 1);
2156 *Error = strerror(errno);
2161 else if (rlen > 0) {
2163 IOBuf->BufUsed += rlen;
2164 IOBuf->buf[IOBuf->BufUsed] = '\0';
2165 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
2166 IncreaseBuf(IOBuf, 1, -1);
2170 pche = IOBuf->buf + IOBuf->BufUsed;
2172 while ((pch < pche) && (*pch != '\n'))
2174 if ((pch >= pche) || (*pch == '\0'))
2183 if (len > 0 && (*(pch - 1) == '\r') )
2185 StrBufSub(Line, IOBuf, 0, len - rlen);
2186 *Pos = pos + len + 1;
2189 *Error = ErrRBLF_NotEnoughSentFromServer;
2194 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
2196 * @ingroup StrBuf_IO
2197 * @brief Input binary data from socket
2198 * flushes and closes the FD on error
2199 * @param Buf the buffer to get the input to
2200 * @param fd pointer to the filedescriptor to read
2201 * @param append Append to an existing string or replace?
2202 * @param nBytes the maximal number of bytes to read
2203 * @param Error strerror() on error
2204 * @returns numbers of chars read
2206 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
2209 int len, rlen, slen;
2217 if ((Buf == NULL) || (*fd == -1))
2219 *Error = ErrRBLF_BLOBPreConditionFailed;
2224 if (Buf->BufUsed + nBytes >= Buf->BufSize)
2225 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
2227 ptr = Buf->buf + Buf->BufUsed;
2229 slen = len = Buf->BufUsed;
2231 fdflags = fcntl(*fd, F_GETFL);
2232 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2234 while ((nRead < nBytes) &&
2244 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2245 *Error = strerror(errno);
2249 *Error = ErrRBLF_SelectFailed;
2252 if (! FD_ISSET(*fd, &rfds) != 0) {
2258 if ((rlen = read(*fd,
2260 nBytes - nRead)) == -1) {
2263 *Error = strerror(errno);
2268 Buf->BufUsed += rlen;
2270 Buf->buf[Buf->BufUsed] = '\0';
2274 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
2275 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
2277 * @ingroup StrBuf_BufferedIO
2278 * @brief Input binary data from socket
2279 * flushes and closes the FD on error
2280 * @param Blob put binary thing here
2281 * @param IOBuf the buffer to get the input to
2282 * @param Pos offset inside of IOBuf
2283 * @param fd pointer to the filedescriptor to read
2284 * @param append Append to an existing string or replace?
2285 * @param nBytes the maximal number of bytes to read
2286 * @param check whether we should search for '000\n' terminators in case of timeouts
2287 * @param Error strerror() on error
2288 * @returns numbers of chars read
2290 int StrBufReadBLOBBuffered(StrBuf *Blob,
2307 int nAlreadyRead = 0;
2315 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2317 *Error = ErrRBB_BLOBFPreConditionFailed;
2323 if (Blob->BufUsed + nBytes >= Blob->BufSize)
2324 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2329 len = pos - IOBuf->buf;
2330 rlen = IOBuf->BufUsed - len;
2333 if ((IOBuf->BufUsed > 0) &&
2335 (pos < IOBuf->buf + IOBuf->BufUsed))
2337 pche = IOBuf->buf + IOBuf->BufUsed;
2340 if (rlen < nBytes) {
2341 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2342 Blob->BufUsed += rlen;
2343 Blob->buf[Blob->BufUsed] = '\0';
2344 nAlreadyRead = nRead = rlen;
2347 if (rlen >= nBytes) {
2348 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2349 Blob->BufUsed += nBytes;
2350 Blob->buf[Blob->BufUsed] = '\0';
2351 if (rlen == nBytes) {
2362 if (IOBuf->BufSize < nBytes - nRead)
2363 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2366 slen = len = Blob->BufUsed;
2368 fdflags = fcntl(*fd, F_GETFL);
2369 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2374 while ((nRead < nBytes) &&
2383 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2384 *Error = strerror(errno);
2388 *Error = ErrRBLF_SelectFailed;
2391 if (! FD_ISSET(*fd, &rfds) != 0) {
2403 *Error = strerror(errno);
2406 else if (rlen == 0){
2408 if ((check == NNN_TERM) &&
2410 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2412 StrBufPlain(Blob, HKEY("\n000\n"));
2413 StrBufCutRight(Blob, 5);
2414 return Blob->BufUsed;
2416 if (nSelects > 10) {
2418 *Error = ErrRBB_too_many_selects;
2422 else if (rlen > 0) {
2425 IOBuf->BufUsed += rlen;
2428 if (nRead > nBytes) {
2429 *Pos = IOBuf->buf + nBytes;
2431 Blob->buf[Blob->BufUsed] = '\0';
2432 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2436 return nRead + nAlreadyRead;
2441 * @brief Cut nChars from the start of the string
2442 * @param Buf Buffer to modify
2443 * @param nChars how many chars should be skipped?
2445 void StrBufCutLeft(StrBuf *Buf, int nChars)
2447 if (nChars >= Buf->BufUsed) {
2451 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2452 Buf->BufUsed -= nChars;
2453 Buf->buf[Buf->BufUsed] = '\0';
2458 * @brief Cut the trailing n Chars from the string
2459 * @param Buf Buffer to modify
2460 * @param nChars how many chars should be trunkated?
2462 void StrBufCutRight(StrBuf *Buf, int nChars)
2464 if (nChars >= Buf->BufUsed) {
2468 Buf->BufUsed -= nChars;
2469 Buf->buf[Buf->BufUsed] = '\0';
2474 * @brief Cut the string after n Chars
2475 * @param Buf Buffer to modify
2476 * @param AfternChars after how many chars should we trunkate the string?
2477 * @param At if non-null and points inside of our string, cut it there.
2479 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2482 AfternChars = At - Buf->buf;
2485 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2487 Buf->BufUsed = AfternChars;
2488 Buf->buf[Buf->BufUsed] = '\0';
2494 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2495 * @param Buf the string to modify
2497 void StrBufTrim(StrBuf *Buf)
2500 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2502 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2505 if (delta > 0) StrBufCutLeft(Buf, delta);
2507 if (Buf->BufUsed == 0) return;
2508 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2511 Buf->buf[Buf->BufUsed] = '\0';
2516 * @brief uppercase the contents of a buffer
2517 * @param Buf the buffer to translate
2519 void StrBufUpCase(StrBuf *Buf)
2524 pche = pch + Buf->BufUsed;
2525 while (pch < pche) {
2526 *pch = toupper(*pch);
2534 * @brief lowercase the contents of a buffer
2535 * @param Buf the buffer to translate
2537 void StrBufLowerCase(StrBuf *Buf)
2542 pche = pch + Buf->BufUsed;
2543 while (pch < pche) {
2544 *pch = tolower(*pch);
2551 * @brief removes double slashes from pathnames
2552 * @param Dir directory string to filter
2553 * @param RemoveTrailingSlash allows / disallows trailing slashes
2555 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2561 while (!IsEmptyStr(a)) {
2573 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2578 Dir->BufUsed = b - Dir->buf;
2582 * @ingroup StrBuf_DeEnCoder
2583 * @brief unhide special chars hidden to the HTML escaper
2584 * @param target buffer to put the unescaped string in
2585 * @param source buffer to unescape
2587 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2593 FlushStrBuf(target);
2595 if (source == NULL ||target == NULL)
2600 len = source->BufUsed;
2601 for (a = 0; a < len; ++a) {
2602 if (target->BufUsed >= target->BufSize)
2603 IncreaseBuf(target, 1, -1);
2605 if (source->buf[a] == '=') {
2606 hex[0] = source->buf[a + 1];
2607 hex[1] = source->buf[a + 2];
2610 sscanf(hex, "%02x", &b);
2611 target->buf[target->BufUsed] = b;
2612 target->buf[++target->BufUsed] = 0;
2616 target->buf[target->BufUsed] = source->buf[a];
2617 target->buf[++target->BufUsed] = 0;
2624 * @ingroup StrBuf_DeEnCoder
2625 * @brief hide special chars from the HTML escapers and friends
2626 * @param target buffer to put the escaped string in
2627 * @param source buffer to escape
2629 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2634 FlushStrBuf(target);
2636 if (source == NULL ||target == NULL)
2641 len = source->BufUsed;
2642 for (i=0; i<len; ++i) {
2643 if (target->BufUsed + 4 >= target->BufSize)
2644 IncreaseBuf(target, 1, -1);
2645 if ( (isalnum(source->buf[i])) ||
2646 (source->buf[i]=='-') ||
2647 (source->buf[i]=='_') ) {
2648 target->buf[target->BufUsed++] = source->buf[i];
2651 sprintf(&target->buf[target->BufUsed],
2653 (0xFF &source->buf[i]));
2654 target->BufUsed += 3;
2657 target->buf[target->BufUsed + 1] = '\0';
2661 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2662 #define OS_CODE 0x03 /*< unix */
2665 * @ingroup StrBuf_DeEnCoder
2666 * @brief uses the same calling syntax as compress2(), but it
2667 * creates a stream compatible with HTTP "Content-encoding: gzip"
2668 * @param dest compressed buffer
2669 * @param destLen length of the compresed data
2670 * @param source source to encode
2671 * @param sourceLen length of source to encode
2672 * @param level compression level
2674 int ZEXPORT compress_gzip(Bytef * dest,
2676 const Bytef * source,
2680 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2682 /* write gzip header */
2683 snprintf((char *) dest, *destLen,
2684 "%c%c%c%c%c%c%c%c%c%c",
2685 gz_magic[0], gz_magic[1], Z_DEFLATED,
2686 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2689 /* normal deflate */
2692 stream.next_in = (Bytef *) source;
2693 stream.avail_in = (uInt) sourceLen;
2694 stream.next_out = dest + 10L; // after header
2695 stream.avail_out = (uInt) * destLen;
2696 if ((uLong) stream.avail_out != *destLen)
2699 stream.zalloc = (alloc_func) 0;
2700 stream.zfree = (free_func) 0;
2701 stream.opaque = (voidpf) 0;
2703 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2704 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2708 err = deflate(&stream, Z_FINISH);
2709 if (err != Z_STREAM_END) {
2710 deflateEnd(&stream);
2711 return err == Z_OK ? Z_BUF_ERROR : err;
2713 *destLen = stream.total_out + 10L;
2715 /* write CRC and Length */
2716 uLong crc = crc32(0L, source, sourceLen);
2718 for (n = 0; n < 4; ++n, ++*destLen) {
2719 dest[*destLen] = (int) (crc & 0xff);
2722 uLong len = stream.total_in;
2723 for (n = 0; n < 4; ++n, ++*destLen) {
2724 dest[*destLen] = (int) (len & 0xff);
2727 err = deflateEnd(&stream);
2734 * @ingroup StrBuf_DeEnCoder
2735 * @brief compress the buffer with gzip
2736 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2737 * @param Buf buffer whose content is to be gzipped
2739 int CompressBuffer(StrBuf *Buf)
2742 char *compressed_data = NULL;
2743 size_t compressed_len, bufsize;
2746 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2747 compressed_data = malloc(compressed_len);
2749 if (compressed_data == NULL)
2751 /* Flush some space after the used payload so valgrind shuts up... */
2752 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2753 Buf->buf[Buf->BufUsed + i++] = '\0';
2754 if (compress_gzip((Bytef *) compressed_data,
2757 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2760 Buf->buf = compressed_data;
2761 Buf->BufUsed = compressed_len;
2762 Buf->BufSize = bufsize;
2763 /* Flush some space after the used payload so valgrind shuts up... */
2765 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2766 Buf->buf[Buf->BufUsed + i++] = '\0';
2769 free(compressed_data);
2771 #endif /* HAVE_ZLIB */
2776 * @ingroup StrBuf_DeEnCoder
2777 * @brief decode a buffer from base 64 encoding; destroys original
2778 * @param Buf Buffor to transform
2780 int StrBufDecodeBase64(StrBuf *Buf)
2784 if (Buf == NULL) return -1;
2786 xferbuf = (char*) malloc(Buf->BufSize);
2787 siz = CtdlDecodeBase64(xferbuf,
2797 * @ingroup StrBuf_DeEnCoder
2798 * @brief decode a buffer from base 64 encoding; destroys original
2799 * @param Buf Buffor to transform
2801 int StrBufDecodeHex(StrBuf *Buf)
2804 char *pch, *pche, *pchi;
2806 if (Buf == NULL) return -1;
2808 pch = pchi = Buf->buf;
2809 pche = pch + Buf->BufUsed;
2811 while (pchi < pche){
2812 ch = decode_hex(pchi);
2819 Buf->BufUsed = pch - Buf->buf;
2820 return Buf->BufUsed;
2824 * @ingroup StrBuf_DeEnCoder
2825 * @brief replace all chars >0x20 && < 0x7F with Mute
2826 * @param Mute char to put over invalid chars
2827 * @param Buf Buffor to transform
2829 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2833 if (Buf == NULL) return -1;
2834 pch = (unsigned char *)Buf->buf;
2835 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2836 if ((*pch < 0x20) || (*pch > 0x7F))
2840 return Buf->BufUsed;
2845 * @ingroup StrBuf_DeEnCoder
2846 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2847 * @param Buf Buffer to translate
2848 * @param StripBlanks Reduce several blanks to one?
2850 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2856 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2857 Buf->buf[Buf->BufUsed - 1] = '\0';
2862 while (a < Buf->BufUsed) {
2863 if (Buf->buf[a] == '+')
2865 else if (Buf->buf[a] == '%') {
2866 /* don't let % chars through, rather truncate the input. */
2867 if (a + 2 > Buf->BufUsed) {
2872 hex[0] = Buf->buf[a + 1];
2873 hex[1] = Buf->buf[a + 2];
2876 sscanf(hex, "%02x", &b);
2877 Buf->buf[a] = (char) b;
2878 len = Buf->BufUsed - a - 2;
2880 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2892 * @ingroup StrBuf_DeEnCoder
2893 * @brief RFC2047-encode a header field if necessary.
2894 * If no non-ASCII characters are found, the string
2895 * will be copied verbatim without encoding.
2897 * @param target Target buffer.
2898 * @param source Source string to be encoded.
2899 * @returns encoded length; -1 if non success.
2901 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2903 const char headerStr[] = "=?UTF-8?Q?";
2904 int need_to_encode = 0;
2908 if ((source == NULL) ||
2912 while ((i < source->BufUsed) &&
2913 (!IsEmptyStr (&source->buf[i])) &&
2914 (need_to_encode == 0)) {
2915 if (((unsigned char) source->buf[i] < 32) ||
2916 ((unsigned char) source->buf[i] > 126)) {
2922 if (!need_to_encode) {
2923 if (*target == NULL) {
2924 *target = NewStrBufPlain(source->buf, source->BufUsed);
2927 FlushStrBuf(*target);
2928 StrBufAppendBuf(*target, source, 0);
2930 return (*target)->BufUsed;
2932 if (*target == NULL)
2933 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2934 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2935 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2936 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2937 (*target)->BufUsed = sizeof(headerStr) - 1;
2938 for (i=0; (i < source->BufUsed); ++i) {
2939 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2940 IncreaseBuf(*target, 1, 0);
2941 ch = (unsigned char) source->buf[i];
2942 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2943 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2944 (*target)->BufUsed += 3;
2947 (*target)->buf[(*target)->BufUsed] = ch;
2948 (*target)->BufUsed++;
2952 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2953 IncreaseBuf(*target, 1, 0);
2955 (*target)->buf[(*target)->BufUsed++] = '?';
2956 (*target)->buf[(*target)->BufUsed++] = '=';
2957 (*target)->buf[(*target)->BufUsed] = '\0';
2958 return (*target)->BufUsed;;
2963 * @brief replaces all occurances of 'search' by 'replace'
2964 * @param buf Buffer to modify
2965 * @param search character to search
2966 * @param replace character to replace search by
2968 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2973 for (i=0; i<buf->BufUsed; i++)
2974 if (buf->buf[i] == search)
2975 buf->buf[i] = replace;
2982 * @ingroup StrBuf_DeEnCoder
2983 * @brief Wrapper around iconv_open()
2984 * Our version adds aliases for non-standard Microsoft charsets
2985 * such as 'MS950', aliasing them to names like 'CP950'
2987 * @param tocode Target encoding
2988 * @param fromcode Source encoding
2989 * @param pic anonimized pointer to iconv struct
2991 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2994 iconv_t ic = (iconv_t)(-1) ;
2995 ic = iconv_open(tocode, fromcode);
2996 if (ic == (iconv_t)(-1) ) {
2997 char alias_fromcode[64];
2998 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2999 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
3000 alias_fromcode[0] = 'C';
3001 alias_fromcode[1] = 'P';
3002 ic = iconv_open(tocode, alias_fromcode);
3005 *(iconv_t *)pic = ic;
3011 * @ingroup StrBuf_DeEnCoder
3012 * @brief find one chunk of a RFC822 encoded string
3013 * @param Buffer where to search
3014 * @param bptr where to start searching
3015 * @returns found position, NULL if none.
3017 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
3020 /* Find the next ?Q? */
3021 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
3024 end = strchr(bptr + 2, '?');
3029 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
3030 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
3031 (*(end + 2) == '?')) {
3032 /* skip on to the end of the cluster, the next ?= */
3033 end = strstr(end + 3, "?=");
3036 /* sort of half valid encoding, try to find an end. */
3037 end = strstr(bptr, "?=");
3043 * @brief swaps the contents of two StrBufs
3044 * this is to be used to have cheap switched between a work-buffer and a target buffer
3045 * @param A First one
3046 * @param B second one
3048 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
3052 memcpy(&C, A, sizeof(*A));
3053 memcpy(A, B, sizeof(*B));
3054 memcpy(B, &C, sizeof(C));
3060 * @ingroup StrBuf_DeEnCoder
3061 * @brief convert one buffer according to the preselected iconv pointer PIC
3062 * @param ConvertBuf buffer we need to translate
3063 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3064 * @param pic Pointer to the iconv-session Object
3066 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
3072 char *ibuf; /**< Buffer of characters to be converted */
3073 char *obuf; /**< Buffer for converted characters */
3074 size_t ibuflen; /**< Length of input buffer */
3075 size_t obuflen; /**< Length of output buffer */
3078 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3079 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3080 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3082 ic = *(iconv_t*)pic;
3083 ibuf = ConvertBuf->buf;
3084 ibuflen = ConvertBuf->BufUsed;
3086 obuflen = TmpBuf->BufSize;
3088 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3091 if (errno == E2BIG) {
3093 IncreaseBuf(TmpBuf, 0, 0);
3098 else if (errno == EILSEQ){
3099 /* hm, invalid utf8 sequence... what to do now? */
3100 /* An invalid multibyte sequence has been encountered in the input */
3102 else if (errno == EINVAL) {
3103 /* An incomplete multibyte sequence has been encountered in the input. */
3106 FlushStrBuf(TmpBuf);
3109 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3110 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3112 /* little card game: wheres the red lady? */
3113 SwapBuffers(ConvertBuf, TmpBuf);
3114 FlushStrBuf(TmpBuf);
3121 * @ingroup StrBuf_DeEnCoder
3122 * @brief catches one RFC822 encoded segment, and decodes it.
3123 * @param Target buffer to fill with result
3124 * @param DecodeMe buffer with stuff to process
3125 * @param SegmentStart points to our current segment in DecodeMe
3126 * @param SegmentEnd Points to the end of our current segment in DecodeMe
3127 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3128 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3129 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3131 inline static void DecodeSegment(StrBuf *Target,
3132 const StrBuf *DecodeMe,
3136 StrBuf *ConvertBuf2,
3137 StrBuf *FoundCharset)
3143 iconv_t ic = (iconv_t)(-1);
3147 /* Now we handle foreign character sets properly encoded
3148 * in RFC2047 format.
3150 StaticBuf.buf = SegmentStart;
3151 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3152 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3153 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3154 if (FoundCharset != NULL) {
3155 FlushStrBuf(FoundCharset);
3156 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3158 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3159 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3161 *encoding = toupper(*encoding);
3162 if (*encoding == 'B') { /**< base64 */
3163 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
3165 ConvertBuf->BufUsed);
3167 else if (*encoding == 'Q') { /**< quoted-printable */
3171 while (pos < ConvertBuf->BufUsed)
3173 if (ConvertBuf->buf[pos] == '_')
3174 ConvertBuf->buf[pos] = ' ';
3178 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3181 ConvertBuf->BufUsed);
3184 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3187 ctdl_iconv_open("UTF-8", charset, &ic);
3188 if (ic != (iconv_t)(-1) ) {
3190 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3191 StrBufAppendBuf(Target, ConvertBuf2, 0);
3196 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3202 * @ingroup StrBuf_DeEnCoder
3203 * @brief Handle subjects with RFC2047 encoding such as:
3204 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3205 * @param Target where to put the decoded string to
3206 * @param DecodeMe buffer with encoded string
3207 * @param DefaultCharset if we don't find one, which should we use?
3208 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3209 * put it here for later use where no string might be known.
3211 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3213 StrBuf *DecodedInvalidBuf = NULL;
3214 StrBuf *ConvertBuf, *ConvertBuf2;
3215 const StrBuf *DecodeMee = DecodeMe;
3216 char *start, *end, *next, *nextend, *ptr = NULL;
3218 iconv_t ic = (iconv_t)(-1) ;
3223 int illegal_non_rfc2047_encoding = 0;
3225 /* Sometimes, badly formed messages contain strings which were simply
3226 * written out directly in some foreign character set instead of
3227 * using RFC2047 encoding. This is illegal but we will attempt to
3228 * handle it anyway by converting from a user-specified default
3229 * charset to UTF-8 if we see any nonprintable characters.
3232 len = StrLength(DecodeMe);
3233 for (i=0; i<DecodeMe->BufUsed; ++i) {
3234 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3235 illegal_non_rfc2047_encoding = 1;
3240 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3241 if ((illegal_non_rfc2047_encoding) &&
3242 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3243 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3246 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3247 if (ic != (iconv_t)(-1) ) {
3248 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3249 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3250 DecodeMee = DecodedInvalidBuf;
3256 /* pre evaluate the first pair */
3257 nextend = end = NULL;
3258 len = StrLength(DecodeMee);
3259 start = strstr(DecodeMee->buf, "=?");
3260 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3262 end = FindNextEnd (DecodeMee, start);
3264 StrBufAppendBuf(Target, DecodeMee, 0);
3265 FreeStrBuf(&ConvertBuf);
3266 FreeStrBuf(&DecodedInvalidBuf);
3270 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3272 if (start != DecodeMee->buf) {
3275 nFront = start - DecodeMee->buf;
3276 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3280 * Since spammers will go to all sorts of absurd lengths to get their
3281 * messages through, there are LOTS of corrupt headers out there.
3282 * So, prevent a really badly formed RFC2047 header from throwing
3283 * this function into an infinite loop.
3285 while ((start != NULL) &&
3292 DecodeSegment(Target,
3300 next = strstr(end, "=?");
3302 if ((next != NULL) &&
3304 nextend = FindNextEnd(DecodeMee, next);
3305 if (nextend == NULL)
3308 /* did we find two partitions */
3309 if ((next != NULL) &&
3313 while ((ptr < next) &&
3319 /* did we find a gab just filled with blanks? */
3322 long gap = next - start;
3327 /* now terminate the gab at the end */
3328 delta = (next - end) - 2; ////TODO: const!
3329 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3330 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3332 /* move next to its new location. */
3337 /* our next-pair is our new first pair now. */
3343 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3344 if ((end != NULL) && (end < nextend)) {
3346 while ( (ptr < nextend) &&
3353 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3355 FreeStrBuf(&ConvertBuf);
3356 FreeStrBuf(&ConvertBuf2);
3357 FreeStrBuf(&DecodedInvalidBuf);
3362 * @brief evaluate the length of an utf8 special character sequence
3363 * @param Char the character to examine
3364 * @returns width of utf8 chars in bytes
3366 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3371 while ((n < 8) && ((test & *CharS) != 0)) {
3375 if ((n > 6) || ((CharE - CharS) < n))
3382 * @brief detect whether this char starts an utf-8 encoded char
3383 * @param Char character to inspect
3384 * @returns yes or no
3386 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3388 /** 11??.???? indicates an UTF8 Sequence. */
3389 return ((Char & 0xC0) != 0);
3394 * @brief measure the number of glyphs in an UTF8 string...
3395 * @param Buf string to measure
3396 * @returns the number of glyphs in Buf
3398 long StrBuf_Utf8StrLen(StrBuf *Buf)
3404 if ((Buf == NULL) || (Buf->BufUsed == 0))
3407 eptr = Buf->buf + Buf->BufUsed;
3408 while ((aptr < eptr) && (*aptr != '\0')) {
3409 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3410 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3411 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3424 * @brief cuts a string after maxlen glyphs
3425 * @param Buf string to cut to maxlen glyphs
3426 * @param maxlen how long may the string become?
3427 * @returns current length of the string
3429 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3435 eptr = Buf->buf + Buf->BufUsed;
3436 while ((aptr < eptr) && (*aptr != '\0')) {
3437 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3438 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3439 while ((*aptr++ != '\0') && (m-- > 0));
3448 Buf->BufUsed = aptr - Buf->buf;
3449 return Buf->BufUsed;
3452 return Buf->BufUsed;
3459 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3460 * @param LineBuf your line will be copied here.
3461 * @param Buf BLOB with lines of text...
3462 * @param Ptr moved arround to keep the next-line across several iterations
3463 * has to be &NULL on start; will be &NotNULL on end of buffer
3464 * @returns size of copied buffer
3466 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3468 const char *aptr, *ptr, *eptr;
3471 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3472 *Ptr = StrBufNOTNULL;
3476 FlushStrBuf(LineBuf);
3478 ptr = aptr = Buf->buf;
3482 optr = LineBuf->buf;
3483 eptr = Buf->buf + Buf->BufUsed;
3484 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3486 while ((ptr <= eptr) &&
3493 LineBuf->BufUsed = optr - LineBuf->buf;
3494 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3495 optr = LineBuf->buf + LineBuf->BufUsed;
3496 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3500 if ((ptr >= eptr) && (optr > LineBuf->buf))
3502 LineBuf->BufUsed = optr - LineBuf->buf;
3504 if ((ptr <= eptr) && (*ptr == '\r'))
3506 if ((ptr <= eptr) && (*ptr == '\n'))
3513 *Ptr = StrBufNOTNULL;
3516 return Buf->BufUsed - (ptr - Buf->buf);