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->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)
314 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
316 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
317 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
318 Buf->BufSize = Buf->BufUsed + 1;
326 * @ingroup StrBuf_DeConstructors
327 * @brief Allocate a new buffer with default buffer size
328 * @returns the new stringbuffer
330 StrBuf* NewStrBuf(void)
334 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
335 NewBuf->buf = (char*) malloc(BaseStrBufSize);
336 NewBuf->buf[0] = '\0';
337 NewBuf->BufSize = BaseStrBufSize;
339 NewBuf->ConstBuf = 0;
347 * @ingroup StrBuf_DeConstructors
348 * @brief Copy Constructor; returns a duplicate of CopyMe
349 * @param CopyMe Buffer to faxmilate
350 * @returns the new stringbuffer
352 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
359 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
360 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
361 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
362 NewBuf->BufUsed = CopyMe->BufUsed;
363 NewBuf->BufSize = CopyMe->BufSize;
364 NewBuf->ConstBuf = 0;
372 * @ingroup StrBuf_DeConstructors
373 * @brief create a new Buffer using an existing c-string
374 * this function should also be used if you want to pre-suggest
375 * the buffer size to allocate in conjunction with ptr == NULL
376 * @param ptr the c-string to copy; may be NULL to create a blank instance
377 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
378 * @returns the new stringbuffer
380 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
383 size_t Siz = BaseStrBufSize;
386 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
388 CopySize = strlen((ptr != NULL)?ptr:"");
392 while (Siz <= CopySize)
395 NewBuf->buf = (char*) malloc(Siz);
396 NewBuf->BufSize = Siz;
398 memcpy(NewBuf->buf, ptr, CopySize);
399 NewBuf->buf[CopySize] = '\0';
400 NewBuf->BufUsed = CopySize;
403 NewBuf->buf[0] = '\0';
406 NewBuf->ConstBuf = 0;
414 * @ingroup StrBuf_DeConstructors
415 * @brief Set an existing buffer from a c-string
416 * @param Buf buffer to load
417 * @param ptr c-string to put into
418 * @param nChars set to -1 if we should work 0-terminated
419 * @returns the new length of the string
421 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
423 size_t Siz = Buf->BufSize;
427 CopySize = strlen(ptr);
431 while (Siz <= CopySize)
434 if (Siz != Buf->BufSize)
435 IncreaseBuf(Buf, 0, Siz);
436 memcpy(Buf->buf, ptr, CopySize);
437 Buf->buf[CopySize] = '\0';
438 Buf->BufUsed = CopySize;
445 * @ingroup StrBuf_DeConstructors
446 * @brief use strbuf as wrapper for a string constant for easy handling
447 * @param StringConstant a string to wrap
448 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
450 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
454 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
455 NewBuf->buf = (char*) StringConstant;
456 NewBuf->BufSize = SizeOfStrConstant;
457 NewBuf->BufUsed = SizeOfStrConstant;
458 NewBuf->ConstBuf = 1;
467 * @ingroup StrBuf_DeConstructors
468 * @brief flush the content of a Buf; keep its struct
469 * @param buf Buffer to flush
471 int FlushStrBuf(StrBuf *buf)
483 * @ingroup StrBuf_DeConstructors
484 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
485 * @param buf Buffer to wipe
487 int FLUSHStrBuf(StrBuf *buf)
493 if (buf->BufUsed > 0) {
494 memset(buf->buf, 0, buf->BufUsed);
501 int hFreeDbglog = -1;
504 * @ingroup StrBuf_DeConstructors
505 * @brief Release a Buffer
506 * Its a double pointer, so it can NULL your pointer
507 * so fancy SIG11 appear instead of random results
508 * @param FreeMe Pointer Pointer to the buffer to free
510 void FreeStrBuf (StrBuf **FreeMe)
515 dbg_FreeStrBuf(FreeMe, 'F');
517 if (!(*FreeMe)->ConstBuf)
518 free((*FreeMe)->buf);
524 * @ingroup StrBuf_DeConstructors
525 * @brief flatten a Buffer to the Char * we return
526 * Its a double pointer, so it can NULL your pointer
527 * so fancy SIG11 appear instead of random results
528 * The Callee then owns the buffer and is responsible for freeing it.
529 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
530 * @returns the pointer of the buffer; Callee owns the memory thereafter.
532 char *SmashStrBuf (StrBuf **SmashMe)
536 if ((SmashMe == NULL) || (*SmashMe == NULL))
539 dbg_FreeStrBuf(SmashMe, 'S');
541 Ret = (*SmashMe)->buf;
548 * @ingroup StrBuf_DeConstructors
549 * @brief Release the buffer
550 * If you want put your StrBuf into a Hash, use this as Destructor.
551 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
553 void HFreeStrBuf (void *VFreeMe)
555 StrBuf *FreeMe = (StrBuf*)VFreeMe;
559 dbg_FreeStrBuf(SmashMe, 'H');
561 if (!FreeMe->ConstBuf)
567 /*******************************************************************************
568 * Simple string transformations *
569 *******************************************************************************/
573 * @brief Wrapper around atol
575 long StrTol(const StrBuf *Buf)
580 return atol(Buf->buf);
587 * @brief Wrapper around atoi
589 int StrToi(const StrBuf *Buf)
593 if (Buf->BufUsed > 0)
594 return atoi(Buf->buf);
601 * @brief Checks to see if the string is a pure number
602 * @param Buf The buffer to inspect
603 * @returns 1 if its a pure number, 0, if not.
605 int StrBufIsNumber(const StrBuf *Buf) {
607 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
610 strtoll(Buf->buf, &pEnd, 10);
611 if (pEnd == Buf->buf)
613 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
615 if (Buf->buf == pEnd)
621 * @brief modifies a Single char of the Buf
622 * You can point to it via char* or a zero-based integer
623 * @param Buf The buffer to manipulate
624 * @param ptr char* to zero; use NULL if unused
625 * @param nThChar zero based pointer into the string; use -1 if unused
626 * @param PeekValue The Character to place into the position
628 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
633 nThChar = ptr - Buf->buf;
634 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
636 Buf->buf[nThChar] = PeekValue;
642 * @brief Append a StringBuffer to the buffer
643 * @param Buf Buffer to modify
644 * @param AppendBuf Buffer to copy at the end of our buffer
645 * @param Offset Should we start copying from an offset?
647 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
649 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
652 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
655 AppendBuf->BufUsed + Buf->BufUsed);
657 memcpy(Buf->buf + Buf->BufUsed,
658 AppendBuf->buf + Offset,
659 AppendBuf->BufUsed - Offset);
660 Buf->BufUsed += AppendBuf->BufUsed - Offset;
661 Buf->buf[Buf->BufUsed] = '\0';
667 * @brief Append a C-String to the buffer
668 * @param Buf Buffer to modify
669 * @param AppendBuf Buffer to copy at the end of our buffer
670 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
671 * @param Offset Should we start copying from an offset?
673 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
676 long BufSizeRequired;
678 if ((AppendBuf == NULL) || (Buf == NULL))
682 aps = strlen(AppendBuf + Offset);
684 aps = AppendSize - Offset;
686 BufSizeRequired = Buf->BufUsed + aps + 1;
687 if (Buf->BufSize <= BufSizeRequired)
688 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
690 memcpy(Buf->buf + Buf->BufUsed,
694 Buf->buf[Buf->BufUsed] = '\0';
699 * @brief sprintf like function appending the formated string to the buffer
700 * vsnprintf version to wrap into own calls
701 * @param Buf Buffer to extend by format and Params
702 * @param format printf alike format to add
703 * @param ap va_list containing the items for format
705 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
713 if ((Buf == NULL) || (format == NULL))
716 BufSize = Buf->BufSize;
717 nWritten = Buf->BufSize + 1;
718 Offset = Buf->BufUsed;
719 newused = Offset + nWritten;
721 while (newused >= BufSize) {
723 nWritten = vsnprintf(Buf->buf + Offset,
724 Buf->BufSize - Offset,
727 newused = Offset + nWritten;
728 if (newused >= Buf->BufSize) {
729 IncreaseBuf(Buf, 1, newused);
730 newused = Buf->BufSize + 1;
733 Buf->BufUsed = Offset + nWritten;
734 BufSize = Buf->BufSize;
742 * @brief sprintf like function appending the formated string to the buffer
743 * @param Buf Buffer to extend by format and Params
744 * @param format printf alike format to add
746 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
754 if ((Buf == NULL) || (format == NULL))
757 BufSize = Buf->BufSize;
758 nWritten = Buf->BufSize + 1;
759 Offset = Buf->BufUsed;
760 newused = Offset + nWritten;
762 while (newused >= BufSize) {
763 va_start(arg_ptr, format);
764 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
765 Buf->BufSize - Buf->BufUsed,
768 newused = Buf->BufUsed + nWritten;
769 if (newused >= Buf->BufSize) {
770 IncreaseBuf(Buf, 1, newused);
771 newused = Buf->BufSize + 1;
774 Buf->BufUsed += nWritten;
775 BufSize = Buf->BufSize;
783 * @brief sprintf like function putting the formated string into the buffer
784 * @param Buf Buffer to extend by format and Parameters
785 * @param format printf alike format to add
787 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
792 if ((Buf == NULL) || (format == NULL))
795 nWritten = Buf->BufSize + 1;
796 while (nWritten >= Buf->BufSize) {
797 va_start(arg_ptr, format);
798 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
800 if (nWritten >= Buf->BufSize) {
801 IncreaseBuf(Buf, 0, 0);
802 nWritten = Buf->BufSize + 1;
805 Buf->BufUsed = nWritten ;
811 * @brief Callback for cURL to append the webserver reply to a buffer
812 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
813 * @param size pre-defined by the cURL API; see man 3 curl for mre info
814 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
815 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
817 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
826 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
833 * @brief extracts a substring from Source into dest
834 * @param dest buffer to place substring into
835 * @param Source string to copy substring from
836 * @param Offset chars to skip from start
837 * @param nChars number of chars to copy
838 * @returns the number of chars copied; may be different from nChars due to the size of Source
840 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
843 if (Offset > Source->BufUsed)
848 if (Offset + nChars < Source->BufUsed)
850 if (nChars >= dest->BufSize)
851 IncreaseBuf(dest, 0, nChars + 1);
852 memcpy(dest->buf, Source->buf + Offset, nChars);
853 dest->BufUsed = nChars;
854 dest->buf[dest->BufUsed] = '\0';
857 NCharsRemain = Source->BufUsed - Offset;
858 if (NCharsRemain >= dest->BufSize)
859 IncreaseBuf(dest, 0, NCharsRemain + 1);
860 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
861 dest->BufUsed = NCharsRemain;
862 dest->buf[dest->BufUsed] = '\0';
868 * @brief Cut nChars from the start of the string
869 * @param Buf Buffer to modify
870 * @param nChars how many chars should be skipped?
872 void StrBufCutLeft(StrBuf *Buf, int nChars)
874 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
875 if (nChars >= Buf->BufUsed) {
879 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
880 Buf->BufUsed -= nChars;
881 Buf->buf[Buf->BufUsed] = '\0';
886 * @brief Cut the trailing n Chars from the string
887 * @param Buf Buffer to modify
888 * @param nChars how many chars should be trunkated?
890 void StrBufCutRight(StrBuf *Buf, int nChars)
892 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
893 if (nChars >= Buf->BufUsed) {
897 Buf->BufUsed -= nChars;
898 Buf->buf[Buf->BufUsed] = '\0';
903 * @brief Cut the string after n Chars
904 * @param Buf Buffer to modify
905 * @param AfternChars after how many chars should we trunkate the string?
906 * @param At if non-null and points inside of our string, cut it there.
908 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
910 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
912 AfternChars = At - Buf->buf;
915 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
917 Buf->BufUsed = AfternChars;
918 Buf->buf[Buf->BufUsed] = '\0';
924 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
925 * @param Buf the string to modify
927 void StrBufTrim(StrBuf *Buf)
930 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
932 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
935 if (delta > 0) StrBufCutLeft(Buf, delta);
937 if (Buf->BufUsed == 0) return;
938 while (isspace(Buf->buf[Buf->BufUsed - 1])){
941 Buf->buf[Buf->BufUsed] = '\0';
946 * @brief uppercase the contents of a buffer
947 * @param Buf the buffer to translate
949 void StrBufUpCase(StrBuf *Buf)
953 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
956 pche = pch + Buf->BufUsed;
958 *pch = toupper(*pch);
966 * @brief lowercase the contents of a buffer
967 * @param Buf the buffer to translate
969 void StrBufLowerCase(StrBuf *Buf)
973 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
976 pche = pch + Buf->BufUsed;
978 *pch = tolower(*pch);
984 /*******************************************************************************
985 * a tokenizer that kills, maims, and destroys *
986 *******************************************************************************/
989 * @ingroup StrBuf_Tokenizer
990 * @brief Counts the numbmer of tokens in a buffer
991 * @param source String to count tokens in
992 * @param tok Tokenizer char to count
993 * @returns numbers of tokenizer chars found
995 int StrBufNum_tokens(const StrBuf *source, char tok)
999 if ((source == NULL) || (source->BufUsed == 0))
1001 if ((source->BufUsed == 1) && (*source->buf == tok))
1005 pche = pch + source->BufUsed;
1016 * @ingroup StrBuf_Tokenizer
1017 * @brief a string tokenizer
1018 * @param Source StringBuffer to read into
1019 * @param parmnum n'th Parameter to remove
1020 * @param separator tokenizer character
1021 * @returns -1 if not found, else length of token.
1023 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1026 char *d, *s, *end; /* dest, source */
1029 /* Find desired @parameter */
1030 end = Source->buf + Source->BufUsed;
1032 while ((d <= end) &&
1035 /* End of string, bail! */
1040 if (*d == separator) {
1045 if ((d == NULL) || (d >= end))
1046 return 0; /* @Parameter not found */
1048 /* Find next @parameter */
1050 while ((s <= end) &&
1051 (*s && *s != separator))
1055 if (*s == separator)
1059 /* Hack and slash */
1064 memmove(d, s, Source->BufUsed - (s - Source->buf));
1065 Source->BufUsed += ReducedBy;
1066 Source->buf[Source->BufUsed] = '\0';
1068 else if (d == Source->buf) {
1070 Source->BufUsed = 0;
1074 Source->BufUsed += ReducedBy;
1087 * @ingroup StrBuf_Tokenizer
1088 * @brief a string tokenizer
1089 * @param dest Destination StringBuffer
1090 * @param Source StringBuffer to read into
1091 * @param parmnum n'th Parameter to extract
1092 * @param separator tokenizer character
1093 * @returns -1 if not found, else length of token.
1095 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1097 const char *s, *e; //* source * /
1098 int len = 0; //* running total length of extracted string * /
1099 int current_token = 0; //* token currently being processed * /
1102 dest->buf[0] = '\0';
1108 if ((Source == NULL) || (Source->BufUsed ==0)) {
1112 e = s + Source->BufUsed;
1115 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1117 while ((s<e) && !IsEmptyStr(s)) {
1118 if (*s == separator) {
1121 if (len >= dest->BufSize) {
1122 dest->BufUsed = len;
1123 if (IncreaseBuf(dest, 1, -1) < 0) {
1128 if ( (current_token == parmnum) &&
1129 (*s != separator)) {
1130 dest->buf[len] = *s;
1133 else if (current_token > parmnum) {
1139 dest->buf[len] = '\0';
1140 dest->BufUsed = len;
1142 if (current_token < parmnum) {
1143 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1146 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1155 * @ingroup StrBuf_Tokenizer
1156 * @brief a string tokenizer to fetch an integer
1157 * @param Source String containing tokens
1158 * @param parmnum n'th Parameter to extract
1159 * @param separator tokenizer character
1160 * @returns 0 if not found, else integer representation of the token
1162 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1172 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1179 * @ingroup StrBuf_Tokenizer
1180 * @brief a string tokenizer to fetch a long integer
1181 * @param Source String containing tokens
1182 * @param parmnum n'th Parameter to extract
1183 * @param separator tokenizer character
1184 * @returns 0 if not found, else long integer representation of the token
1186 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1196 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1204 * @ingroup StrBuf_Tokenizer
1205 * @brief a string tokenizer to fetch an unsigned long
1206 * @param Source String containing tokens
1207 * @param parmnum n'th Parameter to extract
1208 * @param separator tokenizer character
1209 * @returns 0 if not found, else unsigned long representation of the token
1211 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1222 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1226 return (unsigned long) atol(pnum);
1235 * @ingroup StrBuf_NextTokenizer
1236 * @brief a string tokenizer; Bounds checker
1237 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1238 * @param Source our tokenbuffer
1239 * @param pStart the token iterator pointer to inspect
1240 * @returns whether the revolving pointer is inside of the search range
1242 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1244 if ((Source == NULL) ||
1245 (*pStart == StrBufNOTNULL) ||
1246 (Source->BufUsed == 0))
1250 if (*pStart == NULL)
1254 else if (*pStart > Source->buf + Source->BufUsed)
1258 else if (*pStart <= Source->buf)
1267 * @ingroup StrBuf_NextTokenizer
1268 * @brief a string tokenizer
1269 * @param dest Destination StringBuffer
1270 * @param Source StringBuffer to read into
1271 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1272 * @param separator tokenizer
1273 * @returns -1 if not found, else length of token.
1275 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1277 const char *s; /* source */
1278 const char *EndBuffer; /* end stop of source buffer */
1279 int current_token = 0; /* token currently being processed */
1280 int len = 0; /* running total length of extracted string */
1282 if ((Source == NULL) ||
1283 (Source->BufUsed == 0) )
1285 *pStart = StrBufNOTNULL;
1289 EndBuffer = Source->buf + Source->BufUsed;
1293 dest->buf[0] = '\0';
1298 *pStart = EndBuffer + 1;
1302 if (*pStart == NULL)
1304 *pStart = Source->buf; /* we're starting to examine this buffer. */
1306 else if ((*pStart < Source->buf) ||
1307 (*pStart > EndBuffer ) )
1309 return -1; /* no more tokens to find. */
1313 /* start to find the next token */
1314 while ((s <= EndBuffer) &&
1315 (current_token == 0) )
1317 if (*s == separator)
1319 /* we found the next token */
1323 if (len >= dest->BufSize)
1325 /* our Dest-buffer isn't big enough, increase it. */
1326 dest->BufUsed = len;
1328 if (IncreaseBuf(dest, 1, -1) < 0) {
1329 /* WHUT? no more mem? bail out. */
1336 if ( (current_token == 0 ) && /* are we in our target token? */
1337 (!IsEmptyStr(s) ) &&
1338 (separator != *s) ) /* don't copy the token itself */
1340 dest->buf[len] = *s; /* Copy the payload */
1341 ++len; /* remember the bigger size. */
1347 /* did we reach the end? */
1348 if ((s > EndBuffer)) {
1349 EndBuffer = StrBufNOTNULL;
1350 *pStart = EndBuffer;
1353 *pStart = s; /* remember the position for the next run */
1356 /* sanitize our extracted token */
1357 dest->buf[len] = '\0';
1358 dest->BufUsed = len;
1365 * @ingroup StrBuf_NextTokenizer
1366 * @brief a string tokenizer
1367 * @param Source StringBuffer to read from
1368 * @param pStart pointer to the end of the last token. Feed with NULL.
1369 * @param separator tokenizer character
1370 * @param nTokens number of tokens to fastforward over
1371 * @returns -1 if not found, else length of token.
1373 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1375 const char *s, *EndBuffer; //* source * /
1376 int len = 0; //* running total length of extracted string * /
1377 int current_token = 0; //* token currently being processed * /
1379 if ((Source == NULL) ||
1380 (Source->BufUsed ==0)) {
1384 return Source->BufUsed;
1386 if (*pStart == NULL)
1387 *pStart = Source->buf;
1389 EndBuffer = Source->buf + Source->BufUsed;
1391 if ((*pStart < Source->buf) ||
1392 (*pStart > EndBuffer)) {
1400 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1402 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1403 if (*s == separator) {
1406 if (current_token >= nTokens) {
1418 * @ingroup StrBuf_NextTokenizer
1419 * @brief a string tokenizer to fetch an integer
1420 * @param Source StringBuffer to read from
1421 * @param pStart Cursor on the tokenstring
1422 * @param separator tokenizer character
1423 * @returns 0 if not found, else integer representation of the token
1425 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1435 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1442 * @ingroup StrBuf_NextTokenizer
1443 * @brief a string tokenizer to fetch a long integer
1444 * @param Source StringBuffer to read from
1445 * @param pStart Cursor on the tokenstring
1446 * @param separator tokenizer character
1447 * @returns 0 if not found, else long integer representation of the token
1449 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1459 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1467 * @ingroup StrBuf_NextTokenizer
1468 * @brief a string tokenizer to fetch an unsigned long
1469 * @param Source StringBuffer to read from
1470 * @param pStart Cursor on the tokenstring
1471 * @param separator tokenizer character
1472 * @returns 0 if not found, else unsigned long representation of the token
1474 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1485 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1489 return (unsigned long) atol(pnum);
1499 /*******************************************************************************
1500 * Escape Appending *
1501 *******************************************************************************/
1504 * @ingroup StrBuf_DeEnCoder
1505 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1506 * @param OutBuf the output buffer
1507 * @param In Buffer to encode
1508 * @param PlainIn way in from plain old c strings
1510 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1512 const char *pch, *pche;
1516 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1518 if (PlainIn != NULL) {
1519 len = strlen(PlainIn);
1525 pche = pch + In->BufUsed;
1532 pt = OutBuf->buf + OutBuf->BufUsed;
1533 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1535 while (pch < pche) {
1537 IncreaseBuf(OutBuf, 1, -1);
1538 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1539 pt = OutBuf->buf + OutBuf->BufUsed;
1542 if((*pch >= 'a' && *pch <= 'z') ||
1543 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1544 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1545 (*pch == '!') || (*pch == '_') ||
1546 (*pch == ',') || (*pch == '.') ||
1554 *(pt + 1) = HexList[(unsigned char)*pch][0];
1555 *(pt + 2) = HexList[(unsigned char)*pch][1];
1557 OutBuf->BufUsed += 3;
1565 * @ingroup StrBuf_DeEnCoder
1566 * @brief Append a string, escaping characters which have meaning in HTML.
1568 * @param Target target buffer
1569 * @param Source source buffer; set to NULL if you just have a C-String
1570 * @param PlainIn Plain-C string to append; set to NULL if unused
1571 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1572 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1573 * if set to 2, linebreaks are replaced by <br/>
1575 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1577 const char *aptr, *eiptr;
1581 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1584 if (PlainIn != NULL) {
1586 len = strlen(PlainIn);
1591 eiptr = aptr + Source->BufUsed;
1592 len = Source->BufUsed;
1598 bptr = Target->buf + Target->BufUsed;
1599 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1601 while (aptr < eiptr){
1603 IncreaseBuf(Target, 1, -1);
1604 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1605 bptr = Target->buf + Target->BufUsed;
1608 memcpy(bptr, "<", 4);
1610 Target->BufUsed += 4;
1612 else if (*aptr == '>') {
1613 memcpy(bptr, ">", 4);
1615 Target->BufUsed += 4;
1617 else if (*aptr == '&') {
1618 memcpy(bptr, "&", 5);
1620 Target->BufUsed += 5;
1622 else if (*aptr == '"') {
1623 memcpy(bptr, """, 6);
1625 Target->BufUsed += 6;
1627 else if (*aptr == '\'') {
1628 memcpy(bptr, "'", 5);
1630 Target->BufUsed += 5;
1632 else if (*aptr == LB) {
1637 else if (*aptr == RB) {
1642 else if (*aptr == QU) {
1647 else if ((*aptr == 32) && (nbsp == 1)) {
1648 memcpy(bptr, " ", 6);
1650 Target->BufUsed += 6;
1652 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1653 *bptr='\0'; /* nothing */
1655 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1656 memcpy(bptr, "<br/>", 11);
1658 Target->BufUsed += 11;
1662 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1663 *bptr='\0'; /* nothing */
1673 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1675 return Target->BufUsed;
1679 * @ingroup StrBuf_DeEnCoder
1680 * @brief Append a string, escaping characters which have meaning in HTML.
1681 * Converts linebreaks into blanks; escapes single quotes
1682 * @param Target target buffer
1683 * @param Source source buffer; set to NULL if you just have a C-String
1684 * @param PlainIn Plain-C string to append; set to NULL if unused
1686 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1688 const char *aptr, *eiptr;
1692 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1695 if (PlainIn != NULL) {
1697 len = strlen(PlainIn);
1702 eiptr = aptr + Source->BufUsed;
1703 len = Source->BufUsed;
1709 eptr = Target->buf + Target->BufSize - 8;
1710 tptr = Target->buf + Target->BufUsed;
1712 while (aptr < eiptr){
1714 IncreaseBuf(Target, 1, -1);
1715 eptr = Target->buf + Target->BufSize - 8;
1716 tptr = Target->buf + Target->BufUsed;
1719 if (*aptr == '\n') {
1723 else if (*aptr == '\r') {
1727 else if (*aptr == '\'') {
1733 Target->BufUsed += 5;
1746 * @ingroup StrBuf_DeEnCoder
1747 * @brief Append a string, escaping characters which have meaning in ICAL.
1749 * @param Target target buffer
1750 * @param Source source buffer; set to NULL if you just have a C-String
1751 * @param PlainIn Plain-C string to append; set to NULL if unused
1753 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1755 const char *aptr, *eiptr;
1759 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1762 if (PlainIn != NULL) {
1764 len = strlen(PlainIn);
1769 eiptr = aptr + Source->BufUsed;
1770 len = Source->BufUsed;
1776 eptr = Target->buf + Target->BufSize - 8;
1777 tptr = Target->buf + Target->BufUsed;
1779 while (aptr < eiptr){
1780 if(tptr + 3 >= eptr) {
1781 IncreaseBuf(Target, 1, -1);
1782 eptr = Target->buf + Target->BufSize - 8;
1783 tptr = Target->buf + Target->BufUsed;
1786 if (*aptr == '\n') {
1793 else if (*aptr == '\r') {
1800 else if (*aptr == ',') {
1816 * @ingroup StrBuf_DeEnCoder
1817 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1819 * @param Target target buffer
1820 * @param Source source buffer; set to NULL if you just have a C-String
1821 * @param PlainIn Plain-C string to append; set to NULL if unused
1822 * @returns size of result or -1
1824 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1826 const char *aptr, *eiptr;
1830 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1833 if (PlainIn != NULL) {
1835 len = strlen(PlainIn);
1840 eiptr = aptr + Source->BufUsed;
1841 len = Source->BufUsed;
1847 bptr = Target->buf + Target->BufUsed;
1848 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1850 while (aptr < eiptr){
1852 IncreaseBuf(Target, 1, -1);
1853 eptr = Target->buf + Target->BufSize - 3;
1854 bptr = Target->buf + Target->BufUsed;
1861 Target->BufUsed += 2;
1862 } else if (*aptr == '\\') {
1867 Target->BufUsed += 2;
1877 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1879 return Target->BufUsed;
1883 * @ingroup StrBuf_DeEnCoder
1884 * @brief Append a string, escaping characters which have meaning in HTML + json.
1886 * @param Target target buffer
1887 * @param Source source buffer; set to NULL if you just have a C-String
1888 * @param PlainIn Plain-C string to append; set to NULL if unused
1889 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1890 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1891 * if set to 2, linebreaks are replaced by <br/>
1893 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1895 const char *aptr, *eiptr;
1898 int IsUtf8Sequence = 0;
1900 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1903 if (PlainIn != NULL) {
1905 len = strlen(PlainIn);
1910 eiptr = aptr + Source->BufUsed;
1911 len = Source->BufUsed;
1917 bptr = Target->buf + Target->BufUsed;
1918 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1920 while (aptr < eiptr){
1922 IncreaseBuf(Target, 1, -1);
1923 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1924 bptr = Target->buf + Target->BufUsed;
1927 memcpy(bptr, "<", 4);
1929 Target->BufUsed += 4;
1931 else if (*aptr == '>') {
1932 memcpy(bptr, ">", 4);
1934 Target->BufUsed += 4;
1936 else if (*aptr == '&') {
1937 memcpy(bptr, "&", 5);
1939 Target->BufUsed += 5;
1941 else if (*aptr == LB) {
1946 else if (*aptr == RB) {
1951 else if ((*aptr == 32) && (nbsp == 1)) {
1952 memcpy(bptr, " ", 6);
1954 Target->BufUsed += 6;
1956 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1957 *bptr='\0'; /* nothing */
1959 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1960 memcpy(bptr, "<br/>", 11);
1962 Target->BufUsed += 11;
1965 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1966 *bptr='\0'; /* nothing */
1969 else if ((*aptr == '"') || (*aptr == QU)) {
1974 Target->BufUsed += 2;
1975 } else if (*aptr == '\\') {
1980 Target->BufUsed += 2;
1983 if (((unsigned char)*aptr) >= 0x20)
1985 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1989 while (IsUtf8Sequence > 1){
1990 if(bptr + IsUtf8Sequence >= eptr) {
1991 IncreaseBuf(Target, 1, -1);
1992 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1993 bptr = Target->buf + Target->BufUsed - 1;
2007 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2009 return Target->BufUsed;
2013 * @ingroup StrBuf_DeEnCoder
2014 * @brief unhide special chars hidden to the HTML escaper
2015 * @param target buffer to put the unescaped string in
2016 * @param source buffer to unescape
2018 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2024 FlushStrBuf(target);
2026 if (source == NULL ||target == NULL)
2031 len = source->BufUsed;
2032 for (a = 0; a < len; ++a) {
2033 if (target->BufUsed >= target->BufSize)
2034 IncreaseBuf(target, 1, -1);
2036 if (source->buf[a] == '=') {
2037 hex[0] = source->buf[a + 1];
2038 hex[1] = source->buf[a + 2];
2041 sscanf(hex, "%02x", &b);
2042 target->buf[target->BufUsed] = b;
2043 target->buf[++target->BufUsed] = 0;
2047 target->buf[target->BufUsed] = source->buf[a];
2048 target->buf[++target->BufUsed] = 0;
2055 * @ingroup StrBuf_DeEnCoder
2056 * @brief hide special chars from the HTML escapers and friends
2057 * @param target buffer to put the escaped string in
2058 * @param source buffer to escape
2060 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2065 FlushStrBuf(target);
2067 if (source == NULL ||target == NULL)
2072 len = source->BufUsed;
2073 for (i=0; i<len; ++i) {
2074 if (target->BufUsed + 4 >= target->BufSize)
2075 IncreaseBuf(target, 1, -1);
2076 if ( (isalnum(source->buf[i])) ||
2077 (source->buf[i]=='-') ||
2078 (source->buf[i]=='_') ) {
2079 target->buf[target->BufUsed++] = source->buf[i];
2082 sprintf(&target->buf[target->BufUsed],
2084 (0xFF &source->buf[i]));
2085 target->BufUsed += 3;
2088 target->buf[target->BufUsed + 1] = '\0';
2092 /*******************************************************************************
2093 * Quoted Printable de/encoding *
2094 *******************************************************************************/
2097 * @ingroup StrBuf_DeEnCoder
2098 * @brief decode a buffer from base 64 encoding; destroys original
2099 * @param Buf Buffor to transform
2101 int StrBufDecodeBase64(StrBuf *Buf)
2105 if (Buf == NULL) return -1;
2107 xferbuf = (char*) malloc(Buf->BufSize);
2108 siz = CtdlDecodeBase64(xferbuf,
2118 * @ingroup StrBuf_DeEnCoder
2119 * @brief decode a buffer from base 64 encoding; destroys original
2120 * @param Buf Buffor to transform
2122 int StrBufDecodeHex(StrBuf *Buf)
2125 char *pch, *pche, *pchi;
2127 if (Buf == NULL) return -1;
2129 pch = pchi = Buf->buf;
2130 pche = pch + Buf->BufUsed;
2132 while (pchi < pche){
2133 ch = decode_hex(pchi);
2140 Buf->BufUsed = pch - Buf->buf;
2141 return Buf->BufUsed;
2145 * @ingroup StrBuf_DeEnCoder
2146 * @brief replace all chars >0x20 && < 0x7F with Mute
2147 * @param Mute char to put over invalid chars
2148 * @param Buf Buffor to transform
2150 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2154 if (Buf == NULL) return -1;
2155 pch = (unsigned char *)Buf->buf;
2156 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2157 if ((*pch < 0x20) || (*pch > 0x7F))
2161 return Buf->BufUsed;
2166 * @ingroup StrBuf_DeEnCoder
2167 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2168 * @param Buf Buffer to translate
2169 * @param StripBlanks Reduce several blanks to one?
2171 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2177 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2178 Buf->buf[Buf->BufUsed - 1] = '\0';
2183 while (a < Buf->BufUsed) {
2184 if (Buf->buf[a] == '+')
2186 else if (Buf->buf[a] == '%') {
2187 /* don't let % chars through, rather truncate the input. */
2188 if (a + 2 > Buf->BufUsed) {
2193 hex[0] = Buf->buf[a + 1];
2194 hex[1] = Buf->buf[a + 2];
2197 sscanf(hex, "%02x", &b);
2198 Buf->buf[a] = (char) b;
2199 len = Buf->BufUsed - a - 2;
2201 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2213 * @ingroup StrBuf_DeEnCoder
2214 * @brief RFC2047-encode a header field if necessary.
2215 * If no non-ASCII characters are found, the string
2216 * will be copied verbatim without encoding.
2218 * @param target Target buffer.
2219 * @param source Source string to be encoded.
2220 * @returns encoded length; -1 if non success.
2222 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2224 const char headerStr[] = "=?UTF-8?Q?";
2225 int need_to_encode = 0;
2229 if ((source == NULL) ||
2233 while ((i < source->BufUsed) &&
2234 (!IsEmptyStr (&source->buf[i])) &&
2235 (need_to_encode == 0)) {
2236 if (((unsigned char) source->buf[i] < 32) ||
2237 ((unsigned char) source->buf[i] > 126)) {
2243 if (!need_to_encode) {
2244 if (*target == NULL) {
2245 *target = NewStrBufPlain(source->buf, source->BufUsed);
2248 FlushStrBuf(*target);
2249 StrBufAppendBuf(*target, source, 0);
2251 return (*target)->BufUsed;
2253 if (*target == NULL)
2254 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2255 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2256 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2257 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2258 (*target)->BufUsed = sizeof(headerStr) - 1;
2259 for (i=0; (i < source->BufUsed); ++i) {
2260 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2261 IncreaseBuf(*target, 1, 0);
2262 ch = (unsigned char) source->buf[i];
2263 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2264 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2265 (*target)->BufUsed += 3;
2268 (*target)->buf[(*target)->BufUsed] = ch;
2269 (*target)->BufUsed++;
2273 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2274 IncreaseBuf(*target, 1, 0);
2276 (*target)->buf[(*target)->BufUsed++] = '?';
2277 (*target)->buf[(*target)->BufUsed++] = '=';
2278 (*target)->buf[(*target)->BufUsed] = '\0';
2279 return (*target)->BufUsed;;
2284 * @brief replaces all occurances of 'search' by 'replace'
2285 * @param buf Buffer to modify
2286 * @param search character to search
2287 * @param replace character to replace search by
2289 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2294 for (i=0; i<buf->BufUsed; i++)
2295 if (buf->buf[i] == search)
2296 buf->buf[i] = replace;
2301 /*******************************************************************************
2302 * Iconv Wrapper; RFC822 de/encoding *
2303 *******************************************************************************/
2306 * @ingroup StrBuf_DeEnCoder
2307 * @brief Wrapper around iconv_open()
2308 * Our version adds aliases for non-standard Microsoft charsets
2309 * such as 'MS950', aliasing them to names like 'CP950'
2311 * @param tocode Target encoding
2312 * @param fromcode Source encoding
2313 * @param pic anonimized pointer to iconv struct
2315 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2318 iconv_t ic = (iconv_t)(-1) ;
2319 ic = iconv_open(tocode, fromcode);
2320 if (ic == (iconv_t)(-1) ) {
2321 char alias_fromcode[64];
2322 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2323 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2324 alias_fromcode[0] = 'C';
2325 alias_fromcode[1] = 'P';
2326 ic = iconv_open(tocode, alias_fromcode);
2329 *(iconv_t *)pic = ic;
2335 * @ingroup StrBuf_DeEnCoder
2336 * @brief find one chunk of a RFC822 encoded string
2337 * @param Buffer where to search
2338 * @param bptr where to start searching
2339 * @returns found position, NULL if none.
2341 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2344 /* Find the next ?Q? */
2345 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2348 end = strchr(bptr + 2, '?');
2353 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2354 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2355 (*(end + 2) == '?')) {
2356 /* skip on to the end of the cluster, the next ?= */
2357 end = strstr(end + 3, "?=");
2360 /* sort of half valid encoding, try to find an end. */
2361 end = strstr(bptr, "?=");
2367 * @brief swaps the contents of two StrBufs
2368 * this is to be used to have cheap switched between a work-buffer and a target buffer
2369 * @param A First one
2370 * @param B second one
2372 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2376 memcpy(&C, A, sizeof(*A));
2377 memcpy(A, B, sizeof(*B));
2378 memcpy(B, &C, sizeof(C));
2384 * @ingroup StrBuf_DeEnCoder
2385 * @brief convert one buffer according to the preselected iconv pointer PIC
2386 * @param ConvertBuf buffer we need to translate
2387 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2388 * @param pic Pointer to the iconv-session Object
2390 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2396 char *ibuf; /**< Buffer of characters to be converted */
2397 char *obuf; /**< Buffer for converted characters */
2398 size_t ibuflen; /**< Length of input buffer */
2399 size_t obuflen; /**< Length of output buffer */
2402 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2403 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2404 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2406 ic = *(iconv_t*)pic;
2407 ibuf = ConvertBuf->buf;
2408 ibuflen = ConvertBuf->BufUsed;
2410 obuflen = TmpBuf->BufSize;
2412 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2415 if (errno == E2BIG) {
2417 IncreaseBuf(TmpBuf, 0, 0);
2422 else if (errno == EILSEQ){
2423 /* hm, invalid utf8 sequence... what to do now? */
2424 /* An invalid multibyte sequence has been encountered in the input */
2426 else if (errno == EINVAL) {
2427 /* An incomplete multibyte sequence has been encountered in the input. */
2430 FlushStrBuf(TmpBuf);
2433 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2434 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2436 /* little card game: wheres the red lady? */
2437 SwapBuffers(ConvertBuf, TmpBuf);
2438 FlushStrBuf(TmpBuf);
2445 * @ingroup StrBuf_DeEnCoder
2446 * @brief catches one RFC822 encoded segment, and decodes it.
2447 * @param Target buffer to fill with result
2448 * @param DecodeMe buffer with stuff to process
2449 * @param SegmentStart points to our current segment in DecodeMe
2450 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2451 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2452 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2453 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2455 inline static void DecodeSegment(StrBuf *Target,
2456 const StrBuf *DecodeMe,
2460 StrBuf *ConvertBuf2,
2461 StrBuf *FoundCharset)
2467 iconv_t ic = (iconv_t)(-1);
2471 /* Now we handle foreign character sets properly encoded
2472 * in RFC2047 format.
2474 StaticBuf.buf = SegmentStart;
2475 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2476 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2477 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2478 if (FoundCharset != NULL) {
2479 FlushStrBuf(FoundCharset);
2480 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2482 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2483 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2485 *encoding = toupper(*encoding);
2486 if (*encoding == 'B') { /**< base64 */
2487 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2489 ConvertBuf->BufUsed);
2491 else if (*encoding == 'Q') { /**< quoted-printable */
2495 while (pos < ConvertBuf->BufUsed)
2497 if (ConvertBuf->buf[pos] == '_')
2498 ConvertBuf->buf[pos] = ' ';
2502 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2505 ConvertBuf->BufUsed);
2508 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2511 ctdl_iconv_open("UTF-8", charset, &ic);
2512 if (ic != (iconv_t)(-1) ) {
2514 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2515 StrBufAppendBuf(Target, ConvertBuf2, 0);
2520 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2526 * @ingroup StrBuf_DeEnCoder
2527 * @brief Handle subjects with RFC2047 encoding such as:
2528 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2529 * @param Target where to put the decoded string to
2530 * @param DecodeMe buffer with encoded string
2531 * @param DefaultCharset if we don't find one, which should we use?
2532 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2533 * put it here for later use where no string might be known.
2535 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2537 StrBuf *DecodedInvalidBuf = NULL;
2538 StrBuf *ConvertBuf, *ConvertBuf2;
2539 const StrBuf *DecodeMee = DecodeMe;
2540 char *start, *end, *next, *nextend, *ptr = NULL;
2542 iconv_t ic = (iconv_t)(-1) ;
2547 int illegal_non_rfc2047_encoding = 0;
2549 /* Sometimes, badly formed messages contain strings which were simply
2550 * written out directly in some foreign character set instead of
2551 * using RFC2047 encoding. This is illegal but we will attempt to
2552 * handle it anyway by converting from a user-specified default
2553 * charset to UTF-8 if we see any nonprintable characters.
2556 len = StrLength(DecodeMe);
2557 for (i=0; i<DecodeMe->BufUsed; ++i) {
2558 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2559 illegal_non_rfc2047_encoding = 1;
2564 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2565 if ((illegal_non_rfc2047_encoding) &&
2566 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2567 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2570 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2571 if (ic != (iconv_t)(-1) ) {
2572 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2573 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2574 DecodeMee = DecodedInvalidBuf;
2580 /* pre evaluate the first pair */
2581 nextend = end = NULL;
2582 len = StrLength(DecodeMee);
2583 start = strstr(DecodeMee->buf, "=?");
2584 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2586 end = FindNextEnd (DecodeMee, start);
2588 StrBufAppendBuf(Target, DecodeMee, 0);
2589 FreeStrBuf(&ConvertBuf);
2590 FreeStrBuf(&DecodedInvalidBuf);
2594 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2596 if (start != DecodeMee->buf) {
2599 nFront = start - DecodeMee->buf;
2600 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2604 * Since spammers will go to all sorts of absurd lengths to get their
2605 * messages through, there are LOTS of corrupt headers out there.
2606 * So, prevent a really badly formed RFC2047 header from throwing
2607 * this function into an infinite loop.
2609 while ((start != NULL) &&
2616 DecodeSegment(Target,
2624 next = strstr(end, "=?");
2626 if ((next != NULL) &&
2628 nextend = FindNextEnd(DecodeMee, next);
2629 if (nextend == NULL)
2632 /* did we find two partitions */
2633 if ((next != NULL) &&
2637 while ((ptr < next) &&
2643 /* did we find a gab just filled with blanks? */
2646 long gap = next - start;
2651 /* now terminate the gab at the end */
2652 delta = (next - end) - 2; ////TODO: const!
2653 ((StrBuf*)DecodeMee)->BufUsed -= delta;
2654 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
2656 /* move next to its new location. */
2661 /* our next-pair is our new first pair now. */
2667 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2668 if ((end != NULL) && (end < nextend)) {
2670 while ( (ptr < nextend) &&
2677 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2679 FreeStrBuf(&ConvertBuf);
2680 FreeStrBuf(&ConvertBuf2);
2681 FreeStrBuf(&DecodedInvalidBuf);
2684 /*******************************************************************************
2685 * Manipulating UTF-8 Strings *
2686 *******************************************************************************/
2690 * @brief evaluate the length of an utf8 special character sequence
2691 * @param Char the character to examine
2692 * @returns width of utf8 chars in bytes
2694 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2699 while ((n < 8) && ((test & *CharS) != 0)) {
2703 if ((n > 6) || ((CharE - CharS) < n))
2710 * @brief detect whether this char starts an utf-8 encoded char
2711 * @param Char character to inspect
2712 * @returns yes or no
2714 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2716 /** 11??.???? indicates an UTF8 Sequence. */
2717 return ((Char & 0xC0) != 0);
2722 * @brief measure the number of glyphs in an UTF8 string...
2723 * @param Buf string to measure
2724 * @returns the number of glyphs in Buf
2726 long StrBuf_Utf8StrLen(StrBuf *Buf)
2732 if ((Buf == NULL) || (Buf->BufUsed == 0))
2735 eptr = Buf->buf + Buf->BufUsed;
2736 while ((aptr < eptr) && (*aptr != '\0')) {
2737 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2738 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2739 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2752 * @brief cuts a string after maxlen glyphs
2753 * @param Buf string to cut to maxlen glyphs
2754 * @param maxlen how long may the string become?
2755 * @returns current length of the string
2757 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2763 eptr = Buf->buf + Buf->BufUsed;
2764 while ((aptr < eptr) && (*aptr != '\0')) {
2765 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2766 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2767 while ((*aptr++ != '\0') && (m-- > 0));
2776 Buf->BufUsed = aptr - Buf->buf;
2777 return Buf->BufUsed;
2780 return Buf->BufUsed;
2788 /*******************************************************************************
2790 *******************************************************************************/
2793 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2794 #define OS_CODE 0x03 /*< unix */
2797 * @ingroup StrBuf_DeEnCoder
2798 * @brief uses the same calling syntax as compress2(), but it
2799 * creates a stream compatible with HTTP "Content-encoding: gzip"
2800 * @param dest compressed buffer
2801 * @param destLen length of the compresed data
2802 * @param source source to encode
2803 * @param sourceLen length of source to encode
2804 * @param level compression level
2806 int ZEXPORT compress_gzip(Bytef * dest,
2808 const Bytef * source,
2812 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2814 /* write gzip header */
2815 snprintf((char *) dest, *destLen,
2816 "%c%c%c%c%c%c%c%c%c%c",
2817 gz_magic[0], gz_magic[1], Z_DEFLATED,
2818 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2821 /* normal deflate */
2824 stream.next_in = (Bytef *) source;
2825 stream.avail_in = (uInt) sourceLen;
2826 stream.next_out = dest + 10L; // after header
2827 stream.avail_out = (uInt) * destLen;
2828 if ((uLong) stream.avail_out != *destLen)
2831 stream.zalloc = (alloc_func) 0;
2832 stream.zfree = (free_func) 0;
2833 stream.opaque = (voidpf) 0;
2835 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2836 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2840 err = deflate(&stream, Z_FINISH);
2841 if (err != Z_STREAM_END) {
2842 deflateEnd(&stream);
2843 return err == Z_OK ? Z_BUF_ERROR : err;
2845 *destLen = stream.total_out + 10L;
2847 /* write CRC and Length */
2848 uLong crc = crc32(0L, source, sourceLen);
2850 for (n = 0; n < 4; ++n, ++*destLen) {
2851 dest[*destLen] = (int) (crc & 0xff);
2854 uLong len = stream.total_in;
2855 for (n = 0; n < 4; ++n, ++*destLen) {
2856 dest[*destLen] = (int) (len & 0xff);
2859 err = deflateEnd(&stream);
2866 * @ingroup StrBuf_DeEnCoder
2867 * @brief compress the buffer with gzip
2868 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2869 * @param Buf buffer whose content is to be gzipped
2871 int CompressBuffer(StrBuf *Buf)
2874 char *compressed_data = NULL;
2875 size_t compressed_len, bufsize;
2878 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2879 compressed_data = malloc(compressed_len);
2881 if (compressed_data == NULL)
2883 /* Flush some space after the used payload so valgrind shuts up... */
2884 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2885 Buf->buf[Buf->BufUsed + i++] = '\0';
2886 if (compress_gzip((Bytef *) compressed_data,
2889 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2892 Buf->buf = compressed_data;
2893 Buf->BufUsed = compressed_len;
2894 Buf->BufSize = bufsize;
2895 /* Flush some space after the used payload so valgrind shuts up... */
2897 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2898 Buf->buf[Buf->BufUsed + i++] = '\0';
2901 free(compressed_data);
2903 #endif /* HAVE_ZLIB */
2909 /*******************************************************************************
2910 * File I/O; Prefer buffered read since its faster! *
2911 *******************************************************************************/
2914 * @ingroup StrBuf_IO
2915 * @brief Read a line from socket
2916 * flushes and closes the FD on error
2917 * @param buf the buffer to get the input to
2918 * @param fd pointer to the filedescriptor to read
2919 * @param append Append to an existing string or replace?
2920 * @param Error strerror() on error
2921 * @returns numbers of chars read
2923 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
2925 int len, rlen, slen;
2930 slen = len = buf->BufUsed;
2932 rlen = read(*fd, &buf->buf[len], 1);
2934 *Error = strerror(errno);
2941 if (buf->buf[len] == '\n')
2943 if (buf->buf[len] != '\r')
2945 if (len + 2 >= buf->BufSize) {
2947 buf->buf[len+1] = '\0';
2948 IncreaseBuf(buf, 1, -1);
2952 buf->buf[len] = '\0';
2957 * @ingroup StrBuf_BufferedIO
2958 * @brief Read a line from socket
2959 * flushes and closes the FD on error
2960 * @param Line the line to read from the fd / I/O Buffer
2961 * @param buf the buffer to get the input to
2962 * @param fd pointer to the filedescriptor to read
2963 * @param timeout number of successless selects until we bail out
2964 * @param selectresolution how long to wait on each select
2965 * @param Error strerror() on error
2966 * @returns numbers of chars read
2968 int StrBufTCP_read_buffered_line(StrBuf *Line,
2972 int selectresolution,
2976 int nSuccessLess = 0;
2983 if (buf->BufUsed > 0) {
2984 pch = strchr(buf->buf, '\n');
2987 len = pch - buf->buf;
2988 if (len > 0 && (*(pch - 1) == '\r') )
2990 StrBufSub(Line, buf, 0, len - rlen);
2991 StrBufCutLeft(buf, len + 1);
2996 if (buf->BufSize - buf->BufUsed < 10)
2997 IncreaseBuf(buf, 1, -1);
2999 fdflags = fcntl(*fd, F_GETFL);
3000 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3002 while ((nSuccessLess < timeout) && (pch == NULL)) {
3004 tv.tv_sec = selectresolution;
3009 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3010 *Error = strerror(errno);
3016 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3021 &buf->buf[buf->BufUsed],
3022 buf->BufSize - buf->BufUsed - 1);
3024 *Error = strerror(errno);
3029 else if (rlen > 0) {
3031 buf->BufUsed += rlen;
3032 buf->buf[buf->BufUsed] = '\0';
3033 if (buf->BufUsed + 10 > buf->BufSize) {
3034 IncreaseBuf(buf, 1, -1);
3036 pch = strchr(buf->buf, '\n');
3043 len = pch - buf->buf;
3044 if (len > 0 && (*(pch - 1) == '\r') )
3046 StrBufSub(Line, buf, 0, len - rlen);
3047 StrBufCutLeft(buf, len + 1);
3054 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3055 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3056 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3058 * @ingroup StrBuf_BufferedIO
3059 * @brief Read a line from socket
3060 * flushes and closes the FD on error
3061 * @param Line Line to read from the fd / I/O Buffer
3062 * @param IOBuf the buffer to get the input to
3063 * @param Pos pointer to the current read position, should be NULL initialized!
3064 * @param fd pointer to the filedescriptor to read
3065 * @param timeout number of successless selects until we bail out
3066 * @param selectresolution how long to wait on each select
3067 * @param Error strerror() on error
3068 * @returns numbers of chars read
3070 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3075 int selectresolution,
3078 const char *pche = NULL;
3079 const char *pos = NULL;
3081 int nSuccessLess = 0;
3083 const char *pch = NULL;
3088 if ((Line == NULL) ||
3095 *Error = ErrRBLF_PreConditionFailed;
3100 if ((IOBuf->BufUsed > 0) &&
3102 (pos < IOBuf->buf + IOBuf->BufUsed))
3104 pche = IOBuf->buf + IOBuf->BufUsed;
3106 while ((pch < pche) && (*pch != '\n'))
3108 if ((pch >= pche) || (*pch == '\0'))
3110 if ((pch != NULL) &&
3115 if (len > 0 && (*(pch - 1) == '\r') )
3117 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
3127 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
3131 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
3132 IncreaseBuf(IOBuf, 1, -1);
3136 fdflags = fcntl(*fd, F_GETFL);
3137 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3140 while ((nSuccessLess < timeout) &&
3150 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3151 *Error = strerror(errno);
3155 *Error = ErrRBLF_SelectFailed;
3158 if (! FD_ISSET(*fd, &rfds) != 0) {
3164 &IOBuf->buf[IOBuf->BufUsed],
3165 IOBuf->BufSize - IOBuf->BufUsed - 1);
3167 *Error = strerror(errno);
3172 else if (rlen > 0) {
3174 IOBuf->BufUsed += rlen;
3175 IOBuf->buf[IOBuf->BufUsed] = '\0';
3176 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
3177 IncreaseBuf(IOBuf, 1, -1);
3181 pche = IOBuf->buf + IOBuf->BufUsed;
3183 while ((pch < pche) && (*pch != '\n'))
3185 if ((pch >= pche) || (*pch == '\0'))
3194 if (len > 0 && (*(pch - 1) == '\r') )
3196 StrBufSub(Line, IOBuf, 0, len - rlen);
3197 *Pos = pos + len + 1;
3200 *Error = ErrRBLF_NotEnoughSentFromServer;
3205 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3207 * @ingroup StrBuf_IO
3208 * @brief Input binary data from socket
3209 * flushes and closes the FD on error
3210 * @param Buf the buffer to get the input to
3211 * @param fd pointer to the filedescriptor to read
3212 * @param append Append to an existing string or replace?
3213 * @param nBytes the maximal number of bytes to read
3214 * @param Error strerror() on error
3215 * @returns numbers of chars read
3217 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3220 int len, rlen, slen;
3228 if ((Buf == NULL) || (*fd == -1))
3230 *Error = ErrRBLF_BLOBPreConditionFailed;
3235 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3236 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3238 ptr = Buf->buf + Buf->BufUsed;
3240 slen = len = Buf->BufUsed;
3242 fdflags = fcntl(*fd, F_GETFL);
3243 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3245 while ((nRead < nBytes) &&
3255 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3256 *Error = strerror(errno);
3260 *Error = ErrRBLF_SelectFailed;
3263 if (! FD_ISSET(*fd, &rfds) != 0) {
3269 if ((rlen = read(*fd,
3271 nBytes - nRead)) == -1) {
3274 *Error = strerror(errno);
3279 Buf->BufUsed += rlen;
3281 Buf->buf[Buf->BufUsed] = '\0';
3285 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3286 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3288 * @ingroup StrBuf_BufferedIO
3289 * @brief Input binary data from socket
3290 * flushes and closes the FD on error
3291 * @param Blob put binary thing here
3292 * @param IOBuf the buffer to get the input to
3293 * @param Pos offset inside of IOBuf
3294 * @param fd pointer to the filedescriptor to read
3295 * @param append Append to an existing string or replace?
3296 * @param nBytes the maximal number of bytes to read
3297 * @param check whether we should search for '000\n' terminators in case of timeouts
3298 * @param Error strerror() on error
3299 * @returns numbers of chars read
3301 int StrBufReadBLOBBuffered(StrBuf *Blob,
3318 int nAlreadyRead = 0;
3326 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3330 *Error = ErrRBB_BLOBFPreConditionFailed;
3336 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3337 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3342 len = pos - IOBuf->buf;
3343 rlen = IOBuf->BufUsed - len;
3346 if ((IOBuf->BufUsed > 0) &&
3348 (pos < IOBuf->buf + IOBuf->BufUsed))
3350 pche = IOBuf->buf + IOBuf->BufUsed;
3353 if (rlen < nBytes) {
3354 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3355 Blob->BufUsed += rlen;
3356 Blob->buf[Blob->BufUsed] = '\0';
3357 nAlreadyRead = nRead = rlen;
3360 if (rlen >= nBytes) {
3361 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3362 Blob->BufUsed += nBytes;
3363 Blob->buf[Blob->BufUsed] = '\0';
3364 if (rlen == nBytes) {
3376 if (IOBuf->BufSize < nBytes - nRead)
3377 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3380 slen = len = Blob->BufUsed;
3382 fdflags = fcntl(*fd, F_GETFL);
3383 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3388 while ((nRead < nBytes) &&
3397 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3398 *Error = strerror(errno);
3402 *Error = ErrRBLF_SelectFailed;
3405 if (! FD_ISSET(*fd, &rfds) != 0) {
3417 *Error = strerror(errno);
3420 else if (rlen == 0){
3422 if ((check == NNN_TERM) &&
3424 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3426 StrBufPlain(Blob, HKEY("\n000\n"));
3427 StrBufCutRight(Blob, 5);
3428 return Blob->BufUsed;
3430 if (nSelects > 10) {
3432 *Error = ErrRBB_too_many_selects;
3436 else if (rlen > 0) {
3439 IOBuf->BufUsed += rlen;
3442 if (nRead > nBytes) {
3443 *Pos = IOBuf->buf + nBytes;
3445 Blob->buf[Blob->BufUsed] = '\0';
3446 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3450 return nRead + nAlreadyRead;
3454 * @ingroup StrBuf_IO
3455 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3456 * @param LineBuf your line will be copied here.
3457 * @param Buf BLOB with lines of text...
3458 * @param Ptr moved arround to keep the next-line across several iterations
3459 * has to be &NULL on start; will be &NotNULL on end of buffer
3460 * @returns size of copied buffer
3462 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3464 const char *aptr, *ptr, *eptr;
3467 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3468 *Ptr = StrBufNOTNULL;
3472 FlushStrBuf(LineBuf);
3474 ptr = aptr = Buf->buf;
3478 optr = LineBuf->buf;
3479 eptr = Buf->buf + Buf->BufUsed;
3480 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3482 while ((ptr <= eptr) &&
3489 LineBuf->BufUsed = optr - LineBuf->buf;
3490 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3491 optr = LineBuf->buf + LineBuf->BufUsed;
3492 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3496 if ((ptr >= eptr) && (optr > LineBuf->buf))
3498 LineBuf->BufUsed = optr - LineBuf->buf;
3500 if ((ptr <= eptr) && (*ptr == '\r'))
3502 if ((ptr <= eptr) && (*ptr == '\n'))
3509 *Ptr = StrBufNOTNULL;
3512 return Buf->BufUsed - (ptr - Buf->buf);
3517 * @ingroup StrBuf_IO
3518 * @brief removes double slashes from pathnames
3519 * @param Dir directory string to filter
3520 * @param RemoveTrailingSlash allows / disallows trailing slashes
3522 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3528 while (!IsEmptyStr(a)) {
3540 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3545 Dir->BufUsed = b - Dir->buf;