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)
265 NewBuf= (char*) malloc(NewSize);
269 if (KeepOriginal && (Buf->BufUsed > 0))
271 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
280 Buf->BufSize = NewSize;
282 dbg_IncreaseBuf(Buf);
288 * @ingroup StrBuf_DeConstructors
289 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
290 * @param Buf Buffer to shrink (has to be empty)
291 * @param ThreshHold if the buffer is bigger then this, its readjusted
292 * @param NewSize if we Shrink it, how big are we going to be afterwards?
294 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
296 if ((Buf != NULL) && (Buf->BufUsed > ThreshHold)) {
298 Buf->buf = (char*) malloc(NewSize);
300 Buf->BufSize = NewSize;
305 * @ingroup StrBuf_DeConstructors
306 * @brief shrink long term buffers to their real size so they don't waste memory
307 * @param Buf buffer to shrink
308 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
309 * @returns physical size of the buffer
311 long StrBufShrinkToFit(StrBuf *Buf, int Force)
316 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
318 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
319 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
320 Buf->BufSize = Buf->BufUsed + 1;
328 * @ingroup StrBuf_DeConstructors
329 * @brief Allocate a new buffer with default buffer size
330 * @returns the new stringbuffer
332 StrBuf* NewStrBuf(void)
336 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
337 NewBuf->buf = (char*) malloc(BaseStrBufSize);
338 NewBuf->buf[0] = '\0';
339 NewBuf->BufSize = BaseStrBufSize;
341 NewBuf->ConstBuf = 0;
349 * @ingroup StrBuf_DeConstructors
350 * @brief Copy Constructor; returns a duplicate of CopyMe
351 * @param CopyMe Buffer to faxmilate
352 * @returns the new stringbuffer
354 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
361 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
362 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
363 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
364 NewBuf->BufUsed = CopyMe->BufUsed;
365 NewBuf->BufSize = CopyMe->BufSize;
366 NewBuf->ConstBuf = 0;
374 * @ingroup StrBuf_DeConstructors
375 * @brief create a new Buffer using an existing c-string
376 * this function should also be used if you want to pre-suggest
377 * the buffer size to allocate in conjunction with ptr == NULL
378 * @param ptr the c-string to copy; may be NULL to create a blank instance
379 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
380 * @returns the new stringbuffer
382 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
385 size_t Siz = BaseStrBufSize;
388 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
390 CopySize = strlen((ptr != NULL)?ptr:"");
394 while (Siz <= CopySize)
397 NewBuf->buf = (char*) malloc(Siz);
398 NewBuf->BufSize = Siz;
400 memcpy(NewBuf->buf, ptr, CopySize);
401 NewBuf->buf[CopySize] = '\0';
402 NewBuf->BufUsed = CopySize;
405 NewBuf->buf[0] = '\0';
408 NewBuf->ConstBuf = 0;
416 * @ingroup StrBuf_DeConstructors
417 * @brief Set an existing buffer from a c-string
418 * @param Buf buffer to load
419 * @param ptr c-string to put into
420 * @param nChars set to -1 if we should work 0-terminated
421 * @returns the new length of the string
423 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
438 CopySize = strlen(ptr);
442 while (Siz <= CopySize)
445 if (Siz != Buf->BufSize)
446 IncreaseBuf(Buf, 0, Siz);
447 memcpy(Buf->buf, ptr, CopySize);
448 Buf->buf[CopySize] = '\0';
449 Buf->BufUsed = CopySize;
456 * @ingroup StrBuf_DeConstructors
457 * @brief use strbuf as wrapper for a string constant for easy handling
458 * @param StringConstant a string to wrap
459 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
461 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
465 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
466 NewBuf->buf = (char*) StringConstant;
467 NewBuf->BufSize = SizeOfStrConstant;
468 NewBuf->BufUsed = SizeOfStrConstant;
469 NewBuf->ConstBuf = 1;
478 * @ingroup StrBuf_DeConstructors
479 * @brief flush the content of a Buf; keep its struct
480 * @param buf Buffer to flush
482 int FlushStrBuf(StrBuf *buf)
494 * @ingroup StrBuf_DeConstructors
495 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
496 * @param buf Buffer to wipe
498 int FLUSHStrBuf(StrBuf *buf)
504 if (buf->BufUsed > 0) {
505 memset(buf->buf, 0, buf->BufUsed);
512 int hFreeDbglog = -1;
515 * @ingroup StrBuf_DeConstructors
516 * @brief Release a Buffer
517 * Its a double pointer, so it can NULL your pointer
518 * so fancy SIG11 appear instead of random results
519 * @param FreeMe Pointer Pointer to the buffer to free
521 void FreeStrBuf (StrBuf **FreeMe)
526 dbg_FreeStrBuf(FreeMe, 'F');
528 if (!(*FreeMe)->ConstBuf)
529 free((*FreeMe)->buf);
535 * @ingroup StrBuf_DeConstructors
536 * @brief flatten a Buffer to the Char * we return
537 * Its a double pointer, so it can NULL your pointer
538 * so fancy SIG11 appear instead of random results
539 * The Callee then owns the buffer and is responsible for freeing it.
540 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
541 * @returns the pointer of the buffer; Callee owns the memory thereafter.
543 char *SmashStrBuf (StrBuf **SmashMe)
547 if ((SmashMe == NULL) || (*SmashMe == NULL))
550 dbg_FreeStrBuf(SmashMe, 'S');
552 Ret = (*SmashMe)->buf;
559 * @ingroup StrBuf_DeConstructors
560 * @brief Release the buffer
561 * If you want put your StrBuf into a Hash, use this as Destructor.
562 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
564 void HFreeStrBuf (void *VFreeMe)
566 StrBuf *FreeMe = (StrBuf*)VFreeMe;
570 dbg_FreeStrBuf(SmashMe, 'H');
572 if (!FreeMe->ConstBuf)
578 /*******************************************************************************
579 * Simple string transformations *
580 *******************************************************************************/
584 * @brief Wrapper around atol
586 long StrTol(const StrBuf *Buf)
591 return atol(Buf->buf);
598 * @brief Wrapper around atoi
600 int StrToi(const StrBuf *Buf)
604 if (Buf->BufUsed > 0)
605 return atoi(Buf->buf);
612 * @brief Checks to see if the string is a pure number
613 * @param Buf The buffer to inspect
614 * @returns 1 if its a pure number, 0, if not.
616 int StrBufIsNumber(const StrBuf *Buf) {
618 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
621 strtoll(Buf->buf, &pEnd, 10);
622 if (pEnd == Buf->buf)
624 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
626 if (Buf->buf == pEnd)
632 * @ingroup StrBuf_Filler
633 * @brief modifies a Single char of the Buf
634 * You can point to it via char* or a zero-based integer
635 * @param Buf The buffer to manipulate
636 * @param ptr char* to zero; use NULL if unused
637 * @param nThChar zero based pointer into the string; use -1 if unused
638 * @param PeekValue The Character to place into the position
640 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
645 nThChar = ptr - Buf->buf;
646 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
648 Buf->buf[nThChar] = PeekValue;
653 * @ingroup StrBuf_Filler
654 * @brief modifies a range of chars of the Buf
655 * You can point to it via char* or a zero-based integer
656 * @param Buf The buffer to manipulate
657 * @param ptr char* to zero; use NULL if unused
658 * @param nThChar zero based pointer into the string; use -1 if unused
659 * @param nChars how many chars are to be flushed?
660 * @param PookValue The Character to place into that area
662 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
667 nThChar = ptr - Buf->buf;
668 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
670 if (nThChar + nChars > Buf->BufUsed)
671 nChars = Buf->BufUsed - nThChar;
673 memset(Buf->buf + nThChar, PookValue, nChars);
674 /* just to be shure... */
675 Buf->buf[Buf->BufUsed] = 0;
680 * @ingroup StrBuf_Filler
681 * @brief Append a StringBuffer to the buffer
682 * @param Buf Buffer to modify
683 * @param AppendBuf Buffer to copy at the end of our buffer
684 * @param Offset Should we start copying from an offset?
686 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
688 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
691 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
694 AppendBuf->BufUsed + Buf->BufUsed);
696 memcpy(Buf->buf + Buf->BufUsed,
697 AppendBuf->buf + Offset,
698 AppendBuf->BufUsed - Offset);
699 Buf->BufUsed += AppendBuf->BufUsed - Offset;
700 Buf->buf[Buf->BufUsed] = '\0';
705 * @ingroup StrBuf_Filler
706 * @brief Append a C-String to the buffer
707 * @param Buf Buffer to modify
708 * @param AppendBuf Buffer to copy at the end of our buffer
709 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
710 * @param Offset Should we start copying from an offset?
712 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
715 long BufSizeRequired;
717 if ((AppendBuf == NULL) || (Buf == NULL))
721 aps = strlen(AppendBuf + Offset);
723 aps = AppendSize - Offset;
725 BufSizeRequired = Buf->BufUsed + aps + 1;
726 if (Buf->BufSize <= BufSizeRequired)
727 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
729 memcpy(Buf->buf + Buf->BufUsed,
733 Buf->buf[Buf->BufUsed] = '\0';
737 * @ingroup StrBuf_Filler
738 * @brief sprintf like function appending the formated string to the buffer
739 * vsnprintf version to wrap into own calls
740 * @param Buf Buffer to extend by format and Params
741 * @param format printf alike format to add
742 * @param ap va_list containing the items for format
744 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
752 if ((Buf == NULL) || (format == NULL))
755 BufSize = Buf->BufSize;
756 nWritten = Buf->BufSize + 1;
757 Offset = Buf->BufUsed;
758 newused = Offset + nWritten;
760 while (newused >= BufSize) {
762 nWritten = vsnprintf(Buf->buf + Offset,
763 Buf->BufSize - Offset,
766 newused = Offset + nWritten;
767 if (newused >= Buf->BufSize) {
768 IncreaseBuf(Buf, 1, newused);
769 newused = Buf->BufSize + 1;
772 Buf->BufUsed = Offset + nWritten;
773 BufSize = Buf->BufSize;
780 * @ingroup StrBuf_Filler
781 * @brief sprintf like function appending the formated string to the buffer
782 * @param Buf Buffer to extend by format and Params
783 * @param format printf alike format to add
785 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
793 if ((Buf == NULL) || (format == NULL))
796 BufSize = Buf->BufSize;
797 nWritten = Buf->BufSize + 1;
798 Offset = Buf->BufUsed;
799 newused = Offset + nWritten;
801 while (newused >= BufSize) {
802 va_start(arg_ptr, format);
803 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
804 Buf->BufSize - Buf->BufUsed,
807 newused = Buf->BufUsed + nWritten;
808 if (newused >= Buf->BufSize) {
809 IncreaseBuf(Buf, 1, newused);
810 newused = Buf->BufSize + 1;
813 Buf->BufUsed += nWritten;
814 BufSize = Buf->BufSize;
821 * @ingroup StrBuf_Filler
822 * @brief sprintf like function putting the formated string into the buffer
823 * @param Buf Buffer to extend by format and Parameters
824 * @param format printf alike format to add
826 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
831 if ((Buf == NULL) || (format == NULL))
834 nWritten = Buf->BufSize + 1;
835 while (nWritten >= Buf->BufSize) {
836 va_start(arg_ptr, format);
837 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
839 if (nWritten >= Buf->BufSize) {
840 IncreaseBuf(Buf, 0, 0);
841 nWritten = Buf->BufSize + 1;
844 Buf->BufUsed = nWritten ;
849 * @ingroup StrBuf_Filler
850 * @brief Callback for cURL to append the webserver reply to a buffer
851 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
852 * @param size pre-defined by the cURL API; see man 3 curl for mre info
853 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
854 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
856 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
865 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
872 * @brief extracts a substring from Source into dest
873 * @param dest buffer to place substring into
874 * @param Source string to copy substring from
875 * @param Offset chars to skip from start
876 * @param nChars number of chars to copy
877 * @returns the number of chars copied; may be different from nChars due to the size of Source
879 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
882 if (Offset > Source->BufUsed)
888 if (Offset + nChars < Source->BufUsed)
890 if (nChars >= dest->BufSize)
891 IncreaseBuf(dest, 0, nChars + 1);
892 memcpy(dest->buf, Source->buf + Offset, nChars);
893 dest->BufUsed = nChars;
894 dest->buf[dest->BufUsed] = '\0';
897 NCharsRemain = Source->BufUsed - Offset;
898 if (NCharsRemain >= dest->BufSize)
899 IncreaseBuf(dest, 0, NCharsRemain + 1);
900 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
901 dest->BufUsed = NCharsRemain;
902 dest->buf[dest->BufUsed] = '\0';
908 * @brief Cut nChars from the start of the string
909 * @param Buf Buffer to modify
910 * @param nChars how many chars should be skipped?
912 void StrBufCutLeft(StrBuf *Buf, int nChars)
914 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
915 if (nChars >= Buf->BufUsed) {
919 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
920 Buf->BufUsed -= nChars;
921 Buf->buf[Buf->BufUsed] = '\0';
926 * @brief Cut the trailing n Chars from the string
927 * @param Buf Buffer to modify
928 * @param nChars how many chars should be trunkated?
930 void StrBufCutRight(StrBuf *Buf, int nChars)
932 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
933 if (nChars >= Buf->BufUsed) {
937 Buf->BufUsed -= nChars;
938 Buf->buf[Buf->BufUsed] = '\0';
943 * @brief Cut the string after n Chars
944 * @param Buf Buffer to modify
945 * @param AfternChars after how many chars should we trunkate the string?
946 * @param At if non-null and points inside of our string, cut it there.
948 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
950 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
952 AfternChars = At - Buf->buf;
955 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
957 Buf->BufUsed = AfternChars;
958 Buf->buf[Buf->BufUsed] = '\0';
964 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
965 * @param Buf the string to modify
967 void StrBufTrim(StrBuf *Buf)
970 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
972 while ((Buf->BufUsed > 0) &&
973 isspace(Buf->buf[Buf->BufUsed - 1]))
977 Buf->buf[Buf->BufUsed] = '\0';
979 if (Buf->BufUsed == 0) return;
981 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
984 if (delta > 0) StrBufCutLeft(Buf, delta);
987 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
995 pLeft = pBuff = Buf->buf;
996 while (pBuff != NULL) {
998 pBuff = strchr(pBuff, leftboundary);
1007 pRight = strchr(pBuff, rightboundary);
1009 StrBufCutAt(Buf, 0, pRight);
1011 StrBufCutLeft(Buf, pLeft - Buf->buf);
1016 * @ingroup StrBuf_Filler
1017 * @brief uppercase the contents of a buffer
1018 * @param Buf the buffer to translate
1020 void StrBufUpCase(StrBuf *Buf)
1024 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1027 pche = pch + Buf->BufUsed;
1028 while (pch < pche) {
1029 *pch = toupper(*pch);
1036 * @ingroup StrBuf_Filler
1037 * @brief lowercase the contents of a buffer
1038 * @param Buf the buffer to translate
1040 void StrBufLowerCase(StrBuf *Buf)
1044 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1047 pche = pch + Buf->BufUsed;
1048 while (pch < pche) {
1049 *pch = tolower(*pch);
1055 /*******************************************************************************
1056 * a tokenizer that kills, maims, and destroys *
1057 *******************************************************************************/
1060 * @ingroup StrBuf_Tokenizer
1061 * @brief Replace a token at a given place with a given length by another token with given length
1062 * @param Buf String where to work on
1063 * @param where where inside of the Buf is the search-token
1064 * @param HowLong How long is the token to be replaced
1065 * @param Repl Token to insert at 'where'
1066 * @param ReplLen Length of repl
1067 * @returns -1 if fail else length of resulting Buf
1069 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1070 const char *Repl, long ReplLen)
1073 if ((Buf == NULL) ||
1074 (where > Buf->BufUsed) ||
1075 (where + HowLong > Buf->BufUsed))
1078 if (where + ReplLen - HowLong > Buf->BufSize)
1079 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1082 memmove(Buf->buf + where + ReplLen,
1083 Buf->buf + where + HowLong,
1084 Buf->BufUsed - where - HowLong);
1086 memcpy(Buf->buf + where,
1089 Buf->BufUsed += ReplLen - HowLong;
1091 return Buf->BufUsed;
1095 * @ingroup StrBuf_Tokenizer
1096 * @brief Counts the numbmer of tokens in a buffer
1097 * @param source String to count tokens in
1098 * @param tok Tokenizer char to count
1099 * @returns numbers of tokenizer chars found
1101 int StrBufNum_tokens(const StrBuf *source, char tok)
1105 if ((source == NULL) || (source->BufUsed == 0))
1107 if ((source->BufUsed == 1) && (*source->buf == tok))
1111 pche = pch + source->BufUsed;
1122 * @ingroup StrBuf_Tokenizer
1123 * @brief a string tokenizer
1124 * @param Source StringBuffer to read into
1125 * @param parmnum n'th Parameter to remove
1126 * @param separator tokenizer character
1127 * @returns -1 if not found, else length of token.
1129 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1132 char *d, *s, *end; /* dest, source */
1135 /* Find desired @parameter */
1136 end = Source->buf + Source->BufUsed;
1138 while ((d <= end) &&
1141 /* End of string, bail! */
1146 if (*d == separator) {
1151 if ((d == NULL) || (d >= end))
1152 return 0; /* @Parameter not found */
1154 /* Find next @parameter */
1156 while ((s <= end) &&
1157 (*s && *s != separator))
1161 if (*s == separator)
1165 /* Hack and slash */
1170 memmove(d, s, Source->BufUsed - (s - Source->buf));
1171 Source->BufUsed += ReducedBy;
1172 Source->buf[Source->BufUsed] = '\0';
1174 else if (d == Source->buf) {
1176 Source->BufUsed = 0;
1180 Source->BufUsed += ReducedBy;
1193 * @ingroup StrBuf_Tokenizer
1194 * @brief a string tokenizer
1195 * @param dest Destination StringBuffer
1196 * @param Source StringBuffer to read into
1197 * @param parmnum n'th Parameter to extract
1198 * @param separator tokenizer character
1199 * @returns -1 if not found, else length of token.
1201 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1203 const char *s, *e; //* source * /
1204 int len = 0; //* running total length of extracted string * /
1205 int current_token = 0; //* token currently being processed * /
1208 dest->buf[0] = '\0';
1214 if ((Source == NULL) || (Source->BufUsed ==0)) {
1218 e = s + Source->BufUsed;
1221 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1223 while ((s<e) && !IsEmptyStr(s)) {
1224 if (*s == separator) {
1227 if (len >= dest->BufSize) {
1228 dest->BufUsed = len;
1229 if (IncreaseBuf(dest, 1, -1) < 0) {
1234 if ( (current_token == parmnum) &&
1235 (*s != separator)) {
1236 dest->buf[len] = *s;
1239 else if (current_token > parmnum) {
1245 dest->buf[len] = '\0';
1246 dest->BufUsed = len;
1248 if (current_token < parmnum) {
1249 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1252 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1261 * @ingroup StrBuf_Tokenizer
1262 * @brief a string tokenizer to fetch an integer
1263 * @param Source String containing tokens
1264 * @param parmnum n'th Parameter to extract
1265 * @param separator tokenizer character
1266 * @returns 0 if not found, else integer representation of the token
1268 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1278 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1285 * @ingroup StrBuf_Tokenizer
1286 * @brief a string tokenizer to fetch a long integer
1287 * @param Source String containing tokens
1288 * @param parmnum n'th Parameter to extract
1289 * @param separator tokenizer character
1290 * @returns 0 if not found, else long integer representation of the token
1292 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1302 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1310 * @ingroup StrBuf_Tokenizer
1311 * @brief a string tokenizer to fetch an unsigned long
1312 * @param Source String containing tokens
1313 * @param parmnum n'th Parameter to extract
1314 * @param separator tokenizer character
1315 * @returns 0 if not found, else unsigned long representation of the token
1317 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1328 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1332 return (unsigned long) atol(pnum);
1341 * @ingroup StrBuf_NextTokenizer
1342 * @brief a string tokenizer; Bounds checker
1343 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1344 * @param Source our tokenbuffer
1345 * @param pStart the token iterator pointer to inspect
1346 * @returns whether the revolving pointer is inside of the search range
1348 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1350 if ((Source == NULL) ||
1351 (*pStart == StrBufNOTNULL) ||
1352 (Source->BufUsed == 0))
1356 if (*pStart == NULL)
1360 else if (*pStart > Source->buf + Source->BufUsed)
1364 else if (*pStart <= Source->buf)
1373 * @ingroup StrBuf_NextTokenizer
1374 * @brief a string tokenizer
1375 * @param dest Destination StringBuffer
1376 * @param Source StringBuffer to read into
1377 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1378 * @param separator tokenizer
1379 * @returns -1 if not found, else length of token.
1381 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1383 const char *s; /* source */
1384 const char *EndBuffer; /* end stop of source buffer */
1385 int current_token = 0; /* token currently being processed */
1386 int len = 0; /* running total length of extracted string */
1388 if ((Source == NULL) ||
1389 (Source->BufUsed == 0) )
1391 *pStart = StrBufNOTNULL;
1395 EndBuffer = Source->buf + Source->BufUsed;
1399 dest->buf[0] = '\0';
1404 *pStart = EndBuffer + 1;
1408 if (*pStart == NULL)
1410 *pStart = Source->buf; /* we're starting to examine this buffer. */
1412 else if ((*pStart < Source->buf) ||
1413 (*pStart > EndBuffer ) )
1415 return -1; /* no more tokens to find. */
1419 /* start to find the next token */
1420 while ((s <= EndBuffer) &&
1421 (current_token == 0) )
1423 if (*s == separator)
1425 /* we found the next token */
1429 if (len >= dest->BufSize)
1431 /* our Dest-buffer isn't big enough, increase it. */
1432 dest->BufUsed = len;
1434 if (IncreaseBuf(dest, 1, -1) < 0) {
1435 /* WHUT? no more mem? bail out. */
1442 if ( (current_token == 0 ) && /* are we in our target token? */
1443 (!IsEmptyStr(s) ) &&
1444 (separator != *s) ) /* don't copy the token itself */
1446 dest->buf[len] = *s; /* Copy the payload */
1447 ++len; /* remember the bigger size. */
1453 /* did we reach the end? */
1454 if ((s > EndBuffer)) {
1455 EndBuffer = StrBufNOTNULL;
1456 *pStart = EndBuffer;
1459 *pStart = s; /* remember the position for the next run */
1462 /* sanitize our extracted token */
1463 dest->buf[len] = '\0';
1464 dest->BufUsed = len;
1471 * @ingroup StrBuf_NextTokenizer
1472 * @brief a string tokenizer
1473 * @param Source StringBuffer to read from
1474 * @param pStart pointer to the end of the last token. Feed with NULL.
1475 * @param separator tokenizer character
1476 * @param nTokens number of tokens to fastforward over
1477 * @returns -1 if not found, else length of token.
1479 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1481 const char *s, *EndBuffer; //* source * /
1482 int len = 0; //* running total length of extracted string * /
1483 int current_token = 0; //* token currently being processed * /
1485 if ((Source == NULL) ||
1486 (Source->BufUsed ==0)) {
1490 return Source->BufUsed;
1492 if (*pStart == NULL)
1493 *pStart = Source->buf;
1495 EndBuffer = Source->buf + Source->BufUsed;
1497 if ((*pStart < Source->buf) ||
1498 (*pStart > EndBuffer)) {
1506 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1508 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1509 if (*s == separator) {
1512 if (current_token >= nTokens) {
1524 * @ingroup StrBuf_NextTokenizer
1525 * @brief a string tokenizer to fetch an integer
1526 * @param Source StringBuffer to read from
1527 * @param pStart Cursor on the tokenstring
1528 * @param separator tokenizer character
1529 * @returns 0 if not found, else integer representation of the token
1531 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1541 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1548 * @ingroup StrBuf_NextTokenizer
1549 * @brief a string tokenizer to fetch a long integer
1550 * @param Source StringBuffer to read from
1551 * @param pStart Cursor on the tokenstring
1552 * @param separator tokenizer character
1553 * @returns 0 if not found, else long integer representation of the token
1555 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1565 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1573 * @ingroup StrBuf_NextTokenizer
1574 * @brief a string tokenizer to fetch an unsigned long
1575 * @param Source StringBuffer to read from
1576 * @param pStart Cursor on the tokenstring
1577 * @param separator tokenizer character
1578 * @returns 0 if not found, else unsigned long representation of the token
1580 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1591 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1595 return (unsigned long) atol(pnum);
1605 /*******************************************************************************
1606 * Escape Appending *
1607 *******************************************************************************/
1610 * @ingroup StrBuf_DeEnCoder
1611 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1612 * @param OutBuf the output buffer
1613 * @param In Buffer to encode
1614 * @param PlainIn way in from plain old c strings
1616 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1618 const char *pch, *pche;
1622 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1624 if (PlainIn != NULL) {
1625 len = strlen(PlainIn);
1631 pche = pch + In->BufUsed;
1638 pt = OutBuf->buf + OutBuf->BufUsed;
1639 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1641 while (pch < pche) {
1643 IncreaseBuf(OutBuf, 1, -1);
1644 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1645 pt = OutBuf->buf + OutBuf->BufUsed;
1648 if((*pch >= 'a' && *pch <= 'z') ||
1649 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1650 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1651 (*pch == '!') || (*pch == '_') ||
1652 (*pch == ',') || (*pch == '.'))
1659 *(pt + 1) = HexList[(unsigned char)*pch][0];
1660 *(pt + 2) = HexList[(unsigned char)*pch][1];
1662 OutBuf->BufUsed += 3;
1670 * @ingroup StrBuf_DeEnCoder
1671 * @brief append a string in hex encoding to the buffer
1672 * @param OutBuf the output buffer
1673 * @param In Buffer to encode
1674 * @param PlainIn way in from plain old c strings
1676 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1678 const char *pch, *pche;
1682 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1684 if (PlainIn != NULL) {
1685 len = strlen(PlainIn);
1691 pche = pch + In->BufUsed;
1698 pt = OutBuf->buf + OutBuf->BufUsed;
1699 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1701 while (pch < pche) {
1703 IncreaseBuf(OutBuf, 1, -1);
1704 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1705 pt = OutBuf->buf + OutBuf->BufUsed;
1708 *pt = HexList[(unsigned char)*pch][0];
1710 *pt = HexList[(unsigned char)*pch][1];
1711 pt ++; pch ++; OutBuf->BufUsed += 2;
1717 * @ingroup StrBuf_DeEnCoder
1718 * @brief Append a string, escaping characters which have meaning in HTML.
1720 * @param Target target buffer
1721 * @param Source source buffer; set to NULL if you just have a C-String
1722 * @param PlainIn Plain-C string to append; set to NULL if unused
1723 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1724 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1725 * if set to 2, linebreaks are replaced by <br/>
1727 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1729 const char *aptr, *eiptr;
1733 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1736 if (PlainIn != NULL) {
1738 len = strlen(PlainIn);
1743 eiptr = aptr + Source->BufUsed;
1744 len = Source->BufUsed;
1750 bptr = Target->buf + Target->BufUsed;
1751 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1753 while (aptr < eiptr){
1755 IncreaseBuf(Target, 1, -1);
1756 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1757 bptr = Target->buf + Target->BufUsed;
1760 memcpy(bptr, "<", 4);
1762 Target->BufUsed += 4;
1764 else if (*aptr == '>') {
1765 memcpy(bptr, ">", 4);
1767 Target->BufUsed += 4;
1769 else if (*aptr == '&') {
1770 memcpy(bptr, "&", 5);
1772 Target->BufUsed += 5;
1774 else if (*aptr == '"') {
1775 memcpy(bptr, """, 6);
1777 Target->BufUsed += 6;
1779 else if (*aptr == '\'') {
1780 memcpy(bptr, "'", 5);
1782 Target->BufUsed += 5;
1784 else if (*aptr == LB) {
1789 else if (*aptr == RB) {
1794 else if (*aptr == QU) {
1799 else if ((*aptr == 32) && (nbsp == 1)) {
1800 memcpy(bptr, " ", 6);
1802 Target->BufUsed += 6;
1804 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1805 *bptr='\0'; /* nothing */
1807 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1808 memcpy(bptr, "<br/>", 11);
1810 Target->BufUsed += 11;
1814 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1815 *bptr='\0'; /* nothing */
1825 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1827 return Target->BufUsed;
1831 * @ingroup StrBuf_DeEnCoder
1832 * @brief Append a string, escaping characters which have meaning in HTML.
1833 * Converts linebreaks into blanks; escapes single quotes
1834 * @param Target target buffer
1835 * @param Source source buffer; set to NULL if you just have a C-String
1836 * @param PlainIn Plain-C string to append; set to NULL if unused
1838 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1840 const char *aptr, *eiptr;
1844 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1847 if (PlainIn != NULL) {
1849 len = strlen(PlainIn);
1854 eiptr = aptr + Source->BufUsed;
1855 len = Source->BufUsed;
1861 eptr = Target->buf + Target->BufSize - 8;
1862 tptr = Target->buf + Target->BufUsed;
1864 while (aptr < eiptr){
1866 IncreaseBuf(Target, 1, -1);
1867 eptr = Target->buf + Target->BufSize - 8;
1868 tptr = Target->buf + Target->BufUsed;
1871 if (*aptr == '\n') {
1875 else if (*aptr == '\r') {
1879 else if (*aptr == '\'') {
1885 Target->BufUsed += 5;
1898 * @ingroup StrBuf_DeEnCoder
1899 * @brief Append a string, escaping characters which have meaning in ICAL.
1901 * @param Target target buffer
1902 * @param Source source buffer; set to NULL if you just have a C-String
1903 * @param PlainIn Plain-C string to append; set to NULL if unused
1905 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1907 const char *aptr, *eiptr;
1911 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1914 if (PlainIn != NULL) {
1916 len = strlen(PlainIn);
1921 eiptr = aptr + Source->BufUsed;
1922 len = Source->BufUsed;
1928 eptr = Target->buf + Target->BufSize - 8;
1929 tptr = Target->buf + Target->BufUsed;
1931 while (aptr < eiptr){
1932 if(tptr + 3 >= eptr) {
1933 IncreaseBuf(Target, 1, -1);
1934 eptr = Target->buf + Target->BufSize - 8;
1935 tptr = Target->buf + Target->BufUsed;
1938 if (*aptr == '\n') {
1945 else if (*aptr == '\r') {
1952 else if (*aptr == ',') {
1968 * @ingroup StrBuf_DeEnCoder
1969 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1971 * @param Target target buffer
1972 * @param Source source buffer; set to NULL if you just have a C-String
1973 * @param PlainIn Plain-C string to append; set to NULL if unused
1974 * @returns size of result or -1
1976 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1978 const char *aptr, *eiptr;
1982 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1985 if (PlainIn != NULL) {
1987 len = strlen(PlainIn);
1992 eiptr = aptr + Source->BufUsed;
1993 len = Source->BufUsed;
1999 bptr = Target->buf + Target->BufUsed;
2000 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
2002 while (aptr < eiptr){
2004 IncreaseBuf(Target, 1, -1);
2005 eptr = Target->buf + Target->BufSize - 3;
2006 bptr = Target->buf + Target->BufUsed;
2013 Target->BufUsed += 2;
2014 } else if (*aptr == '\\') {
2019 Target->BufUsed += 2;
2029 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2031 return Target->BufUsed;
2035 * @ingroup StrBuf_DeEnCoder
2036 * @brief Append a string, escaping characters which have meaning in HTML + json.
2038 * @param Target target buffer
2039 * @param Source source buffer; set to NULL if you just have a C-String
2040 * @param PlainIn Plain-C string to append; set to NULL if unused
2041 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2042 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2043 * if set to 2, linebreaks are replaced by <br/>
2045 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2047 const char *aptr, *eiptr;
2050 int IsUtf8Sequence = 0;
2052 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2055 if (PlainIn != NULL) {
2057 len = strlen(PlainIn);
2062 eiptr = aptr + Source->BufUsed;
2063 len = Source->BufUsed;
2069 bptr = Target->buf + Target->BufUsed;
2070 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2072 while (aptr < eiptr){
2074 IncreaseBuf(Target, 1, -1);
2075 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2076 bptr = Target->buf + Target->BufUsed;
2079 memcpy(bptr, "<", 4);
2081 Target->BufUsed += 4;
2083 else if (*aptr == '>') {
2084 memcpy(bptr, ">", 4);
2086 Target->BufUsed += 4;
2088 else if (*aptr == '&') {
2089 memcpy(bptr, "&", 5);
2091 Target->BufUsed += 5;
2093 else if (*aptr == LB) {
2098 else if (*aptr == RB) {
2103 else if ((*aptr == 32) && (nbsp == 1)) {
2104 memcpy(bptr, " ", 6);
2106 Target->BufUsed += 6;
2108 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2109 *bptr='\0'; /* nothing */
2111 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2112 memcpy(bptr, "<br/>", 11);
2114 Target->BufUsed += 11;
2117 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2118 *bptr='\0'; /* nothing */
2121 else if ((*aptr == '"') || (*aptr == QU)) {
2126 Target->BufUsed += 2;
2127 } else if (*aptr == '\\') {
2132 Target->BufUsed += 2;
2135 if (((unsigned char)*aptr) >= 0x20)
2137 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2141 while (IsUtf8Sequence > 1){
2142 if(bptr + IsUtf8Sequence >= eptr) {
2143 IncreaseBuf(Target, 1, -1);
2144 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2145 bptr = Target->buf + Target->BufUsed - 1;
2159 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2161 return Target->BufUsed;
2165 * @ingroup StrBuf_DeEnCoder
2166 * @brief unhide special chars hidden to the HTML escaper
2167 * @param target buffer to put the unescaped string in
2168 * @param source buffer to unescape
2170 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2176 FlushStrBuf(target);
2178 if (source == NULL ||target == NULL)
2183 len = source->BufUsed;
2184 for (a = 0; a < len; ++a) {
2185 if (target->BufUsed >= target->BufSize)
2186 IncreaseBuf(target, 1, -1);
2188 if (source->buf[a] == '=') {
2189 hex[0] = source->buf[a + 1];
2190 hex[1] = source->buf[a + 2];
2193 sscanf(hex, "%02x", &b);
2194 target->buf[target->BufUsed] = b;
2195 target->buf[++target->BufUsed] = 0;
2199 target->buf[target->BufUsed] = source->buf[a];
2200 target->buf[++target->BufUsed] = 0;
2207 * @ingroup StrBuf_DeEnCoder
2208 * @brief hide special chars from the HTML escapers and friends
2209 * @param target buffer to put the escaped string in
2210 * @param source buffer to escape
2212 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2217 FlushStrBuf(target);
2219 if (source == NULL ||target == NULL)
2224 len = source->BufUsed;
2225 for (i=0; i<len; ++i) {
2226 if (target->BufUsed + 4 >= target->BufSize)
2227 IncreaseBuf(target, 1, -1);
2228 if ( (isalnum(source->buf[i])) ||
2229 (source->buf[i]=='-') ||
2230 (source->buf[i]=='_') ) {
2231 target->buf[target->BufUsed++] = source->buf[i];
2234 sprintf(&target->buf[target->BufUsed],
2236 (0xFF &source->buf[i]));
2237 target->BufUsed += 3;
2240 target->buf[target->BufUsed + 1] = '\0';
2244 /*******************************************************************************
2245 * Quoted Printable de/encoding *
2246 *******************************************************************************/
2249 * @ingroup StrBuf_DeEnCoder
2250 * @brief decode a buffer from base 64 encoding; destroys original
2251 * @param Buf Buffor to transform
2253 int StrBufDecodeBase64(StrBuf *Buf)
2257 if (Buf == NULL) return -1;
2259 xferbuf = (char*) malloc(Buf->BufSize);
2260 siz = CtdlDecodeBase64(xferbuf,
2270 * @ingroup StrBuf_DeEnCoder
2271 * @brief decode a buffer from base 64 encoding; destroys original
2272 * @param Buf Buffor to transform
2274 int StrBufDecodeHex(StrBuf *Buf)
2277 char *pch, *pche, *pchi;
2279 if (Buf == NULL) return -1;
2281 pch = pchi = Buf->buf;
2282 pche = pch + Buf->BufUsed;
2284 while (pchi < pche){
2285 ch = decode_hex(pchi);
2292 Buf->BufUsed = pch - Buf->buf;
2293 return Buf->BufUsed;
2297 * @ingroup StrBuf_DeEnCoder
2298 * @brief replace all chars >0x20 && < 0x7F with Mute
2299 * @param Mute char to put over invalid chars
2300 * @param Buf Buffor to transform
2302 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2306 if (Buf == NULL) return -1;
2307 pch = (unsigned char *)Buf->buf;
2308 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2309 if ((*pch < 0x20) || (*pch > 0x7F))
2313 return Buf->BufUsed;
2318 * @ingroup StrBuf_DeEnCoder
2319 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2320 * @param Buf Buffer to translate
2321 * @param StripBlanks Reduce several blanks to one?
2323 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2332 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2333 Buf->buf[Buf->BufUsed - 1] = '\0';
2338 while (a < Buf->BufUsed) {
2339 if (Buf->buf[a] == '+')
2341 else if (Buf->buf[a] == '%') {
2342 /* don't let % chars through, rather truncate the input. */
2343 if (a + 2 > Buf->BufUsed) {
2348 hex[0] = Buf->buf[a + 1];
2349 hex[1] = Buf->buf[a + 2];
2352 sscanf(hex, "%02x", &b);
2353 Buf->buf[a] = (char) b;
2354 len = Buf->BufUsed - a - 2;
2356 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2368 * @ingroup StrBuf_DeEnCoder
2369 * @brief RFC2047-encode a header field if necessary.
2370 * If no non-ASCII characters are found, the string
2371 * will be copied verbatim without encoding.
2373 * @param target Target buffer.
2374 * @param source Source string to be encoded.
2375 * @returns encoded length; -1 if non success.
2377 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2379 const char headerStr[] = "=?UTF-8?Q?";
2380 int need_to_encode = 0;
2384 if ((source == NULL) ||
2388 while ((i < source->BufUsed) &&
2389 (!IsEmptyStr (&source->buf[i])) &&
2390 (need_to_encode == 0)) {
2391 if (((unsigned char) source->buf[i] < 32) ||
2392 ((unsigned char) source->buf[i] > 126)) {
2398 if (!need_to_encode) {
2399 if (*target == NULL) {
2400 *target = NewStrBufPlain(source->buf, source->BufUsed);
2403 FlushStrBuf(*target);
2404 StrBufAppendBuf(*target, source, 0);
2406 return (*target)->BufUsed;
2408 if (*target == NULL)
2409 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2410 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2411 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2412 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2413 (*target)->BufUsed = sizeof(headerStr) - 1;
2414 for (i=0; (i < source->BufUsed); ++i) {
2415 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2416 IncreaseBuf(*target, 1, 0);
2417 ch = (unsigned char) source->buf[i];
2418 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2419 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2420 (*target)->BufUsed += 3;
2423 (*target)->buf[(*target)->BufUsed] = ch;
2424 (*target)->BufUsed++;
2428 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2429 IncreaseBuf(*target, 1, 0);
2431 (*target)->buf[(*target)->BufUsed++] = '?';
2432 (*target)->buf[(*target)->BufUsed++] = '=';
2433 (*target)->buf[(*target)->BufUsed] = '\0';
2434 return (*target)->BufUsed;;
2439 * @brief replaces all occurances of 'search' by 'replace'
2440 * @param buf Buffer to modify
2441 * @param search character to search
2442 * @param replace character to replace search by
2444 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2449 for (i=0; i<buf->BufUsed; i++)
2450 if (buf->buf[i] == search)
2451 buf->buf[i] = replace;
2457 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2458 * @param buf Buffer to modify
2460 void StrBufToUnixLF(StrBuf *buf)
2462 char *pche, *pchS, *pchT;
2466 pche = buf->buf + buf->BufUsed;
2467 pchS = pchT = buf->buf;
2473 if (*pchS != '\n') {
2482 buf->BufUsed = pchT - buf->buf;
2486 /*******************************************************************************
2487 * Iconv Wrapper; RFC822 de/encoding *
2488 *******************************************************************************/
2491 * @ingroup StrBuf_DeEnCoder
2492 * @brief Wrapper around iconv_open()
2493 * Our version adds aliases for non-standard Microsoft charsets
2494 * such as 'MS950', aliasing them to names like 'CP950'
2496 * @param tocode Target encoding
2497 * @param fromcode Source encoding
2498 * @param pic anonimized pointer to iconv struct
2500 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2503 iconv_t ic = (iconv_t)(-1) ;
2504 ic = iconv_open(tocode, fromcode);
2505 if (ic == (iconv_t)(-1) ) {
2506 char alias_fromcode[64];
2507 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2508 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2509 alias_fromcode[0] = 'C';
2510 alias_fromcode[1] = 'P';
2511 ic = iconv_open(tocode, alias_fromcode);
2514 *(iconv_t *)pic = ic;
2520 * @ingroup StrBuf_DeEnCoder
2521 * @brief find one chunk of a RFC822 encoded string
2522 * @param Buffer where to search
2523 * @param bptr where to start searching
2524 * @returns found position, NULL if none.
2526 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2529 /* Find the next ?Q? */
2530 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2533 end = strchr(bptr + 2, '?');
2538 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2539 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2540 (*(end + 2) == '?')) {
2541 /* skip on to the end of the cluster, the next ?= */
2542 end = strstr(end + 3, "?=");
2545 /* sort of half valid encoding, try to find an end. */
2546 end = strstr(bptr, "?=");
2552 * @brief swaps the contents of two StrBufs
2553 * this is to be used to have cheap switched between a work-buffer and a target buffer
2554 * @param A First one
2555 * @param B second one
2557 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2561 memcpy(&C, A, sizeof(*A));
2562 memcpy(A, B, sizeof(*B));
2563 memcpy(B, &C, sizeof(C));
2569 * @ingroup StrBuf_DeEnCoder
2570 * @brief convert one buffer according to the preselected iconv pointer PIC
2571 * @param ConvertBuf buffer we need to translate
2572 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2573 * @param pic Pointer to the iconv-session Object
2575 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2581 char *ibuf; /**< Buffer of characters to be converted */
2582 char *obuf; /**< Buffer for converted characters */
2583 size_t ibuflen; /**< Length of input buffer */
2584 size_t obuflen; /**< Length of output buffer */
2587 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2588 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2589 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2591 ic = *(iconv_t*)pic;
2592 ibuf = ConvertBuf->buf;
2593 ibuflen = ConvertBuf->BufUsed;
2595 obuflen = TmpBuf->BufSize;
2597 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2600 if (errno == E2BIG) {
2602 IncreaseBuf(TmpBuf, 0, 0);
2607 else if (errno == EILSEQ){
2608 /* hm, invalid utf8 sequence... what to do now? */
2609 /* An invalid multibyte sequence has been encountered in the input */
2611 else if (errno == EINVAL) {
2612 /* An incomplete multibyte sequence has been encountered in the input. */
2615 FlushStrBuf(TmpBuf);
2618 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2619 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2621 /* little card game: wheres the red lady? */
2622 SwapBuffers(ConvertBuf, TmpBuf);
2623 FlushStrBuf(TmpBuf);
2630 * @ingroup StrBuf_DeEnCoder
2631 * @brief catches one RFC822 encoded segment, and decodes it.
2632 * @param Target buffer to fill with result
2633 * @param DecodeMe buffer with stuff to process
2634 * @param SegmentStart points to our current segment in DecodeMe
2635 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2636 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2637 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2638 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2640 inline static void DecodeSegment(StrBuf *Target,
2641 const StrBuf *DecodeMe,
2642 const char *SegmentStart,
2643 const char *SegmentEnd,
2645 StrBuf *ConvertBuf2,
2646 StrBuf *FoundCharset)
2652 iconv_t ic = (iconv_t)(-1);
2656 /* Now we handle foreign character sets properly encoded
2657 * in RFC2047 format.
2659 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2660 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2661 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2662 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2663 if (FoundCharset != NULL) {
2664 FlushStrBuf(FoundCharset);
2665 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2667 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2668 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2670 *encoding = toupper(*encoding);
2671 if (*encoding == 'B') { /**< base64 */
2672 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2674 ConvertBuf->BufUsed);
2676 else if (*encoding == 'Q') { /**< quoted-printable */
2680 while (pos < ConvertBuf->BufUsed)
2682 if (ConvertBuf->buf[pos] == '_')
2683 ConvertBuf->buf[pos] = ' ';
2687 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2690 ConvertBuf->BufUsed);
2693 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2696 ctdl_iconv_open("UTF-8", charset, &ic);
2697 if (ic != (iconv_t)(-1) ) {
2699 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2700 StrBufAppendBuf(Target, ConvertBuf2, 0);
2705 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2711 * @ingroup StrBuf_DeEnCoder
2712 * @brief Handle subjects with RFC2047 encoding such as:
2713 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2714 * @param Target where to put the decoded string to
2715 * @param DecodeMe buffer with encoded string
2716 * @param DefaultCharset if we don't find one, which should we use?
2717 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2718 * put it here for later use where no string might be known.
2720 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2722 StrBuf *DecodedInvalidBuf = NULL;
2723 StrBuf *ConvertBuf, *ConvertBuf2;
2724 const StrBuf *DecodeMee = DecodeMe;
2725 const char *start, *end, *next, *nextend, *ptr = NULL;
2727 iconv_t ic = (iconv_t)(-1) ;
2732 int illegal_non_rfc2047_encoding = 0;
2734 /* Sometimes, badly formed messages contain strings which were simply
2735 * written out directly in some foreign character set instead of
2736 * using RFC2047 encoding. This is illegal but we will attempt to
2737 * handle it anyway by converting from a user-specified default
2738 * charset to UTF-8 if we see any nonprintable characters.
2741 len = StrLength(DecodeMe);
2742 for (i=0; i<DecodeMe->BufUsed; ++i) {
2743 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2744 illegal_non_rfc2047_encoding = 1;
2749 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2750 if ((illegal_non_rfc2047_encoding) &&
2751 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2752 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2755 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2756 if (ic != (iconv_t)(-1) ) {
2757 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2758 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2759 DecodeMee = DecodedInvalidBuf;
2765 /* pre evaluate the first pair */
2766 nextend = end = NULL;
2767 len = StrLength(DecodeMee);
2768 start = strstr(DecodeMee->buf, "=?");
2769 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2771 end = FindNextEnd (DecodeMee, start);
2773 StrBufAppendBuf(Target, DecodeMee, 0);
2774 FreeStrBuf(&ConvertBuf);
2775 FreeStrBuf(&DecodedInvalidBuf);
2779 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2781 if (start != DecodeMee->buf) {
2784 nFront = start - DecodeMee->buf;
2785 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2789 * Since spammers will go to all sorts of absurd lengths to get their
2790 * messages through, there are LOTS of corrupt headers out there.
2791 * So, prevent a really badly formed RFC2047 header from throwing
2792 * this function into an infinite loop.
2794 while ((start != NULL) &&
2801 DecodeSegment(Target,
2809 next = strstr(end, "=?");
2811 if ((next != NULL) &&
2813 nextend = FindNextEnd(DecodeMee, next);
2814 if (nextend == NULL)
2817 /* did we find two partitions */
2818 if ((next != NULL) &&
2822 while ((ptr < next) &&
2829 * did we find a gab just filled with blanks?
2830 * if not, copy its stuff over.
2834 StrBufAppendBufPlain(Target,
2840 /* our next-pair is our new first pair now. */
2846 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2847 if ((end != NULL) && (end < nextend)) {
2849 while ( (ptr < nextend) &&
2856 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2858 FreeStrBuf(&ConvertBuf);
2859 FreeStrBuf(&ConvertBuf2);
2860 FreeStrBuf(&DecodedInvalidBuf);
2863 /*******************************************************************************
2864 * Manipulating UTF-8 Strings *
2865 *******************************************************************************/
2869 * @brief evaluate the length of an utf8 special character sequence
2870 * @param Char the character to examine
2871 * @returns width of utf8 chars in bytes
2873 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2878 while ((n < 8) && ((test & *CharS) != 0)) {
2882 if ((n > 6) || ((CharE - CharS) < n))
2889 * @brief detect whether this char starts an utf-8 encoded char
2890 * @param Char character to inspect
2891 * @returns yes or no
2893 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2895 /** 11??.???? indicates an UTF8 Sequence. */
2896 return ((Char & 0xC0) != 0);
2901 * @brief measure the number of glyphs in an UTF8 string...
2902 * @param Buf string to measure
2903 * @returns the number of glyphs in Buf
2905 long StrBuf_Utf8StrLen(StrBuf *Buf)
2911 if ((Buf == NULL) || (Buf->BufUsed == 0))
2914 eptr = Buf->buf + Buf->BufUsed;
2915 while ((aptr < eptr) && (*aptr != '\0')) {
2916 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2917 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2918 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2931 * @brief cuts a string after maxlen glyphs
2932 * @param Buf string to cut to maxlen glyphs
2933 * @param maxlen how long may the string become?
2934 * @returns current length of the string
2936 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2942 eptr = Buf->buf + Buf->BufUsed;
2943 while ((aptr < eptr) && (*aptr != '\0')) {
2944 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2945 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2946 while ((*aptr++ != '\0') && (m-- > 0));
2955 Buf->BufUsed = aptr - Buf->buf;
2956 return Buf->BufUsed;
2959 return Buf->BufUsed;
2967 /*******************************************************************************
2969 *******************************************************************************/
2972 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2973 #define OS_CODE 0x03 /*< unix */
2976 * @ingroup StrBuf_DeEnCoder
2977 * @brief uses the same calling syntax as compress2(), but it
2978 * creates a stream compatible with HTTP "Content-encoding: gzip"
2979 * @param dest compressed buffer
2980 * @param destLen length of the compresed data
2981 * @param source source to encode
2982 * @param sourceLen length of source to encode
2983 * @param level compression level
2985 int ZEXPORT compress_gzip(Bytef * dest,
2987 const Bytef * source,
2991 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2993 /* write gzip header */
2994 snprintf((char *) dest, *destLen,
2995 "%c%c%c%c%c%c%c%c%c%c",
2996 gz_magic[0], gz_magic[1], Z_DEFLATED,
2997 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3000 /* normal deflate */
3003 stream.next_in = (Bytef *) source;
3004 stream.avail_in = (uInt) sourceLen;
3005 stream.next_out = dest + 10L; // after header
3006 stream.avail_out = (uInt) * destLen;
3007 if ((uLong) stream.avail_out != *destLen)
3010 stream.zalloc = (alloc_func) 0;
3011 stream.zfree = (free_func) 0;
3012 stream.opaque = (voidpf) 0;
3014 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3015 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3019 err = deflate(&stream, Z_FINISH);
3020 if (err != Z_STREAM_END) {
3021 deflateEnd(&stream);
3022 return err == Z_OK ? Z_BUF_ERROR : err;
3024 *destLen = stream.total_out + 10L;
3026 /* write CRC and Length */
3027 uLong crc = crc32(0L, source, sourceLen);
3029 for (n = 0; n < 4; ++n, ++*destLen) {
3030 dest[*destLen] = (int) (crc & 0xff);
3033 uLong len = stream.total_in;
3034 for (n = 0; n < 4; ++n, ++*destLen) {
3035 dest[*destLen] = (int) (len & 0xff);
3038 err = deflateEnd(&stream);
3045 * @ingroup StrBuf_DeEnCoder
3046 * @brief compress the buffer with gzip
3047 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3048 * @param Buf buffer whose content is to be gzipped
3050 int CompressBuffer(StrBuf *Buf)
3053 char *compressed_data = NULL;
3054 size_t compressed_len, bufsize;
3057 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3058 compressed_data = malloc(compressed_len);
3060 if (compressed_data == NULL)
3062 /* Flush some space after the used payload so valgrind shuts up... */
3063 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3064 Buf->buf[Buf->BufUsed + i++] = '\0';
3065 if (compress_gzip((Bytef *) compressed_data,
3068 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3071 Buf->buf = compressed_data;
3072 Buf->BufUsed = compressed_len;
3073 Buf->BufSize = bufsize;
3074 /* Flush some space after the used payload so valgrind shuts up... */
3076 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3077 Buf->buf[Buf->BufUsed + i++] = '\0';
3080 free(compressed_data);
3082 #endif /* HAVE_ZLIB */
3088 /*******************************************************************************
3089 * File I/O; Prefer buffered read since its faster! *
3090 *******************************************************************************/
3093 * @ingroup StrBuf_IO
3094 * @brief Read a line from socket
3095 * flushes and closes the FD on error
3096 * @param buf the buffer to get the input to
3097 * @param fd pointer to the filedescriptor to read
3098 * @param append Append to an existing string or replace?
3099 * @param Error strerror() on error
3100 * @returns numbers of chars read
3102 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3104 int len, rlen, slen;
3109 slen = len = buf->BufUsed;
3111 rlen = read(*fd, &buf->buf[len], 1);
3113 *Error = strerror(errno);
3120 if (buf->buf[len] == '\n')
3122 if (buf->buf[len] != '\r')
3124 if (len + 2 >= buf->BufSize) {
3126 buf->buf[len+1] = '\0';
3127 IncreaseBuf(buf, 1, -1);
3131 buf->buf[len] = '\0';
3136 * @ingroup StrBuf_BufferedIO
3137 * @brief Read a line from socket
3138 * flushes and closes the FD on error
3139 * @param Line the line to read from the fd / I/O Buffer
3140 * @param buf the buffer to get the input to
3141 * @param fd pointer to the filedescriptor to read
3142 * @param timeout number of successless selects until we bail out
3143 * @param selectresolution how long to wait on each select
3144 * @param Error strerror() on error
3145 * @returns numbers of chars read
3147 int StrBufTCP_read_buffered_line(StrBuf *Line,
3151 int selectresolution,
3155 int nSuccessLess = 0;
3162 if (buf->BufUsed > 0) {
3163 pch = strchr(buf->buf, '\n');
3166 len = pch - buf->buf;
3167 if (len > 0 && (*(pch - 1) == '\r') )
3169 StrBufSub(Line, buf, 0, len - rlen);
3170 StrBufCutLeft(buf, len + 1);
3175 if (buf->BufSize - buf->BufUsed < 10)
3176 IncreaseBuf(buf, 1, -1);
3178 fdflags = fcntl(*fd, F_GETFL);
3179 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3181 while ((nSuccessLess < timeout) && (pch == NULL)) {
3183 tv.tv_sec = selectresolution;
3188 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3189 *Error = strerror(errno);
3195 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3200 &buf->buf[buf->BufUsed],
3201 buf->BufSize - buf->BufUsed - 1);
3203 *Error = strerror(errno);
3208 else if (rlen > 0) {
3210 buf->BufUsed += rlen;
3211 buf->buf[buf->BufUsed] = '\0';
3212 if (buf->BufUsed + 10 > buf->BufSize) {
3213 IncreaseBuf(buf, 1, -1);
3215 pch = strchr(buf->buf, '\n');
3222 len = pch - buf->buf;
3223 if (len > 0 && (*(pch - 1) == '\r') )
3225 StrBufSub(Line, buf, 0, len - rlen);
3226 StrBufCutLeft(buf, len + 1);
3233 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3234 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3235 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3237 * @ingroup StrBuf_BufferedIO
3238 * @brief Read a line from socket
3239 * flushes and closes the FD on error
3240 * @param Line where to append our Line read from the fd / I/O Buffer;
3241 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3242 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3243 * @param fd pointer to the filedescriptor to read
3244 * @param timeout number of successless selects until we bail out
3245 * @param selectresolution how long to wait on each select
3246 * @param Error strerror() on error
3247 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3249 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3254 int selectresolution,
3257 const char *pche = NULL;
3258 const char *pos = NULL;
3260 int len, rlen, retlen;
3261 int nSuccessLess = 0;
3263 const char *pch = NULL;
3269 if ((Line == NULL) ||
3276 *Error = ErrRBLF_PreConditionFailed;
3281 if ((IOBuf->BufUsed > 0) &&
3283 (pos < IOBuf->buf + IOBuf->BufUsed))
3287 pche = IOBuf->buf + IOBuf->BufUsed;
3291 while ((pch < pche) && (*pch != '\n'))
3293 if (Line->BufUsed + 10 > Line->BufSize)
3296 apos = pcht - Line->buf;
3298 IncreaseBuf(Line, 1, -1);
3299 pcht = Line->buf + apos;
3307 if (len > 0 && (*(pch - 1) == '\r') )
3316 if ((pch >= pche) || (*pch == '\0'))
3324 if ((pch != NULL) &&
3327 if (pch + 1 >= pche) {
3340 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3342 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3343 IncreaseBuf(IOBuf, 1, -1);
3345 fdflags = fcntl(*fd, F_GETFL);
3346 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3349 while ((nSuccessLess < timeout) &&
3359 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3360 *Error = strerror(errno);
3364 *Error = ErrRBLF_SelectFailed;
3367 if (! FD_ISSET(*fd, &rfds) != 0) {
3373 &IOBuf->buf[IOBuf->BufUsed],
3374 IOBuf->BufSize - IOBuf->BufUsed - 1);
3376 *Error = strerror(errno);
3381 else if (rlen > 0) {
3383 pLF = IOBuf->buf + IOBuf->BufUsed;
3384 IOBuf->BufUsed += rlen;
3385 IOBuf->buf[IOBuf->BufUsed] = '\0';
3387 pche = IOBuf->buf + IOBuf->BufUsed;
3389 while ((pLF < pche) && (*pLF != '\n'))
3391 if ((pLF >= pche) || (*pLF == '\0'))
3394 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3398 if (pLF != NULL) apos = pLF - IOBuf->buf;
3399 IncreaseBuf(IOBuf, 1, -1);
3400 if (pLF != NULL) pLF = IOBuf->buf + apos;
3410 if (len > 0 && (*(pLF - 1) == '\r') )
3412 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3413 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3419 return retlen + len;
3421 *Error = ErrRBLF_NotEnoughSentFromServer;
3426 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3428 * @ingroup StrBuf_IO
3429 * @brief Input binary data from socket
3430 * flushes and closes the FD on error
3431 * @param Buf the buffer to get the input to
3432 * @param fd pointer to the filedescriptor to read
3433 * @param append Append to an existing string or replace?
3434 * @param nBytes the maximal number of bytes to read
3435 * @param Error strerror() on error
3436 * @returns numbers of chars read
3438 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3441 int len, rlen, slen;
3449 if ((Buf == NULL) || (*fd == -1))
3451 *Error = ErrRBLF_BLOBPreConditionFailed;
3456 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3457 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3459 ptr = Buf->buf + Buf->BufUsed;
3461 slen = len = Buf->BufUsed;
3463 fdflags = fcntl(*fd, F_GETFL);
3464 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3466 while ((nRead < nBytes) &&
3476 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3477 *Error = strerror(errno);
3481 *Error = ErrRBLF_SelectFailed;
3484 if (! FD_ISSET(*fd, &rfds) != 0) {
3490 if ((rlen = read(*fd,
3492 nBytes - nRead)) == -1) {
3495 *Error = strerror(errno);
3500 Buf->BufUsed += rlen;
3502 Buf->buf[Buf->BufUsed] = '\0';
3506 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3507 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3509 * @ingroup StrBuf_BufferedIO
3510 * @brief Input binary data from socket
3511 * flushes and closes the FD on error
3512 * @param Blob put binary thing here
3513 * @param IOBuf the buffer to get the input to
3514 * @param Pos offset inside of IOBuf
3515 * @param fd pointer to the filedescriptor to read
3516 * @param append Append to an existing string or replace?
3517 * @param nBytes the maximal number of bytes to read
3518 * @param check whether we should search for '000\n' terminators in case of timeouts
3519 * @param Error strerror() on error
3520 * @returns numbers of chars read
3522 int StrBufReadBLOBBuffered(StrBuf *Blob,
3537 int nAlreadyRead = 0;
3543 int nSuccessLess = 0;
3546 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3550 *Error = ErrRBB_BLOBFPreConditionFailed;
3556 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3557 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3562 len = pos - IOBuf->buf;
3563 rlen = IOBuf->BufUsed - len;
3566 if ((IOBuf->BufUsed > 0) &&
3568 (pos < IOBuf->buf + IOBuf->BufUsed))
3570 pche = IOBuf->buf + IOBuf->BufUsed;
3573 if (rlen < nBytes) {
3574 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3575 Blob->BufUsed += rlen;
3576 Blob->buf[Blob->BufUsed] = '\0';
3577 nAlreadyRead = nRead = rlen;
3580 if (rlen >= nBytes) {
3581 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3582 Blob->BufUsed += nBytes;
3583 Blob->buf[Blob->BufUsed] = '\0';
3584 if (rlen == nBytes) {
3596 if (IOBuf->BufSize < nBytes - nRead)
3597 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3600 slen = len = Blob->BufUsed;
3602 fdflags = fcntl(*fd, F_GETFL);
3603 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3611 while ((nSuccessLess < MaxTries) &&
3621 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3622 *Error = strerror(errno);
3626 *Error = ErrRBLF_SelectFailed;
3629 if (! FD_ISSET(*fd, &rfds) != 0) {
3640 *Error = strerror(errno);
3643 else if (rlen == 0){
3644 if ((check == NNN_TERM) &&
3646 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3648 StrBufPlain(Blob, HKEY("\n000\n"));
3649 StrBufCutRight(Blob, 5);
3650 return Blob->BufUsed;
3652 else if (!IsNonBlock)
3654 else if (nSuccessLess > MaxTries) {
3656 *Error = ErrRBB_too_many_selects;
3660 else if (rlen > 0) {
3664 IOBuf->BufUsed += rlen;
3667 if (nSuccessLess >= MaxTries) {
3669 *Error = ErrRBB_too_many_selects;
3673 if (nRead > nBytes) {
3674 *Pos = IOBuf->buf + nBytes;
3676 Blob->buf[Blob->BufUsed] = '\0';
3677 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3681 return nRead + nAlreadyRead;
3685 * @ingroup StrBuf_IO
3686 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3687 * @param LineBuf your line will be copied here.
3688 * @param Buf BLOB with lines of text...
3689 * @param Ptr moved arround to keep the next-line across several iterations
3690 * has to be &NULL on start; will be &NotNULL on end of buffer
3691 * @returns size of copied buffer
3693 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3695 const char *aptr, *ptr, *eptr;
3698 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3699 *Ptr = StrBufNOTNULL;
3703 FlushStrBuf(LineBuf);
3705 ptr = aptr = Buf->buf;
3709 optr = LineBuf->buf;
3710 eptr = Buf->buf + Buf->BufUsed;
3711 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3713 while ((ptr <= eptr) &&
3720 LineBuf->BufUsed = optr - LineBuf->buf;
3721 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3722 optr = LineBuf->buf + LineBuf->BufUsed;
3723 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3727 if ((ptr >= eptr) && (optr > LineBuf->buf))
3729 LineBuf->BufUsed = optr - LineBuf->buf;
3731 if ((ptr <= eptr) && (*ptr == '\r'))
3733 if ((ptr <= eptr) && (*ptr == '\n'))
3740 *Ptr = StrBufNOTNULL;
3743 return Buf->BufUsed - (ptr - Buf->buf);
3748 * @ingroup StrBuf_IO
3749 * @brief removes double slashes from pathnames
3750 * @param Dir directory string to filter
3751 * @param RemoveTrailingSlash allows / disallows trailing slashes
3753 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3759 while (!IsEmptyStr(a)) {
3771 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3776 Dir->BufUsed = b - Dir->buf;