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 Counts the numbmer of tokens in a buffer
997 * @param source String to count tokens in
998 * @param tok Tokenizer char to count
999 * @returns numbers of tokenizer chars found
1001 int StrBufNum_tokens(const StrBuf *source, char tok)
1005 if ((source == NULL) || (source->BufUsed == 0))
1007 if ((source->BufUsed == 1) && (*source->buf == tok))
1011 pche = pch + source->BufUsed;
1022 * @ingroup StrBuf_Tokenizer
1023 * @brief a string tokenizer
1024 * @param Source StringBuffer to read into
1025 * @param parmnum n'th Parameter to remove
1026 * @param separator tokenizer character
1027 * @returns -1 if not found, else length of token.
1029 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1032 char *d, *s, *end; /* dest, source */
1035 /* Find desired @parameter */
1036 end = Source->buf + Source->BufUsed;
1038 while ((d <= end) &&
1041 /* End of string, bail! */
1046 if (*d == separator) {
1051 if ((d == NULL) || (d >= end))
1052 return 0; /* @Parameter not found */
1054 /* Find next @parameter */
1056 while ((s <= end) &&
1057 (*s && *s != separator))
1061 if (*s == separator)
1065 /* Hack and slash */
1070 memmove(d, s, Source->BufUsed - (s - Source->buf));
1071 Source->BufUsed += ReducedBy;
1072 Source->buf[Source->BufUsed] = '\0';
1074 else if (d == Source->buf) {
1076 Source->BufUsed = 0;
1080 Source->BufUsed += ReducedBy;
1093 * @ingroup StrBuf_Tokenizer
1094 * @brief a string tokenizer
1095 * @param dest Destination StringBuffer
1096 * @param Source StringBuffer to read into
1097 * @param parmnum n'th Parameter to extract
1098 * @param separator tokenizer character
1099 * @returns -1 if not found, else length of token.
1101 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1103 const char *s, *e; //* source * /
1104 int len = 0; //* running total length of extracted string * /
1105 int current_token = 0; //* token currently being processed * /
1108 dest->buf[0] = '\0';
1114 if ((Source == NULL) || (Source->BufUsed ==0)) {
1118 e = s + Source->BufUsed;
1121 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1123 while ((s<e) && !IsEmptyStr(s)) {
1124 if (*s == separator) {
1127 if (len >= dest->BufSize) {
1128 dest->BufUsed = len;
1129 if (IncreaseBuf(dest, 1, -1) < 0) {
1134 if ( (current_token == parmnum) &&
1135 (*s != separator)) {
1136 dest->buf[len] = *s;
1139 else if (current_token > parmnum) {
1145 dest->buf[len] = '\0';
1146 dest->BufUsed = len;
1148 if (current_token < parmnum) {
1149 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1152 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1161 * @ingroup StrBuf_Tokenizer
1162 * @brief a string tokenizer to fetch an integer
1163 * @param Source String containing tokens
1164 * @param parmnum n'th Parameter to extract
1165 * @param separator tokenizer character
1166 * @returns 0 if not found, else integer representation of the token
1168 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1178 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1185 * @ingroup StrBuf_Tokenizer
1186 * @brief a string tokenizer to fetch a long integer
1187 * @param Source String containing tokens
1188 * @param parmnum n'th Parameter to extract
1189 * @param separator tokenizer character
1190 * @returns 0 if not found, else long integer representation of the token
1192 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1202 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1210 * @ingroup StrBuf_Tokenizer
1211 * @brief a string tokenizer to fetch an unsigned long
1212 * @param Source String containing tokens
1213 * @param parmnum n'th Parameter to extract
1214 * @param separator tokenizer character
1215 * @returns 0 if not found, else unsigned long representation of the token
1217 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1228 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1232 return (unsigned long) atol(pnum);
1241 * @ingroup StrBuf_NextTokenizer
1242 * @brief a string tokenizer; Bounds checker
1243 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1244 * @param Source our tokenbuffer
1245 * @param pStart the token iterator pointer to inspect
1246 * @returns whether the revolving pointer is inside of the search range
1248 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1250 if ((Source == NULL) ||
1251 (*pStart == StrBufNOTNULL) ||
1252 (Source->BufUsed == 0))
1256 if (*pStart == NULL)
1260 else if (*pStart > Source->buf + Source->BufUsed)
1264 else if (*pStart <= Source->buf)
1273 * @ingroup StrBuf_NextTokenizer
1274 * @brief a string tokenizer
1275 * @param dest Destination StringBuffer
1276 * @param Source StringBuffer to read into
1277 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1278 * @param separator tokenizer
1279 * @returns -1 if not found, else length of token.
1281 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1283 const char *s; /* source */
1284 const char *EndBuffer; /* end stop of source buffer */
1285 int current_token = 0; /* token currently being processed */
1286 int len = 0; /* running total length of extracted string */
1288 if ((Source == NULL) ||
1289 (Source->BufUsed == 0) )
1291 *pStart = StrBufNOTNULL;
1295 EndBuffer = Source->buf + Source->BufUsed;
1299 dest->buf[0] = '\0';
1304 *pStart = EndBuffer + 1;
1308 if (*pStart == NULL)
1310 *pStart = Source->buf; /* we're starting to examine this buffer. */
1312 else if ((*pStart < Source->buf) ||
1313 (*pStart > EndBuffer ) )
1315 return -1; /* no more tokens to find. */
1319 /* start to find the next token */
1320 while ((s <= EndBuffer) &&
1321 (current_token == 0) )
1323 if (*s == separator)
1325 /* we found the next token */
1329 if (len >= dest->BufSize)
1331 /* our Dest-buffer isn't big enough, increase it. */
1332 dest->BufUsed = len;
1334 if (IncreaseBuf(dest, 1, -1) < 0) {
1335 /* WHUT? no more mem? bail out. */
1342 if ( (current_token == 0 ) && /* are we in our target token? */
1343 (!IsEmptyStr(s) ) &&
1344 (separator != *s) ) /* don't copy the token itself */
1346 dest->buf[len] = *s; /* Copy the payload */
1347 ++len; /* remember the bigger size. */
1353 /* did we reach the end? */
1354 if ((s > EndBuffer)) {
1355 EndBuffer = StrBufNOTNULL;
1356 *pStart = EndBuffer;
1359 *pStart = s; /* remember the position for the next run */
1362 /* sanitize our extracted token */
1363 dest->buf[len] = '\0';
1364 dest->BufUsed = len;
1371 * @ingroup StrBuf_NextTokenizer
1372 * @brief a string tokenizer
1373 * @param Source StringBuffer to read from
1374 * @param pStart pointer to the end of the last token. Feed with NULL.
1375 * @param separator tokenizer character
1376 * @param nTokens number of tokens to fastforward over
1377 * @returns -1 if not found, else length of token.
1379 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1381 const char *s, *EndBuffer; //* source * /
1382 int len = 0; //* running total length of extracted string * /
1383 int current_token = 0; //* token currently being processed * /
1385 if ((Source == NULL) ||
1386 (Source->BufUsed ==0)) {
1390 return Source->BufUsed;
1392 if (*pStart == NULL)
1393 *pStart = Source->buf;
1395 EndBuffer = Source->buf + Source->BufUsed;
1397 if ((*pStart < Source->buf) ||
1398 (*pStart > EndBuffer)) {
1406 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1408 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1409 if (*s == separator) {
1412 if (current_token >= nTokens) {
1424 * @ingroup StrBuf_NextTokenizer
1425 * @brief a string tokenizer to fetch an integer
1426 * @param Source StringBuffer to read from
1427 * @param pStart Cursor on the tokenstring
1428 * @param separator tokenizer character
1429 * @returns 0 if not found, else integer representation of the token
1431 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1441 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1448 * @ingroup StrBuf_NextTokenizer
1449 * @brief a string tokenizer to fetch a long integer
1450 * @param Source StringBuffer to read from
1451 * @param pStart Cursor on the tokenstring
1452 * @param separator tokenizer character
1453 * @returns 0 if not found, else long integer representation of the token
1455 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1465 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1473 * @ingroup StrBuf_NextTokenizer
1474 * @brief a string tokenizer to fetch an unsigned long
1475 * @param Source StringBuffer to read from
1476 * @param pStart Cursor on the tokenstring
1477 * @param separator tokenizer character
1478 * @returns 0 if not found, else unsigned long representation of the token
1480 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1491 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1495 return (unsigned long) atol(pnum);
1505 /*******************************************************************************
1506 * Escape Appending *
1507 *******************************************************************************/
1510 * @ingroup StrBuf_DeEnCoder
1511 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1512 * @param OutBuf the output buffer
1513 * @param In Buffer to encode
1514 * @param PlainIn way in from plain old c strings
1516 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1518 const char *pch, *pche;
1522 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1524 if (PlainIn != NULL) {
1525 len = strlen(PlainIn);
1531 pche = pch + In->BufUsed;
1538 pt = OutBuf->buf + OutBuf->BufUsed;
1539 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1541 while (pch < pche) {
1543 IncreaseBuf(OutBuf, 1, -1);
1544 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1545 pt = OutBuf->buf + OutBuf->BufUsed;
1548 if((*pch >= 'a' && *pch <= 'z') ||
1549 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1550 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1551 (*pch == '!') || (*pch == '_') ||
1552 (*pch == ',') || (*pch == '.') ||
1560 *(pt + 1) = HexList[(unsigned char)*pch][0];
1561 *(pt + 2) = HexList[(unsigned char)*pch][1];
1563 OutBuf->BufUsed += 3;
1571 * @ingroup StrBuf_DeEnCoder
1572 * @brief append a string in hex encoding to the buffer
1573 * @param OutBuf the output buffer
1574 * @param In Buffer to encode
1575 * @param PlainIn way in from plain old c strings
1577 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1579 const char *pch, *pche;
1583 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1585 if (PlainIn != NULL) {
1586 len = strlen(PlainIn);
1592 pche = pch + In->BufUsed;
1599 pt = OutBuf->buf + OutBuf->BufUsed;
1600 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1602 while (pch < pche) {
1604 IncreaseBuf(OutBuf, 1, -1);
1605 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1606 pt = OutBuf->buf + OutBuf->BufUsed;
1609 *pt = HexList[(unsigned char)*pch][0];
1611 *pt = HexList[(unsigned char)*pch][1];
1612 pt ++; pch ++; OutBuf->BufUsed += 2;
1618 * @ingroup StrBuf_DeEnCoder
1619 * @brief Append a string, escaping characters which have meaning in HTML.
1621 * @param Target target buffer
1622 * @param Source source buffer; set to NULL if you just have a C-String
1623 * @param PlainIn Plain-C string to append; set to NULL if unused
1624 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1625 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1626 * if set to 2, linebreaks are replaced by <br/>
1628 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1630 const char *aptr, *eiptr;
1634 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1637 if (PlainIn != NULL) {
1639 len = strlen(PlainIn);
1644 eiptr = aptr + Source->BufUsed;
1645 len = Source->BufUsed;
1651 bptr = Target->buf + Target->BufUsed;
1652 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1654 while (aptr < eiptr){
1656 IncreaseBuf(Target, 1, -1);
1657 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1658 bptr = Target->buf + Target->BufUsed;
1661 memcpy(bptr, "<", 4);
1663 Target->BufUsed += 4;
1665 else if (*aptr == '>') {
1666 memcpy(bptr, ">", 4);
1668 Target->BufUsed += 4;
1670 else if (*aptr == '&') {
1671 memcpy(bptr, "&", 5);
1673 Target->BufUsed += 5;
1675 else if (*aptr == '"') {
1676 memcpy(bptr, """, 6);
1678 Target->BufUsed += 6;
1680 else if (*aptr == '\'') {
1681 memcpy(bptr, "'", 5);
1683 Target->BufUsed += 5;
1685 else if (*aptr == LB) {
1690 else if (*aptr == RB) {
1695 else if (*aptr == QU) {
1700 else if ((*aptr == 32) && (nbsp == 1)) {
1701 memcpy(bptr, " ", 6);
1703 Target->BufUsed += 6;
1705 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1706 *bptr='\0'; /* nothing */
1708 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1709 memcpy(bptr, "<br/>", 11);
1711 Target->BufUsed += 11;
1715 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1716 *bptr='\0'; /* nothing */
1726 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1728 return Target->BufUsed;
1732 * @ingroup StrBuf_DeEnCoder
1733 * @brief Append a string, escaping characters which have meaning in HTML.
1734 * Converts linebreaks into blanks; escapes single quotes
1735 * @param Target target buffer
1736 * @param Source source buffer; set to NULL if you just have a C-String
1737 * @param PlainIn Plain-C string to append; set to NULL if unused
1739 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1741 const char *aptr, *eiptr;
1745 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1748 if (PlainIn != NULL) {
1750 len = strlen(PlainIn);
1755 eiptr = aptr + Source->BufUsed;
1756 len = Source->BufUsed;
1762 eptr = Target->buf + Target->BufSize - 8;
1763 tptr = Target->buf + Target->BufUsed;
1765 while (aptr < eiptr){
1767 IncreaseBuf(Target, 1, -1);
1768 eptr = Target->buf + Target->BufSize - 8;
1769 tptr = Target->buf + Target->BufUsed;
1772 if (*aptr == '\n') {
1776 else if (*aptr == '\r') {
1780 else if (*aptr == '\'') {
1786 Target->BufUsed += 5;
1799 * @ingroup StrBuf_DeEnCoder
1800 * @brief Append a string, escaping characters which have meaning in ICAL.
1802 * @param Target target buffer
1803 * @param Source source buffer; set to NULL if you just have a C-String
1804 * @param PlainIn Plain-C string to append; set to NULL if unused
1806 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1808 const char *aptr, *eiptr;
1812 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1815 if (PlainIn != NULL) {
1817 len = strlen(PlainIn);
1822 eiptr = aptr + Source->BufUsed;
1823 len = Source->BufUsed;
1829 eptr = Target->buf + Target->BufSize - 8;
1830 tptr = Target->buf + Target->BufUsed;
1832 while (aptr < eiptr){
1833 if(tptr + 3 >= eptr) {
1834 IncreaseBuf(Target, 1, -1);
1835 eptr = Target->buf + Target->BufSize - 8;
1836 tptr = Target->buf + Target->BufUsed;
1839 if (*aptr == '\n') {
1846 else if (*aptr == '\r') {
1853 else if (*aptr == ',') {
1869 * @ingroup StrBuf_DeEnCoder
1870 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1872 * @param Target target buffer
1873 * @param Source source buffer; set to NULL if you just have a C-String
1874 * @param PlainIn Plain-C string to append; set to NULL if unused
1875 * @returns size of result or -1
1877 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1879 const char *aptr, *eiptr;
1883 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1886 if (PlainIn != NULL) {
1888 len = strlen(PlainIn);
1893 eiptr = aptr + Source->BufUsed;
1894 len = Source->BufUsed;
1900 bptr = Target->buf + Target->BufUsed;
1901 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1903 while (aptr < eiptr){
1905 IncreaseBuf(Target, 1, -1);
1906 eptr = Target->buf + Target->BufSize - 3;
1907 bptr = Target->buf + Target->BufUsed;
1914 Target->BufUsed += 2;
1915 } else if (*aptr == '\\') {
1920 Target->BufUsed += 2;
1930 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1932 return Target->BufUsed;
1936 * @ingroup StrBuf_DeEnCoder
1937 * @brief Append a string, escaping characters which have meaning in HTML + json.
1939 * @param Target target buffer
1940 * @param Source source buffer; set to NULL if you just have a C-String
1941 * @param PlainIn Plain-C string to append; set to NULL if unused
1942 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1943 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1944 * if set to 2, linebreaks are replaced by <br/>
1946 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1948 const char *aptr, *eiptr;
1951 int IsUtf8Sequence = 0;
1953 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1956 if (PlainIn != NULL) {
1958 len = strlen(PlainIn);
1963 eiptr = aptr + Source->BufUsed;
1964 len = Source->BufUsed;
1970 bptr = Target->buf + Target->BufUsed;
1971 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1973 while (aptr < eiptr){
1975 IncreaseBuf(Target, 1, -1);
1976 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1977 bptr = Target->buf + Target->BufUsed;
1980 memcpy(bptr, "<", 4);
1982 Target->BufUsed += 4;
1984 else if (*aptr == '>') {
1985 memcpy(bptr, ">", 4);
1987 Target->BufUsed += 4;
1989 else if (*aptr == '&') {
1990 memcpy(bptr, "&", 5);
1992 Target->BufUsed += 5;
1994 else if (*aptr == LB) {
1999 else if (*aptr == RB) {
2004 else if ((*aptr == 32) && (nbsp == 1)) {
2005 memcpy(bptr, " ", 6);
2007 Target->BufUsed += 6;
2009 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2010 *bptr='\0'; /* nothing */
2012 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2013 memcpy(bptr, "<br/>", 11);
2015 Target->BufUsed += 11;
2018 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2019 *bptr='\0'; /* nothing */
2022 else if ((*aptr == '"') || (*aptr == QU)) {
2027 Target->BufUsed += 2;
2028 } else if (*aptr == '\\') {
2033 Target->BufUsed += 2;
2036 if (((unsigned char)*aptr) >= 0x20)
2038 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2042 while (IsUtf8Sequence > 1){
2043 if(bptr + IsUtf8Sequence >= eptr) {
2044 IncreaseBuf(Target, 1, -1);
2045 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2046 bptr = Target->buf + Target->BufUsed - 1;
2060 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2062 return Target->BufUsed;
2066 * @ingroup StrBuf_DeEnCoder
2067 * @brief unhide special chars hidden to the HTML escaper
2068 * @param target buffer to put the unescaped string in
2069 * @param source buffer to unescape
2071 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2077 FlushStrBuf(target);
2079 if (source == NULL ||target == NULL)
2084 len = source->BufUsed;
2085 for (a = 0; a < len; ++a) {
2086 if (target->BufUsed >= target->BufSize)
2087 IncreaseBuf(target, 1, -1);
2089 if (source->buf[a] == '=') {
2090 hex[0] = source->buf[a + 1];
2091 hex[1] = source->buf[a + 2];
2094 sscanf(hex, "%02x", &b);
2095 target->buf[target->BufUsed] = b;
2096 target->buf[++target->BufUsed] = 0;
2100 target->buf[target->BufUsed] = source->buf[a];
2101 target->buf[++target->BufUsed] = 0;
2108 * @ingroup StrBuf_DeEnCoder
2109 * @brief hide special chars from the HTML escapers and friends
2110 * @param target buffer to put the escaped string in
2111 * @param source buffer to escape
2113 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2118 FlushStrBuf(target);
2120 if (source == NULL ||target == NULL)
2125 len = source->BufUsed;
2126 for (i=0; i<len; ++i) {
2127 if (target->BufUsed + 4 >= target->BufSize)
2128 IncreaseBuf(target, 1, -1);
2129 if ( (isalnum(source->buf[i])) ||
2130 (source->buf[i]=='-') ||
2131 (source->buf[i]=='_') ) {
2132 target->buf[target->BufUsed++] = source->buf[i];
2135 sprintf(&target->buf[target->BufUsed],
2137 (0xFF &source->buf[i]));
2138 target->BufUsed += 3;
2141 target->buf[target->BufUsed + 1] = '\0';
2145 /*******************************************************************************
2146 * Quoted Printable de/encoding *
2147 *******************************************************************************/
2150 * @ingroup StrBuf_DeEnCoder
2151 * @brief decode a buffer from base 64 encoding; destroys original
2152 * @param Buf Buffor to transform
2154 int StrBufDecodeBase64(StrBuf *Buf)
2158 if (Buf == NULL) return -1;
2160 xferbuf = (char*) malloc(Buf->BufSize);
2161 siz = CtdlDecodeBase64(xferbuf,
2171 * @ingroup StrBuf_DeEnCoder
2172 * @brief decode a buffer from base 64 encoding; destroys original
2173 * @param Buf Buffor to transform
2175 int StrBufDecodeHex(StrBuf *Buf)
2178 char *pch, *pche, *pchi;
2180 if (Buf == NULL) return -1;
2182 pch = pchi = Buf->buf;
2183 pche = pch + Buf->BufUsed;
2185 while (pchi < pche){
2186 ch = decode_hex(pchi);
2193 Buf->BufUsed = pch - Buf->buf;
2194 return Buf->BufUsed;
2198 * @ingroup StrBuf_DeEnCoder
2199 * @brief replace all chars >0x20 && < 0x7F with Mute
2200 * @param Mute char to put over invalid chars
2201 * @param Buf Buffor to transform
2203 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2207 if (Buf == NULL) return -1;
2208 pch = (unsigned char *)Buf->buf;
2209 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2210 if ((*pch < 0x20) || (*pch > 0x7F))
2214 return Buf->BufUsed;
2219 * @ingroup StrBuf_DeEnCoder
2220 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2221 * @param Buf Buffer to translate
2222 * @param StripBlanks Reduce several blanks to one?
2224 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2233 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2234 Buf->buf[Buf->BufUsed - 1] = '\0';
2239 while (a < Buf->BufUsed) {
2240 if (Buf->buf[a] == '+')
2242 else if (Buf->buf[a] == '%') {
2243 /* don't let % chars through, rather truncate the input. */
2244 if (a + 2 > Buf->BufUsed) {
2249 hex[0] = Buf->buf[a + 1];
2250 hex[1] = Buf->buf[a + 2];
2253 sscanf(hex, "%02x", &b);
2254 Buf->buf[a] = (char) b;
2255 len = Buf->BufUsed - a - 2;
2257 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2269 * @ingroup StrBuf_DeEnCoder
2270 * @brief RFC2047-encode a header field if necessary.
2271 * If no non-ASCII characters are found, the string
2272 * will be copied verbatim without encoding.
2274 * @param target Target buffer.
2275 * @param source Source string to be encoded.
2276 * @returns encoded length; -1 if non success.
2278 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2280 const char headerStr[] = "=?UTF-8?Q?";
2281 int need_to_encode = 0;
2285 if ((source == NULL) ||
2289 while ((i < source->BufUsed) &&
2290 (!IsEmptyStr (&source->buf[i])) &&
2291 (need_to_encode == 0)) {
2292 if (((unsigned char) source->buf[i] < 32) ||
2293 ((unsigned char) source->buf[i] > 126)) {
2299 if (!need_to_encode) {
2300 if (*target == NULL) {
2301 *target = NewStrBufPlain(source->buf, source->BufUsed);
2304 FlushStrBuf(*target);
2305 StrBufAppendBuf(*target, source, 0);
2307 return (*target)->BufUsed;
2309 if (*target == NULL)
2310 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2311 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2312 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2313 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2314 (*target)->BufUsed = sizeof(headerStr) - 1;
2315 for (i=0; (i < source->BufUsed); ++i) {
2316 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2317 IncreaseBuf(*target, 1, 0);
2318 ch = (unsigned char) source->buf[i];
2319 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2320 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2321 (*target)->BufUsed += 3;
2324 (*target)->buf[(*target)->BufUsed] = ch;
2325 (*target)->BufUsed++;
2329 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2330 IncreaseBuf(*target, 1, 0);
2332 (*target)->buf[(*target)->BufUsed++] = '?';
2333 (*target)->buf[(*target)->BufUsed++] = '=';
2334 (*target)->buf[(*target)->BufUsed] = '\0';
2335 return (*target)->BufUsed;;
2340 * @brief replaces all occurances of 'search' by 'replace'
2341 * @param buf Buffer to modify
2342 * @param search character to search
2343 * @param replace character to replace search by
2345 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2350 for (i=0; i<buf->BufUsed; i++)
2351 if (buf->buf[i] == search)
2352 buf->buf[i] = replace;
2358 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2359 * @param buf Buffer to modify
2361 void StrBufToUnixLF(StrBuf *buf)
2363 char *pche, *pchS, *pchT;
2367 pche = buf->buf + buf->BufUsed;
2368 pchS = pchT = buf->buf;
2374 if (*pchS != '\n') {
2383 buf->BufUsed = pchT - buf->buf;
2387 /*******************************************************************************
2388 * Iconv Wrapper; RFC822 de/encoding *
2389 *******************************************************************************/
2392 * @ingroup StrBuf_DeEnCoder
2393 * @brief Wrapper around iconv_open()
2394 * Our version adds aliases for non-standard Microsoft charsets
2395 * such as 'MS950', aliasing them to names like 'CP950'
2397 * @param tocode Target encoding
2398 * @param fromcode Source encoding
2399 * @param pic anonimized pointer to iconv struct
2401 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2404 iconv_t ic = (iconv_t)(-1) ;
2405 ic = iconv_open(tocode, fromcode);
2406 if (ic == (iconv_t)(-1) ) {
2407 char alias_fromcode[64];
2408 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2409 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2410 alias_fromcode[0] = 'C';
2411 alias_fromcode[1] = 'P';
2412 ic = iconv_open(tocode, alias_fromcode);
2415 *(iconv_t *)pic = ic;
2421 * @ingroup StrBuf_DeEnCoder
2422 * @brief find one chunk of a RFC822 encoded string
2423 * @param Buffer where to search
2424 * @param bptr where to start searching
2425 * @returns found position, NULL if none.
2427 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2430 /* Find the next ?Q? */
2431 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2434 end = strchr(bptr + 2, '?');
2439 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2440 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2441 (*(end + 2) == '?')) {
2442 /* skip on to the end of the cluster, the next ?= */
2443 end = strstr(end + 3, "?=");
2446 /* sort of half valid encoding, try to find an end. */
2447 end = strstr(bptr, "?=");
2453 * @brief swaps the contents of two StrBufs
2454 * this is to be used to have cheap switched between a work-buffer and a target buffer
2455 * @param A First one
2456 * @param B second one
2458 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2462 memcpy(&C, A, sizeof(*A));
2463 memcpy(A, B, sizeof(*B));
2464 memcpy(B, &C, sizeof(C));
2470 * @ingroup StrBuf_DeEnCoder
2471 * @brief convert one buffer according to the preselected iconv pointer PIC
2472 * @param ConvertBuf buffer we need to translate
2473 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2474 * @param pic Pointer to the iconv-session Object
2476 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2482 char *ibuf; /**< Buffer of characters to be converted */
2483 char *obuf; /**< Buffer for converted characters */
2484 size_t ibuflen; /**< Length of input buffer */
2485 size_t obuflen; /**< Length of output buffer */
2488 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2489 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2490 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2492 ic = *(iconv_t*)pic;
2493 ibuf = ConvertBuf->buf;
2494 ibuflen = ConvertBuf->BufUsed;
2496 obuflen = TmpBuf->BufSize;
2498 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2501 if (errno == E2BIG) {
2503 IncreaseBuf(TmpBuf, 0, 0);
2508 else if (errno == EILSEQ){
2509 /* hm, invalid utf8 sequence... what to do now? */
2510 /* An invalid multibyte sequence has been encountered in the input */
2512 else if (errno == EINVAL) {
2513 /* An incomplete multibyte sequence has been encountered in the input. */
2516 FlushStrBuf(TmpBuf);
2519 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2520 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2522 /* little card game: wheres the red lady? */
2523 SwapBuffers(ConvertBuf, TmpBuf);
2524 FlushStrBuf(TmpBuf);
2531 * @ingroup StrBuf_DeEnCoder
2532 * @brief catches one RFC822 encoded segment, and decodes it.
2533 * @param Target buffer to fill with result
2534 * @param DecodeMe buffer with stuff to process
2535 * @param SegmentStart points to our current segment in DecodeMe
2536 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2537 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2538 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2539 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2541 inline static void DecodeSegment(StrBuf *Target,
2542 const StrBuf *DecodeMe,
2543 const char *SegmentStart,
2544 const char *SegmentEnd,
2546 StrBuf *ConvertBuf2,
2547 StrBuf *FoundCharset)
2553 iconv_t ic = (iconv_t)(-1);
2557 /* Now we handle foreign character sets properly encoded
2558 * in RFC2047 format.
2560 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2561 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2562 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2563 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2564 if (FoundCharset != NULL) {
2565 FlushStrBuf(FoundCharset);
2566 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2568 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2569 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2571 *encoding = toupper(*encoding);
2572 if (*encoding == 'B') { /**< base64 */
2573 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2575 ConvertBuf->BufUsed);
2577 else if (*encoding == 'Q') { /**< quoted-printable */
2581 while (pos < ConvertBuf->BufUsed)
2583 if (ConvertBuf->buf[pos] == '_')
2584 ConvertBuf->buf[pos] = ' ';
2588 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2591 ConvertBuf->BufUsed);
2594 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2597 ctdl_iconv_open("UTF-8", charset, &ic);
2598 if (ic != (iconv_t)(-1) ) {
2600 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2601 StrBufAppendBuf(Target, ConvertBuf2, 0);
2606 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2612 * @ingroup StrBuf_DeEnCoder
2613 * @brief Handle subjects with RFC2047 encoding such as:
2614 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2615 * @param Target where to put the decoded string to
2616 * @param DecodeMe buffer with encoded string
2617 * @param DefaultCharset if we don't find one, which should we use?
2618 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2619 * put it here for later use where no string might be known.
2621 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2623 StrBuf *DecodedInvalidBuf = NULL;
2624 StrBuf *ConvertBuf, *ConvertBuf2;
2625 const StrBuf *DecodeMee = DecodeMe;
2626 const char *start, *end, *next, *nextend, *ptr = NULL;
2628 iconv_t ic = (iconv_t)(-1) ;
2633 int illegal_non_rfc2047_encoding = 0;
2635 /* Sometimes, badly formed messages contain strings which were simply
2636 * written out directly in some foreign character set instead of
2637 * using RFC2047 encoding. This is illegal but we will attempt to
2638 * handle it anyway by converting from a user-specified default
2639 * charset to UTF-8 if we see any nonprintable characters.
2642 len = StrLength(DecodeMe);
2643 for (i=0; i<DecodeMe->BufUsed; ++i) {
2644 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2645 illegal_non_rfc2047_encoding = 1;
2650 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2651 if ((illegal_non_rfc2047_encoding) &&
2652 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2653 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2656 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2657 if (ic != (iconv_t)(-1) ) {
2658 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2659 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2660 DecodeMee = DecodedInvalidBuf;
2666 /* pre evaluate the first pair */
2667 nextend = end = NULL;
2668 len = StrLength(DecodeMee);
2669 start = strstr(DecodeMee->buf, "=?");
2670 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2672 end = FindNextEnd (DecodeMee, start);
2674 StrBufAppendBuf(Target, DecodeMee, 0);
2675 FreeStrBuf(&ConvertBuf);
2676 FreeStrBuf(&DecodedInvalidBuf);
2680 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2682 if (start != DecodeMee->buf) {
2685 nFront = start - DecodeMee->buf;
2686 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2690 * Since spammers will go to all sorts of absurd lengths to get their
2691 * messages through, there are LOTS of corrupt headers out there.
2692 * So, prevent a really badly formed RFC2047 header from throwing
2693 * this function into an infinite loop.
2695 while ((start != NULL) &&
2702 DecodeSegment(Target,
2710 next = strstr(end, "=?");
2712 if ((next != NULL) &&
2714 nextend = FindNextEnd(DecodeMee, next);
2715 if (nextend == NULL)
2718 /* did we find two partitions */
2719 if ((next != NULL) &&
2723 while ((ptr < next) &&
2730 * did we find a gab just filled with blanks?
2731 * if not, copy its stuff over.
2735 StrBufAppendBufPlain(Target,
2741 /* our next-pair is our new first pair now. */
2747 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2748 if ((end != NULL) && (end < nextend)) {
2750 while ( (ptr < nextend) &&
2757 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2759 FreeStrBuf(&ConvertBuf);
2760 FreeStrBuf(&ConvertBuf2);
2761 FreeStrBuf(&DecodedInvalidBuf);
2764 /*******************************************************************************
2765 * Manipulating UTF-8 Strings *
2766 *******************************************************************************/
2770 * @brief evaluate the length of an utf8 special character sequence
2771 * @param Char the character to examine
2772 * @returns width of utf8 chars in bytes
2774 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2779 while ((n < 8) && ((test & *CharS) != 0)) {
2783 if ((n > 6) || ((CharE - CharS) < n))
2790 * @brief detect whether this char starts an utf-8 encoded char
2791 * @param Char character to inspect
2792 * @returns yes or no
2794 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2796 /** 11??.???? indicates an UTF8 Sequence. */
2797 return ((Char & 0xC0) != 0);
2802 * @brief measure the number of glyphs in an UTF8 string...
2803 * @param Buf string to measure
2804 * @returns the number of glyphs in Buf
2806 long StrBuf_Utf8StrLen(StrBuf *Buf)
2812 if ((Buf == NULL) || (Buf->BufUsed == 0))
2815 eptr = Buf->buf + Buf->BufUsed;
2816 while ((aptr < eptr) && (*aptr != '\0')) {
2817 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2818 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2819 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2832 * @brief cuts a string after maxlen glyphs
2833 * @param Buf string to cut to maxlen glyphs
2834 * @param maxlen how long may the string become?
2835 * @returns current length of the string
2837 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2843 eptr = Buf->buf + Buf->BufUsed;
2844 while ((aptr < eptr) && (*aptr != '\0')) {
2845 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2846 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2847 while ((*aptr++ != '\0') && (m-- > 0));
2856 Buf->BufUsed = aptr - Buf->buf;
2857 return Buf->BufUsed;
2860 return Buf->BufUsed;
2868 /*******************************************************************************
2870 *******************************************************************************/
2873 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2874 #define OS_CODE 0x03 /*< unix */
2877 * @ingroup StrBuf_DeEnCoder
2878 * @brief uses the same calling syntax as compress2(), but it
2879 * creates a stream compatible with HTTP "Content-encoding: gzip"
2880 * @param dest compressed buffer
2881 * @param destLen length of the compresed data
2882 * @param source source to encode
2883 * @param sourceLen length of source to encode
2884 * @param level compression level
2886 int ZEXPORT compress_gzip(Bytef * dest,
2888 const Bytef * source,
2892 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2894 /* write gzip header */
2895 snprintf((char *) dest, *destLen,
2896 "%c%c%c%c%c%c%c%c%c%c",
2897 gz_magic[0], gz_magic[1], Z_DEFLATED,
2898 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2901 /* normal deflate */
2904 stream.next_in = (Bytef *) source;
2905 stream.avail_in = (uInt) sourceLen;
2906 stream.next_out = dest + 10L; // after header
2907 stream.avail_out = (uInt) * destLen;
2908 if ((uLong) stream.avail_out != *destLen)
2911 stream.zalloc = (alloc_func) 0;
2912 stream.zfree = (free_func) 0;
2913 stream.opaque = (voidpf) 0;
2915 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2916 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2920 err = deflate(&stream, Z_FINISH);
2921 if (err != Z_STREAM_END) {
2922 deflateEnd(&stream);
2923 return err == Z_OK ? Z_BUF_ERROR : err;
2925 *destLen = stream.total_out + 10L;
2927 /* write CRC and Length */
2928 uLong crc = crc32(0L, source, sourceLen);
2930 for (n = 0; n < 4; ++n, ++*destLen) {
2931 dest[*destLen] = (int) (crc & 0xff);
2934 uLong len = stream.total_in;
2935 for (n = 0; n < 4; ++n, ++*destLen) {
2936 dest[*destLen] = (int) (len & 0xff);
2939 err = deflateEnd(&stream);
2946 * @ingroup StrBuf_DeEnCoder
2947 * @brief compress the buffer with gzip
2948 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2949 * @param Buf buffer whose content is to be gzipped
2951 int CompressBuffer(StrBuf *Buf)
2954 char *compressed_data = NULL;
2955 size_t compressed_len, bufsize;
2958 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2959 compressed_data = malloc(compressed_len);
2961 if (compressed_data == NULL)
2963 /* Flush some space after the used payload so valgrind shuts up... */
2964 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2965 Buf->buf[Buf->BufUsed + i++] = '\0';
2966 if (compress_gzip((Bytef *) compressed_data,
2969 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2972 Buf->buf = compressed_data;
2973 Buf->BufUsed = compressed_len;
2974 Buf->BufSize = bufsize;
2975 /* Flush some space after the used payload so valgrind shuts up... */
2977 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2978 Buf->buf[Buf->BufUsed + i++] = '\0';
2981 free(compressed_data);
2983 #endif /* HAVE_ZLIB */
2989 /*******************************************************************************
2990 * File I/O; Prefer buffered read since its faster! *
2991 *******************************************************************************/
2994 * @ingroup StrBuf_IO
2995 * @brief Read a line from socket
2996 * flushes and closes the FD on error
2997 * @param buf the buffer to get the input to
2998 * @param fd pointer to the filedescriptor to read
2999 * @param append Append to an existing string or replace?
3000 * @param Error strerror() on error
3001 * @returns numbers of chars read
3003 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3005 int len, rlen, slen;
3010 slen = len = buf->BufUsed;
3012 rlen = read(*fd, &buf->buf[len], 1);
3014 *Error = strerror(errno);
3021 if (buf->buf[len] == '\n')
3023 if (buf->buf[len] != '\r')
3025 if (len + 2 >= buf->BufSize) {
3027 buf->buf[len+1] = '\0';
3028 IncreaseBuf(buf, 1, -1);
3032 buf->buf[len] = '\0';
3037 * @ingroup StrBuf_BufferedIO
3038 * @brief Read a line from socket
3039 * flushes and closes the FD on error
3040 * @param Line the line to read from the fd / I/O Buffer
3041 * @param buf the buffer to get the input to
3042 * @param fd pointer to the filedescriptor to read
3043 * @param timeout number of successless selects until we bail out
3044 * @param selectresolution how long to wait on each select
3045 * @param Error strerror() on error
3046 * @returns numbers of chars read
3048 int StrBufTCP_read_buffered_line(StrBuf *Line,
3052 int selectresolution,
3056 int nSuccessLess = 0;
3063 if (buf->BufUsed > 0) {
3064 pch = strchr(buf->buf, '\n');
3067 len = pch - buf->buf;
3068 if (len > 0 && (*(pch - 1) == '\r') )
3070 StrBufSub(Line, buf, 0, len - rlen);
3071 StrBufCutLeft(buf, len + 1);
3076 if (buf->BufSize - buf->BufUsed < 10)
3077 IncreaseBuf(buf, 1, -1);
3079 fdflags = fcntl(*fd, F_GETFL);
3080 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3082 while ((nSuccessLess < timeout) && (pch == NULL)) {
3084 tv.tv_sec = selectresolution;
3089 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3090 *Error = strerror(errno);
3096 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3101 &buf->buf[buf->BufUsed],
3102 buf->BufSize - buf->BufUsed - 1);
3104 *Error = strerror(errno);
3109 else if (rlen > 0) {
3111 buf->BufUsed += rlen;
3112 buf->buf[buf->BufUsed] = '\0';
3113 if (buf->BufUsed + 10 > buf->BufSize) {
3114 IncreaseBuf(buf, 1, -1);
3116 pch = strchr(buf->buf, '\n');
3123 len = pch - buf->buf;
3124 if (len > 0 && (*(pch - 1) == '\r') )
3126 StrBufSub(Line, buf, 0, len - rlen);
3127 StrBufCutLeft(buf, len + 1);
3134 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3135 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3136 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3138 * @ingroup StrBuf_BufferedIO
3139 * @brief Read a line from socket
3140 * flushes and closes the FD on error
3141 * @param Line where to append our Line read from the fd / I/O Buffer;
3142 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3143 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3144 * @param fd pointer to the filedescriptor to read
3145 * @param timeout number of successless selects until we bail out
3146 * @param selectresolution how long to wait on each select
3147 * @param Error strerror() on error
3148 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3150 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3155 int selectresolution,
3158 const char *pche = NULL;
3159 const char *pos = NULL;
3161 int len, rlen, retlen;
3162 int nSuccessLess = 0;
3164 const char *pch = NULL;
3170 if ((Line == NULL) ||
3177 *Error = ErrRBLF_PreConditionFailed;
3182 if ((IOBuf->BufUsed > 0) &&
3184 (pos < IOBuf->buf + IOBuf->BufUsed))
3188 pche = IOBuf->buf + IOBuf->BufUsed;
3192 while ((pch < pche) && (*pch != '\n'))
3194 if (Line->BufUsed + 10 > Line->BufSize)
3197 apos = pcht - Line->buf;
3199 IncreaseBuf(Line, 1, -1);
3200 pcht = Line->buf + apos;
3208 if (len > 0 && (*(pch - 1) == '\r') )
3217 if ((pch >= pche) || (*pch == '\0'))
3225 if ((pch != NULL) &&
3228 if (pch + 1 >= pche) {
3241 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3243 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3244 IncreaseBuf(IOBuf, 1, -1);
3246 fdflags = fcntl(*fd, F_GETFL);
3247 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3250 while ((nSuccessLess < timeout) &&
3260 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3261 *Error = strerror(errno);
3265 *Error = ErrRBLF_SelectFailed;
3268 if (! FD_ISSET(*fd, &rfds) != 0) {
3274 &IOBuf->buf[IOBuf->BufUsed],
3275 IOBuf->BufSize - IOBuf->BufUsed - 1);
3277 *Error = strerror(errno);
3282 else if (rlen > 0) {
3284 pLF = IOBuf->buf + IOBuf->BufUsed;
3285 IOBuf->BufUsed += rlen;
3286 IOBuf->buf[IOBuf->BufUsed] = '\0';
3288 pche = IOBuf->buf + IOBuf->BufUsed;
3290 while ((pLF < pche) && (*pLF != '\n'))
3292 if ((pLF >= pche) || (*pLF == '\0'))
3295 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3299 if (pLF != NULL) apos = pLF - IOBuf->buf;
3300 IncreaseBuf(IOBuf, 1, -1);
3301 if (pLF != NULL) pLF = IOBuf->buf + apos;
3311 if (len > 0 && (*(pLF - 1) == '\r') )
3313 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3314 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3320 return retlen + len;
3322 *Error = ErrRBLF_NotEnoughSentFromServer;
3327 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3329 * @ingroup StrBuf_IO
3330 * @brief Input binary data from socket
3331 * flushes and closes the FD on error
3332 * @param Buf the buffer to get the input to
3333 * @param fd pointer to the filedescriptor to read
3334 * @param append Append to an existing string or replace?
3335 * @param nBytes the maximal number of bytes to read
3336 * @param Error strerror() on error
3337 * @returns numbers of chars read
3339 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3342 int len, rlen, slen;
3350 if ((Buf == NULL) || (*fd == -1))
3352 *Error = ErrRBLF_BLOBPreConditionFailed;
3357 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3358 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3360 ptr = Buf->buf + Buf->BufUsed;
3362 slen = len = Buf->BufUsed;
3364 fdflags = fcntl(*fd, F_GETFL);
3365 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3367 while ((nRead < nBytes) &&
3377 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3378 *Error = strerror(errno);
3382 *Error = ErrRBLF_SelectFailed;
3385 if (! FD_ISSET(*fd, &rfds) != 0) {
3391 if ((rlen = read(*fd,
3393 nBytes - nRead)) == -1) {
3396 *Error = strerror(errno);
3401 Buf->BufUsed += rlen;
3403 Buf->buf[Buf->BufUsed] = '\0';
3407 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3408 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3410 * @ingroup StrBuf_BufferedIO
3411 * @brief Input binary data from socket
3412 * flushes and closes the FD on error
3413 * @param Blob put binary thing here
3414 * @param IOBuf the buffer to get the input to
3415 * @param Pos offset inside of IOBuf
3416 * @param fd pointer to the filedescriptor to read
3417 * @param append Append to an existing string or replace?
3418 * @param nBytes the maximal number of bytes to read
3419 * @param check whether we should search for '000\n' terminators in case of timeouts
3420 * @param Error strerror() on error
3421 * @returns numbers of chars read
3423 int StrBufReadBLOBBuffered(StrBuf *Blob,
3440 int nAlreadyRead = 0;
3448 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3452 *Error = ErrRBB_BLOBFPreConditionFailed;
3458 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3459 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3464 len = pos - IOBuf->buf;
3465 rlen = IOBuf->BufUsed - len;
3468 if ((IOBuf->BufUsed > 0) &&
3470 (pos < IOBuf->buf + IOBuf->BufUsed))
3472 pche = IOBuf->buf + IOBuf->BufUsed;
3475 if (rlen < nBytes) {
3476 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3477 Blob->BufUsed += rlen;
3478 Blob->buf[Blob->BufUsed] = '\0';
3479 nAlreadyRead = nRead = rlen;
3482 if (rlen >= nBytes) {
3483 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3484 Blob->BufUsed += nBytes;
3485 Blob->buf[Blob->BufUsed] = '\0';
3486 if (rlen == nBytes) {
3498 if (IOBuf->BufSize < nBytes - nRead)
3499 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3502 slen = len = Blob->BufUsed;
3504 fdflags = fcntl(*fd, F_GETFL);
3505 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3510 while ((nRead < nBytes) &&
3519 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3520 *Error = strerror(errno);
3524 *Error = ErrRBLF_SelectFailed;
3527 if (! FD_ISSET(*fd, &rfds) != 0) {
3539 *Error = strerror(errno);
3542 else if (rlen == 0){
3544 if ((check == NNN_TERM) &&
3546 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3548 StrBufPlain(Blob, HKEY("\n000\n"));
3549 StrBufCutRight(Blob, 5);
3550 return Blob->BufUsed;
3552 if (nSelects > 10) {
3554 *Error = ErrRBB_too_many_selects;
3558 else if (rlen > 0) {
3561 IOBuf->BufUsed += rlen;
3564 if (nRead > nBytes) {
3565 *Pos = IOBuf->buf + nBytes;
3567 Blob->buf[Blob->BufUsed] = '\0';
3568 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3572 return nRead + nAlreadyRead;
3576 * @ingroup StrBuf_IO
3577 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3578 * @param LineBuf your line will be copied here.
3579 * @param Buf BLOB with lines of text...
3580 * @param Ptr moved arround to keep the next-line across several iterations
3581 * has to be &NULL on start; will be &NotNULL on end of buffer
3582 * @returns size of copied buffer
3584 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3586 const char *aptr, *ptr, *eptr;
3589 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3590 *Ptr = StrBufNOTNULL;
3594 FlushStrBuf(LineBuf);
3596 ptr = aptr = Buf->buf;
3600 optr = LineBuf->buf;
3601 eptr = Buf->buf + Buf->BufUsed;
3602 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3604 while ((ptr <= eptr) &&
3611 LineBuf->BufUsed = optr - LineBuf->buf;
3612 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3613 optr = LineBuf->buf + LineBuf->BufUsed;
3614 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3618 if ((ptr >= eptr) && (optr > LineBuf->buf))
3620 LineBuf->BufUsed = optr - LineBuf->buf;
3622 if ((ptr <= eptr) && (*ptr == '\r'))
3624 if ((ptr <= eptr) && (*ptr == '\n'))
3631 *Ptr = StrBufNOTNULL;
3634 return Buf->BufUsed - (ptr - Buf->buf);
3639 * @ingroup StrBuf_IO
3640 * @brief removes double slashes from pathnames
3641 * @param Dir directory string to filter
3642 * @param RemoveTrailingSlash allows / disallows trailing slashes
3644 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3650 while (!IsEmptyStr(a)) {
3662 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3667 Dir->BufUsed = b - Dir->buf;