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 * @brief modifies a Single char of the Buf
624 * You can point to it via char* or a zero-based integer
625 * @param Buf The buffer to manipulate
626 * @param ptr char* to zero; use NULL if unused
627 * @param nThChar zero based pointer into the string; use -1 if unused
628 * @param PeekValue The Character to place into the position
630 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
635 nThChar = ptr - Buf->buf;
636 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
638 Buf->buf[nThChar] = PeekValue;
644 * @brief Append a StringBuffer to the buffer
645 * @param Buf Buffer to modify
646 * @param AppendBuf Buffer to copy at the end of our buffer
647 * @param Offset Should we start copying from an offset?
649 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
651 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
654 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
657 AppendBuf->BufUsed + Buf->BufUsed);
659 memcpy(Buf->buf + Buf->BufUsed,
660 AppendBuf->buf + Offset,
661 AppendBuf->BufUsed - Offset);
662 Buf->BufUsed += AppendBuf->BufUsed - Offset;
663 Buf->buf[Buf->BufUsed] = '\0';
669 * @brief Append a C-String to the buffer
670 * @param Buf Buffer to modify
671 * @param AppendBuf Buffer to copy at the end of our buffer
672 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
673 * @param Offset Should we start copying from an offset?
675 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
678 long BufSizeRequired;
680 if ((AppendBuf == NULL) || (Buf == NULL))
684 aps = strlen(AppendBuf + Offset);
686 aps = AppendSize - Offset;
688 BufSizeRequired = Buf->BufUsed + aps + 1;
689 if (Buf->BufSize <= BufSizeRequired)
690 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
692 memcpy(Buf->buf + Buf->BufUsed,
696 Buf->buf[Buf->BufUsed] = '\0';
701 * @brief sprintf like function appending the formated string to the buffer
702 * vsnprintf version to wrap into own calls
703 * @param Buf Buffer to extend by format and Params
704 * @param format printf alike format to add
705 * @param ap va_list containing the items for format
707 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
715 if ((Buf == NULL) || (format == NULL))
718 BufSize = Buf->BufSize;
719 nWritten = Buf->BufSize + 1;
720 Offset = Buf->BufUsed;
721 newused = Offset + nWritten;
723 while (newused >= BufSize) {
725 nWritten = vsnprintf(Buf->buf + Offset,
726 Buf->BufSize - Offset,
729 newused = Offset + nWritten;
730 if (newused >= Buf->BufSize) {
731 IncreaseBuf(Buf, 1, newused);
732 newused = Buf->BufSize + 1;
735 Buf->BufUsed = Offset + nWritten;
736 BufSize = Buf->BufSize;
744 * @brief sprintf like function appending the formated string to the buffer
745 * @param Buf Buffer to extend by format and Params
746 * @param format printf alike format to add
748 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
756 if ((Buf == NULL) || (format == NULL))
759 BufSize = Buf->BufSize;
760 nWritten = Buf->BufSize + 1;
761 Offset = Buf->BufUsed;
762 newused = Offset + nWritten;
764 while (newused >= BufSize) {
765 va_start(arg_ptr, format);
766 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
767 Buf->BufSize - Buf->BufUsed,
770 newused = Buf->BufUsed + nWritten;
771 if (newused >= Buf->BufSize) {
772 IncreaseBuf(Buf, 1, newused);
773 newused = Buf->BufSize + 1;
776 Buf->BufUsed += nWritten;
777 BufSize = Buf->BufSize;
785 * @brief sprintf like function putting the formated string into the buffer
786 * @param Buf Buffer to extend by format and Parameters
787 * @param format printf alike format to add
789 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
794 if ((Buf == NULL) || (format == NULL))
797 nWritten = Buf->BufSize + 1;
798 while (nWritten >= Buf->BufSize) {
799 va_start(arg_ptr, format);
800 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
802 if (nWritten >= Buf->BufSize) {
803 IncreaseBuf(Buf, 0, 0);
804 nWritten = Buf->BufSize + 1;
807 Buf->BufUsed = nWritten ;
813 * @brief Callback for cURL to append the webserver reply to a buffer
814 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
815 * @param size pre-defined by the cURL API; see man 3 curl for mre info
816 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
817 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
819 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
828 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
835 * @brief extracts a substring from Source into dest
836 * @param dest buffer to place substring into
837 * @param Source string to copy substring from
838 * @param Offset chars to skip from start
839 * @param nChars number of chars to copy
840 * @returns the number of chars copied; may be different from nChars due to the size of Source
842 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
845 if (Offset > Source->BufUsed)
850 if (Offset + nChars < Source->BufUsed)
852 if (nChars >= dest->BufSize)
853 IncreaseBuf(dest, 0, nChars + 1);
854 memcpy(dest->buf, Source->buf + Offset, nChars);
855 dest->BufUsed = nChars;
856 dest->buf[dest->BufUsed] = '\0';
859 NCharsRemain = Source->BufUsed - Offset;
860 if (NCharsRemain >= dest->BufSize)
861 IncreaseBuf(dest, 0, NCharsRemain + 1);
862 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
863 dest->BufUsed = NCharsRemain;
864 dest->buf[dest->BufUsed] = '\0';
870 * @brief Cut nChars from the start of the string
871 * @param Buf Buffer to modify
872 * @param nChars how many chars should be skipped?
874 void StrBufCutLeft(StrBuf *Buf, int nChars)
876 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
877 if (nChars >= Buf->BufUsed) {
881 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
882 Buf->BufUsed -= nChars;
883 Buf->buf[Buf->BufUsed] = '\0';
888 * @brief Cut the trailing n Chars from the string
889 * @param Buf Buffer to modify
890 * @param nChars how many chars should be trunkated?
892 void StrBufCutRight(StrBuf *Buf, int nChars)
894 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
895 if (nChars >= Buf->BufUsed) {
899 Buf->BufUsed -= nChars;
900 Buf->buf[Buf->BufUsed] = '\0';
905 * @brief Cut the string after n Chars
906 * @param Buf Buffer to modify
907 * @param AfternChars after how many chars should we trunkate the string?
908 * @param At if non-null and points inside of our string, cut it there.
910 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
912 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
914 AfternChars = At - Buf->buf;
917 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
919 Buf->BufUsed = AfternChars;
920 Buf->buf[Buf->BufUsed] = '\0';
926 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
927 * @param Buf the string to modify
929 void StrBufTrim(StrBuf *Buf)
932 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
934 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
937 if (delta > 0) StrBufCutLeft(Buf, delta);
939 if (Buf->BufUsed == 0) return;
940 while (isspace(Buf->buf[Buf->BufUsed - 1])){
943 Buf->buf[Buf->BufUsed] = '\0';
948 * @brief uppercase the contents of a buffer
949 * @param Buf the buffer to translate
951 void StrBufUpCase(StrBuf *Buf)
955 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
958 pche = pch + Buf->BufUsed;
960 *pch = toupper(*pch);
968 * @brief lowercase the contents of a buffer
969 * @param Buf the buffer to translate
971 void StrBufLowerCase(StrBuf *Buf)
975 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
978 pche = pch + Buf->BufUsed;
980 *pch = tolower(*pch);
986 /*******************************************************************************
987 * a tokenizer that kills, maims, and destroys *
988 *******************************************************************************/
991 * @ingroup StrBuf_Tokenizer
992 * @brief Counts the numbmer of tokens in a buffer
993 * @param source String to count tokens in
994 * @param tok Tokenizer char to count
995 * @returns numbers of tokenizer chars found
997 int StrBufNum_tokens(const StrBuf *source, char tok)
1001 if ((source == NULL) || (source->BufUsed == 0))
1003 if ((source->BufUsed == 1) && (*source->buf == tok))
1007 pche = pch + source->BufUsed;
1018 * @ingroup StrBuf_Tokenizer
1019 * @brief a string tokenizer
1020 * @param Source StringBuffer to read into
1021 * @param parmnum n'th Parameter to remove
1022 * @param separator tokenizer character
1023 * @returns -1 if not found, else length of token.
1025 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1028 char *d, *s, *end; /* dest, source */
1031 /* Find desired @parameter */
1032 end = Source->buf + Source->BufUsed;
1034 while ((d <= end) &&
1037 /* End of string, bail! */
1042 if (*d == separator) {
1047 if ((d == NULL) || (d >= end))
1048 return 0; /* @Parameter not found */
1050 /* Find next @parameter */
1052 while ((s <= end) &&
1053 (*s && *s != separator))
1057 if (*s == separator)
1061 /* Hack and slash */
1066 memmove(d, s, Source->BufUsed - (s - Source->buf));
1067 Source->BufUsed += ReducedBy;
1068 Source->buf[Source->BufUsed] = '\0';
1070 else if (d == Source->buf) {
1072 Source->BufUsed = 0;
1076 Source->BufUsed += ReducedBy;
1089 * @ingroup StrBuf_Tokenizer
1090 * @brief a string tokenizer
1091 * @param dest Destination StringBuffer
1092 * @param Source StringBuffer to read into
1093 * @param parmnum n'th Parameter to extract
1094 * @param separator tokenizer character
1095 * @returns -1 if not found, else length of token.
1097 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1099 const char *s, *e; //* source * /
1100 int len = 0; //* running total length of extracted string * /
1101 int current_token = 0; //* token currently being processed * /
1104 dest->buf[0] = '\0';
1110 if ((Source == NULL) || (Source->BufUsed ==0)) {
1114 e = s + Source->BufUsed;
1117 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1119 while ((s<e) && !IsEmptyStr(s)) {
1120 if (*s == separator) {
1123 if (len >= dest->BufSize) {
1124 dest->BufUsed = len;
1125 if (IncreaseBuf(dest, 1, -1) < 0) {
1130 if ( (current_token == parmnum) &&
1131 (*s != separator)) {
1132 dest->buf[len] = *s;
1135 else if (current_token > parmnum) {
1141 dest->buf[len] = '\0';
1142 dest->BufUsed = len;
1144 if (current_token < parmnum) {
1145 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1148 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1157 * @ingroup StrBuf_Tokenizer
1158 * @brief a string tokenizer to fetch an integer
1159 * @param Source String containing tokens
1160 * @param parmnum n'th Parameter to extract
1161 * @param separator tokenizer character
1162 * @returns 0 if not found, else integer representation of the token
1164 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1174 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1181 * @ingroup StrBuf_Tokenizer
1182 * @brief a string tokenizer to fetch a long integer
1183 * @param Source String containing tokens
1184 * @param parmnum n'th Parameter to extract
1185 * @param separator tokenizer character
1186 * @returns 0 if not found, else long integer representation of the token
1188 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1198 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1206 * @ingroup StrBuf_Tokenizer
1207 * @brief a string tokenizer to fetch an unsigned long
1208 * @param Source String containing tokens
1209 * @param parmnum n'th Parameter to extract
1210 * @param separator tokenizer character
1211 * @returns 0 if not found, else unsigned long representation of the token
1213 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1224 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1228 return (unsigned long) atol(pnum);
1237 * @ingroup StrBuf_NextTokenizer
1238 * @brief a string tokenizer; Bounds checker
1239 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1240 * @param Source our tokenbuffer
1241 * @param pStart the token iterator pointer to inspect
1242 * @returns whether the revolving pointer is inside of the search range
1244 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1246 if ((Source == NULL) ||
1247 (*pStart == StrBufNOTNULL) ||
1248 (Source->BufUsed == 0))
1252 if (*pStart == NULL)
1256 else if (*pStart > Source->buf + Source->BufUsed)
1260 else if (*pStart <= Source->buf)
1269 * @ingroup StrBuf_NextTokenizer
1270 * @brief a string tokenizer
1271 * @param dest Destination StringBuffer
1272 * @param Source StringBuffer to read into
1273 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1274 * @param separator tokenizer
1275 * @returns -1 if not found, else length of token.
1277 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1279 const char *s; /* source */
1280 const char *EndBuffer; /* end stop of source buffer */
1281 int current_token = 0; /* token currently being processed */
1282 int len = 0; /* running total length of extracted string */
1284 if ((Source == NULL) ||
1285 (Source->BufUsed == 0) )
1287 *pStart = StrBufNOTNULL;
1291 EndBuffer = Source->buf + Source->BufUsed;
1295 dest->buf[0] = '\0';
1300 *pStart = EndBuffer + 1;
1304 if (*pStart == NULL)
1306 *pStart = Source->buf; /* we're starting to examine this buffer. */
1308 else if ((*pStart < Source->buf) ||
1309 (*pStart > EndBuffer ) )
1311 return -1; /* no more tokens to find. */
1315 /* start to find the next token */
1316 while ((s <= EndBuffer) &&
1317 (current_token == 0) )
1319 if (*s == separator)
1321 /* we found the next token */
1325 if (len >= dest->BufSize)
1327 /* our Dest-buffer isn't big enough, increase it. */
1328 dest->BufUsed = len;
1330 if (IncreaseBuf(dest, 1, -1) < 0) {
1331 /* WHUT? no more mem? bail out. */
1338 if ( (current_token == 0 ) && /* are we in our target token? */
1339 (!IsEmptyStr(s) ) &&
1340 (separator != *s) ) /* don't copy the token itself */
1342 dest->buf[len] = *s; /* Copy the payload */
1343 ++len; /* remember the bigger size. */
1349 /* did we reach the end? */
1350 if ((s > EndBuffer)) {
1351 EndBuffer = StrBufNOTNULL;
1352 *pStart = EndBuffer;
1355 *pStart = s; /* remember the position for the next run */
1358 /* sanitize our extracted token */
1359 dest->buf[len] = '\0';
1360 dest->BufUsed = len;
1367 * @ingroup StrBuf_NextTokenizer
1368 * @brief a string tokenizer
1369 * @param Source StringBuffer to read from
1370 * @param pStart pointer to the end of the last token. Feed with NULL.
1371 * @param separator tokenizer character
1372 * @param nTokens number of tokens to fastforward over
1373 * @returns -1 if not found, else length of token.
1375 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1377 const char *s, *EndBuffer; //* source * /
1378 int len = 0; //* running total length of extracted string * /
1379 int current_token = 0; //* token currently being processed * /
1381 if ((Source == NULL) ||
1382 (Source->BufUsed ==0)) {
1386 return Source->BufUsed;
1388 if (*pStart == NULL)
1389 *pStart = Source->buf;
1391 EndBuffer = Source->buf + Source->BufUsed;
1393 if ((*pStart < Source->buf) ||
1394 (*pStart > EndBuffer)) {
1402 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1404 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1405 if (*s == separator) {
1408 if (current_token >= nTokens) {
1420 * @ingroup StrBuf_NextTokenizer
1421 * @brief a string tokenizer to fetch an integer
1422 * @param Source StringBuffer to read from
1423 * @param pStart Cursor on the tokenstring
1424 * @param separator tokenizer character
1425 * @returns 0 if not found, else integer representation of the token
1427 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1437 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1444 * @ingroup StrBuf_NextTokenizer
1445 * @brief a string tokenizer to fetch a long integer
1446 * @param Source StringBuffer to read from
1447 * @param pStart Cursor on the tokenstring
1448 * @param separator tokenizer character
1449 * @returns 0 if not found, else long integer representation of the token
1451 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1461 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1469 * @ingroup StrBuf_NextTokenizer
1470 * @brief a string tokenizer to fetch an unsigned long
1471 * @param Source StringBuffer to read from
1472 * @param pStart Cursor on the tokenstring
1473 * @param separator tokenizer character
1474 * @returns 0 if not found, else unsigned long representation of the token
1476 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1487 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1491 return (unsigned long) atol(pnum);
1501 /*******************************************************************************
1502 * Escape Appending *
1503 *******************************************************************************/
1506 * @ingroup StrBuf_DeEnCoder
1507 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1508 * @param OutBuf the output buffer
1509 * @param In Buffer to encode
1510 * @param PlainIn way in from plain old c strings
1512 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1514 const char *pch, *pche;
1518 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1520 if (PlainIn != NULL) {
1521 len = strlen(PlainIn);
1527 pche = pch + In->BufUsed;
1534 pt = OutBuf->buf + OutBuf->BufUsed;
1535 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1537 while (pch < pche) {
1539 IncreaseBuf(OutBuf, 1, -1);
1540 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1541 pt = OutBuf->buf + OutBuf->BufUsed;
1544 if((*pch >= 'a' && *pch <= 'z') ||
1545 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1546 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1547 (*pch == '!') || (*pch == '_') ||
1548 (*pch == ',') || (*pch == '.') ||
1556 *(pt + 1) = HexList[(unsigned char)*pch][0];
1557 *(pt + 2) = HexList[(unsigned char)*pch][1];
1559 OutBuf->BufUsed += 3;
1567 * @ingroup StrBuf_DeEnCoder
1568 * @brief append a string in hex encoding to the buffer
1569 * @param OutBuf the output buffer
1570 * @param In Buffer to encode
1571 * @param PlainIn way in from plain old c strings
1573 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1575 const char *pch, *pche;
1579 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1581 if (PlainIn != NULL) {
1582 len = strlen(PlainIn);
1588 pche = pch + In->BufUsed;
1595 pt = OutBuf->buf + OutBuf->BufUsed;
1596 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1598 while (pch < pche) {
1600 IncreaseBuf(OutBuf, 1, -1);
1601 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1602 pt = OutBuf->buf + OutBuf->BufUsed;
1605 *pt = HexList[(unsigned char)*pch][0];
1607 *pt = HexList[(unsigned char)*pch][1];
1608 pt ++; pch ++; OutBuf->BufUsed += 2;
1614 * @ingroup StrBuf_DeEnCoder
1615 * @brief Append a string, escaping characters which have meaning in HTML.
1617 * @param Target target buffer
1618 * @param Source source buffer; set to NULL if you just have a C-String
1619 * @param PlainIn Plain-C string to append; set to NULL if unused
1620 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1621 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1622 * if set to 2, linebreaks are replaced by <br/>
1624 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1626 const char *aptr, *eiptr;
1630 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1633 if (PlainIn != NULL) {
1635 len = strlen(PlainIn);
1640 eiptr = aptr + Source->BufUsed;
1641 len = Source->BufUsed;
1647 bptr = Target->buf + Target->BufUsed;
1648 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1650 while (aptr < eiptr){
1652 IncreaseBuf(Target, 1, -1);
1653 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1654 bptr = Target->buf + Target->BufUsed;
1657 memcpy(bptr, "<", 4);
1659 Target->BufUsed += 4;
1661 else if (*aptr == '>') {
1662 memcpy(bptr, ">", 4);
1664 Target->BufUsed += 4;
1666 else if (*aptr == '&') {
1667 memcpy(bptr, "&", 5);
1669 Target->BufUsed += 5;
1671 else if (*aptr == '"') {
1672 memcpy(bptr, """, 6);
1674 Target->BufUsed += 6;
1676 else if (*aptr == '\'') {
1677 memcpy(bptr, "'", 5);
1679 Target->BufUsed += 5;
1681 else if (*aptr == LB) {
1686 else if (*aptr == RB) {
1691 else if (*aptr == QU) {
1696 else if ((*aptr == 32) && (nbsp == 1)) {
1697 memcpy(bptr, " ", 6);
1699 Target->BufUsed += 6;
1701 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1702 *bptr='\0'; /* nothing */
1704 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1705 memcpy(bptr, "<br/>", 11);
1707 Target->BufUsed += 11;
1711 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1712 *bptr='\0'; /* nothing */
1722 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1724 return Target->BufUsed;
1728 * @ingroup StrBuf_DeEnCoder
1729 * @brief Append a string, escaping characters which have meaning in HTML.
1730 * Converts linebreaks into blanks; escapes single quotes
1731 * @param Target target buffer
1732 * @param Source source buffer; set to NULL if you just have a C-String
1733 * @param PlainIn Plain-C string to append; set to NULL if unused
1735 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1737 const char *aptr, *eiptr;
1741 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1744 if (PlainIn != NULL) {
1746 len = strlen(PlainIn);
1751 eiptr = aptr + Source->BufUsed;
1752 len = Source->BufUsed;
1758 eptr = Target->buf + Target->BufSize - 8;
1759 tptr = Target->buf + Target->BufUsed;
1761 while (aptr < eiptr){
1763 IncreaseBuf(Target, 1, -1);
1764 eptr = Target->buf + Target->BufSize - 8;
1765 tptr = Target->buf + Target->BufUsed;
1768 if (*aptr == '\n') {
1772 else if (*aptr == '\r') {
1776 else if (*aptr == '\'') {
1782 Target->BufUsed += 5;
1795 * @ingroup StrBuf_DeEnCoder
1796 * @brief Append a string, escaping characters which have meaning in ICAL.
1798 * @param Target target buffer
1799 * @param Source source buffer; set to NULL if you just have a C-String
1800 * @param PlainIn Plain-C string to append; set to NULL if unused
1802 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1804 const char *aptr, *eiptr;
1808 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1811 if (PlainIn != NULL) {
1813 len = strlen(PlainIn);
1818 eiptr = aptr + Source->BufUsed;
1819 len = Source->BufUsed;
1825 eptr = Target->buf + Target->BufSize - 8;
1826 tptr = Target->buf + Target->BufUsed;
1828 while (aptr < eiptr){
1829 if(tptr + 3 >= eptr) {
1830 IncreaseBuf(Target, 1, -1);
1831 eptr = Target->buf + Target->BufSize - 8;
1832 tptr = Target->buf + Target->BufUsed;
1835 if (*aptr == '\n') {
1842 else if (*aptr == '\r') {
1849 else if (*aptr == ',') {
1865 * @ingroup StrBuf_DeEnCoder
1866 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1868 * @param Target target buffer
1869 * @param Source source buffer; set to NULL if you just have a C-String
1870 * @param PlainIn Plain-C string to append; set to NULL if unused
1871 * @returns size of result or -1
1873 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1875 const char *aptr, *eiptr;
1879 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1882 if (PlainIn != NULL) {
1884 len = strlen(PlainIn);
1889 eiptr = aptr + Source->BufUsed;
1890 len = Source->BufUsed;
1896 bptr = Target->buf + Target->BufUsed;
1897 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1899 while (aptr < eiptr){
1901 IncreaseBuf(Target, 1, -1);
1902 eptr = Target->buf + Target->BufSize - 3;
1903 bptr = Target->buf + Target->BufUsed;
1910 Target->BufUsed += 2;
1911 } else if (*aptr == '\\') {
1916 Target->BufUsed += 2;
1926 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1928 return Target->BufUsed;
1932 * @ingroup StrBuf_DeEnCoder
1933 * @brief Append a string, escaping characters which have meaning in HTML + json.
1935 * @param Target target buffer
1936 * @param Source source buffer; set to NULL if you just have a C-String
1937 * @param PlainIn Plain-C string to append; set to NULL if unused
1938 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1939 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1940 * if set to 2, linebreaks are replaced by <br/>
1942 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1944 const char *aptr, *eiptr;
1947 int IsUtf8Sequence = 0;
1949 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1952 if (PlainIn != NULL) {
1954 len = strlen(PlainIn);
1959 eiptr = aptr + Source->BufUsed;
1960 len = Source->BufUsed;
1966 bptr = Target->buf + Target->BufUsed;
1967 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1969 while (aptr < eiptr){
1971 IncreaseBuf(Target, 1, -1);
1972 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1973 bptr = Target->buf + Target->BufUsed;
1976 memcpy(bptr, "<", 4);
1978 Target->BufUsed += 4;
1980 else if (*aptr == '>') {
1981 memcpy(bptr, ">", 4);
1983 Target->BufUsed += 4;
1985 else if (*aptr == '&') {
1986 memcpy(bptr, "&", 5);
1988 Target->BufUsed += 5;
1990 else if (*aptr == LB) {
1995 else if (*aptr == RB) {
2000 else if ((*aptr == 32) && (nbsp == 1)) {
2001 memcpy(bptr, " ", 6);
2003 Target->BufUsed += 6;
2005 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2006 *bptr='\0'; /* nothing */
2008 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2009 memcpy(bptr, "<br/>", 11);
2011 Target->BufUsed += 11;
2014 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2015 *bptr='\0'; /* nothing */
2018 else if ((*aptr == '"') || (*aptr == QU)) {
2023 Target->BufUsed += 2;
2024 } else if (*aptr == '\\') {
2029 Target->BufUsed += 2;
2032 if (((unsigned char)*aptr) >= 0x20)
2034 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2038 while (IsUtf8Sequence > 1){
2039 if(bptr + IsUtf8Sequence >= eptr) {
2040 IncreaseBuf(Target, 1, -1);
2041 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2042 bptr = Target->buf + Target->BufUsed - 1;
2056 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2058 return Target->BufUsed;
2062 * @ingroup StrBuf_DeEnCoder
2063 * @brief unhide special chars hidden to the HTML escaper
2064 * @param target buffer to put the unescaped string in
2065 * @param source buffer to unescape
2067 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2073 FlushStrBuf(target);
2075 if (source == NULL ||target == NULL)
2080 len = source->BufUsed;
2081 for (a = 0; a < len; ++a) {
2082 if (target->BufUsed >= target->BufSize)
2083 IncreaseBuf(target, 1, -1);
2085 if (source->buf[a] == '=') {
2086 hex[0] = source->buf[a + 1];
2087 hex[1] = source->buf[a + 2];
2090 sscanf(hex, "%02x", &b);
2091 target->buf[target->BufUsed] = b;
2092 target->buf[++target->BufUsed] = 0;
2096 target->buf[target->BufUsed] = source->buf[a];
2097 target->buf[++target->BufUsed] = 0;
2104 * @ingroup StrBuf_DeEnCoder
2105 * @brief hide special chars from the HTML escapers and friends
2106 * @param target buffer to put the escaped string in
2107 * @param source buffer to escape
2109 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2114 FlushStrBuf(target);
2116 if (source == NULL ||target == NULL)
2121 len = source->BufUsed;
2122 for (i=0; i<len; ++i) {
2123 if (target->BufUsed + 4 >= target->BufSize)
2124 IncreaseBuf(target, 1, -1);
2125 if ( (isalnum(source->buf[i])) ||
2126 (source->buf[i]=='-') ||
2127 (source->buf[i]=='_') ) {
2128 target->buf[target->BufUsed++] = source->buf[i];
2131 sprintf(&target->buf[target->BufUsed],
2133 (0xFF &source->buf[i]));
2134 target->BufUsed += 3;
2137 target->buf[target->BufUsed + 1] = '\0';
2141 /*******************************************************************************
2142 * Quoted Printable de/encoding *
2143 *******************************************************************************/
2146 * @ingroup StrBuf_DeEnCoder
2147 * @brief decode a buffer from base 64 encoding; destroys original
2148 * @param Buf Buffor to transform
2150 int StrBufDecodeBase64(StrBuf *Buf)
2154 if (Buf == NULL) return -1;
2156 xferbuf = (char*) malloc(Buf->BufSize);
2157 siz = CtdlDecodeBase64(xferbuf,
2167 * @ingroup StrBuf_DeEnCoder
2168 * @brief decode a buffer from base 64 encoding; destroys original
2169 * @param Buf Buffor to transform
2171 int StrBufDecodeHex(StrBuf *Buf)
2174 char *pch, *pche, *pchi;
2176 if (Buf == NULL) return -1;
2178 pch = pchi = Buf->buf;
2179 pche = pch + Buf->BufUsed;
2181 while (pchi < pche){
2182 ch = decode_hex(pchi);
2189 Buf->BufUsed = pch - Buf->buf;
2190 return Buf->BufUsed;
2194 * @ingroup StrBuf_DeEnCoder
2195 * @brief replace all chars >0x20 && < 0x7F with Mute
2196 * @param Mute char to put over invalid chars
2197 * @param Buf Buffor to transform
2199 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2203 if (Buf == NULL) return -1;
2204 pch = (unsigned char *)Buf->buf;
2205 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2206 if ((*pch < 0x20) || (*pch > 0x7F))
2210 return Buf->BufUsed;
2215 * @ingroup StrBuf_DeEnCoder
2216 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2217 * @param Buf Buffer to translate
2218 * @param StripBlanks Reduce several blanks to one?
2220 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2229 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2230 Buf->buf[Buf->BufUsed - 1] = '\0';
2235 while (a < Buf->BufUsed) {
2236 if (Buf->buf[a] == '+')
2238 else if (Buf->buf[a] == '%') {
2239 /* don't let % chars through, rather truncate the input. */
2240 if (a + 2 > Buf->BufUsed) {
2245 hex[0] = Buf->buf[a + 1];
2246 hex[1] = Buf->buf[a + 2];
2249 sscanf(hex, "%02x", &b);
2250 Buf->buf[a] = (char) b;
2251 len = Buf->BufUsed - a - 2;
2253 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2265 * @ingroup StrBuf_DeEnCoder
2266 * @brief RFC2047-encode a header field if necessary.
2267 * If no non-ASCII characters are found, the string
2268 * will be copied verbatim without encoding.
2270 * @param target Target buffer.
2271 * @param source Source string to be encoded.
2272 * @returns encoded length; -1 if non success.
2274 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2276 const char headerStr[] = "=?UTF-8?Q?";
2277 int need_to_encode = 0;
2281 if ((source == NULL) ||
2285 while ((i < source->BufUsed) &&
2286 (!IsEmptyStr (&source->buf[i])) &&
2287 (need_to_encode == 0)) {
2288 if (((unsigned char) source->buf[i] < 32) ||
2289 ((unsigned char) source->buf[i] > 126)) {
2295 if (!need_to_encode) {
2296 if (*target == NULL) {
2297 *target = NewStrBufPlain(source->buf, source->BufUsed);
2300 FlushStrBuf(*target);
2301 StrBufAppendBuf(*target, source, 0);
2303 return (*target)->BufUsed;
2305 if (*target == NULL)
2306 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2307 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2308 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2309 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2310 (*target)->BufUsed = sizeof(headerStr) - 1;
2311 for (i=0; (i < source->BufUsed); ++i) {
2312 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2313 IncreaseBuf(*target, 1, 0);
2314 ch = (unsigned char) source->buf[i];
2315 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2316 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2317 (*target)->BufUsed += 3;
2320 (*target)->buf[(*target)->BufUsed] = ch;
2321 (*target)->BufUsed++;
2325 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2326 IncreaseBuf(*target, 1, 0);
2328 (*target)->buf[(*target)->BufUsed++] = '?';
2329 (*target)->buf[(*target)->BufUsed++] = '=';
2330 (*target)->buf[(*target)->BufUsed] = '\0';
2331 return (*target)->BufUsed;;
2336 * @brief replaces all occurances of 'search' by 'replace'
2337 * @param buf Buffer to modify
2338 * @param search character to search
2339 * @param replace character to replace search by
2341 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2346 for (i=0; i<buf->BufUsed; i++)
2347 if (buf->buf[i] == search)
2348 buf->buf[i] = replace;
2353 /*******************************************************************************
2354 * Iconv Wrapper; RFC822 de/encoding *
2355 *******************************************************************************/
2358 * @ingroup StrBuf_DeEnCoder
2359 * @brief Wrapper around iconv_open()
2360 * Our version adds aliases for non-standard Microsoft charsets
2361 * such as 'MS950', aliasing them to names like 'CP950'
2363 * @param tocode Target encoding
2364 * @param fromcode Source encoding
2365 * @param pic anonimized pointer to iconv struct
2367 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2370 iconv_t ic = (iconv_t)(-1) ;
2371 ic = iconv_open(tocode, fromcode);
2372 if (ic == (iconv_t)(-1) ) {
2373 char alias_fromcode[64];
2374 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2375 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2376 alias_fromcode[0] = 'C';
2377 alias_fromcode[1] = 'P';
2378 ic = iconv_open(tocode, alias_fromcode);
2381 *(iconv_t *)pic = ic;
2387 * @ingroup StrBuf_DeEnCoder
2388 * @brief find one chunk of a RFC822 encoded string
2389 * @param Buffer where to search
2390 * @param bptr where to start searching
2391 * @returns found position, NULL if none.
2393 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2396 /* Find the next ?Q? */
2397 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2400 end = strchr(bptr + 2, '?');
2405 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2406 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2407 (*(end + 2) == '?')) {
2408 /* skip on to the end of the cluster, the next ?= */
2409 end = strstr(end + 3, "?=");
2412 /* sort of half valid encoding, try to find an end. */
2413 end = strstr(bptr, "?=");
2419 * @brief swaps the contents of two StrBufs
2420 * this is to be used to have cheap switched between a work-buffer and a target buffer
2421 * @param A First one
2422 * @param B second one
2424 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2428 memcpy(&C, A, sizeof(*A));
2429 memcpy(A, B, sizeof(*B));
2430 memcpy(B, &C, sizeof(C));
2436 * @ingroup StrBuf_DeEnCoder
2437 * @brief convert one buffer according to the preselected iconv pointer PIC
2438 * @param ConvertBuf buffer we need to translate
2439 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2440 * @param pic Pointer to the iconv-session Object
2442 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2448 char *ibuf; /**< Buffer of characters to be converted */
2449 char *obuf; /**< Buffer for converted characters */
2450 size_t ibuflen; /**< Length of input buffer */
2451 size_t obuflen; /**< Length of output buffer */
2454 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2455 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2456 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2458 ic = *(iconv_t*)pic;
2459 ibuf = ConvertBuf->buf;
2460 ibuflen = ConvertBuf->BufUsed;
2462 obuflen = TmpBuf->BufSize;
2464 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2467 if (errno == E2BIG) {
2469 IncreaseBuf(TmpBuf, 0, 0);
2474 else if (errno == EILSEQ){
2475 /* hm, invalid utf8 sequence... what to do now? */
2476 /* An invalid multibyte sequence has been encountered in the input */
2478 else if (errno == EINVAL) {
2479 /* An incomplete multibyte sequence has been encountered in the input. */
2482 FlushStrBuf(TmpBuf);
2485 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2486 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2488 /* little card game: wheres the red lady? */
2489 SwapBuffers(ConvertBuf, TmpBuf);
2490 FlushStrBuf(TmpBuf);
2497 * @ingroup StrBuf_DeEnCoder
2498 * @brief catches one RFC822 encoded segment, and decodes it.
2499 * @param Target buffer to fill with result
2500 * @param DecodeMe buffer with stuff to process
2501 * @param SegmentStart points to our current segment in DecodeMe
2502 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2503 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2504 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2505 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2507 inline static void DecodeSegment(StrBuf *Target,
2508 const StrBuf *DecodeMe,
2512 StrBuf *ConvertBuf2,
2513 StrBuf *FoundCharset)
2519 iconv_t ic = (iconv_t)(-1);
2523 /* Now we handle foreign character sets properly encoded
2524 * in RFC2047 format.
2526 StaticBuf.buf = SegmentStart;
2527 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2528 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2529 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2530 if (FoundCharset != NULL) {
2531 FlushStrBuf(FoundCharset);
2532 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2534 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2535 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2537 *encoding = toupper(*encoding);
2538 if (*encoding == 'B') { /**< base64 */
2539 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2541 ConvertBuf->BufUsed);
2543 else if (*encoding == 'Q') { /**< quoted-printable */
2547 while (pos < ConvertBuf->BufUsed)
2549 if (ConvertBuf->buf[pos] == '_')
2550 ConvertBuf->buf[pos] = ' ';
2554 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2557 ConvertBuf->BufUsed);
2560 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2563 ctdl_iconv_open("UTF-8", charset, &ic);
2564 if (ic != (iconv_t)(-1) ) {
2566 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2567 StrBufAppendBuf(Target, ConvertBuf2, 0);
2572 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2578 * @ingroup StrBuf_DeEnCoder
2579 * @brief Handle subjects with RFC2047 encoding such as:
2580 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2581 * @param Target where to put the decoded string to
2582 * @param DecodeMe buffer with encoded string
2583 * @param DefaultCharset if we don't find one, which should we use?
2584 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2585 * put it here for later use where no string might be known.
2587 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2589 StrBuf *DecodedInvalidBuf = NULL;
2590 StrBuf *ConvertBuf, *ConvertBuf2;
2591 const StrBuf *DecodeMee = DecodeMe;
2592 char *start, *end, *next, *nextend, *ptr = NULL;
2594 iconv_t ic = (iconv_t)(-1) ;
2599 int illegal_non_rfc2047_encoding = 0;
2601 /* Sometimes, badly formed messages contain strings which were simply
2602 * written out directly in some foreign character set instead of
2603 * using RFC2047 encoding. This is illegal but we will attempt to
2604 * handle it anyway by converting from a user-specified default
2605 * charset to UTF-8 if we see any nonprintable characters.
2608 len = StrLength(DecodeMe);
2609 for (i=0; i<DecodeMe->BufUsed; ++i) {
2610 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2611 illegal_non_rfc2047_encoding = 1;
2616 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2617 if ((illegal_non_rfc2047_encoding) &&
2618 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2619 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2622 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2623 if (ic != (iconv_t)(-1) ) {
2624 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2625 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2626 DecodeMee = DecodedInvalidBuf;
2632 /* pre evaluate the first pair */
2633 nextend = end = NULL;
2634 len = StrLength(DecodeMee);
2635 start = strstr(DecodeMee->buf, "=?");
2636 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2638 end = FindNextEnd (DecodeMee, start);
2640 StrBufAppendBuf(Target, DecodeMee, 0);
2641 FreeStrBuf(&ConvertBuf);
2642 FreeStrBuf(&DecodedInvalidBuf);
2646 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2648 if (start != DecodeMee->buf) {
2651 nFront = start - DecodeMee->buf;
2652 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2656 * Since spammers will go to all sorts of absurd lengths to get their
2657 * messages through, there are LOTS of corrupt headers out there.
2658 * So, prevent a really badly formed RFC2047 header from throwing
2659 * this function into an infinite loop.
2661 while ((start != NULL) &&
2668 DecodeSegment(Target,
2676 next = strstr(end, "=?");
2678 if ((next != NULL) &&
2680 nextend = FindNextEnd(DecodeMee, next);
2681 if (nextend == NULL)
2684 /* did we find two partitions */
2685 if ((next != NULL) &&
2689 while ((ptr < next) &&
2695 /* did we find a gab just filled with blanks? */
2698 long gap = next - start;
2703 /* now terminate the gab at the end */
2704 delta = (next - end) - 2; ////TODO: const!
2705 ((StrBuf*)DecodeMee)->BufUsed -= delta;
2706 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
2708 /* move next to its new location. */
2713 /* our next-pair is our new first pair now. */
2719 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2720 if ((end != NULL) && (end < nextend)) {
2722 while ( (ptr < nextend) &&
2729 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2731 FreeStrBuf(&ConvertBuf);
2732 FreeStrBuf(&ConvertBuf2);
2733 FreeStrBuf(&DecodedInvalidBuf);
2736 /*******************************************************************************
2737 * Manipulating UTF-8 Strings *
2738 *******************************************************************************/
2742 * @brief evaluate the length of an utf8 special character sequence
2743 * @param Char the character to examine
2744 * @returns width of utf8 chars in bytes
2746 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2751 while ((n < 8) && ((test & *CharS) != 0)) {
2755 if ((n > 6) || ((CharE - CharS) < n))
2762 * @brief detect whether this char starts an utf-8 encoded char
2763 * @param Char character to inspect
2764 * @returns yes or no
2766 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2768 /** 11??.???? indicates an UTF8 Sequence. */
2769 return ((Char & 0xC0) != 0);
2774 * @brief measure the number of glyphs in an UTF8 string...
2775 * @param Buf string to measure
2776 * @returns the number of glyphs in Buf
2778 long StrBuf_Utf8StrLen(StrBuf *Buf)
2784 if ((Buf == NULL) || (Buf->BufUsed == 0))
2787 eptr = Buf->buf + Buf->BufUsed;
2788 while ((aptr < eptr) && (*aptr != '\0')) {
2789 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2790 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2791 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2804 * @brief cuts a string after maxlen glyphs
2805 * @param Buf string to cut to maxlen glyphs
2806 * @param maxlen how long may the string become?
2807 * @returns current length of the string
2809 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2815 eptr = Buf->buf + Buf->BufUsed;
2816 while ((aptr < eptr) && (*aptr != '\0')) {
2817 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2818 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2819 while ((*aptr++ != '\0') && (m-- > 0));
2828 Buf->BufUsed = aptr - Buf->buf;
2829 return Buf->BufUsed;
2832 return Buf->BufUsed;
2840 /*******************************************************************************
2842 *******************************************************************************/
2845 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2846 #define OS_CODE 0x03 /*< unix */
2849 * @ingroup StrBuf_DeEnCoder
2850 * @brief uses the same calling syntax as compress2(), but it
2851 * creates a stream compatible with HTTP "Content-encoding: gzip"
2852 * @param dest compressed buffer
2853 * @param destLen length of the compresed data
2854 * @param source source to encode
2855 * @param sourceLen length of source to encode
2856 * @param level compression level
2858 int ZEXPORT compress_gzip(Bytef * dest,
2860 const Bytef * source,
2864 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2866 /* write gzip header */
2867 snprintf((char *) dest, *destLen,
2868 "%c%c%c%c%c%c%c%c%c%c",
2869 gz_magic[0], gz_magic[1], Z_DEFLATED,
2870 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2873 /* normal deflate */
2876 stream.next_in = (Bytef *) source;
2877 stream.avail_in = (uInt) sourceLen;
2878 stream.next_out = dest + 10L; // after header
2879 stream.avail_out = (uInt) * destLen;
2880 if ((uLong) stream.avail_out != *destLen)
2883 stream.zalloc = (alloc_func) 0;
2884 stream.zfree = (free_func) 0;
2885 stream.opaque = (voidpf) 0;
2887 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2888 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2892 err = deflate(&stream, Z_FINISH);
2893 if (err != Z_STREAM_END) {
2894 deflateEnd(&stream);
2895 return err == Z_OK ? Z_BUF_ERROR : err;
2897 *destLen = stream.total_out + 10L;
2899 /* write CRC and Length */
2900 uLong crc = crc32(0L, source, sourceLen);
2902 for (n = 0; n < 4; ++n, ++*destLen) {
2903 dest[*destLen] = (int) (crc & 0xff);
2906 uLong len = stream.total_in;
2907 for (n = 0; n < 4; ++n, ++*destLen) {
2908 dest[*destLen] = (int) (len & 0xff);
2911 err = deflateEnd(&stream);
2918 * @ingroup StrBuf_DeEnCoder
2919 * @brief compress the buffer with gzip
2920 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2921 * @param Buf buffer whose content is to be gzipped
2923 int CompressBuffer(StrBuf *Buf)
2926 char *compressed_data = NULL;
2927 size_t compressed_len, bufsize;
2930 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2931 compressed_data = malloc(compressed_len);
2933 if (compressed_data == NULL)
2935 /* Flush some space after the used payload so valgrind shuts up... */
2936 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2937 Buf->buf[Buf->BufUsed + i++] = '\0';
2938 if (compress_gzip((Bytef *) compressed_data,
2941 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2944 Buf->buf = compressed_data;
2945 Buf->BufUsed = compressed_len;
2946 Buf->BufSize = bufsize;
2947 /* Flush some space after the used payload so valgrind shuts up... */
2949 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2950 Buf->buf[Buf->BufUsed + i++] = '\0';
2953 free(compressed_data);
2955 #endif /* HAVE_ZLIB */
2961 /*******************************************************************************
2962 * File I/O; Prefer buffered read since its faster! *
2963 *******************************************************************************/
2966 * @ingroup StrBuf_IO
2967 * @brief Read a line from socket
2968 * flushes and closes the FD on error
2969 * @param buf the buffer to get the input to
2970 * @param fd pointer to the filedescriptor to read
2971 * @param append Append to an existing string or replace?
2972 * @param Error strerror() on error
2973 * @returns numbers of chars read
2975 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
2977 int len, rlen, slen;
2982 slen = len = buf->BufUsed;
2984 rlen = read(*fd, &buf->buf[len], 1);
2986 *Error = strerror(errno);
2993 if (buf->buf[len] == '\n')
2995 if (buf->buf[len] != '\r')
2997 if (len + 2 >= buf->BufSize) {
2999 buf->buf[len+1] = '\0';
3000 IncreaseBuf(buf, 1, -1);
3004 buf->buf[len] = '\0';
3009 * @ingroup StrBuf_BufferedIO
3010 * @brief Read a line from socket
3011 * flushes and closes the FD on error
3012 * @param Line the line to read from the fd / I/O Buffer
3013 * @param buf the buffer to get the input to
3014 * @param fd pointer to the filedescriptor to read
3015 * @param timeout number of successless selects until we bail out
3016 * @param selectresolution how long to wait on each select
3017 * @param Error strerror() on error
3018 * @returns numbers of chars read
3020 int StrBufTCP_read_buffered_line(StrBuf *Line,
3024 int selectresolution,
3028 int nSuccessLess = 0;
3035 if (buf->BufUsed > 0) {
3036 pch = strchr(buf->buf, '\n');
3039 len = pch - buf->buf;
3040 if (len > 0 && (*(pch - 1) == '\r') )
3042 StrBufSub(Line, buf, 0, len - rlen);
3043 StrBufCutLeft(buf, len + 1);
3048 if (buf->BufSize - buf->BufUsed < 10)
3049 IncreaseBuf(buf, 1, -1);
3051 fdflags = fcntl(*fd, F_GETFL);
3052 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3054 while ((nSuccessLess < timeout) && (pch == NULL)) {
3056 tv.tv_sec = selectresolution;
3061 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3062 *Error = strerror(errno);
3068 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3073 &buf->buf[buf->BufUsed],
3074 buf->BufSize - buf->BufUsed - 1);
3076 *Error = strerror(errno);
3081 else if (rlen > 0) {
3083 buf->BufUsed += rlen;
3084 buf->buf[buf->BufUsed] = '\0';
3085 if (buf->BufUsed + 10 > buf->BufSize) {
3086 IncreaseBuf(buf, 1, -1);
3088 pch = strchr(buf->buf, '\n');
3095 len = pch - buf->buf;
3096 if (len > 0 && (*(pch - 1) == '\r') )
3098 StrBufSub(Line, buf, 0, len - rlen);
3099 StrBufCutLeft(buf, len + 1);
3106 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3107 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3108 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3110 * @ingroup StrBuf_BufferedIO
3111 * @brief Read a line from socket
3112 * flushes and closes the FD on error
3113 * @param Line where to append our Line read from the fd / I/O Buffer;
3114 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3115 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3116 * @param fd pointer to the filedescriptor to read
3117 * @param timeout number of successless selects until we bail out
3118 * @param selectresolution how long to wait on each select
3119 * @param Error strerror() on error
3120 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3122 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3127 int selectresolution,
3130 const char *pche = NULL;
3131 const char *pos = NULL;
3133 int len, rlen, retlen;
3134 int nSuccessLess = 0;
3136 const char *pch = NULL;
3142 if ((Line == NULL) ||
3149 *Error = ErrRBLF_PreConditionFailed;
3154 if ((IOBuf->BufUsed > 0) &&
3156 (pos < IOBuf->buf + IOBuf->BufUsed))
3160 pche = IOBuf->buf + IOBuf->BufUsed;
3164 while ((pch < pche) && (*pch != '\n'))
3166 if (Line->BufUsed + 10 > Line->BufSize)
3169 apos = pcht - Line->buf;
3171 IncreaseBuf(Line, 1, -1);
3172 pcht = Line->buf + apos;
3180 if (len > 0 && (*(pch - 1) == '\r') )
3189 if ((pch >= pche) || (*pch == '\0'))
3197 if ((pch != NULL) &&
3200 if (pch + 1 >= pche) {
3213 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3215 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3216 IncreaseBuf(IOBuf, 1, -1);
3218 fdflags = fcntl(*fd, F_GETFL);
3219 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3222 while ((nSuccessLess < timeout) &&
3232 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3233 *Error = strerror(errno);
3237 *Error = ErrRBLF_SelectFailed;
3240 if (! FD_ISSET(*fd, &rfds) != 0) {
3246 &IOBuf->buf[IOBuf->BufUsed],
3247 IOBuf->BufSize - IOBuf->BufUsed - 1);
3249 *Error = strerror(errno);
3254 else if (rlen > 0) {
3256 pLF = IOBuf->buf + IOBuf->BufUsed;
3257 IOBuf->BufUsed += rlen;
3258 IOBuf->buf[IOBuf->BufUsed] = '\0';
3260 pche = IOBuf->buf + IOBuf->BufUsed;
3262 while ((pLF < pche) && (*pLF != '\n'))
3264 if ((pLF >= pche) || (*pLF == '\0'))
3267 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3271 if (pLF != NULL) apos = pLF - IOBuf->buf;
3272 IncreaseBuf(IOBuf, 1, -1);
3273 if (pLF != NULL) pLF = IOBuf->buf + apos;
3283 if (len > 0 && (*(pLF - 1) == '\r') )
3285 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3286 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3292 return retlen + len;
3294 *Error = ErrRBLF_NotEnoughSentFromServer;
3299 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3301 * @ingroup StrBuf_IO
3302 * @brief Input binary data from socket
3303 * flushes and closes the FD on error
3304 * @param Buf the buffer to get the input to
3305 * @param fd pointer to the filedescriptor to read
3306 * @param append Append to an existing string or replace?
3307 * @param nBytes the maximal number of bytes to read
3308 * @param Error strerror() on error
3309 * @returns numbers of chars read
3311 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3314 int len, rlen, slen;
3322 if ((Buf == NULL) || (*fd == -1))
3324 *Error = ErrRBLF_BLOBPreConditionFailed;
3329 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3330 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3332 ptr = Buf->buf + Buf->BufUsed;
3334 slen = len = Buf->BufUsed;
3336 fdflags = fcntl(*fd, F_GETFL);
3337 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3339 while ((nRead < nBytes) &&
3349 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3350 *Error = strerror(errno);
3354 *Error = ErrRBLF_SelectFailed;
3357 if (! FD_ISSET(*fd, &rfds) != 0) {
3363 if ((rlen = read(*fd,
3365 nBytes - nRead)) == -1) {
3368 *Error = strerror(errno);
3373 Buf->BufUsed += rlen;
3375 Buf->buf[Buf->BufUsed] = '\0';
3379 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3380 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3382 * @ingroup StrBuf_BufferedIO
3383 * @brief Input binary data from socket
3384 * flushes and closes the FD on error
3385 * @param Blob put binary thing here
3386 * @param IOBuf the buffer to get the input to
3387 * @param Pos offset inside of IOBuf
3388 * @param fd pointer to the filedescriptor to read
3389 * @param append Append to an existing string or replace?
3390 * @param nBytes the maximal number of bytes to read
3391 * @param check whether we should search for '000\n' terminators in case of timeouts
3392 * @param Error strerror() on error
3393 * @returns numbers of chars read
3395 int StrBufReadBLOBBuffered(StrBuf *Blob,
3412 int nAlreadyRead = 0;
3420 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3424 *Error = ErrRBB_BLOBFPreConditionFailed;
3430 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3431 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3436 len = pos - IOBuf->buf;
3437 rlen = IOBuf->BufUsed - len;
3440 if ((IOBuf->BufUsed > 0) &&
3442 (pos < IOBuf->buf + IOBuf->BufUsed))
3444 pche = IOBuf->buf + IOBuf->BufUsed;
3447 if (rlen < nBytes) {
3448 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3449 Blob->BufUsed += rlen;
3450 Blob->buf[Blob->BufUsed] = '\0';
3451 nAlreadyRead = nRead = rlen;
3454 if (rlen >= nBytes) {
3455 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3456 Blob->BufUsed += nBytes;
3457 Blob->buf[Blob->BufUsed] = '\0';
3458 if (rlen == nBytes) {
3470 if (IOBuf->BufSize < nBytes - nRead)
3471 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3474 slen = len = Blob->BufUsed;
3476 fdflags = fcntl(*fd, F_GETFL);
3477 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3482 while ((nRead < nBytes) &&
3491 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3492 *Error = strerror(errno);
3496 *Error = ErrRBLF_SelectFailed;
3499 if (! FD_ISSET(*fd, &rfds) != 0) {
3511 *Error = strerror(errno);
3514 else if (rlen == 0){
3516 if ((check == NNN_TERM) &&
3518 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3520 StrBufPlain(Blob, HKEY("\n000\n"));
3521 StrBufCutRight(Blob, 5);
3522 return Blob->BufUsed;
3524 if (nSelects > 10) {
3526 *Error = ErrRBB_too_many_selects;
3530 else if (rlen > 0) {
3533 IOBuf->BufUsed += rlen;
3536 if (nRead > nBytes) {
3537 *Pos = IOBuf->buf + nBytes;
3539 Blob->buf[Blob->BufUsed] = '\0';
3540 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3544 return nRead + nAlreadyRead;
3548 * @ingroup StrBuf_IO
3549 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3550 * @param LineBuf your line will be copied here.
3551 * @param Buf BLOB with lines of text...
3552 * @param Ptr moved arround to keep the next-line across several iterations
3553 * has to be &NULL on start; will be &NotNULL on end of buffer
3554 * @returns size of copied buffer
3556 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3558 const char *aptr, *ptr, *eptr;
3561 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3562 *Ptr = StrBufNOTNULL;
3566 FlushStrBuf(LineBuf);
3568 ptr = aptr = Buf->buf;
3572 optr = LineBuf->buf;
3573 eptr = Buf->buf + Buf->BufUsed;
3574 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3576 while ((ptr <= eptr) &&
3583 LineBuf->BufUsed = optr - LineBuf->buf;
3584 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3585 optr = LineBuf->buf + LineBuf->BufUsed;
3586 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3590 if ((ptr >= eptr) && (optr > LineBuf->buf))
3592 LineBuf->BufUsed = optr - LineBuf->buf;
3594 if ((ptr <= eptr) && (*ptr == '\r'))
3596 if ((ptr <= eptr) && (*ptr == '\n'))
3603 *Ptr = StrBufNOTNULL;
3606 return Buf->BufUsed - (ptr - Buf->buf);
3611 * @ingroup StrBuf_IO
3612 * @brief removes double slashes from pathnames
3613 * @param Dir directory string to filter
3614 * @param RemoveTrailingSlash allows / disallows trailing slashes
3616 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3622 while (!IsEmptyStr(a)) {
3634 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3639 Dir->BufUsed = b - Dir->buf;