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)
425 size_t Siz = Buf->BufSize;
429 CopySize = strlen(ptr);
433 while (Siz <= CopySize)
436 if (Siz != Buf->BufSize)
437 IncreaseBuf(Buf, 0, Siz);
438 memcpy(Buf->buf, ptr, CopySize);
439 Buf->buf[CopySize] = '\0';
440 Buf->BufUsed = CopySize;
447 * @ingroup StrBuf_DeConstructors
448 * @brief use strbuf as wrapper for a string constant for easy handling
449 * @param StringConstant a string to wrap
450 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
452 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
456 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
457 NewBuf->buf = (char*) StringConstant;
458 NewBuf->BufSize = SizeOfStrConstant;
459 NewBuf->BufUsed = SizeOfStrConstant;
460 NewBuf->ConstBuf = 1;
469 * @ingroup StrBuf_DeConstructors
470 * @brief flush the content of a Buf; keep its struct
471 * @param buf Buffer to flush
473 int FlushStrBuf(StrBuf *buf)
485 * @ingroup StrBuf_DeConstructors
486 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
487 * @param buf Buffer to wipe
489 int FLUSHStrBuf(StrBuf *buf)
495 if (buf->BufUsed > 0) {
496 memset(buf->buf, 0, buf->BufUsed);
503 int hFreeDbglog = -1;
506 * @ingroup StrBuf_DeConstructors
507 * @brief Release a Buffer
508 * Its a double pointer, so it can NULL your pointer
509 * so fancy SIG11 appear instead of random results
510 * @param FreeMe Pointer Pointer to the buffer to free
512 void FreeStrBuf (StrBuf **FreeMe)
517 dbg_FreeStrBuf(FreeMe, 'F');
519 if (!(*FreeMe)->ConstBuf)
520 free((*FreeMe)->buf);
526 * @ingroup StrBuf_DeConstructors
527 * @brief flatten a Buffer to the Char * we return
528 * Its a double pointer, so it can NULL your pointer
529 * so fancy SIG11 appear instead of random results
530 * The Callee then owns the buffer and is responsible for freeing it.
531 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
532 * @returns the pointer of the buffer; Callee owns the memory thereafter.
534 char *SmashStrBuf (StrBuf **SmashMe)
538 if ((SmashMe == NULL) || (*SmashMe == NULL))
541 dbg_FreeStrBuf(SmashMe, 'S');
543 Ret = (*SmashMe)->buf;
550 * @ingroup StrBuf_DeConstructors
551 * @brief Release the buffer
552 * If you want put your StrBuf into a Hash, use this as Destructor.
553 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
555 void HFreeStrBuf (void *VFreeMe)
557 StrBuf *FreeMe = (StrBuf*)VFreeMe;
561 dbg_FreeStrBuf(SmashMe, 'H');
563 if (!FreeMe->ConstBuf)
569 /*******************************************************************************
570 * Simple string transformations *
571 *******************************************************************************/
575 * @brief Wrapper around atol
577 long StrTol(const StrBuf *Buf)
582 return atol(Buf->buf);
589 * @brief Wrapper around atoi
591 int StrToi(const StrBuf *Buf)
595 if (Buf->BufUsed > 0)
596 return atoi(Buf->buf);
603 * @brief Checks to see if the string is a pure number
604 * @param Buf The buffer to inspect
605 * @returns 1 if its a pure number, 0, if not.
607 int StrBufIsNumber(const StrBuf *Buf) {
609 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
612 strtoll(Buf->buf, &pEnd, 10);
613 if (pEnd == Buf->buf)
615 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
617 if (Buf->buf == pEnd)
622 * @ingroup StrBuf_Filler
623 * @brief modifies a Single char of the Buf
624 * You can point to it via char* or a zero-based integer
625 * @param Buf The buffer to manipulate
626 * @param ptr char* to zero; use NULL if unused
627 * @param nThChar zero based pointer into the string; use -1 if unused
628 * @param PeekValue The Character to place into the position
630 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
635 nThChar = ptr - Buf->buf;
636 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
638 Buf->buf[nThChar] = PeekValue;
643 * @ingroup StrBuf_Filler
644 * @brief Append a StringBuffer to the buffer
645 * @param Buf Buffer to modify
646 * @param AppendBuf Buffer to copy at the end of our buffer
647 * @param Offset Should we start copying from an offset?
649 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
651 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
654 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
657 AppendBuf->BufUsed + Buf->BufUsed);
659 memcpy(Buf->buf + Buf->BufUsed,
660 AppendBuf->buf + Offset,
661 AppendBuf->BufUsed - Offset);
662 Buf->BufUsed += AppendBuf->BufUsed - Offset;
663 Buf->buf[Buf->BufUsed] = '\0';
668 * @ingroup StrBuf_Filler
669 * @brief Append a C-String to the buffer
670 * @param Buf Buffer to modify
671 * @param AppendBuf Buffer to copy at the end of our buffer
672 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
673 * @param Offset Should we start copying from an offset?
675 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
678 long BufSizeRequired;
680 if ((AppendBuf == NULL) || (Buf == NULL))
684 aps = strlen(AppendBuf + Offset);
686 aps = AppendSize - Offset;
688 BufSizeRequired = Buf->BufUsed + aps + 1;
689 if (Buf->BufSize <= BufSizeRequired)
690 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
692 memcpy(Buf->buf + Buf->BufUsed,
696 Buf->buf[Buf->BufUsed] = '\0';
700 * @ingroup StrBuf_Filler
701 * @brief sprintf like function appending the formated string to the buffer
702 * vsnprintf version to wrap into own calls
703 * @param Buf Buffer to extend by format and Params
704 * @param format printf alike format to add
705 * @param ap va_list containing the items for format
707 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
715 if ((Buf == NULL) || (format == NULL))
718 BufSize = Buf->BufSize;
719 nWritten = Buf->BufSize + 1;
720 Offset = Buf->BufUsed;
721 newused = Offset + nWritten;
723 while (newused >= BufSize) {
725 nWritten = vsnprintf(Buf->buf + Offset,
726 Buf->BufSize - Offset,
729 newused = Offset + nWritten;
730 if (newused >= Buf->BufSize) {
731 IncreaseBuf(Buf, 1, newused);
732 newused = Buf->BufSize + 1;
735 Buf->BufUsed = Offset + nWritten;
736 BufSize = Buf->BufSize;
743 * @ingroup StrBuf_Filler
744 * @brief sprintf like function appending the formated string to the buffer
745 * @param Buf Buffer to extend by format and Params
746 * @param format printf alike format to add
748 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
756 if ((Buf == NULL) || (format == NULL))
759 BufSize = Buf->BufSize;
760 nWritten = Buf->BufSize + 1;
761 Offset = Buf->BufUsed;
762 newused = Offset + nWritten;
764 while (newused >= BufSize) {
765 va_start(arg_ptr, format);
766 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
767 Buf->BufSize - Buf->BufUsed,
770 newused = Buf->BufUsed + nWritten;
771 if (newused >= Buf->BufSize) {
772 IncreaseBuf(Buf, 1, newused);
773 newused = Buf->BufSize + 1;
776 Buf->BufUsed += nWritten;
777 BufSize = Buf->BufSize;
784 * @ingroup StrBuf_Filler
785 * @brief sprintf like function putting the formated string into the buffer
786 * @param Buf Buffer to extend by format and Parameters
787 * @param format printf alike format to add
789 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
794 if ((Buf == NULL) || (format == NULL))
797 nWritten = Buf->BufSize + 1;
798 while (nWritten >= Buf->BufSize) {
799 va_start(arg_ptr, format);
800 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
802 if (nWritten >= Buf->BufSize) {
803 IncreaseBuf(Buf, 0, 0);
804 nWritten = Buf->BufSize + 1;
807 Buf->BufUsed = nWritten ;
812 * @ingroup StrBuf_Filler
813 * @brief Callback for cURL to append the webserver reply to a buffer
814 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
815 * @param size pre-defined by the cURL API; see man 3 curl for mre info
816 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
817 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
819 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
828 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
835 * @brief extracts a substring from Source into dest
836 * @param dest buffer to place substring into
837 * @param Source string to copy substring from
838 * @param Offset chars to skip from start
839 * @param nChars number of chars to copy
840 * @returns the number of chars copied; may be different from nChars due to the size of Source
842 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
845 if (Offset > Source->BufUsed)
850 if (Offset + nChars < Source->BufUsed)
852 if (nChars >= dest->BufSize)
853 IncreaseBuf(dest, 0, nChars + 1);
854 memcpy(dest->buf, Source->buf + Offset, nChars);
855 dest->BufUsed = nChars;
856 dest->buf[dest->BufUsed] = '\0';
859 NCharsRemain = Source->BufUsed - Offset;
860 if (NCharsRemain >= dest->BufSize)
861 IncreaseBuf(dest, 0, NCharsRemain + 1);
862 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
863 dest->BufUsed = NCharsRemain;
864 dest->buf[dest->BufUsed] = '\0';
870 * @brief Cut nChars from the start of the string
871 * @param Buf Buffer to modify
872 * @param nChars how many chars should be skipped?
874 void StrBufCutLeft(StrBuf *Buf, int nChars)
876 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
877 if (nChars >= Buf->BufUsed) {
881 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
882 Buf->BufUsed -= nChars;
883 Buf->buf[Buf->BufUsed] = '\0';
888 * @brief Cut the trailing n Chars from the string
889 * @param Buf Buffer to modify
890 * @param nChars how many chars should be trunkated?
892 void StrBufCutRight(StrBuf *Buf, int nChars)
894 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
895 if (nChars >= Buf->BufUsed) {
899 Buf->BufUsed -= nChars;
900 Buf->buf[Buf->BufUsed] = '\0';
905 * @brief Cut the string after n Chars
906 * @param Buf Buffer to modify
907 * @param AfternChars after how many chars should we trunkate the string?
908 * @param At if non-null and points inside of our string, cut it there.
910 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
912 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
914 AfternChars = At - Buf->buf;
917 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
919 Buf->BufUsed = AfternChars;
920 Buf->buf[Buf->BufUsed] = '\0';
926 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
927 * @param Buf the string to modify
929 void StrBufTrim(StrBuf *Buf)
932 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
934 while ((Buf->BufUsed > 0) &&
935 isspace(Buf->buf[Buf->BufUsed - 1]))
939 Buf->buf[Buf->BufUsed] = '\0';
941 if (Buf->BufUsed == 0) return;
943 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
946 if (delta > 0) StrBufCutLeft(Buf, delta);
951 * @ingroup StrBuf_Filler
952 * @brief uppercase the contents of a buffer
953 * @param Buf the buffer to translate
955 void StrBufUpCase(StrBuf *Buf)
959 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
962 pche = pch + Buf->BufUsed;
964 *pch = toupper(*pch);
971 * @ingroup StrBuf_Filler
972 * @brief lowercase the contents of a buffer
973 * @param Buf the buffer to translate
975 void StrBufLowerCase(StrBuf *Buf)
979 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
982 pche = pch + Buf->BufUsed;
984 *pch = tolower(*pch);
990 /*******************************************************************************
991 * a tokenizer that kills, maims, and destroys *
992 *******************************************************************************/
995 * @ingroup StrBuf_Tokenizer
996 * @brief Replace a token at a given place with a given length by another token with given length
997 * @param Buf String where to work on
998 * @param where where inside of the Buf is the search-token
999 * @param HowLong How long is the token to be replaced
1000 * @param Repl Token to insert at 'where'
1001 * @param ReplLen Length of repl
1002 * @returns -1 if fail else length of resulting Buf
1004 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1005 const char *Repl, long ReplLen)
1008 if ((Buf == NULL) ||
1009 (where > Buf->BufUsed) ||
1010 (where + HowLong > Buf->BufUsed))
1013 if (where + ReplLen - HowLong > Buf->BufSize)
1014 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1017 memmove(Buf->buf + where + HowLong,
1018 Buf->buf + where + ReplLen,
1019 Buf->BufUsed - where - HowLong);
1021 memcpy(Buf->buf + where,
1024 Buf->BufUsed += ReplLen - HowLong;
1026 return Buf->BufUsed;
1030 * @ingroup StrBuf_Tokenizer
1031 * @brief Counts the numbmer of tokens in a buffer
1032 * @param source String to count tokens in
1033 * @param tok Tokenizer char to count
1034 * @returns numbers of tokenizer chars found
1036 int StrBufNum_tokens(const StrBuf *source, char tok)
1040 if ((source == NULL) || (source->BufUsed == 0))
1042 if ((source->BufUsed == 1) && (*source->buf == tok))
1046 pche = pch + source->BufUsed;
1057 * @ingroup StrBuf_Tokenizer
1058 * @brief a string tokenizer
1059 * @param Source StringBuffer to read into
1060 * @param parmnum n'th Parameter to remove
1061 * @param separator tokenizer character
1062 * @returns -1 if not found, else length of token.
1064 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1067 char *d, *s, *end; /* dest, source */
1070 /* Find desired @parameter */
1071 end = Source->buf + Source->BufUsed;
1073 while ((d <= end) &&
1076 /* End of string, bail! */
1081 if (*d == separator) {
1086 if ((d == NULL) || (d >= end))
1087 return 0; /* @Parameter not found */
1089 /* Find next @parameter */
1091 while ((s <= end) &&
1092 (*s && *s != separator))
1096 if (*s == separator)
1100 /* Hack and slash */
1105 memmove(d, s, Source->BufUsed - (s - Source->buf));
1106 Source->BufUsed += ReducedBy;
1107 Source->buf[Source->BufUsed] = '\0';
1109 else if (d == Source->buf) {
1111 Source->BufUsed = 0;
1115 Source->BufUsed += ReducedBy;
1128 * @ingroup StrBuf_Tokenizer
1129 * @brief a string tokenizer
1130 * @param dest Destination StringBuffer
1131 * @param Source StringBuffer to read into
1132 * @param parmnum n'th Parameter to extract
1133 * @param separator tokenizer character
1134 * @returns -1 if not found, else length of token.
1136 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1138 const char *s, *e; //* source * /
1139 int len = 0; //* running total length of extracted string * /
1140 int current_token = 0; //* token currently being processed * /
1143 dest->buf[0] = '\0';
1149 if ((Source == NULL) || (Source->BufUsed ==0)) {
1153 e = s + Source->BufUsed;
1156 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1158 while ((s<e) && !IsEmptyStr(s)) {
1159 if (*s == separator) {
1162 if (len >= dest->BufSize) {
1163 dest->BufUsed = len;
1164 if (IncreaseBuf(dest, 1, -1) < 0) {
1169 if ( (current_token == parmnum) &&
1170 (*s != separator)) {
1171 dest->buf[len] = *s;
1174 else if (current_token > parmnum) {
1180 dest->buf[len] = '\0';
1181 dest->BufUsed = len;
1183 if (current_token < parmnum) {
1184 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1187 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1196 * @ingroup StrBuf_Tokenizer
1197 * @brief a string tokenizer to fetch an integer
1198 * @param Source String containing tokens
1199 * @param parmnum n'th Parameter to extract
1200 * @param separator tokenizer character
1201 * @returns 0 if not found, else integer representation of the token
1203 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1213 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1220 * @ingroup StrBuf_Tokenizer
1221 * @brief a string tokenizer to fetch a long integer
1222 * @param Source String containing tokens
1223 * @param parmnum n'th Parameter to extract
1224 * @param separator tokenizer character
1225 * @returns 0 if not found, else long integer representation of the token
1227 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1237 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1245 * @ingroup StrBuf_Tokenizer
1246 * @brief a string tokenizer to fetch an unsigned long
1247 * @param Source String containing tokens
1248 * @param parmnum n'th Parameter to extract
1249 * @param separator tokenizer character
1250 * @returns 0 if not found, else unsigned long representation of the token
1252 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1263 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1267 return (unsigned long) atol(pnum);
1276 * @ingroup StrBuf_NextTokenizer
1277 * @brief a string tokenizer; Bounds checker
1278 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1279 * @param Source our tokenbuffer
1280 * @param pStart the token iterator pointer to inspect
1281 * @returns whether the revolving pointer is inside of the search range
1283 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1285 if ((Source == NULL) ||
1286 (*pStart == StrBufNOTNULL) ||
1287 (Source->BufUsed == 0))
1291 if (*pStart == NULL)
1295 else if (*pStart > Source->buf + Source->BufUsed)
1299 else if (*pStart <= Source->buf)
1308 * @ingroup StrBuf_NextTokenizer
1309 * @brief a string tokenizer
1310 * @param dest Destination StringBuffer
1311 * @param Source StringBuffer to read into
1312 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1313 * @param separator tokenizer
1314 * @returns -1 if not found, else length of token.
1316 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1318 const char *s; /* source */
1319 const char *EndBuffer; /* end stop of source buffer */
1320 int current_token = 0; /* token currently being processed */
1321 int len = 0; /* running total length of extracted string */
1323 if ((Source == NULL) ||
1324 (Source->BufUsed == 0) )
1326 *pStart = StrBufNOTNULL;
1330 EndBuffer = Source->buf + Source->BufUsed;
1334 dest->buf[0] = '\0';
1339 *pStart = EndBuffer + 1;
1343 if (*pStart == NULL)
1345 *pStart = Source->buf; /* we're starting to examine this buffer. */
1347 else if ((*pStart < Source->buf) ||
1348 (*pStart > EndBuffer ) )
1350 return -1; /* no more tokens to find. */
1354 /* start to find the next token */
1355 while ((s <= EndBuffer) &&
1356 (current_token == 0) )
1358 if (*s == separator)
1360 /* we found the next token */
1364 if (len >= dest->BufSize)
1366 /* our Dest-buffer isn't big enough, increase it. */
1367 dest->BufUsed = len;
1369 if (IncreaseBuf(dest, 1, -1) < 0) {
1370 /* WHUT? no more mem? bail out. */
1377 if ( (current_token == 0 ) && /* are we in our target token? */
1378 (!IsEmptyStr(s) ) &&
1379 (separator != *s) ) /* don't copy the token itself */
1381 dest->buf[len] = *s; /* Copy the payload */
1382 ++len; /* remember the bigger size. */
1388 /* did we reach the end? */
1389 if ((s > EndBuffer)) {
1390 EndBuffer = StrBufNOTNULL;
1391 *pStart = EndBuffer;
1394 *pStart = s; /* remember the position for the next run */
1397 /* sanitize our extracted token */
1398 dest->buf[len] = '\0';
1399 dest->BufUsed = len;
1406 * @ingroup StrBuf_NextTokenizer
1407 * @brief a string tokenizer
1408 * @param Source StringBuffer to read from
1409 * @param pStart pointer to the end of the last token. Feed with NULL.
1410 * @param separator tokenizer character
1411 * @param nTokens number of tokens to fastforward over
1412 * @returns -1 if not found, else length of token.
1414 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1416 const char *s, *EndBuffer; //* source * /
1417 int len = 0; //* running total length of extracted string * /
1418 int current_token = 0; //* token currently being processed * /
1420 if ((Source == NULL) ||
1421 (Source->BufUsed ==0)) {
1425 return Source->BufUsed;
1427 if (*pStart == NULL)
1428 *pStart = Source->buf;
1430 EndBuffer = Source->buf + Source->BufUsed;
1432 if ((*pStart < Source->buf) ||
1433 (*pStart > EndBuffer)) {
1441 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1443 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1444 if (*s == separator) {
1447 if (current_token >= nTokens) {
1459 * @ingroup StrBuf_NextTokenizer
1460 * @brief a string tokenizer to fetch an integer
1461 * @param Source StringBuffer to read from
1462 * @param pStart Cursor on the tokenstring
1463 * @param separator tokenizer character
1464 * @returns 0 if not found, else integer representation of the token
1466 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1476 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1483 * @ingroup StrBuf_NextTokenizer
1484 * @brief a string tokenizer to fetch a long integer
1485 * @param Source StringBuffer to read from
1486 * @param pStart Cursor on the tokenstring
1487 * @param separator tokenizer character
1488 * @returns 0 if not found, else long integer representation of the token
1490 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1500 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1508 * @ingroup StrBuf_NextTokenizer
1509 * @brief a string tokenizer to fetch an unsigned long
1510 * @param Source StringBuffer to read from
1511 * @param pStart Cursor on the tokenstring
1512 * @param separator tokenizer character
1513 * @returns 0 if not found, else unsigned long representation of the token
1515 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1526 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1530 return (unsigned long) atol(pnum);
1540 /*******************************************************************************
1541 * Escape Appending *
1542 *******************************************************************************/
1545 * @ingroup StrBuf_DeEnCoder
1546 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1547 * @param OutBuf the output buffer
1548 * @param In Buffer to encode
1549 * @param PlainIn way in from plain old c strings
1551 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1553 const char *pch, *pche;
1557 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1559 if (PlainIn != NULL) {
1560 len = strlen(PlainIn);
1566 pche = pch + In->BufUsed;
1573 pt = OutBuf->buf + OutBuf->BufUsed;
1574 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1576 while (pch < pche) {
1578 IncreaseBuf(OutBuf, 1, -1);
1579 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1580 pt = OutBuf->buf + OutBuf->BufUsed;
1583 if((*pch >= 'a' && *pch <= 'z') ||
1584 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1585 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1586 (*pch == '!') || (*pch == '_') ||
1587 (*pch == ',') || (*pch == '.'))
1594 *(pt + 1) = HexList[(unsigned char)*pch][0];
1595 *(pt + 2) = HexList[(unsigned char)*pch][1];
1597 OutBuf->BufUsed += 3;
1605 * @ingroup StrBuf_DeEnCoder
1606 * @brief append a string in hex encoding to the buffer
1607 * @param OutBuf the output buffer
1608 * @param In Buffer to encode
1609 * @param PlainIn way in from plain old c strings
1611 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1613 const char *pch, *pche;
1617 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1619 if (PlainIn != NULL) {
1620 len = strlen(PlainIn);
1626 pche = pch + In->BufUsed;
1633 pt = OutBuf->buf + OutBuf->BufUsed;
1634 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1636 while (pch < pche) {
1638 IncreaseBuf(OutBuf, 1, -1);
1639 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1640 pt = OutBuf->buf + OutBuf->BufUsed;
1643 *pt = HexList[(unsigned char)*pch][0];
1645 *pt = HexList[(unsigned char)*pch][1];
1646 pt ++; pch ++; OutBuf->BufUsed += 2;
1652 * @ingroup StrBuf_DeEnCoder
1653 * @brief Append a string, escaping characters which have meaning in HTML.
1655 * @param Target target buffer
1656 * @param Source source buffer; set to NULL if you just have a C-String
1657 * @param PlainIn Plain-C string to append; set to NULL if unused
1658 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1659 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1660 * if set to 2, linebreaks are replaced by <br/>
1662 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1664 const char *aptr, *eiptr;
1668 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1671 if (PlainIn != NULL) {
1673 len = strlen(PlainIn);
1678 eiptr = aptr + Source->BufUsed;
1679 len = Source->BufUsed;
1685 bptr = Target->buf + Target->BufUsed;
1686 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1688 while (aptr < eiptr){
1690 IncreaseBuf(Target, 1, -1);
1691 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1692 bptr = Target->buf + Target->BufUsed;
1695 memcpy(bptr, "<", 4);
1697 Target->BufUsed += 4;
1699 else if (*aptr == '>') {
1700 memcpy(bptr, ">", 4);
1702 Target->BufUsed += 4;
1704 else if (*aptr == '&') {
1705 memcpy(bptr, "&", 5);
1707 Target->BufUsed += 5;
1709 else if (*aptr == '"') {
1710 memcpy(bptr, """, 6);
1712 Target->BufUsed += 6;
1714 else if (*aptr == '\'') {
1715 memcpy(bptr, "'", 5);
1717 Target->BufUsed += 5;
1719 else if (*aptr == LB) {
1724 else if (*aptr == RB) {
1729 else if (*aptr == QU) {
1734 else if ((*aptr == 32) && (nbsp == 1)) {
1735 memcpy(bptr, " ", 6);
1737 Target->BufUsed += 6;
1739 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1740 *bptr='\0'; /* nothing */
1742 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1743 memcpy(bptr, "<br/>", 11);
1745 Target->BufUsed += 11;
1749 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1750 *bptr='\0'; /* nothing */
1760 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1762 return Target->BufUsed;
1766 * @ingroup StrBuf_DeEnCoder
1767 * @brief Append a string, escaping characters which have meaning in HTML.
1768 * Converts linebreaks into blanks; escapes single quotes
1769 * @param Target target buffer
1770 * @param Source source buffer; set to NULL if you just have a C-String
1771 * @param PlainIn Plain-C string to append; set to NULL if unused
1773 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1775 const char *aptr, *eiptr;
1779 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1782 if (PlainIn != NULL) {
1784 len = strlen(PlainIn);
1789 eiptr = aptr + Source->BufUsed;
1790 len = Source->BufUsed;
1796 eptr = Target->buf + Target->BufSize - 8;
1797 tptr = Target->buf + Target->BufUsed;
1799 while (aptr < eiptr){
1801 IncreaseBuf(Target, 1, -1);
1802 eptr = Target->buf + Target->BufSize - 8;
1803 tptr = Target->buf + Target->BufUsed;
1806 if (*aptr == '\n') {
1810 else if (*aptr == '\r') {
1814 else if (*aptr == '\'') {
1820 Target->BufUsed += 5;
1833 * @ingroup StrBuf_DeEnCoder
1834 * @brief Append a string, escaping characters which have meaning in ICAL.
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 StrIcalEscAppend(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){
1867 if(tptr + 3 >= eptr) {
1868 IncreaseBuf(Target, 1, -1);
1869 eptr = Target->buf + Target->BufSize - 8;
1870 tptr = Target->buf + Target->BufUsed;
1873 if (*aptr == '\n') {
1880 else if (*aptr == '\r') {
1887 else if (*aptr == ',') {
1903 * @ingroup StrBuf_DeEnCoder
1904 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1906 * @param Target target buffer
1907 * @param Source source buffer; set to NULL if you just have a C-String
1908 * @param PlainIn Plain-C string to append; set to NULL if unused
1909 * @returns size of result or -1
1911 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1913 const char *aptr, *eiptr;
1917 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1920 if (PlainIn != NULL) {
1922 len = strlen(PlainIn);
1927 eiptr = aptr + Source->BufUsed;
1928 len = Source->BufUsed;
1934 bptr = Target->buf + Target->BufUsed;
1935 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1937 while (aptr < eiptr){
1939 IncreaseBuf(Target, 1, -1);
1940 eptr = Target->buf + Target->BufSize - 3;
1941 bptr = Target->buf + Target->BufUsed;
1948 Target->BufUsed += 2;
1949 } else if (*aptr == '\\') {
1954 Target->BufUsed += 2;
1964 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1966 return Target->BufUsed;
1970 * @ingroup StrBuf_DeEnCoder
1971 * @brief Append a string, escaping characters which have meaning in HTML + json.
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 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1977 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1978 * if set to 2, linebreaks are replaced by <br/>
1980 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1982 const char *aptr, *eiptr;
1985 int IsUtf8Sequence = 0;
1987 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1990 if (PlainIn != NULL) {
1992 len = strlen(PlainIn);
1997 eiptr = aptr + Source->BufUsed;
1998 len = Source->BufUsed;
2004 bptr = Target->buf + Target->BufUsed;
2005 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2007 while (aptr < eiptr){
2009 IncreaseBuf(Target, 1, -1);
2010 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2011 bptr = Target->buf + Target->BufUsed;
2014 memcpy(bptr, "<", 4);
2016 Target->BufUsed += 4;
2018 else if (*aptr == '>') {
2019 memcpy(bptr, ">", 4);
2021 Target->BufUsed += 4;
2023 else if (*aptr == '&') {
2024 memcpy(bptr, "&", 5);
2026 Target->BufUsed += 5;
2028 else if (*aptr == LB) {
2033 else if (*aptr == RB) {
2038 else if ((*aptr == 32) && (nbsp == 1)) {
2039 memcpy(bptr, " ", 6);
2041 Target->BufUsed += 6;
2043 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2044 *bptr='\0'; /* nothing */
2046 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2047 memcpy(bptr, "<br/>", 11);
2049 Target->BufUsed += 11;
2052 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2053 *bptr='\0'; /* nothing */
2056 else if ((*aptr == '"') || (*aptr == QU)) {
2061 Target->BufUsed += 2;
2062 } else if (*aptr == '\\') {
2067 Target->BufUsed += 2;
2070 if (((unsigned char)*aptr) >= 0x20)
2072 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2076 while (IsUtf8Sequence > 1){
2077 if(bptr + IsUtf8Sequence >= eptr) {
2078 IncreaseBuf(Target, 1, -1);
2079 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2080 bptr = Target->buf + Target->BufUsed - 1;
2094 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2096 return Target->BufUsed;
2100 * @ingroup StrBuf_DeEnCoder
2101 * @brief unhide special chars hidden to the HTML escaper
2102 * @param target buffer to put the unescaped string in
2103 * @param source buffer to unescape
2105 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2111 FlushStrBuf(target);
2113 if (source == NULL ||target == NULL)
2118 len = source->BufUsed;
2119 for (a = 0; a < len; ++a) {
2120 if (target->BufUsed >= target->BufSize)
2121 IncreaseBuf(target, 1, -1);
2123 if (source->buf[a] == '=') {
2124 hex[0] = source->buf[a + 1];
2125 hex[1] = source->buf[a + 2];
2128 sscanf(hex, "%02x", &b);
2129 target->buf[target->BufUsed] = b;
2130 target->buf[++target->BufUsed] = 0;
2134 target->buf[target->BufUsed] = source->buf[a];
2135 target->buf[++target->BufUsed] = 0;
2142 * @ingroup StrBuf_DeEnCoder
2143 * @brief hide special chars from the HTML escapers and friends
2144 * @param target buffer to put the escaped string in
2145 * @param source buffer to escape
2147 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2152 FlushStrBuf(target);
2154 if (source == NULL ||target == NULL)
2159 len = source->BufUsed;
2160 for (i=0; i<len; ++i) {
2161 if (target->BufUsed + 4 >= target->BufSize)
2162 IncreaseBuf(target, 1, -1);
2163 if ( (isalnum(source->buf[i])) ||
2164 (source->buf[i]=='-') ||
2165 (source->buf[i]=='_') ) {
2166 target->buf[target->BufUsed++] = source->buf[i];
2169 sprintf(&target->buf[target->BufUsed],
2171 (0xFF &source->buf[i]));
2172 target->BufUsed += 3;
2175 target->buf[target->BufUsed + 1] = '\0';
2179 /*******************************************************************************
2180 * Quoted Printable de/encoding *
2181 *******************************************************************************/
2184 * @ingroup StrBuf_DeEnCoder
2185 * @brief decode a buffer from base 64 encoding; destroys original
2186 * @param Buf Buffor to transform
2188 int StrBufDecodeBase64(StrBuf *Buf)
2192 if (Buf == NULL) return -1;
2194 xferbuf = (char*) malloc(Buf->BufSize);
2195 siz = CtdlDecodeBase64(xferbuf,
2205 * @ingroup StrBuf_DeEnCoder
2206 * @brief decode a buffer from base 64 encoding; destroys original
2207 * @param Buf Buffor to transform
2209 int StrBufDecodeHex(StrBuf *Buf)
2212 char *pch, *pche, *pchi;
2214 if (Buf == NULL) return -1;
2216 pch = pchi = Buf->buf;
2217 pche = pch + Buf->BufUsed;
2219 while (pchi < pche){
2220 ch = decode_hex(pchi);
2227 Buf->BufUsed = pch - Buf->buf;
2228 return Buf->BufUsed;
2232 * @ingroup StrBuf_DeEnCoder
2233 * @brief replace all chars >0x20 && < 0x7F with Mute
2234 * @param Mute char to put over invalid chars
2235 * @param Buf Buffor to transform
2237 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2241 if (Buf == NULL) return -1;
2242 pch = (unsigned char *)Buf->buf;
2243 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2244 if ((*pch < 0x20) || (*pch > 0x7F))
2248 return Buf->BufUsed;
2253 * @ingroup StrBuf_DeEnCoder
2254 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2255 * @param Buf Buffer to translate
2256 * @param StripBlanks Reduce several blanks to one?
2258 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2267 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2268 Buf->buf[Buf->BufUsed - 1] = '\0';
2273 while (a < Buf->BufUsed) {
2274 if (Buf->buf[a] == '+')
2276 else if (Buf->buf[a] == '%') {
2277 /* don't let % chars through, rather truncate the input. */
2278 if (a + 2 > Buf->BufUsed) {
2283 hex[0] = Buf->buf[a + 1];
2284 hex[1] = Buf->buf[a + 2];
2287 sscanf(hex, "%02x", &b);
2288 Buf->buf[a] = (char) b;
2289 len = Buf->BufUsed - a - 2;
2291 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2303 * @ingroup StrBuf_DeEnCoder
2304 * @brief RFC2047-encode a header field if necessary.
2305 * If no non-ASCII characters are found, the string
2306 * will be copied verbatim without encoding.
2308 * @param target Target buffer.
2309 * @param source Source string to be encoded.
2310 * @returns encoded length; -1 if non success.
2312 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2314 const char headerStr[] = "=?UTF-8?Q?";
2315 int need_to_encode = 0;
2319 if ((source == NULL) ||
2323 while ((i < source->BufUsed) &&
2324 (!IsEmptyStr (&source->buf[i])) &&
2325 (need_to_encode == 0)) {
2326 if (((unsigned char) source->buf[i] < 32) ||
2327 ((unsigned char) source->buf[i] > 126)) {
2333 if (!need_to_encode) {
2334 if (*target == NULL) {
2335 *target = NewStrBufPlain(source->buf, source->BufUsed);
2338 FlushStrBuf(*target);
2339 StrBufAppendBuf(*target, source, 0);
2341 return (*target)->BufUsed;
2343 if (*target == NULL)
2344 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2345 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2346 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2347 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2348 (*target)->BufUsed = sizeof(headerStr) - 1;
2349 for (i=0; (i < source->BufUsed); ++i) {
2350 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2351 IncreaseBuf(*target, 1, 0);
2352 ch = (unsigned char) source->buf[i];
2353 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2354 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2355 (*target)->BufUsed += 3;
2358 (*target)->buf[(*target)->BufUsed] = ch;
2359 (*target)->BufUsed++;
2363 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2364 IncreaseBuf(*target, 1, 0);
2366 (*target)->buf[(*target)->BufUsed++] = '?';
2367 (*target)->buf[(*target)->BufUsed++] = '=';
2368 (*target)->buf[(*target)->BufUsed] = '\0';
2369 return (*target)->BufUsed;;
2374 * @brief replaces all occurances of 'search' by 'replace'
2375 * @param buf Buffer to modify
2376 * @param search character to search
2377 * @param replace character to replace search by
2379 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2384 for (i=0; i<buf->BufUsed; i++)
2385 if (buf->buf[i] == search)
2386 buf->buf[i] = replace;
2392 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2393 * @param buf Buffer to modify
2395 void StrBufToUnixLF(StrBuf *buf)
2397 char *pche, *pchS, *pchT;
2401 pche = buf->buf + buf->BufUsed;
2402 pchS = pchT = buf->buf;
2408 if (*pchS != '\n') {
2417 buf->BufUsed = pchT - buf->buf;
2421 /*******************************************************************************
2422 * Iconv Wrapper; RFC822 de/encoding *
2423 *******************************************************************************/
2426 * @ingroup StrBuf_DeEnCoder
2427 * @brief Wrapper around iconv_open()
2428 * Our version adds aliases for non-standard Microsoft charsets
2429 * such as 'MS950', aliasing them to names like 'CP950'
2431 * @param tocode Target encoding
2432 * @param fromcode Source encoding
2433 * @param pic anonimized pointer to iconv struct
2435 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2438 iconv_t ic = (iconv_t)(-1) ;
2439 ic = iconv_open(tocode, fromcode);
2440 if (ic == (iconv_t)(-1) ) {
2441 char alias_fromcode[64];
2442 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2443 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2444 alias_fromcode[0] = 'C';
2445 alias_fromcode[1] = 'P';
2446 ic = iconv_open(tocode, alias_fromcode);
2449 *(iconv_t *)pic = ic;
2455 * @ingroup StrBuf_DeEnCoder
2456 * @brief find one chunk of a RFC822 encoded string
2457 * @param Buffer where to search
2458 * @param bptr where to start searching
2459 * @returns found position, NULL if none.
2461 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2464 /* Find the next ?Q? */
2465 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2468 end = strchr(bptr + 2, '?');
2473 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2474 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2475 (*(end + 2) == '?')) {
2476 /* skip on to the end of the cluster, the next ?= */
2477 end = strstr(end + 3, "?=");
2480 /* sort of half valid encoding, try to find an end. */
2481 end = strstr(bptr, "?=");
2487 * @brief swaps the contents of two StrBufs
2488 * this is to be used to have cheap switched between a work-buffer and a target buffer
2489 * @param A First one
2490 * @param B second one
2492 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2496 memcpy(&C, A, sizeof(*A));
2497 memcpy(A, B, sizeof(*B));
2498 memcpy(B, &C, sizeof(C));
2504 * @ingroup StrBuf_DeEnCoder
2505 * @brief convert one buffer according to the preselected iconv pointer PIC
2506 * @param ConvertBuf buffer we need to translate
2507 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2508 * @param pic Pointer to the iconv-session Object
2510 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2516 char *ibuf; /**< Buffer of characters to be converted */
2517 char *obuf; /**< Buffer for converted characters */
2518 size_t ibuflen; /**< Length of input buffer */
2519 size_t obuflen; /**< Length of output buffer */
2522 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2523 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2524 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2526 ic = *(iconv_t*)pic;
2527 ibuf = ConvertBuf->buf;
2528 ibuflen = ConvertBuf->BufUsed;
2530 obuflen = TmpBuf->BufSize;
2532 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2535 if (errno == E2BIG) {
2537 IncreaseBuf(TmpBuf, 0, 0);
2542 else if (errno == EILSEQ){
2543 /* hm, invalid utf8 sequence... what to do now? */
2544 /* An invalid multibyte sequence has been encountered in the input */
2546 else if (errno == EINVAL) {
2547 /* An incomplete multibyte sequence has been encountered in the input. */
2550 FlushStrBuf(TmpBuf);
2553 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2554 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2556 /* little card game: wheres the red lady? */
2557 SwapBuffers(ConvertBuf, TmpBuf);
2558 FlushStrBuf(TmpBuf);
2565 * @ingroup StrBuf_DeEnCoder
2566 * @brief catches one RFC822 encoded segment, and decodes it.
2567 * @param Target buffer to fill with result
2568 * @param DecodeMe buffer with stuff to process
2569 * @param SegmentStart points to our current segment in DecodeMe
2570 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2571 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2572 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2573 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2575 inline static void DecodeSegment(StrBuf *Target,
2576 const StrBuf *DecodeMe,
2577 const char *SegmentStart,
2578 const char *SegmentEnd,
2580 StrBuf *ConvertBuf2,
2581 StrBuf *FoundCharset)
2587 iconv_t ic = (iconv_t)(-1);
2591 /* Now we handle foreign character sets properly encoded
2592 * in RFC2047 format.
2594 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2595 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2596 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2597 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2598 if (FoundCharset != NULL) {
2599 FlushStrBuf(FoundCharset);
2600 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2602 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2603 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2605 *encoding = toupper(*encoding);
2606 if (*encoding == 'B') { /**< base64 */
2607 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2609 ConvertBuf->BufUsed);
2611 else if (*encoding == 'Q') { /**< quoted-printable */
2615 while (pos < ConvertBuf->BufUsed)
2617 if (ConvertBuf->buf[pos] == '_')
2618 ConvertBuf->buf[pos] = ' ';
2622 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2625 ConvertBuf->BufUsed);
2628 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2631 ctdl_iconv_open("UTF-8", charset, &ic);
2632 if (ic != (iconv_t)(-1) ) {
2634 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2635 StrBufAppendBuf(Target, ConvertBuf2, 0);
2640 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2646 * @ingroup StrBuf_DeEnCoder
2647 * @brief Handle subjects with RFC2047 encoding such as:
2648 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2649 * @param Target where to put the decoded string to
2650 * @param DecodeMe buffer with encoded string
2651 * @param DefaultCharset if we don't find one, which should we use?
2652 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2653 * put it here for later use where no string might be known.
2655 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2657 StrBuf *DecodedInvalidBuf = NULL;
2658 StrBuf *ConvertBuf, *ConvertBuf2;
2659 const StrBuf *DecodeMee = DecodeMe;
2660 const char *start, *end, *next, *nextend, *ptr = NULL;
2662 iconv_t ic = (iconv_t)(-1) ;
2667 int illegal_non_rfc2047_encoding = 0;
2669 /* Sometimes, badly formed messages contain strings which were simply
2670 * written out directly in some foreign character set instead of
2671 * using RFC2047 encoding. This is illegal but we will attempt to
2672 * handle it anyway by converting from a user-specified default
2673 * charset to UTF-8 if we see any nonprintable characters.
2676 len = StrLength(DecodeMe);
2677 for (i=0; i<DecodeMe->BufUsed; ++i) {
2678 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2679 illegal_non_rfc2047_encoding = 1;
2684 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2685 if ((illegal_non_rfc2047_encoding) &&
2686 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2687 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2690 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2691 if (ic != (iconv_t)(-1) ) {
2692 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2693 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2694 DecodeMee = DecodedInvalidBuf;
2700 /* pre evaluate the first pair */
2701 nextend = end = NULL;
2702 len = StrLength(DecodeMee);
2703 start = strstr(DecodeMee->buf, "=?");
2704 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2706 end = FindNextEnd (DecodeMee, start);
2708 StrBufAppendBuf(Target, DecodeMee, 0);
2709 FreeStrBuf(&ConvertBuf);
2710 FreeStrBuf(&DecodedInvalidBuf);
2714 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2716 if (start != DecodeMee->buf) {
2719 nFront = start - DecodeMee->buf;
2720 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2724 * Since spammers will go to all sorts of absurd lengths to get their
2725 * messages through, there are LOTS of corrupt headers out there.
2726 * So, prevent a really badly formed RFC2047 header from throwing
2727 * this function into an infinite loop.
2729 while ((start != NULL) &&
2736 DecodeSegment(Target,
2744 next = strstr(end, "=?");
2746 if ((next != NULL) &&
2748 nextend = FindNextEnd(DecodeMee, next);
2749 if (nextend == NULL)
2752 /* did we find two partitions */
2753 if ((next != NULL) &&
2757 while ((ptr < next) &&
2764 * did we find a gab just filled with blanks?
2765 * if not, copy its stuff over.
2769 StrBufAppendBufPlain(Target,
2775 /* our next-pair is our new first pair now. */
2781 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2782 if ((end != NULL) && (end < nextend)) {
2784 while ( (ptr < nextend) &&
2791 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2793 FreeStrBuf(&ConvertBuf);
2794 FreeStrBuf(&ConvertBuf2);
2795 FreeStrBuf(&DecodedInvalidBuf);
2798 /*******************************************************************************
2799 * Manipulating UTF-8 Strings *
2800 *******************************************************************************/
2804 * @brief evaluate the length of an utf8 special character sequence
2805 * @param Char the character to examine
2806 * @returns width of utf8 chars in bytes
2808 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2813 while ((n < 8) && ((test & *CharS) != 0)) {
2817 if ((n > 6) || ((CharE - CharS) < n))
2824 * @brief detect whether this char starts an utf-8 encoded char
2825 * @param Char character to inspect
2826 * @returns yes or no
2828 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2830 /** 11??.???? indicates an UTF8 Sequence. */
2831 return ((Char & 0xC0) != 0);
2836 * @brief measure the number of glyphs in an UTF8 string...
2837 * @param Buf string to measure
2838 * @returns the number of glyphs in Buf
2840 long StrBuf_Utf8StrLen(StrBuf *Buf)
2846 if ((Buf == NULL) || (Buf->BufUsed == 0))
2849 eptr = Buf->buf + Buf->BufUsed;
2850 while ((aptr < eptr) && (*aptr != '\0')) {
2851 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2852 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2853 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2866 * @brief cuts a string after maxlen glyphs
2867 * @param Buf string to cut to maxlen glyphs
2868 * @param maxlen how long may the string become?
2869 * @returns current length of the string
2871 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2877 eptr = Buf->buf + Buf->BufUsed;
2878 while ((aptr < eptr) && (*aptr != '\0')) {
2879 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2880 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2881 while ((*aptr++ != '\0') && (m-- > 0));
2890 Buf->BufUsed = aptr - Buf->buf;
2891 return Buf->BufUsed;
2894 return Buf->BufUsed;
2902 /*******************************************************************************
2904 *******************************************************************************/
2907 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2908 #define OS_CODE 0x03 /*< unix */
2911 * @ingroup StrBuf_DeEnCoder
2912 * @brief uses the same calling syntax as compress2(), but it
2913 * creates a stream compatible with HTTP "Content-encoding: gzip"
2914 * @param dest compressed buffer
2915 * @param destLen length of the compresed data
2916 * @param source source to encode
2917 * @param sourceLen length of source to encode
2918 * @param level compression level
2920 int ZEXPORT compress_gzip(Bytef * dest,
2922 const Bytef * source,
2926 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2928 /* write gzip header */
2929 snprintf((char *) dest, *destLen,
2930 "%c%c%c%c%c%c%c%c%c%c",
2931 gz_magic[0], gz_magic[1], Z_DEFLATED,
2932 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2935 /* normal deflate */
2938 stream.next_in = (Bytef *) source;
2939 stream.avail_in = (uInt) sourceLen;
2940 stream.next_out = dest + 10L; // after header
2941 stream.avail_out = (uInt) * destLen;
2942 if ((uLong) stream.avail_out != *destLen)
2945 stream.zalloc = (alloc_func) 0;
2946 stream.zfree = (free_func) 0;
2947 stream.opaque = (voidpf) 0;
2949 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2950 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2954 err = deflate(&stream, Z_FINISH);
2955 if (err != Z_STREAM_END) {
2956 deflateEnd(&stream);
2957 return err == Z_OK ? Z_BUF_ERROR : err;
2959 *destLen = stream.total_out + 10L;
2961 /* write CRC and Length */
2962 uLong crc = crc32(0L, source, sourceLen);
2964 for (n = 0; n < 4; ++n, ++*destLen) {
2965 dest[*destLen] = (int) (crc & 0xff);
2968 uLong len = stream.total_in;
2969 for (n = 0; n < 4; ++n, ++*destLen) {
2970 dest[*destLen] = (int) (len & 0xff);
2973 err = deflateEnd(&stream);
2980 * @ingroup StrBuf_DeEnCoder
2981 * @brief compress the buffer with gzip
2982 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2983 * @param Buf buffer whose content is to be gzipped
2985 int CompressBuffer(StrBuf *Buf)
2988 char *compressed_data = NULL;
2989 size_t compressed_len, bufsize;
2992 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2993 compressed_data = malloc(compressed_len);
2995 if (compressed_data == NULL)
2997 /* Flush some space after the used payload so valgrind shuts up... */
2998 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2999 Buf->buf[Buf->BufUsed + i++] = '\0';
3000 if (compress_gzip((Bytef *) compressed_data,
3003 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3006 Buf->buf = compressed_data;
3007 Buf->BufUsed = compressed_len;
3008 Buf->BufSize = bufsize;
3009 /* Flush some space after the used payload so valgrind shuts up... */
3011 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3012 Buf->buf[Buf->BufUsed + i++] = '\0';
3015 free(compressed_data);
3017 #endif /* HAVE_ZLIB */
3023 /*******************************************************************************
3024 * File I/O; Prefer buffered read since its faster! *
3025 *******************************************************************************/
3028 * @ingroup StrBuf_IO
3029 * @brief Read a line from socket
3030 * flushes and closes the FD on error
3031 * @param buf the buffer to get the input to
3032 * @param fd pointer to the filedescriptor to read
3033 * @param append Append to an existing string or replace?
3034 * @param Error strerror() on error
3035 * @returns numbers of chars read
3037 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3039 int len, rlen, slen;
3044 slen = len = buf->BufUsed;
3046 rlen = read(*fd, &buf->buf[len], 1);
3048 *Error = strerror(errno);
3055 if (buf->buf[len] == '\n')
3057 if (buf->buf[len] != '\r')
3059 if (len + 2 >= buf->BufSize) {
3061 buf->buf[len+1] = '\0';
3062 IncreaseBuf(buf, 1, -1);
3066 buf->buf[len] = '\0';
3071 * @ingroup StrBuf_BufferedIO
3072 * @brief Read a line from socket
3073 * flushes and closes the FD on error
3074 * @param Line the line to read from the fd / I/O Buffer
3075 * @param buf the buffer to get the input to
3076 * @param fd pointer to the filedescriptor to read
3077 * @param timeout number of successless selects until we bail out
3078 * @param selectresolution how long to wait on each select
3079 * @param Error strerror() on error
3080 * @returns numbers of chars read
3082 int StrBufTCP_read_buffered_line(StrBuf *Line,
3086 int selectresolution,
3090 int nSuccessLess = 0;
3097 if (buf->BufUsed > 0) {
3098 pch = strchr(buf->buf, '\n');
3101 len = pch - buf->buf;
3102 if (len > 0 && (*(pch - 1) == '\r') )
3104 StrBufSub(Line, buf, 0, len - rlen);
3105 StrBufCutLeft(buf, len + 1);
3110 if (buf->BufSize - buf->BufUsed < 10)
3111 IncreaseBuf(buf, 1, -1);
3113 fdflags = fcntl(*fd, F_GETFL);
3114 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3116 while ((nSuccessLess < timeout) && (pch == NULL)) {
3118 tv.tv_sec = selectresolution;
3123 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3124 *Error = strerror(errno);
3130 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3135 &buf->buf[buf->BufUsed],
3136 buf->BufSize - buf->BufUsed - 1);
3138 *Error = strerror(errno);
3143 else if (rlen > 0) {
3145 buf->BufUsed += rlen;
3146 buf->buf[buf->BufUsed] = '\0';
3147 if (buf->BufUsed + 10 > buf->BufSize) {
3148 IncreaseBuf(buf, 1, -1);
3150 pch = strchr(buf->buf, '\n');
3157 len = pch - buf->buf;
3158 if (len > 0 && (*(pch - 1) == '\r') )
3160 StrBufSub(Line, buf, 0, len - rlen);
3161 StrBufCutLeft(buf, len + 1);
3168 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3169 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3170 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3172 * @ingroup StrBuf_BufferedIO
3173 * @brief Read a line from socket
3174 * flushes and closes the FD on error
3175 * @param Line where to append our Line read from the fd / I/O Buffer;
3176 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3177 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3178 * @param fd pointer to the filedescriptor to read
3179 * @param timeout number of successless selects until we bail out
3180 * @param selectresolution how long to wait on each select
3181 * @param Error strerror() on error
3182 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3184 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3189 int selectresolution,
3192 const char *pche = NULL;
3193 const char *pos = NULL;
3195 int len, rlen, retlen;
3196 int nSuccessLess = 0;
3198 const char *pch = NULL;
3204 if ((Line == NULL) ||
3211 *Error = ErrRBLF_PreConditionFailed;
3216 if ((IOBuf->BufUsed > 0) &&
3218 (pos < IOBuf->buf + IOBuf->BufUsed))
3222 pche = IOBuf->buf + IOBuf->BufUsed;
3226 while ((pch < pche) && (*pch != '\n'))
3228 if (Line->BufUsed + 10 > Line->BufSize)
3231 apos = pcht - Line->buf;
3233 IncreaseBuf(Line, 1, -1);
3234 pcht = Line->buf + apos;
3242 if (len > 0 && (*(pch - 1) == '\r') )
3251 if ((pch >= pche) || (*pch == '\0'))
3259 if ((pch != NULL) &&
3262 if (pch + 1 >= pche) {
3275 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3277 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3278 IncreaseBuf(IOBuf, 1, -1);
3280 fdflags = fcntl(*fd, F_GETFL);
3281 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3284 while ((nSuccessLess < timeout) &&
3294 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3295 *Error = strerror(errno);
3299 *Error = ErrRBLF_SelectFailed;
3302 if (! FD_ISSET(*fd, &rfds) != 0) {
3308 &IOBuf->buf[IOBuf->BufUsed],
3309 IOBuf->BufSize - IOBuf->BufUsed - 1);
3311 *Error = strerror(errno);
3316 else if (rlen > 0) {
3318 pLF = IOBuf->buf + IOBuf->BufUsed;
3319 IOBuf->BufUsed += rlen;
3320 IOBuf->buf[IOBuf->BufUsed] = '\0';
3322 pche = IOBuf->buf + IOBuf->BufUsed;
3324 while ((pLF < pche) && (*pLF != '\n'))
3326 if ((pLF >= pche) || (*pLF == '\0'))
3329 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3333 if (pLF != NULL) apos = pLF - IOBuf->buf;
3334 IncreaseBuf(IOBuf, 1, -1);
3335 if (pLF != NULL) pLF = IOBuf->buf + apos;
3345 if (len > 0 && (*(pLF - 1) == '\r') )
3347 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3348 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3354 return retlen + len;
3356 *Error = ErrRBLF_NotEnoughSentFromServer;
3361 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3363 * @ingroup StrBuf_IO
3364 * @brief Input binary data from socket
3365 * flushes and closes the FD on error
3366 * @param Buf the buffer to get the input to
3367 * @param fd pointer to the filedescriptor to read
3368 * @param append Append to an existing string or replace?
3369 * @param nBytes the maximal number of bytes to read
3370 * @param Error strerror() on error
3371 * @returns numbers of chars read
3373 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3376 int len, rlen, slen;
3384 if ((Buf == NULL) || (*fd == -1))
3386 *Error = ErrRBLF_BLOBPreConditionFailed;
3391 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3392 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3394 ptr = Buf->buf + Buf->BufUsed;
3396 slen = len = Buf->BufUsed;
3398 fdflags = fcntl(*fd, F_GETFL);
3399 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3401 while ((nRead < nBytes) &&
3411 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3412 *Error = strerror(errno);
3416 *Error = ErrRBLF_SelectFailed;
3419 if (! FD_ISSET(*fd, &rfds) != 0) {
3425 if ((rlen = read(*fd,
3427 nBytes - nRead)) == -1) {
3430 *Error = strerror(errno);
3435 Buf->BufUsed += rlen;
3437 Buf->buf[Buf->BufUsed] = '\0';
3441 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3442 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3444 * @ingroup StrBuf_BufferedIO
3445 * @brief Input binary data from socket
3446 * flushes and closes the FD on error
3447 * @param Blob put binary thing here
3448 * @param IOBuf the buffer to get the input to
3449 * @param Pos offset inside of IOBuf
3450 * @param fd pointer to the filedescriptor to read
3451 * @param append Append to an existing string or replace?
3452 * @param nBytes the maximal number of bytes to read
3453 * @param check whether we should search for '000\n' terminators in case of timeouts
3454 * @param Error strerror() on error
3455 * @returns numbers of chars read
3457 int StrBufReadBLOBBuffered(StrBuf *Blob,
3474 int nAlreadyRead = 0;
3482 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3486 *Error = ErrRBB_BLOBFPreConditionFailed;
3492 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3493 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3498 len = pos - IOBuf->buf;
3499 rlen = IOBuf->BufUsed - len;
3502 if ((IOBuf->BufUsed > 0) &&
3504 (pos < IOBuf->buf + IOBuf->BufUsed))
3506 pche = IOBuf->buf + IOBuf->BufUsed;
3509 if (rlen < nBytes) {
3510 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3511 Blob->BufUsed += rlen;
3512 Blob->buf[Blob->BufUsed] = '\0';
3513 nAlreadyRead = nRead = rlen;
3516 if (rlen >= nBytes) {
3517 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3518 Blob->BufUsed += nBytes;
3519 Blob->buf[Blob->BufUsed] = '\0';
3520 if (rlen == nBytes) {
3532 if (IOBuf->BufSize < nBytes - nRead)
3533 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3536 slen = len = Blob->BufUsed;
3538 fdflags = fcntl(*fd, F_GETFL);
3539 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3544 while ((nRead < nBytes) &&
3553 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3554 *Error = strerror(errno);
3558 *Error = ErrRBLF_SelectFailed;
3561 if (! FD_ISSET(*fd, &rfds) != 0) {
3573 *Error = strerror(errno);
3576 else if (rlen == 0){
3578 if ((check == NNN_TERM) &&
3580 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3582 StrBufPlain(Blob, HKEY("\n000\n"));
3583 StrBufCutRight(Blob, 5);
3584 return Blob->BufUsed;
3586 if (nSelects > 10) {
3588 *Error = ErrRBB_too_many_selects;
3592 else if (rlen > 0) {
3595 IOBuf->BufUsed += rlen;
3598 if (nRead > nBytes) {
3599 *Pos = IOBuf->buf + nBytes;
3601 Blob->buf[Blob->BufUsed] = '\0';
3602 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3606 return nRead + nAlreadyRead;
3610 * @ingroup StrBuf_IO
3611 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3612 * @param LineBuf your line will be copied here.
3613 * @param Buf BLOB with lines of text...
3614 * @param Ptr moved arround to keep the next-line across several iterations
3615 * has to be &NULL on start; will be &NotNULL on end of buffer
3616 * @returns size of copied buffer
3618 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3620 const char *aptr, *ptr, *eptr;
3623 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3624 *Ptr = StrBufNOTNULL;
3628 FlushStrBuf(LineBuf);
3630 ptr = aptr = Buf->buf;
3634 optr = LineBuf->buf;
3635 eptr = Buf->buf + Buf->BufUsed;
3636 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3638 while ((ptr <= eptr) &&
3645 LineBuf->BufUsed = optr - LineBuf->buf;
3646 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3647 optr = LineBuf->buf + LineBuf->BufUsed;
3648 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3652 if ((ptr >= eptr) && (optr > LineBuf->buf))
3654 LineBuf->BufUsed = optr - LineBuf->buf;
3656 if ((ptr <= eptr) && (*ptr == '\r'))
3658 if ((ptr <= eptr) && (*ptr == '\n'))
3665 *Ptr = StrBufNOTNULL;
3668 return Buf->BufUsed - (ptr - Buf->buf);
3673 * @ingroup StrBuf_IO
3674 * @brief removes double slashes from pathnames
3675 * @param Dir directory string to filter
3676 * @param RemoveTrailingSlash allows / disallows trailing slashes
3678 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3684 while (!IsEmptyStr(a)) {
3696 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3701 Dir->BufUsed = b - Dir->buf;