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 (nChars >= Buf->BufUsed) {
878 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
879 Buf->BufUsed -= nChars;
880 Buf->buf[Buf->BufUsed] = '\0';
885 * @brief Cut the trailing n Chars from the string
886 * @param Buf Buffer to modify
887 * @param nChars how many chars should be trunkated?
889 void StrBufCutRight(StrBuf *Buf, int nChars)
891 if (nChars >= Buf->BufUsed) {
895 Buf->BufUsed -= nChars;
896 Buf->buf[Buf->BufUsed] = '\0';
901 * @brief Cut the string after n Chars
902 * @param Buf Buffer to modify
903 * @param AfternChars after how many chars should we trunkate the string?
904 * @param At if non-null and points inside of our string, cut it there.
906 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
909 AfternChars = At - Buf->buf;
912 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
914 Buf->BufUsed = AfternChars;
915 Buf->buf[Buf->BufUsed] = '\0';
921 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
922 * @param Buf the string to modify
924 void StrBufTrim(StrBuf *Buf)
927 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
929 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
932 if (delta > 0) StrBufCutLeft(Buf, delta);
934 if (Buf->BufUsed == 0) return;
935 while (isspace(Buf->buf[Buf->BufUsed - 1])){
938 Buf->buf[Buf->BufUsed] = '\0';
943 * @brief uppercase the contents of a buffer
944 * @param Buf the buffer to translate
946 void StrBufUpCase(StrBuf *Buf)
951 pche = pch + Buf->BufUsed;
953 *pch = toupper(*pch);
961 * @brief lowercase the contents of a buffer
962 * @param Buf the buffer to translate
964 void StrBufLowerCase(StrBuf *Buf)
969 pche = pch + Buf->BufUsed;
971 *pch = tolower(*pch);
977 /*******************************************************************************
978 * a tokenizer that kills, maims, and destroys *
979 *******************************************************************************/
982 * @ingroup StrBuf_Tokenizer
983 * @brief Counts the numbmer of tokens in a buffer
984 * @param source String to count tokens in
985 * @param tok Tokenizer char to count
986 * @returns numbers of tokenizer chars found
988 int StrBufNum_tokens(const StrBuf *source, char tok)
992 return num_tokens(source->buf, tok);
996 * @ingroup StrBuf_Tokenizer
997 * @brief a string tokenizer
998 * @param Source StringBuffer to read into
999 * @param parmnum n'th Parameter to remove
1000 * @param separator tokenizer character
1001 * @returns -1 if not found, else length of token.
1003 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1006 char *d, *s, *end; /* dest, source */
1009 /* Find desired @parameter */
1010 end = Source->buf + Source->BufUsed;
1012 while ((d <= end) &&
1015 /* End of string, bail! */
1020 if (*d == separator) {
1025 if ((d == NULL) || (d >= end))
1026 return 0; /* @Parameter not found */
1028 /* Find next @parameter */
1030 while ((s <= end) &&
1031 (*s && *s != separator))
1035 if (*s == separator)
1039 /* Hack and slash */
1044 memmove(d, s, Source->BufUsed - (s - Source->buf));
1045 Source->BufUsed += ReducedBy;
1046 Source->buf[Source->BufUsed] = '\0';
1048 else if (d == Source->buf) {
1050 Source->BufUsed = 0;
1054 Source->BufUsed += ReducedBy;
1067 * @ingroup StrBuf_Tokenizer
1068 * @brief a string tokenizer
1069 * @param dest Destination StringBuffer
1070 * @param Source StringBuffer to read into
1071 * @param parmnum n'th Parameter to extract
1072 * @param separator tokenizer character
1073 * @returns -1 if not found, else length of token.
1075 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1077 const char *s, *e; //* source * /
1078 int len = 0; //* running total length of extracted string * /
1079 int current_token = 0; //* token currently being processed * /
1082 dest->buf[0] = '\0';
1088 if ((Source == NULL) || (Source->BufUsed ==0)) {
1092 e = s + Source->BufUsed;
1095 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1097 while ((s<e) && !IsEmptyStr(s)) {
1098 if (*s == separator) {
1101 if (len >= dest->BufSize) {
1102 dest->BufUsed = len;
1103 if (IncreaseBuf(dest, 1, -1) < 0) {
1108 if ( (current_token == parmnum) &&
1109 (*s != separator)) {
1110 dest->buf[len] = *s;
1113 else if (current_token > parmnum) {
1119 dest->buf[len] = '\0';
1120 dest->BufUsed = len;
1122 if (current_token < parmnum) {
1123 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1126 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1135 * @ingroup StrBuf_Tokenizer
1136 * @brief a string tokenizer to fetch an integer
1137 * @param Source String containing tokens
1138 * @param parmnum n'th Parameter to extract
1139 * @param separator tokenizer character
1140 * @returns 0 if not found, else integer representation of the token
1142 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1152 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1159 * @ingroup StrBuf_Tokenizer
1160 * @brief a string tokenizer to fetch a long integer
1161 * @param Source String containing tokens
1162 * @param parmnum n'th Parameter to extract
1163 * @param separator tokenizer character
1164 * @returns 0 if not found, else long integer representation of the token
1166 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1176 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1184 * @ingroup StrBuf_Tokenizer
1185 * @brief a string tokenizer to fetch an unsigned long
1186 * @param Source String containing tokens
1187 * @param parmnum n'th Parameter to extract
1188 * @param separator tokenizer character
1189 * @returns 0 if not found, else unsigned long representation of the token
1191 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1202 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1206 return (unsigned long) atol(pnum);
1215 * @ingroup StrBuf_NextTokenizer
1216 * @brief a string tokenizer; Bounds checker
1217 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1218 * @param Source our tokenbuffer
1219 * @param pStart the token iterator pointer to inspect
1220 * @returns whether the revolving pointer is inside of the search range
1222 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1224 if ((Source == NULL) ||
1225 (*pStart == StrBufNOTNULL) ||
1226 (Source->BufUsed == 0))
1230 if (*pStart == NULL)
1234 else if (*pStart > Source->buf + Source->BufUsed)
1238 else if (*pStart <= Source->buf)
1247 * @ingroup StrBuf_NextTokenizer
1248 * @brief a string tokenizer
1249 * @param dest Destination StringBuffer
1250 * @param Source StringBuffer to read into
1251 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1252 * @param separator tokenizer
1253 * @returns -1 if not found, else length of token.
1255 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1257 const char *s; /* source */
1258 const char *EndBuffer; /* end stop of source buffer */
1259 int current_token = 0; /* token currently being processed */
1260 int len = 0; /* running total length of extracted string */
1262 if ((Source == NULL) ||
1263 (Source->BufUsed == 0) )
1265 *pStart = StrBufNOTNULL;
1269 EndBuffer = Source->buf + Source->BufUsed;
1273 dest->buf[0] = '\0';
1278 *pStart = EndBuffer + 1;
1282 if (*pStart == NULL)
1284 *pStart = Source->buf; /* we're starting to examine this buffer. */
1286 else if ((*pStart < Source->buf) ||
1287 (*pStart > EndBuffer ) )
1289 return -1; /* no more tokens to find. */
1293 /* start to find the next token */
1294 while ((s <= EndBuffer) &&
1295 (current_token == 0) )
1297 if (*s == separator)
1299 /* we found the next token */
1303 if (len >= dest->BufSize)
1305 /* our Dest-buffer isn't big enough, increase it. */
1306 dest->BufUsed = len;
1308 if (IncreaseBuf(dest, 1, -1) < 0) {
1309 /* WHUT? no more mem? bail out. */
1316 if ( (current_token == 0 ) && /* are we in our target token? */
1317 (!IsEmptyStr(s) ) &&
1318 (separator != *s) ) /* don't copy the token itself */
1320 dest->buf[len] = *s; /* Copy the payload */
1321 ++len; /* remember the bigger size. */
1327 /* did we reach the end? */
1328 if ((s > EndBuffer)) {
1329 EndBuffer = StrBufNOTNULL;
1330 *pStart = EndBuffer;
1333 *pStart = s; /* remember the position for the next run */
1336 /* sanitize our extracted token */
1337 dest->buf[len] = '\0';
1338 dest->BufUsed = len;
1345 * @ingroup StrBuf_NextTokenizer
1346 * @brief a string tokenizer
1347 * @param Source StringBuffer to read from
1348 * @param pStart pointer to the end of the last token. Feed with NULL.
1349 * @param separator tokenizer character
1350 * @param nTokens number of tokens to fastforward over
1351 * @returns -1 if not found, else length of token.
1353 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1355 const char *s, *EndBuffer; //* source * /
1356 int len = 0; //* running total length of extracted string * /
1357 int current_token = 0; //* token currently being processed * /
1359 if ((Source == NULL) ||
1360 (Source->BufUsed ==0)) {
1364 return Source->BufUsed;
1366 if (*pStart == NULL)
1367 *pStart = Source->buf;
1369 EndBuffer = Source->buf + Source->BufUsed;
1371 if ((*pStart < Source->buf) ||
1372 (*pStart > EndBuffer)) {
1380 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1382 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1383 if (*s == separator) {
1386 if (current_token >= nTokens) {
1398 * @ingroup StrBuf_NextTokenizer
1399 * @brief a string tokenizer to fetch an integer
1400 * @param Source StringBuffer to read from
1401 * @param pStart Cursor on the tokenstring
1402 * @param separator tokenizer character
1403 * @returns 0 if not found, else integer representation of the token
1405 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1415 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1422 * @ingroup StrBuf_NextTokenizer
1423 * @brief a string tokenizer to fetch a long integer
1424 * @param Source StringBuffer to read from
1425 * @param pStart Cursor on the tokenstring
1426 * @param separator tokenizer character
1427 * @returns 0 if not found, else long integer representation of the token
1429 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1439 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1447 * @ingroup StrBuf_NextTokenizer
1448 * @brief a string tokenizer to fetch an unsigned long
1449 * @param Source StringBuffer to read from
1450 * @param pStart Cursor on the tokenstring
1451 * @param separator tokenizer character
1452 * @returns 0 if not found, else unsigned long representation of the token
1454 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1465 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1469 return (unsigned long) atol(pnum);
1479 /*******************************************************************************
1480 * Escape Appending *
1481 *******************************************************************************/
1484 * @ingroup StrBuf_DeEnCoder
1485 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1486 * @param OutBuf the output buffer
1487 * @param In Buffer to encode
1488 * @param PlainIn way in from plain old c strings
1490 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1492 const char *pch, *pche;
1496 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1498 if (PlainIn != NULL) {
1499 len = strlen(PlainIn);
1505 pche = pch + In->BufUsed;
1512 pt = OutBuf->buf + OutBuf->BufUsed;
1513 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1515 while (pch < pche) {
1517 IncreaseBuf(OutBuf, 1, -1);
1518 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1519 pt = OutBuf->buf + OutBuf->BufUsed;
1522 if((*pch >= 'a' && *pch <= 'z') ||
1523 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1524 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1525 (*pch == '!') || (*pch == '_') ||
1526 (*pch == ',') || (*pch == '.') ||
1534 *(pt + 1) = HexList[(unsigned char)*pch][0];
1535 *(pt + 2) = HexList[(unsigned char)*pch][1];
1537 OutBuf->BufUsed += 3;
1545 * @ingroup StrBuf_DeEnCoder
1546 * @brief Append a string, escaping characters which have meaning in HTML.
1548 * @param Target target buffer
1549 * @param Source source buffer; set to NULL if you just have a C-String
1550 * @param PlainIn Plain-C string to append; set to NULL if unused
1551 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1552 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1553 * if set to 2, linebreaks are replaced by <br/>
1555 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1557 const char *aptr, *eiptr;
1561 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1564 if (PlainIn != NULL) {
1566 len = strlen(PlainIn);
1571 eiptr = aptr + Source->BufUsed;
1572 len = Source->BufUsed;
1578 bptr = Target->buf + Target->BufUsed;
1579 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1581 while (aptr < eiptr){
1583 IncreaseBuf(Target, 1, -1);
1584 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1585 bptr = Target->buf + Target->BufUsed;
1588 memcpy(bptr, "<", 4);
1590 Target->BufUsed += 4;
1592 else if (*aptr == '>') {
1593 memcpy(bptr, ">", 4);
1595 Target->BufUsed += 4;
1597 else if (*aptr == '&') {
1598 memcpy(bptr, "&", 5);
1600 Target->BufUsed += 5;
1602 else if (*aptr == '"') {
1603 memcpy(bptr, """, 6);
1605 Target->BufUsed += 6;
1607 else if (*aptr == '\'') {
1608 memcpy(bptr, "'", 5);
1610 Target->BufUsed += 5;
1612 else if (*aptr == LB) {
1617 else if (*aptr == RB) {
1622 else if (*aptr == QU) {
1627 else if ((*aptr == 32) && (nbsp == 1)) {
1628 memcpy(bptr, " ", 6);
1630 Target->BufUsed += 6;
1632 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1633 *bptr='\0'; /* nothing */
1635 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1636 memcpy(bptr, "<br/>", 11);
1638 Target->BufUsed += 11;
1642 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1643 *bptr='\0'; /* nothing */
1653 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1655 return Target->BufUsed;
1659 * @ingroup StrBuf_DeEnCoder
1660 * @brief Append a string, escaping characters which have meaning in HTML.
1661 * Converts linebreaks into blanks; escapes single quotes
1662 * @param Target target buffer
1663 * @param Source source buffer; set to NULL if you just have a C-String
1664 * @param PlainIn Plain-C string to append; set to NULL if unused
1666 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1668 const char *aptr, *eiptr;
1672 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1675 if (PlainIn != NULL) {
1677 len = strlen(PlainIn);
1682 eiptr = aptr + Source->BufUsed;
1683 len = Source->BufUsed;
1689 eptr = Target->buf + Target->BufSize - 8;
1690 tptr = Target->buf + Target->BufUsed;
1692 while (aptr < eiptr){
1694 IncreaseBuf(Target, 1, -1);
1695 eptr = Target->buf + Target->BufSize - 8;
1696 tptr = Target->buf + Target->BufUsed;
1699 if (*aptr == '\n') {
1703 else if (*aptr == '\r') {
1707 else if (*aptr == '\'') {
1713 Target->BufUsed += 5;
1726 * @ingroup StrBuf_DeEnCoder
1727 * @brief Append a string, escaping characters which have meaning in ICAL.
1729 * @param Target target buffer
1730 * @param Source source buffer; set to NULL if you just have a C-String
1731 * @param PlainIn Plain-C string to append; set to NULL if unused
1733 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1735 const char *aptr, *eiptr;
1739 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1742 if (PlainIn != NULL) {
1744 len = strlen(PlainIn);
1749 eiptr = aptr + Source->BufUsed;
1750 len = Source->BufUsed;
1756 eptr = Target->buf + Target->BufSize - 8;
1757 tptr = Target->buf + Target->BufUsed;
1759 while (aptr < eiptr){
1760 if(tptr + 3 >= eptr) {
1761 IncreaseBuf(Target, 1, -1);
1762 eptr = Target->buf + Target->BufSize - 8;
1763 tptr = Target->buf + Target->BufUsed;
1766 if (*aptr == '\n') {
1773 else if (*aptr == '\r') {
1780 else if (*aptr == ',') {
1796 * @ingroup StrBuf_DeEnCoder
1797 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1799 * @param Target target buffer
1800 * @param Source source buffer; set to NULL if you just have a C-String
1801 * @param PlainIn Plain-C string to append; set to NULL if unused
1802 * @returns size of result or -1
1804 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1806 const char *aptr, *eiptr;
1810 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1813 if (PlainIn != NULL) {
1815 len = strlen(PlainIn);
1820 eiptr = aptr + Source->BufUsed;
1821 len = Source->BufUsed;
1827 bptr = Target->buf + Target->BufUsed;
1828 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1830 while (aptr < eiptr){
1832 IncreaseBuf(Target, 1, -1);
1833 eptr = Target->buf + Target->BufSize - 3;
1834 bptr = Target->buf + Target->BufUsed;
1841 Target->BufUsed += 2;
1842 } else if (*aptr == '\\') {
1847 Target->BufUsed += 2;
1857 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1859 return Target->BufUsed;
1863 * @ingroup StrBuf_DeEnCoder
1864 * @brief Append a string, escaping characters which have meaning in HTML + json.
1866 * @param Target target buffer
1867 * @param Source source buffer; set to NULL if you just have a C-String
1868 * @param PlainIn Plain-C string to append; set to NULL if unused
1869 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1870 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1871 * if set to 2, linebreaks are replaced by <br/>
1873 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1875 const char *aptr, *eiptr;
1878 int IsUtf8Sequence = 0;
1880 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1883 if (PlainIn != NULL) {
1885 len = strlen(PlainIn);
1890 eiptr = aptr + Source->BufUsed;
1891 len = Source->BufUsed;
1897 bptr = Target->buf + Target->BufUsed;
1898 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1900 while (aptr < eiptr){
1902 IncreaseBuf(Target, 1, -1);
1903 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1904 bptr = Target->buf + Target->BufUsed;
1907 memcpy(bptr, "<", 4);
1909 Target->BufUsed += 4;
1911 else if (*aptr == '>') {
1912 memcpy(bptr, ">", 4);
1914 Target->BufUsed += 4;
1916 else if (*aptr == '&') {
1917 memcpy(bptr, "&", 5);
1919 Target->BufUsed += 5;
1921 else if (*aptr == LB) {
1926 else if (*aptr == RB) {
1931 else if ((*aptr == 32) && (nbsp == 1)) {
1932 memcpy(bptr, " ", 6);
1934 Target->BufUsed += 6;
1936 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1937 *bptr='\0'; /* nothing */
1939 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1940 memcpy(bptr, "<br/>", 11);
1942 Target->BufUsed += 11;
1945 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1946 *bptr='\0'; /* nothing */
1949 else if ((*aptr == '"') || (*aptr == QU)) {
1954 Target->BufUsed += 2;
1955 } else if (*aptr == '\\') {
1960 Target->BufUsed += 2;
1963 if (((unsigned char)*aptr) >= 0x20)
1965 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1969 while (IsUtf8Sequence > 1){
1970 if(bptr + IsUtf8Sequence >= eptr) {
1971 IncreaseBuf(Target, 1, -1);
1972 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1973 bptr = Target->buf + Target->BufUsed - 1;
1987 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1989 return Target->BufUsed;
1993 * @ingroup StrBuf_DeEnCoder
1994 * @brief unhide special chars hidden to the HTML escaper
1995 * @param target buffer to put the unescaped string in
1996 * @param source buffer to unescape
1998 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2004 FlushStrBuf(target);
2006 if (source == NULL ||target == NULL)
2011 len = source->BufUsed;
2012 for (a = 0; a < len; ++a) {
2013 if (target->BufUsed >= target->BufSize)
2014 IncreaseBuf(target, 1, -1);
2016 if (source->buf[a] == '=') {
2017 hex[0] = source->buf[a + 1];
2018 hex[1] = source->buf[a + 2];
2021 sscanf(hex, "%02x", &b);
2022 target->buf[target->BufUsed] = b;
2023 target->buf[++target->BufUsed] = 0;
2027 target->buf[target->BufUsed] = source->buf[a];
2028 target->buf[++target->BufUsed] = 0;
2035 * @ingroup StrBuf_DeEnCoder
2036 * @brief hide special chars from the HTML escapers and friends
2037 * @param target buffer to put the escaped string in
2038 * @param source buffer to escape
2040 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2045 FlushStrBuf(target);
2047 if (source == NULL ||target == NULL)
2052 len = source->BufUsed;
2053 for (i=0; i<len; ++i) {
2054 if (target->BufUsed + 4 >= target->BufSize)
2055 IncreaseBuf(target, 1, -1);
2056 if ( (isalnum(source->buf[i])) ||
2057 (source->buf[i]=='-') ||
2058 (source->buf[i]=='_') ) {
2059 target->buf[target->BufUsed++] = source->buf[i];
2062 sprintf(&target->buf[target->BufUsed],
2064 (0xFF &source->buf[i]));
2065 target->BufUsed += 3;
2068 target->buf[target->BufUsed + 1] = '\0';
2072 /*******************************************************************************
2073 * Quoted Printable de/encoding *
2074 *******************************************************************************/
2077 * @ingroup StrBuf_DeEnCoder
2078 * @brief decode a buffer from base 64 encoding; destroys original
2079 * @param Buf Buffor to transform
2081 int StrBufDecodeBase64(StrBuf *Buf)
2085 if (Buf == NULL) return -1;
2087 xferbuf = (char*) malloc(Buf->BufSize);
2088 siz = CtdlDecodeBase64(xferbuf,
2098 * @ingroup StrBuf_DeEnCoder
2099 * @brief decode a buffer from base 64 encoding; destroys original
2100 * @param Buf Buffor to transform
2102 int StrBufDecodeHex(StrBuf *Buf)
2105 char *pch, *pche, *pchi;
2107 if (Buf == NULL) return -1;
2109 pch = pchi = Buf->buf;
2110 pche = pch + Buf->BufUsed;
2112 while (pchi < pche){
2113 ch = decode_hex(pchi);
2120 Buf->BufUsed = pch - Buf->buf;
2121 return Buf->BufUsed;
2125 * @ingroup StrBuf_DeEnCoder
2126 * @brief replace all chars >0x20 && < 0x7F with Mute
2127 * @param Mute char to put over invalid chars
2128 * @param Buf Buffor to transform
2130 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2134 if (Buf == NULL) return -1;
2135 pch = (unsigned char *)Buf->buf;
2136 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2137 if ((*pch < 0x20) || (*pch > 0x7F))
2141 return Buf->BufUsed;
2146 * @ingroup StrBuf_DeEnCoder
2147 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2148 * @param Buf Buffer to translate
2149 * @param StripBlanks Reduce several blanks to one?
2151 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2157 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2158 Buf->buf[Buf->BufUsed - 1] = '\0';
2163 while (a < Buf->BufUsed) {
2164 if (Buf->buf[a] == '+')
2166 else if (Buf->buf[a] == '%') {
2167 /* don't let % chars through, rather truncate the input. */
2168 if (a + 2 > Buf->BufUsed) {
2173 hex[0] = Buf->buf[a + 1];
2174 hex[1] = Buf->buf[a + 2];
2177 sscanf(hex, "%02x", &b);
2178 Buf->buf[a] = (char) b;
2179 len = Buf->BufUsed - a - 2;
2181 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2193 * @ingroup StrBuf_DeEnCoder
2194 * @brief RFC2047-encode a header field if necessary.
2195 * If no non-ASCII characters are found, the string
2196 * will be copied verbatim without encoding.
2198 * @param target Target buffer.
2199 * @param source Source string to be encoded.
2200 * @returns encoded length; -1 if non success.
2202 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2204 const char headerStr[] = "=?UTF-8?Q?";
2205 int need_to_encode = 0;
2209 if ((source == NULL) ||
2213 while ((i < source->BufUsed) &&
2214 (!IsEmptyStr (&source->buf[i])) &&
2215 (need_to_encode == 0)) {
2216 if (((unsigned char) source->buf[i] < 32) ||
2217 ((unsigned char) source->buf[i] > 126)) {
2223 if (!need_to_encode) {
2224 if (*target == NULL) {
2225 *target = NewStrBufPlain(source->buf, source->BufUsed);
2228 FlushStrBuf(*target);
2229 StrBufAppendBuf(*target, source, 0);
2231 return (*target)->BufUsed;
2233 if (*target == NULL)
2234 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2235 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2236 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2237 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2238 (*target)->BufUsed = sizeof(headerStr) - 1;
2239 for (i=0; (i < source->BufUsed); ++i) {
2240 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2241 IncreaseBuf(*target, 1, 0);
2242 ch = (unsigned char) source->buf[i];
2243 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2244 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2245 (*target)->BufUsed += 3;
2248 (*target)->buf[(*target)->BufUsed] = ch;
2249 (*target)->BufUsed++;
2253 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2254 IncreaseBuf(*target, 1, 0);
2256 (*target)->buf[(*target)->BufUsed++] = '?';
2257 (*target)->buf[(*target)->BufUsed++] = '=';
2258 (*target)->buf[(*target)->BufUsed] = '\0';
2259 return (*target)->BufUsed;;
2264 * @brief replaces all occurances of 'search' by 'replace'
2265 * @param buf Buffer to modify
2266 * @param search character to search
2267 * @param replace character to replace search by
2269 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2274 for (i=0; i<buf->BufUsed; i++)
2275 if (buf->buf[i] == search)
2276 buf->buf[i] = replace;
2281 /*******************************************************************************
2282 * Iconv Wrapper; RFC822 de/encoding *
2283 *******************************************************************************/
2286 * @ingroup StrBuf_DeEnCoder
2287 * @brief Wrapper around iconv_open()
2288 * Our version adds aliases for non-standard Microsoft charsets
2289 * such as 'MS950', aliasing them to names like 'CP950'
2291 * @param tocode Target encoding
2292 * @param fromcode Source encoding
2293 * @param pic anonimized pointer to iconv struct
2295 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2298 iconv_t ic = (iconv_t)(-1) ;
2299 ic = iconv_open(tocode, fromcode);
2300 if (ic == (iconv_t)(-1) ) {
2301 char alias_fromcode[64];
2302 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2303 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2304 alias_fromcode[0] = 'C';
2305 alias_fromcode[1] = 'P';
2306 ic = iconv_open(tocode, alias_fromcode);
2309 *(iconv_t *)pic = ic;
2315 * @ingroup StrBuf_DeEnCoder
2316 * @brief find one chunk of a RFC822 encoded string
2317 * @param Buffer where to search
2318 * @param bptr where to start searching
2319 * @returns found position, NULL if none.
2321 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2324 /* Find the next ?Q? */
2325 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2328 end = strchr(bptr + 2, '?');
2333 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2334 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2335 (*(end + 2) == '?')) {
2336 /* skip on to the end of the cluster, the next ?= */
2337 end = strstr(end + 3, "?=");
2340 /* sort of half valid encoding, try to find an end. */
2341 end = strstr(bptr, "?=");
2347 * @brief swaps the contents of two StrBufs
2348 * this is to be used to have cheap switched between a work-buffer and a target buffer
2349 * @param A First one
2350 * @param B second one
2352 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2356 memcpy(&C, A, sizeof(*A));
2357 memcpy(A, B, sizeof(*B));
2358 memcpy(B, &C, sizeof(C));
2364 * @ingroup StrBuf_DeEnCoder
2365 * @brief convert one buffer according to the preselected iconv pointer PIC
2366 * @param ConvertBuf buffer we need to translate
2367 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2368 * @param pic Pointer to the iconv-session Object
2370 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2376 char *ibuf; /**< Buffer of characters to be converted */
2377 char *obuf; /**< Buffer for converted characters */
2378 size_t ibuflen; /**< Length of input buffer */
2379 size_t obuflen; /**< Length of output buffer */
2382 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2383 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2384 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2386 ic = *(iconv_t*)pic;
2387 ibuf = ConvertBuf->buf;
2388 ibuflen = ConvertBuf->BufUsed;
2390 obuflen = TmpBuf->BufSize;
2392 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2395 if (errno == E2BIG) {
2397 IncreaseBuf(TmpBuf, 0, 0);
2402 else if (errno == EILSEQ){
2403 /* hm, invalid utf8 sequence... what to do now? */
2404 /* An invalid multibyte sequence has been encountered in the input */
2406 else if (errno == EINVAL) {
2407 /* An incomplete multibyte sequence has been encountered in the input. */
2410 FlushStrBuf(TmpBuf);
2413 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2414 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2416 /* little card game: wheres the red lady? */
2417 SwapBuffers(ConvertBuf, TmpBuf);
2418 FlushStrBuf(TmpBuf);
2425 * @ingroup StrBuf_DeEnCoder
2426 * @brief catches one RFC822 encoded segment, and decodes it.
2427 * @param Target buffer to fill with result
2428 * @param DecodeMe buffer with stuff to process
2429 * @param SegmentStart points to our current segment in DecodeMe
2430 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2431 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2432 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2433 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2435 inline static void DecodeSegment(StrBuf *Target,
2436 const StrBuf *DecodeMe,
2440 StrBuf *ConvertBuf2,
2441 StrBuf *FoundCharset)
2447 iconv_t ic = (iconv_t)(-1);
2451 /* Now we handle foreign character sets properly encoded
2452 * in RFC2047 format.
2454 StaticBuf.buf = SegmentStart;
2455 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2456 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2457 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2458 if (FoundCharset != NULL) {
2459 FlushStrBuf(FoundCharset);
2460 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2462 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2463 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2465 *encoding = toupper(*encoding);
2466 if (*encoding == 'B') { /**< base64 */
2467 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2469 ConvertBuf->BufUsed);
2471 else if (*encoding == 'Q') { /**< quoted-printable */
2475 while (pos < ConvertBuf->BufUsed)
2477 if (ConvertBuf->buf[pos] == '_')
2478 ConvertBuf->buf[pos] = ' ';
2482 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2485 ConvertBuf->BufUsed);
2488 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2491 ctdl_iconv_open("UTF-8", charset, &ic);
2492 if (ic != (iconv_t)(-1) ) {
2494 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2495 StrBufAppendBuf(Target, ConvertBuf2, 0);
2500 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2506 * @ingroup StrBuf_DeEnCoder
2507 * @brief Handle subjects with RFC2047 encoding such as:
2508 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2509 * @param Target where to put the decoded string to
2510 * @param DecodeMe buffer with encoded string
2511 * @param DefaultCharset if we don't find one, which should we use?
2512 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2513 * put it here for later use where no string might be known.
2515 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2517 StrBuf *DecodedInvalidBuf = NULL;
2518 StrBuf *ConvertBuf, *ConvertBuf2;
2519 const StrBuf *DecodeMee = DecodeMe;
2520 char *start, *end, *next, *nextend, *ptr = NULL;
2522 iconv_t ic = (iconv_t)(-1) ;
2527 int illegal_non_rfc2047_encoding = 0;
2529 /* Sometimes, badly formed messages contain strings which were simply
2530 * written out directly in some foreign character set instead of
2531 * using RFC2047 encoding. This is illegal but we will attempt to
2532 * handle it anyway by converting from a user-specified default
2533 * charset to UTF-8 if we see any nonprintable characters.
2536 len = StrLength(DecodeMe);
2537 for (i=0; i<DecodeMe->BufUsed; ++i) {
2538 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2539 illegal_non_rfc2047_encoding = 1;
2544 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2545 if ((illegal_non_rfc2047_encoding) &&
2546 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2547 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2550 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2551 if (ic != (iconv_t)(-1) ) {
2552 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2553 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2554 DecodeMee = DecodedInvalidBuf;
2560 /* pre evaluate the first pair */
2561 nextend = end = NULL;
2562 len = StrLength(DecodeMee);
2563 start = strstr(DecodeMee->buf, "=?");
2564 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2566 end = FindNextEnd (DecodeMee, start);
2568 StrBufAppendBuf(Target, DecodeMee, 0);
2569 FreeStrBuf(&ConvertBuf);
2570 FreeStrBuf(&DecodedInvalidBuf);
2574 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2576 if (start != DecodeMee->buf) {
2579 nFront = start - DecodeMee->buf;
2580 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2584 * Since spammers will go to all sorts of absurd lengths to get their
2585 * messages through, there are LOTS of corrupt headers out there.
2586 * So, prevent a really badly formed RFC2047 header from throwing
2587 * this function into an infinite loop.
2589 while ((start != NULL) &&
2596 DecodeSegment(Target,
2604 next = strstr(end, "=?");
2606 if ((next != NULL) &&
2608 nextend = FindNextEnd(DecodeMee, next);
2609 if (nextend == NULL)
2612 /* did we find two partitions */
2613 if ((next != NULL) &&
2617 while ((ptr < next) &&
2623 /* did we find a gab just filled with blanks? */
2626 long gap = next - start;
2631 /* now terminate the gab at the end */
2632 delta = (next - end) - 2; ////TODO: const!
2633 ((StrBuf*)DecodeMee)->BufUsed -= delta;
2634 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
2636 /* move next to its new location. */
2641 /* our next-pair is our new first pair now. */
2647 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2648 if ((end != NULL) && (end < nextend)) {
2650 while ( (ptr < nextend) &&
2657 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2659 FreeStrBuf(&ConvertBuf);
2660 FreeStrBuf(&ConvertBuf2);
2661 FreeStrBuf(&DecodedInvalidBuf);
2664 /*******************************************************************************
2665 * Manipulating UTF-8 Strings *
2666 *******************************************************************************/
2670 * @brief evaluate the length of an utf8 special character sequence
2671 * @param Char the character to examine
2672 * @returns width of utf8 chars in bytes
2674 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2679 while ((n < 8) && ((test & *CharS) != 0)) {
2683 if ((n > 6) || ((CharE - CharS) < n))
2690 * @brief detect whether this char starts an utf-8 encoded char
2691 * @param Char character to inspect
2692 * @returns yes or no
2694 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2696 /** 11??.???? indicates an UTF8 Sequence. */
2697 return ((Char & 0xC0) != 0);
2702 * @brief measure the number of glyphs in an UTF8 string...
2703 * @param Buf string to measure
2704 * @returns the number of glyphs in Buf
2706 long StrBuf_Utf8StrLen(StrBuf *Buf)
2712 if ((Buf == NULL) || (Buf->BufUsed == 0))
2715 eptr = Buf->buf + Buf->BufUsed;
2716 while ((aptr < eptr) && (*aptr != '\0')) {
2717 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2718 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2719 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2732 * @brief cuts a string after maxlen glyphs
2733 * @param Buf string to cut to maxlen glyphs
2734 * @param maxlen how long may the string become?
2735 * @returns current length of the string
2737 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2743 eptr = Buf->buf + Buf->BufUsed;
2744 while ((aptr < eptr) && (*aptr != '\0')) {
2745 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2746 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2747 while ((*aptr++ != '\0') && (m-- > 0));
2756 Buf->BufUsed = aptr - Buf->buf;
2757 return Buf->BufUsed;
2760 return Buf->BufUsed;
2768 /*******************************************************************************
2770 *******************************************************************************/
2773 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2774 #define OS_CODE 0x03 /*< unix */
2777 * @ingroup StrBuf_DeEnCoder
2778 * @brief uses the same calling syntax as compress2(), but it
2779 * creates a stream compatible with HTTP "Content-encoding: gzip"
2780 * @param dest compressed buffer
2781 * @param destLen length of the compresed data
2782 * @param source source to encode
2783 * @param sourceLen length of source to encode
2784 * @param level compression level
2786 int ZEXPORT compress_gzip(Bytef * dest,
2788 const Bytef * source,
2792 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2794 /* write gzip header */
2795 snprintf((char *) dest, *destLen,
2796 "%c%c%c%c%c%c%c%c%c%c",
2797 gz_magic[0], gz_magic[1], Z_DEFLATED,
2798 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2801 /* normal deflate */
2804 stream.next_in = (Bytef *) source;
2805 stream.avail_in = (uInt) sourceLen;
2806 stream.next_out = dest + 10L; // after header
2807 stream.avail_out = (uInt) * destLen;
2808 if ((uLong) stream.avail_out != *destLen)
2811 stream.zalloc = (alloc_func) 0;
2812 stream.zfree = (free_func) 0;
2813 stream.opaque = (voidpf) 0;
2815 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2816 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2820 err = deflate(&stream, Z_FINISH);
2821 if (err != Z_STREAM_END) {
2822 deflateEnd(&stream);
2823 return err == Z_OK ? Z_BUF_ERROR : err;
2825 *destLen = stream.total_out + 10L;
2827 /* write CRC and Length */
2828 uLong crc = crc32(0L, source, sourceLen);
2830 for (n = 0; n < 4; ++n, ++*destLen) {
2831 dest[*destLen] = (int) (crc & 0xff);
2834 uLong len = stream.total_in;
2835 for (n = 0; n < 4; ++n, ++*destLen) {
2836 dest[*destLen] = (int) (len & 0xff);
2839 err = deflateEnd(&stream);
2846 * @ingroup StrBuf_DeEnCoder
2847 * @brief compress the buffer with gzip
2848 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2849 * @param Buf buffer whose content is to be gzipped
2851 int CompressBuffer(StrBuf *Buf)
2854 char *compressed_data = NULL;
2855 size_t compressed_len, bufsize;
2858 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2859 compressed_data = malloc(compressed_len);
2861 if (compressed_data == NULL)
2863 /* Flush some space after the used payload so valgrind shuts up... */
2864 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2865 Buf->buf[Buf->BufUsed + i++] = '\0';
2866 if (compress_gzip((Bytef *) compressed_data,
2869 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2872 Buf->buf = compressed_data;
2873 Buf->BufUsed = compressed_len;
2874 Buf->BufSize = bufsize;
2875 /* Flush some space after the used payload so valgrind shuts up... */
2877 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2878 Buf->buf[Buf->BufUsed + i++] = '\0';
2881 free(compressed_data);
2883 #endif /* HAVE_ZLIB */
2889 /*******************************************************************************
2890 * File I/O; Prefer buffered read since its faster! *
2891 *******************************************************************************/
2894 * @ingroup StrBuf_IO
2895 * @brief Read a line from socket
2896 * flushes and closes the FD on error
2897 * @param buf the buffer to get the input to
2898 * @param fd pointer to the filedescriptor to read
2899 * @param append Append to an existing string or replace?
2900 * @param Error strerror() on error
2901 * @returns numbers of chars read
2903 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
2905 int len, rlen, slen;
2910 slen = len = buf->BufUsed;
2912 rlen = read(*fd, &buf->buf[len], 1);
2914 *Error = strerror(errno);
2921 if (buf->buf[len] == '\n')
2923 if (buf->buf[len] != '\r')
2925 if (len + 2 >= buf->BufSize) {
2927 buf->buf[len+1] = '\0';
2928 IncreaseBuf(buf, 1, -1);
2932 buf->buf[len] = '\0';
2937 * @ingroup StrBuf_BufferedIO
2938 * @brief Read a line from socket
2939 * flushes and closes the FD on error
2940 * @param Line the line to read from the fd / I/O Buffer
2941 * @param buf the buffer to get the input to
2942 * @param fd pointer to the filedescriptor to read
2943 * @param timeout number of successless selects until we bail out
2944 * @param selectresolution how long to wait on each select
2945 * @param Error strerror() on error
2946 * @returns numbers of chars read
2948 int StrBufTCP_read_buffered_line(StrBuf *Line,
2952 int selectresolution,
2956 int nSuccessLess = 0;
2963 if (buf->BufUsed > 0) {
2964 pch = strchr(buf->buf, '\n');
2967 len = pch - buf->buf;
2968 if (len > 0 && (*(pch - 1) == '\r') )
2970 StrBufSub(Line, buf, 0, len - rlen);
2971 StrBufCutLeft(buf, len + 1);
2976 if (buf->BufSize - buf->BufUsed < 10)
2977 IncreaseBuf(buf, 1, -1);
2979 fdflags = fcntl(*fd, F_GETFL);
2980 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2982 while ((nSuccessLess < timeout) && (pch == NULL)) {
2984 tv.tv_sec = selectresolution;
2989 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
2990 *Error = strerror(errno);
2996 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3001 &buf->buf[buf->BufUsed],
3002 buf->BufSize - buf->BufUsed - 1);
3004 *Error = strerror(errno);
3009 else if (rlen > 0) {
3011 buf->BufUsed += rlen;
3012 buf->buf[buf->BufUsed] = '\0';
3013 if (buf->BufUsed + 10 > buf->BufSize) {
3014 IncreaseBuf(buf, 1, -1);
3016 pch = strchr(buf->buf, '\n');
3023 len = pch - buf->buf;
3024 if (len > 0 && (*(pch - 1) == '\r') )
3026 StrBufSub(Line, buf, 0, len - rlen);
3027 StrBufCutLeft(buf, len + 1);
3034 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3035 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3036 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3038 * @ingroup StrBuf_BufferedIO
3039 * @brief Read a line from socket
3040 * flushes and closes the FD on error
3041 * @param Line Line to read from the fd / I/O Buffer
3042 * @param IOBuf the buffer to get the input to
3043 * @param Pos pointer to the current read position, should be NULL initialized!
3044 * @param fd pointer to the filedescriptor to read
3045 * @param timeout number of successless selects until we bail out
3046 * @param selectresolution how long to wait on each select
3047 * @param Error strerror() on error
3048 * @returns numbers of chars read
3050 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3055 int selectresolution,
3058 const char *pche = NULL;
3059 const char *pos = NULL;
3061 int nSuccessLess = 0;
3063 const char *pch = NULL;
3068 if ((Line == NULL) ||
3075 *Error = ErrRBLF_PreConditionFailed;
3080 if ((IOBuf->BufUsed > 0) &&
3082 (pos < IOBuf->buf + IOBuf->BufUsed))
3084 pche = IOBuf->buf + IOBuf->BufUsed;
3086 while ((pch < pche) && (*pch != '\n'))
3088 if ((pch >= pche) || (*pch == '\0'))
3090 if ((pch != NULL) &&
3095 if (len > 0 && (*(pch - 1) == '\r') )
3097 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
3107 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
3111 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
3112 IncreaseBuf(IOBuf, 1, -1);
3116 fdflags = fcntl(*fd, F_GETFL);
3117 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3120 while ((nSuccessLess < timeout) &&
3130 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3131 *Error = strerror(errno);
3135 *Error = ErrRBLF_SelectFailed;
3138 if (! FD_ISSET(*fd, &rfds) != 0) {
3144 &IOBuf->buf[IOBuf->BufUsed],
3145 IOBuf->BufSize - IOBuf->BufUsed - 1);
3147 *Error = strerror(errno);
3152 else if (rlen > 0) {
3154 IOBuf->BufUsed += rlen;
3155 IOBuf->buf[IOBuf->BufUsed] = '\0';
3156 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
3157 IncreaseBuf(IOBuf, 1, -1);
3161 pche = IOBuf->buf + IOBuf->BufUsed;
3163 while ((pch < pche) && (*pch != '\n'))
3165 if ((pch >= pche) || (*pch == '\0'))
3174 if (len > 0 && (*(pch - 1) == '\r') )
3176 StrBufSub(Line, IOBuf, 0, len - rlen);
3177 *Pos = pos + len + 1;
3180 *Error = ErrRBLF_NotEnoughSentFromServer;
3185 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3187 * @ingroup StrBuf_IO
3188 * @brief Input binary data from socket
3189 * flushes and closes the FD on error
3190 * @param Buf the buffer to get the input to
3191 * @param fd pointer to the filedescriptor to read
3192 * @param append Append to an existing string or replace?
3193 * @param nBytes the maximal number of bytes to read
3194 * @param Error strerror() on error
3195 * @returns numbers of chars read
3197 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3200 int len, rlen, slen;
3208 if ((Buf == NULL) || (*fd == -1))
3210 *Error = ErrRBLF_BLOBPreConditionFailed;
3215 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3216 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3218 ptr = Buf->buf + Buf->BufUsed;
3220 slen = len = Buf->BufUsed;
3222 fdflags = fcntl(*fd, F_GETFL);
3223 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3225 while ((nRead < nBytes) &&
3235 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3236 *Error = strerror(errno);
3240 *Error = ErrRBLF_SelectFailed;
3243 if (! FD_ISSET(*fd, &rfds) != 0) {
3249 if ((rlen = read(*fd,
3251 nBytes - nRead)) == -1) {
3254 *Error = strerror(errno);
3259 Buf->BufUsed += rlen;
3261 Buf->buf[Buf->BufUsed] = '\0';
3265 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3266 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3268 * @ingroup StrBuf_BufferedIO
3269 * @brief Input binary data from socket
3270 * flushes and closes the FD on error
3271 * @param Blob put binary thing here
3272 * @param IOBuf the buffer to get the input to
3273 * @param Pos offset inside of IOBuf
3274 * @param fd pointer to the filedescriptor to read
3275 * @param append Append to an existing string or replace?
3276 * @param nBytes the maximal number of bytes to read
3277 * @param check whether we should search for '000\n' terminators in case of timeouts
3278 * @param Error strerror() on error
3279 * @returns numbers of chars read
3281 int StrBufReadBLOBBuffered(StrBuf *Blob,
3298 int nAlreadyRead = 0;
3306 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3310 *Error = ErrRBB_BLOBFPreConditionFailed;
3316 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3317 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3322 len = pos - IOBuf->buf;
3323 rlen = IOBuf->BufUsed - len;
3326 if ((IOBuf->BufUsed > 0) &&
3328 (pos < IOBuf->buf + IOBuf->BufUsed))
3330 pche = IOBuf->buf + IOBuf->BufUsed;
3333 if (rlen < nBytes) {
3334 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3335 Blob->BufUsed += rlen;
3336 Blob->buf[Blob->BufUsed] = '\0';
3337 nAlreadyRead = nRead = rlen;
3340 if (rlen >= nBytes) {
3341 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3342 Blob->BufUsed += nBytes;
3343 Blob->buf[Blob->BufUsed] = '\0';
3344 if (rlen == nBytes) {
3356 if (IOBuf->BufSize < nBytes - nRead)
3357 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3360 slen = len = Blob->BufUsed;
3362 fdflags = fcntl(*fd, F_GETFL);
3363 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3368 while ((nRead < nBytes) &&
3377 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3378 *Error = strerror(errno);
3382 *Error = ErrRBLF_SelectFailed;
3385 if (! FD_ISSET(*fd, &rfds) != 0) {
3397 *Error = strerror(errno);
3400 else if (rlen == 0){
3402 if ((check == NNN_TERM) &&
3404 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3406 StrBufPlain(Blob, HKEY("\n000\n"));
3407 StrBufCutRight(Blob, 5);
3408 return Blob->BufUsed;
3410 if (nSelects > 10) {
3412 *Error = ErrRBB_too_many_selects;
3416 else if (rlen > 0) {
3419 IOBuf->BufUsed += rlen;
3422 if (nRead > nBytes) {
3423 *Pos = IOBuf->buf + nBytes;
3425 Blob->buf[Blob->BufUsed] = '\0';
3426 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3430 return nRead + nAlreadyRead;
3434 * @ingroup StrBuf_IO
3435 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3436 * @param LineBuf your line will be copied here.
3437 * @param Buf BLOB with lines of text...
3438 * @param Ptr moved arround to keep the next-line across several iterations
3439 * has to be &NULL on start; will be &NotNULL on end of buffer
3440 * @returns size of copied buffer
3442 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3444 const char *aptr, *ptr, *eptr;
3447 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3448 *Ptr = StrBufNOTNULL;
3452 FlushStrBuf(LineBuf);
3454 ptr = aptr = Buf->buf;
3458 optr = LineBuf->buf;
3459 eptr = Buf->buf + Buf->BufUsed;
3460 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3462 while ((ptr <= eptr) &&
3469 LineBuf->BufUsed = optr - LineBuf->buf;
3470 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3471 optr = LineBuf->buf + LineBuf->BufUsed;
3472 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3476 if ((ptr >= eptr) && (optr > LineBuf->buf))
3478 LineBuf->BufUsed = optr - LineBuf->buf;
3480 if ((ptr <= eptr) && (*ptr == '\r'))
3482 if ((ptr <= eptr) && (*ptr == '\n'))
3489 *Ptr = StrBufNOTNULL;
3492 return Buf->BufUsed - (ptr - Buf->buf);
3497 * @ingroup StrBuf_IO
3498 * @brief removes double slashes from pathnames
3499 * @param Dir directory string to filter
3500 * @param RemoveTrailingSlash allows / disallows trailing slashes
3502 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3508 while (!IsEmptyStr(a)) {
3520 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3525 Dir->BufUsed = b - Dir->buf;