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]);
159 void dbg_FreeStrBuf(StrBuf *FreeMe, char *FromWhere)
161 if (hFreeDbglog == -1){
162 pid_t pid = getpid();
164 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
165 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
167 if ((*FreeMe)->nIncreases > 0)
171 n = snprintf(buf, SIZ * 3, "%c+|%ld|%ld|%ld|%s|%s|\n",
173 (*FreeMe)->nIncreases,
177 (*FreeMe)->bt_lastinc);
178 n = write(hFreeDbglog, buf, n);
184 n = snprintf(buf, 128, "%c_|0|%ld%ld|\n",
188 n = write(hFreeDbglog, buf, n);
192 void dbg_IncreaseBuf(StrBuf *IncMe)
195 #ifdef HAVE_BACKTRACE
196 StrBufBacktrace(Buf, 1);
200 void dbg_Init(StrBuf *Buf)
204 Buf->bt_lastinc[0] = '\0';
205 #ifdef HAVE_BACKTRACE
206 StrBufBacktrace(Buf, 0);
212 #define dbg_FreeStrBuf(a, b)
213 #define dbg_IncreaseBuf(a)
219 * @ingroup StrBuf_Cast
220 * @brief Cast operator to Plain String
221 * @note if the buffer is altered by StrBuf operations, this pointer may become
222 * invalid. So don't lean on it after altering the buffer!
223 * Since this operation is considered cheap, rather call it often than risking
224 * your pointer to become invalid!
225 * @param Str the string we want to get the c-string representation for
226 * @returns the Pointer to the Content. Don't mess with it!
228 inline const char *ChrPtr(const StrBuf *Str)
236 * @ingroup StrBuf_Cast
237 * @brief since we know strlen()'s result, provide it here.
238 * @param Str the string to return the length to
239 * @returns contentlength of the buffer
241 inline int StrLength(const StrBuf *Str)
243 return (Str != NULL) ? Str->BufUsed : 0;
247 * @ingroup StrBuf_DeConstructors
248 * @brief local utility function to resize the buffer
249 * @param Buf the buffer whichs storage we should increase
250 * @param KeepOriginal should we copy the original buffer or just start over with a new one
251 * @param DestSize what should fit in after?
253 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
256 size_t NewSize = Buf->BufSize * 2;
262 while ((NewSize <= DestSize) && (NewSize != 0))
268 NewBuf= (char*) malloc(NewSize);
272 if (KeepOriginal && (Buf->BufUsed > 0))
274 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
283 Buf->BufSize = NewSize;
285 dbg_IncreaseBuf(Buf);
291 * @ingroup StrBuf_DeConstructors
292 * @brief shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
293 * @param Buf Buffer to shrink (has to be empty)
294 * @param ThreshHold if the buffer is bigger then this, its readjusted
295 * @param NewSize if we Shrink it, how big are we going to be afterwards?
297 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
300 (Buf->BufUsed == 0) &&
301 (Buf->BufSize < ThreshHold)) {
303 Buf->buf = (char*) malloc(NewSize);
305 Buf->BufSize = NewSize;
310 * @ingroup StrBuf_DeConstructors
311 * @brief shrink long term buffers to their real size so they don't waste memory
312 * @param Buf buffer to shrink
313 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
314 * @returns physical size of the buffer
316 long StrBufShrinkToFit(StrBuf *Buf, int Force)
321 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
323 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
324 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
325 Buf->BufSize = Buf->BufUsed + 1;
333 * @ingroup StrBuf_DeConstructors
334 * @brief Allocate a new buffer with default buffer size
335 * @returns the new stringbuffer
337 StrBuf* NewStrBuf(void)
341 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
342 NewBuf->buf = (char*) malloc(BaseStrBufSize);
343 NewBuf->buf[0] = '\0';
344 NewBuf->BufSize = BaseStrBufSize;
346 NewBuf->ConstBuf = 0;
354 * @ingroup StrBuf_DeConstructors
355 * @brief Copy Constructor; returns a duplicate of CopyMe
356 * @param CopyMe Buffer to faxmilate
357 * @returns the new stringbuffer
359 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
366 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
367 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
368 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
369 NewBuf->BufUsed = CopyMe->BufUsed;
370 NewBuf->BufSize = CopyMe->BufSize;
371 NewBuf->ConstBuf = 0;
379 * @ingroup StrBuf_DeConstructors
380 * @brief create a new Buffer using an existing c-string
381 * this function should also be used if you want to pre-suggest
382 * the buffer size to allocate in conjunction with ptr == NULL
383 * @param ptr the c-string to copy; may be NULL to create a blank instance
384 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
385 * @returns the new stringbuffer
387 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
390 size_t Siz = BaseStrBufSize;
393 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
395 CopySize = strlen((ptr != NULL)?ptr:"");
399 while ((Siz <= CopySize) && (Siz != 0))
407 NewBuf->buf = (char*) malloc(Siz);
408 NewBuf->BufSize = Siz;
410 memcpy(NewBuf->buf, ptr, CopySize);
411 NewBuf->buf[CopySize] = '\0';
412 NewBuf->BufUsed = CopySize;
415 NewBuf->buf[0] = '\0';
418 NewBuf->ConstBuf = 0;
426 * @ingroup StrBuf_DeConstructors
427 * @brief Set an existing buffer from a c-string
428 * @param Buf buffer to load
429 * @param ptr c-string to put into
430 * @param nChars set to -1 if we should work 0-terminated
431 * @returns the new length of the string
433 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
448 CopySize = strlen(ptr);
452 while ((Siz <= CopySize) && (Siz != 0))
460 if (Siz != Buf->BufSize)
461 IncreaseBuf(Buf, 0, Siz);
462 memcpy(Buf->buf, ptr, CopySize);
463 Buf->buf[CopySize] = '\0';
464 Buf->BufUsed = CopySize;
471 * @ingroup StrBuf_DeConstructors
472 * @brief use strbuf as wrapper for a string constant for easy handling
473 * @param StringConstant a string to wrap
474 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
476 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
480 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
481 NewBuf->buf = (char*) StringConstant;
482 NewBuf->BufSize = SizeOfStrConstant;
483 NewBuf->BufUsed = SizeOfStrConstant;
484 NewBuf->ConstBuf = 1;
493 * @ingroup StrBuf_DeConstructors
494 * @brief flush the content of a Buf; keep its struct
495 * @param buf Buffer to flush
497 int FlushStrBuf(StrBuf *buf)
509 * @ingroup StrBuf_DeConstructors
510 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
511 * @param buf Buffer to wipe
513 int FLUSHStrBuf(StrBuf *buf)
519 if (buf->BufUsed > 0) {
520 memset(buf->buf, 0, buf->BufUsed);
527 int hFreeDbglog = -1;
530 * @ingroup StrBuf_DeConstructors
531 * @brief Release a Buffer
532 * Its a double pointer, so it can NULL your pointer
533 * so fancy SIG11 appear instead of random results
534 * @param FreeMe Pointer Pointer to the buffer to free
536 void FreeStrBuf (StrBuf **FreeMe)
541 dbg_FreeStrBuf(FreeMe, 'F');
543 if (!(*FreeMe)->ConstBuf)
544 free((*FreeMe)->buf);
550 * @ingroup StrBuf_DeConstructors
551 * @brief flatten a Buffer to the Char * we return
552 * Its a double pointer, so it can NULL your pointer
553 * so fancy SIG11 appear instead of random results
554 * The Callee then owns the buffer and is responsible for freeing it.
555 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
556 * @returns the pointer of the buffer; Callee owns the memory thereafter.
558 char *SmashStrBuf (StrBuf **SmashMe)
562 if ((SmashMe == NULL) || (*SmashMe == NULL))
565 dbg_FreeStrBuf(SmashMe, 'S');
567 Ret = (*SmashMe)->buf;
574 * @ingroup StrBuf_DeConstructors
575 * @brief Release the buffer
576 * If you want put your StrBuf into a Hash, use this as Destructor.
577 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
579 void HFreeStrBuf (void *VFreeMe)
581 StrBuf *FreeMe = (StrBuf*)VFreeMe;
585 dbg_FreeStrBuf(SmashMe, 'H');
587 if (!FreeMe->ConstBuf)
593 /*******************************************************************************
594 * Simple string transformations *
595 *******************************************************************************/
599 * @brief Wrapper around atol
601 long StrTol(const StrBuf *Buf)
606 return atol(Buf->buf);
613 * @brief Wrapper around atoi
615 int StrToi(const StrBuf *Buf)
619 if (Buf->BufUsed > 0)
620 return atoi(Buf->buf);
627 * @brief Checks to see if the string is a pure number
628 * @param Buf The buffer to inspect
629 * @returns 1 if its a pure number, 0, if not.
631 int StrBufIsNumber(const StrBuf *Buf) {
633 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
636 strtoll(Buf->buf, &pEnd, 10);
637 if (pEnd == Buf->buf)
639 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
641 if (Buf->buf == pEnd)
647 * @ingroup StrBuf_Filler
648 * @brief modifies a Single char of the Buf
649 * You can point to it via char* or a zero-based integer
650 * @param Buf The buffer to manipulate
651 * @param ptr char* to zero; use NULL if unused
652 * @param nThChar zero based pointer into the string; use -1 if unused
653 * @param PeekValue The Character to place into the position
655 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
660 nThChar = ptr - Buf->buf;
661 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
663 Buf->buf[nThChar] = PeekValue;
668 * @ingroup StrBuf_Filler
669 * @brief modifies a range of chars of the Buf
670 * You can point to it via char* or a zero-based integer
671 * @param Buf The buffer to manipulate
672 * @param ptr char* to zero; use NULL if unused
673 * @param nThChar zero based pointer into the string; use -1 if unused
674 * @param nChars how many chars are to be flushed?
675 * @param PookValue The Character to place into that area
677 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
682 nThChar = ptr - Buf->buf;
683 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
685 if (nThChar + nChars > Buf->BufUsed)
686 nChars = Buf->BufUsed - nThChar;
688 memset(Buf->buf + nThChar, PookValue, nChars);
689 /* just to be shure... */
690 Buf->buf[Buf->BufUsed] = 0;
695 * @ingroup StrBuf_Filler
696 * @brief Append a StringBuffer to the buffer
697 * @param Buf Buffer to modify
698 * @param AppendBuf Buffer to copy at the end of our buffer
699 * @param Offset Should we start copying from an offset?
701 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
703 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
706 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
709 AppendBuf->BufUsed + Buf->BufUsed);
711 memcpy(Buf->buf + Buf->BufUsed,
712 AppendBuf->buf + Offset,
713 AppendBuf->BufUsed - Offset);
714 Buf->BufUsed += AppendBuf->BufUsed - Offset;
715 Buf->buf[Buf->BufUsed] = '\0';
720 * @ingroup StrBuf_Filler
721 * @brief Append a C-String to the buffer
722 * @param Buf Buffer to modify
723 * @param AppendBuf Buffer to copy at the end of our buffer
724 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
725 * @param Offset Should we start copying from an offset?
727 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
730 long BufSizeRequired;
732 if ((AppendBuf == NULL) || (Buf == NULL))
736 aps = strlen(AppendBuf + Offset);
738 aps = AppendSize - Offset;
740 BufSizeRequired = Buf->BufUsed + aps + 1;
741 if (Buf->BufSize <= BufSizeRequired)
742 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
744 memcpy(Buf->buf + Buf->BufUsed,
748 Buf->buf[Buf->BufUsed] = '\0';
752 * @ingroup StrBuf_Filler
753 * @brief sprintf like function appending the formated string to the buffer
754 * vsnprintf version to wrap into own calls
755 * @param Buf Buffer to extend by format and Params
756 * @param format printf alike format to add
757 * @param ap va_list containing the items for format
759 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
767 if ((Buf == NULL) || (format == NULL))
770 BufSize = Buf->BufSize;
771 nWritten = Buf->BufSize + 1;
772 Offset = Buf->BufUsed;
773 newused = Offset + nWritten;
775 while (newused >= BufSize) {
777 nWritten = vsnprintf(Buf->buf + Offset,
778 Buf->BufSize - Offset,
781 newused = Offset + nWritten;
782 if (newused >= Buf->BufSize) {
783 if (IncreaseBuf(Buf, 1, newused) == -1)
784 return; /* TODO: error handling? */
785 newused = Buf->BufSize + 1;
788 Buf->BufUsed = Offset + nWritten;
789 BufSize = Buf->BufSize;
796 * @ingroup StrBuf_Filler
797 * @brief sprintf like function appending the formated string to the buffer
798 * @param Buf Buffer to extend by format and Params
799 * @param format printf alike format to add
801 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
809 if ((Buf == NULL) || (format == NULL))
812 BufSize = Buf->BufSize;
813 nWritten = Buf->BufSize + 1;
814 Offset = Buf->BufUsed;
815 newused = Offset + nWritten;
817 while (newused >= BufSize) {
818 va_start(arg_ptr, format);
819 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
820 Buf->BufSize - Buf->BufUsed,
823 newused = Buf->BufUsed + nWritten;
824 if (newused >= Buf->BufSize) {
825 if (IncreaseBuf(Buf, 1, newused) == -1)
826 return; /* TODO: error handling? */
827 newused = Buf->BufSize + 1;
830 Buf->BufUsed += nWritten;
831 BufSize = Buf->BufSize;
838 * @ingroup StrBuf_Filler
839 * @brief sprintf like function putting the formated string into the buffer
840 * @param Buf Buffer to extend by format and Parameters
841 * @param format printf alike format to add
843 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
848 if ((Buf == NULL) || (format == NULL))
851 nWritten = Buf->BufSize + 1;
852 while (nWritten >= Buf->BufSize) {
853 va_start(arg_ptr, format);
854 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
856 if (nWritten >= Buf->BufSize) {
857 if (IncreaseBuf(Buf, 0, 0) == -1)
858 return; /* TODO: error handling? */
859 nWritten = Buf->BufSize + 1;
862 Buf->BufUsed = nWritten ;
867 * @ingroup StrBuf_Filler
868 * @brief Callback for cURL to append the webserver reply to a buffer
869 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
870 * @param size pre-defined by the cURL API; see man 3 curl for mre info
871 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
872 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
874 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
883 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
890 * @brief extracts a substring from Source into dest
891 * @param dest buffer to place substring into
892 * @param Source string to copy substring from
893 * @param Offset chars to skip from start
894 * @param nChars number of chars to copy
895 * @returns the number of chars copied; may be different from nChars due to the size of Source
897 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
900 if (Offset > Source->BufUsed)
906 if (Offset + nChars < Source->BufUsed)
908 if (nChars >= dest->BufSize)
909 IncreaseBuf(dest, 0, nChars + 1);
910 memcpy(dest->buf, Source->buf + Offset, nChars);
911 dest->BufUsed = nChars;
912 dest->buf[dest->BufUsed] = '\0';
915 NCharsRemain = Source->BufUsed - Offset;
916 if (NCharsRemain >= dest->BufSize)
917 IncreaseBuf(dest, 0, NCharsRemain + 1);
918 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
919 dest->BufUsed = NCharsRemain;
920 dest->buf[dest->BufUsed] = '\0';
926 * @brief Cut nChars from the start of the string
927 * @param Buf Buffer to modify
928 * @param nChars how many chars should be skipped?
930 void StrBufCutLeft(StrBuf *Buf, int nChars)
932 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
933 if (nChars >= Buf->BufUsed) {
937 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
938 Buf->BufUsed -= nChars;
939 Buf->buf[Buf->BufUsed] = '\0';
944 * @brief Cut the trailing n Chars from the string
945 * @param Buf Buffer to modify
946 * @param nChars how many chars should be trunkated?
948 void StrBufCutRight(StrBuf *Buf, int nChars)
950 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
951 if (nChars >= Buf->BufUsed) {
955 Buf->BufUsed -= nChars;
956 Buf->buf[Buf->BufUsed] = '\0';
961 * @brief Cut the string after n Chars
962 * @param Buf Buffer to modify
963 * @param AfternChars after how many chars should we trunkate the string?
964 * @param At if non-null and points inside of our string, cut it there.
966 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
968 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
970 AfternChars = At - Buf->buf;
973 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
975 Buf->BufUsed = AfternChars;
976 Buf->buf[Buf->BufUsed] = '\0';
982 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
983 * @param Buf the string to modify
985 void StrBufTrim(StrBuf *Buf)
988 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
990 while ((Buf->BufUsed > 0) &&
991 isspace(Buf->buf[Buf->BufUsed - 1]))
995 Buf->buf[Buf->BufUsed] = '\0';
997 if (Buf->BufUsed == 0) return;
999 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1002 if (delta > 0) StrBufCutLeft(Buf, delta);
1005 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
1013 pLeft = pBuff = Buf->buf;
1014 while (pBuff != NULL) {
1016 pBuff = strchr(pBuff, leftboundary);
1025 pRight = strchr(pBuff, rightboundary);
1027 StrBufCutAt(Buf, 0, pRight);
1029 StrBufCutLeft(Buf, pLeft - Buf->buf);
1034 * @ingroup StrBuf_Filler
1035 * @brief uppercase the contents of a buffer
1036 * @param Buf the buffer to translate
1038 void StrBufUpCase(StrBuf *Buf)
1042 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1045 pche = pch + Buf->BufUsed;
1046 while (pch < pche) {
1047 *pch = toupper(*pch);
1054 * @ingroup StrBuf_Filler
1055 * @brief lowercase the contents of a buffer
1056 * @param Buf the buffer to translate
1058 void StrBufLowerCase(StrBuf *Buf)
1062 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1065 pche = pch + Buf->BufUsed;
1066 while (pch < pche) {
1067 *pch = tolower(*pch);
1073 /*******************************************************************************
1074 * a tokenizer that kills, maims, and destroys *
1075 *******************************************************************************/
1078 * @ingroup StrBuf_Tokenizer
1079 * @brief Replace a token at a given place with a given length by another token with given length
1080 * @param Buf String where to work on
1081 * @param where where inside of the Buf is the search-token
1082 * @param HowLong How long is the token to be replaced
1083 * @param Repl Token to insert at 'where'
1084 * @param ReplLen Length of repl
1085 * @returns -1 if fail else length of resulting Buf
1087 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1088 const char *Repl, long ReplLen)
1091 if ((Buf == NULL) ||
1092 (where > Buf->BufUsed) ||
1093 (where + HowLong > Buf->BufUsed))
1096 if (where + ReplLen - HowLong > Buf->BufSize)
1097 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1100 memmove(Buf->buf + where + ReplLen,
1101 Buf->buf + where + HowLong,
1102 Buf->BufUsed - where - HowLong);
1104 memcpy(Buf->buf + where,
1107 Buf->BufUsed += ReplLen - HowLong;
1109 return Buf->BufUsed;
1113 * @ingroup StrBuf_Tokenizer
1114 * @brief Counts the numbmer of tokens in a buffer
1115 * @param source String to count tokens in
1116 * @param tok Tokenizer char to count
1117 * @returns numbers of tokenizer chars found
1119 int StrBufNum_tokens(const StrBuf *source, char tok)
1123 if ((source == NULL) || (source->BufUsed == 0))
1125 if ((source->BufUsed == 1) && (*source->buf == tok))
1129 pche = pch + source->BufUsed;
1140 * @ingroup StrBuf_Tokenizer
1141 * @brief a string tokenizer
1142 * @param Source StringBuffer to read into
1143 * @param parmnum n'th Parameter to remove
1144 * @param separator tokenizer character
1145 * @returns -1 if not found, else length of token.
1147 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1150 char *d, *s, *end; /* dest, source */
1153 /* Find desired @parameter */
1154 end = Source->buf + Source->BufUsed;
1156 while ((d <= end) &&
1159 /* End of string, bail! */
1164 if (*d == separator) {
1169 if ((d == NULL) || (d >= end))
1170 return 0; /* @Parameter not found */
1172 /* Find next @parameter */
1174 while ((s <= end) &&
1175 (*s && *s != separator))
1179 if (*s == separator)
1183 /* Hack and slash */
1188 memmove(d, s, Source->BufUsed - (s - Source->buf));
1189 Source->BufUsed += ReducedBy;
1190 Source->buf[Source->BufUsed] = '\0';
1192 else if (d == Source->buf) {
1194 Source->BufUsed = 0;
1198 Source->BufUsed += ReducedBy;
1211 * @ingroup StrBuf_Tokenizer
1212 * @brief a string tokenizer
1213 * @param dest Destination StringBuffer
1214 * @param Source StringBuffer to read into
1215 * @param parmnum n'th Parameter to extract
1216 * @param separator tokenizer character
1217 * @returns -1 if not found, else length of token.
1219 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1221 const char *s, *e; //* source * /
1222 int len = 0; //* running total length of extracted string * /
1223 int current_token = 0; //* token currently being processed * /
1226 dest->buf[0] = '\0';
1232 if ((Source == NULL) || (Source->BufUsed ==0)) {
1236 e = s + Source->BufUsed;
1239 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1241 while ((s < e) && !IsEmptyStr(s)) {
1242 if (*s == separator) {
1245 if (len >= dest->BufSize) {
1246 dest->BufUsed = len;
1247 if (IncreaseBuf(dest, 1, -1) < 0) {
1252 if ( (current_token == parmnum) &&
1253 (*s != separator)) {
1254 dest->buf[len] = *s;
1257 else if (current_token > parmnum) {
1263 dest->buf[len] = '\0';
1264 dest->BufUsed = len;
1266 if (current_token < parmnum) {
1267 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1270 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1279 * @ingroup StrBuf_Tokenizer
1280 * @brief a string tokenizer to fetch an integer
1281 * @param Source String containing tokens
1282 * @param parmnum n'th Parameter to extract
1283 * @param separator tokenizer character
1284 * @returns 0 if not found, else integer representation of the token
1286 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1296 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1303 * @ingroup StrBuf_Tokenizer
1304 * @brief a string tokenizer to fetch a long integer
1305 * @param Source String containing tokens
1306 * @param parmnum n'th Parameter to extract
1307 * @param separator tokenizer character
1308 * @returns 0 if not found, else long integer representation of the token
1310 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1320 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1328 * @ingroup StrBuf_Tokenizer
1329 * @brief a string tokenizer to fetch an unsigned long
1330 * @param Source String containing tokens
1331 * @param parmnum n'th Parameter to extract
1332 * @param separator tokenizer character
1333 * @returns 0 if not found, else unsigned long representation of the token
1335 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1346 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1350 return (unsigned long) atol(pnum);
1359 * @ingroup StrBuf_NextTokenizer
1360 * @brief a string tokenizer; Bounds checker
1361 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1362 * @param Source our tokenbuffer
1363 * @param pStart the token iterator pointer to inspect
1364 * @returns whether the revolving pointer is inside of the search range
1366 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1368 if ((Source == NULL) ||
1369 (*pStart == StrBufNOTNULL) ||
1370 (Source->BufUsed == 0))
1374 if (*pStart == NULL)
1378 else if (*pStart > Source->buf + Source->BufUsed)
1382 else if (*pStart <= Source->buf)
1391 * @ingroup StrBuf_NextTokenizer
1392 * @brief a string tokenizer
1393 * @param dest Destination StringBuffer
1394 * @param Source StringBuffer to read into
1395 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1396 * @param separator tokenizer
1397 * @returns -1 if not found, else length of token.
1399 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1401 const char *s; /* source */
1402 const char *EndBuffer; /* end stop of source buffer */
1403 int current_token = 0; /* token currently being processed */
1404 int len = 0; /* running total length of extracted string */
1406 if ((Source == NULL) ||
1407 (Source->BufUsed == 0) )
1409 *pStart = StrBufNOTNULL;
1413 EndBuffer = Source->buf + Source->BufUsed;
1417 dest->buf[0] = '\0';
1422 *pStart = EndBuffer + 1;
1426 if (*pStart == NULL)
1428 *pStart = Source->buf; /* we're starting to examine this buffer. */
1430 else if ((*pStart < Source->buf) ||
1431 (*pStart > EndBuffer ) )
1433 return -1; /* no more tokens to find. */
1437 /* start to find the next token */
1438 while ((s <= EndBuffer) &&
1439 (current_token == 0) )
1441 if (*s == separator)
1443 /* we found the next token */
1447 if (len >= dest->BufSize)
1449 /* our Dest-buffer isn't big enough, increase it. */
1450 dest->BufUsed = len;
1452 if (IncreaseBuf(dest, 1, -1) < 0) {
1453 /* WHUT? no more mem? bail out. */
1460 if ( (current_token == 0 ) && /* are we in our target token? */
1461 (!IsEmptyStr(s) ) &&
1462 (separator != *s) ) /* don't copy the token itself */
1464 dest->buf[len] = *s; /* Copy the payload */
1465 ++len; /* remember the bigger size. */
1471 /* did we reach the end? */
1472 if ((s > EndBuffer)) {
1473 EndBuffer = StrBufNOTNULL;
1474 *pStart = EndBuffer;
1477 *pStart = s; /* remember the position for the next run */
1480 /* sanitize our extracted token */
1481 dest->buf[len] = '\0';
1482 dest->BufUsed = len;
1489 * @ingroup StrBuf_NextTokenizer
1490 * @brief a string tokenizer
1491 * @param Source StringBuffer to read from
1492 * @param pStart pointer to the end of the last token. Feed with NULL.
1493 * @param separator tokenizer character
1494 * @param nTokens number of tokens to fastforward over
1495 * @returns -1 if not found, else length of token.
1497 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1499 const char *s, *EndBuffer; //* source * /
1500 int len = 0; //* running total length of extracted string * /
1501 int current_token = 0; //* token currently being processed * /
1503 if ((Source == NULL) ||
1504 (Source->BufUsed ==0)) {
1508 return Source->BufUsed;
1510 if (*pStart == NULL)
1511 *pStart = Source->buf;
1513 EndBuffer = Source->buf + Source->BufUsed;
1515 if ((*pStart < Source->buf) ||
1516 (*pStart > EndBuffer)) {
1524 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1526 while ((s < EndBuffer) && !IsEmptyStr(s)) {
1527 if (*s == separator) {
1530 if (current_token >= nTokens) {
1542 * @ingroup StrBuf_NextTokenizer
1543 * @brief a string tokenizer to fetch an integer
1544 * @param Source StringBuffer to read from
1545 * @param pStart Cursor on the tokenstring
1546 * @param separator tokenizer character
1547 * @returns 0 if not found, else integer representation of the token
1549 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1559 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1566 * @ingroup StrBuf_NextTokenizer
1567 * @brief a string tokenizer to fetch a long integer
1568 * @param Source StringBuffer to read from
1569 * @param pStart Cursor on the tokenstring
1570 * @param separator tokenizer character
1571 * @returns 0 if not found, else long integer representation of the token
1573 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1583 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1591 * @ingroup StrBuf_NextTokenizer
1592 * @brief a string tokenizer to fetch an unsigned long
1593 * @param Source StringBuffer to read from
1594 * @param pStart Cursor on the tokenstring
1595 * @param separator tokenizer character
1596 * @returns 0 if not found, else unsigned long representation of the token
1598 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1609 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1613 return (unsigned long) atol(pnum);
1623 /*******************************************************************************
1624 * Escape Appending *
1625 *******************************************************************************/
1628 * @ingroup StrBuf_DeEnCoder
1629 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1630 * @param OutBuf the output buffer
1631 * @param In Buffer to encode
1632 * @param PlainIn way in from plain old c strings
1634 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1636 const char *pch, *pche;
1640 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1642 if (PlainIn != NULL) {
1643 len = strlen(PlainIn);
1649 pche = pch + In->BufUsed;
1656 pt = OutBuf->buf + OutBuf->BufUsed;
1657 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1659 while (pch < pche) {
1661 IncreaseBuf(OutBuf, 1, -1);
1662 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1663 pt = OutBuf->buf + OutBuf->BufUsed;
1666 if((*pch >= 'a' && *pch <= 'z') ||
1667 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1668 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1669 (*pch == '!') || (*pch == '_') ||
1670 (*pch == ',') || (*pch == '.'))
1677 *(pt + 1) = HexList[(unsigned char)*pch][0];
1678 *(pt + 2) = HexList[(unsigned char)*pch][1];
1680 OutBuf->BufUsed += 3;
1688 * @ingroup StrBuf_DeEnCoder
1689 * @brief append a string in hex encoding to the buffer
1690 * @param OutBuf the output buffer
1691 * @param In Buffer to encode
1692 * @param PlainIn way in from plain old c strings
1694 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1696 const char *pch, *pche;
1700 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1702 if (PlainIn != NULL) {
1703 len = strlen(PlainIn);
1709 pche = pch + In->BufUsed;
1716 pt = OutBuf->buf + OutBuf->BufUsed;
1717 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1719 while (pch < pche) {
1721 IncreaseBuf(OutBuf, 1, -1);
1722 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1723 pt = OutBuf->buf + OutBuf->BufUsed;
1726 *pt = HexList[(unsigned char)*pch][0];
1728 *pt = HexList[(unsigned char)*pch][1];
1729 pt ++; pch ++; OutBuf->BufUsed += 2;
1735 * @ingroup StrBuf_DeEnCoder
1736 * @brief Append a string, escaping characters which have meaning in HTML.
1738 * @param Target target buffer
1739 * @param Source source buffer; set to NULL if you just have a C-String
1740 * @param PlainIn Plain-C string to append; set to NULL if unused
1741 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1742 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1743 * if set to 2, linebreaks are replaced by <br/>
1745 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1747 const char *aptr, *eiptr;
1751 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1754 if (PlainIn != NULL) {
1756 len = strlen(PlainIn);
1761 eiptr = aptr + Source->BufUsed;
1762 len = Source->BufUsed;
1768 bptr = Target->buf + Target->BufUsed;
1769 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1771 while (aptr < eiptr){
1773 IncreaseBuf(Target, 1, -1);
1774 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1775 bptr = Target->buf + Target->BufUsed;
1778 memcpy(bptr, "<", 4);
1780 Target->BufUsed += 4;
1782 else if (*aptr == '>') {
1783 memcpy(bptr, ">", 4);
1785 Target->BufUsed += 4;
1787 else if (*aptr == '&') {
1788 memcpy(bptr, "&", 5);
1790 Target->BufUsed += 5;
1792 else if (*aptr == '"') {
1793 memcpy(bptr, """, 6);
1795 Target->BufUsed += 6;
1797 else if (*aptr == '\'') {
1798 memcpy(bptr, "'", 5);
1800 Target->BufUsed += 5;
1802 else if (*aptr == LB) {
1807 else if (*aptr == RB) {
1812 else if (*aptr == QU) {
1817 else if ((*aptr == 32) && (nbsp == 1)) {
1818 memcpy(bptr, " ", 6);
1820 Target->BufUsed += 6;
1822 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1823 *bptr='\0'; /* nothing */
1825 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1826 memcpy(bptr, "<br/>", 11);
1828 Target->BufUsed += 11;
1832 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1833 *bptr='\0'; /* nothing */
1843 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1845 return Target->BufUsed;
1849 * @ingroup StrBuf_DeEnCoder
1850 * @brief Append a string, escaping characters which have meaning in HTML.
1851 * Converts linebreaks into blanks; escapes single quotes
1852 * @param Target target buffer
1853 * @param Source source buffer; set to NULL if you just have a C-String
1854 * @param PlainIn Plain-C string to append; set to NULL if unused
1856 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1858 const char *aptr, *eiptr;
1862 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1865 if (PlainIn != NULL) {
1867 len = strlen(PlainIn);
1872 eiptr = aptr + Source->BufUsed;
1873 len = Source->BufUsed;
1879 eptr = Target->buf + Target->BufSize - 8;
1880 tptr = Target->buf + Target->BufUsed;
1882 while (aptr < eiptr){
1884 IncreaseBuf(Target, 1, -1);
1885 eptr = Target->buf + Target->BufSize - 8;
1886 tptr = Target->buf + Target->BufUsed;
1889 if (*aptr == '\n') {
1893 else if (*aptr == '\r') {
1897 else if (*aptr == '\'') {
1903 Target->BufUsed += 5;
1916 * @ingroup StrBuf_DeEnCoder
1917 * @brief Append a string, escaping characters which have meaning in ICAL.
1919 * @param Target target buffer
1920 * @param Source source buffer; set to NULL if you just have a C-String
1921 * @param PlainIn Plain-C string to append; set to NULL if unused
1923 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1925 const char *aptr, *eiptr;
1929 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1932 if (PlainIn != NULL) {
1934 len = strlen(PlainIn);
1939 eiptr = aptr + Source->BufUsed;
1940 len = Source->BufUsed;
1946 eptr = Target->buf + Target->BufSize - 8;
1947 tptr = Target->buf + Target->BufUsed;
1949 while (aptr < eiptr){
1950 if(tptr + 3 >= eptr) {
1951 IncreaseBuf(Target, 1, -1);
1952 eptr = Target->buf + Target->BufSize - 8;
1953 tptr = Target->buf + Target->BufUsed;
1956 if (*aptr == '\n') {
1963 else if (*aptr == '\r') {
1970 else if (*aptr == ',') {
1986 * @ingroup StrBuf_DeEnCoder
1987 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1989 * @param Target target buffer
1990 * @param Source source buffer; set to NULL if you just have a C-String
1991 * @param PlainIn Plain-C string to append; set to NULL if unused
1992 * @returns size of result or -1
1994 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1996 const char *aptr, *eiptr;
2000 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2003 if (PlainIn != NULL) {
2005 len = strlen(PlainIn);
2010 eiptr = aptr + Source->BufUsed;
2011 len = Source->BufUsed;
2017 bptr = Target->buf + Target->BufUsed;
2018 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2020 while (aptr < eiptr){
2022 IncreaseBuf(Target, 1, -1);
2023 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2024 bptr = Target->buf + Target->BufUsed;
2028 memcpy(bptr, HKEY("\\n"));
2030 Target->BufUsed += 2;
2033 memcpy(bptr, HKEY("\\r"));
2035 Target->BufUsed += 2;
2042 Target->BufUsed += 2;
2045 if ((*(aptr + 1) == 'u') &&
2046 isxdigit(*(aptr + 2)) &&
2047 isxdigit(*(aptr + 3)) &&
2048 isxdigit(*(aptr + 4)) &&
2049 isxdigit(*(aptr + 5)))
2050 { /* oh, a unicode escaper. let it pass through. */
2051 memcpy(bptr, aptr, 6);
2054 Target->BufUsed += 6;
2062 Target->BufUsed += 2;
2070 Target->BufUsed += 2;
2077 Target->BufUsed += 2;
2084 Target->BufUsed += 2;
2087 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2088 while (IsUtf8Sequence > 0){
2091 if (--IsUtf8Sequence)
2099 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2101 return Target->BufUsed;
2105 * @ingroup StrBuf_DeEnCoder
2106 * @brief Append a string, escaping characters which have meaning in HTML + json.
2108 * @param Target target buffer
2109 * @param Source source buffer; set to NULL if you just have a C-String
2110 * @param PlainIn Plain-C string to append; set to NULL if unused
2111 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2112 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2113 * if set to 2, linebreaks are replaced by <br/>
2115 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2117 const char *aptr, *eiptr;
2120 int IsUtf8Sequence = 0;
2122 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2125 if (PlainIn != NULL) {
2127 len = strlen(PlainIn);
2132 eiptr = aptr + Source->BufUsed;
2133 len = Source->BufUsed;
2139 bptr = Target->buf + Target->BufUsed;
2140 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2142 while (aptr < eiptr){
2144 IncreaseBuf(Target, 1, -1);
2145 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2146 bptr = Target->buf + Target->BufUsed;
2150 memcpy(bptr, HKEY("<"));
2152 Target->BufUsed += 4;
2155 memcpy(bptr, HKEY(">"));
2157 Target->BufUsed += 4;
2160 memcpy(bptr, HKEY("&"));
2162 Target->BufUsed += 5;
2175 switch (nolinebreaks) {
2177 *bptr='\0'; /* nothing */
2180 memcpy(bptr, HKEY("<br/>"));
2182 Target->BufUsed += 11;
2185 memcpy(bptr, HKEY("\\n"));
2187 Target->BufUsed += 2;
2191 switch (nolinebreaks) {
2194 *bptr='\0'; /* nothing */
2197 memcpy(bptr, HKEY("\\r"));
2199 Target->BufUsed += 2;
2209 Target->BufUsed += 2;
2212 if ((*(aptr + 1) == 'u') &&
2213 isxdigit(*(aptr + 2)) &&
2214 isxdigit(*(aptr + 3)) &&
2215 isxdigit(*(aptr + 4)) &&
2216 isxdigit(*(aptr + 5)))
2217 { /* oh, a unicode escaper. let it pass through. */
2218 memcpy(bptr, aptr, 6);
2221 Target->BufUsed += 6;
2229 Target->BufUsed += 2;
2237 Target->BufUsed += 2;
2244 Target->BufUsed += 2;
2251 Target->BufUsed += 2;
2255 memcpy(bptr, HKEY(" "));
2257 Target->BufUsed += 6;
2261 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2262 while (IsUtf8Sequence > 0){
2265 if (--IsUtf8Sequence)
2273 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2275 return Target->BufUsed;
2279 * @ingroup StrBuf_DeEnCoder
2280 * @brief unhide special chars hidden to the HTML escaper
2281 * @param target buffer to put the unescaped string in
2282 * @param source buffer to unescape
2284 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2290 FlushStrBuf(target);
2292 if (source == NULL ||target == NULL)
2297 len = source->BufUsed;
2298 for (a = 0; a < len; ++a) {
2299 if (target->BufUsed >= target->BufSize)
2300 IncreaseBuf(target, 1, -1);
2302 if (source->buf[a] == '=') {
2303 hex[0] = source->buf[a + 1];
2304 hex[1] = source->buf[a + 2];
2307 sscanf(hex, "%02x", &b);
2308 target->buf[target->BufUsed] = b;
2309 target->buf[++target->BufUsed] = 0;
2313 target->buf[target->BufUsed] = source->buf[a];
2314 target->buf[++target->BufUsed] = 0;
2321 * @ingroup StrBuf_DeEnCoder
2322 * @brief hide special chars from the HTML escapers and friends
2323 * @param target buffer to put the escaped string in
2324 * @param source buffer to escape
2326 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2331 FlushStrBuf(target);
2333 if (source == NULL ||target == NULL)
2338 len = source->BufUsed;
2339 for (i=0; i<len; ++i) {
2340 if (target->BufUsed + 4 >= target->BufSize)
2341 IncreaseBuf(target, 1, -1);
2342 if ( (isalnum(source->buf[i])) ||
2343 (source->buf[i]=='-') ||
2344 (source->buf[i]=='_') ) {
2345 target->buf[target->BufUsed++] = source->buf[i];
2348 sprintf(&target->buf[target->BufUsed],
2350 (0xFF &source->buf[i]));
2351 target->BufUsed += 3;
2354 target->buf[target->BufUsed + 1] = '\0';
2358 /*******************************************************************************
2359 * Quoted Printable de/encoding *
2360 *******************************************************************************/
2363 * @ingroup StrBuf_DeEnCoder
2364 * @brief decode a buffer from base 64 encoding; destroys original
2365 * @param Buf Buffor to transform
2367 int StrBufDecodeBase64(StrBuf *Buf)
2371 if (Buf == NULL) return -1;
2373 xferbuf = (char*) malloc(Buf->BufSize);
2375 siz = CtdlDecodeBase64(xferbuf,
2385 * @ingroup StrBuf_DeEnCoder
2386 * @brief decode a buffer from base 64 encoding; destroys original
2387 * @param Buf Buffor to transform
2389 int StrBufDecodeHex(StrBuf *Buf)
2392 char *pch, *pche, *pchi;
2394 if (Buf == NULL) return -1;
2396 pch = pchi = Buf->buf;
2397 pche = pch + Buf->BufUsed;
2399 while (pchi < pche){
2400 ch = decode_hex(pchi);
2407 Buf->BufUsed = pch - Buf->buf;
2408 return Buf->BufUsed;
2412 * @ingroup StrBuf_DeEnCoder
2413 * @brief replace all chars >0x20 && < 0x7F with Mute
2414 * @param Mute char to put over invalid chars
2415 * @param Buf Buffor to transform
2417 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2421 if (Buf == NULL) return -1;
2422 pch = (unsigned char *)Buf->buf;
2423 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2424 if ((*pch < 0x20) || (*pch > 0x7F))
2428 return Buf->BufUsed;
2433 * @ingroup StrBuf_DeEnCoder
2434 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2435 * @param Buf Buffer to translate
2436 * @param StripBlanks Reduce several blanks to one?
2438 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2447 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2448 Buf->buf[Buf->BufUsed - 1] = '\0';
2453 while (a < Buf->BufUsed) {
2454 if (Buf->buf[a] == '+')
2456 else if (Buf->buf[a] == '%') {
2457 /* don't let % chars through, rather truncate the input. */
2458 if (a + 2 > Buf->BufUsed) {
2463 hex[0] = Buf->buf[a + 1];
2464 hex[1] = Buf->buf[a + 2];
2467 sscanf(hex, "%02x", &b);
2468 Buf->buf[a] = (char) b;
2469 len = Buf->BufUsed - a - 2;
2471 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2483 * @ingroup StrBuf_DeEnCoder
2484 * @brief RFC2047-encode a header field if necessary.
2485 * If no non-ASCII characters are found, the string
2486 * will be copied verbatim without encoding.
2488 * @param target Target buffer.
2489 * @param source Source string to be encoded.
2490 * @returns encoded length; -1 if non success.
2492 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2494 const char headerStr[] = "=?UTF-8?Q?";
2495 int need_to_encode = 0;
2499 if ((source == NULL) ||
2503 while ((i < source->BufUsed) &&
2504 (!IsEmptyStr (&source->buf[i])) &&
2505 (need_to_encode == 0)) {
2506 if (((unsigned char) source->buf[i] < 32) ||
2507 ((unsigned char) source->buf[i] > 126)) {
2513 if (!need_to_encode) {
2514 if (*target == NULL) {
2515 *target = NewStrBufPlain(source->buf, source->BufUsed);
2518 FlushStrBuf(*target);
2519 StrBufAppendBuf(*target, source, 0);
2521 return (*target)->BufUsed;
2523 if (*target == NULL)
2524 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2525 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2526 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2527 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2528 (*target)->BufUsed = sizeof(headerStr) - 1;
2529 for (i=0; (i < source->BufUsed); ++i) {
2530 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2531 IncreaseBuf(*target, 1, 0);
2532 ch = (unsigned char) source->buf[i];
2542 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2543 (*target)->BufUsed += 3;
2547 (*target)->buf[(*target)->BufUsed] = '_';
2549 (*target)->buf[(*target)->BufUsed] = ch;
2550 (*target)->BufUsed++;
2554 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2555 IncreaseBuf(*target, 1, 0);
2557 (*target)->buf[(*target)->BufUsed++] = '?';
2558 (*target)->buf[(*target)->BufUsed++] = '=';
2559 (*target)->buf[(*target)->BufUsed] = '\0';
2560 return (*target)->BufUsed;;
2565 static void AddRecipient(StrBuf *Target,
2567 StrBuf *EmailAddress,
2572 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2573 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2575 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
2576 StrBufRFC2047encode(&EncBuf, UserName);
2577 StrBufAppendBuf(Target, EncBuf, 0);
2578 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2579 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
2581 if (StrLength(EmailAddress) > 0){
2582 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2583 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2584 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2590 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2591 * \param Recp Source list of email recipients
2592 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2593 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2594 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2595 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2597 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp,
2599 StrBuf *EmailAddress,
2605 const char *pch, *pche;
2606 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2608 if ((Recp == NULL) || (StrLength(Recp) == 0))
2613 pche = pch + StrLength(Recp);
2615 if (!CheckEncode(pch, -1, pche))
2616 return NewStrBufDup(Recp);
2618 Target = NewStrBufPlain(NULL, StrLength(Recp));
2620 while ((pch != NULL) && (pch < pche))
2624 while (isspace(*pch)) pch++;
2625 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2627 if ((*pch == '"') || (*pch == '\'')) {
2628 UserStart = pch + 1;
2630 UserEnd = strchr(UserStart, *pch);
2631 if (UserEnd == NULL)
2632 break; ///TODO: Userfeedback??
2633 EmailStart = UserEnd + 1;
2634 while (isspace(*EmailStart))
2636 if (UserEnd == UserStart) {
2637 UserStart = UserEnd = NULL;
2640 if (*EmailStart == '<') {
2642 EmailEnd = strchr(EmailStart, '>');
2643 if (EmailEnd == NULL)
2644 EmailEnd = strchr(EmailStart, ',');
2648 EmailEnd = strchr(EmailStart, ',');
2650 if (EmailEnd == NULL)
2658 EmailEnd = strchr(UserStart, ',');
2659 if (EmailEnd == NULL) {
2660 EmailEnd = strchr(pch, '>');
2662 if (EmailEnd != NULL) {
2672 while ((EmailEnd > UserStart) && !gt &&
2673 ((*EmailEnd == ',') ||
2674 (*EmailEnd == '>') ||
2675 (isspace(*EmailEnd))))
2677 if (*EmailEnd == '>')
2682 if (EmailEnd == UserStart)
2686 EmailStart = strchr(UserStart, '<');
2687 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2689 UserEnd = EmailStart;
2691 while ((UserEnd > UserStart) &&
2692 isspace (*(UserEnd - 1)))
2695 if (UserStart >= UserEnd)
2696 UserStart = UserEnd = NULL;
2697 At = strchr(EmailStart, '@');
2699 else { /* this is a local recipient... no domain, just a realname */
2700 EmailStart = UserStart;
2701 At = strchr(EmailStart, '@');
2707 EmailStart = UserStart;
2713 if ((UserStart != NULL) && (UserEnd != NULL))
2714 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2715 else if ((UserStart != NULL) && (UserEnd == NULL))
2716 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2718 FlushStrBuf(UserName);
2720 if ((EmailStart != NULL) && (EmailEnd != NULL))
2721 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2722 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2723 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2725 FlushStrBuf(EmailAddress);
2727 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2732 if ((pch != NULL) && (*pch == ','))
2734 if (pch != NULL) while (isspace(*pch))
2743 * @brief replaces all occurances of 'search' by 'replace'
2744 * @param buf Buffer to modify
2745 * @param search character to search
2746 * @param replace character to replace search by
2748 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2753 for (i=0; i<buf->BufUsed; i++)
2754 if (buf->buf[i] == search)
2755 buf->buf[i] = replace;
2761 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2762 * @param buf Buffer to modify
2764 void StrBufToUnixLF(StrBuf *buf)
2766 char *pche, *pchS, *pchT;
2770 pche = buf->buf + buf->BufUsed;
2771 pchS = pchT = buf->buf;
2777 if (*pchS != '\n') {
2786 buf->BufUsed = pchT - buf->buf;
2790 /*******************************************************************************
2791 * Iconv Wrapper; RFC822 de/encoding *
2792 *******************************************************************************/
2795 * @ingroup StrBuf_DeEnCoder
2796 * @brief Wrapper around iconv_open()
2797 * Our version adds aliases for non-standard Microsoft charsets
2798 * such as 'MS950', aliasing them to names like 'CP950'
2800 * @param tocode Target encoding
2801 * @param fromcode Source encoding
2802 * @param pic anonimized pointer to iconv struct
2804 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2807 iconv_t ic = (iconv_t)(-1) ;
2808 ic = iconv_open(tocode, fromcode);
2809 if (ic == (iconv_t)(-1) ) {
2810 char alias_fromcode[64];
2811 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2812 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2813 alias_fromcode[0] = 'C';
2814 alias_fromcode[1] = 'P';
2815 ic = iconv_open(tocode, alias_fromcode);
2818 *(iconv_t *)pic = ic;
2824 * @ingroup StrBuf_DeEnCoder
2825 * @brief find one chunk of a RFC822 encoded string
2826 * @param Buffer where to search
2827 * @param bptr where to start searching
2828 * @returns found position, NULL if none.
2830 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2833 /* Find the next ?Q? */
2834 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2837 end = strchr(bptr + 2, '?');
2842 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2843 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2844 (*(end + 2) == '?')) {
2845 /* skip on to the end of the cluster, the next ?= */
2846 end = strstr(end + 3, "?=");
2849 /* sort of half valid encoding, try to find an end. */
2850 end = strstr(bptr, "?=");
2856 * @brief swaps the contents of two StrBufs
2857 * this is to be used to have cheap switched between a work-buffer and a target buffer
2858 * @param A First one
2859 * @param B second one
2861 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2865 memcpy(&C, A, sizeof(*A));
2866 memcpy(A, B, sizeof(*B));
2867 memcpy(B, &C, sizeof(C));
2873 * @ingroup StrBuf_DeEnCoder
2874 * @brief convert one buffer according to the preselected iconv pointer PIC
2875 * @param ConvertBuf buffer we need to translate
2876 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2877 * @param pic Pointer to the iconv-session Object
2879 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2885 char *ibuf; /**< Buffer of characters to be converted */
2886 char *obuf; /**< Buffer for converted characters */
2887 size_t ibuflen; /**< Length of input buffer */
2888 size_t obuflen; /**< Length of output buffer */
2891 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2892 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2893 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2895 ic = *(iconv_t*)pic;
2896 ibuf = ConvertBuf->buf;
2897 ibuflen = ConvertBuf->BufUsed;
2899 obuflen = TmpBuf->BufSize;
2901 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2904 if (errno == E2BIG) {
2906 IncreaseBuf(TmpBuf, 0, 0);
2911 else if (errno == EILSEQ){
2912 /* hm, invalid utf8 sequence... what to do now? */
2913 /* An invalid multibyte sequence has been encountered in the input */
2915 else if (errno == EINVAL) {
2916 /* An incomplete multibyte sequence has been encountered in the input. */
2919 FlushStrBuf(TmpBuf);
2922 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2923 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2925 /* little card game: wheres the red lady? */
2926 SwapBuffers(ConvertBuf, TmpBuf);
2927 FlushStrBuf(TmpBuf);
2934 * @ingroup StrBuf_DeEnCoder
2935 * @brief catches one RFC822 encoded segment, and decodes it.
2936 * @param Target buffer to fill with result
2937 * @param DecodeMe buffer with stuff to process
2938 * @param SegmentStart points to our current segment in DecodeMe
2939 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2940 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2941 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2942 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2944 inline static void DecodeSegment(StrBuf *Target,
2945 const StrBuf *DecodeMe,
2946 const char *SegmentStart,
2947 const char *SegmentEnd,
2949 StrBuf *ConvertBuf2,
2950 StrBuf *FoundCharset)
2956 iconv_t ic = (iconv_t)(-1);
2960 /* Now we handle foreign character sets properly encoded
2961 * in RFC2047 format.
2963 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2964 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2965 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2966 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2967 if (FoundCharset != NULL) {
2968 FlushStrBuf(FoundCharset);
2969 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2971 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2972 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2974 *encoding = toupper(*encoding);
2975 if (*encoding == 'B') { /**< base64 */
2976 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2977 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2978 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2980 ConvertBuf->BufUsed);
2982 else if (*encoding == 'Q') { /**< quoted-printable */
2986 while (pos < ConvertBuf->BufUsed)
2988 if (ConvertBuf->buf[pos] == '_')
2989 ConvertBuf->buf[pos] = ' ';
2993 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2994 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2996 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2999 ConvertBuf->BufUsed);
3002 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3005 ctdl_iconv_open("UTF-8", charset, &ic);
3006 if (ic != (iconv_t)(-1) ) {
3008 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3009 StrBufAppendBuf(Target, ConvertBuf2, 0);
3014 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3020 * @ingroup StrBuf_DeEnCoder
3021 * @brief Handle subjects with RFC2047 encoding such as:
3022 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3023 * @param Target where to put the decoded string to
3024 * @param DecodeMe buffer with encoded string
3025 * @param DefaultCharset if we don't find one, which should we use?
3026 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3027 * put it here for later use where no string might be known.
3029 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3031 StrBuf *DecodedInvalidBuf = NULL;
3032 StrBuf *ConvertBuf, *ConvertBuf2;
3033 const StrBuf *DecodeMee = DecodeMe;
3034 const char *start, *end, *next, *nextend, *ptr = NULL;
3036 iconv_t ic = (iconv_t)(-1) ;
3041 int illegal_non_rfc2047_encoding = 0;
3043 /* Sometimes, badly formed messages contain strings which were simply
3044 * written out directly in some foreign character set instead of
3045 * using RFC2047 encoding. This is illegal but we will attempt to
3046 * handle it anyway by converting from a user-specified default
3047 * charset to UTF-8 if we see any nonprintable characters.
3050 len = StrLength(DecodeMe);
3051 for (i=0; i<DecodeMe->BufUsed; ++i) {
3052 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3053 illegal_non_rfc2047_encoding = 1;
3058 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3059 if ((illegal_non_rfc2047_encoding) &&
3060 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3061 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3064 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3065 if (ic != (iconv_t)(-1) ) {
3066 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3067 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3068 DecodeMee = DecodedInvalidBuf;
3074 /* pre evaluate the first pair */
3075 nextend = end = NULL;
3076 len = StrLength(DecodeMee);
3077 start = strstr(DecodeMee->buf, "=?");
3078 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3080 end = FindNextEnd (DecodeMee, start);
3082 StrBufAppendBuf(Target, DecodeMee, 0);
3083 FreeStrBuf(&ConvertBuf);
3084 FreeStrBuf(&DecodedInvalidBuf);
3088 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3090 if (start != DecodeMee->buf) {
3093 nFront = start - DecodeMee->buf;
3094 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3098 * Since spammers will go to all sorts of absurd lengths to get their
3099 * messages through, there are LOTS of corrupt headers out there.
3100 * So, prevent a really badly formed RFC2047 header from throwing
3101 * this function into an infinite loop.
3103 while ((start != NULL) &&
3110 DecodeSegment(Target,
3118 next = strstr(end, "=?");
3120 if ((next != NULL) &&
3122 nextend = FindNextEnd(DecodeMee, next);
3123 if (nextend == NULL)
3126 /* did we find two partitions */
3127 if ((next != NULL) &&
3131 while ((ptr < next) &&
3138 * did we find a gab just filled with blanks?
3139 * if not, copy its stuff over.
3143 StrBufAppendBufPlain(Target,
3149 /* our next-pair is our new first pair now. */
3155 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3156 if ((end != NULL) && (end < nextend)) {
3158 while ( (ptr < nextend) &&
3165 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3167 FreeStrBuf(&ConvertBuf);
3168 FreeStrBuf(&ConvertBuf2);
3169 FreeStrBuf(&DecodedInvalidBuf);
3172 /*******************************************************************************
3173 * Manipulating UTF-8 Strings *
3174 *******************************************************************************/
3178 * @brief evaluate the length of an utf8 special character sequence
3179 * @param Char the character to examine
3180 * @returns width of utf8 chars in bytes; if the sequence is broken 0 is returned; 1 if its simply ASCII.
3182 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3185 unsigned char test = (1<<7);
3187 if ((*CharS & 0xC0) != 0xC0)
3191 ((test & ((unsigned char)*CharS)) != 0))
3196 if ((n > 6) || ((CharE - CharS) < n))
3203 * @brief detect whether this char starts an utf-8 encoded char
3204 * @param Char character to inspect
3205 * @returns yes or no
3207 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3209 /** 11??.???? indicates an UTF8 Sequence. */
3210 return ((Char & 0xC0) == 0xC0);
3215 * @brief measure the number of glyphs in an UTF8 string...
3216 * @param Buf string to measure
3217 * @returns the number of glyphs in Buf
3219 long StrBuf_Utf8StrLen(StrBuf *Buf)
3225 if ((Buf == NULL) || (Buf->BufUsed == 0))
3228 eptr = Buf->buf + Buf->BufUsed;
3229 while ((aptr < eptr) && (*aptr != '\0')) {
3230 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3231 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3232 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3245 * @brief cuts a string after maxlen glyphs
3246 * @param Buf string to cut to maxlen glyphs
3247 * @param maxlen how long may the string become?
3248 * @returns current length of the string
3250 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3256 eptr = Buf->buf + Buf->BufUsed;
3257 while ((aptr < eptr) && (*aptr != '\0')) {
3258 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3259 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3260 while ((*aptr++ != '\0') && (m-- > 0));
3269 Buf->BufUsed = aptr - Buf->buf;
3270 return Buf->BufUsed;
3273 return Buf->BufUsed;
3281 /*******************************************************************************
3283 *******************************************************************************/
3286 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3287 #define OS_CODE 0x03 /*< unix */
3290 * @ingroup StrBuf_DeEnCoder
3291 * @brief uses the same calling syntax as compress2(), but it
3292 * creates a stream compatible with HTTP "Content-encoding: gzip"
3293 * @param dest compressed buffer
3294 * @param destLen length of the compresed data
3295 * @param source source to encode
3296 * @param sourceLen length of source to encode
3297 * @param level compression level
3299 int ZEXPORT compress_gzip(Bytef * dest,
3301 const Bytef * source,
3305 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3307 /* write gzip header */
3308 snprintf((char *) dest, *destLen,
3309 "%c%c%c%c%c%c%c%c%c%c",
3310 gz_magic[0], gz_magic[1], Z_DEFLATED,
3311 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3314 /* normal deflate */
3317 stream.next_in = (Bytef *) source;
3318 stream.avail_in = (uInt) sourceLen;
3319 stream.next_out = dest + 10L; // after header
3320 stream.avail_out = (uInt) * destLen;
3321 if ((uLong) stream.avail_out != *destLen)
3324 stream.zalloc = (alloc_func) 0;
3325 stream.zfree = (free_func) 0;
3326 stream.opaque = (voidpf) 0;
3328 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3329 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3333 err = deflate(&stream, Z_FINISH);
3334 if (err != Z_STREAM_END) {
3335 deflateEnd(&stream);
3336 return err == Z_OK ? Z_BUF_ERROR : err;
3338 *destLen = stream.total_out + 10L;
3340 /* write CRC and Length */
3341 uLong crc = crc32(0L, source, sourceLen);
3343 for (n = 0; n < 4; ++n, ++*destLen) {
3344 dest[*destLen] = (int) (crc & 0xff);
3347 uLong len = stream.total_in;
3348 for (n = 0; n < 4; ++n, ++*destLen) {
3349 dest[*destLen] = (int) (len & 0xff);
3352 err = deflateEnd(&stream);
3359 * @ingroup StrBuf_DeEnCoder
3360 * @brief compress the buffer with gzip
3361 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3362 * @param Buf buffer whose content is to be gzipped
3364 int CompressBuffer(StrBuf *Buf)
3367 char *compressed_data = NULL;
3368 size_t compressed_len, bufsize;
3371 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3372 compressed_data = malloc(compressed_len);
3374 if (compressed_data == NULL)
3376 /* Flush some space after the used payload so valgrind shuts up... */
3377 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3378 Buf->buf[Buf->BufUsed + i++] = '\0';
3379 if (compress_gzip((Bytef *) compressed_data,
3382 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3385 Buf->buf = compressed_data;
3386 Buf->BufUsed = compressed_len;
3387 Buf->BufSize = bufsize;
3388 /* Flush some space after the used payload so valgrind shuts up... */
3390 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3391 Buf->buf[Buf->BufUsed + i++] = '\0';
3394 free(compressed_data);
3396 #endif /* HAVE_ZLIB */
3402 /*******************************************************************************
3403 * File I/O; Prefer buffered read since its faster! *
3404 *******************************************************************************/
3407 * @ingroup StrBuf_IO
3408 * @brief Read a line from socket
3409 * flushes and closes the FD on error
3410 * @param buf the buffer to get the input to
3411 * @param fd pointer to the filedescriptor to read
3412 * @param append Append to an existing string or replace?
3413 * @param Error strerror() on error
3414 * @returns numbers of chars read
3416 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3418 int len, rlen, slen;
3423 slen = len = buf->BufUsed;
3425 rlen = read(*fd, &buf->buf[len], 1);
3427 *Error = strerror(errno);
3434 if (buf->buf[len] == '\n')
3436 if (buf->buf[len] != '\r')
3438 if (len + 2 >= buf->BufSize) {
3440 buf->buf[len+1] = '\0';
3441 IncreaseBuf(buf, 1, -1);
3445 buf->buf[len] = '\0';
3450 * @ingroup StrBuf_BufferedIO
3451 * @brief Read a line from socket
3452 * flushes and closes the FD on error
3453 * @param Line the line to read from the fd / I/O Buffer
3454 * @param buf the buffer to get the input to
3455 * @param fd pointer to the filedescriptor to read
3456 * @param timeout number of successless selects until we bail out
3457 * @param selectresolution how long to wait on each select
3458 * @param Error strerror() on error
3459 * @returns numbers of chars read
3461 int StrBufTCP_read_buffered_line(StrBuf *Line,
3465 int selectresolution,
3469 int nSuccessLess = 0;
3476 if (buf->BufUsed > 0) {
3477 pch = strchr(buf->buf, '\n');
3480 len = pch - buf->buf;
3481 if (len > 0 && (*(pch - 1) == '\r') )
3483 StrBufSub(Line, buf, 0, len - rlen);
3484 StrBufCutLeft(buf, len + 1);
3489 if (buf->BufSize - buf->BufUsed < 10)
3490 IncreaseBuf(buf, 1, -1);
3492 fdflags = fcntl(*fd, F_GETFL);
3493 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3495 while ((nSuccessLess < timeout) && (pch == NULL)) {
3497 tv.tv_sec = selectresolution;
3502 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3503 *Error = strerror(errno);
3509 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3514 &buf->buf[buf->BufUsed],
3515 buf->BufSize - buf->BufUsed - 1);
3517 *Error = strerror(errno);
3522 else if (rlen > 0) {
3524 buf->BufUsed += rlen;
3525 buf->buf[buf->BufUsed] = '\0';
3526 if (buf->BufUsed + 10 > buf->BufSize) {
3527 IncreaseBuf(buf, 1, -1);
3529 pch = strchr(buf->buf, '\n');
3536 len = pch - buf->buf;
3537 if (len > 0 && (*(pch - 1) == '\r') )
3539 StrBufSub(Line, buf, 0, len - rlen);
3540 StrBufCutLeft(buf, len + 1);
3547 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3548 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3549 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3551 * @ingroup StrBuf_BufferedIO
3552 * @brief Read a line from socket
3553 * flushes and closes the FD on error
3554 * @param Line where to append our Line read from the fd / I/O Buffer;
3555 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3556 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3557 * @param fd pointer to the filedescriptor to read
3558 * @param timeout number of successless selects until we bail out
3559 * @param selectresolution how long to wait on each select
3560 * @param Error strerror() on error
3561 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3563 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3568 int selectresolution,
3571 const char *pche = NULL;
3572 const char *pos = NULL;
3574 int len, rlen, retlen;
3575 int nSuccessLess = 0;
3577 const char *pch = NULL;
3583 if ((Line == NULL) ||
3590 *Error = ErrRBLF_PreConditionFailed;
3595 if ((IOBuf->BufUsed > 0) &&
3597 (pos < IOBuf->buf + IOBuf->BufUsed))
3601 pche = IOBuf->buf + IOBuf->BufUsed;
3605 while ((pch < pche) && (*pch != '\n'))
3607 if (Line->BufUsed + 10 > Line->BufSize)
3610 apos = pcht - Line->buf;
3612 IncreaseBuf(Line, 1, -1);
3613 pcht = Line->buf + apos;
3621 if (len > 0 && (*(pch - 1) == '\r') )
3630 if ((pch >= pche) || (*pch == '\0'))
3638 if ((pch != NULL) &&
3641 if (pch + 1 >= pche) {
3654 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3656 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3657 IncreaseBuf(IOBuf, 1, -1);
3659 fdflags = fcntl(*fd, F_GETFL);
3660 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3663 while ((nSuccessLess < timeout) &&
3673 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3674 *Error = strerror(errno);
3678 *Error = ErrRBLF_SelectFailed;
3681 if (! FD_ISSET(*fd, &rfds) != 0) {
3687 &IOBuf->buf[IOBuf->BufUsed],
3688 IOBuf->BufSize - IOBuf->BufUsed - 1);
3690 *Error = strerror(errno);
3695 else if (rlen > 0) {
3697 pLF = IOBuf->buf + IOBuf->BufUsed;
3698 IOBuf->BufUsed += rlen;
3699 IOBuf->buf[IOBuf->BufUsed] = '\0';
3701 pche = IOBuf->buf + IOBuf->BufUsed;
3703 while ((pLF < pche) && (*pLF != '\n'))
3705 if ((pLF >= pche) || (*pLF == '\0'))
3708 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3712 if (pLF != NULL) apos = pLF - IOBuf->buf;
3713 IncreaseBuf(IOBuf, 1, -1);
3714 if (pLF != NULL) pLF = IOBuf->buf + apos;
3724 if (len > 0 && (*(pLF - 1) == '\r') )
3726 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3727 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3733 return retlen + len;
3735 *Error = ErrRBLF_NotEnoughSentFromServer;
3740 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3742 * @ingroup StrBuf_IO
3743 * @brief Input binary data from socket
3744 * flushes and closes the FD on error
3745 * @param Buf the buffer to get the input to
3746 * @param fd pointer to the filedescriptor to read
3747 * @param append Append to an existing string or replace?
3748 * @param nBytes the maximal number of bytes to read
3749 * @param Error strerror() on error
3750 * @returns numbers of chars read
3752 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3755 int len, rlen, slen;
3763 if ((Buf == NULL) || (*fd == -1))
3765 *Error = ErrRBLF_BLOBPreConditionFailed;
3770 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3771 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3773 ptr = Buf->buf + Buf->BufUsed;
3775 slen = len = Buf->BufUsed;
3777 fdflags = fcntl(*fd, F_GETFL);
3778 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3780 while ((nRead < nBytes) &&
3790 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3791 *Error = strerror(errno);
3795 *Error = ErrRBLF_SelectFailed;
3798 if (! FD_ISSET(*fd, &rfds) != 0) {
3804 if ((rlen = read(*fd,
3806 nBytes - nRead)) == -1) {
3809 *Error = strerror(errno);
3814 Buf->BufUsed += rlen;
3816 Buf->buf[Buf->BufUsed] = '\0';
3820 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3821 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3823 * @ingroup StrBuf_BufferedIO
3824 * @brief Input binary data from socket
3825 * flushes and closes the FD on error
3826 * @param Blob put binary thing here
3827 * @param IOBuf the buffer to get the input to
3828 * @param Pos offset inside of IOBuf
3829 * @param fd pointer to the filedescriptor to read
3830 * @param append Append to an existing string or replace?
3831 * @param nBytes the maximal number of bytes to read
3832 * @param check whether we should search for '000\n' terminators in case of timeouts
3833 * @param Error strerror() on error
3834 * @returns numbers of chars read
3836 int StrBufReadBLOBBuffered(StrBuf *Blob,
3851 int nAlreadyRead = 0;
3857 int nSuccessLess = 0;
3860 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3864 *Error = ErrRBB_BLOBFPreConditionFailed;
3870 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3871 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3876 len = pos - IOBuf->buf;
3877 rlen = IOBuf->BufUsed - len;
3880 if ((IOBuf->BufUsed > 0) &&
3882 (pos < IOBuf->buf + IOBuf->BufUsed))
3884 pche = IOBuf->buf + IOBuf->BufUsed;
3887 if (rlen < nBytes) {
3888 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3889 Blob->BufUsed += rlen;
3890 Blob->buf[Blob->BufUsed] = '\0';
3891 nAlreadyRead = nRead = rlen;
3894 if (rlen >= nBytes) {
3895 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3896 Blob->BufUsed += nBytes;
3897 Blob->buf[Blob->BufUsed] = '\0';
3898 if (rlen == nBytes) {
3910 if (IOBuf->BufSize < nBytes - nRead)
3911 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3914 slen = len = Blob->BufUsed;
3916 fdflags = fcntl(*fd, F_GETFL);
3917 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3925 while ((nSuccessLess < MaxTries) &&
3935 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3936 *Error = strerror(errno);
3940 *Error = ErrRBLF_SelectFailed;
3943 if (! FD_ISSET(*fd, &rfds) != 0) {
3950 IOBuf->BufSize - (ptr - IOBuf->buf));
3954 *Error = strerror(errno);
3957 else if (rlen == 0){
3958 if ((check == NNN_TERM) &&
3960 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3962 StrBufPlain(Blob, HKEY("\n000\n"));
3963 StrBufCutRight(Blob, 5);
3964 return Blob->BufUsed;
3966 else if (!IsNonBlock)
3968 else if (nSuccessLess > MaxTries) {
3970 *Error = ErrRBB_too_many_selects;
3974 else if (rlen > 0) {
3978 IOBuf->BufUsed += rlen;
3981 if (nSuccessLess >= MaxTries) {
3983 *Error = ErrRBB_too_many_selects;
3987 if (nRead > nBytes) {
3988 *Pos = IOBuf->buf + nBytes;
3990 Blob->buf[Blob->BufUsed] = '\0';
3991 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3995 return nRead + nAlreadyRead;
3999 * @ingroup StrBuf_IO
4000 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
4001 * @param LineBuf your line will be copied here.
4002 * @param Buf BLOB with lines of text...
4003 * @param Ptr moved arround to keep the next-line across several iterations
4004 * has to be &NULL on start; will be &NotNULL on end of buffer
4005 * @returns size of copied buffer
4007 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
4009 const char *aptr, *ptr, *eptr;
4012 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
4013 *Ptr = StrBufNOTNULL;
4017 FlushStrBuf(LineBuf);
4019 ptr = aptr = Buf->buf;
4023 optr = LineBuf->buf;
4024 eptr = Buf->buf + Buf->BufUsed;
4025 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4027 while ((ptr <= eptr) &&
4034 LineBuf->BufUsed = optr - LineBuf->buf;
4035 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
4036 optr = LineBuf->buf + LineBuf->BufUsed;
4037 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4041 if ((ptr >= eptr) && (optr > LineBuf->buf))
4043 LineBuf->BufUsed = optr - LineBuf->buf;
4045 if ((ptr <= eptr) && (*ptr == '\r'))
4047 if ((ptr <= eptr) && (*ptr == '\n'))
4054 *Ptr = StrBufNOTNULL;
4057 return Buf->BufUsed - (ptr - Buf->buf);
4062 * @ingroup StrBuf_IO
4063 * @brief removes double slashes from pathnames
4064 * @param Dir directory string to filter
4065 * @param RemoveTrailingSlash allows / disallows trailing slashes
4067 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
4073 while (!IsEmptyStr(a)) {
4085 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4090 Dir->BufUsed = b - Dir->buf;