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 / increase an _EMPTY_ buffer 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)
297 (Buf->BufUsed == 0) &&
298 (Buf->BufSize < ThreshHold)) {
300 Buf->buf = (char*) malloc(NewSize);
302 Buf->BufSize = NewSize;
307 * @ingroup StrBuf_DeConstructors
308 * @brief shrink long term buffers to their real size so they don't waste memory
309 * @param Buf buffer to shrink
310 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
311 * @returns physical size of the buffer
313 long StrBufShrinkToFit(StrBuf *Buf, int Force)
318 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
320 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
321 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
322 Buf->BufSize = Buf->BufUsed + 1;
330 * @ingroup StrBuf_DeConstructors
331 * @brief Allocate a new buffer with default buffer size
332 * @returns the new stringbuffer
334 StrBuf* NewStrBuf(void)
338 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
339 NewBuf->buf = (char*) malloc(BaseStrBufSize);
340 NewBuf->buf[0] = '\0';
341 NewBuf->BufSize = BaseStrBufSize;
343 NewBuf->ConstBuf = 0;
351 * @ingroup StrBuf_DeConstructors
352 * @brief Copy Constructor; returns a duplicate of CopyMe
353 * @param CopyMe Buffer to faxmilate
354 * @returns the new stringbuffer
356 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
363 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
364 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
365 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
366 NewBuf->BufUsed = CopyMe->BufUsed;
367 NewBuf->BufSize = CopyMe->BufSize;
368 NewBuf->ConstBuf = 0;
376 * @ingroup StrBuf_DeConstructors
377 * @brief create a new Buffer using an existing c-string
378 * this function should also be used if you want to pre-suggest
379 * the buffer size to allocate in conjunction with ptr == NULL
380 * @param ptr the c-string to copy; may be NULL to create a blank instance
381 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
382 * @returns the new stringbuffer
384 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
387 size_t Siz = BaseStrBufSize;
390 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
392 CopySize = strlen((ptr != NULL)?ptr:"");
396 while (Siz <= CopySize)
399 NewBuf->buf = (char*) malloc(Siz);
400 NewBuf->BufSize = Siz;
402 memcpy(NewBuf->buf, ptr, CopySize);
403 NewBuf->buf[CopySize] = '\0';
404 NewBuf->BufUsed = CopySize;
407 NewBuf->buf[0] = '\0';
410 NewBuf->ConstBuf = 0;
418 * @ingroup StrBuf_DeConstructors
419 * @brief Set an existing buffer from a c-string
420 * @param Buf buffer to load
421 * @param ptr c-string to put into
422 * @param nChars set to -1 if we should work 0-terminated
423 * @returns the new length of the string
425 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
440 CopySize = strlen(ptr);
444 while (Siz <= CopySize)
447 if (Siz != Buf->BufSize)
448 IncreaseBuf(Buf, 0, Siz);
449 memcpy(Buf->buf, ptr, CopySize);
450 Buf->buf[CopySize] = '\0';
451 Buf->BufUsed = CopySize;
458 * @ingroup StrBuf_DeConstructors
459 * @brief use strbuf as wrapper for a string constant for easy handling
460 * @param StringConstant a string to wrap
461 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
463 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
467 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
468 NewBuf->buf = (char*) StringConstant;
469 NewBuf->BufSize = SizeOfStrConstant;
470 NewBuf->BufUsed = SizeOfStrConstant;
471 NewBuf->ConstBuf = 1;
480 * @ingroup StrBuf_DeConstructors
481 * @brief flush the content of a Buf; keep its struct
482 * @param buf Buffer to flush
484 int FlushStrBuf(StrBuf *buf)
496 * @ingroup StrBuf_DeConstructors
497 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
498 * @param buf Buffer to wipe
500 int FLUSHStrBuf(StrBuf *buf)
506 if (buf->BufUsed > 0) {
507 memset(buf->buf, 0, buf->BufUsed);
514 int hFreeDbglog = -1;
517 * @ingroup StrBuf_DeConstructors
518 * @brief Release a Buffer
519 * Its a double pointer, so it can NULL your pointer
520 * so fancy SIG11 appear instead of random results
521 * @param FreeMe Pointer Pointer to the buffer to free
523 void FreeStrBuf (StrBuf **FreeMe)
528 dbg_FreeStrBuf(FreeMe, 'F');
530 if (!(*FreeMe)->ConstBuf)
531 free((*FreeMe)->buf);
537 * @ingroup StrBuf_DeConstructors
538 * @brief flatten a Buffer to the Char * we return
539 * Its a double pointer, so it can NULL your pointer
540 * so fancy SIG11 appear instead of random results
541 * The Callee then owns the buffer and is responsible for freeing it.
542 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
543 * @returns the pointer of the buffer; Callee owns the memory thereafter.
545 char *SmashStrBuf (StrBuf **SmashMe)
549 if ((SmashMe == NULL) || (*SmashMe == NULL))
552 dbg_FreeStrBuf(SmashMe, 'S');
554 Ret = (*SmashMe)->buf;
561 * @ingroup StrBuf_DeConstructors
562 * @brief Release the buffer
563 * If you want put your StrBuf into a Hash, use this as Destructor.
564 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
566 void HFreeStrBuf (void *VFreeMe)
568 StrBuf *FreeMe = (StrBuf*)VFreeMe;
572 dbg_FreeStrBuf(SmashMe, 'H');
574 if (!FreeMe->ConstBuf)
580 /*******************************************************************************
581 * Simple string transformations *
582 *******************************************************************************/
586 * @brief Wrapper around atol
588 long StrTol(const StrBuf *Buf)
593 return atol(Buf->buf);
600 * @brief Wrapper around atoi
602 int StrToi(const StrBuf *Buf)
606 if (Buf->BufUsed > 0)
607 return atoi(Buf->buf);
614 * @brief Checks to see if the string is a pure number
615 * @param Buf The buffer to inspect
616 * @returns 1 if its a pure number, 0, if not.
618 int StrBufIsNumber(const StrBuf *Buf) {
620 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
623 strtoll(Buf->buf, &pEnd, 10);
624 if (pEnd == Buf->buf)
626 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
628 if (Buf->buf == pEnd)
634 * @ingroup StrBuf_Filler
635 * @brief modifies a Single char of the Buf
636 * You can point to it via char* or a zero-based integer
637 * @param Buf The buffer to manipulate
638 * @param ptr char* to zero; use NULL if unused
639 * @param nThChar zero based pointer into the string; use -1 if unused
640 * @param PeekValue The Character to place into the position
642 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
647 nThChar = ptr - Buf->buf;
648 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
650 Buf->buf[nThChar] = PeekValue;
655 * @ingroup StrBuf_Filler
656 * @brief modifies a range of chars of the Buf
657 * You can point to it via char* or a zero-based integer
658 * @param Buf The buffer to manipulate
659 * @param ptr char* to zero; use NULL if unused
660 * @param nThChar zero based pointer into the string; use -1 if unused
661 * @param nChars how many chars are to be flushed?
662 * @param PookValue The Character to place into that area
664 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
669 nThChar = ptr - Buf->buf;
670 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
672 if (nThChar + nChars > Buf->BufUsed)
673 nChars = Buf->BufUsed - nThChar;
675 memset(Buf->buf + nThChar, PookValue, nChars);
676 /* just to be shure... */
677 Buf->buf[Buf->BufUsed] = 0;
682 * @ingroup StrBuf_Filler
683 * @brief Append a StringBuffer to the buffer
684 * @param Buf Buffer to modify
685 * @param AppendBuf Buffer to copy at the end of our buffer
686 * @param Offset Should we start copying from an offset?
688 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
690 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
693 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
696 AppendBuf->BufUsed + Buf->BufUsed);
698 memcpy(Buf->buf + Buf->BufUsed,
699 AppendBuf->buf + Offset,
700 AppendBuf->BufUsed - Offset);
701 Buf->BufUsed += AppendBuf->BufUsed - Offset;
702 Buf->buf[Buf->BufUsed] = '\0';
707 * @ingroup StrBuf_Filler
708 * @brief Append a C-String to the buffer
709 * @param Buf Buffer to modify
710 * @param AppendBuf Buffer to copy at the end of our buffer
711 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
712 * @param Offset Should we start copying from an offset?
714 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
717 long BufSizeRequired;
719 if ((AppendBuf == NULL) || (Buf == NULL))
723 aps = strlen(AppendBuf + Offset);
725 aps = AppendSize - Offset;
727 BufSizeRequired = Buf->BufUsed + aps + 1;
728 if (Buf->BufSize <= BufSizeRequired)
729 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
731 memcpy(Buf->buf + Buf->BufUsed,
735 Buf->buf[Buf->BufUsed] = '\0';
739 * @ingroup StrBuf_Filler
740 * @brief sprintf like function appending the formated string to the buffer
741 * vsnprintf version to wrap into own calls
742 * @param Buf Buffer to extend by format and Params
743 * @param format printf alike format to add
744 * @param ap va_list containing the items for format
746 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
754 if ((Buf == NULL) || (format == NULL))
757 BufSize = Buf->BufSize;
758 nWritten = Buf->BufSize + 1;
759 Offset = Buf->BufUsed;
760 newused = Offset + nWritten;
762 while (newused >= BufSize) {
764 nWritten = vsnprintf(Buf->buf + Offset,
765 Buf->BufSize - Offset,
768 newused = Offset + nWritten;
769 if (newused >= Buf->BufSize) {
770 IncreaseBuf(Buf, 1, newused);
771 newused = Buf->BufSize + 1;
774 Buf->BufUsed = Offset + nWritten;
775 BufSize = Buf->BufSize;
782 * @ingroup StrBuf_Filler
783 * @brief sprintf like function appending the formated string to the buffer
784 * @param Buf Buffer to extend by format and Params
785 * @param format printf alike format to add
787 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
795 if ((Buf == NULL) || (format == NULL))
798 BufSize = Buf->BufSize;
799 nWritten = Buf->BufSize + 1;
800 Offset = Buf->BufUsed;
801 newused = Offset + nWritten;
803 while (newused >= BufSize) {
804 va_start(arg_ptr, format);
805 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
806 Buf->BufSize - Buf->BufUsed,
809 newused = Buf->BufUsed + nWritten;
810 if (newused >= Buf->BufSize) {
811 IncreaseBuf(Buf, 1, newused);
812 newused = Buf->BufSize + 1;
815 Buf->BufUsed += nWritten;
816 BufSize = Buf->BufSize;
823 * @ingroup StrBuf_Filler
824 * @brief sprintf like function putting the formated string into the buffer
825 * @param Buf Buffer to extend by format and Parameters
826 * @param format printf alike format to add
828 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
833 if ((Buf == NULL) || (format == NULL))
836 nWritten = Buf->BufSize + 1;
837 while (nWritten >= Buf->BufSize) {
838 va_start(arg_ptr, format);
839 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
841 if (nWritten >= Buf->BufSize) {
842 IncreaseBuf(Buf, 0, 0);
843 nWritten = Buf->BufSize + 1;
846 Buf->BufUsed = nWritten ;
851 * @ingroup StrBuf_Filler
852 * @brief Callback for cURL to append the webserver reply to a buffer
853 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
854 * @param size pre-defined by the cURL API; see man 3 curl for mre info
855 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
856 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
858 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
867 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
874 * @brief extracts a substring from Source into dest
875 * @param dest buffer to place substring into
876 * @param Source string to copy substring from
877 * @param Offset chars to skip from start
878 * @param nChars number of chars to copy
879 * @returns the number of chars copied; may be different from nChars due to the size of Source
881 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
884 if (Offset > Source->BufUsed)
890 if (Offset + nChars < Source->BufUsed)
892 if (nChars >= dest->BufSize)
893 IncreaseBuf(dest, 0, nChars + 1);
894 memcpy(dest->buf, Source->buf + Offset, nChars);
895 dest->BufUsed = nChars;
896 dest->buf[dest->BufUsed] = '\0';
899 NCharsRemain = Source->BufUsed - Offset;
900 if (NCharsRemain >= dest->BufSize)
901 IncreaseBuf(dest, 0, NCharsRemain + 1);
902 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
903 dest->BufUsed = NCharsRemain;
904 dest->buf[dest->BufUsed] = '\0';
910 * @brief Cut nChars from the start of the string
911 * @param Buf Buffer to modify
912 * @param nChars how many chars should be skipped?
914 void StrBufCutLeft(StrBuf *Buf, int nChars)
916 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
917 if (nChars >= Buf->BufUsed) {
921 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
922 Buf->BufUsed -= nChars;
923 Buf->buf[Buf->BufUsed] = '\0';
928 * @brief Cut the trailing n Chars from the string
929 * @param Buf Buffer to modify
930 * @param nChars how many chars should be trunkated?
932 void StrBufCutRight(StrBuf *Buf, int nChars)
934 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
935 if (nChars >= Buf->BufUsed) {
939 Buf->BufUsed -= nChars;
940 Buf->buf[Buf->BufUsed] = '\0';
945 * @brief Cut the string after n Chars
946 * @param Buf Buffer to modify
947 * @param AfternChars after how many chars should we trunkate the string?
948 * @param At if non-null and points inside of our string, cut it there.
950 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
952 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
954 AfternChars = At - Buf->buf;
957 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
959 Buf->BufUsed = AfternChars;
960 Buf->buf[Buf->BufUsed] = '\0';
966 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
967 * @param Buf the string to modify
969 void StrBufTrim(StrBuf *Buf)
972 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
974 while ((Buf->BufUsed > 0) &&
975 isspace(Buf->buf[Buf->BufUsed - 1]))
979 Buf->buf[Buf->BufUsed] = '\0';
981 if (Buf->BufUsed == 0) return;
983 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
986 if (delta > 0) StrBufCutLeft(Buf, delta);
989 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
997 pLeft = pBuff = Buf->buf;
998 while (pBuff != NULL) {
1000 pBuff = strchr(pBuff, leftboundary);
1009 pRight = strchr(pBuff, rightboundary);
1011 StrBufCutAt(Buf, 0, pRight);
1013 StrBufCutLeft(Buf, pLeft - Buf->buf);
1018 * @ingroup StrBuf_Filler
1019 * @brief uppercase the contents of a buffer
1020 * @param Buf the buffer to translate
1022 void StrBufUpCase(StrBuf *Buf)
1026 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1029 pche = pch + Buf->BufUsed;
1030 while (pch < pche) {
1031 *pch = toupper(*pch);
1038 * @ingroup StrBuf_Filler
1039 * @brief lowercase the contents of a buffer
1040 * @param Buf the buffer to translate
1042 void StrBufLowerCase(StrBuf *Buf)
1046 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1049 pche = pch + Buf->BufUsed;
1050 while (pch < pche) {
1051 *pch = tolower(*pch);
1057 /*******************************************************************************
1058 * a tokenizer that kills, maims, and destroys *
1059 *******************************************************************************/
1062 * @ingroup StrBuf_Tokenizer
1063 * @brief Replace a token at a given place with a given length by another token with given length
1064 * @param Buf String where to work on
1065 * @param where where inside of the Buf is the search-token
1066 * @param HowLong How long is the token to be replaced
1067 * @param Repl Token to insert at 'where'
1068 * @param ReplLen Length of repl
1069 * @returns -1 if fail else length of resulting Buf
1071 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1072 const char *Repl, long ReplLen)
1075 if ((Buf == NULL) ||
1076 (where > Buf->BufUsed) ||
1077 (where + HowLong > Buf->BufUsed))
1080 if (where + ReplLen - HowLong > Buf->BufSize)
1081 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1084 memmove(Buf->buf + where + ReplLen,
1085 Buf->buf + where + HowLong,
1086 Buf->BufUsed - where - HowLong);
1088 memcpy(Buf->buf + where,
1091 Buf->BufUsed += ReplLen - HowLong;
1093 return Buf->BufUsed;
1097 * @ingroup StrBuf_Tokenizer
1098 * @brief Counts the numbmer of tokens in a buffer
1099 * @param source String to count tokens in
1100 * @param tok Tokenizer char to count
1101 * @returns numbers of tokenizer chars found
1103 int StrBufNum_tokens(const StrBuf *source, char tok)
1107 if ((source == NULL) || (source->BufUsed == 0))
1109 if ((source->BufUsed == 1) && (*source->buf == tok))
1113 pche = pch + source->BufUsed;
1124 * @ingroup StrBuf_Tokenizer
1125 * @brief a string tokenizer
1126 * @param Source StringBuffer to read into
1127 * @param parmnum n'th Parameter to remove
1128 * @param separator tokenizer character
1129 * @returns -1 if not found, else length of token.
1131 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1134 char *d, *s, *end; /* dest, source */
1137 /* Find desired @parameter */
1138 end = Source->buf + Source->BufUsed;
1140 while ((d <= end) &&
1143 /* End of string, bail! */
1148 if (*d == separator) {
1153 if ((d == NULL) || (d >= end))
1154 return 0; /* @Parameter not found */
1156 /* Find next @parameter */
1158 while ((s <= end) &&
1159 (*s && *s != separator))
1163 if (*s == separator)
1167 /* Hack and slash */
1172 memmove(d, s, Source->BufUsed - (s - Source->buf));
1173 Source->BufUsed += ReducedBy;
1174 Source->buf[Source->BufUsed] = '\0';
1176 else if (d == Source->buf) {
1178 Source->BufUsed = 0;
1182 Source->BufUsed += ReducedBy;
1195 * @ingroup StrBuf_Tokenizer
1196 * @brief a string tokenizer
1197 * @param dest Destination StringBuffer
1198 * @param Source StringBuffer to read into
1199 * @param parmnum n'th Parameter to extract
1200 * @param separator tokenizer character
1201 * @returns -1 if not found, else length of token.
1203 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1205 const char *s, *e; //* source * /
1206 int len = 0; //* running total length of extracted string * /
1207 int current_token = 0; //* token currently being processed * /
1210 dest->buf[0] = '\0';
1216 if ((Source == NULL) || (Source->BufUsed ==0)) {
1220 e = s + Source->BufUsed;
1223 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1225 while ((s<e) && !IsEmptyStr(s)) {
1226 if (*s == separator) {
1229 if (len >= dest->BufSize) {
1230 dest->BufUsed = len;
1231 if (IncreaseBuf(dest, 1, -1) < 0) {
1236 if ( (current_token == parmnum) &&
1237 (*s != separator)) {
1238 dest->buf[len] = *s;
1241 else if (current_token > parmnum) {
1247 dest->buf[len] = '\0';
1248 dest->BufUsed = len;
1250 if (current_token < parmnum) {
1251 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1254 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1263 * @ingroup StrBuf_Tokenizer
1264 * @brief a string tokenizer to fetch an integer
1265 * @param Source String containing tokens
1266 * @param parmnum n'th Parameter to extract
1267 * @param separator tokenizer character
1268 * @returns 0 if not found, else integer representation of the token
1270 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1280 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1287 * @ingroup StrBuf_Tokenizer
1288 * @brief a string tokenizer to fetch a long integer
1289 * @param Source String containing tokens
1290 * @param parmnum n'th Parameter to extract
1291 * @param separator tokenizer character
1292 * @returns 0 if not found, else long integer representation of the token
1294 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1304 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1312 * @ingroup StrBuf_Tokenizer
1313 * @brief a string tokenizer to fetch an unsigned long
1314 * @param Source String containing tokens
1315 * @param parmnum n'th Parameter to extract
1316 * @param separator tokenizer character
1317 * @returns 0 if not found, else unsigned long representation of the token
1319 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1330 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1334 return (unsigned long) atol(pnum);
1343 * @ingroup StrBuf_NextTokenizer
1344 * @brief a string tokenizer; Bounds checker
1345 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1346 * @param Source our tokenbuffer
1347 * @param pStart the token iterator pointer to inspect
1348 * @returns whether the revolving pointer is inside of the search range
1350 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1352 if ((Source == NULL) ||
1353 (*pStart == StrBufNOTNULL) ||
1354 (Source->BufUsed == 0))
1358 if (*pStart == NULL)
1362 else if (*pStart > Source->buf + Source->BufUsed)
1366 else if (*pStart <= Source->buf)
1375 * @ingroup StrBuf_NextTokenizer
1376 * @brief a string tokenizer
1377 * @param dest Destination StringBuffer
1378 * @param Source StringBuffer to read into
1379 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1380 * @param separator tokenizer
1381 * @returns -1 if not found, else length of token.
1383 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1385 const char *s; /* source */
1386 const char *EndBuffer; /* end stop of source buffer */
1387 int current_token = 0; /* token currently being processed */
1388 int len = 0; /* running total length of extracted string */
1390 if ((Source == NULL) ||
1391 (Source->BufUsed == 0) )
1393 *pStart = StrBufNOTNULL;
1397 EndBuffer = Source->buf + Source->BufUsed;
1401 dest->buf[0] = '\0';
1406 *pStart = EndBuffer + 1;
1410 if (*pStart == NULL)
1412 *pStart = Source->buf; /* we're starting to examine this buffer. */
1414 else if ((*pStart < Source->buf) ||
1415 (*pStart > EndBuffer ) )
1417 return -1; /* no more tokens to find. */
1421 /* start to find the next token */
1422 while ((s <= EndBuffer) &&
1423 (current_token == 0) )
1425 if (*s == separator)
1427 /* we found the next token */
1431 if (len >= dest->BufSize)
1433 /* our Dest-buffer isn't big enough, increase it. */
1434 dest->BufUsed = len;
1436 if (IncreaseBuf(dest, 1, -1) < 0) {
1437 /* WHUT? no more mem? bail out. */
1444 if ( (current_token == 0 ) && /* are we in our target token? */
1445 (!IsEmptyStr(s) ) &&
1446 (separator != *s) ) /* don't copy the token itself */
1448 dest->buf[len] = *s; /* Copy the payload */
1449 ++len; /* remember the bigger size. */
1455 /* did we reach the end? */
1456 if ((s > EndBuffer)) {
1457 EndBuffer = StrBufNOTNULL;
1458 *pStart = EndBuffer;
1461 *pStart = s; /* remember the position for the next run */
1464 /* sanitize our extracted token */
1465 dest->buf[len] = '\0';
1466 dest->BufUsed = len;
1473 * @ingroup StrBuf_NextTokenizer
1474 * @brief a string tokenizer
1475 * @param Source StringBuffer to read from
1476 * @param pStart pointer to the end of the last token. Feed with NULL.
1477 * @param separator tokenizer character
1478 * @param nTokens number of tokens to fastforward over
1479 * @returns -1 if not found, else length of token.
1481 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1483 const char *s, *EndBuffer; //* source * /
1484 int len = 0; //* running total length of extracted string * /
1485 int current_token = 0; //* token currently being processed * /
1487 if ((Source == NULL) ||
1488 (Source->BufUsed ==0)) {
1492 return Source->BufUsed;
1494 if (*pStart == NULL)
1495 *pStart = Source->buf;
1497 EndBuffer = Source->buf + Source->BufUsed;
1499 if ((*pStart < Source->buf) ||
1500 (*pStart > EndBuffer)) {
1508 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1510 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1511 if (*s == separator) {
1514 if (current_token >= nTokens) {
1526 * @ingroup StrBuf_NextTokenizer
1527 * @brief a string tokenizer to fetch an integer
1528 * @param Source StringBuffer to read from
1529 * @param pStart Cursor on the tokenstring
1530 * @param separator tokenizer character
1531 * @returns 0 if not found, else integer representation of the token
1533 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1543 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1550 * @ingroup StrBuf_NextTokenizer
1551 * @brief a string tokenizer to fetch a long integer
1552 * @param Source StringBuffer to read from
1553 * @param pStart Cursor on the tokenstring
1554 * @param separator tokenizer character
1555 * @returns 0 if not found, else long integer representation of the token
1557 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1567 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1575 * @ingroup StrBuf_NextTokenizer
1576 * @brief a string tokenizer to fetch an unsigned long
1577 * @param Source StringBuffer to read from
1578 * @param pStart Cursor on the tokenstring
1579 * @param separator tokenizer character
1580 * @returns 0 if not found, else unsigned long representation of the token
1582 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1593 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1597 return (unsigned long) atol(pnum);
1607 /*******************************************************************************
1608 * Escape Appending *
1609 *******************************************************************************/
1612 * @ingroup StrBuf_DeEnCoder
1613 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1614 * @param OutBuf the output buffer
1615 * @param In Buffer to encode
1616 * @param PlainIn way in from plain old c strings
1618 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1620 const char *pch, *pche;
1624 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1626 if (PlainIn != NULL) {
1627 len = strlen(PlainIn);
1633 pche = pch + In->BufUsed;
1640 pt = OutBuf->buf + OutBuf->BufUsed;
1641 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1643 while (pch < pche) {
1645 IncreaseBuf(OutBuf, 1, -1);
1646 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1647 pt = OutBuf->buf + OutBuf->BufUsed;
1650 if((*pch >= 'a' && *pch <= 'z') ||
1651 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1652 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1653 (*pch == '!') || (*pch == '_') ||
1654 (*pch == ',') || (*pch == '.'))
1661 *(pt + 1) = HexList[(unsigned char)*pch][0];
1662 *(pt + 2) = HexList[(unsigned char)*pch][1];
1664 OutBuf->BufUsed += 3;
1672 * @ingroup StrBuf_DeEnCoder
1673 * @brief append a string in hex encoding to the buffer
1674 * @param OutBuf the output buffer
1675 * @param In Buffer to encode
1676 * @param PlainIn way in from plain old c strings
1678 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1680 const char *pch, *pche;
1684 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1686 if (PlainIn != NULL) {
1687 len = strlen(PlainIn);
1693 pche = pch + In->BufUsed;
1700 pt = OutBuf->buf + OutBuf->BufUsed;
1701 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1703 while (pch < pche) {
1705 IncreaseBuf(OutBuf, 1, -1);
1706 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1707 pt = OutBuf->buf + OutBuf->BufUsed;
1710 *pt = HexList[(unsigned char)*pch][0];
1712 *pt = HexList[(unsigned char)*pch][1];
1713 pt ++; pch ++; OutBuf->BufUsed += 2;
1719 * @ingroup StrBuf_DeEnCoder
1720 * @brief Append a string, escaping characters which have meaning in HTML.
1722 * @param Target target buffer
1723 * @param Source source buffer; set to NULL if you just have a C-String
1724 * @param PlainIn Plain-C string to append; set to NULL if unused
1725 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1726 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1727 * if set to 2, linebreaks are replaced by <br/>
1729 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1731 const char *aptr, *eiptr;
1735 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1738 if (PlainIn != NULL) {
1740 len = strlen(PlainIn);
1745 eiptr = aptr + Source->BufUsed;
1746 len = Source->BufUsed;
1752 bptr = Target->buf + Target->BufUsed;
1753 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1755 while (aptr < eiptr){
1757 IncreaseBuf(Target, 1, -1);
1758 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1759 bptr = Target->buf + Target->BufUsed;
1762 memcpy(bptr, "<", 4);
1764 Target->BufUsed += 4;
1766 else if (*aptr == '>') {
1767 memcpy(bptr, ">", 4);
1769 Target->BufUsed += 4;
1771 else if (*aptr == '&') {
1772 memcpy(bptr, "&", 5);
1774 Target->BufUsed += 5;
1776 else if (*aptr == '"') {
1777 memcpy(bptr, """, 6);
1779 Target->BufUsed += 6;
1781 else if (*aptr == '\'') {
1782 memcpy(bptr, "'", 5);
1784 Target->BufUsed += 5;
1786 else if (*aptr == LB) {
1791 else if (*aptr == RB) {
1796 else if (*aptr == QU) {
1801 else if ((*aptr == 32) && (nbsp == 1)) {
1802 memcpy(bptr, " ", 6);
1804 Target->BufUsed += 6;
1806 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1807 *bptr='\0'; /* nothing */
1809 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1810 memcpy(bptr, "<br/>", 11);
1812 Target->BufUsed += 11;
1816 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1817 *bptr='\0'; /* nothing */
1827 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1829 return Target->BufUsed;
1833 * @ingroup StrBuf_DeEnCoder
1834 * @brief Append a string, escaping characters which have meaning in HTML.
1835 * Converts linebreaks into blanks; escapes single quotes
1836 * @param Target target buffer
1837 * @param Source source buffer; set to NULL if you just have a C-String
1838 * @param PlainIn Plain-C string to append; set to NULL if unused
1840 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1842 const char *aptr, *eiptr;
1846 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1849 if (PlainIn != NULL) {
1851 len = strlen(PlainIn);
1856 eiptr = aptr + Source->BufUsed;
1857 len = Source->BufUsed;
1863 eptr = Target->buf + Target->BufSize - 8;
1864 tptr = Target->buf + Target->BufUsed;
1866 while (aptr < eiptr){
1868 IncreaseBuf(Target, 1, -1);
1869 eptr = Target->buf + Target->BufSize - 8;
1870 tptr = Target->buf + Target->BufUsed;
1873 if (*aptr == '\n') {
1877 else if (*aptr == '\r') {
1881 else if (*aptr == '\'') {
1887 Target->BufUsed += 5;
1900 * @ingroup StrBuf_DeEnCoder
1901 * @brief Append a string, escaping characters which have meaning in ICAL.
1903 * @param Target target buffer
1904 * @param Source source buffer; set to NULL if you just have a C-String
1905 * @param PlainIn Plain-C string to append; set to NULL if unused
1907 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1909 const char *aptr, *eiptr;
1913 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1916 if (PlainIn != NULL) {
1918 len = strlen(PlainIn);
1923 eiptr = aptr + Source->BufUsed;
1924 len = Source->BufUsed;
1930 eptr = Target->buf + Target->BufSize - 8;
1931 tptr = Target->buf + Target->BufUsed;
1933 while (aptr < eiptr){
1934 if(tptr + 3 >= eptr) {
1935 IncreaseBuf(Target, 1, -1);
1936 eptr = Target->buf + Target->BufSize - 8;
1937 tptr = Target->buf + Target->BufUsed;
1940 if (*aptr == '\n') {
1947 else if (*aptr == '\r') {
1954 else if (*aptr == ',') {
1970 * @ingroup StrBuf_DeEnCoder
1971 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1973 * @param Target target buffer
1974 * @param Source source buffer; set to NULL if you just have a C-String
1975 * @param PlainIn Plain-C string to append; set to NULL if unused
1976 * @returns size of result or -1
1978 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1980 const char *aptr, *eiptr;
1984 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1987 if (PlainIn != NULL) {
1989 len = strlen(PlainIn);
1994 eiptr = aptr + Source->BufUsed;
1995 len = Source->BufUsed;
2001 bptr = Target->buf + Target->BufUsed;
2002 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
2004 while (aptr < eiptr){
2006 IncreaseBuf(Target, 1, -1);
2007 eptr = Target->buf + Target->BufSize - 3;
2008 bptr = Target->buf + Target->BufUsed;
2015 Target->BufUsed += 2;
2016 } else if (*aptr == '\\') {
2021 Target->BufUsed += 2;
2031 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2033 return Target->BufUsed;
2037 * @ingroup StrBuf_DeEnCoder
2038 * @brief Append a string, escaping characters which have meaning in HTML + json.
2040 * @param Target target buffer
2041 * @param Source source buffer; set to NULL if you just have a C-String
2042 * @param PlainIn Plain-C string to append; set to NULL if unused
2043 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2044 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2045 * if set to 2, linebreaks are replaced by <br/>
2047 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2049 const char *aptr, *eiptr;
2052 int IsUtf8Sequence = 0;
2054 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2057 if (PlainIn != NULL) {
2059 len = strlen(PlainIn);
2064 eiptr = aptr + Source->BufUsed;
2065 len = Source->BufUsed;
2071 bptr = Target->buf + Target->BufUsed;
2072 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2074 while (aptr < eiptr){
2076 IncreaseBuf(Target, 1, -1);
2077 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2078 bptr = Target->buf + Target->BufUsed;
2081 memcpy(bptr, "<", 4);
2083 Target->BufUsed += 4;
2085 else if (*aptr == '>') {
2086 memcpy(bptr, ">", 4);
2088 Target->BufUsed += 4;
2090 else if (*aptr == '&') {
2091 memcpy(bptr, "&", 5);
2093 Target->BufUsed += 5;
2095 else if (*aptr == LB) {
2100 else if (*aptr == RB) {
2105 else if ((*aptr == 32) && (nbsp == 1)) {
2106 memcpy(bptr, " ", 6);
2108 Target->BufUsed += 6;
2110 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2111 *bptr='\0'; /* nothing */
2113 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2114 memcpy(bptr, "<br/>", 11);
2116 Target->BufUsed += 11;
2119 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2120 *bptr='\0'; /* nothing */
2123 else if ((*aptr == '"') || (*aptr == QU)) {
2128 Target->BufUsed += 2;
2129 } else if (*aptr == '\\') {
2134 Target->BufUsed += 2;
2137 if (((unsigned char)*aptr) >= 0x20)
2139 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2143 while (IsUtf8Sequence > 1){
2144 if(bptr + IsUtf8Sequence >= eptr) {
2145 IncreaseBuf(Target, 1, -1);
2146 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2147 bptr = Target->buf + Target->BufUsed - 1;
2161 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2163 return Target->BufUsed;
2167 * @ingroup StrBuf_DeEnCoder
2168 * @brief unhide special chars hidden to the HTML escaper
2169 * @param target buffer to put the unescaped string in
2170 * @param source buffer to unescape
2172 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2178 FlushStrBuf(target);
2180 if (source == NULL ||target == NULL)
2185 len = source->BufUsed;
2186 for (a = 0; a < len; ++a) {
2187 if (target->BufUsed >= target->BufSize)
2188 IncreaseBuf(target, 1, -1);
2190 if (source->buf[a] == '=') {
2191 hex[0] = source->buf[a + 1];
2192 hex[1] = source->buf[a + 2];
2195 sscanf(hex, "%02x", &b);
2196 target->buf[target->BufUsed] = b;
2197 target->buf[++target->BufUsed] = 0;
2201 target->buf[target->BufUsed] = source->buf[a];
2202 target->buf[++target->BufUsed] = 0;
2209 * @ingroup StrBuf_DeEnCoder
2210 * @brief hide special chars from the HTML escapers and friends
2211 * @param target buffer to put the escaped string in
2212 * @param source buffer to escape
2214 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2219 FlushStrBuf(target);
2221 if (source == NULL ||target == NULL)
2226 len = source->BufUsed;
2227 for (i=0; i<len; ++i) {
2228 if (target->BufUsed + 4 >= target->BufSize)
2229 IncreaseBuf(target, 1, -1);
2230 if ( (isalnum(source->buf[i])) ||
2231 (source->buf[i]=='-') ||
2232 (source->buf[i]=='_') ) {
2233 target->buf[target->BufUsed++] = source->buf[i];
2236 sprintf(&target->buf[target->BufUsed],
2238 (0xFF &source->buf[i]));
2239 target->BufUsed += 3;
2242 target->buf[target->BufUsed + 1] = '\0';
2246 /*******************************************************************************
2247 * Quoted Printable de/encoding *
2248 *******************************************************************************/
2251 * @ingroup StrBuf_DeEnCoder
2252 * @brief decode a buffer from base 64 encoding; destroys original
2253 * @param Buf Buffor to transform
2255 int StrBufDecodeBase64(StrBuf *Buf)
2259 if (Buf == NULL) return -1;
2261 xferbuf = (char*) malloc(Buf->BufSize);
2262 siz = CtdlDecodeBase64(xferbuf,
2272 * @ingroup StrBuf_DeEnCoder
2273 * @brief decode a buffer from base 64 encoding; destroys original
2274 * @param Buf Buffor to transform
2276 int StrBufDecodeHex(StrBuf *Buf)
2279 char *pch, *pche, *pchi;
2281 if (Buf == NULL) return -1;
2283 pch = pchi = Buf->buf;
2284 pche = pch + Buf->BufUsed;
2286 while (pchi < pche){
2287 ch = decode_hex(pchi);
2294 Buf->BufUsed = pch - Buf->buf;
2295 return Buf->BufUsed;
2299 * @ingroup StrBuf_DeEnCoder
2300 * @brief replace all chars >0x20 && < 0x7F with Mute
2301 * @param Mute char to put over invalid chars
2302 * @param Buf Buffor to transform
2304 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2308 if (Buf == NULL) return -1;
2309 pch = (unsigned char *)Buf->buf;
2310 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2311 if ((*pch < 0x20) || (*pch > 0x7F))
2315 return Buf->BufUsed;
2320 * @ingroup StrBuf_DeEnCoder
2321 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2322 * @param Buf Buffer to translate
2323 * @param StripBlanks Reduce several blanks to one?
2325 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2334 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2335 Buf->buf[Buf->BufUsed - 1] = '\0';
2340 while (a < Buf->BufUsed) {
2341 if (Buf->buf[a] == '+')
2343 else if (Buf->buf[a] == '%') {
2344 /* don't let % chars through, rather truncate the input. */
2345 if (a + 2 > Buf->BufUsed) {
2350 hex[0] = Buf->buf[a + 1];
2351 hex[1] = Buf->buf[a + 2];
2354 sscanf(hex, "%02x", &b);
2355 Buf->buf[a] = (char) b;
2356 len = Buf->BufUsed - a - 2;
2358 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2370 * @ingroup StrBuf_DeEnCoder
2371 * @brief RFC2047-encode a header field if necessary.
2372 * If no non-ASCII characters are found, the string
2373 * will be copied verbatim without encoding.
2375 * @param target Target buffer.
2376 * @param source Source string to be encoded.
2377 * @returns encoded length; -1 if non success.
2379 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2381 const char headerStr[] = "=?UTF-8?Q?";
2382 int need_to_encode = 0;
2386 if ((source == NULL) ||
2390 while ((i < source->BufUsed) &&
2391 (!IsEmptyStr (&source->buf[i])) &&
2392 (need_to_encode == 0)) {
2393 if (((unsigned char) source->buf[i] < 32) ||
2394 ((unsigned char) source->buf[i] > 126)) {
2400 if (!need_to_encode) {
2401 if (*target == NULL) {
2402 *target = NewStrBufPlain(source->buf, source->BufUsed);
2405 FlushStrBuf(*target);
2406 StrBufAppendBuf(*target, source, 0);
2408 return (*target)->BufUsed;
2410 if (*target == NULL)
2411 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2412 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2413 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2414 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2415 (*target)->BufUsed = sizeof(headerStr) - 1;
2416 for (i=0; (i < source->BufUsed); ++i) {
2417 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2418 IncreaseBuf(*target, 1, 0);
2419 ch = (unsigned char) source->buf[i];
2420 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2421 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2422 (*target)->BufUsed += 3;
2425 (*target)->buf[(*target)->BufUsed] = ch;
2426 (*target)->BufUsed++;
2430 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2431 IncreaseBuf(*target, 1, 0);
2433 (*target)->buf[(*target)->BufUsed++] = '?';
2434 (*target)->buf[(*target)->BufUsed++] = '=';
2435 (*target)->buf[(*target)->BufUsed] = '\0';
2436 return (*target)->BufUsed;;
2441 * @brief replaces all occurances of 'search' by 'replace'
2442 * @param buf Buffer to modify
2443 * @param search character to search
2444 * @param replace character to replace search by
2446 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2451 for (i=0; i<buf->BufUsed; i++)
2452 if (buf->buf[i] == search)
2453 buf->buf[i] = replace;
2459 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2460 * @param buf Buffer to modify
2462 void StrBufToUnixLF(StrBuf *buf)
2464 char *pche, *pchS, *pchT;
2468 pche = buf->buf + buf->BufUsed;
2469 pchS = pchT = buf->buf;
2475 if (*pchS != '\n') {
2484 buf->BufUsed = pchT - buf->buf;
2488 /*******************************************************************************
2489 * Iconv Wrapper; RFC822 de/encoding *
2490 *******************************************************************************/
2493 * @ingroup StrBuf_DeEnCoder
2494 * @brief Wrapper around iconv_open()
2495 * Our version adds aliases for non-standard Microsoft charsets
2496 * such as 'MS950', aliasing them to names like 'CP950'
2498 * @param tocode Target encoding
2499 * @param fromcode Source encoding
2500 * @param pic anonimized pointer to iconv struct
2502 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2505 iconv_t ic = (iconv_t)(-1) ;
2506 ic = iconv_open(tocode, fromcode);
2507 if (ic == (iconv_t)(-1) ) {
2508 char alias_fromcode[64];
2509 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2510 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2511 alias_fromcode[0] = 'C';
2512 alias_fromcode[1] = 'P';
2513 ic = iconv_open(tocode, alias_fromcode);
2516 *(iconv_t *)pic = ic;
2522 * @ingroup StrBuf_DeEnCoder
2523 * @brief find one chunk of a RFC822 encoded string
2524 * @param Buffer where to search
2525 * @param bptr where to start searching
2526 * @returns found position, NULL if none.
2528 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2531 /* Find the next ?Q? */
2532 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2535 end = strchr(bptr + 2, '?');
2540 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2541 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2542 (*(end + 2) == '?')) {
2543 /* skip on to the end of the cluster, the next ?= */
2544 end = strstr(end + 3, "?=");
2547 /* sort of half valid encoding, try to find an end. */
2548 end = strstr(bptr, "?=");
2554 * @brief swaps the contents of two StrBufs
2555 * this is to be used to have cheap switched between a work-buffer and a target buffer
2556 * @param A First one
2557 * @param B second one
2559 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2563 memcpy(&C, A, sizeof(*A));
2564 memcpy(A, B, sizeof(*B));
2565 memcpy(B, &C, sizeof(C));
2571 * @ingroup StrBuf_DeEnCoder
2572 * @brief convert one buffer according to the preselected iconv pointer PIC
2573 * @param ConvertBuf buffer we need to translate
2574 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2575 * @param pic Pointer to the iconv-session Object
2577 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2583 char *ibuf; /**< Buffer of characters to be converted */
2584 char *obuf; /**< Buffer for converted characters */
2585 size_t ibuflen; /**< Length of input buffer */
2586 size_t obuflen; /**< Length of output buffer */
2589 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2590 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2591 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2593 ic = *(iconv_t*)pic;
2594 ibuf = ConvertBuf->buf;
2595 ibuflen = ConvertBuf->BufUsed;
2597 obuflen = TmpBuf->BufSize;
2599 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2602 if (errno == E2BIG) {
2604 IncreaseBuf(TmpBuf, 0, 0);
2609 else if (errno == EILSEQ){
2610 /* hm, invalid utf8 sequence... what to do now? */
2611 /* An invalid multibyte sequence has been encountered in the input */
2613 else if (errno == EINVAL) {
2614 /* An incomplete multibyte sequence has been encountered in the input. */
2617 FlushStrBuf(TmpBuf);
2620 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2621 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2623 /* little card game: wheres the red lady? */
2624 SwapBuffers(ConvertBuf, TmpBuf);
2625 FlushStrBuf(TmpBuf);
2632 * @ingroup StrBuf_DeEnCoder
2633 * @brief catches one RFC822 encoded segment, and decodes it.
2634 * @param Target buffer to fill with result
2635 * @param DecodeMe buffer with stuff to process
2636 * @param SegmentStart points to our current segment in DecodeMe
2637 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2638 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2639 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2640 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2642 inline static void DecodeSegment(StrBuf *Target,
2643 const StrBuf *DecodeMe,
2644 const char *SegmentStart,
2645 const char *SegmentEnd,
2647 StrBuf *ConvertBuf2,
2648 StrBuf *FoundCharset)
2654 iconv_t ic = (iconv_t)(-1);
2658 /* Now we handle foreign character sets properly encoded
2659 * in RFC2047 format.
2661 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2662 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2663 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2664 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2665 if (FoundCharset != NULL) {
2666 FlushStrBuf(FoundCharset);
2667 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2669 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2670 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2672 *encoding = toupper(*encoding);
2673 if (*encoding == 'B') { /**< base64 */
2674 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2676 ConvertBuf->BufUsed);
2678 else if (*encoding == 'Q') { /**< quoted-printable */
2682 while (pos < ConvertBuf->BufUsed)
2684 if (ConvertBuf->buf[pos] == '_')
2685 ConvertBuf->buf[pos] = ' ';
2689 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2692 ConvertBuf->BufUsed);
2695 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2698 ctdl_iconv_open("UTF-8", charset, &ic);
2699 if (ic != (iconv_t)(-1) ) {
2701 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2702 StrBufAppendBuf(Target, ConvertBuf2, 0);
2707 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2713 * @ingroup StrBuf_DeEnCoder
2714 * @brief Handle subjects with RFC2047 encoding such as:
2715 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2716 * @param Target where to put the decoded string to
2717 * @param DecodeMe buffer with encoded string
2718 * @param DefaultCharset if we don't find one, which should we use?
2719 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2720 * put it here for later use where no string might be known.
2722 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2724 StrBuf *DecodedInvalidBuf = NULL;
2725 StrBuf *ConvertBuf, *ConvertBuf2;
2726 const StrBuf *DecodeMee = DecodeMe;
2727 const char *start, *end, *next, *nextend, *ptr = NULL;
2729 iconv_t ic = (iconv_t)(-1) ;
2734 int illegal_non_rfc2047_encoding = 0;
2736 /* Sometimes, badly formed messages contain strings which were simply
2737 * written out directly in some foreign character set instead of
2738 * using RFC2047 encoding. This is illegal but we will attempt to
2739 * handle it anyway by converting from a user-specified default
2740 * charset to UTF-8 if we see any nonprintable characters.
2743 len = StrLength(DecodeMe);
2744 for (i=0; i<DecodeMe->BufUsed; ++i) {
2745 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2746 illegal_non_rfc2047_encoding = 1;
2751 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2752 if ((illegal_non_rfc2047_encoding) &&
2753 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2754 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2757 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2758 if (ic != (iconv_t)(-1) ) {
2759 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2760 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2761 DecodeMee = DecodedInvalidBuf;
2767 /* pre evaluate the first pair */
2768 nextend = end = NULL;
2769 len = StrLength(DecodeMee);
2770 start = strstr(DecodeMee->buf, "=?");
2771 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2773 end = FindNextEnd (DecodeMee, start);
2775 StrBufAppendBuf(Target, DecodeMee, 0);
2776 FreeStrBuf(&ConvertBuf);
2777 FreeStrBuf(&DecodedInvalidBuf);
2781 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2783 if (start != DecodeMee->buf) {
2786 nFront = start - DecodeMee->buf;
2787 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2791 * Since spammers will go to all sorts of absurd lengths to get their
2792 * messages through, there are LOTS of corrupt headers out there.
2793 * So, prevent a really badly formed RFC2047 header from throwing
2794 * this function into an infinite loop.
2796 while ((start != NULL) &&
2803 DecodeSegment(Target,
2811 next = strstr(end, "=?");
2813 if ((next != NULL) &&
2815 nextend = FindNextEnd(DecodeMee, next);
2816 if (nextend == NULL)
2819 /* did we find two partitions */
2820 if ((next != NULL) &&
2824 while ((ptr < next) &&
2831 * did we find a gab just filled with blanks?
2832 * if not, copy its stuff over.
2836 StrBufAppendBufPlain(Target,
2842 /* our next-pair is our new first pair now. */
2848 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2849 if ((end != NULL) && (end < nextend)) {
2851 while ( (ptr < nextend) &&
2858 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2860 FreeStrBuf(&ConvertBuf);
2861 FreeStrBuf(&ConvertBuf2);
2862 FreeStrBuf(&DecodedInvalidBuf);
2865 /*******************************************************************************
2866 * Manipulating UTF-8 Strings *
2867 *******************************************************************************/
2871 * @brief evaluate the length of an utf8 special character sequence
2872 * @param Char the character to examine
2873 * @returns width of utf8 chars in bytes
2875 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2880 while ((n < 8) && ((test & *CharS) != 0)) {
2884 if ((n > 6) || ((CharE - CharS) < n))
2891 * @brief detect whether this char starts an utf-8 encoded char
2892 * @param Char character to inspect
2893 * @returns yes or no
2895 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2897 /** 11??.???? indicates an UTF8 Sequence. */
2898 return ((Char & 0xC0) != 0);
2903 * @brief measure the number of glyphs in an UTF8 string...
2904 * @param Buf string to measure
2905 * @returns the number of glyphs in Buf
2907 long StrBuf_Utf8StrLen(StrBuf *Buf)
2913 if ((Buf == NULL) || (Buf->BufUsed == 0))
2916 eptr = Buf->buf + Buf->BufUsed;
2917 while ((aptr < eptr) && (*aptr != '\0')) {
2918 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2919 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2920 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2933 * @brief cuts a string after maxlen glyphs
2934 * @param Buf string to cut to maxlen glyphs
2935 * @param maxlen how long may the string become?
2936 * @returns current length of the string
2938 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2944 eptr = Buf->buf + Buf->BufUsed;
2945 while ((aptr < eptr) && (*aptr != '\0')) {
2946 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2947 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2948 while ((*aptr++ != '\0') && (m-- > 0));
2957 Buf->BufUsed = aptr - Buf->buf;
2958 return Buf->BufUsed;
2961 return Buf->BufUsed;
2969 /*******************************************************************************
2971 *******************************************************************************/
2974 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2975 #define OS_CODE 0x03 /*< unix */
2978 * @ingroup StrBuf_DeEnCoder
2979 * @brief uses the same calling syntax as compress2(), but it
2980 * creates a stream compatible with HTTP "Content-encoding: gzip"
2981 * @param dest compressed buffer
2982 * @param destLen length of the compresed data
2983 * @param source source to encode
2984 * @param sourceLen length of source to encode
2985 * @param level compression level
2987 int ZEXPORT compress_gzip(Bytef * dest,
2989 const Bytef * source,
2993 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2995 /* write gzip header */
2996 snprintf((char *) dest, *destLen,
2997 "%c%c%c%c%c%c%c%c%c%c",
2998 gz_magic[0], gz_magic[1], Z_DEFLATED,
2999 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3002 /* normal deflate */
3005 stream.next_in = (Bytef *) source;
3006 stream.avail_in = (uInt) sourceLen;
3007 stream.next_out = dest + 10L; // after header
3008 stream.avail_out = (uInt) * destLen;
3009 if ((uLong) stream.avail_out != *destLen)
3012 stream.zalloc = (alloc_func) 0;
3013 stream.zfree = (free_func) 0;
3014 stream.opaque = (voidpf) 0;
3016 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3017 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3021 err = deflate(&stream, Z_FINISH);
3022 if (err != Z_STREAM_END) {
3023 deflateEnd(&stream);
3024 return err == Z_OK ? Z_BUF_ERROR : err;
3026 *destLen = stream.total_out + 10L;
3028 /* write CRC and Length */
3029 uLong crc = crc32(0L, source, sourceLen);
3031 for (n = 0; n < 4; ++n, ++*destLen) {
3032 dest[*destLen] = (int) (crc & 0xff);
3035 uLong len = stream.total_in;
3036 for (n = 0; n < 4; ++n, ++*destLen) {
3037 dest[*destLen] = (int) (len & 0xff);
3040 err = deflateEnd(&stream);
3047 * @ingroup StrBuf_DeEnCoder
3048 * @brief compress the buffer with gzip
3049 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3050 * @param Buf buffer whose content is to be gzipped
3052 int CompressBuffer(StrBuf *Buf)
3055 char *compressed_data = NULL;
3056 size_t compressed_len, bufsize;
3059 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3060 compressed_data = malloc(compressed_len);
3062 if (compressed_data == NULL)
3064 /* Flush some space after the used payload so valgrind shuts up... */
3065 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3066 Buf->buf[Buf->BufUsed + i++] = '\0';
3067 if (compress_gzip((Bytef *) compressed_data,
3070 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3073 Buf->buf = compressed_data;
3074 Buf->BufUsed = compressed_len;
3075 Buf->BufSize = bufsize;
3076 /* Flush some space after the used payload so valgrind shuts up... */
3078 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3079 Buf->buf[Buf->BufUsed + i++] = '\0';
3082 free(compressed_data);
3084 #endif /* HAVE_ZLIB */
3090 /*******************************************************************************
3091 * File I/O; Prefer buffered read since its faster! *
3092 *******************************************************************************/
3095 * @ingroup StrBuf_IO
3096 * @brief Read a line from socket
3097 * flushes and closes the FD on error
3098 * @param buf the buffer to get the input to
3099 * @param fd pointer to the filedescriptor to read
3100 * @param append Append to an existing string or replace?
3101 * @param Error strerror() on error
3102 * @returns numbers of chars read
3104 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3106 int len, rlen, slen;
3111 slen = len = buf->BufUsed;
3113 rlen = read(*fd, &buf->buf[len], 1);
3115 *Error = strerror(errno);
3122 if (buf->buf[len] == '\n')
3124 if (buf->buf[len] != '\r')
3126 if (len + 2 >= buf->BufSize) {
3128 buf->buf[len+1] = '\0';
3129 IncreaseBuf(buf, 1, -1);
3133 buf->buf[len] = '\0';
3138 * @ingroup StrBuf_BufferedIO
3139 * @brief Read a line from socket
3140 * flushes and closes the FD on error
3141 * @param Line the line to read from the fd / I/O Buffer
3142 * @param buf the buffer to get the input to
3143 * @param fd pointer to the filedescriptor to read
3144 * @param timeout number of successless selects until we bail out
3145 * @param selectresolution how long to wait on each select
3146 * @param Error strerror() on error
3147 * @returns numbers of chars read
3149 int StrBufTCP_read_buffered_line(StrBuf *Line,
3153 int selectresolution,
3157 int nSuccessLess = 0;
3164 if (buf->BufUsed > 0) {
3165 pch = strchr(buf->buf, '\n');
3168 len = pch - buf->buf;
3169 if (len > 0 && (*(pch - 1) == '\r') )
3171 StrBufSub(Line, buf, 0, len - rlen);
3172 StrBufCutLeft(buf, len + 1);
3177 if (buf->BufSize - buf->BufUsed < 10)
3178 IncreaseBuf(buf, 1, -1);
3180 fdflags = fcntl(*fd, F_GETFL);
3181 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3183 while ((nSuccessLess < timeout) && (pch == NULL)) {
3185 tv.tv_sec = selectresolution;
3190 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3191 *Error = strerror(errno);
3197 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3202 &buf->buf[buf->BufUsed],
3203 buf->BufSize - buf->BufUsed - 1);
3205 *Error = strerror(errno);
3210 else if (rlen > 0) {
3212 buf->BufUsed += rlen;
3213 buf->buf[buf->BufUsed] = '\0';
3214 if (buf->BufUsed + 10 > buf->BufSize) {
3215 IncreaseBuf(buf, 1, -1);
3217 pch = strchr(buf->buf, '\n');
3224 len = pch - buf->buf;
3225 if (len > 0 && (*(pch - 1) == '\r') )
3227 StrBufSub(Line, buf, 0, len - rlen);
3228 StrBufCutLeft(buf, len + 1);
3235 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3236 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3237 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3239 * @ingroup StrBuf_BufferedIO
3240 * @brief Read a line from socket
3241 * flushes and closes the FD on error
3242 * @param Line where to append our Line read from the fd / I/O Buffer;
3243 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3244 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3245 * @param fd pointer to the filedescriptor to read
3246 * @param timeout number of successless selects until we bail out
3247 * @param selectresolution how long to wait on each select
3248 * @param Error strerror() on error
3249 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3251 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3256 int selectresolution,
3259 const char *pche = NULL;
3260 const char *pos = NULL;
3262 int len, rlen, retlen;
3263 int nSuccessLess = 0;
3265 const char *pch = NULL;
3271 if ((Line == NULL) ||
3278 *Error = ErrRBLF_PreConditionFailed;
3283 if ((IOBuf->BufUsed > 0) &&
3285 (pos < IOBuf->buf + IOBuf->BufUsed))
3289 pche = IOBuf->buf + IOBuf->BufUsed;
3293 while ((pch < pche) && (*pch != '\n'))
3295 if (Line->BufUsed + 10 > Line->BufSize)
3298 apos = pcht - Line->buf;
3300 IncreaseBuf(Line, 1, -1);
3301 pcht = Line->buf + apos;
3309 if (len > 0 && (*(pch - 1) == '\r') )
3318 if ((pch >= pche) || (*pch == '\0'))
3326 if ((pch != NULL) &&
3329 if (pch + 1 >= pche) {
3342 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3344 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3345 IncreaseBuf(IOBuf, 1, -1);
3347 fdflags = fcntl(*fd, F_GETFL);
3348 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3351 while ((nSuccessLess < timeout) &&
3361 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3362 *Error = strerror(errno);
3366 *Error = ErrRBLF_SelectFailed;
3369 if (! FD_ISSET(*fd, &rfds) != 0) {
3375 &IOBuf->buf[IOBuf->BufUsed],
3376 IOBuf->BufSize - IOBuf->BufUsed - 1);
3378 *Error = strerror(errno);
3383 else if (rlen > 0) {
3385 pLF = IOBuf->buf + IOBuf->BufUsed;
3386 IOBuf->BufUsed += rlen;
3387 IOBuf->buf[IOBuf->BufUsed] = '\0';
3389 pche = IOBuf->buf + IOBuf->BufUsed;
3391 while ((pLF < pche) && (*pLF != '\n'))
3393 if ((pLF >= pche) || (*pLF == '\0'))
3396 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3400 if (pLF != NULL) apos = pLF - IOBuf->buf;
3401 IncreaseBuf(IOBuf, 1, -1);
3402 if (pLF != NULL) pLF = IOBuf->buf + apos;
3412 if (len > 0 && (*(pLF - 1) == '\r') )
3414 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3415 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3421 return retlen + len;
3423 *Error = ErrRBLF_NotEnoughSentFromServer;
3428 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3430 * @ingroup StrBuf_IO
3431 * @brief Input binary data from socket
3432 * flushes and closes the FD on error
3433 * @param Buf the buffer to get the input to
3434 * @param fd pointer to the filedescriptor to read
3435 * @param append Append to an existing string or replace?
3436 * @param nBytes the maximal number of bytes to read
3437 * @param Error strerror() on error
3438 * @returns numbers of chars read
3440 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3443 int len, rlen, slen;
3451 if ((Buf == NULL) || (*fd == -1))
3453 *Error = ErrRBLF_BLOBPreConditionFailed;
3458 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3459 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3461 ptr = Buf->buf + Buf->BufUsed;
3463 slen = len = Buf->BufUsed;
3465 fdflags = fcntl(*fd, F_GETFL);
3466 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3468 while ((nRead < nBytes) &&
3478 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3479 *Error = strerror(errno);
3483 *Error = ErrRBLF_SelectFailed;
3486 if (! FD_ISSET(*fd, &rfds) != 0) {
3492 if ((rlen = read(*fd,
3494 nBytes - nRead)) == -1) {
3497 *Error = strerror(errno);
3502 Buf->BufUsed += rlen;
3504 Buf->buf[Buf->BufUsed] = '\0';
3508 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3509 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3511 * @ingroup StrBuf_BufferedIO
3512 * @brief Input binary data from socket
3513 * flushes and closes the FD on error
3514 * @param Blob put binary thing here
3515 * @param IOBuf the buffer to get the input to
3516 * @param Pos offset inside of IOBuf
3517 * @param fd pointer to the filedescriptor to read
3518 * @param append Append to an existing string or replace?
3519 * @param nBytes the maximal number of bytes to read
3520 * @param check whether we should search for '000\n' terminators in case of timeouts
3521 * @param Error strerror() on error
3522 * @returns numbers of chars read
3524 int StrBufReadBLOBBuffered(StrBuf *Blob,
3539 int nAlreadyRead = 0;
3545 int nSuccessLess = 0;
3548 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3552 *Error = ErrRBB_BLOBFPreConditionFailed;
3558 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3559 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3564 len = pos - IOBuf->buf;
3565 rlen = IOBuf->BufUsed - len;
3568 if ((IOBuf->BufUsed > 0) &&
3570 (pos < IOBuf->buf + IOBuf->BufUsed))
3572 pche = IOBuf->buf + IOBuf->BufUsed;
3575 if (rlen < nBytes) {
3576 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3577 Blob->BufUsed += rlen;
3578 Blob->buf[Blob->BufUsed] = '\0';
3579 nAlreadyRead = nRead = rlen;
3582 if (rlen >= nBytes) {
3583 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3584 Blob->BufUsed += nBytes;
3585 Blob->buf[Blob->BufUsed] = '\0';
3586 if (rlen == nBytes) {
3598 if (IOBuf->BufSize < nBytes - nRead)
3599 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3602 slen = len = Blob->BufUsed;
3604 fdflags = fcntl(*fd, F_GETFL);
3605 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3613 while ((nSuccessLess < MaxTries) &&
3623 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3624 *Error = strerror(errno);
3628 *Error = ErrRBLF_SelectFailed;
3631 if (! FD_ISSET(*fd, &rfds) != 0) {
3638 IOBuf->BufSize - (ptr - IOBuf->buf));
3642 *Error = strerror(errno);
3645 else if (rlen == 0){
3646 if ((check == NNN_TERM) &&
3648 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3650 StrBufPlain(Blob, HKEY("\n000\n"));
3651 StrBufCutRight(Blob, 5);
3652 return Blob->BufUsed;
3654 else if (!IsNonBlock)
3656 else if (nSuccessLess > MaxTries) {
3658 *Error = ErrRBB_too_many_selects;
3662 else if (rlen > 0) {
3666 IOBuf->BufUsed += rlen;
3669 if (nSuccessLess >= MaxTries) {
3671 *Error = ErrRBB_too_many_selects;
3675 if (nRead > nBytes) {
3676 *Pos = IOBuf->buf + nBytes;
3678 Blob->buf[Blob->BufUsed] = '\0';
3679 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3683 return nRead + nAlreadyRead;
3687 * @ingroup StrBuf_IO
3688 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3689 * @param LineBuf your line will be copied here.
3690 * @param Buf BLOB with lines of text...
3691 * @param Ptr moved arround to keep the next-line across several iterations
3692 * has to be &NULL on start; will be &NotNULL on end of buffer
3693 * @returns size of copied buffer
3695 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3697 const char *aptr, *ptr, *eptr;
3700 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3701 *Ptr = StrBufNOTNULL;
3705 FlushStrBuf(LineBuf);
3707 ptr = aptr = Buf->buf;
3711 optr = LineBuf->buf;
3712 eptr = Buf->buf + Buf->BufUsed;
3713 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3715 while ((ptr <= eptr) &&
3722 LineBuf->BufUsed = optr - LineBuf->buf;
3723 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3724 optr = LineBuf->buf + LineBuf->BufUsed;
3725 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3729 if ((ptr >= eptr) && (optr > LineBuf->buf))
3731 LineBuf->BufUsed = optr - LineBuf->buf;
3733 if ((ptr <= eptr) && (*ptr == '\r'))
3735 if ((ptr <= eptr) && (*ptr == '\n'))
3742 *Ptr = StrBufNOTNULL;
3745 return Buf->BufUsed - (ptr - Buf->buf);
3750 * @ingroup StrBuf_IO
3751 * @brief removes double slashes from pathnames
3752 * @param Dir directory string to filter
3753 * @param RemoveTrailingSlash allows / disallows trailing slashes
3755 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3761 while (!IsEmptyStr(a)) {
3773 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3778 Dir->BufUsed = b - Dir->buf;