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;
435 CopySize = strlen(ptr);
439 while (Siz <= CopySize)
442 if (Siz != Buf->BufSize)
443 IncreaseBuf(Buf, 0, Siz);
444 memcpy(Buf->buf, ptr, CopySize);
445 Buf->buf[CopySize] = '\0';
446 Buf->BufUsed = CopySize;
453 * @ingroup StrBuf_DeConstructors
454 * @brief use strbuf as wrapper for a string constant for easy handling
455 * @param StringConstant a string to wrap
456 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
458 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
462 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
463 NewBuf->buf = (char*) StringConstant;
464 NewBuf->BufSize = SizeOfStrConstant;
465 NewBuf->BufUsed = SizeOfStrConstant;
466 NewBuf->ConstBuf = 1;
475 * @ingroup StrBuf_DeConstructors
476 * @brief flush the content of a Buf; keep its struct
477 * @param buf Buffer to flush
479 int FlushStrBuf(StrBuf *buf)
491 * @ingroup StrBuf_DeConstructors
492 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
493 * @param buf Buffer to wipe
495 int FLUSHStrBuf(StrBuf *buf)
501 if (buf->BufUsed > 0) {
502 memset(buf->buf, 0, buf->BufUsed);
509 int hFreeDbglog = -1;
512 * @ingroup StrBuf_DeConstructors
513 * @brief Release a Buffer
514 * Its a double pointer, so it can NULL your pointer
515 * so fancy SIG11 appear instead of random results
516 * @param FreeMe Pointer Pointer to the buffer to free
518 void FreeStrBuf (StrBuf **FreeMe)
523 dbg_FreeStrBuf(FreeMe, 'F');
525 if (!(*FreeMe)->ConstBuf)
526 free((*FreeMe)->buf);
532 * @ingroup StrBuf_DeConstructors
533 * @brief flatten a Buffer to the Char * we return
534 * Its a double pointer, so it can NULL your pointer
535 * so fancy SIG11 appear instead of random results
536 * The Callee then owns the buffer and is responsible for freeing it.
537 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
538 * @returns the pointer of the buffer; Callee owns the memory thereafter.
540 char *SmashStrBuf (StrBuf **SmashMe)
544 if ((SmashMe == NULL) || (*SmashMe == NULL))
547 dbg_FreeStrBuf(SmashMe, 'S');
549 Ret = (*SmashMe)->buf;
556 * @ingroup StrBuf_DeConstructors
557 * @brief Release the buffer
558 * If you want put your StrBuf into a Hash, use this as Destructor.
559 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
561 void HFreeStrBuf (void *VFreeMe)
563 StrBuf *FreeMe = (StrBuf*)VFreeMe;
567 dbg_FreeStrBuf(SmashMe, 'H');
569 if (!FreeMe->ConstBuf)
575 /*******************************************************************************
576 * Simple string transformations *
577 *******************************************************************************/
581 * @brief Wrapper around atol
583 long StrTol(const StrBuf *Buf)
588 return atol(Buf->buf);
595 * @brief Wrapper around atoi
597 int StrToi(const StrBuf *Buf)
601 if (Buf->BufUsed > 0)
602 return atoi(Buf->buf);
609 * @brief Checks to see if the string is a pure number
610 * @param Buf The buffer to inspect
611 * @returns 1 if its a pure number, 0, if not.
613 int StrBufIsNumber(const StrBuf *Buf) {
615 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
618 strtoll(Buf->buf, &pEnd, 10);
619 if (pEnd == Buf->buf)
621 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
623 if (Buf->buf == pEnd)
629 * @ingroup StrBuf_Filler
630 * @brief modifies a Single char of the Buf
631 * You can point to it via char* or a zero-based integer
632 * @param Buf The buffer to manipulate
633 * @param ptr char* to zero; use NULL if unused
634 * @param nThChar zero based pointer into the string; use -1 if unused
635 * @param PeekValue The Character to place into the position
637 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
642 nThChar = ptr - Buf->buf;
643 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
645 Buf->buf[nThChar] = PeekValue;
650 * @ingroup StrBuf_Filler
651 * @brief modifies a range of chars of the Buf
652 * You can point to it via char* or a zero-based integer
653 * @param Buf The buffer to manipulate
654 * @param ptr char* to zero; use NULL if unused
655 * @param nThChar zero based pointer into the string; use -1 if unused
656 * @param nChars how many chars are to be flushed?
657 * @param PookValue The Character to place into that area
659 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
664 nThChar = ptr - Buf->buf;
665 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
667 if (nThChar + nChars > Buf->BufUsed)
668 nChars = Buf->BufUsed - nThChar;
670 memset(Buf->buf + nThChar, PookValue, nChars);
671 /* just to be shure... */
672 Buf->buf[Buf->BufUsed] = 0;
677 * @ingroup StrBuf_Filler
678 * @brief Append a StringBuffer to the buffer
679 * @param Buf Buffer to modify
680 * @param AppendBuf Buffer to copy at the end of our buffer
681 * @param Offset Should we start copying from an offset?
683 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
685 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
688 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
691 AppendBuf->BufUsed + Buf->BufUsed);
693 memcpy(Buf->buf + Buf->BufUsed,
694 AppendBuf->buf + Offset,
695 AppendBuf->BufUsed - Offset);
696 Buf->BufUsed += AppendBuf->BufUsed - Offset;
697 Buf->buf[Buf->BufUsed] = '\0';
702 * @ingroup StrBuf_Filler
703 * @brief Append a C-String to the buffer
704 * @param Buf Buffer to modify
705 * @param AppendBuf Buffer to copy at the end of our buffer
706 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
707 * @param Offset Should we start copying from an offset?
709 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
712 long BufSizeRequired;
714 if ((AppendBuf == NULL) || (Buf == NULL))
718 aps = strlen(AppendBuf + Offset);
720 aps = AppendSize - Offset;
722 BufSizeRequired = Buf->BufUsed + aps + 1;
723 if (Buf->BufSize <= BufSizeRequired)
724 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
726 memcpy(Buf->buf + Buf->BufUsed,
730 Buf->buf[Buf->BufUsed] = '\0';
734 * @ingroup StrBuf_Filler
735 * @brief sprintf like function appending the formated string to the buffer
736 * vsnprintf version to wrap into own calls
737 * @param Buf Buffer to extend by format and Params
738 * @param format printf alike format to add
739 * @param ap va_list containing the items for format
741 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
749 if ((Buf == NULL) || (format == NULL))
752 BufSize = Buf->BufSize;
753 nWritten = Buf->BufSize + 1;
754 Offset = Buf->BufUsed;
755 newused = Offset + nWritten;
757 while (newused >= BufSize) {
759 nWritten = vsnprintf(Buf->buf + Offset,
760 Buf->BufSize - Offset,
763 newused = Offset + nWritten;
764 if (newused >= Buf->BufSize) {
765 IncreaseBuf(Buf, 1, newused);
766 newused = Buf->BufSize + 1;
769 Buf->BufUsed = Offset + nWritten;
770 BufSize = Buf->BufSize;
777 * @ingroup StrBuf_Filler
778 * @brief sprintf like function appending the formated string to the buffer
779 * @param Buf Buffer to extend by format and Params
780 * @param format printf alike format to add
782 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
790 if ((Buf == NULL) || (format == NULL))
793 BufSize = Buf->BufSize;
794 nWritten = Buf->BufSize + 1;
795 Offset = Buf->BufUsed;
796 newused = Offset + nWritten;
798 while (newused >= BufSize) {
799 va_start(arg_ptr, format);
800 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
801 Buf->BufSize - Buf->BufUsed,
804 newused = Buf->BufUsed + nWritten;
805 if (newused >= Buf->BufSize) {
806 IncreaseBuf(Buf, 1, newused);
807 newused = Buf->BufSize + 1;
810 Buf->BufUsed += nWritten;
811 BufSize = Buf->BufSize;
818 * @ingroup StrBuf_Filler
819 * @brief sprintf like function putting the formated string into the buffer
820 * @param Buf Buffer to extend by format and Parameters
821 * @param format printf alike format to add
823 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
828 if ((Buf == NULL) || (format == NULL))
831 nWritten = Buf->BufSize + 1;
832 while (nWritten >= Buf->BufSize) {
833 va_start(arg_ptr, format);
834 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
836 if (nWritten >= Buf->BufSize) {
837 IncreaseBuf(Buf, 0, 0);
838 nWritten = Buf->BufSize + 1;
841 Buf->BufUsed = nWritten ;
846 * @ingroup StrBuf_Filler
847 * @brief Callback for cURL to append the webserver reply to a buffer
848 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
849 * @param size pre-defined by the cURL API; see man 3 curl for mre info
850 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
851 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
853 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
862 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
869 * @brief extracts a substring from Source into dest
870 * @param dest buffer to place substring into
871 * @param Source string to copy substring from
872 * @param Offset chars to skip from start
873 * @param nChars number of chars to copy
874 * @returns the number of chars copied; may be different from nChars due to the size of Source
876 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
879 if (Offset > Source->BufUsed)
885 if (Offset + nChars < Source->BufUsed)
887 if (nChars >= dest->BufSize)
888 IncreaseBuf(dest, 0, nChars + 1);
889 memcpy(dest->buf, Source->buf + Offset, nChars);
890 dest->BufUsed = nChars;
891 dest->buf[dest->BufUsed] = '\0';
894 NCharsRemain = Source->BufUsed - Offset;
895 if (NCharsRemain >= dest->BufSize)
896 IncreaseBuf(dest, 0, NCharsRemain + 1);
897 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
898 dest->BufUsed = NCharsRemain;
899 dest->buf[dest->BufUsed] = '\0';
905 * @brief Cut nChars from the start of the string
906 * @param Buf Buffer to modify
907 * @param nChars how many chars should be skipped?
909 void StrBufCutLeft(StrBuf *Buf, int nChars)
911 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
912 if (nChars >= Buf->BufUsed) {
916 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
917 Buf->BufUsed -= nChars;
918 Buf->buf[Buf->BufUsed] = '\0';
923 * @brief Cut the trailing n Chars from the string
924 * @param Buf Buffer to modify
925 * @param nChars how many chars should be trunkated?
927 void StrBufCutRight(StrBuf *Buf, int nChars)
929 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
930 if (nChars >= Buf->BufUsed) {
934 Buf->BufUsed -= nChars;
935 Buf->buf[Buf->BufUsed] = '\0';
940 * @brief Cut the string after n Chars
941 * @param Buf Buffer to modify
942 * @param AfternChars after how many chars should we trunkate the string?
943 * @param At if non-null and points inside of our string, cut it there.
945 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
947 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
949 AfternChars = At - Buf->buf;
952 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
954 Buf->BufUsed = AfternChars;
955 Buf->buf[Buf->BufUsed] = '\0';
961 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
962 * @param Buf the string to modify
964 void StrBufTrim(StrBuf *Buf)
967 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
969 while ((Buf->BufUsed > 0) &&
970 isspace(Buf->buf[Buf->BufUsed - 1]))
974 Buf->buf[Buf->BufUsed] = '\0';
976 if (Buf->BufUsed == 0) return;
978 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
981 if (delta > 0) StrBufCutLeft(Buf, delta);
984 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
992 pLeft = pBuff = Buf->buf;
993 while (pBuff != NULL) {
995 pBuff = strchr(pBuff, leftboundary);
1004 pRight = strchr(pBuff, rightboundary);
1006 StrBufCutAt(Buf, 0, pRight);
1008 StrBufCutLeft(Buf, pLeft - Buf->buf);
1013 * @ingroup StrBuf_Filler
1014 * @brief uppercase the contents of a buffer
1015 * @param Buf the buffer to translate
1017 void StrBufUpCase(StrBuf *Buf)
1021 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1024 pche = pch + Buf->BufUsed;
1025 while (pch < pche) {
1026 *pch = toupper(*pch);
1033 * @ingroup StrBuf_Filler
1034 * @brief lowercase the contents of a buffer
1035 * @param Buf the buffer to translate
1037 void StrBufLowerCase(StrBuf *Buf)
1041 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1044 pche = pch + Buf->BufUsed;
1045 while (pch < pche) {
1046 *pch = tolower(*pch);
1052 /*******************************************************************************
1053 * a tokenizer that kills, maims, and destroys *
1054 *******************************************************************************/
1057 * @ingroup StrBuf_Tokenizer
1058 * @brief Replace a token at a given place with a given length by another token with given length
1059 * @param Buf String where to work on
1060 * @param where where inside of the Buf is the search-token
1061 * @param HowLong How long is the token to be replaced
1062 * @param Repl Token to insert at 'where'
1063 * @param ReplLen Length of repl
1064 * @returns -1 if fail else length of resulting Buf
1066 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1067 const char *Repl, long ReplLen)
1070 if ((Buf == NULL) ||
1071 (where > Buf->BufUsed) ||
1072 (where + HowLong > Buf->BufUsed))
1075 if (where + ReplLen - HowLong > Buf->BufSize)
1076 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1079 memmove(Buf->buf + where + ReplLen,
1080 Buf->buf + where + HowLong,
1081 Buf->BufUsed - where - HowLong);
1083 memcpy(Buf->buf + where,
1086 Buf->BufUsed += ReplLen - HowLong;
1088 return Buf->BufUsed;
1092 * @ingroup StrBuf_Tokenizer
1093 * @brief Counts the numbmer of tokens in a buffer
1094 * @param source String to count tokens in
1095 * @param tok Tokenizer char to count
1096 * @returns numbers of tokenizer chars found
1098 int StrBufNum_tokens(const StrBuf *source, char tok)
1102 if ((source == NULL) || (source->BufUsed == 0))
1104 if ((source->BufUsed == 1) && (*source->buf == tok))
1108 pche = pch + source->BufUsed;
1119 * @ingroup StrBuf_Tokenizer
1120 * @brief a string tokenizer
1121 * @param Source StringBuffer to read into
1122 * @param parmnum n'th Parameter to remove
1123 * @param separator tokenizer character
1124 * @returns -1 if not found, else length of token.
1126 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1129 char *d, *s, *end; /* dest, source */
1132 /* Find desired @parameter */
1133 end = Source->buf + Source->BufUsed;
1135 while ((d <= end) &&
1138 /* End of string, bail! */
1143 if (*d == separator) {
1148 if ((d == NULL) || (d >= end))
1149 return 0; /* @Parameter not found */
1151 /* Find next @parameter */
1153 while ((s <= end) &&
1154 (*s && *s != separator))
1158 if (*s == separator)
1162 /* Hack and slash */
1167 memmove(d, s, Source->BufUsed - (s - Source->buf));
1168 Source->BufUsed += ReducedBy;
1169 Source->buf[Source->BufUsed] = '\0';
1171 else if (d == Source->buf) {
1173 Source->BufUsed = 0;
1177 Source->BufUsed += ReducedBy;
1190 * @ingroup StrBuf_Tokenizer
1191 * @brief a string tokenizer
1192 * @param dest Destination StringBuffer
1193 * @param Source StringBuffer to read into
1194 * @param parmnum n'th Parameter to extract
1195 * @param separator tokenizer character
1196 * @returns -1 if not found, else length of token.
1198 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1200 const char *s, *e; //* source * /
1201 int len = 0; //* running total length of extracted string * /
1202 int current_token = 0; //* token currently being processed * /
1205 dest->buf[0] = '\0';
1211 if ((Source == NULL) || (Source->BufUsed ==0)) {
1215 e = s + Source->BufUsed;
1218 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1220 while ((s<e) && !IsEmptyStr(s)) {
1221 if (*s == separator) {
1224 if (len >= dest->BufSize) {
1225 dest->BufUsed = len;
1226 if (IncreaseBuf(dest, 1, -1) < 0) {
1231 if ( (current_token == parmnum) &&
1232 (*s != separator)) {
1233 dest->buf[len] = *s;
1236 else if (current_token > parmnum) {
1242 dest->buf[len] = '\0';
1243 dest->BufUsed = len;
1245 if (current_token < parmnum) {
1246 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1249 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1258 * @ingroup StrBuf_Tokenizer
1259 * @brief a string tokenizer to fetch an integer
1260 * @param Source String containing tokens
1261 * @param parmnum n'th Parameter to extract
1262 * @param separator tokenizer character
1263 * @returns 0 if not found, else integer representation of the token
1265 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1275 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1282 * @ingroup StrBuf_Tokenizer
1283 * @brief a string tokenizer to fetch a long integer
1284 * @param Source String containing tokens
1285 * @param parmnum n'th Parameter to extract
1286 * @param separator tokenizer character
1287 * @returns 0 if not found, else long integer representation of the token
1289 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1299 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1307 * @ingroup StrBuf_Tokenizer
1308 * @brief a string tokenizer to fetch an unsigned long
1309 * @param Source String containing tokens
1310 * @param parmnum n'th Parameter to extract
1311 * @param separator tokenizer character
1312 * @returns 0 if not found, else unsigned long representation of the token
1314 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1325 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1329 return (unsigned long) atol(pnum);
1338 * @ingroup StrBuf_NextTokenizer
1339 * @brief a string tokenizer; Bounds checker
1340 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1341 * @param Source our tokenbuffer
1342 * @param pStart the token iterator pointer to inspect
1343 * @returns whether the revolving pointer is inside of the search range
1345 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1347 if ((Source == NULL) ||
1348 (*pStart == StrBufNOTNULL) ||
1349 (Source->BufUsed == 0))
1353 if (*pStart == NULL)
1357 else if (*pStart > Source->buf + Source->BufUsed)
1361 else if (*pStart <= Source->buf)
1370 * @ingroup StrBuf_NextTokenizer
1371 * @brief a string tokenizer
1372 * @param dest Destination StringBuffer
1373 * @param Source StringBuffer to read into
1374 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1375 * @param separator tokenizer
1376 * @returns -1 if not found, else length of token.
1378 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1380 const char *s; /* source */
1381 const char *EndBuffer; /* end stop of source buffer */
1382 int current_token = 0; /* token currently being processed */
1383 int len = 0; /* running total length of extracted string */
1385 if ((Source == NULL) ||
1386 (Source->BufUsed == 0) )
1388 *pStart = StrBufNOTNULL;
1392 EndBuffer = Source->buf + Source->BufUsed;
1396 dest->buf[0] = '\0';
1401 *pStart = EndBuffer + 1;
1405 if (*pStart == NULL)
1407 *pStart = Source->buf; /* we're starting to examine this buffer. */
1409 else if ((*pStart < Source->buf) ||
1410 (*pStart > EndBuffer ) )
1412 return -1; /* no more tokens to find. */
1416 /* start to find the next token */
1417 while ((s <= EndBuffer) &&
1418 (current_token == 0) )
1420 if (*s == separator)
1422 /* we found the next token */
1426 if (len >= dest->BufSize)
1428 /* our Dest-buffer isn't big enough, increase it. */
1429 dest->BufUsed = len;
1431 if (IncreaseBuf(dest, 1, -1) < 0) {
1432 /* WHUT? no more mem? bail out. */
1439 if ( (current_token == 0 ) && /* are we in our target token? */
1440 (!IsEmptyStr(s) ) &&
1441 (separator != *s) ) /* don't copy the token itself */
1443 dest->buf[len] = *s; /* Copy the payload */
1444 ++len; /* remember the bigger size. */
1450 /* did we reach the end? */
1451 if ((s > EndBuffer)) {
1452 EndBuffer = StrBufNOTNULL;
1453 *pStart = EndBuffer;
1456 *pStart = s; /* remember the position for the next run */
1459 /* sanitize our extracted token */
1460 dest->buf[len] = '\0';
1461 dest->BufUsed = len;
1468 * @ingroup StrBuf_NextTokenizer
1469 * @brief a string tokenizer
1470 * @param Source StringBuffer to read from
1471 * @param pStart pointer to the end of the last token. Feed with NULL.
1472 * @param separator tokenizer character
1473 * @param nTokens number of tokens to fastforward over
1474 * @returns -1 if not found, else length of token.
1476 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1478 const char *s, *EndBuffer; //* source * /
1479 int len = 0; //* running total length of extracted string * /
1480 int current_token = 0; //* token currently being processed * /
1482 if ((Source == NULL) ||
1483 (Source->BufUsed ==0)) {
1487 return Source->BufUsed;
1489 if (*pStart == NULL)
1490 *pStart = Source->buf;
1492 EndBuffer = Source->buf + Source->BufUsed;
1494 if ((*pStart < Source->buf) ||
1495 (*pStart > EndBuffer)) {
1503 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1505 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1506 if (*s == separator) {
1509 if (current_token >= nTokens) {
1521 * @ingroup StrBuf_NextTokenizer
1522 * @brief a string tokenizer to fetch an integer
1523 * @param Source StringBuffer to read from
1524 * @param pStart Cursor on the tokenstring
1525 * @param separator tokenizer character
1526 * @returns 0 if not found, else integer representation of the token
1528 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1538 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1545 * @ingroup StrBuf_NextTokenizer
1546 * @brief a string tokenizer to fetch a long integer
1547 * @param Source StringBuffer to read from
1548 * @param pStart Cursor on the tokenstring
1549 * @param separator tokenizer character
1550 * @returns 0 if not found, else long integer representation of the token
1552 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1562 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1570 * @ingroup StrBuf_NextTokenizer
1571 * @brief a string tokenizer to fetch an unsigned long
1572 * @param Source StringBuffer to read from
1573 * @param pStart Cursor on the tokenstring
1574 * @param separator tokenizer character
1575 * @returns 0 if not found, else unsigned long representation of the token
1577 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1588 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1592 return (unsigned long) atol(pnum);
1602 /*******************************************************************************
1603 * Escape Appending *
1604 *******************************************************************************/
1607 * @ingroup StrBuf_DeEnCoder
1608 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1609 * @param OutBuf the output buffer
1610 * @param In Buffer to encode
1611 * @param PlainIn way in from plain old c strings
1613 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1615 const char *pch, *pche;
1619 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1621 if (PlainIn != NULL) {
1622 len = strlen(PlainIn);
1628 pche = pch + In->BufUsed;
1635 pt = OutBuf->buf + OutBuf->BufUsed;
1636 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1638 while (pch < pche) {
1640 IncreaseBuf(OutBuf, 1, -1);
1641 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1642 pt = OutBuf->buf + OutBuf->BufUsed;
1645 if((*pch >= 'a' && *pch <= 'z') ||
1646 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1647 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1648 (*pch == '!') || (*pch == '_') ||
1649 (*pch == ',') || (*pch == '.'))
1656 *(pt + 1) = HexList[(unsigned char)*pch][0];
1657 *(pt + 2) = HexList[(unsigned char)*pch][1];
1659 OutBuf->BufUsed += 3;
1667 * @ingroup StrBuf_DeEnCoder
1668 * @brief append a string in hex encoding to the buffer
1669 * @param OutBuf the output buffer
1670 * @param In Buffer to encode
1671 * @param PlainIn way in from plain old c strings
1673 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1675 const char *pch, *pche;
1679 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1681 if (PlainIn != NULL) {
1682 len = strlen(PlainIn);
1688 pche = pch + In->BufUsed;
1695 pt = OutBuf->buf + OutBuf->BufUsed;
1696 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1698 while (pch < pche) {
1700 IncreaseBuf(OutBuf, 1, -1);
1701 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1702 pt = OutBuf->buf + OutBuf->BufUsed;
1705 *pt = HexList[(unsigned char)*pch][0];
1707 *pt = HexList[(unsigned char)*pch][1];
1708 pt ++; pch ++; OutBuf->BufUsed += 2;
1714 * @ingroup StrBuf_DeEnCoder
1715 * @brief Append a string, escaping characters which have meaning in HTML.
1717 * @param Target target buffer
1718 * @param Source source buffer; set to NULL if you just have a C-String
1719 * @param PlainIn Plain-C string to append; set to NULL if unused
1720 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1721 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1722 * if set to 2, linebreaks are replaced by <br/>
1724 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1726 const char *aptr, *eiptr;
1730 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1733 if (PlainIn != NULL) {
1735 len = strlen(PlainIn);
1740 eiptr = aptr + Source->BufUsed;
1741 len = Source->BufUsed;
1747 bptr = Target->buf + Target->BufUsed;
1748 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1750 while (aptr < eiptr){
1752 IncreaseBuf(Target, 1, -1);
1753 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1754 bptr = Target->buf + Target->BufUsed;
1757 memcpy(bptr, "<", 4);
1759 Target->BufUsed += 4;
1761 else if (*aptr == '>') {
1762 memcpy(bptr, ">", 4);
1764 Target->BufUsed += 4;
1766 else if (*aptr == '&') {
1767 memcpy(bptr, "&", 5);
1769 Target->BufUsed += 5;
1771 else if (*aptr == '"') {
1772 memcpy(bptr, """, 6);
1774 Target->BufUsed += 6;
1776 else if (*aptr == '\'') {
1777 memcpy(bptr, "'", 5);
1779 Target->BufUsed += 5;
1781 else if (*aptr == LB) {
1786 else if (*aptr == RB) {
1791 else if (*aptr == QU) {
1796 else if ((*aptr == 32) && (nbsp == 1)) {
1797 memcpy(bptr, " ", 6);
1799 Target->BufUsed += 6;
1801 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1802 *bptr='\0'; /* nothing */
1804 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1805 memcpy(bptr, "<br/>", 11);
1807 Target->BufUsed += 11;
1811 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1812 *bptr='\0'; /* nothing */
1822 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1824 return Target->BufUsed;
1828 * @ingroup StrBuf_DeEnCoder
1829 * @brief Append a string, escaping characters which have meaning in HTML.
1830 * Converts linebreaks into blanks; escapes single quotes
1831 * @param Target target buffer
1832 * @param Source source buffer; set to NULL if you just have a C-String
1833 * @param PlainIn Plain-C string to append; set to NULL if unused
1835 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1837 const char *aptr, *eiptr;
1841 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1844 if (PlainIn != NULL) {
1846 len = strlen(PlainIn);
1851 eiptr = aptr + Source->BufUsed;
1852 len = Source->BufUsed;
1858 eptr = Target->buf + Target->BufSize - 8;
1859 tptr = Target->buf + Target->BufUsed;
1861 while (aptr < eiptr){
1863 IncreaseBuf(Target, 1, -1);
1864 eptr = Target->buf + Target->BufSize - 8;
1865 tptr = Target->buf + Target->BufUsed;
1868 if (*aptr == '\n') {
1872 else if (*aptr == '\r') {
1876 else if (*aptr == '\'') {
1882 Target->BufUsed += 5;
1895 * @ingroup StrBuf_DeEnCoder
1896 * @brief Append a string, escaping characters which have meaning in ICAL.
1898 * @param Target target buffer
1899 * @param Source source buffer; set to NULL if you just have a C-String
1900 * @param PlainIn Plain-C string to append; set to NULL if unused
1902 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1904 const char *aptr, *eiptr;
1908 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1911 if (PlainIn != NULL) {
1913 len = strlen(PlainIn);
1918 eiptr = aptr + Source->BufUsed;
1919 len = Source->BufUsed;
1925 eptr = Target->buf + Target->BufSize - 8;
1926 tptr = Target->buf + Target->BufUsed;
1928 while (aptr < eiptr){
1929 if(tptr + 3 >= eptr) {
1930 IncreaseBuf(Target, 1, -1);
1931 eptr = Target->buf + Target->BufSize - 8;
1932 tptr = Target->buf + Target->BufUsed;
1935 if (*aptr == '\n') {
1942 else if (*aptr == '\r') {
1949 else if (*aptr == ',') {
1965 * @ingroup StrBuf_DeEnCoder
1966 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1968 * @param Target target buffer
1969 * @param Source source buffer; set to NULL if you just have a C-String
1970 * @param PlainIn Plain-C string to append; set to NULL if unused
1971 * @returns size of result or -1
1973 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1975 const char *aptr, *eiptr;
1979 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1982 if (PlainIn != NULL) {
1984 len = strlen(PlainIn);
1989 eiptr = aptr + Source->BufUsed;
1990 len = Source->BufUsed;
1996 bptr = Target->buf + Target->BufUsed;
1997 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1999 while (aptr < eiptr){
2001 IncreaseBuf(Target, 1, -1);
2002 eptr = Target->buf + Target->BufSize - 3;
2003 bptr = Target->buf + Target->BufUsed;
2010 Target->BufUsed += 2;
2011 } else if (*aptr == '\\') {
2016 Target->BufUsed += 2;
2026 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2028 return Target->BufUsed;
2032 * @ingroup StrBuf_DeEnCoder
2033 * @brief Append a string, escaping characters which have meaning in HTML + json.
2035 * @param Target target buffer
2036 * @param Source source buffer; set to NULL if you just have a C-String
2037 * @param PlainIn Plain-C string to append; set to NULL if unused
2038 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2039 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2040 * if set to 2, linebreaks are replaced by <br/>
2042 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2044 const char *aptr, *eiptr;
2047 int IsUtf8Sequence = 0;
2049 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2052 if (PlainIn != NULL) {
2054 len = strlen(PlainIn);
2059 eiptr = aptr + Source->BufUsed;
2060 len = Source->BufUsed;
2066 bptr = Target->buf + Target->BufUsed;
2067 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2069 while (aptr < eiptr){
2071 IncreaseBuf(Target, 1, -1);
2072 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2073 bptr = Target->buf + Target->BufUsed;
2076 memcpy(bptr, "<", 4);
2078 Target->BufUsed += 4;
2080 else if (*aptr == '>') {
2081 memcpy(bptr, ">", 4);
2083 Target->BufUsed += 4;
2085 else if (*aptr == '&') {
2086 memcpy(bptr, "&", 5);
2088 Target->BufUsed += 5;
2090 else if (*aptr == LB) {
2095 else if (*aptr == RB) {
2100 else if ((*aptr == 32) && (nbsp == 1)) {
2101 memcpy(bptr, " ", 6);
2103 Target->BufUsed += 6;
2105 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2106 *bptr='\0'; /* nothing */
2108 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2109 memcpy(bptr, "<br/>", 11);
2111 Target->BufUsed += 11;
2114 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2115 *bptr='\0'; /* nothing */
2118 else if ((*aptr == '"') || (*aptr == QU)) {
2123 Target->BufUsed += 2;
2124 } else if (*aptr == '\\') {
2129 Target->BufUsed += 2;
2132 if (((unsigned char)*aptr) >= 0x20)
2134 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2138 while (IsUtf8Sequence > 1){
2139 if(bptr + IsUtf8Sequence >= eptr) {
2140 IncreaseBuf(Target, 1, -1);
2141 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2142 bptr = Target->buf + Target->BufUsed - 1;
2156 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2158 return Target->BufUsed;
2162 * @ingroup StrBuf_DeEnCoder
2163 * @brief unhide special chars hidden to the HTML escaper
2164 * @param target buffer to put the unescaped string in
2165 * @param source buffer to unescape
2167 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2173 FlushStrBuf(target);
2175 if (source == NULL ||target == NULL)
2180 len = source->BufUsed;
2181 for (a = 0; a < len; ++a) {
2182 if (target->BufUsed >= target->BufSize)
2183 IncreaseBuf(target, 1, -1);
2185 if (source->buf[a] == '=') {
2186 hex[0] = source->buf[a + 1];
2187 hex[1] = source->buf[a + 2];
2190 sscanf(hex, "%02x", &b);
2191 target->buf[target->BufUsed] = b;
2192 target->buf[++target->BufUsed] = 0;
2196 target->buf[target->BufUsed] = source->buf[a];
2197 target->buf[++target->BufUsed] = 0;
2204 * @ingroup StrBuf_DeEnCoder
2205 * @brief hide special chars from the HTML escapers and friends
2206 * @param target buffer to put the escaped string in
2207 * @param source buffer to escape
2209 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2214 FlushStrBuf(target);
2216 if (source == NULL ||target == NULL)
2221 len = source->BufUsed;
2222 for (i=0; i<len; ++i) {
2223 if (target->BufUsed + 4 >= target->BufSize)
2224 IncreaseBuf(target, 1, -1);
2225 if ( (isalnum(source->buf[i])) ||
2226 (source->buf[i]=='-') ||
2227 (source->buf[i]=='_') ) {
2228 target->buf[target->BufUsed++] = source->buf[i];
2231 sprintf(&target->buf[target->BufUsed],
2233 (0xFF &source->buf[i]));
2234 target->BufUsed += 3;
2237 target->buf[target->BufUsed + 1] = '\0';
2241 /*******************************************************************************
2242 * Quoted Printable de/encoding *
2243 *******************************************************************************/
2246 * @ingroup StrBuf_DeEnCoder
2247 * @brief decode a buffer from base 64 encoding; destroys original
2248 * @param Buf Buffor to transform
2250 int StrBufDecodeBase64(StrBuf *Buf)
2254 if (Buf == NULL) return -1;
2256 xferbuf = (char*) malloc(Buf->BufSize);
2257 siz = CtdlDecodeBase64(xferbuf,
2267 * @ingroup StrBuf_DeEnCoder
2268 * @brief decode a buffer from base 64 encoding; destroys original
2269 * @param Buf Buffor to transform
2271 int StrBufDecodeHex(StrBuf *Buf)
2274 char *pch, *pche, *pchi;
2276 if (Buf == NULL) return -1;
2278 pch = pchi = Buf->buf;
2279 pche = pch + Buf->BufUsed;
2281 while (pchi < pche){
2282 ch = decode_hex(pchi);
2289 Buf->BufUsed = pch - Buf->buf;
2290 return Buf->BufUsed;
2294 * @ingroup StrBuf_DeEnCoder
2295 * @brief replace all chars >0x20 && < 0x7F with Mute
2296 * @param Mute char to put over invalid chars
2297 * @param Buf Buffor to transform
2299 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2303 if (Buf == NULL) return -1;
2304 pch = (unsigned char *)Buf->buf;
2305 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2306 if ((*pch < 0x20) || (*pch > 0x7F))
2310 return Buf->BufUsed;
2315 * @ingroup StrBuf_DeEnCoder
2316 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2317 * @param Buf Buffer to translate
2318 * @param StripBlanks Reduce several blanks to one?
2320 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2329 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2330 Buf->buf[Buf->BufUsed - 1] = '\0';
2335 while (a < Buf->BufUsed) {
2336 if (Buf->buf[a] == '+')
2338 else if (Buf->buf[a] == '%') {
2339 /* don't let % chars through, rather truncate the input. */
2340 if (a + 2 > Buf->BufUsed) {
2345 hex[0] = Buf->buf[a + 1];
2346 hex[1] = Buf->buf[a + 2];
2349 sscanf(hex, "%02x", &b);
2350 Buf->buf[a] = (char) b;
2351 len = Buf->BufUsed - a - 2;
2353 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2365 * @ingroup StrBuf_DeEnCoder
2366 * @brief RFC2047-encode a header field if necessary.
2367 * If no non-ASCII characters are found, the string
2368 * will be copied verbatim without encoding.
2370 * @param target Target buffer.
2371 * @param source Source string to be encoded.
2372 * @returns encoded length; -1 if non success.
2374 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2376 const char headerStr[] = "=?UTF-8?Q?";
2377 int need_to_encode = 0;
2381 if ((source == NULL) ||
2385 while ((i < source->BufUsed) &&
2386 (!IsEmptyStr (&source->buf[i])) &&
2387 (need_to_encode == 0)) {
2388 if (((unsigned char) source->buf[i] < 32) ||
2389 ((unsigned char) source->buf[i] > 126)) {
2395 if (!need_to_encode) {
2396 if (*target == NULL) {
2397 *target = NewStrBufPlain(source->buf, source->BufUsed);
2400 FlushStrBuf(*target);
2401 StrBufAppendBuf(*target, source, 0);
2403 return (*target)->BufUsed;
2405 if (*target == NULL)
2406 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2407 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2408 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2409 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2410 (*target)->BufUsed = sizeof(headerStr) - 1;
2411 for (i=0; (i < source->BufUsed); ++i) {
2412 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2413 IncreaseBuf(*target, 1, 0);
2414 ch = (unsigned char) source->buf[i];
2415 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2416 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2417 (*target)->BufUsed += 3;
2420 (*target)->buf[(*target)->BufUsed] = ch;
2421 (*target)->BufUsed++;
2425 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2426 IncreaseBuf(*target, 1, 0);
2428 (*target)->buf[(*target)->BufUsed++] = '?';
2429 (*target)->buf[(*target)->BufUsed++] = '=';
2430 (*target)->buf[(*target)->BufUsed] = '\0';
2431 return (*target)->BufUsed;;
2436 * @brief replaces all occurances of 'search' by 'replace'
2437 * @param buf Buffer to modify
2438 * @param search character to search
2439 * @param replace character to replace search by
2441 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2446 for (i=0; i<buf->BufUsed; i++)
2447 if (buf->buf[i] == search)
2448 buf->buf[i] = replace;
2454 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2455 * @param buf Buffer to modify
2457 void StrBufToUnixLF(StrBuf *buf)
2459 char *pche, *pchS, *pchT;
2463 pche = buf->buf + buf->BufUsed;
2464 pchS = pchT = buf->buf;
2470 if (*pchS != '\n') {
2479 buf->BufUsed = pchT - buf->buf;
2483 /*******************************************************************************
2484 * Iconv Wrapper; RFC822 de/encoding *
2485 *******************************************************************************/
2488 * @ingroup StrBuf_DeEnCoder
2489 * @brief Wrapper around iconv_open()
2490 * Our version adds aliases for non-standard Microsoft charsets
2491 * such as 'MS950', aliasing them to names like 'CP950'
2493 * @param tocode Target encoding
2494 * @param fromcode Source encoding
2495 * @param pic anonimized pointer to iconv struct
2497 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2500 iconv_t ic = (iconv_t)(-1) ;
2501 ic = iconv_open(tocode, fromcode);
2502 if (ic == (iconv_t)(-1) ) {
2503 char alias_fromcode[64];
2504 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2505 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2506 alias_fromcode[0] = 'C';
2507 alias_fromcode[1] = 'P';
2508 ic = iconv_open(tocode, alias_fromcode);
2511 *(iconv_t *)pic = ic;
2517 * @ingroup StrBuf_DeEnCoder
2518 * @brief find one chunk of a RFC822 encoded string
2519 * @param Buffer where to search
2520 * @param bptr where to start searching
2521 * @returns found position, NULL if none.
2523 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2526 /* Find the next ?Q? */
2527 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2530 end = strchr(bptr + 2, '?');
2535 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2536 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2537 (*(end + 2) == '?')) {
2538 /* skip on to the end of the cluster, the next ?= */
2539 end = strstr(end + 3, "?=");
2542 /* sort of half valid encoding, try to find an end. */
2543 end = strstr(bptr, "?=");
2549 * @brief swaps the contents of two StrBufs
2550 * this is to be used to have cheap switched between a work-buffer and a target buffer
2551 * @param A First one
2552 * @param B second one
2554 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2558 memcpy(&C, A, sizeof(*A));
2559 memcpy(A, B, sizeof(*B));
2560 memcpy(B, &C, sizeof(C));
2566 * @ingroup StrBuf_DeEnCoder
2567 * @brief convert one buffer according to the preselected iconv pointer PIC
2568 * @param ConvertBuf buffer we need to translate
2569 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2570 * @param pic Pointer to the iconv-session Object
2572 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2578 char *ibuf; /**< Buffer of characters to be converted */
2579 char *obuf; /**< Buffer for converted characters */
2580 size_t ibuflen; /**< Length of input buffer */
2581 size_t obuflen; /**< Length of output buffer */
2584 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2585 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2586 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2588 ic = *(iconv_t*)pic;
2589 ibuf = ConvertBuf->buf;
2590 ibuflen = ConvertBuf->BufUsed;
2592 obuflen = TmpBuf->BufSize;
2594 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2597 if (errno == E2BIG) {
2599 IncreaseBuf(TmpBuf, 0, 0);
2604 else if (errno == EILSEQ){
2605 /* hm, invalid utf8 sequence... what to do now? */
2606 /* An invalid multibyte sequence has been encountered in the input */
2608 else if (errno == EINVAL) {
2609 /* An incomplete multibyte sequence has been encountered in the input. */
2612 FlushStrBuf(TmpBuf);
2615 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2616 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2618 /* little card game: wheres the red lady? */
2619 SwapBuffers(ConvertBuf, TmpBuf);
2620 FlushStrBuf(TmpBuf);
2627 * @ingroup StrBuf_DeEnCoder
2628 * @brief catches one RFC822 encoded segment, and decodes it.
2629 * @param Target buffer to fill with result
2630 * @param DecodeMe buffer with stuff to process
2631 * @param SegmentStart points to our current segment in DecodeMe
2632 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2633 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2634 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2635 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2637 inline static void DecodeSegment(StrBuf *Target,
2638 const StrBuf *DecodeMe,
2639 const char *SegmentStart,
2640 const char *SegmentEnd,
2642 StrBuf *ConvertBuf2,
2643 StrBuf *FoundCharset)
2649 iconv_t ic = (iconv_t)(-1);
2653 /* Now we handle foreign character sets properly encoded
2654 * in RFC2047 format.
2656 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2657 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2658 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2659 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2660 if (FoundCharset != NULL) {
2661 FlushStrBuf(FoundCharset);
2662 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2664 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2665 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2667 *encoding = toupper(*encoding);
2668 if (*encoding == 'B') { /**< base64 */
2669 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2671 ConvertBuf->BufUsed);
2673 else if (*encoding == 'Q') { /**< quoted-printable */
2677 while (pos < ConvertBuf->BufUsed)
2679 if (ConvertBuf->buf[pos] == '_')
2680 ConvertBuf->buf[pos] = ' ';
2684 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2687 ConvertBuf->BufUsed);
2690 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2693 ctdl_iconv_open("UTF-8", charset, &ic);
2694 if (ic != (iconv_t)(-1) ) {
2696 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2697 StrBufAppendBuf(Target, ConvertBuf2, 0);
2702 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2708 * @ingroup StrBuf_DeEnCoder
2709 * @brief Handle subjects with RFC2047 encoding such as:
2710 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2711 * @param Target where to put the decoded string to
2712 * @param DecodeMe buffer with encoded string
2713 * @param DefaultCharset if we don't find one, which should we use?
2714 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2715 * put it here for later use where no string might be known.
2717 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2719 StrBuf *DecodedInvalidBuf = NULL;
2720 StrBuf *ConvertBuf, *ConvertBuf2;
2721 const StrBuf *DecodeMee = DecodeMe;
2722 const char *start, *end, *next, *nextend, *ptr = NULL;
2724 iconv_t ic = (iconv_t)(-1) ;
2729 int illegal_non_rfc2047_encoding = 0;
2731 /* Sometimes, badly formed messages contain strings which were simply
2732 * written out directly in some foreign character set instead of
2733 * using RFC2047 encoding. This is illegal but we will attempt to
2734 * handle it anyway by converting from a user-specified default
2735 * charset to UTF-8 if we see any nonprintable characters.
2738 len = StrLength(DecodeMe);
2739 for (i=0; i<DecodeMe->BufUsed; ++i) {
2740 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2741 illegal_non_rfc2047_encoding = 1;
2746 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2747 if ((illegal_non_rfc2047_encoding) &&
2748 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2749 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2752 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2753 if (ic != (iconv_t)(-1) ) {
2754 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2755 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2756 DecodeMee = DecodedInvalidBuf;
2762 /* pre evaluate the first pair */
2763 nextend = end = NULL;
2764 len = StrLength(DecodeMee);
2765 start = strstr(DecodeMee->buf, "=?");
2766 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2768 end = FindNextEnd (DecodeMee, start);
2770 StrBufAppendBuf(Target, DecodeMee, 0);
2771 FreeStrBuf(&ConvertBuf);
2772 FreeStrBuf(&DecodedInvalidBuf);
2776 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2778 if (start != DecodeMee->buf) {
2781 nFront = start - DecodeMee->buf;
2782 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2786 * Since spammers will go to all sorts of absurd lengths to get their
2787 * messages through, there are LOTS of corrupt headers out there.
2788 * So, prevent a really badly formed RFC2047 header from throwing
2789 * this function into an infinite loop.
2791 while ((start != NULL) &&
2798 DecodeSegment(Target,
2806 next = strstr(end, "=?");
2808 if ((next != NULL) &&
2810 nextend = FindNextEnd(DecodeMee, next);
2811 if (nextend == NULL)
2814 /* did we find two partitions */
2815 if ((next != NULL) &&
2819 while ((ptr < next) &&
2826 * did we find a gab just filled with blanks?
2827 * if not, copy its stuff over.
2831 StrBufAppendBufPlain(Target,
2837 /* our next-pair is our new first pair now. */
2843 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2844 if ((end != NULL) && (end < nextend)) {
2846 while ( (ptr < nextend) &&
2853 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2855 FreeStrBuf(&ConvertBuf);
2856 FreeStrBuf(&ConvertBuf2);
2857 FreeStrBuf(&DecodedInvalidBuf);
2860 /*******************************************************************************
2861 * Manipulating UTF-8 Strings *
2862 *******************************************************************************/
2866 * @brief evaluate the length of an utf8 special character sequence
2867 * @param Char the character to examine
2868 * @returns width of utf8 chars in bytes
2870 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2875 while ((n < 8) && ((test & *CharS) != 0)) {
2879 if ((n > 6) || ((CharE - CharS) < n))
2886 * @brief detect whether this char starts an utf-8 encoded char
2887 * @param Char character to inspect
2888 * @returns yes or no
2890 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2892 /** 11??.???? indicates an UTF8 Sequence. */
2893 return ((Char & 0xC0) != 0);
2898 * @brief measure the number of glyphs in an UTF8 string...
2899 * @param Buf string to measure
2900 * @returns the number of glyphs in Buf
2902 long StrBuf_Utf8StrLen(StrBuf *Buf)
2908 if ((Buf == NULL) || (Buf->BufUsed == 0))
2911 eptr = Buf->buf + Buf->BufUsed;
2912 while ((aptr < eptr) && (*aptr != '\0')) {
2913 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2914 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2915 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2928 * @brief cuts a string after maxlen glyphs
2929 * @param Buf string to cut to maxlen glyphs
2930 * @param maxlen how long may the string become?
2931 * @returns current length of the string
2933 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2939 eptr = Buf->buf + Buf->BufUsed;
2940 while ((aptr < eptr) && (*aptr != '\0')) {
2941 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2942 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2943 while ((*aptr++ != '\0') && (m-- > 0));
2952 Buf->BufUsed = aptr - Buf->buf;
2953 return Buf->BufUsed;
2956 return Buf->BufUsed;
2964 /*******************************************************************************
2966 *******************************************************************************/
2969 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2970 #define OS_CODE 0x03 /*< unix */
2973 * @ingroup StrBuf_DeEnCoder
2974 * @brief uses the same calling syntax as compress2(), but it
2975 * creates a stream compatible with HTTP "Content-encoding: gzip"
2976 * @param dest compressed buffer
2977 * @param destLen length of the compresed data
2978 * @param source source to encode
2979 * @param sourceLen length of source to encode
2980 * @param level compression level
2982 int ZEXPORT compress_gzip(Bytef * dest,
2984 const Bytef * source,
2988 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2990 /* write gzip header */
2991 snprintf((char *) dest, *destLen,
2992 "%c%c%c%c%c%c%c%c%c%c",
2993 gz_magic[0], gz_magic[1], Z_DEFLATED,
2994 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2997 /* normal deflate */
3000 stream.next_in = (Bytef *) source;
3001 stream.avail_in = (uInt) sourceLen;
3002 stream.next_out = dest + 10L; // after header
3003 stream.avail_out = (uInt) * destLen;
3004 if ((uLong) stream.avail_out != *destLen)
3007 stream.zalloc = (alloc_func) 0;
3008 stream.zfree = (free_func) 0;
3009 stream.opaque = (voidpf) 0;
3011 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3012 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3016 err = deflate(&stream, Z_FINISH);
3017 if (err != Z_STREAM_END) {
3018 deflateEnd(&stream);
3019 return err == Z_OK ? Z_BUF_ERROR : err;
3021 *destLen = stream.total_out + 10L;
3023 /* write CRC and Length */
3024 uLong crc = crc32(0L, source, sourceLen);
3026 for (n = 0; n < 4; ++n, ++*destLen) {
3027 dest[*destLen] = (int) (crc & 0xff);
3030 uLong len = stream.total_in;
3031 for (n = 0; n < 4; ++n, ++*destLen) {
3032 dest[*destLen] = (int) (len & 0xff);
3035 err = deflateEnd(&stream);
3042 * @ingroup StrBuf_DeEnCoder
3043 * @brief compress the buffer with gzip
3044 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3045 * @param Buf buffer whose content is to be gzipped
3047 int CompressBuffer(StrBuf *Buf)
3050 char *compressed_data = NULL;
3051 size_t compressed_len, bufsize;
3054 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3055 compressed_data = malloc(compressed_len);
3057 if (compressed_data == NULL)
3059 /* Flush some space after the used payload so valgrind shuts up... */
3060 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3061 Buf->buf[Buf->BufUsed + i++] = '\0';
3062 if (compress_gzip((Bytef *) compressed_data,
3065 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3068 Buf->buf = compressed_data;
3069 Buf->BufUsed = compressed_len;
3070 Buf->BufSize = bufsize;
3071 /* Flush some space after the used payload so valgrind shuts up... */
3073 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3074 Buf->buf[Buf->BufUsed + i++] = '\0';
3077 free(compressed_data);
3079 #endif /* HAVE_ZLIB */
3085 /*******************************************************************************
3086 * File I/O; Prefer buffered read since its faster! *
3087 *******************************************************************************/
3090 * @ingroup StrBuf_IO
3091 * @brief Read a line from socket
3092 * flushes and closes the FD on error
3093 * @param buf the buffer to get the input to
3094 * @param fd pointer to the filedescriptor to read
3095 * @param append Append to an existing string or replace?
3096 * @param Error strerror() on error
3097 * @returns numbers of chars read
3099 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3101 int len, rlen, slen;
3106 slen = len = buf->BufUsed;
3108 rlen = read(*fd, &buf->buf[len], 1);
3110 *Error = strerror(errno);
3117 if (buf->buf[len] == '\n')
3119 if (buf->buf[len] != '\r')
3121 if (len + 2 >= buf->BufSize) {
3123 buf->buf[len+1] = '\0';
3124 IncreaseBuf(buf, 1, -1);
3128 buf->buf[len] = '\0';
3133 * @ingroup StrBuf_BufferedIO
3134 * @brief Read a line from socket
3135 * flushes and closes the FD on error
3136 * @param Line the line to read from the fd / I/O Buffer
3137 * @param buf the buffer to get the input to
3138 * @param fd pointer to the filedescriptor to read
3139 * @param timeout number of successless selects until we bail out
3140 * @param selectresolution how long to wait on each select
3141 * @param Error strerror() on error
3142 * @returns numbers of chars read
3144 int StrBufTCP_read_buffered_line(StrBuf *Line,
3148 int selectresolution,
3152 int nSuccessLess = 0;
3159 if (buf->BufUsed > 0) {
3160 pch = strchr(buf->buf, '\n');
3163 len = pch - buf->buf;
3164 if (len > 0 && (*(pch - 1) == '\r') )
3166 StrBufSub(Line, buf, 0, len - rlen);
3167 StrBufCutLeft(buf, len + 1);
3172 if (buf->BufSize - buf->BufUsed < 10)
3173 IncreaseBuf(buf, 1, -1);
3175 fdflags = fcntl(*fd, F_GETFL);
3176 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3178 while ((nSuccessLess < timeout) && (pch == NULL)) {
3180 tv.tv_sec = selectresolution;
3185 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3186 *Error = strerror(errno);
3192 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3197 &buf->buf[buf->BufUsed],
3198 buf->BufSize - buf->BufUsed - 1);
3200 *Error = strerror(errno);
3205 else if (rlen > 0) {
3207 buf->BufUsed += rlen;
3208 buf->buf[buf->BufUsed] = '\0';
3209 if (buf->BufUsed + 10 > buf->BufSize) {
3210 IncreaseBuf(buf, 1, -1);
3212 pch = strchr(buf->buf, '\n');
3219 len = pch - buf->buf;
3220 if (len > 0 && (*(pch - 1) == '\r') )
3222 StrBufSub(Line, buf, 0, len - rlen);
3223 StrBufCutLeft(buf, len + 1);
3230 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3231 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3232 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3234 * @ingroup StrBuf_BufferedIO
3235 * @brief Read a line from socket
3236 * flushes and closes the FD on error
3237 * @param Line where to append our Line read from the fd / I/O Buffer;
3238 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3239 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3240 * @param fd pointer to the filedescriptor to read
3241 * @param timeout number of successless selects until we bail out
3242 * @param selectresolution how long to wait on each select
3243 * @param Error strerror() on error
3244 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3246 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3251 int selectresolution,
3254 const char *pche = NULL;
3255 const char *pos = NULL;
3257 int len, rlen, retlen;
3258 int nSuccessLess = 0;
3260 const char *pch = NULL;
3266 if ((Line == NULL) ||
3273 *Error = ErrRBLF_PreConditionFailed;
3278 if ((IOBuf->BufUsed > 0) &&
3280 (pos < IOBuf->buf + IOBuf->BufUsed))
3284 pche = IOBuf->buf + IOBuf->BufUsed;
3288 while ((pch < pche) && (*pch != '\n'))
3290 if (Line->BufUsed + 10 > Line->BufSize)
3293 apos = pcht - Line->buf;
3295 IncreaseBuf(Line, 1, -1);
3296 pcht = Line->buf + apos;
3304 if (len > 0 && (*(pch - 1) == '\r') )
3313 if ((pch >= pche) || (*pch == '\0'))
3321 if ((pch != NULL) &&
3324 if (pch + 1 >= pche) {
3337 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3339 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3340 IncreaseBuf(IOBuf, 1, -1);
3342 fdflags = fcntl(*fd, F_GETFL);
3343 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3346 while ((nSuccessLess < timeout) &&
3356 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3357 *Error = strerror(errno);
3361 *Error = ErrRBLF_SelectFailed;
3364 if (! FD_ISSET(*fd, &rfds) != 0) {
3370 &IOBuf->buf[IOBuf->BufUsed],
3371 IOBuf->BufSize - IOBuf->BufUsed - 1);
3373 *Error = strerror(errno);
3378 else if (rlen > 0) {
3380 pLF = IOBuf->buf + IOBuf->BufUsed;
3381 IOBuf->BufUsed += rlen;
3382 IOBuf->buf[IOBuf->BufUsed] = '\0';
3384 pche = IOBuf->buf + IOBuf->BufUsed;
3386 while ((pLF < pche) && (*pLF != '\n'))
3388 if ((pLF >= pche) || (*pLF == '\0'))
3391 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3395 if (pLF != NULL) apos = pLF - IOBuf->buf;
3396 IncreaseBuf(IOBuf, 1, -1);
3397 if (pLF != NULL) pLF = IOBuf->buf + apos;
3407 if (len > 0 && (*(pLF - 1) == '\r') )
3409 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3410 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3416 return retlen + len;
3418 *Error = ErrRBLF_NotEnoughSentFromServer;
3423 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3425 * @ingroup StrBuf_IO
3426 * @brief Input binary data from socket
3427 * flushes and closes the FD on error
3428 * @param Buf the buffer to get the input to
3429 * @param fd pointer to the filedescriptor to read
3430 * @param append Append to an existing string or replace?
3431 * @param nBytes the maximal number of bytes to read
3432 * @param Error strerror() on error
3433 * @returns numbers of chars read
3435 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3438 int len, rlen, slen;
3446 if ((Buf == NULL) || (*fd == -1))
3448 *Error = ErrRBLF_BLOBPreConditionFailed;
3453 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3454 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3456 ptr = Buf->buf + Buf->BufUsed;
3458 slen = len = Buf->BufUsed;
3460 fdflags = fcntl(*fd, F_GETFL);
3461 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3463 while ((nRead < nBytes) &&
3473 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3474 *Error = strerror(errno);
3478 *Error = ErrRBLF_SelectFailed;
3481 if (! FD_ISSET(*fd, &rfds) != 0) {
3487 if ((rlen = read(*fd,
3489 nBytes - nRead)) == -1) {
3492 *Error = strerror(errno);
3497 Buf->BufUsed += rlen;
3499 Buf->buf[Buf->BufUsed] = '\0';
3503 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3504 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3506 * @ingroup StrBuf_BufferedIO
3507 * @brief Input binary data from socket
3508 * flushes and closes the FD on error
3509 * @param Blob put binary thing here
3510 * @param IOBuf the buffer to get the input to
3511 * @param Pos offset inside of IOBuf
3512 * @param fd pointer to the filedescriptor to read
3513 * @param append Append to an existing string or replace?
3514 * @param nBytes the maximal number of bytes to read
3515 * @param check whether we should search for '000\n' terminators in case of timeouts
3516 * @param Error strerror() on error
3517 * @returns numbers of chars read
3519 int StrBufReadBLOBBuffered(StrBuf *Blob,
3536 int nAlreadyRead = 0;
3544 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3548 *Error = ErrRBB_BLOBFPreConditionFailed;
3554 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3555 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3560 len = pos - IOBuf->buf;
3561 rlen = IOBuf->BufUsed - len;
3564 if ((IOBuf->BufUsed > 0) &&
3566 (pos < IOBuf->buf + IOBuf->BufUsed))
3568 pche = IOBuf->buf + IOBuf->BufUsed;
3571 if (rlen < nBytes) {
3572 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3573 Blob->BufUsed += rlen;
3574 Blob->buf[Blob->BufUsed] = '\0';
3575 nAlreadyRead = nRead = rlen;
3578 if (rlen >= nBytes) {
3579 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3580 Blob->BufUsed += nBytes;
3581 Blob->buf[Blob->BufUsed] = '\0';
3582 if (rlen == nBytes) {
3594 if (IOBuf->BufSize < nBytes - nRead)
3595 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3598 slen = len = Blob->BufUsed;
3600 fdflags = fcntl(*fd, F_GETFL);
3601 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3606 while ((nRead < nBytes) &&
3615 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3616 *Error = strerror(errno);
3620 *Error = ErrRBLF_SelectFailed;
3623 if (! FD_ISSET(*fd, &rfds) != 0) {
3635 *Error = strerror(errno);
3638 else if (rlen == 0){
3640 if ((check == NNN_TERM) &&
3642 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3644 StrBufPlain(Blob, HKEY("\n000\n"));
3645 StrBufCutRight(Blob, 5);
3646 return Blob->BufUsed;
3648 if (nSelects > 10) {
3650 *Error = ErrRBB_too_many_selects;
3654 else if (rlen > 0) {
3657 IOBuf->BufUsed += rlen;
3660 if (nRead > nBytes) {
3661 *Pos = IOBuf->buf + nBytes;
3663 Blob->buf[Blob->BufUsed] = '\0';
3664 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3668 return nRead + nAlreadyRead;
3672 * @ingroup StrBuf_IO
3673 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3674 * @param LineBuf your line will be copied here.
3675 * @param Buf BLOB with lines of text...
3676 * @param Ptr moved arround to keep the next-line across several iterations
3677 * has to be &NULL on start; will be &NotNULL on end of buffer
3678 * @returns size of copied buffer
3680 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3682 const char *aptr, *ptr, *eptr;
3685 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3686 *Ptr = StrBufNOTNULL;
3690 FlushStrBuf(LineBuf);
3692 ptr = aptr = Buf->buf;
3696 optr = LineBuf->buf;
3697 eptr = Buf->buf + Buf->BufUsed;
3698 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3700 while ((ptr <= eptr) &&
3707 LineBuf->BufUsed = optr - LineBuf->buf;
3708 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3709 optr = LineBuf->buf + LineBuf->BufUsed;
3710 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3714 if ((ptr >= eptr) && (optr > LineBuf->buf))
3716 LineBuf->BufUsed = optr - LineBuf->buf;
3718 if ((ptr <= eptr) && (*ptr == '\r'))
3720 if ((ptr <= eptr) && (*ptr == '\n'))
3727 *Ptr = StrBufNOTNULL;
3730 return Buf->BufUsed - (ptr - Buf->buf);
3735 * @ingroup StrBuf_IO
3736 * @brief removes double slashes from pathnames
3737 * @param Dir directory string to filter
3738 * @param RemoveTrailingSlash allows / disallows trailing slashes
3740 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3746 while (!IsEmptyStr(a)) {
3758 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3763 Dir->BufUsed = b - Dir->buf;