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);
998 pRight = strchr(pBuff, rightboundary);
1000 StrBufCutAt(Buf, 0, pRight - 1);
1002 StrBufCutLeft(Buf, pLeft - Buf->buf);
1007 * @ingroup StrBuf_Filler
1008 * @brief uppercase the contents of a buffer
1009 * @param Buf the buffer to translate
1011 void StrBufUpCase(StrBuf *Buf)
1015 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1018 pche = pch + Buf->BufUsed;
1019 while (pch < pche) {
1020 *pch = toupper(*pch);
1027 * @ingroup StrBuf_Filler
1028 * @brief lowercase the contents of a buffer
1029 * @param Buf the buffer to translate
1031 void StrBufLowerCase(StrBuf *Buf)
1035 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1038 pche = pch + Buf->BufUsed;
1039 while (pch < pche) {
1040 *pch = tolower(*pch);
1046 /*******************************************************************************
1047 * a tokenizer that kills, maims, and destroys *
1048 *******************************************************************************/
1051 * @ingroup StrBuf_Tokenizer
1052 * @brief Replace a token at a given place with a given length by another token with given length
1053 * @param Buf String where to work on
1054 * @param where where inside of the Buf is the search-token
1055 * @param HowLong How long is the token to be replaced
1056 * @param Repl Token to insert at 'where'
1057 * @param ReplLen Length of repl
1058 * @returns -1 if fail else length of resulting Buf
1060 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1061 const char *Repl, long ReplLen)
1064 if ((Buf == NULL) ||
1065 (where > Buf->BufUsed) ||
1066 (where + HowLong > Buf->BufUsed))
1069 if (where + ReplLen - HowLong > Buf->BufSize)
1070 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1073 memmove(Buf->buf + where + HowLong,
1074 Buf->buf + where + ReplLen,
1075 Buf->BufUsed - where - HowLong);
1077 memcpy(Buf->buf + where,
1080 Buf->BufUsed += ReplLen - HowLong;
1082 return Buf->BufUsed;
1086 * @ingroup StrBuf_Tokenizer
1087 * @brief Counts the numbmer of tokens in a buffer
1088 * @param source String to count tokens in
1089 * @param tok Tokenizer char to count
1090 * @returns numbers of tokenizer chars found
1092 int StrBufNum_tokens(const StrBuf *source, char tok)
1096 if ((source == NULL) || (source->BufUsed == 0))
1098 if ((source->BufUsed == 1) && (*source->buf == tok))
1102 pche = pch + source->BufUsed;
1113 * @ingroup StrBuf_Tokenizer
1114 * @brief a string tokenizer
1115 * @param Source StringBuffer to read into
1116 * @param parmnum n'th Parameter to remove
1117 * @param separator tokenizer character
1118 * @returns -1 if not found, else length of token.
1120 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1123 char *d, *s, *end; /* dest, source */
1126 /* Find desired @parameter */
1127 end = Source->buf + Source->BufUsed;
1129 while ((d <= end) &&
1132 /* End of string, bail! */
1137 if (*d == separator) {
1142 if ((d == NULL) || (d >= end))
1143 return 0; /* @Parameter not found */
1145 /* Find next @parameter */
1147 while ((s <= end) &&
1148 (*s && *s != separator))
1152 if (*s == separator)
1156 /* Hack and slash */
1161 memmove(d, s, Source->BufUsed - (s - Source->buf));
1162 Source->BufUsed += ReducedBy;
1163 Source->buf[Source->BufUsed] = '\0';
1165 else if (d == Source->buf) {
1167 Source->BufUsed = 0;
1171 Source->BufUsed += ReducedBy;
1184 * @ingroup StrBuf_Tokenizer
1185 * @brief a string tokenizer
1186 * @param dest Destination StringBuffer
1187 * @param Source StringBuffer to read into
1188 * @param parmnum n'th Parameter to extract
1189 * @param separator tokenizer character
1190 * @returns -1 if not found, else length of token.
1192 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1194 const char *s, *e; //* source * /
1195 int len = 0; //* running total length of extracted string * /
1196 int current_token = 0; //* token currently being processed * /
1199 dest->buf[0] = '\0';
1205 if ((Source == NULL) || (Source->BufUsed ==0)) {
1209 e = s + Source->BufUsed;
1212 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1214 while ((s<e) && !IsEmptyStr(s)) {
1215 if (*s == separator) {
1218 if (len >= dest->BufSize) {
1219 dest->BufUsed = len;
1220 if (IncreaseBuf(dest, 1, -1) < 0) {
1225 if ( (current_token == parmnum) &&
1226 (*s != separator)) {
1227 dest->buf[len] = *s;
1230 else if (current_token > parmnum) {
1236 dest->buf[len] = '\0';
1237 dest->BufUsed = len;
1239 if (current_token < parmnum) {
1240 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1243 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1252 * @ingroup StrBuf_Tokenizer
1253 * @brief a string tokenizer to fetch an integer
1254 * @param Source String containing tokens
1255 * @param parmnum n'th Parameter to extract
1256 * @param separator tokenizer character
1257 * @returns 0 if not found, else integer representation of the token
1259 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1269 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1276 * @ingroup StrBuf_Tokenizer
1277 * @brief a string tokenizer to fetch a long integer
1278 * @param Source String containing tokens
1279 * @param parmnum n'th Parameter to extract
1280 * @param separator tokenizer character
1281 * @returns 0 if not found, else long integer representation of the token
1283 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1293 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1301 * @ingroup StrBuf_Tokenizer
1302 * @brief a string tokenizer to fetch an unsigned long
1303 * @param Source String containing tokens
1304 * @param parmnum n'th Parameter to extract
1305 * @param separator tokenizer character
1306 * @returns 0 if not found, else unsigned long representation of the token
1308 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1319 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1323 return (unsigned long) atol(pnum);
1332 * @ingroup StrBuf_NextTokenizer
1333 * @brief a string tokenizer; Bounds checker
1334 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1335 * @param Source our tokenbuffer
1336 * @param pStart the token iterator pointer to inspect
1337 * @returns whether the revolving pointer is inside of the search range
1339 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1341 if ((Source == NULL) ||
1342 (*pStart == StrBufNOTNULL) ||
1343 (Source->BufUsed == 0))
1347 if (*pStart == NULL)
1351 else if (*pStart > Source->buf + Source->BufUsed)
1355 else if (*pStart <= Source->buf)
1364 * @ingroup StrBuf_NextTokenizer
1365 * @brief a string tokenizer
1366 * @param dest Destination StringBuffer
1367 * @param Source StringBuffer to read into
1368 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1369 * @param separator tokenizer
1370 * @returns -1 if not found, else length of token.
1372 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1374 const char *s; /* source */
1375 const char *EndBuffer; /* end stop of source buffer */
1376 int current_token = 0; /* token currently being processed */
1377 int len = 0; /* running total length of extracted string */
1379 if ((Source == NULL) ||
1380 (Source->BufUsed == 0) )
1382 *pStart = StrBufNOTNULL;
1386 EndBuffer = Source->buf + Source->BufUsed;
1390 dest->buf[0] = '\0';
1395 *pStart = EndBuffer + 1;
1399 if (*pStart == NULL)
1401 *pStart = Source->buf; /* we're starting to examine this buffer. */
1403 else if ((*pStart < Source->buf) ||
1404 (*pStart > EndBuffer ) )
1406 return -1; /* no more tokens to find. */
1410 /* start to find the next token */
1411 while ((s <= EndBuffer) &&
1412 (current_token == 0) )
1414 if (*s == separator)
1416 /* we found the next token */
1420 if (len >= dest->BufSize)
1422 /* our Dest-buffer isn't big enough, increase it. */
1423 dest->BufUsed = len;
1425 if (IncreaseBuf(dest, 1, -1) < 0) {
1426 /* WHUT? no more mem? bail out. */
1433 if ( (current_token == 0 ) && /* are we in our target token? */
1434 (!IsEmptyStr(s) ) &&
1435 (separator != *s) ) /* don't copy the token itself */
1437 dest->buf[len] = *s; /* Copy the payload */
1438 ++len; /* remember the bigger size. */
1444 /* did we reach the end? */
1445 if ((s > EndBuffer)) {
1446 EndBuffer = StrBufNOTNULL;
1447 *pStart = EndBuffer;
1450 *pStart = s; /* remember the position for the next run */
1453 /* sanitize our extracted token */
1454 dest->buf[len] = '\0';
1455 dest->BufUsed = len;
1462 * @ingroup StrBuf_NextTokenizer
1463 * @brief a string tokenizer
1464 * @param Source StringBuffer to read from
1465 * @param pStart pointer to the end of the last token. Feed with NULL.
1466 * @param separator tokenizer character
1467 * @param nTokens number of tokens to fastforward over
1468 * @returns -1 if not found, else length of token.
1470 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1472 const char *s, *EndBuffer; //* source * /
1473 int len = 0; //* running total length of extracted string * /
1474 int current_token = 0; //* token currently being processed * /
1476 if ((Source == NULL) ||
1477 (Source->BufUsed ==0)) {
1481 return Source->BufUsed;
1483 if (*pStart == NULL)
1484 *pStart = Source->buf;
1486 EndBuffer = Source->buf + Source->BufUsed;
1488 if ((*pStart < Source->buf) ||
1489 (*pStart > EndBuffer)) {
1497 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1499 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1500 if (*s == separator) {
1503 if (current_token >= nTokens) {
1515 * @ingroup StrBuf_NextTokenizer
1516 * @brief a string tokenizer to fetch an integer
1517 * @param Source StringBuffer to read from
1518 * @param pStart Cursor on the tokenstring
1519 * @param separator tokenizer character
1520 * @returns 0 if not found, else integer representation of the token
1522 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1532 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1539 * @ingroup StrBuf_NextTokenizer
1540 * @brief a string tokenizer to fetch a long integer
1541 * @param Source StringBuffer to read from
1542 * @param pStart Cursor on the tokenstring
1543 * @param separator tokenizer character
1544 * @returns 0 if not found, else long integer representation of the token
1546 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1556 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1564 * @ingroup StrBuf_NextTokenizer
1565 * @brief a string tokenizer to fetch an unsigned long
1566 * @param Source StringBuffer to read from
1567 * @param pStart Cursor on the tokenstring
1568 * @param separator tokenizer character
1569 * @returns 0 if not found, else unsigned long representation of the token
1571 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1582 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1586 return (unsigned long) atol(pnum);
1596 /*******************************************************************************
1597 * Escape Appending *
1598 *******************************************************************************/
1601 * @ingroup StrBuf_DeEnCoder
1602 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1603 * @param OutBuf the output buffer
1604 * @param In Buffer to encode
1605 * @param PlainIn way in from plain old c strings
1607 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1609 const char *pch, *pche;
1613 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1615 if (PlainIn != NULL) {
1616 len = strlen(PlainIn);
1622 pche = pch + In->BufUsed;
1629 pt = OutBuf->buf + OutBuf->BufUsed;
1630 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1632 while (pch < pche) {
1634 IncreaseBuf(OutBuf, 1, -1);
1635 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1636 pt = OutBuf->buf + OutBuf->BufUsed;
1639 if((*pch >= 'a' && *pch <= 'z') ||
1640 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1641 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1642 (*pch == '!') || (*pch == '_') ||
1643 (*pch == ',') || (*pch == '.'))
1650 *(pt + 1) = HexList[(unsigned char)*pch][0];
1651 *(pt + 2) = HexList[(unsigned char)*pch][1];
1653 OutBuf->BufUsed += 3;
1661 * @ingroup StrBuf_DeEnCoder
1662 * @brief append a string in hex encoding to the buffer
1663 * @param OutBuf the output buffer
1664 * @param In Buffer to encode
1665 * @param PlainIn way in from plain old c strings
1667 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1669 const char *pch, *pche;
1673 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1675 if (PlainIn != NULL) {
1676 len = strlen(PlainIn);
1682 pche = pch + In->BufUsed;
1689 pt = OutBuf->buf + OutBuf->BufUsed;
1690 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1692 while (pch < pche) {
1694 IncreaseBuf(OutBuf, 1, -1);
1695 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1696 pt = OutBuf->buf + OutBuf->BufUsed;
1699 *pt = HexList[(unsigned char)*pch][0];
1701 *pt = HexList[(unsigned char)*pch][1];
1702 pt ++; pch ++; OutBuf->BufUsed += 2;
1708 * @ingroup StrBuf_DeEnCoder
1709 * @brief Append a string, escaping characters which have meaning in HTML.
1711 * @param Target target buffer
1712 * @param Source source buffer; set to NULL if you just have a C-String
1713 * @param PlainIn Plain-C string to append; set to NULL if unused
1714 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1715 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1716 * if set to 2, linebreaks are replaced by <br/>
1718 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1720 const char *aptr, *eiptr;
1724 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1727 if (PlainIn != NULL) {
1729 len = strlen(PlainIn);
1734 eiptr = aptr + Source->BufUsed;
1735 len = Source->BufUsed;
1741 bptr = Target->buf + Target->BufUsed;
1742 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1744 while (aptr < eiptr){
1746 IncreaseBuf(Target, 1, -1);
1747 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1748 bptr = Target->buf + Target->BufUsed;
1751 memcpy(bptr, "<", 4);
1753 Target->BufUsed += 4;
1755 else if (*aptr == '>') {
1756 memcpy(bptr, ">", 4);
1758 Target->BufUsed += 4;
1760 else if (*aptr == '&') {
1761 memcpy(bptr, "&", 5);
1763 Target->BufUsed += 5;
1765 else if (*aptr == '"') {
1766 memcpy(bptr, """, 6);
1768 Target->BufUsed += 6;
1770 else if (*aptr == '\'') {
1771 memcpy(bptr, "'", 5);
1773 Target->BufUsed += 5;
1775 else if (*aptr == LB) {
1780 else if (*aptr == RB) {
1785 else if (*aptr == QU) {
1790 else if ((*aptr == 32) && (nbsp == 1)) {
1791 memcpy(bptr, " ", 6);
1793 Target->BufUsed += 6;
1795 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1796 *bptr='\0'; /* nothing */
1798 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1799 memcpy(bptr, "<br/>", 11);
1801 Target->BufUsed += 11;
1805 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1806 *bptr='\0'; /* nothing */
1816 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1818 return Target->BufUsed;
1822 * @ingroup StrBuf_DeEnCoder
1823 * @brief Append a string, escaping characters which have meaning in HTML.
1824 * Converts linebreaks into blanks; escapes single quotes
1825 * @param Target target buffer
1826 * @param Source source buffer; set to NULL if you just have a C-String
1827 * @param PlainIn Plain-C string to append; set to NULL if unused
1829 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1831 const char *aptr, *eiptr;
1835 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1838 if (PlainIn != NULL) {
1840 len = strlen(PlainIn);
1845 eiptr = aptr + Source->BufUsed;
1846 len = Source->BufUsed;
1852 eptr = Target->buf + Target->BufSize - 8;
1853 tptr = Target->buf + Target->BufUsed;
1855 while (aptr < eiptr){
1857 IncreaseBuf(Target, 1, -1);
1858 eptr = Target->buf + Target->BufSize - 8;
1859 tptr = Target->buf + Target->BufUsed;
1862 if (*aptr == '\n') {
1866 else if (*aptr == '\r') {
1870 else if (*aptr == '\'') {
1876 Target->BufUsed += 5;
1889 * @ingroup StrBuf_DeEnCoder
1890 * @brief Append a string, escaping characters which have meaning in ICAL.
1892 * @param Target target buffer
1893 * @param Source source buffer; set to NULL if you just have a C-String
1894 * @param PlainIn Plain-C string to append; set to NULL if unused
1896 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1898 const char *aptr, *eiptr;
1902 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1905 if (PlainIn != NULL) {
1907 len = strlen(PlainIn);
1912 eiptr = aptr + Source->BufUsed;
1913 len = Source->BufUsed;
1919 eptr = Target->buf + Target->BufSize - 8;
1920 tptr = Target->buf + Target->BufUsed;
1922 while (aptr < eiptr){
1923 if(tptr + 3 >= eptr) {
1924 IncreaseBuf(Target, 1, -1);
1925 eptr = Target->buf + Target->BufSize - 8;
1926 tptr = Target->buf + Target->BufUsed;
1929 if (*aptr == '\n') {
1936 else if (*aptr == '\r') {
1943 else if (*aptr == ',') {
1959 * @ingroup StrBuf_DeEnCoder
1960 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1962 * @param Target target buffer
1963 * @param Source source buffer; set to NULL if you just have a C-String
1964 * @param PlainIn Plain-C string to append; set to NULL if unused
1965 * @returns size of result or -1
1967 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1969 const char *aptr, *eiptr;
1973 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1976 if (PlainIn != NULL) {
1978 len = strlen(PlainIn);
1983 eiptr = aptr + Source->BufUsed;
1984 len = Source->BufUsed;
1990 bptr = Target->buf + Target->BufUsed;
1991 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1993 while (aptr < eiptr){
1995 IncreaseBuf(Target, 1, -1);
1996 eptr = Target->buf + Target->BufSize - 3;
1997 bptr = Target->buf + Target->BufUsed;
2004 Target->BufUsed += 2;
2005 } else if (*aptr == '\\') {
2010 Target->BufUsed += 2;
2020 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2022 return Target->BufUsed;
2026 * @ingroup StrBuf_DeEnCoder
2027 * @brief Append a string, escaping characters which have meaning in HTML + json.
2029 * @param Target target buffer
2030 * @param Source source buffer; set to NULL if you just have a C-String
2031 * @param PlainIn Plain-C string to append; set to NULL if unused
2032 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2033 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2034 * if set to 2, linebreaks are replaced by <br/>
2036 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2038 const char *aptr, *eiptr;
2041 int IsUtf8Sequence = 0;
2043 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2046 if (PlainIn != NULL) {
2048 len = strlen(PlainIn);
2053 eiptr = aptr + Source->BufUsed;
2054 len = Source->BufUsed;
2060 bptr = Target->buf + Target->BufUsed;
2061 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2063 while (aptr < eiptr){
2065 IncreaseBuf(Target, 1, -1);
2066 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2067 bptr = Target->buf + Target->BufUsed;
2070 memcpy(bptr, "<", 4);
2072 Target->BufUsed += 4;
2074 else if (*aptr == '>') {
2075 memcpy(bptr, ">", 4);
2077 Target->BufUsed += 4;
2079 else if (*aptr == '&') {
2080 memcpy(bptr, "&", 5);
2082 Target->BufUsed += 5;
2084 else if (*aptr == LB) {
2089 else if (*aptr == RB) {
2094 else if ((*aptr == 32) && (nbsp == 1)) {
2095 memcpy(bptr, " ", 6);
2097 Target->BufUsed += 6;
2099 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2100 *bptr='\0'; /* nothing */
2102 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2103 memcpy(bptr, "<br/>", 11);
2105 Target->BufUsed += 11;
2108 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2109 *bptr='\0'; /* nothing */
2112 else if ((*aptr == '"') || (*aptr == QU)) {
2117 Target->BufUsed += 2;
2118 } else if (*aptr == '\\') {
2123 Target->BufUsed += 2;
2126 if (((unsigned char)*aptr) >= 0x20)
2128 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2132 while (IsUtf8Sequence > 1){
2133 if(bptr + IsUtf8Sequence >= eptr) {
2134 IncreaseBuf(Target, 1, -1);
2135 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2136 bptr = Target->buf + Target->BufUsed - 1;
2150 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2152 return Target->BufUsed;
2156 * @ingroup StrBuf_DeEnCoder
2157 * @brief unhide special chars hidden to the HTML escaper
2158 * @param target buffer to put the unescaped string in
2159 * @param source buffer to unescape
2161 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2167 FlushStrBuf(target);
2169 if (source == NULL ||target == NULL)
2174 len = source->BufUsed;
2175 for (a = 0; a < len; ++a) {
2176 if (target->BufUsed >= target->BufSize)
2177 IncreaseBuf(target, 1, -1);
2179 if (source->buf[a] == '=') {
2180 hex[0] = source->buf[a + 1];
2181 hex[1] = source->buf[a + 2];
2184 sscanf(hex, "%02x", &b);
2185 target->buf[target->BufUsed] = b;
2186 target->buf[++target->BufUsed] = 0;
2190 target->buf[target->BufUsed] = source->buf[a];
2191 target->buf[++target->BufUsed] = 0;
2198 * @ingroup StrBuf_DeEnCoder
2199 * @brief hide special chars from the HTML escapers and friends
2200 * @param target buffer to put the escaped string in
2201 * @param source buffer to escape
2203 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2208 FlushStrBuf(target);
2210 if (source == NULL ||target == NULL)
2215 len = source->BufUsed;
2216 for (i=0; i<len; ++i) {
2217 if (target->BufUsed + 4 >= target->BufSize)
2218 IncreaseBuf(target, 1, -1);
2219 if ( (isalnum(source->buf[i])) ||
2220 (source->buf[i]=='-') ||
2221 (source->buf[i]=='_') ) {
2222 target->buf[target->BufUsed++] = source->buf[i];
2225 sprintf(&target->buf[target->BufUsed],
2227 (0xFF &source->buf[i]));
2228 target->BufUsed += 3;
2231 target->buf[target->BufUsed + 1] = '\0';
2235 /*******************************************************************************
2236 * Quoted Printable de/encoding *
2237 *******************************************************************************/
2240 * @ingroup StrBuf_DeEnCoder
2241 * @brief decode a buffer from base 64 encoding; destroys original
2242 * @param Buf Buffor to transform
2244 int StrBufDecodeBase64(StrBuf *Buf)
2248 if (Buf == NULL) return -1;
2250 xferbuf = (char*) malloc(Buf->BufSize);
2251 siz = CtdlDecodeBase64(xferbuf,
2261 * @ingroup StrBuf_DeEnCoder
2262 * @brief decode a buffer from base 64 encoding; destroys original
2263 * @param Buf Buffor to transform
2265 int StrBufDecodeHex(StrBuf *Buf)
2268 char *pch, *pche, *pchi;
2270 if (Buf == NULL) return -1;
2272 pch = pchi = Buf->buf;
2273 pche = pch + Buf->BufUsed;
2275 while (pchi < pche){
2276 ch = decode_hex(pchi);
2283 Buf->BufUsed = pch - Buf->buf;
2284 return Buf->BufUsed;
2288 * @ingroup StrBuf_DeEnCoder
2289 * @brief replace all chars >0x20 && < 0x7F with Mute
2290 * @param Mute char to put over invalid chars
2291 * @param Buf Buffor to transform
2293 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2297 if (Buf == NULL) return -1;
2298 pch = (unsigned char *)Buf->buf;
2299 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2300 if ((*pch < 0x20) || (*pch > 0x7F))
2304 return Buf->BufUsed;
2309 * @ingroup StrBuf_DeEnCoder
2310 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2311 * @param Buf Buffer to translate
2312 * @param StripBlanks Reduce several blanks to one?
2314 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2323 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2324 Buf->buf[Buf->BufUsed - 1] = '\0';
2329 while (a < Buf->BufUsed) {
2330 if (Buf->buf[a] == '+')
2332 else if (Buf->buf[a] == '%') {
2333 /* don't let % chars through, rather truncate the input. */
2334 if (a + 2 > Buf->BufUsed) {
2339 hex[0] = Buf->buf[a + 1];
2340 hex[1] = Buf->buf[a + 2];
2343 sscanf(hex, "%02x", &b);
2344 Buf->buf[a] = (char) b;
2345 len = Buf->BufUsed - a - 2;
2347 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2359 * @ingroup StrBuf_DeEnCoder
2360 * @brief RFC2047-encode a header field if necessary.
2361 * If no non-ASCII characters are found, the string
2362 * will be copied verbatim without encoding.
2364 * @param target Target buffer.
2365 * @param source Source string to be encoded.
2366 * @returns encoded length; -1 if non success.
2368 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2370 const char headerStr[] = "=?UTF-8?Q?";
2371 int need_to_encode = 0;
2375 if ((source == NULL) ||
2379 while ((i < source->BufUsed) &&
2380 (!IsEmptyStr (&source->buf[i])) &&
2381 (need_to_encode == 0)) {
2382 if (((unsigned char) source->buf[i] < 32) ||
2383 ((unsigned char) source->buf[i] > 126)) {
2389 if (!need_to_encode) {
2390 if (*target == NULL) {
2391 *target = NewStrBufPlain(source->buf, source->BufUsed);
2394 FlushStrBuf(*target);
2395 StrBufAppendBuf(*target, source, 0);
2397 return (*target)->BufUsed;
2399 if (*target == NULL)
2400 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2401 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2402 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2403 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2404 (*target)->BufUsed = sizeof(headerStr) - 1;
2405 for (i=0; (i < source->BufUsed); ++i) {
2406 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2407 IncreaseBuf(*target, 1, 0);
2408 ch = (unsigned char) source->buf[i];
2409 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2410 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2411 (*target)->BufUsed += 3;
2414 (*target)->buf[(*target)->BufUsed] = ch;
2415 (*target)->BufUsed++;
2419 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2420 IncreaseBuf(*target, 1, 0);
2422 (*target)->buf[(*target)->BufUsed++] = '?';
2423 (*target)->buf[(*target)->BufUsed++] = '=';
2424 (*target)->buf[(*target)->BufUsed] = '\0';
2425 return (*target)->BufUsed;;
2430 * @brief replaces all occurances of 'search' by 'replace'
2431 * @param buf Buffer to modify
2432 * @param search character to search
2433 * @param replace character to replace search by
2435 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2440 for (i=0; i<buf->BufUsed; i++)
2441 if (buf->buf[i] == search)
2442 buf->buf[i] = replace;
2448 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2449 * @param buf Buffer to modify
2451 void StrBufToUnixLF(StrBuf *buf)
2453 char *pche, *pchS, *pchT;
2457 pche = buf->buf + buf->BufUsed;
2458 pchS = pchT = buf->buf;
2464 if (*pchS != '\n') {
2473 buf->BufUsed = pchT - buf->buf;
2477 /*******************************************************************************
2478 * Iconv Wrapper; RFC822 de/encoding *
2479 *******************************************************************************/
2482 * @ingroup StrBuf_DeEnCoder
2483 * @brief Wrapper around iconv_open()
2484 * Our version adds aliases for non-standard Microsoft charsets
2485 * such as 'MS950', aliasing them to names like 'CP950'
2487 * @param tocode Target encoding
2488 * @param fromcode Source encoding
2489 * @param pic anonimized pointer to iconv struct
2491 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2494 iconv_t ic = (iconv_t)(-1) ;
2495 ic = iconv_open(tocode, fromcode);
2496 if (ic == (iconv_t)(-1) ) {
2497 char alias_fromcode[64];
2498 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2499 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2500 alias_fromcode[0] = 'C';
2501 alias_fromcode[1] = 'P';
2502 ic = iconv_open(tocode, alias_fromcode);
2505 *(iconv_t *)pic = ic;
2511 * @ingroup StrBuf_DeEnCoder
2512 * @brief find one chunk of a RFC822 encoded string
2513 * @param Buffer where to search
2514 * @param bptr where to start searching
2515 * @returns found position, NULL if none.
2517 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2520 /* Find the next ?Q? */
2521 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2524 end = strchr(bptr + 2, '?');
2529 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2530 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2531 (*(end + 2) == '?')) {
2532 /* skip on to the end of the cluster, the next ?= */
2533 end = strstr(end + 3, "?=");
2536 /* sort of half valid encoding, try to find an end. */
2537 end = strstr(bptr, "?=");
2543 * @brief swaps the contents of two StrBufs
2544 * this is to be used to have cheap switched between a work-buffer and a target buffer
2545 * @param A First one
2546 * @param B second one
2548 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2552 memcpy(&C, A, sizeof(*A));
2553 memcpy(A, B, sizeof(*B));
2554 memcpy(B, &C, sizeof(C));
2560 * @ingroup StrBuf_DeEnCoder
2561 * @brief convert one buffer according to the preselected iconv pointer PIC
2562 * @param ConvertBuf buffer we need to translate
2563 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2564 * @param pic Pointer to the iconv-session Object
2566 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2572 char *ibuf; /**< Buffer of characters to be converted */
2573 char *obuf; /**< Buffer for converted characters */
2574 size_t ibuflen; /**< Length of input buffer */
2575 size_t obuflen; /**< Length of output buffer */
2578 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2579 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2580 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2582 ic = *(iconv_t*)pic;
2583 ibuf = ConvertBuf->buf;
2584 ibuflen = ConvertBuf->BufUsed;
2586 obuflen = TmpBuf->BufSize;
2588 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2591 if (errno == E2BIG) {
2593 IncreaseBuf(TmpBuf, 0, 0);
2598 else if (errno == EILSEQ){
2599 /* hm, invalid utf8 sequence... what to do now? */
2600 /* An invalid multibyte sequence has been encountered in the input */
2602 else if (errno == EINVAL) {
2603 /* An incomplete multibyte sequence has been encountered in the input. */
2606 FlushStrBuf(TmpBuf);
2609 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2610 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2612 /* little card game: wheres the red lady? */
2613 SwapBuffers(ConvertBuf, TmpBuf);
2614 FlushStrBuf(TmpBuf);
2621 * @ingroup StrBuf_DeEnCoder
2622 * @brief catches one RFC822 encoded segment, and decodes it.
2623 * @param Target buffer to fill with result
2624 * @param DecodeMe buffer with stuff to process
2625 * @param SegmentStart points to our current segment in DecodeMe
2626 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2627 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2628 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2629 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2631 inline static void DecodeSegment(StrBuf *Target,
2632 const StrBuf *DecodeMe,
2633 const char *SegmentStart,
2634 const char *SegmentEnd,
2636 StrBuf *ConvertBuf2,
2637 StrBuf *FoundCharset)
2643 iconv_t ic = (iconv_t)(-1);
2647 /* Now we handle foreign character sets properly encoded
2648 * in RFC2047 format.
2650 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2651 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2652 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2653 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2654 if (FoundCharset != NULL) {
2655 FlushStrBuf(FoundCharset);
2656 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2658 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2659 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2661 *encoding = toupper(*encoding);
2662 if (*encoding == 'B') { /**< base64 */
2663 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2665 ConvertBuf->BufUsed);
2667 else if (*encoding == 'Q') { /**< quoted-printable */
2671 while (pos < ConvertBuf->BufUsed)
2673 if (ConvertBuf->buf[pos] == '_')
2674 ConvertBuf->buf[pos] = ' ';
2678 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2681 ConvertBuf->BufUsed);
2684 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2687 ctdl_iconv_open("UTF-8", charset, &ic);
2688 if (ic != (iconv_t)(-1) ) {
2690 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2691 StrBufAppendBuf(Target, ConvertBuf2, 0);
2696 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2702 * @ingroup StrBuf_DeEnCoder
2703 * @brief Handle subjects with RFC2047 encoding such as:
2704 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2705 * @param Target where to put the decoded string to
2706 * @param DecodeMe buffer with encoded string
2707 * @param DefaultCharset if we don't find one, which should we use?
2708 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2709 * put it here for later use where no string might be known.
2711 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2713 StrBuf *DecodedInvalidBuf = NULL;
2714 StrBuf *ConvertBuf, *ConvertBuf2;
2715 const StrBuf *DecodeMee = DecodeMe;
2716 const char *start, *end, *next, *nextend, *ptr = NULL;
2718 iconv_t ic = (iconv_t)(-1) ;
2723 int illegal_non_rfc2047_encoding = 0;
2725 /* Sometimes, badly formed messages contain strings which were simply
2726 * written out directly in some foreign character set instead of
2727 * using RFC2047 encoding. This is illegal but we will attempt to
2728 * handle it anyway by converting from a user-specified default
2729 * charset to UTF-8 if we see any nonprintable characters.
2732 len = StrLength(DecodeMe);
2733 for (i=0; i<DecodeMe->BufUsed; ++i) {
2734 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2735 illegal_non_rfc2047_encoding = 1;
2740 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2741 if ((illegal_non_rfc2047_encoding) &&
2742 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2743 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2746 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2747 if (ic != (iconv_t)(-1) ) {
2748 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2749 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2750 DecodeMee = DecodedInvalidBuf;
2756 /* pre evaluate the first pair */
2757 nextend = end = NULL;
2758 len = StrLength(DecodeMee);
2759 start = strstr(DecodeMee->buf, "=?");
2760 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2762 end = FindNextEnd (DecodeMee, start);
2764 StrBufAppendBuf(Target, DecodeMee, 0);
2765 FreeStrBuf(&ConvertBuf);
2766 FreeStrBuf(&DecodedInvalidBuf);
2770 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2772 if (start != DecodeMee->buf) {
2775 nFront = start - DecodeMee->buf;
2776 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2780 * Since spammers will go to all sorts of absurd lengths to get their
2781 * messages through, there are LOTS of corrupt headers out there.
2782 * So, prevent a really badly formed RFC2047 header from throwing
2783 * this function into an infinite loop.
2785 while ((start != NULL) &&
2792 DecodeSegment(Target,
2800 next = strstr(end, "=?");
2802 if ((next != NULL) &&
2804 nextend = FindNextEnd(DecodeMee, next);
2805 if (nextend == NULL)
2808 /* did we find two partitions */
2809 if ((next != NULL) &&
2813 while ((ptr < next) &&
2820 * did we find a gab just filled with blanks?
2821 * if not, copy its stuff over.
2825 StrBufAppendBufPlain(Target,
2831 /* our next-pair is our new first pair now. */
2837 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2838 if ((end != NULL) && (end < nextend)) {
2840 while ( (ptr < nextend) &&
2847 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2849 FreeStrBuf(&ConvertBuf);
2850 FreeStrBuf(&ConvertBuf2);
2851 FreeStrBuf(&DecodedInvalidBuf);
2854 /*******************************************************************************
2855 * Manipulating UTF-8 Strings *
2856 *******************************************************************************/
2860 * @brief evaluate the length of an utf8 special character sequence
2861 * @param Char the character to examine
2862 * @returns width of utf8 chars in bytes
2864 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2869 while ((n < 8) && ((test & *CharS) != 0)) {
2873 if ((n > 6) || ((CharE - CharS) < n))
2880 * @brief detect whether this char starts an utf-8 encoded char
2881 * @param Char character to inspect
2882 * @returns yes or no
2884 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2886 /** 11??.???? indicates an UTF8 Sequence. */
2887 return ((Char & 0xC0) != 0);
2892 * @brief measure the number of glyphs in an UTF8 string...
2893 * @param Buf string to measure
2894 * @returns the number of glyphs in Buf
2896 long StrBuf_Utf8StrLen(StrBuf *Buf)
2902 if ((Buf == NULL) || (Buf->BufUsed == 0))
2905 eptr = Buf->buf + Buf->BufUsed;
2906 while ((aptr < eptr) && (*aptr != '\0')) {
2907 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2908 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2909 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2922 * @brief cuts a string after maxlen glyphs
2923 * @param Buf string to cut to maxlen glyphs
2924 * @param maxlen how long may the string become?
2925 * @returns current length of the string
2927 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2933 eptr = Buf->buf + Buf->BufUsed;
2934 while ((aptr < eptr) && (*aptr != '\0')) {
2935 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2936 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2937 while ((*aptr++ != '\0') && (m-- > 0));
2946 Buf->BufUsed = aptr - Buf->buf;
2947 return Buf->BufUsed;
2950 return Buf->BufUsed;
2958 /*******************************************************************************
2960 *******************************************************************************/
2963 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2964 #define OS_CODE 0x03 /*< unix */
2967 * @ingroup StrBuf_DeEnCoder
2968 * @brief uses the same calling syntax as compress2(), but it
2969 * creates a stream compatible with HTTP "Content-encoding: gzip"
2970 * @param dest compressed buffer
2971 * @param destLen length of the compresed data
2972 * @param source source to encode
2973 * @param sourceLen length of source to encode
2974 * @param level compression level
2976 int ZEXPORT compress_gzip(Bytef * dest,
2978 const Bytef * source,
2982 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2984 /* write gzip header */
2985 snprintf((char *) dest, *destLen,
2986 "%c%c%c%c%c%c%c%c%c%c",
2987 gz_magic[0], gz_magic[1], Z_DEFLATED,
2988 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2991 /* normal deflate */
2994 stream.next_in = (Bytef *) source;
2995 stream.avail_in = (uInt) sourceLen;
2996 stream.next_out = dest + 10L; // after header
2997 stream.avail_out = (uInt) * destLen;
2998 if ((uLong) stream.avail_out != *destLen)
3001 stream.zalloc = (alloc_func) 0;
3002 stream.zfree = (free_func) 0;
3003 stream.opaque = (voidpf) 0;
3005 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3006 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3010 err = deflate(&stream, Z_FINISH);
3011 if (err != Z_STREAM_END) {
3012 deflateEnd(&stream);
3013 return err == Z_OK ? Z_BUF_ERROR : err;
3015 *destLen = stream.total_out + 10L;
3017 /* write CRC and Length */
3018 uLong crc = crc32(0L, source, sourceLen);
3020 for (n = 0; n < 4; ++n, ++*destLen) {
3021 dest[*destLen] = (int) (crc & 0xff);
3024 uLong len = stream.total_in;
3025 for (n = 0; n < 4; ++n, ++*destLen) {
3026 dest[*destLen] = (int) (len & 0xff);
3029 err = deflateEnd(&stream);
3036 * @ingroup StrBuf_DeEnCoder
3037 * @brief compress the buffer with gzip
3038 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3039 * @param Buf buffer whose content is to be gzipped
3041 int CompressBuffer(StrBuf *Buf)
3044 char *compressed_data = NULL;
3045 size_t compressed_len, bufsize;
3048 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3049 compressed_data = malloc(compressed_len);
3051 if (compressed_data == NULL)
3053 /* Flush some space after the used payload so valgrind shuts up... */
3054 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3055 Buf->buf[Buf->BufUsed + i++] = '\0';
3056 if (compress_gzip((Bytef *) compressed_data,
3059 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3062 Buf->buf = compressed_data;
3063 Buf->BufUsed = compressed_len;
3064 Buf->BufSize = bufsize;
3065 /* Flush some space after the used payload so valgrind shuts up... */
3067 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3068 Buf->buf[Buf->BufUsed + i++] = '\0';
3071 free(compressed_data);
3073 #endif /* HAVE_ZLIB */
3079 /*******************************************************************************
3080 * File I/O; Prefer buffered read since its faster! *
3081 *******************************************************************************/
3084 * @ingroup StrBuf_IO
3085 * @brief Read a line from socket
3086 * flushes and closes the FD on error
3087 * @param buf the buffer to get the input to
3088 * @param fd pointer to the filedescriptor to read
3089 * @param append Append to an existing string or replace?
3090 * @param Error strerror() on error
3091 * @returns numbers of chars read
3093 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3095 int len, rlen, slen;
3100 slen = len = buf->BufUsed;
3102 rlen = read(*fd, &buf->buf[len], 1);
3104 *Error = strerror(errno);
3111 if (buf->buf[len] == '\n')
3113 if (buf->buf[len] != '\r')
3115 if (len + 2 >= buf->BufSize) {
3117 buf->buf[len+1] = '\0';
3118 IncreaseBuf(buf, 1, -1);
3122 buf->buf[len] = '\0';
3127 * @ingroup StrBuf_BufferedIO
3128 * @brief Read a line from socket
3129 * flushes and closes the FD on error
3130 * @param Line the line to read from the fd / I/O Buffer
3131 * @param buf the buffer to get the input to
3132 * @param fd pointer to the filedescriptor to read
3133 * @param timeout number of successless selects until we bail out
3134 * @param selectresolution how long to wait on each select
3135 * @param Error strerror() on error
3136 * @returns numbers of chars read
3138 int StrBufTCP_read_buffered_line(StrBuf *Line,
3142 int selectresolution,
3146 int nSuccessLess = 0;
3153 if (buf->BufUsed > 0) {
3154 pch = strchr(buf->buf, '\n');
3157 len = pch - buf->buf;
3158 if (len > 0 && (*(pch - 1) == '\r') )
3160 StrBufSub(Line, buf, 0, len - rlen);
3161 StrBufCutLeft(buf, len + 1);
3166 if (buf->BufSize - buf->BufUsed < 10)
3167 IncreaseBuf(buf, 1, -1);
3169 fdflags = fcntl(*fd, F_GETFL);
3170 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3172 while ((nSuccessLess < timeout) && (pch == NULL)) {
3174 tv.tv_sec = selectresolution;
3179 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3180 *Error = strerror(errno);
3186 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3191 &buf->buf[buf->BufUsed],
3192 buf->BufSize - buf->BufUsed - 1);
3194 *Error = strerror(errno);
3199 else if (rlen > 0) {
3201 buf->BufUsed += rlen;
3202 buf->buf[buf->BufUsed] = '\0';
3203 if (buf->BufUsed + 10 > buf->BufSize) {
3204 IncreaseBuf(buf, 1, -1);
3206 pch = strchr(buf->buf, '\n');
3213 len = pch - buf->buf;
3214 if (len > 0 && (*(pch - 1) == '\r') )
3216 StrBufSub(Line, buf, 0, len - rlen);
3217 StrBufCutLeft(buf, len + 1);
3224 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3225 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3226 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3228 * @ingroup StrBuf_BufferedIO
3229 * @brief Read a line from socket
3230 * flushes and closes the FD on error
3231 * @param Line where to append our Line read from the fd / I/O Buffer;
3232 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3233 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3234 * @param fd pointer to the filedescriptor to read
3235 * @param timeout number of successless selects until we bail out
3236 * @param selectresolution how long to wait on each select
3237 * @param Error strerror() on error
3238 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3240 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3245 int selectresolution,
3248 const char *pche = NULL;
3249 const char *pos = NULL;
3251 int len, rlen, retlen;
3252 int nSuccessLess = 0;
3254 const char *pch = NULL;
3260 if ((Line == NULL) ||
3267 *Error = ErrRBLF_PreConditionFailed;
3272 if ((IOBuf->BufUsed > 0) &&
3274 (pos < IOBuf->buf + IOBuf->BufUsed))
3278 pche = IOBuf->buf + IOBuf->BufUsed;
3282 while ((pch < pche) && (*pch != '\n'))
3284 if (Line->BufUsed + 10 > Line->BufSize)
3287 apos = pcht - Line->buf;
3289 IncreaseBuf(Line, 1, -1);
3290 pcht = Line->buf + apos;
3298 if (len > 0 && (*(pch - 1) == '\r') )
3307 if ((pch >= pche) || (*pch == '\0'))
3315 if ((pch != NULL) &&
3318 if (pch + 1 >= pche) {
3331 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3333 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3334 IncreaseBuf(IOBuf, 1, -1);
3336 fdflags = fcntl(*fd, F_GETFL);
3337 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3340 while ((nSuccessLess < timeout) &&
3350 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3351 *Error = strerror(errno);
3355 *Error = ErrRBLF_SelectFailed;
3358 if (! FD_ISSET(*fd, &rfds) != 0) {
3364 &IOBuf->buf[IOBuf->BufUsed],
3365 IOBuf->BufSize - IOBuf->BufUsed - 1);
3367 *Error = strerror(errno);
3372 else if (rlen > 0) {
3374 pLF = IOBuf->buf + IOBuf->BufUsed;
3375 IOBuf->BufUsed += rlen;
3376 IOBuf->buf[IOBuf->BufUsed] = '\0';
3378 pche = IOBuf->buf + IOBuf->BufUsed;
3380 while ((pLF < pche) && (*pLF != '\n'))
3382 if ((pLF >= pche) || (*pLF == '\0'))
3385 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3389 if (pLF != NULL) apos = pLF - IOBuf->buf;
3390 IncreaseBuf(IOBuf, 1, -1);
3391 if (pLF != NULL) pLF = IOBuf->buf + apos;
3401 if (len > 0 && (*(pLF - 1) == '\r') )
3403 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3404 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3410 return retlen + len;
3412 *Error = ErrRBLF_NotEnoughSentFromServer;
3417 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3419 * @ingroup StrBuf_IO
3420 * @brief Input binary data from socket
3421 * flushes and closes the FD on error
3422 * @param Buf the buffer to get the input to
3423 * @param fd pointer to the filedescriptor to read
3424 * @param append Append to an existing string or replace?
3425 * @param nBytes the maximal number of bytes to read
3426 * @param Error strerror() on error
3427 * @returns numbers of chars read
3429 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3432 int len, rlen, slen;
3440 if ((Buf == NULL) || (*fd == -1))
3442 *Error = ErrRBLF_BLOBPreConditionFailed;
3447 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3448 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3450 ptr = Buf->buf + Buf->BufUsed;
3452 slen = len = Buf->BufUsed;
3454 fdflags = fcntl(*fd, F_GETFL);
3455 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3457 while ((nRead < nBytes) &&
3467 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3468 *Error = strerror(errno);
3472 *Error = ErrRBLF_SelectFailed;
3475 if (! FD_ISSET(*fd, &rfds) != 0) {
3481 if ((rlen = read(*fd,
3483 nBytes - nRead)) == -1) {
3486 *Error = strerror(errno);
3491 Buf->BufUsed += rlen;
3493 Buf->buf[Buf->BufUsed] = '\0';
3497 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3498 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3500 * @ingroup StrBuf_BufferedIO
3501 * @brief Input binary data from socket
3502 * flushes and closes the FD on error
3503 * @param Blob put binary thing here
3504 * @param IOBuf the buffer to get the input to
3505 * @param Pos offset inside of IOBuf
3506 * @param fd pointer to the filedescriptor to read
3507 * @param append Append to an existing string or replace?
3508 * @param nBytes the maximal number of bytes to read
3509 * @param check whether we should search for '000\n' terminators in case of timeouts
3510 * @param Error strerror() on error
3511 * @returns numbers of chars read
3513 int StrBufReadBLOBBuffered(StrBuf *Blob,
3530 int nAlreadyRead = 0;
3538 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3542 *Error = ErrRBB_BLOBFPreConditionFailed;
3548 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3549 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3554 len = pos - IOBuf->buf;
3555 rlen = IOBuf->BufUsed - len;
3558 if ((IOBuf->BufUsed > 0) &&
3560 (pos < IOBuf->buf + IOBuf->BufUsed))
3562 pche = IOBuf->buf + IOBuf->BufUsed;
3565 if (rlen < nBytes) {
3566 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3567 Blob->BufUsed += rlen;
3568 Blob->buf[Blob->BufUsed] = '\0';
3569 nAlreadyRead = nRead = rlen;
3572 if (rlen >= nBytes) {
3573 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3574 Blob->BufUsed += nBytes;
3575 Blob->buf[Blob->BufUsed] = '\0';
3576 if (rlen == nBytes) {
3588 if (IOBuf->BufSize < nBytes - nRead)
3589 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3592 slen = len = Blob->BufUsed;
3594 fdflags = fcntl(*fd, F_GETFL);
3595 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3600 while ((nRead < nBytes) &&
3609 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3610 *Error = strerror(errno);
3614 *Error = ErrRBLF_SelectFailed;
3617 if (! FD_ISSET(*fd, &rfds) != 0) {
3629 *Error = strerror(errno);
3632 else if (rlen == 0){
3634 if ((check == NNN_TERM) &&
3636 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3638 StrBufPlain(Blob, HKEY("\n000\n"));
3639 StrBufCutRight(Blob, 5);
3640 return Blob->BufUsed;
3642 if (nSelects > 10) {
3644 *Error = ErrRBB_too_many_selects;
3648 else if (rlen > 0) {
3651 IOBuf->BufUsed += rlen;
3654 if (nRead > nBytes) {
3655 *Pos = IOBuf->buf + nBytes;
3657 Blob->buf[Blob->BufUsed] = '\0';
3658 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3662 return nRead + nAlreadyRead;
3666 * @ingroup StrBuf_IO
3667 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3668 * @param LineBuf your line will be copied here.
3669 * @param Buf BLOB with lines of text...
3670 * @param Ptr moved arround to keep the next-line across several iterations
3671 * has to be &NULL on start; will be &NotNULL on end of buffer
3672 * @returns size of copied buffer
3674 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3676 const char *aptr, *ptr, *eptr;
3679 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3680 *Ptr = StrBufNOTNULL;
3684 FlushStrBuf(LineBuf);
3686 ptr = aptr = Buf->buf;
3690 optr = LineBuf->buf;
3691 eptr = Buf->buf + Buf->BufUsed;
3692 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3694 while ((ptr <= eptr) &&
3701 LineBuf->BufUsed = optr - LineBuf->buf;
3702 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3703 optr = LineBuf->buf + LineBuf->BufUsed;
3704 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3708 if ((ptr >= eptr) && (optr > LineBuf->buf))
3710 LineBuf->BufUsed = optr - LineBuf->buf;
3712 if ((ptr <= eptr) && (*ptr == '\r'))
3714 if ((ptr <= eptr) && (*ptr == '\n'))
3721 *Ptr = StrBufNOTNULL;
3724 return Buf->BufUsed - (ptr - Buf->buf);
3729 * @ingroup StrBuf_IO
3730 * @brief removes double slashes from pathnames
3731 * @param Dir directory string to filter
3732 * @param RemoveTrailingSlash allows / disallows trailing slashes
3734 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3740 while (!IsEmptyStr(a)) {
3752 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3757 Dir->BufUsed = b - Dir->buf;