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)
623 * @ingroup StrBuf_Filler
624 * @brief modifies a Single char of the Buf
625 * You can point to it via char* or a zero-based integer
626 * @param Buf The buffer to manipulate
627 * @param ptr char* to zero; use NULL if unused
628 * @param nThChar zero based pointer into the string; use -1 if unused
629 * @param PeekValue The Character to place into the position
631 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
636 nThChar = ptr - Buf->buf;
637 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
639 Buf->buf[nThChar] = PeekValue;
644 * @ingroup StrBuf_Filler
645 * @brief modifies a range of chars of the Buf
646 * You can point to it via char* or a zero-based integer
647 * @param Buf The buffer to manipulate
648 * @param ptr char* to zero; use NULL if unused
649 * @param nThChar zero based pointer into the string; use -1 if unused
650 * @param nChars how many chars are to be flushed?
651 * @param PookValue The Character to place into that area
653 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
658 nThChar = ptr - Buf->buf;
659 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
661 if (nThChar + nChars > Buf->BufUsed)
662 nChars = Buf->BufUsed - nThChar;
664 memset(Buf->buf + nThChar, PookValue, nChars);
665 /* just to be shure... */
666 Buf->buf[Buf->BufUsed] = 0;
671 * @ingroup StrBuf_Filler
672 * @brief Append a StringBuffer to the buffer
673 * @param Buf Buffer to modify
674 * @param AppendBuf Buffer to copy at the end of our buffer
675 * @param Offset Should we start copying from an offset?
677 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
679 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
682 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
685 AppendBuf->BufUsed + Buf->BufUsed);
687 memcpy(Buf->buf + Buf->BufUsed,
688 AppendBuf->buf + Offset,
689 AppendBuf->BufUsed - Offset);
690 Buf->BufUsed += AppendBuf->BufUsed - Offset;
691 Buf->buf[Buf->BufUsed] = '\0';
696 * @ingroup StrBuf_Filler
697 * @brief Append a C-String to the buffer
698 * @param Buf Buffer to modify
699 * @param AppendBuf Buffer to copy at the end of our buffer
700 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
701 * @param Offset Should we start copying from an offset?
703 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
706 long BufSizeRequired;
708 if ((AppendBuf == NULL) || (Buf == NULL))
712 aps = strlen(AppendBuf + Offset);
714 aps = AppendSize - Offset;
716 BufSizeRequired = Buf->BufUsed + aps + 1;
717 if (Buf->BufSize <= BufSizeRequired)
718 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
720 memcpy(Buf->buf + Buf->BufUsed,
724 Buf->buf[Buf->BufUsed] = '\0';
728 * @ingroup StrBuf_Filler
729 * @brief sprintf like function appending the formated string to the buffer
730 * vsnprintf version to wrap into own calls
731 * @param Buf Buffer to extend by format and Params
732 * @param format printf alike format to add
733 * @param ap va_list containing the items for format
735 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
743 if ((Buf == NULL) || (format == NULL))
746 BufSize = Buf->BufSize;
747 nWritten = Buf->BufSize + 1;
748 Offset = Buf->BufUsed;
749 newused = Offset + nWritten;
751 while (newused >= BufSize) {
753 nWritten = vsnprintf(Buf->buf + Offset,
754 Buf->BufSize - Offset,
757 newused = Offset + nWritten;
758 if (newused >= Buf->BufSize) {
759 IncreaseBuf(Buf, 1, newused);
760 newused = Buf->BufSize + 1;
763 Buf->BufUsed = Offset + nWritten;
764 BufSize = Buf->BufSize;
771 * @ingroup StrBuf_Filler
772 * @brief sprintf like function appending the formated string to the buffer
773 * @param Buf Buffer to extend by format and Params
774 * @param format printf alike format to add
776 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
784 if ((Buf == NULL) || (format == NULL))
787 BufSize = Buf->BufSize;
788 nWritten = Buf->BufSize + 1;
789 Offset = Buf->BufUsed;
790 newused = Offset + nWritten;
792 while (newused >= BufSize) {
793 va_start(arg_ptr, format);
794 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
795 Buf->BufSize - Buf->BufUsed,
798 newused = Buf->BufUsed + nWritten;
799 if (newused >= Buf->BufSize) {
800 IncreaseBuf(Buf, 1, newused);
801 newused = Buf->BufSize + 1;
804 Buf->BufUsed += nWritten;
805 BufSize = Buf->BufSize;
812 * @ingroup StrBuf_Filler
813 * @brief sprintf like function putting the formated string into the buffer
814 * @param Buf Buffer to extend by format and Parameters
815 * @param format printf alike format to add
817 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
822 if ((Buf == NULL) || (format == NULL))
825 nWritten = Buf->BufSize + 1;
826 while (nWritten >= Buf->BufSize) {
827 va_start(arg_ptr, format);
828 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
830 if (nWritten >= Buf->BufSize) {
831 IncreaseBuf(Buf, 0, 0);
832 nWritten = Buf->BufSize + 1;
835 Buf->BufUsed = nWritten ;
840 * @ingroup StrBuf_Filler
841 * @brief Callback for cURL to append the webserver reply to a buffer
842 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
843 * @param size pre-defined by the cURL API; see man 3 curl for mre info
844 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
845 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
847 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
856 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
863 * @brief extracts a substring from Source into dest
864 * @param dest buffer to place substring into
865 * @param Source string to copy substring from
866 * @param Offset chars to skip from start
867 * @param nChars number of chars to copy
868 * @returns the number of chars copied; may be different from nChars due to the size of Source
870 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
873 if (Offset > Source->BufUsed)
879 if (Offset + nChars < Source->BufUsed)
881 if (nChars >= dest->BufSize)
882 IncreaseBuf(dest, 0, nChars + 1);
883 memcpy(dest->buf, Source->buf + Offset, nChars);
884 dest->BufUsed = nChars;
885 dest->buf[dest->BufUsed] = '\0';
888 NCharsRemain = Source->BufUsed - Offset;
889 if (NCharsRemain >= dest->BufSize)
890 IncreaseBuf(dest, 0, NCharsRemain + 1);
891 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
892 dest->BufUsed = NCharsRemain;
893 dest->buf[dest->BufUsed] = '\0';
899 * @brief Cut nChars from the start of the string
900 * @param Buf Buffer to modify
901 * @param nChars how many chars should be skipped?
903 void StrBufCutLeft(StrBuf *Buf, int nChars)
905 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
906 if (nChars >= Buf->BufUsed) {
910 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
911 Buf->BufUsed -= nChars;
912 Buf->buf[Buf->BufUsed] = '\0';
917 * @brief Cut the trailing n Chars from the string
918 * @param Buf Buffer to modify
919 * @param nChars how many chars should be trunkated?
921 void StrBufCutRight(StrBuf *Buf, int nChars)
923 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
924 if (nChars >= Buf->BufUsed) {
928 Buf->BufUsed -= nChars;
929 Buf->buf[Buf->BufUsed] = '\0';
934 * @brief Cut the string after n Chars
935 * @param Buf Buffer to modify
936 * @param AfternChars after how many chars should we trunkate the string?
937 * @param At if non-null and points inside of our string, cut it there.
939 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
941 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
943 AfternChars = At - Buf->buf;
946 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
948 Buf->BufUsed = AfternChars;
949 Buf->buf[Buf->BufUsed] = '\0';
955 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
956 * @param Buf the string to modify
958 void StrBufTrim(StrBuf *Buf)
961 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
963 while ((Buf->BufUsed > 0) &&
964 isspace(Buf->buf[Buf->BufUsed - 1]))
968 Buf->buf[Buf->BufUsed] = '\0';
970 if (Buf->BufUsed == 0) return;
972 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
975 if (delta > 0) StrBufCutLeft(Buf, delta);
978 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
986 pLeft = pBuff = Buf->buf;
987 while (pBuff != NULL) {
989 pBuff = strchr(pBuff, leftboundary);
996 pRight = strchr(pBuff, rightboundary);
998 StrBufCutAt(Buf, 0, pRight - 1);
1000 StrBufCutLeft(Buf, pLeft - Buf->buf + 1);
1005 * @ingroup StrBuf_Filler
1006 * @brief uppercase the contents of a buffer
1007 * @param Buf the buffer to translate
1009 void StrBufUpCase(StrBuf *Buf)
1013 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1016 pche = pch + Buf->BufUsed;
1017 while (pch < pche) {
1018 *pch = toupper(*pch);
1025 * @ingroup StrBuf_Filler
1026 * @brief lowercase the contents of a buffer
1027 * @param Buf the buffer to translate
1029 void StrBufLowerCase(StrBuf *Buf)
1033 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1036 pche = pch + Buf->BufUsed;
1037 while (pch < pche) {
1038 *pch = tolower(*pch);
1044 /*******************************************************************************
1045 * a tokenizer that kills, maims, and destroys *
1046 *******************************************************************************/
1049 * @ingroup StrBuf_Tokenizer
1050 * @brief Replace a token at a given place with a given length by another token with given length
1051 * @param Buf String where to work on
1052 * @param where where inside of the Buf is the search-token
1053 * @param HowLong How long is the token to be replaced
1054 * @param Repl Token to insert at 'where'
1055 * @param ReplLen Length of repl
1056 * @returns -1 if fail else length of resulting Buf
1058 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1059 const char *Repl, long ReplLen)
1062 if ((Buf == NULL) ||
1063 (where > Buf->BufUsed) ||
1064 (where + HowLong > Buf->BufUsed))
1067 if (where + ReplLen - HowLong > Buf->BufSize)
1068 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1071 memmove(Buf->buf + where + HowLong,
1072 Buf->buf + where + ReplLen,
1073 Buf->BufUsed - where - HowLong);
1075 memcpy(Buf->buf + where,
1078 Buf->BufUsed += ReplLen - HowLong;
1080 return Buf->BufUsed;
1084 * @ingroup StrBuf_Tokenizer
1085 * @brief Counts the numbmer of tokens in a buffer
1086 * @param source String to count tokens in
1087 * @param tok Tokenizer char to count
1088 * @returns numbers of tokenizer chars found
1090 int StrBufNum_tokens(const StrBuf *source, char tok)
1094 if ((source == NULL) || (source->BufUsed == 0))
1096 if ((source->BufUsed == 1) && (*source->buf == tok))
1100 pche = pch + source->BufUsed;
1111 * @ingroup StrBuf_Tokenizer
1112 * @brief a string tokenizer
1113 * @param Source StringBuffer to read into
1114 * @param parmnum n'th Parameter to remove
1115 * @param separator tokenizer character
1116 * @returns -1 if not found, else length of token.
1118 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1121 char *d, *s, *end; /* dest, source */
1124 /* Find desired @parameter */
1125 end = Source->buf + Source->BufUsed;
1127 while ((d <= end) &&
1130 /* End of string, bail! */
1135 if (*d == separator) {
1140 if ((d == NULL) || (d >= end))
1141 return 0; /* @Parameter not found */
1143 /* Find next @parameter */
1145 while ((s <= end) &&
1146 (*s && *s != separator))
1150 if (*s == separator)
1154 /* Hack and slash */
1159 memmove(d, s, Source->BufUsed - (s - Source->buf));
1160 Source->BufUsed += ReducedBy;
1161 Source->buf[Source->BufUsed] = '\0';
1163 else if (d == Source->buf) {
1165 Source->BufUsed = 0;
1169 Source->BufUsed += ReducedBy;
1182 * @ingroup StrBuf_Tokenizer
1183 * @brief a string tokenizer
1184 * @param dest Destination StringBuffer
1185 * @param Source StringBuffer to read into
1186 * @param parmnum n'th Parameter to extract
1187 * @param separator tokenizer character
1188 * @returns -1 if not found, else length of token.
1190 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1192 const char *s, *e; //* source * /
1193 int len = 0; //* running total length of extracted string * /
1194 int current_token = 0; //* token currently being processed * /
1197 dest->buf[0] = '\0';
1203 if ((Source == NULL) || (Source->BufUsed ==0)) {
1207 e = s + Source->BufUsed;
1210 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1212 while ((s<e) && !IsEmptyStr(s)) {
1213 if (*s == separator) {
1216 if (len >= dest->BufSize) {
1217 dest->BufUsed = len;
1218 if (IncreaseBuf(dest, 1, -1) < 0) {
1223 if ( (current_token == parmnum) &&
1224 (*s != separator)) {
1225 dest->buf[len] = *s;
1228 else if (current_token > parmnum) {
1234 dest->buf[len] = '\0';
1235 dest->BufUsed = len;
1237 if (current_token < parmnum) {
1238 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1241 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1250 * @ingroup StrBuf_Tokenizer
1251 * @brief a string tokenizer to fetch an integer
1252 * @param Source String containing tokens
1253 * @param parmnum n'th Parameter to extract
1254 * @param separator tokenizer character
1255 * @returns 0 if not found, else integer representation of the token
1257 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1267 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1274 * @ingroup StrBuf_Tokenizer
1275 * @brief a string tokenizer to fetch a long integer
1276 * @param Source String containing tokens
1277 * @param parmnum n'th Parameter to extract
1278 * @param separator tokenizer character
1279 * @returns 0 if not found, else long integer representation of the token
1281 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1291 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1299 * @ingroup StrBuf_Tokenizer
1300 * @brief a string tokenizer to fetch an unsigned long
1301 * @param Source String containing tokens
1302 * @param parmnum n'th Parameter to extract
1303 * @param separator tokenizer character
1304 * @returns 0 if not found, else unsigned long representation of the token
1306 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1317 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1321 return (unsigned long) atol(pnum);
1330 * @ingroup StrBuf_NextTokenizer
1331 * @brief a string tokenizer; Bounds checker
1332 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1333 * @param Source our tokenbuffer
1334 * @param pStart the token iterator pointer to inspect
1335 * @returns whether the revolving pointer is inside of the search range
1337 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1339 if ((Source == NULL) ||
1340 (*pStart == StrBufNOTNULL) ||
1341 (Source->BufUsed == 0))
1345 if (*pStart == NULL)
1349 else if (*pStart > Source->buf + Source->BufUsed)
1353 else if (*pStart <= Source->buf)
1362 * @ingroup StrBuf_NextTokenizer
1363 * @brief a string tokenizer
1364 * @param dest Destination StringBuffer
1365 * @param Source StringBuffer to read into
1366 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1367 * @param separator tokenizer
1368 * @returns -1 if not found, else length of token.
1370 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1372 const char *s; /* source */
1373 const char *EndBuffer; /* end stop of source buffer */
1374 int current_token = 0; /* token currently being processed */
1375 int len = 0; /* running total length of extracted string */
1377 if ((Source == NULL) ||
1378 (Source->BufUsed == 0) )
1380 *pStart = StrBufNOTNULL;
1384 EndBuffer = Source->buf + Source->BufUsed;
1388 dest->buf[0] = '\0';
1393 *pStart = EndBuffer + 1;
1397 if (*pStart == NULL)
1399 *pStart = Source->buf; /* we're starting to examine this buffer. */
1401 else if ((*pStart < Source->buf) ||
1402 (*pStart > EndBuffer ) )
1404 return -1; /* no more tokens to find. */
1408 /* start to find the next token */
1409 while ((s <= EndBuffer) &&
1410 (current_token == 0) )
1412 if (*s == separator)
1414 /* we found the next token */
1418 if (len >= dest->BufSize)
1420 /* our Dest-buffer isn't big enough, increase it. */
1421 dest->BufUsed = len;
1423 if (IncreaseBuf(dest, 1, -1) < 0) {
1424 /* WHUT? no more mem? bail out. */
1431 if ( (current_token == 0 ) && /* are we in our target token? */
1432 (!IsEmptyStr(s) ) &&
1433 (separator != *s) ) /* don't copy the token itself */
1435 dest->buf[len] = *s; /* Copy the payload */
1436 ++len; /* remember the bigger size. */
1442 /* did we reach the end? */
1443 if ((s > EndBuffer)) {
1444 EndBuffer = StrBufNOTNULL;
1445 *pStart = EndBuffer;
1448 *pStart = s; /* remember the position for the next run */
1451 /* sanitize our extracted token */
1452 dest->buf[len] = '\0';
1453 dest->BufUsed = len;
1460 * @ingroup StrBuf_NextTokenizer
1461 * @brief a string tokenizer
1462 * @param Source StringBuffer to read from
1463 * @param pStart pointer to the end of the last token. Feed with NULL.
1464 * @param separator tokenizer character
1465 * @param nTokens number of tokens to fastforward over
1466 * @returns -1 if not found, else length of token.
1468 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1470 const char *s, *EndBuffer; //* source * /
1471 int len = 0; //* running total length of extracted string * /
1472 int current_token = 0; //* token currently being processed * /
1474 if ((Source == NULL) ||
1475 (Source->BufUsed ==0)) {
1479 return Source->BufUsed;
1481 if (*pStart == NULL)
1482 *pStart = Source->buf;
1484 EndBuffer = Source->buf + Source->BufUsed;
1486 if ((*pStart < Source->buf) ||
1487 (*pStart > EndBuffer)) {
1495 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1497 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1498 if (*s == separator) {
1501 if (current_token >= nTokens) {
1513 * @ingroup StrBuf_NextTokenizer
1514 * @brief a string tokenizer to fetch an integer
1515 * @param Source StringBuffer to read from
1516 * @param pStart Cursor on the tokenstring
1517 * @param separator tokenizer character
1518 * @returns 0 if not found, else integer representation of the token
1520 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1530 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1537 * @ingroup StrBuf_NextTokenizer
1538 * @brief a string tokenizer to fetch a long integer
1539 * @param Source StringBuffer to read from
1540 * @param pStart Cursor on the tokenstring
1541 * @param separator tokenizer character
1542 * @returns 0 if not found, else long integer representation of the token
1544 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1554 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1562 * @ingroup StrBuf_NextTokenizer
1563 * @brief a string tokenizer to fetch an unsigned long
1564 * @param Source StringBuffer to read from
1565 * @param pStart Cursor on the tokenstring
1566 * @param separator tokenizer character
1567 * @returns 0 if not found, else unsigned long representation of the token
1569 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1580 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1584 return (unsigned long) atol(pnum);
1594 /*******************************************************************************
1595 * Escape Appending *
1596 *******************************************************************************/
1599 * @ingroup StrBuf_DeEnCoder
1600 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1601 * @param OutBuf the output buffer
1602 * @param In Buffer to encode
1603 * @param PlainIn way in from plain old c strings
1605 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1607 const char *pch, *pche;
1611 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1613 if (PlainIn != NULL) {
1614 len = strlen(PlainIn);
1620 pche = pch + In->BufUsed;
1627 pt = OutBuf->buf + OutBuf->BufUsed;
1628 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1630 while (pch < pche) {
1632 IncreaseBuf(OutBuf, 1, -1);
1633 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1634 pt = OutBuf->buf + OutBuf->BufUsed;
1637 if((*pch >= 'a' && *pch <= 'z') ||
1638 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1639 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1640 (*pch == '!') || (*pch == '_') ||
1641 (*pch == ',') || (*pch == '.'))
1648 *(pt + 1) = HexList[(unsigned char)*pch][0];
1649 *(pt + 2) = HexList[(unsigned char)*pch][1];
1651 OutBuf->BufUsed += 3;
1659 * @ingroup StrBuf_DeEnCoder
1660 * @brief append a string in hex encoding to the buffer
1661 * @param OutBuf the output buffer
1662 * @param In Buffer to encode
1663 * @param PlainIn way in from plain old c strings
1665 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1667 const char *pch, *pche;
1671 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1673 if (PlainIn != NULL) {
1674 len = strlen(PlainIn);
1680 pche = pch + In->BufUsed;
1687 pt = OutBuf->buf + OutBuf->BufUsed;
1688 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1690 while (pch < pche) {
1692 IncreaseBuf(OutBuf, 1, -1);
1693 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1694 pt = OutBuf->buf + OutBuf->BufUsed;
1697 *pt = HexList[(unsigned char)*pch][0];
1699 *pt = HexList[(unsigned char)*pch][1];
1700 pt ++; pch ++; OutBuf->BufUsed += 2;
1706 * @ingroup StrBuf_DeEnCoder
1707 * @brief Append a string, escaping characters which have meaning in HTML.
1709 * @param Target target buffer
1710 * @param Source source buffer; set to NULL if you just have a C-String
1711 * @param PlainIn Plain-C string to append; set to NULL if unused
1712 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1713 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1714 * if set to 2, linebreaks are replaced by <br/>
1716 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1718 const char *aptr, *eiptr;
1722 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1725 if (PlainIn != NULL) {
1727 len = strlen(PlainIn);
1732 eiptr = aptr + Source->BufUsed;
1733 len = Source->BufUsed;
1739 bptr = Target->buf + Target->BufUsed;
1740 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1742 while (aptr < eiptr){
1744 IncreaseBuf(Target, 1, -1);
1745 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1746 bptr = Target->buf + Target->BufUsed;
1749 memcpy(bptr, "<", 4);
1751 Target->BufUsed += 4;
1753 else if (*aptr == '>') {
1754 memcpy(bptr, ">", 4);
1756 Target->BufUsed += 4;
1758 else if (*aptr == '&') {
1759 memcpy(bptr, "&", 5);
1761 Target->BufUsed += 5;
1763 else if (*aptr == '"') {
1764 memcpy(bptr, """, 6);
1766 Target->BufUsed += 6;
1768 else if (*aptr == '\'') {
1769 memcpy(bptr, "'", 5);
1771 Target->BufUsed += 5;
1773 else if (*aptr == LB) {
1778 else if (*aptr == RB) {
1783 else if (*aptr == QU) {
1788 else if ((*aptr == 32) && (nbsp == 1)) {
1789 memcpy(bptr, " ", 6);
1791 Target->BufUsed += 6;
1793 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1794 *bptr='\0'; /* nothing */
1796 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1797 memcpy(bptr, "<br/>", 11);
1799 Target->BufUsed += 11;
1803 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1804 *bptr='\0'; /* nothing */
1814 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1816 return Target->BufUsed;
1820 * @ingroup StrBuf_DeEnCoder
1821 * @brief Append a string, escaping characters which have meaning in HTML.
1822 * Converts linebreaks into blanks; escapes single quotes
1823 * @param Target target buffer
1824 * @param Source source buffer; set to NULL if you just have a C-String
1825 * @param PlainIn Plain-C string to append; set to NULL if unused
1827 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1829 const char *aptr, *eiptr;
1833 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1836 if (PlainIn != NULL) {
1838 len = strlen(PlainIn);
1843 eiptr = aptr + Source->BufUsed;
1844 len = Source->BufUsed;
1850 eptr = Target->buf + Target->BufSize - 8;
1851 tptr = Target->buf + Target->BufUsed;
1853 while (aptr < eiptr){
1855 IncreaseBuf(Target, 1, -1);
1856 eptr = Target->buf + Target->BufSize - 8;
1857 tptr = Target->buf + Target->BufUsed;
1860 if (*aptr == '\n') {
1864 else if (*aptr == '\r') {
1868 else if (*aptr == '\'') {
1874 Target->BufUsed += 5;
1887 * @ingroup StrBuf_DeEnCoder
1888 * @brief Append a string, escaping characters which have meaning in ICAL.
1890 * @param Target target buffer
1891 * @param Source source buffer; set to NULL if you just have a C-String
1892 * @param PlainIn Plain-C string to append; set to NULL if unused
1894 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1896 const char *aptr, *eiptr;
1900 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1903 if (PlainIn != NULL) {
1905 len = strlen(PlainIn);
1910 eiptr = aptr + Source->BufUsed;
1911 len = Source->BufUsed;
1917 eptr = Target->buf + Target->BufSize - 8;
1918 tptr = Target->buf + Target->BufUsed;
1920 while (aptr < eiptr){
1921 if(tptr + 3 >= eptr) {
1922 IncreaseBuf(Target, 1, -1);
1923 eptr = Target->buf + Target->BufSize - 8;
1924 tptr = Target->buf + Target->BufUsed;
1927 if (*aptr == '\n') {
1934 else if (*aptr == '\r') {
1941 else if (*aptr == ',') {
1957 * @ingroup StrBuf_DeEnCoder
1958 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1960 * @param Target target buffer
1961 * @param Source source buffer; set to NULL if you just have a C-String
1962 * @param PlainIn Plain-C string to append; set to NULL if unused
1963 * @returns size of result or -1
1965 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1967 const char *aptr, *eiptr;
1971 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1974 if (PlainIn != NULL) {
1976 len = strlen(PlainIn);
1981 eiptr = aptr + Source->BufUsed;
1982 len = Source->BufUsed;
1988 bptr = Target->buf + Target->BufUsed;
1989 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1991 while (aptr < eiptr){
1993 IncreaseBuf(Target, 1, -1);
1994 eptr = Target->buf + Target->BufSize - 3;
1995 bptr = Target->buf + Target->BufUsed;
2002 Target->BufUsed += 2;
2003 } else if (*aptr == '\\') {
2008 Target->BufUsed += 2;
2018 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2020 return Target->BufUsed;
2024 * @ingroup StrBuf_DeEnCoder
2025 * @brief Append a string, escaping characters which have meaning in HTML + json.
2027 * @param Target target buffer
2028 * @param Source source buffer; set to NULL if you just have a C-String
2029 * @param PlainIn Plain-C string to append; set to NULL if unused
2030 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2031 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2032 * if set to 2, linebreaks are replaced by <br/>
2034 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2036 const char *aptr, *eiptr;
2039 int IsUtf8Sequence = 0;
2041 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2044 if (PlainIn != NULL) {
2046 len = strlen(PlainIn);
2051 eiptr = aptr + Source->BufUsed;
2052 len = Source->BufUsed;
2058 bptr = Target->buf + Target->BufUsed;
2059 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2061 while (aptr < eiptr){
2063 IncreaseBuf(Target, 1, -1);
2064 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2065 bptr = Target->buf + Target->BufUsed;
2068 memcpy(bptr, "<", 4);
2070 Target->BufUsed += 4;
2072 else if (*aptr == '>') {
2073 memcpy(bptr, ">", 4);
2075 Target->BufUsed += 4;
2077 else if (*aptr == '&') {
2078 memcpy(bptr, "&", 5);
2080 Target->BufUsed += 5;
2082 else if (*aptr == LB) {
2087 else if (*aptr == RB) {
2092 else if ((*aptr == 32) && (nbsp == 1)) {
2093 memcpy(bptr, " ", 6);
2095 Target->BufUsed += 6;
2097 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2098 *bptr='\0'; /* nothing */
2100 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2101 memcpy(bptr, "<br/>", 11);
2103 Target->BufUsed += 11;
2106 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2107 *bptr='\0'; /* nothing */
2110 else if ((*aptr == '"') || (*aptr == QU)) {
2115 Target->BufUsed += 2;
2116 } else if (*aptr == '\\') {
2121 Target->BufUsed += 2;
2124 if (((unsigned char)*aptr) >= 0x20)
2126 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2130 while (IsUtf8Sequence > 1){
2131 if(bptr + IsUtf8Sequence >= eptr) {
2132 IncreaseBuf(Target, 1, -1);
2133 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2134 bptr = Target->buf + Target->BufUsed - 1;
2148 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2150 return Target->BufUsed;
2154 * @ingroup StrBuf_DeEnCoder
2155 * @brief unhide special chars hidden to the HTML escaper
2156 * @param target buffer to put the unescaped string in
2157 * @param source buffer to unescape
2159 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2165 FlushStrBuf(target);
2167 if (source == NULL ||target == NULL)
2172 len = source->BufUsed;
2173 for (a = 0; a < len; ++a) {
2174 if (target->BufUsed >= target->BufSize)
2175 IncreaseBuf(target, 1, -1);
2177 if (source->buf[a] == '=') {
2178 hex[0] = source->buf[a + 1];
2179 hex[1] = source->buf[a + 2];
2182 sscanf(hex, "%02x", &b);
2183 target->buf[target->BufUsed] = b;
2184 target->buf[++target->BufUsed] = 0;
2188 target->buf[target->BufUsed] = source->buf[a];
2189 target->buf[++target->BufUsed] = 0;
2196 * @ingroup StrBuf_DeEnCoder
2197 * @brief hide special chars from the HTML escapers and friends
2198 * @param target buffer to put the escaped string in
2199 * @param source buffer to escape
2201 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2206 FlushStrBuf(target);
2208 if (source == NULL ||target == NULL)
2213 len = source->BufUsed;
2214 for (i=0; i<len; ++i) {
2215 if (target->BufUsed + 4 >= target->BufSize)
2216 IncreaseBuf(target, 1, -1);
2217 if ( (isalnum(source->buf[i])) ||
2218 (source->buf[i]=='-') ||
2219 (source->buf[i]=='_') ) {
2220 target->buf[target->BufUsed++] = source->buf[i];
2223 sprintf(&target->buf[target->BufUsed],
2225 (0xFF &source->buf[i]));
2226 target->BufUsed += 3;
2229 target->buf[target->BufUsed + 1] = '\0';
2233 /*******************************************************************************
2234 * Quoted Printable de/encoding *
2235 *******************************************************************************/
2238 * @ingroup StrBuf_DeEnCoder
2239 * @brief decode a buffer from base 64 encoding; destroys original
2240 * @param Buf Buffor to transform
2242 int StrBufDecodeBase64(StrBuf *Buf)
2246 if (Buf == NULL) return -1;
2248 xferbuf = (char*) malloc(Buf->BufSize);
2249 siz = CtdlDecodeBase64(xferbuf,
2259 * @ingroup StrBuf_DeEnCoder
2260 * @brief decode a buffer from base 64 encoding; destroys original
2261 * @param Buf Buffor to transform
2263 int StrBufDecodeHex(StrBuf *Buf)
2266 char *pch, *pche, *pchi;
2268 if (Buf == NULL) return -1;
2270 pch = pchi = Buf->buf;
2271 pche = pch + Buf->BufUsed;
2273 while (pchi < pche){
2274 ch = decode_hex(pchi);
2281 Buf->BufUsed = pch - Buf->buf;
2282 return Buf->BufUsed;
2286 * @ingroup StrBuf_DeEnCoder
2287 * @brief replace all chars >0x20 && < 0x7F with Mute
2288 * @param Mute char to put over invalid chars
2289 * @param Buf Buffor to transform
2291 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2295 if (Buf == NULL) return -1;
2296 pch = (unsigned char *)Buf->buf;
2297 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2298 if ((*pch < 0x20) || (*pch > 0x7F))
2302 return Buf->BufUsed;
2307 * @ingroup StrBuf_DeEnCoder
2308 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2309 * @param Buf Buffer to translate
2310 * @param StripBlanks Reduce several blanks to one?
2312 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2321 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2322 Buf->buf[Buf->BufUsed - 1] = '\0';
2327 while (a < Buf->BufUsed) {
2328 if (Buf->buf[a] == '+')
2330 else if (Buf->buf[a] == '%') {
2331 /* don't let % chars through, rather truncate the input. */
2332 if (a + 2 > Buf->BufUsed) {
2337 hex[0] = Buf->buf[a + 1];
2338 hex[1] = Buf->buf[a + 2];
2341 sscanf(hex, "%02x", &b);
2342 Buf->buf[a] = (char) b;
2343 len = Buf->BufUsed - a - 2;
2345 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2357 * @ingroup StrBuf_DeEnCoder
2358 * @brief RFC2047-encode a header field if necessary.
2359 * If no non-ASCII characters are found, the string
2360 * will be copied verbatim without encoding.
2362 * @param target Target buffer.
2363 * @param source Source string to be encoded.
2364 * @returns encoded length; -1 if non success.
2366 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2368 const char headerStr[] = "=?UTF-8?Q?";
2369 int need_to_encode = 0;
2373 if ((source == NULL) ||
2377 while ((i < source->BufUsed) &&
2378 (!IsEmptyStr (&source->buf[i])) &&
2379 (need_to_encode == 0)) {
2380 if (((unsigned char) source->buf[i] < 32) ||
2381 ((unsigned char) source->buf[i] > 126)) {
2387 if (!need_to_encode) {
2388 if (*target == NULL) {
2389 *target = NewStrBufPlain(source->buf, source->BufUsed);
2392 FlushStrBuf(*target);
2393 StrBufAppendBuf(*target, source, 0);
2395 return (*target)->BufUsed;
2397 if (*target == NULL)
2398 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2399 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2400 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2401 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2402 (*target)->BufUsed = sizeof(headerStr) - 1;
2403 for (i=0; (i < source->BufUsed); ++i) {
2404 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2405 IncreaseBuf(*target, 1, 0);
2406 ch = (unsigned char) source->buf[i];
2407 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2408 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2409 (*target)->BufUsed += 3;
2412 (*target)->buf[(*target)->BufUsed] = ch;
2413 (*target)->BufUsed++;
2417 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2418 IncreaseBuf(*target, 1, 0);
2420 (*target)->buf[(*target)->BufUsed++] = '?';
2421 (*target)->buf[(*target)->BufUsed++] = '=';
2422 (*target)->buf[(*target)->BufUsed] = '\0';
2423 return (*target)->BufUsed;;
2428 * @brief replaces all occurances of 'search' by 'replace'
2429 * @param buf Buffer to modify
2430 * @param search character to search
2431 * @param replace character to replace search by
2433 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2438 for (i=0; i<buf->BufUsed; i++)
2439 if (buf->buf[i] == search)
2440 buf->buf[i] = replace;
2446 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2447 * @param buf Buffer to modify
2449 void StrBufToUnixLF(StrBuf *buf)
2451 char *pche, *pchS, *pchT;
2455 pche = buf->buf + buf->BufUsed;
2456 pchS = pchT = buf->buf;
2462 if (*pchS != '\n') {
2471 buf->BufUsed = pchT - buf->buf;
2475 /*******************************************************************************
2476 * Iconv Wrapper; RFC822 de/encoding *
2477 *******************************************************************************/
2480 * @ingroup StrBuf_DeEnCoder
2481 * @brief Wrapper around iconv_open()
2482 * Our version adds aliases for non-standard Microsoft charsets
2483 * such as 'MS950', aliasing them to names like 'CP950'
2485 * @param tocode Target encoding
2486 * @param fromcode Source encoding
2487 * @param pic anonimized pointer to iconv struct
2489 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2492 iconv_t ic = (iconv_t)(-1) ;
2493 ic = iconv_open(tocode, fromcode);
2494 if (ic == (iconv_t)(-1) ) {
2495 char alias_fromcode[64];
2496 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2497 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2498 alias_fromcode[0] = 'C';
2499 alias_fromcode[1] = 'P';
2500 ic = iconv_open(tocode, alias_fromcode);
2503 *(iconv_t *)pic = ic;
2509 * @ingroup StrBuf_DeEnCoder
2510 * @brief find one chunk of a RFC822 encoded string
2511 * @param Buffer where to search
2512 * @param bptr where to start searching
2513 * @returns found position, NULL if none.
2515 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2518 /* Find the next ?Q? */
2519 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2522 end = strchr(bptr + 2, '?');
2527 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2528 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2529 (*(end + 2) == '?')) {
2530 /* skip on to the end of the cluster, the next ?= */
2531 end = strstr(end + 3, "?=");
2534 /* sort of half valid encoding, try to find an end. */
2535 end = strstr(bptr, "?=");
2541 * @brief swaps the contents of two StrBufs
2542 * this is to be used to have cheap switched between a work-buffer and a target buffer
2543 * @param A First one
2544 * @param B second one
2546 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2550 memcpy(&C, A, sizeof(*A));
2551 memcpy(A, B, sizeof(*B));
2552 memcpy(B, &C, sizeof(C));
2558 * @ingroup StrBuf_DeEnCoder
2559 * @brief convert one buffer according to the preselected iconv pointer PIC
2560 * @param ConvertBuf buffer we need to translate
2561 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2562 * @param pic Pointer to the iconv-session Object
2564 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2570 char *ibuf; /**< Buffer of characters to be converted */
2571 char *obuf; /**< Buffer for converted characters */
2572 size_t ibuflen; /**< Length of input buffer */
2573 size_t obuflen; /**< Length of output buffer */
2576 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2577 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2578 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2580 ic = *(iconv_t*)pic;
2581 ibuf = ConvertBuf->buf;
2582 ibuflen = ConvertBuf->BufUsed;
2584 obuflen = TmpBuf->BufSize;
2586 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2589 if (errno == E2BIG) {
2591 IncreaseBuf(TmpBuf, 0, 0);
2596 else if (errno == EILSEQ){
2597 /* hm, invalid utf8 sequence... what to do now? */
2598 /* An invalid multibyte sequence has been encountered in the input */
2600 else if (errno == EINVAL) {
2601 /* An incomplete multibyte sequence has been encountered in the input. */
2604 FlushStrBuf(TmpBuf);
2607 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2608 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2610 /* little card game: wheres the red lady? */
2611 SwapBuffers(ConvertBuf, TmpBuf);
2612 FlushStrBuf(TmpBuf);
2619 * @ingroup StrBuf_DeEnCoder
2620 * @brief catches one RFC822 encoded segment, and decodes it.
2621 * @param Target buffer to fill with result
2622 * @param DecodeMe buffer with stuff to process
2623 * @param SegmentStart points to our current segment in DecodeMe
2624 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2625 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2626 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2627 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2629 inline static void DecodeSegment(StrBuf *Target,
2630 const StrBuf *DecodeMe,
2631 const char *SegmentStart,
2632 const char *SegmentEnd,
2634 StrBuf *ConvertBuf2,
2635 StrBuf *FoundCharset)
2641 iconv_t ic = (iconv_t)(-1);
2645 /* Now we handle foreign character sets properly encoded
2646 * in RFC2047 format.
2648 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2649 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2650 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2651 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2652 if (FoundCharset != NULL) {
2653 FlushStrBuf(FoundCharset);
2654 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2656 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2657 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2659 *encoding = toupper(*encoding);
2660 if (*encoding == 'B') { /**< base64 */
2661 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2663 ConvertBuf->BufUsed);
2665 else if (*encoding == 'Q') { /**< quoted-printable */
2669 while (pos < ConvertBuf->BufUsed)
2671 if (ConvertBuf->buf[pos] == '_')
2672 ConvertBuf->buf[pos] = ' ';
2676 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2679 ConvertBuf->BufUsed);
2682 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2685 ctdl_iconv_open("UTF-8", charset, &ic);
2686 if (ic != (iconv_t)(-1) ) {
2688 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2689 StrBufAppendBuf(Target, ConvertBuf2, 0);
2694 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2700 * @ingroup StrBuf_DeEnCoder
2701 * @brief Handle subjects with RFC2047 encoding such as:
2702 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2703 * @param Target where to put the decoded string to
2704 * @param DecodeMe buffer with encoded string
2705 * @param DefaultCharset if we don't find one, which should we use?
2706 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2707 * put it here for later use where no string might be known.
2709 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2711 StrBuf *DecodedInvalidBuf = NULL;
2712 StrBuf *ConvertBuf, *ConvertBuf2;
2713 const StrBuf *DecodeMee = DecodeMe;
2714 const char *start, *end, *next, *nextend, *ptr = NULL;
2716 iconv_t ic = (iconv_t)(-1) ;
2721 int illegal_non_rfc2047_encoding = 0;
2723 /* Sometimes, badly formed messages contain strings which were simply
2724 * written out directly in some foreign character set instead of
2725 * using RFC2047 encoding. This is illegal but we will attempt to
2726 * handle it anyway by converting from a user-specified default
2727 * charset to UTF-8 if we see any nonprintable characters.
2730 len = StrLength(DecodeMe);
2731 for (i=0; i<DecodeMe->BufUsed; ++i) {
2732 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2733 illegal_non_rfc2047_encoding = 1;
2738 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2739 if ((illegal_non_rfc2047_encoding) &&
2740 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2741 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2744 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2745 if (ic != (iconv_t)(-1) ) {
2746 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2747 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2748 DecodeMee = DecodedInvalidBuf;
2754 /* pre evaluate the first pair */
2755 nextend = end = NULL;
2756 len = StrLength(DecodeMee);
2757 start = strstr(DecodeMee->buf, "=?");
2758 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2760 end = FindNextEnd (DecodeMee, start);
2762 StrBufAppendBuf(Target, DecodeMee, 0);
2763 FreeStrBuf(&ConvertBuf);
2764 FreeStrBuf(&DecodedInvalidBuf);
2768 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2770 if (start != DecodeMee->buf) {
2773 nFront = start - DecodeMee->buf;
2774 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2778 * Since spammers will go to all sorts of absurd lengths to get their
2779 * messages through, there are LOTS of corrupt headers out there.
2780 * So, prevent a really badly formed RFC2047 header from throwing
2781 * this function into an infinite loop.
2783 while ((start != NULL) &&
2790 DecodeSegment(Target,
2798 next = strstr(end, "=?");
2800 if ((next != NULL) &&
2802 nextend = FindNextEnd(DecodeMee, next);
2803 if (nextend == NULL)
2806 /* did we find two partitions */
2807 if ((next != NULL) &&
2811 while ((ptr < next) &&
2818 * did we find a gab just filled with blanks?
2819 * if not, copy its stuff over.
2823 StrBufAppendBufPlain(Target,
2829 /* our next-pair is our new first pair now. */
2835 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2836 if ((end != NULL) && (end < nextend)) {
2838 while ( (ptr < nextend) &&
2845 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2847 FreeStrBuf(&ConvertBuf);
2848 FreeStrBuf(&ConvertBuf2);
2849 FreeStrBuf(&DecodedInvalidBuf);
2852 /*******************************************************************************
2853 * Manipulating UTF-8 Strings *
2854 *******************************************************************************/
2858 * @brief evaluate the length of an utf8 special character sequence
2859 * @param Char the character to examine
2860 * @returns width of utf8 chars in bytes
2862 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2867 while ((n < 8) && ((test & *CharS) != 0)) {
2871 if ((n > 6) || ((CharE - CharS) < n))
2878 * @brief detect whether this char starts an utf-8 encoded char
2879 * @param Char character to inspect
2880 * @returns yes or no
2882 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2884 /** 11??.???? indicates an UTF8 Sequence. */
2885 return ((Char & 0xC0) != 0);
2890 * @brief measure the number of glyphs in an UTF8 string...
2891 * @param Buf string to measure
2892 * @returns the number of glyphs in Buf
2894 long StrBuf_Utf8StrLen(StrBuf *Buf)
2900 if ((Buf == NULL) || (Buf->BufUsed == 0))
2903 eptr = Buf->buf + Buf->BufUsed;
2904 while ((aptr < eptr) && (*aptr != '\0')) {
2905 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2906 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2907 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2920 * @brief cuts a string after maxlen glyphs
2921 * @param Buf string to cut to maxlen glyphs
2922 * @param maxlen how long may the string become?
2923 * @returns current length of the string
2925 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2931 eptr = Buf->buf + Buf->BufUsed;
2932 while ((aptr < eptr) && (*aptr != '\0')) {
2933 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2934 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2935 while ((*aptr++ != '\0') && (m-- > 0));
2944 Buf->BufUsed = aptr - Buf->buf;
2945 return Buf->BufUsed;
2948 return Buf->BufUsed;
2956 /*******************************************************************************
2958 *******************************************************************************/
2961 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2962 #define OS_CODE 0x03 /*< unix */
2965 * @ingroup StrBuf_DeEnCoder
2966 * @brief uses the same calling syntax as compress2(), but it
2967 * creates a stream compatible with HTTP "Content-encoding: gzip"
2968 * @param dest compressed buffer
2969 * @param destLen length of the compresed data
2970 * @param source source to encode
2971 * @param sourceLen length of source to encode
2972 * @param level compression level
2974 int ZEXPORT compress_gzip(Bytef * dest,
2976 const Bytef * source,
2980 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2982 /* write gzip header */
2983 snprintf((char *) dest, *destLen,
2984 "%c%c%c%c%c%c%c%c%c%c",
2985 gz_magic[0], gz_magic[1], Z_DEFLATED,
2986 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2989 /* normal deflate */
2992 stream.next_in = (Bytef *) source;
2993 stream.avail_in = (uInt) sourceLen;
2994 stream.next_out = dest + 10L; // after header
2995 stream.avail_out = (uInt) * destLen;
2996 if ((uLong) stream.avail_out != *destLen)
2999 stream.zalloc = (alloc_func) 0;
3000 stream.zfree = (free_func) 0;
3001 stream.opaque = (voidpf) 0;
3003 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3004 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3008 err = deflate(&stream, Z_FINISH);
3009 if (err != Z_STREAM_END) {
3010 deflateEnd(&stream);
3011 return err == Z_OK ? Z_BUF_ERROR : err;
3013 *destLen = stream.total_out + 10L;
3015 /* write CRC and Length */
3016 uLong crc = crc32(0L, source, sourceLen);
3018 for (n = 0; n < 4; ++n, ++*destLen) {
3019 dest[*destLen] = (int) (crc & 0xff);
3022 uLong len = stream.total_in;
3023 for (n = 0; n < 4; ++n, ++*destLen) {
3024 dest[*destLen] = (int) (len & 0xff);
3027 err = deflateEnd(&stream);
3034 * @ingroup StrBuf_DeEnCoder
3035 * @brief compress the buffer with gzip
3036 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3037 * @param Buf buffer whose content is to be gzipped
3039 int CompressBuffer(StrBuf *Buf)
3042 char *compressed_data = NULL;
3043 size_t compressed_len, bufsize;
3046 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3047 compressed_data = malloc(compressed_len);
3049 if (compressed_data == NULL)
3051 /* Flush some space after the used payload so valgrind shuts up... */
3052 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3053 Buf->buf[Buf->BufUsed + i++] = '\0';
3054 if (compress_gzip((Bytef *) compressed_data,
3057 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3060 Buf->buf = compressed_data;
3061 Buf->BufUsed = compressed_len;
3062 Buf->BufSize = bufsize;
3063 /* Flush some space after the used payload so valgrind shuts up... */
3065 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3066 Buf->buf[Buf->BufUsed + i++] = '\0';
3069 free(compressed_data);
3071 #endif /* HAVE_ZLIB */
3077 /*******************************************************************************
3078 * File I/O; Prefer buffered read since its faster! *
3079 *******************************************************************************/
3082 * @ingroup StrBuf_IO
3083 * @brief Read a line from socket
3084 * flushes and closes the FD on error
3085 * @param buf the buffer to get the input to
3086 * @param fd pointer to the filedescriptor to read
3087 * @param append Append to an existing string or replace?
3088 * @param Error strerror() on error
3089 * @returns numbers of chars read
3091 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3093 int len, rlen, slen;
3098 slen = len = buf->BufUsed;
3100 rlen = read(*fd, &buf->buf[len], 1);
3102 *Error = strerror(errno);
3109 if (buf->buf[len] == '\n')
3111 if (buf->buf[len] != '\r')
3113 if (len + 2 >= buf->BufSize) {
3115 buf->buf[len+1] = '\0';
3116 IncreaseBuf(buf, 1, -1);
3120 buf->buf[len] = '\0';
3125 * @ingroup StrBuf_BufferedIO
3126 * @brief Read a line from socket
3127 * flushes and closes the FD on error
3128 * @param Line the line to read from the fd / I/O Buffer
3129 * @param buf the buffer to get the input to
3130 * @param fd pointer to the filedescriptor to read
3131 * @param timeout number of successless selects until we bail out
3132 * @param selectresolution how long to wait on each select
3133 * @param Error strerror() on error
3134 * @returns numbers of chars read
3136 int StrBufTCP_read_buffered_line(StrBuf *Line,
3140 int selectresolution,
3144 int nSuccessLess = 0;
3151 if (buf->BufUsed > 0) {
3152 pch = strchr(buf->buf, '\n');
3155 len = pch - buf->buf;
3156 if (len > 0 && (*(pch - 1) == '\r') )
3158 StrBufSub(Line, buf, 0, len - rlen);
3159 StrBufCutLeft(buf, len + 1);
3164 if (buf->BufSize - buf->BufUsed < 10)
3165 IncreaseBuf(buf, 1, -1);
3167 fdflags = fcntl(*fd, F_GETFL);
3168 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3170 while ((nSuccessLess < timeout) && (pch == NULL)) {
3172 tv.tv_sec = selectresolution;
3177 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3178 *Error = strerror(errno);
3184 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3189 &buf->buf[buf->BufUsed],
3190 buf->BufSize - buf->BufUsed - 1);
3192 *Error = strerror(errno);
3197 else if (rlen > 0) {
3199 buf->BufUsed += rlen;
3200 buf->buf[buf->BufUsed] = '\0';
3201 if (buf->BufUsed + 10 > buf->BufSize) {
3202 IncreaseBuf(buf, 1, -1);
3204 pch = strchr(buf->buf, '\n');
3211 len = pch - buf->buf;
3212 if (len > 0 && (*(pch - 1) == '\r') )
3214 StrBufSub(Line, buf, 0, len - rlen);
3215 StrBufCutLeft(buf, len + 1);
3222 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3223 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3224 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3226 * @ingroup StrBuf_BufferedIO
3227 * @brief Read a line from socket
3228 * flushes and closes the FD on error
3229 * @param Line where to append our Line read from the fd / I/O Buffer;
3230 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3231 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3232 * @param fd pointer to the filedescriptor to read
3233 * @param timeout number of successless selects until we bail out
3234 * @param selectresolution how long to wait on each select
3235 * @param Error strerror() on error
3236 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3238 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3243 int selectresolution,
3246 const char *pche = NULL;
3247 const char *pos = NULL;
3249 int len, rlen, retlen;
3250 int nSuccessLess = 0;
3252 const char *pch = NULL;
3258 if ((Line == NULL) ||
3265 *Error = ErrRBLF_PreConditionFailed;
3270 if ((IOBuf->BufUsed > 0) &&
3272 (pos < IOBuf->buf + IOBuf->BufUsed))
3276 pche = IOBuf->buf + IOBuf->BufUsed;
3280 while ((pch < pche) && (*pch != '\n'))
3282 if (Line->BufUsed + 10 > Line->BufSize)
3285 apos = pcht - Line->buf;
3287 IncreaseBuf(Line, 1, -1);
3288 pcht = Line->buf + apos;
3296 if (len > 0 && (*(pch - 1) == '\r') )
3305 if ((pch >= pche) || (*pch == '\0'))
3313 if ((pch != NULL) &&
3316 if (pch + 1 >= pche) {
3329 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3331 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3332 IncreaseBuf(IOBuf, 1, -1);
3334 fdflags = fcntl(*fd, F_GETFL);
3335 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3338 while ((nSuccessLess < timeout) &&
3348 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3349 *Error = strerror(errno);
3353 *Error = ErrRBLF_SelectFailed;
3356 if (! FD_ISSET(*fd, &rfds) != 0) {
3362 &IOBuf->buf[IOBuf->BufUsed],
3363 IOBuf->BufSize - IOBuf->BufUsed - 1);
3365 *Error = strerror(errno);
3370 else if (rlen > 0) {
3372 pLF = IOBuf->buf + IOBuf->BufUsed;
3373 IOBuf->BufUsed += rlen;
3374 IOBuf->buf[IOBuf->BufUsed] = '\0';
3376 pche = IOBuf->buf + IOBuf->BufUsed;
3378 while ((pLF < pche) && (*pLF != '\n'))
3380 if ((pLF >= pche) || (*pLF == '\0'))
3383 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3387 if (pLF != NULL) apos = pLF - IOBuf->buf;
3388 IncreaseBuf(IOBuf, 1, -1);
3389 if (pLF != NULL) pLF = IOBuf->buf + apos;
3399 if (len > 0 && (*(pLF - 1) == '\r') )
3401 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3402 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3408 return retlen + len;
3410 *Error = ErrRBLF_NotEnoughSentFromServer;
3415 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3417 * @ingroup StrBuf_IO
3418 * @brief Input binary data from socket
3419 * flushes and closes the FD on error
3420 * @param Buf the buffer to get the input to
3421 * @param fd pointer to the filedescriptor to read
3422 * @param append Append to an existing string or replace?
3423 * @param nBytes the maximal number of bytes to read
3424 * @param Error strerror() on error
3425 * @returns numbers of chars read
3427 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3430 int len, rlen, slen;
3438 if ((Buf == NULL) || (*fd == -1))
3440 *Error = ErrRBLF_BLOBPreConditionFailed;
3445 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3446 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3448 ptr = Buf->buf + Buf->BufUsed;
3450 slen = len = Buf->BufUsed;
3452 fdflags = fcntl(*fd, F_GETFL);
3453 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3455 while ((nRead < nBytes) &&
3465 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3466 *Error = strerror(errno);
3470 *Error = ErrRBLF_SelectFailed;
3473 if (! FD_ISSET(*fd, &rfds) != 0) {
3479 if ((rlen = read(*fd,
3481 nBytes - nRead)) == -1) {
3484 *Error = strerror(errno);
3489 Buf->BufUsed += rlen;
3491 Buf->buf[Buf->BufUsed] = '\0';
3495 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3496 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3498 * @ingroup StrBuf_BufferedIO
3499 * @brief Input binary data from socket
3500 * flushes and closes the FD on error
3501 * @param Blob put binary thing here
3502 * @param IOBuf the buffer to get the input to
3503 * @param Pos offset inside of IOBuf
3504 * @param fd pointer to the filedescriptor to read
3505 * @param append Append to an existing string or replace?
3506 * @param nBytes the maximal number of bytes to read
3507 * @param check whether we should search for '000\n' terminators in case of timeouts
3508 * @param Error strerror() on error
3509 * @returns numbers of chars read
3511 int StrBufReadBLOBBuffered(StrBuf *Blob,
3528 int nAlreadyRead = 0;
3536 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3540 *Error = ErrRBB_BLOBFPreConditionFailed;
3546 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3547 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3552 len = pos - IOBuf->buf;
3553 rlen = IOBuf->BufUsed - len;
3556 if ((IOBuf->BufUsed > 0) &&
3558 (pos < IOBuf->buf + IOBuf->BufUsed))
3560 pche = IOBuf->buf + IOBuf->BufUsed;
3563 if (rlen < nBytes) {
3564 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3565 Blob->BufUsed += rlen;
3566 Blob->buf[Blob->BufUsed] = '\0';
3567 nAlreadyRead = nRead = rlen;
3570 if (rlen >= nBytes) {
3571 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3572 Blob->BufUsed += nBytes;
3573 Blob->buf[Blob->BufUsed] = '\0';
3574 if (rlen == nBytes) {
3586 if (IOBuf->BufSize < nBytes - nRead)
3587 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3590 slen = len = Blob->BufUsed;
3592 fdflags = fcntl(*fd, F_GETFL);
3593 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3598 while ((nRead < nBytes) &&
3607 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3608 *Error = strerror(errno);
3612 *Error = ErrRBLF_SelectFailed;
3615 if (! FD_ISSET(*fd, &rfds) != 0) {
3627 *Error = strerror(errno);
3630 else if (rlen == 0){
3632 if ((check == NNN_TERM) &&
3634 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3636 StrBufPlain(Blob, HKEY("\n000\n"));
3637 StrBufCutRight(Blob, 5);
3638 return Blob->BufUsed;
3640 if (nSelects > 10) {
3642 *Error = ErrRBB_too_many_selects;
3646 else if (rlen > 0) {
3649 IOBuf->BufUsed += rlen;
3652 if (nRead > nBytes) {
3653 *Pos = IOBuf->buf + nBytes;
3655 Blob->buf[Blob->BufUsed] = '\0';
3656 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3660 return nRead + nAlreadyRead;
3664 * @ingroup StrBuf_IO
3665 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3666 * @param LineBuf your line will be copied here.
3667 * @param Buf BLOB with lines of text...
3668 * @param Ptr moved arround to keep the next-line across several iterations
3669 * has to be &NULL on start; will be &NotNULL on end of buffer
3670 * @returns size of copied buffer
3672 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3674 const char *aptr, *ptr, *eptr;
3677 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3678 *Ptr = StrBufNOTNULL;
3682 FlushStrBuf(LineBuf);
3684 ptr = aptr = Buf->buf;
3688 optr = LineBuf->buf;
3689 eptr = Buf->buf + Buf->BufUsed;
3690 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3692 while ((ptr <= eptr) &&
3699 LineBuf->BufUsed = optr - LineBuf->buf;
3700 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3701 optr = LineBuf->buf + LineBuf->BufUsed;
3702 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3706 if ((ptr >= eptr) && (optr > LineBuf->buf))
3708 LineBuf->BufUsed = optr - LineBuf->buf;
3710 if ((ptr <= eptr) && (*ptr == '\r'))
3712 if ((ptr <= eptr) && (*ptr == '\n'))
3719 *Ptr = StrBufNOTNULL;
3722 return Buf->BufUsed - (ptr - Buf->buf);
3727 * @ingroup StrBuf_IO
3728 * @brief removes double slashes from pathnames
3729 * @param Dir directory string to filter
3730 * @param RemoveTrailingSlash allows / disallows trailing slashes
3732 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3738 while (!IsEmptyStr(a)) {
3750 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3755 Dir->BufUsed = b - Dir->buf;