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)
220 * @brief swaps the contents of two StrBufs
221 * this is to be used to have cheap switched between a work-buffer and a target buffer
223 * @param B second one
225 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
229 memcpy(&C, A, sizeof(*A));
230 memcpy(A, B, sizeof(*B));
231 memcpy(B, &C, sizeof(C));
236 * @ingroup StrBuf_Cast
237 * @brief Cast operator to Plain String
238 * @note if the buffer is altered by StrBuf operations, this pointer may become
239 * invalid. So don't lean on it after altering the buffer!
240 * Since this operation is considered cheap, rather call it often than risking
241 * your pointer to become invalid!
242 * @param Str the string we want to get the c-string representation for
243 * @returns the Pointer to the Content. Don't mess with it!
245 inline const char *ChrPtr(const StrBuf *Str)
253 * @ingroup StrBuf_Cast
254 * @brief since we know strlen()'s result, provide it here.
255 * @param Str the string to return the length to
256 * @returns contentlength of the buffer
258 inline int StrLength(const StrBuf *Str)
260 return (Str != NULL) ? Str->BufUsed : 0;
264 * @ingroup StrBuf_DeConstructors
265 * @brief local utility function to resize the buffer
266 * @param Buf the buffer whichs storage we should increase
267 * @param KeepOriginal should we copy the original buffer or just start over with a new one
268 * @param DestSize what should fit in after?
270 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
273 size_t NewSize = Buf->BufSize * 2;
279 while (NewSize <= DestSize)
282 NewBuf= (char*) malloc(NewSize);
286 if (KeepOriginal && (Buf->BufUsed > 0))
288 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
297 Buf->BufSize = NewSize;
299 dbg_IncreaseBuf(Buf);
305 * @ingroup StrBuf_DeConstructors
306 * @brief shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
307 * @param Buf Buffer to shrink (has to be empty)
308 * @param ThreshHold if the buffer is bigger then this, its readjusted
309 * @param NewSize if we Shrink it, how big are we going to be afterwards?
311 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
314 (Buf->BufUsed == 0) &&
315 (Buf->BufSize < ThreshHold)) {
317 Buf->buf = (char*) malloc(NewSize);
319 Buf->BufSize = NewSize;
324 * @ingroup StrBuf_DeConstructors
325 * @brief shrink long term buffers to their real size so they don't waste memory
326 * @param Buf buffer to shrink
327 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
328 * @returns physical size of the buffer
330 long StrBufShrinkToFit(StrBuf *Buf, int Force)
335 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
337 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
338 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
339 Buf->BufSize = Buf->BufUsed + 1;
347 * @ingroup StrBuf_DeConstructors
348 * @brief Allocate a new buffer with default buffer size
349 * @returns the new stringbuffer
351 StrBuf* NewStrBuf(void)
355 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
356 NewBuf->buf = (char*) malloc(BaseStrBufSize);
357 NewBuf->buf[0] = '\0';
358 NewBuf->BufSize = BaseStrBufSize;
360 NewBuf->ConstBuf = 0;
368 * @ingroup StrBuf_DeConstructors
369 * @brief Copy Constructor; returns a duplicate of CopyMe
370 * @param CopyMe Buffer to faxmilate
371 * @returns the new stringbuffer
373 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
380 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
381 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
382 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
383 NewBuf->BufUsed = CopyMe->BufUsed;
384 NewBuf->BufSize = CopyMe->BufSize;
385 NewBuf->ConstBuf = 0;
393 * @ingroup StrBuf_DeConstructors
394 * @brief Copy Constructor; CreateRelpaceMe will contain CopyFlushMe afterwards.
395 * @param NoMe if non-NULL, we will use that buffer as value; KeepOriginal will abused as len.
396 * @param CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
397 * @param CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe
398 * @param KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
399 * @returns the new stringbuffer
401 void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, const char *NoMe, int KeepOriginal)
405 if (CreateRelpaceMe == NULL)
410 if (*CreateRelpaceMe != NULL)
411 StrBufPlain(*CreateRelpaceMe, NoMe, KeepOriginal);
413 *CreateRelpaceMe = NewStrBufPlain(NoMe, KeepOriginal);
417 if (CopyFlushMe == NULL)
419 if (*CreateRelpaceMe != NULL)
420 FlushStrBuf(*CreateRelpaceMe);
422 *CreateRelpaceMe = NewStrBuf();
427 * Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
428 * else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
429 * be a big IO-Buffer...
431 if (KeepOriginal || (StrLength(CopyFlushMe) < 256))
433 if (*CreateRelpaceMe == NULL)
435 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
440 NewBuf = *CreateRelpaceMe;
443 StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
447 if (*CreateRelpaceMe == NULL)
449 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
453 NewBuf = *CreateRelpaceMe;
454 SwapBuffers (NewBuf, CopyFlushMe);
457 FlushStrBuf(CopyFlushMe);
462 * @ingroup StrBuf_DeConstructors
463 * @brief create a new Buffer using an existing c-string
464 * this function should also be used if you want to pre-suggest
465 * the buffer size to allocate in conjunction with ptr == NULL
466 * @param ptr the c-string to copy; may be NULL to create a blank instance
467 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
468 * @returns the new stringbuffer
470 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
473 size_t Siz = BaseStrBufSize;
476 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
478 CopySize = strlen((ptr != NULL)?ptr:"");
482 while (Siz <= CopySize)
485 NewBuf->buf = (char*) malloc(Siz);
486 if (NewBuf->buf == NULL)
491 NewBuf->BufSize = Siz;
493 memcpy(NewBuf->buf, ptr, CopySize);
494 NewBuf->buf[CopySize] = '\0';
495 NewBuf->BufUsed = CopySize;
498 NewBuf->buf[0] = '\0';
501 NewBuf->ConstBuf = 0;
509 * @ingroup StrBuf_DeConstructors
510 * @brief Set an existing buffer from a c-string
511 * @param Buf buffer to load
512 * @param ptr c-string to put into
513 * @param nChars set to -1 if we should work 0-terminated
514 * @returns the new length of the string
516 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
531 CopySize = strlen(ptr);
535 while (Siz <= CopySize)
538 if (Siz != Buf->BufSize)
539 IncreaseBuf(Buf, 0, Siz);
540 memcpy(Buf->buf, ptr, CopySize);
541 Buf->buf[CopySize] = '\0';
542 Buf->BufUsed = CopySize;
549 * @ingroup StrBuf_DeConstructors
550 * @brief use strbuf as wrapper for a string constant for easy handling
551 * @param StringConstant a string to wrap
552 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
554 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
558 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
559 NewBuf->buf = (char*) StringConstant;
560 NewBuf->BufSize = SizeOfStrConstant;
561 NewBuf->BufUsed = SizeOfStrConstant;
562 NewBuf->ConstBuf = 1;
571 * @ingroup StrBuf_DeConstructors
572 * @brief flush the content of a Buf; keep its struct
573 * @param buf Buffer to flush
575 int FlushStrBuf(StrBuf *buf)
587 * @ingroup StrBuf_DeConstructors
588 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
589 * @param buf Buffer to wipe
591 int FLUSHStrBuf(StrBuf *buf)
597 if (buf->BufUsed > 0) {
598 memset(buf->buf, 0, buf->BufUsed);
605 int hFreeDbglog = -1;
608 * @ingroup StrBuf_DeConstructors
609 * @brief Release a Buffer
610 * Its a double pointer, so it can NULL your pointer
611 * so fancy SIG11 appear instead of random results
612 * @param FreeMe Pointer Pointer to the buffer to free
614 void FreeStrBuf (StrBuf **FreeMe)
619 dbg_FreeStrBuf(FreeMe, 'F');
621 if (!(*FreeMe)->ConstBuf)
622 free((*FreeMe)->buf);
628 * @ingroup StrBuf_DeConstructors
629 * @brief flatten a Buffer to the Char * we return
630 * Its a double pointer, so it can NULL your pointer
631 * so fancy SIG11 appear instead of random results
632 * The Callee then owns the buffer and is responsible for freeing it.
633 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
634 * @returns the pointer of the buffer; Callee owns the memory thereafter.
636 char *SmashStrBuf (StrBuf **SmashMe)
640 if ((SmashMe == NULL) || (*SmashMe == NULL))
643 dbg_FreeStrBuf(SmashMe, 'S');
645 Ret = (*SmashMe)->buf;
652 * @ingroup StrBuf_DeConstructors
653 * @brief Release the buffer
654 * If you want put your StrBuf into a Hash, use this as Destructor.
655 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
657 void HFreeStrBuf (void *VFreeMe)
659 StrBuf *FreeMe = (StrBuf*)VFreeMe;
663 dbg_FreeStrBuf(SmashMe, 'H');
665 if (!FreeMe->ConstBuf)
671 /*******************************************************************************
672 * Simple string transformations *
673 *******************************************************************************/
677 * @brief Wrapper around atol
679 long StrTol(const StrBuf *Buf)
684 return atol(Buf->buf);
691 * @brief Wrapper around atoi
693 int StrToi(const StrBuf *Buf)
697 if (Buf->BufUsed > 0)
698 return atoi(Buf->buf);
705 * @brief Checks to see if the string is a pure number
706 * @param Buf The buffer to inspect
707 * @returns 1 if its a pure number, 0, if not.
709 int StrBufIsNumber(const StrBuf *Buf) {
711 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
714 strtoll(Buf->buf, &pEnd, 10);
715 if (pEnd == Buf->buf)
717 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
719 if (Buf->buf == pEnd)
725 * @ingroup StrBuf_Filler
726 * @brief modifies a Single char of the Buf
727 * You can point to it via char* or a zero-based integer
728 * @param Buf The buffer to manipulate
729 * @param ptr char* to zero; use NULL if unused
730 * @param nThChar zero based pointer into the string; use -1 if unused
731 * @param PeekValue The Character to place into the position
733 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
738 nThChar = ptr - Buf->buf;
739 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
741 Buf->buf[nThChar] = PeekValue;
746 * @ingroup StrBuf_Filler
747 * @brief modifies a range of chars of the Buf
748 * You can point to it via char* or a zero-based integer
749 * @param Buf The buffer to manipulate
750 * @param ptr char* to zero; use NULL if unused
751 * @param nThChar zero based pointer into the string; use -1 if unused
752 * @param nChars how many chars are to be flushed?
753 * @param PookValue The Character to place into that area
755 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
760 nThChar = ptr - Buf->buf;
761 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
763 if (nThChar + nChars > Buf->BufUsed)
764 nChars = Buf->BufUsed - nThChar;
766 memset(Buf->buf + nThChar, PookValue, nChars);
767 /* just to be shure... */
768 Buf->buf[Buf->BufUsed] = 0;
773 * @ingroup StrBuf_Filler
774 * @brief Append a StringBuffer to the buffer
775 * @param Buf Buffer to modify
776 * @param AppendBuf Buffer to copy at the end of our buffer
777 * @param Offset Should we start copying from an offset?
779 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
781 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
784 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
787 AppendBuf->BufUsed + Buf->BufUsed);
789 memcpy(Buf->buf + Buf->BufUsed,
790 AppendBuf->buf + Offset,
791 AppendBuf->BufUsed - Offset);
792 Buf->BufUsed += AppendBuf->BufUsed - Offset;
793 Buf->buf[Buf->BufUsed] = '\0';
798 * @ingroup StrBuf_Filler
799 * @brief Append a C-String to the buffer
800 * @param Buf Buffer to modify
801 * @param AppendBuf Buffer to copy at the end of our buffer
802 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
803 * @param Offset Should we start copying from an offset?
805 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
808 long BufSizeRequired;
810 if ((AppendBuf == NULL) || (Buf == NULL))
814 aps = strlen(AppendBuf + Offset);
816 aps = AppendSize - Offset;
818 BufSizeRequired = Buf->BufUsed + aps + 1;
819 if (Buf->BufSize <= BufSizeRequired)
820 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
822 memcpy(Buf->buf + Buf->BufUsed,
826 Buf->buf[Buf->BufUsed] = '\0';
830 * @ingroup StrBuf_Filler
831 * @brief sprintf like function appending the formated string to the buffer
832 * vsnprintf version to wrap into own calls
833 * @param Buf Buffer to extend by format and Params
834 * @param format printf alike format to add
835 * @param ap va_list containing the items for format
837 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
845 if ((Buf == NULL) || (format == NULL))
848 BufSize = Buf->BufSize;
849 nWritten = Buf->BufSize + 1;
850 Offset = Buf->BufUsed;
851 newused = Offset + nWritten;
853 while (newused >= BufSize) {
855 nWritten = vsnprintf(Buf->buf + Offset,
856 Buf->BufSize - Offset,
859 newused = Offset + nWritten;
860 if (newused >= Buf->BufSize) {
861 IncreaseBuf(Buf, 1, newused);
862 newused = Buf->BufSize + 1;
865 Buf->BufUsed = Offset + nWritten;
866 BufSize = Buf->BufSize;
873 * @ingroup StrBuf_Filler
874 * @brief sprintf like function appending the formated string to the buffer
875 * @param Buf Buffer to extend by format and Params
876 * @param format printf alike format to add
878 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
886 if ((Buf == NULL) || (format == NULL))
889 BufSize = Buf->BufSize;
890 nWritten = Buf->BufSize + 1;
891 Offset = Buf->BufUsed;
892 newused = Offset + nWritten;
894 while (newused >= BufSize) {
895 va_start(arg_ptr, format);
896 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
897 Buf->BufSize - Buf->BufUsed,
900 newused = Buf->BufUsed + nWritten;
901 if (newused >= Buf->BufSize) {
902 IncreaseBuf(Buf, 1, newused);
903 newused = Buf->BufSize + 1;
906 Buf->BufUsed += nWritten;
907 BufSize = Buf->BufSize;
914 * @ingroup StrBuf_Filler
915 * @brief sprintf like function putting the formated string into the buffer
916 * @param Buf Buffer to extend by format and Parameters
917 * @param format printf alike format to add
919 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
924 if ((Buf == NULL) || (format == NULL))
927 nWritten = Buf->BufSize + 1;
928 while (nWritten >= Buf->BufSize) {
929 va_start(arg_ptr, format);
930 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
932 if (nWritten >= Buf->BufSize) {
933 IncreaseBuf(Buf, 0, 0);
934 nWritten = Buf->BufSize + 1;
937 Buf->BufUsed = nWritten ;
942 * @ingroup StrBuf_Filler
943 * @brief Callback for cURL to append the webserver reply to a buffer
944 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
945 * @param size pre-defined by the cURL API; see man 3 curl for mre info
946 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
947 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
949 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
958 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
965 * @brief extracts a substring from Source into dest
966 * @param dest buffer to place substring into
967 * @param Source string to copy substring from
968 * @param Offset chars to skip from start
969 * @param nChars number of chars to copy
970 * @returns the number of chars copied; may be different from nChars due to the size of Source
972 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
975 if (Offset > Source->BufUsed)
981 if (Offset + nChars < Source->BufUsed)
983 if (nChars >= dest->BufSize)
984 IncreaseBuf(dest, 0, nChars + 1);
985 memcpy(dest->buf, Source->buf + Offset, nChars);
986 dest->BufUsed = nChars;
987 dest->buf[dest->BufUsed] = '\0';
990 NCharsRemain = Source->BufUsed - Offset;
991 if (NCharsRemain >= dest->BufSize)
992 IncreaseBuf(dest, 0, NCharsRemain + 1);
993 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
994 dest->BufUsed = NCharsRemain;
995 dest->buf[dest->BufUsed] = '\0';
1001 * @brief Cut nChars from the start of the string
1002 * @param Buf Buffer to modify
1003 * @param nChars how many chars should be skipped?
1005 void StrBufCutLeft(StrBuf *Buf, int nChars)
1007 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1008 if (nChars >= Buf->BufUsed) {
1012 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1013 Buf->BufUsed -= nChars;
1014 Buf->buf[Buf->BufUsed] = '\0';
1019 * @brief Cut the trailing n Chars from the string
1020 * @param Buf Buffer to modify
1021 * @param nChars how many chars should be trunkated?
1023 void StrBufCutRight(StrBuf *Buf, int nChars)
1025 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1026 if (nChars >= Buf->BufUsed) {
1030 Buf->BufUsed -= nChars;
1031 Buf->buf[Buf->BufUsed] = '\0';
1036 * @brief Cut the string after n Chars
1037 * @param Buf Buffer to modify
1038 * @param AfternChars after how many chars should we trunkate the string?
1039 * @param At if non-null and points inside of our string, cut it there.
1041 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1043 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1045 AfternChars = At - Buf->buf;
1048 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1050 Buf->BufUsed = AfternChars;
1051 Buf->buf[Buf->BufUsed] = '\0';
1057 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1058 * @param Buf the string to modify
1060 void StrBufTrim(StrBuf *Buf)
1063 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1065 while ((Buf->BufUsed > 0) &&
1066 isspace(Buf->buf[Buf->BufUsed - 1]))
1070 Buf->buf[Buf->BufUsed] = '\0';
1072 if (Buf->BufUsed == 0) return;
1074 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1077 if (delta > 0) StrBufCutLeft(Buf, delta);
1081 * @brief changes all spaces in the string (tab, linefeed...) to Blank (0x20)
1082 * @param Buf the string to modify
1084 void StrBufSpaceToBlank(StrBuf *Buf)
1088 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1091 pche = pch + Buf->BufUsed;
1100 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
1108 pLeft = pBuff = Buf->buf;
1109 while (pBuff != NULL) {
1111 pBuff = strchr(pBuff, leftboundary);
1120 pRight = strchr(pBuff, rightboundary);
1122 StrBufCutAt(Buf, 0, pRight);
1124 StrBufCutLeft(Buf, pLeft - Buf->buf);
1129 * @ingroup StrBuf_Filler
1130 * @brief uppercase the contents of a buffer
1131 * @param Buf the buffer to translate
1133 void StrBufUpCase(StrBuf *Buf)
1137 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1140 pche = pch + Buf->BufUsed;
1141 while (pch < pche) {
1142 *pch = toupper(*pch);
1149 * @ingroup StrBuf_Filler
1150 * @brief lowercase the contents of a buffer
1151 * @param Buf the buffer to translate
1153 void StrBufLowerCase(StrBuf *Buf)
1157 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1160 pche = pch + Buf->BufUsed;
1161 while (pch < pche) {
1162 *pch = tolower(*pch);
1168 /*******************************************************************************
1169 * a tokenizer that kills, maims, and destroys *
1170 *******************************************************************************/
1173 * @ingroup StrBuf_Tokenizer
1174 * @brief Replace a token at a given place with a given length by another token with given length
1175 * @param Buf String where to work on
1176 * @param where where inside of the Buf is the search-token
1177 * @param HowLong How long is the token to be replaced
1178 * @param Repl Token to insert at 'where'
1179 * @param ReplLen Length of repl
1180 * @returns -1 if fail else length of resulting Buf
1182 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1183 const char *Repl, long ReplLen)
1186 if ((Buf == NULL) ||
1187 (where > Buf->BufUsed) ||
1188 (where + HowLong > Buf->BufUsed))
1191 if (where + ReplLen - HowLong > Buf->BufSize)
1192 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1195 memmove(Buf->buf + where + ReplLen,
1196 Buf->buf + where + HowLong,
1197 Buf->BufUsed - where - HowLong);
1199 memcpy(Buf->buf + where,
1202 Buf->BufUsed += ReplLen - HowLong;
1204 return Buf->BufUsed;
1208 * @ingroup StrBuf_Tokenizer
1209 * @brief Counts the numbmer of tokens in a buffer
1210 * @param source String to count tokens in
1211 * @param tok Tokenizer char to count
1212 * @returns numbers of tokenizer chars found
1214 int StrBufNum_tokens(const StrBuf *source, char tok)
1218 if ((source == NULL) || (source->BufUsed == 0))
1220 if ((source->BufUsed == 1) && (*source->buf == tok))
1224 pche = pch + source->BufUsed;
1235 * @ingroup StrBuf_Tokenizer
1236 * @brief a string tokenizer
1237 * @param Source StringBuffer to read into
1238 * @param parmnum n'th Parameter to remove
1239 * @param separator tokenizer character
1240 * @returns -1 if not found, else length of token.
1242 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1245 char *d, *s, *end; /* dest, source */
1248 /* Find desired @parameter */
1249 end = Source->buf + Source->BufUsed;
1251 while ((d <= end) &&
1254 /* End of string, bail! */
1259 if (*d == separator) {
1264 if ((d == NULL) || (d >= end))
1265 return 0; /* @Parameter not found */
1267 /* Find next @parameter */
1269 while ((s <= end) &&
1270 (*s && *s != separator))
1274 if (*s == separator)
1278 /* Hack and slash */
1283 memmove(d, s, Source->BufUsed - (s - Source->buf));
1284 Source->BufUsed += ReducedBy;
1285 Source->buf[Source->BufUsed] = '\0';
1287 else if (d == Source->buf) {
1289 Source->BufUsed = 0;
1293 Source->BufUsed += ReducedBy;
1306 * @ingroup StrBuf_Tokenizer
1307 * @brief a string tokenizer
1308 * @param dest Destination StringBuffer
1309 * @param Source StringBuffer to read into
1310 * @param parmnum n'th Parameter to extract
1311 * @param separator tokenizer character
1312 * @returns -1 if not found, else length of token.
1314 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1316 const char *s, *e; //* source * /
1317 int len = 0; //* running total length of extracted string * /
1318 int current_token = 0; //* token currently being processed * /
1321 dest->buf[0] = '\0';
1327 if ((Source == NULL) || (Source->BufUsed ==0)) {
1331 e = s + Source->BufUsed;
1334 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1336 while ((s<e) && !IsEmptyStr(s)) {
1337 if (*s == separator) {
1340 if (len >= dest->BufSize) {
1341 dest->BufUsed = len;
1342 if (IncreaseBuf(dest, 1, -1) < 0) {
1347 if ( (current_token == parmnum) &&
1348 (*s != separator)) {
1349 dest->buf[len] = *s;
1352 else if (current_token > parmnum) {
1358 dest->buf[len] = '\0';
1359 dest->BufUsed = len;
1361 if (current_token < parmnum) {
1362 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1365 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1374 * @ingroup StrBuf_Tokenizer
1375 * @brief a string tokenizer to fetch an integer
1376 * @param Source String containing tokens
1377 * @param parmnum n'th Parameter to extract
1378 * @param separator tokenizer character
1379 * @returns 0 if not found, else integer representation of the token
1381 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1391 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1398 * @ingroup StrBuf_Tokenizer
1399 * @brief a string tokenizer to fetch a long integer
1400 * @param Source String containing tokens
1401 * @param parmnum n'th Parameter to extract
1402 * @param separator tokenizer character
1403 * @returns 0 if not found, else long integer representation of the token
1405 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1415 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1423 * @ingroup StrBuf_Tokenizer
1424 * @brief a string tokenizer to fetch an unsigned long
1425 * @param Source String containing tokens
1426 * @param parmnum n'th Parameter to extract
1427 * @param separator tokenizer character
1428 * @returns 0 if not found, else unsigned long representation of the token
1430 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1441 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1445 return (unsigned long) atol(pnum);
1454 * @ingroup StrBuf_NextTokenizer
1455 * @brief a string tokenizer; Bounds checker
1456 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1457 * @param Source our tokenbuffer
1458 * @param pStart the token iterator pointer to inspect
1459 * @returns whether the revolving pointer is inside of the search range
1461 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1463 if ((Source == NULL) ||
1464 (*pStart == StrBufNOTNULL) ||
1465 (Source->BufUsed == 0))
1469 if (*pStart == NULL)
1473 else if (*pStart > Source->buf + Source->BufUsed)
1477 else if (*pStart <= Source->buf)
1486 * @ingroup StrBuf_NextTokenizer
1487 * @brief a string tokenizer
1488 * @param dest Destination StringBuffer
1489 * @param Source StringBuffer to read into
1490 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1491 * @param separator tokenizer
1492 * @returns -1 if not found, else length of token.
1494 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1496 const char *s; /* source */
1497 const char *EndBuffer; /* end stop of source buffer */
1498 int current_token = 0; /* token currently being processed */
1499 int len = 0; /* running total length of extracted string */
1501 if ((Source == NULL) ||
1502 (Source->BufUsed == 0) )
1504 *pStart = StrBufNOTNULL;
1508 EndBuffer = Source->buf + Source->BufUsed;
1512 dest->buf[0] = '\0';
1517 *pStart = EndBuffer + 1;
1521 if (*pStart == NULL)
1523 *pStart = Source->buf; /* we're starting to examine this buffer. */
1525 else if ((*pStart < Source->buf) ||
1526 (*pStart > EndBuffer ) )
1528 return -1; /* no more tokens to find. */
1532 /* start to find the next token */
1533 while ((s <= EndBuffer) &&
1534 (current_token == 0) )
1536 if (*s == separator)
1538 /* we found the next token */
1542 if (len >= dest->BufSize)
1544 /* our Dest-buffer isn't big enough, increase it. */
1545 dest->BufUsed = len;
1547 if (IncreaseBuf(dest, 1, -1) < 0) {
1548 /* WHUT? no more mem? bail out. */
1555 if ( (current_token == 0 ) && /* are we in our target token? */
1556 (!IsEmptyStr(s) ) &&
1557 (separator != *s) ) /* don't copy the token itself */
1559 dest->buf[len] = *s; /* Copy the payload */
1560 ++len; /* remember the bigger size. */
1566 /* did we reach the end? */
1567 if ((s > EndBuffer)) {
1568 EndBuffer = StrBufNOTNULL;
1569 *pStart = EndBuffer;
1572 *pStart = s; /* remember the position for the next run */
1575 /* sanitize our extracted token */
1576 dest->buf[len] = '\0';
1577 dest->BufUsed = len;
1584 * @ingroup StrBuf_NextTokenizer
1585 * @brief a string tokenizer
1586 * @param Source StringBuffer to read from
1587 * @param pStart pointer to the end of the last token. Feed with NULL.
1588 * @param separator tokenizer character
1589 * @param nTokens number of tokens to fastforward over
1590 * @returns -1 if not found, else length of token.
1592 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1594 const char *s, *EndBuffer; //* source * /
1595 int len = 0; //* running total length of extracted string * /
1596 int current_token = 0; //* token currently being processed * /
1598 if ((Source == NULL) ||
1599 (Source->BufUsed ==0)) {
1603 return Source->BufUsed;
1605 if (*pStart == NULL)
1606 *pStart = Source->buf;
1608 EndBuffer = Source->buf + Source->BufUsed;
1610 if ((*pStart < Source->buf) ||
1611 (*pStart > EndBuffer)) {
1619 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1621 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1622 if (*s == separator) {
1625 if (current_token >= nTokens) {
1637 * @ingroup StrBuf_NextTokenizer
1638 * @brief a string tokenizer to fetch an integer
1639 * @param Source StringBuffer to read from
1640 * @param pStart Cursor on the tokenstring
1641 * @param separator tokenizer character
1642 * @returns 0 if not found, else integer representation of the token
1644 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1654 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1661 * @ingroup StrBuf_NextTokenizer
1662 * @brief a string tokenizer to fetch a long integer
1663 * @param Source StringBuffer to read from
1664 * @param pStart Cursor on the tokenstring
1665 * @param separator tokenizer character
1666 * @returns 0 if not found, else long integer representation of the token
1668 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1678 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1686 * @ingroup StrBuf_NextTokenizer
1687 * @brief a string tokenizer to fetch an unsigned long
1688 * @param Source StringBuffer to read from
1689 * @param pStart Cursor on the tokenstring
1690 * @param separator tokenizer character
1691 * @returns 0 if not found, else unsigned long representation of the token
1693 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1704 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1708 return (unsigned long) atol(pnum);
1718 /*******************************************************************************
1719 * Escape Appending *
1720 *******************************************************************************/
1723 * @ingroup StrBuf_DeEnCoder
1724 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1725 * @param OutBuf the output buffer
1726 * @param In Buffer to encode
1727 * @param PlainIn way in from plain old c strings
1729 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1731 const char *pch, *pche;
1735 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1737 if (PlainIn != NULL) {
1738 len = strlen(PlainIn);
1744 pche = pch + In->BufUsed;
1751 pt = OutBuf->buf + OutBuf->BufUsed;
1752 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1754 while (pch < pche) {
1756 IncreaseBuf(OutBuf, 1, -1);
1757 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1758 pt = OutBuf->buf + OutBuf->BufUsed;
1761 if((*pch >= 'a' && *pch <= 'z') ||
1762 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1763 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1764 (*pch == '!') || (*pch == '_') ||
1765 (*pch == ',') || (*pch == '.'))
1772 *(pt + 1) = HexList[(unsigned char)*pch][0];
1773 *(pt + 2) = HexList[(unsigned char)*pch][1];
1775 OutBuf->BufUsed += 3;
1783 * @ingroup StrBuf_DeEnCoder
1784 * @brief append a string in hex encoding to the buffer
1785 * @param OutBuf the output buffer
1786 * @param In Buffer to encode
1787 * @param PlainIn way in from plain old c strings
1789 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1791 const char *pch, *pche;
1795 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1797 if (PlainIn != NULL) {
1798 len = strlen(PlainIn);
1804 pche = pch + In->BufUsed;
1811 pt = OutBuf->buf + OutBuf->BufUsed;
1812 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1814 while (pch < pche) {
1816 IncreaseBuf(OutBuf, 1, -1);
1817 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1818 pt = OutBuf->buf + OutBuf->BufUsed;
1821 *pt = HexList[(unsigned char)*pch][0];
1823 *pt = HexList[(unsigned char)*pch][1];
1824 pt ++; pch ++; OutBuf->BufUsed += 2;
1830 * @ingroup StrBuf_DeEnCoder
1831 * @brief Append a string, escaping characters which have meaning in HTML.
1833 * @param Target target buffer
1834 * @param Source source buffer; set to NULL if you just have a C-String
1835 * @param PlainIn Plain-C string to append; set to NULL if unused
1836 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1837 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1838 * if set to 2, linebreaks are replaced by <br/>
1840 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1842 const char *aptr, *eiptr;
1846 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1849 if (PlainIn != NULL) {
1851 len = strlen(PlainIn);
1856 eiptr = aptr + Source->BufUsed;
1857 len = Source->BufUsed;
1863 bptr = Target->buf + Target->BufUsed;
1864 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1866 while (aptr < eiptr){
1868 IncreaseBuf(Target, 1, -1);
1869 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1870 bptr = Target->buf + Target->BufUsed;
1873 memcpy(bptr, "<", 4);
1875 Target->BufUsed += 4;
1877 else if (*aptr == '>') {
1878 memcpy(bptr, ">", 4);
1880 Target->BufUsed += 4;
1882 else if (*aptr == '&') {
1883 memcpy(bptr, "&", 5);
1885 Target->BufUsed += 5;
1887 else if (*aptr == '"') {
1888 memcpy(bptr, """, 6);
1890 Target->BufUsed += 6;
1892 else if (*aptr == '\'') {
1893 memcpy(bptr, "'", 5);
1895 Target->BufUsed += 5;
1897 else if (*aptr == LB) {
1902 else if (*aptr == RB) {
1907 else if (*aptr == QU) {
1912 else if ((*aptr == 32) && (nbsp == 1)) {
1913 memcpy(bptr, " ", 6);
1915 Target->BufUsed += 6;
1917 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1918 *bptr='\0'; /* nothing */
1920 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1921 memcpy(bptr, "<br/>", 11);
1923 Target->BufUsed += 11;
1927 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1928 *bptr='\0'; /* nothing */
1938 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1940 return Target->BufUsed;
1944 * @ingroup StrBuf_DeEnCoder
1945 * @brief Append a string, escaping characters which have meaning in HTML.
1946 * Converts linebreaks into blanks; escapes single quotes
1947 * @param Target target buffer
1948 * @param Source source buffer; set to NULL if you just have a C-String
1949 * @param PlainIn Plain-C string to append; set to NULL if unused
1951 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1953 const char *aptr, *eiptr;
1957 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1960 if (PlainIn != NULL) {
1962 len = strlen(PlainIn);
1967 eiptr = aptr + Source->BufUsed;
1968 len = Source->BufUsed;
1974 eptr = Target->buf + Target->BufSize - 8;
1975 tptr = Target->buf + Target->BufUsed;
1977 while (aptr < eiptr){
1979 IncreaseBuf(Target, 1, -1);
1980 eptr = Target->buf + Target->BufSize - 8;
1981 tptr = Target->buf + Target->BufUsed;
1984 if (*aptr == '\n') {
1988 else if (*aptr == '\r') {
1992 else if (*aptr == '\'') {
1998 Target->BufUsed += 5;
2011 * @ingroup StrBuf_DeEnCoder
2012 * @brief Append a string, escaping characters which have meaning in ICAL.
2014 * @param Target target buffer
2015 * @param Source source buffer; set to NULL if you just have a C-String
2016 * @param PlainIn Plain-C string to append; set to NULL if unused
2018 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2020 const char *aptr, *eiptr;
2024 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2027 if (PlainIn != NULL) {
2029 len = strlen(PlainIn);
2034 eiptr = aptr + Source->BufUsed;
2035 len = Source->BufUsed;
2041 eptr = Target->buf + Target->BufSize - 8;
2042 tptr = Target->buf + Target->BufUsed;
2044 while (aptr < eiptr){
2045 if(tptr + 3 >= eptr) {
2046 IncreaseBuf(Target, 1, -1);
2047 eptr = Target->buf + Target->BufSize - 8;
2048 tptr = Target->buf + Target->BufUsed;
2051 if (*aptr == '\n') {
2058 else if (*aptr == '\r') {
2065 else if (*aptr == ',') {
2081 * @ingroup StrBuf_DeEnCoder
2082 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
2084 * @param Target target buffer
2085 * @param Source source buffer; set to NULL if you just have a C-String
2086 * @param PlainIn Plain-C string to append; set to NULL if unused
2087 * @returns size of result or -1
2089 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2091 const char *aptr, *eiptr;
2095 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2098 if (PlainIn != NULL) {
2100 len = strlen(PlainIn);
2105 eiptr = aptr + Source->BufUsed;
2106 len = Source->BufUsed;
2112 bptr = Target->buf + Target->BufUsed;
2113 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
2115 while (aptr < eiptr){
2117 IncreaseBuf(Target, 1, -1);
2118 eptr = Target->buf + Target->BufSize - 3;
2119 bptr = Target->buf + Target->BufUsed;
2126 Target->BufUsed += 2;
2127 } else if (*aptr == '\\') {
2132 Target->BufUsed += 2;
2142 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2144 return Target->BufUsed;
2148 * @ingroup StrBuf_DeEnCoder
2149 * @brief Append a string, escaping characters which have meaning in HTML + json.
2151 * @param Target target buffer
2152 * @param Source source buffer; set to NULL if you just have a C-String
2153 * @param PlainIn Plain-C string to append; set to NULL if unused
2154 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2155 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2156 * if set to 2, linebreaks are replaced by <br/>
2158 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2160 const char *aptr, *eiptr;
2163 int IsUtf8Sequence = 0;
2165 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2168 if (PlainIn != NULL) {
2170 len = strlen(PlainIn);
2175 eiptr = aptr + Source->BufUsed;
2176 len = Source->BufUsed;
2182 bptr = Target->buf + Target->BufUsed;
2183 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2185 while (aptr < eiptr){
2187 IncreaseBuf(Target, 1, -1);
2188 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2189 bptr = Target->buf + Target->BufUsed;
2192 memcpy(bptr, "<", 4);
2194 Target->BufUsed += 4;
2196 else if (*aptr == '>') {
2197 memcpy(bptr, ">", 4);
2199 Target->BufUsed += 4;
2201 else if (*aptr == '&') {
2202 memcpy(bptr, "&", 5);
2204 Target->BufUsed += 5;
2206 else if (*aptr == LB) {
2211 else if (*aptr == RB) {
2216 else if ((*aptr == 32) && (nbsp == 1)) {
2217 memcpy(bptr, " ", 6);
2219 Target->BufUsed += 6;
2221 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2222 *bptr='\0'; /* nothing */
2224 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2225 memcpy(bptr, "<br/>", 11);
2227 Target->BufUsed += 11;
2230 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2231 *bptr='\0'; /* nothing */
2234 else if ((*aptr == '"') || (*aptr == QU)) {
2239 Target->BufUsed += 2;
2240 } else if (*aptr == '\\') {
2245 Target->BufUsed += 2;
2248 if (((unsigned char)*aptr) >= 0x20)
2250 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2254 while (IsUtf8Sequence > 1){
2255 if(bptr + IsUtf8Sequence >= eptr) {
2256 IncreaseBuf(Target, 1, -1);
2257 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2258 bptr = Target->buf + Target->BufUsed - 1;
2272 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2274 return Target->BufUsed;
2278 * @ingroup StrBuf_DeEnCoder
2279 * @brief unhide special chars hidden to the HTML escaper
2280 * @param target buffer to put the unescaped string in
2281 * @param source buffer to unescape
2283 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2289 FlushStrBuf(target);
2291 if (source == NULL ||target == NULL)
2296 len = source->BufUsed;
2297 for (a = 0; a < len; ++a) {
2298 if (target->BufUsed >= target->BufSize)
2299 IncreaseBuf(target, 1, -1);
2301 if (source->buf[a] == '=') {
2302 hex[0] = source->buf[a + 1];
2303 hex[1] = source->buf[a + 2];
2306 sscanf(hex, "%02x", &b);
2307 target->buf[target->BufUsed] = b;
2308 target->buf[++target->BufUsed] = 0;
2312 target->buf[target->BufUsed] = source->buf[a];
2313 target->buf[++target->BufUsed] = 0;
2320 * @ingroup StrBuf_DeEnCoder
2321 * @brief hide special chars from the HTML escapers and friends
2322 * @param target buffer to put the escaped string in
2323 * @param source buffer to escape
2325 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2330 FlushStrBuf(target);
2332 if (source == NULL ||target == NULL)
2337 len = source->BufUsed;
2338 for (i=0; i<len; ++i) {
2339 if (target->BufUsed + 4 >= target->BufSize)
2340 IncreaseBuf(target, 1, -1);
2341 if ( (isalnum(source->buf[i])) ||
2342 (source->buf[i]=='-') ||
2343 (source->buf[i]=='_') ) {
2344 target->buf[target->BufUsed++] = source->buf[i];
2347 sprintf(&target->buf[target->BufUsed],
2349 (0xFF &source->buf[i]));
2350 target->BufUsed += 3;
2353 target->buf[target->BufUsed + 1] = '\0';
2357 /*******************************************************************************
2358 * Quoted Printable de/encoding *
2359 *******************************************************************************/
2362 * @ingroup StrBuf_DeEnCoder
2363 * @brief decode a buffer from base 64 encoding; destroys original
2364 * @param Buf Buffor to transform
2366 int StrBufDecodeBase64(StrBuf *Buf)
2370 if (Buf == NULL) return -1;
2372 xferbuf = (char*) malloc(Buf->BufSize);
2374 siz = CtdlDecodeBase64(xferbuf,
2384 * @ingroup StrBuf_DeEnCoder
2385 * @brief decode a buffer from base 64 encoding; destroys original
2386 * @param Buf Buffor to transform
2388 int StrBufDecodeHex(StrBuf *Buf)
2391 char *pch, *pche, *pchi;
2393 if (Buf == NULL) return -1;
2395 pch = pchi = Buf->buf;
2396 pche = pch + Buf->BufUsed;
2398 while (pchi < pche){
2399 ch = decode_hex(pchi);
2406 Buf->BufUsed = pch - Buf->buf;
2407 return Buf->BufUsed;
2411 * @ingroup StrBuf_DeEnCoder
2412 * @brief replace all chars >0x20 && < 0x7F with Mute
2413 * @param Mute char to put over invalid chars
2414 * @param Buf Buffor to transform
2416 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2420 if (Buf == NULL) return -1;
2421 pch = (unsigned char *)Buf->buf;
2422 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2423 if ((*pch < 0x20) || (*pch > 0x7F))
2427 return Buf->BufUsed;
2432 * @ingroup StrBuf_DeEnCoder
2433 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2434 * @param Buf Buffer to translate
2435 * @param StripBlanks Reduce several blanks to one?
2437 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2446 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2447 Buf->buf[Buf->BufUsed - 1] = '\0';
2452 while (a < Buf->BufUsed) {
2453 if (Buf->buf[a] == '+')
2455 else if (Buf->buf[a] == '%') {
2456 /* don't let % chars through, rather truncate the input. */
2457 if (a + 2 > Buf->BufUsed) {
2462 hex[0] = Buf->buf[a + 1];
2463 hex[1] = Buf->buf[a + 2];
2466 sscanf(hex, "%02x", &b);
2467 Buf->buf[a] = (char) b;
2468 len = Buf->BufUsed - a - 2;
2470 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2482 * @ingroup StrBuf_DeEnCoder
2483 * @brief RFC2047-encode a header field if necessary.
2484 * If no non-ASCII characters are found, the string
2485 * will be copied verbatim without encoding.
2487 * @param target Target buffer.
2488 * @param source Source string to be encoded.
2489 * @returns encoded length; -1 if non success.
2491 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2493 const char headerStr[] = "=?UTF-8?Q?";
2494 int need_to_encode = 0;
2498 if ((source == NULL) ||
2502 while ((i < source->BufUsed) &&
2503 (!IsEmptyStr (&source->buf[i])) &&
2504 (need_to_encode == 0)) {
2505 if (((unsigned char) source->buf[i] < 32) ||
2506 ((unsigned char) source->buf[i] > 126)) {
2512 if (!need_to_encode) {
2513 if (*target == NULL) {
2514 *target = NewStrBufPlain(source->buf, source->BufUsed);
2517 FlushStrBuf(*target);
2518 StrBufAppendBuf(*target, source, 0);
2520 return (*target)->BufUsed;
2522 if (*target == NULL)
2523 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2524 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2525 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2526 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2527 (*target)->BufUsed = sizeof(headerStr) - 1;
2528 for (i=0; (i < source->BufUsed); ++i) {
2529 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2530 IncreaseBuf(*target, 1, 0);
2531 ch = (unsigned char) source->buf[i];
2532 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2533 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2534 (*target)->BufUsed += 3;
2537 (*target)->buf[(*target)->BufUsed] = ch;
2538 (*target)->BufUsed++;
2542 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2543 IncreaseBuf(*target, 1, 0);
2545 (*target)->buf[(*target)->BufUsed++] = '?';
2546 (*target)->buf[(*target)->BufUsed++] = '=';
2547 (*target)->buf[(*target)->BufUsed] = '\0';
2548 return (*target)->BufUsed;;
2553 static void AddRecipient(StrBuf *Target,
2555 StrBuf *EmailAddress,
2560 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2561 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2563 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
2564 StrBufRFC2047encode(&EncBuf, UserName);
2565 StrBufAppendBuf(Target, EncBuf, 0);
2566 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2567 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
2569 if (StrLength(EmailAddress) > 0){
2570 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2571 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2572 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2578 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2579 * \param Recp Source list of email recipients
2580 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2581 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2582 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2583 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2585 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp,
2587 StrBuf *EmailAddress,
2593 const char *pch, *pche;
2594 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2596 if ((Recp == NULL) || (StrLength(Recp) == 0))
2601 pche = pch + StrLength(Recp);
2603 if (!CheckEncode(pch, -1, pche))
2604 return NewStrBufDup(Recp);
2606 Target = NewStrBufPlain(NULL, StrLength(Recp));
2608 while ((pch != NULL) && (pch < pche))
2612 while (isspace(*pch)) pch++;
2613 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2615 if ((*pch == '"') || (*pch == '\'')) {
2616 UserStart = pch + 1;
2618 UserEnd = strchr(UserStart, *pch);
2619 if (UserEnd == NULL)
2620 break; ///TODO: Userfeedback??
2621 EmailStart = UserEnd + 1;
2622 while (isspace(*EmailStart))
2624 if (UserEnd == UserStart) {
2625 UserStart = UserEnd = NULL;
2628 if (*EmailStart == '<') {
2630 EmailEnd = strchr(EmailStart, '>');
2631 if (EmailEnd == NULL)
2632 EmailEnd = strchr(EmailStart, ',');
2636 EmailEnd = strchr(EmailStart, ',');
2638 if (EmailEnd == NULL)
2646 EmailEnd = strchr(UserStart, ',');
2647 if (EmailEnd == NULL) {
2648 EmailEnd = strchr(pch, '>');
2650 if (EmailEnd != NULL) {
2660 while ((EmailEnd > UserStart) && !gt &&
2661 ((*EmailEnd == ',') ||
2662 (*EmailEnd == '>') ||
2663 (isspace(*EmailEnd))))
2665 if (*EmailEnd == '>')
2670 if (EmailEnd == UserStart)
2674 EmailStart = strchr(UserStart, '<');
2675 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2677 UserEnd = EmailStart;
2679 while ((UserEnd > UserStart) &&
2680 isspace (*(UserEnd - 1)))
2683 if (UserStart >= UserEnd)
2684 UserStart = UserEnd = NULL;
2685 At = strchr(EmailStart, '@');
2687 else { /* this is a local recipient... no domain, just a realname */
2688 EmailStart = UserStart;
2689 At = strchr(EmailStart, '@');
2695 EmailStart = UserStart;
2701 if ((UserStart != NULL) && (UserEnd != NULL))
2702 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2703 else if ((UserStart != NULL) && (UserEnd == NULL))
2704 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2706 FlushStrBuf(UserName);
2708 if ((EmailStart != NULL) && (EmailEnd != NULL))
2709 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2710 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2711 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2713 FlushStrBuf(EmailAddress);
2715 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2720 if ((pch != NULL) && (*pch == ','))
2722 if (pch != NULL) while (isspace(*pch))
2731 * @brief replaces all occurances of 'search' by 'replace'
2732 * @param buf Buffer to modify
2733 * @param search character to search
2734 * @param replace character to replace search by
2736 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2741 for (i=0; i<buf->BufUsed; i++)
2742 if (buf->buf[i] == search)
2743 buf->buf[i] = replace;
2749 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2750 * @param buf Buffer to modify
2752 void StrBufToUnixLF(StrBuf *buf)
2754 char *pche, *pchS, *pchT;
2758 pche = buf->buf + buf->BufUsed;
2759 pchS = pchT = buf->buf;
2765 if (*pchS != '\n') {
2774 buf->BufUsed = pchT - buf->buf;
2778 /*******************************************************************************
2779 * Iconv Wrapper; RFC822 de/encoding *
2780 *******************************************************************************/
2783 * @ingroup StrBuf_DeEnCoder
2784 * @brief Wrapper around iconv_open()
2785 * Our version adds aliases for non-standard Microsoft charsets
2786 * such as 'MS950', aliasing them to names like 'CP950'
2788 * @param tocode Target encoding
2789 * @param fromcode Source encoding
2790 * @param pic anonimized pointer to iconv struct
2792 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2795 iconv_t ic = (iconv_t)(-1) ;
2796 ic = iconv_open(tocode, fromcode);
2797 if (ic == (iconv_t)(-1) ) {
2798 char alias_fromcode[64];
2799 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2800 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2801 alias_fromcode[0] = 'C';
2802 alias_fromcode[1] = 'P';
2803 ic = iconv_open(tocode, alias_fromcode);
2806 *(iconv_t *)pic = ic;
2812 * @ingroup StrBuf_DeEnCoder
2813 * @brief find one chunk of a RFC822 encoded string
2814 * @param Buffer where to search
2815 * @param bptr where to start searching
2816 * @returns found position, NULL if none.
2818 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2821 /* Find the next ?Q? */
2822 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2825 end = strchr(bptr + 2, '?');
2830 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2831 (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
2832 ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) &&
2833 (*(end + 2) == '?')) {
2834 /* skip on to the end of the cluster, the next ?= */
2835 end = strstr(end + 3, "?=");
2838 /* sort of half valid encoding, try to find an end. */
2839 end = strstr(bptr, "?=");
2846 * @ingroup StrBuf_DeEnCoder
2847 * @brief convert one buffer according to the preselected iconv pointer PIC
2848 * @param ConvertBuf buffer we need to translate
2849 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2850 * @param pic Pointer to the iconv-session Object
2852 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2858 char *ibuf; /**< Buffer of characters to be converted */
2859 char *obuf; /**< Buffer for converted characters */
2860 size_t ibuflen; /**< Length of input buffer */
2861 size_t obuflen; /**< Length of output buffer */
2864 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2865 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2866 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2868 ic = *(iconv_t*)pic;
2869 ibuf = ConvertBuf->buf;
2870 ibuflen = ConvertBuf->BufUsed;
2872 obuflen = TmpBuf->BufSize;
2874 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2877 if (errno == E2BIG) {
2879 IncreaseBuf(TmpBuf, 0, 0);
2884 else if (errno == EILSEQ){
2885 /* hm, invalid utf8 sequence... what to do now? */
2886 /* An invalid multibyte sequence has been encountered in the input */
2888 else if (errno == EINVAL) {
2889 /* An incomplete multibyte sequence has been encountered in the input. */
2892 FlushStrBuf(TmpBuf);
2895 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2896 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2898 /* little card game: wheres the red lady? */
2899 SwapBuffers(ConvertBuf, TmpBuf);
2900 FlushStrBuf(TmpBuf);
2907 * @ingroup StrBuf_DeEnCoder
2908 * @brief catches one RFC822 encoded segment, and decodes it.
2909 * @param Target buffer to fill with result
2910 * @param DecodeMe buffer with stuff to process
2911 * @param SegmentStart points to our current segment in DecodeMe
2912 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2913 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2914 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2915 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2917 inline static void DecodeSegment(StrBuf *Target,
2918 const StrBuf *DecodeMe,
2919 const char *SegmentStart,
2920 const char *SegmentEnd,
2922 StrBuf *ConvertBuf2,
2923 StrBuf *FoundCharset)
2929 iconv_t ic = (iconv_t)(-1);
2933 /* Now we handle foreign character sets properly encoded
2934 * in RFC2047 format.
2936 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2937 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2938 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2939 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2940 if (FoundCharset != NULL) {
2941 FlushStrBuf(FoundCharset);
2942 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2944 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2945 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2947 *encoding = toupper(*encoding);
2948 if (*encoding == 'B') { /**< base64 */
2949 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2950 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2951 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2953 ConvertBuf->BufUsed);
2955 else if (*encoding == 'Q') { /**< quoted-printable */
2959 while (pos < ConvertBuf->BufUsed)
2961 if (ConvertBuf->buf[pos] == '_')
2962 ConvertBuf->buf[pos] = ' ';
2966 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2967 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2969 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2972 ConvertBuf->BufUsed);
2975 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2978 ctdl_iconv_open("UTF-8", charset, &ic);
2979 if (ic != (iconv_t)(-1) ) {
2981 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2982 StrBufAppendBuf(Target, ConvertBuf2, 0);
2987 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2993 * @ingroup StrBuf_DeEnCoder
2994 * @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
2995 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2996 * @param Target where to put the decoded string to
2997 * @param DecodeMe buffer with encoded string
2998 * @param DefaultCharset if we don't find one, which should we use?
2999 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3000 * put it here for later use where no string might be known.
3002 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3005 StrBuf *ConvertBuf2;
3006 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3007 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3009 StrBuf_RFC822_2_Utf8(Target,
3015 FreeStrBuf(&ConvertBuf);
3016 FreeStrBuf(&ConvertBuf2);
3020 * @ingroup StrBuf_DeEnCoder
3021 * @brief Handle subjects with RFC2047 encoding such as:
3022 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3023 * @param Target where to put the decoded string to
3024 * @param DecodeMe buffer with encoded string
3025 * @param DefaultCharset if we don't find one, which should we use?
3026 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3027 * put it here for later use where no string might be known.
3028 * @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3029 * @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3031 void StrBuf_RFC822_2_Utf8(StrBuf *Target,
3032 const StrBuf *DecodeMe,
3033 const StrBuf* DefaultCharset,
3034 StrBuf *FoundCharset,
3036 StrBuf *ConvertBuf2)
3038 StrBuf *DecodedInvalidBuf = NULL;
3039 const StrBuf *DecodeMee = DecodeMe;
3040 const char *start, *end, *next, *nextend, *ptr = NULL;
3042 iconv_t ic = (iconv_t)(-1) ;
3047 int illegal_non_rfc2047_encoding = 0;
3049 /* Sometimes, badly formed messages contain strings which were simply
3050 * written out directly in some foreign character set instead of
3051 * using RFC2047 encoding. This is illegal but we will attempt to
3052 * handle it anyway by converting from a user-specified default
3053 * charset to UTF-8 if we see any nonprintable characters.
3056 len = StrLength(DecodeMe);
3057 for (i=0; i<DecodeMe->BufUsed; ++i) {
3058 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3059 illegal_non_rfc2047_encoding = 1;
3064 if ((illegal_non_rfc2047_encoding) &&
3065 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3066 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3069 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3070 if (ic != (iconv_t)(-1) ) {
3071 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3072 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3073 DecodeMee = DecodedInvalidBuf;
3079 /* pre evaluate the first pair */
3080 nextend = end = NULL;
3081 len = StrLength(DecodeMee);
3082 start = strstr(DecodeMee->buf, "=?");
3083 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3085 end = FindNextEnd (DecodeMee, start + 2);
3087 StrBufAppendBuf(Target, DecodeMee, 0);
3088 FreeStrBuf(&DecodedInvalidBuf);
3093 if (start != DecodeMee->buf) {
3096 nFront = start - DecodeMee->buf;
3097 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3101 * Since spammers will go to all sorts of absurd lengths to get their
3102 * messages through, there are LOTS of corrupt headers out there.
3103 * So, prevent a really badly formed RFC2047 header from throwing
3104 * this function into an infinite loop.
3106 while ((start != NULL) &&
3113 DecodeSegment(Target,
3121 next = strstr(end, "=?");
3123 if ((next != NULL) &&
3125 nextend = FindNextEnd(DecodeMee, next);
3126 if (nextend == NULL)
3129 /* did we find two partitions */
3130 if ((next != NULL) &&
3134 while ((ptr < next) &&
3141 * did we find a gab just filled with blanks?
3142 * if not, copy its stuff over.
3146 StrBufAppendBufPlain(Target,
3152 /* our next-pair is our new first pair now. */
3158 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3159 if ((end != NULL) && (end < nextend)) {
3161 while ( (ptr < nextend) &&
3168 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3170 FreeStrBuf(&DecodedInvalidBuf);
3173 /*******************************************************************************
3174 * Manipulating UTF-8 Strings *
3175 *******************************************************************************/
3179 * @brief evaluate the length of an utf8 special character sequence
3180 * @param Char the character to examine
3181 * @returns width of utf8 chars in bytes
3183 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3188 while ((n < 8) && ((test & *CharS) != 0)) {
3192 if ((n > 6) || ((CharE - CharS) < n))
3199 * @brief detect whether this char starts an utf-8 encoded char
3200 * @param Char character to inspect
3201 * @returns yes or no
3203 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3205 /** 11??.???? indicates an UTF8 Sequence. */
3206 return ((Char & 0xC0) != 0);
3211 * @brief measure the number of glyphs in an UTF8 string...
3212 * @param Buf string to measure
3213 * @returns the number of glyphs in Buf
3215 long StrBuf_Utf8StrLen(StrBuf *Buf)
3221 if ((Buf == NULL) || (Buf->BufUsed == 0))
3224 eptr = Buf->buf + Buf->BufUsed;
3225 while ((aptr < eptr) && (*aptr != '\0')) {
3226 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3227 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3228 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3241 * @brief cuts a string after maxlen glyphs
3242 * @param Buf string to cut to maxlen glyphs
3243 * @param maxlen how long may the string become?
3244 * @returns current length of the string
3246 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3252 eptr = Buf->buf + Buf->BufUsed;
3253 while ((aptr < eptr) && (*aptr != '\0')) {
3254 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3255 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3256 while ((*aptr++ != '\0') && (m-- > 0));
3265 Buf->BufUsed = aptr - Buf->buf;
3266 return Buf->BufUsed;
3269 return Buf->BufUsed;
3277 /*******************************************************************************
3279 *******************************************************************************/
3282 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3283 #define OS_CODE 0x03 /*< unix */
3286 * @ingroup StrBuf_DeEnCoder
3287 * @brief uses the same calling syntax as compress2(), but it
3288 * creates a stream compatible with HTTP "Content-encoding: gzip"
3289 * @param dest compressed buffer
3290 * @param destLen length of the compresed data
3291 * @param source source to encode
3292 * @param sourceLen length of source to encode
3293 * @param level compression level
3295 int ZEXPORT compress_gzip(Bytef * dest,
3297 const Bytef * source,
3301 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3303 /* write gzip header */
3304 snprintf((char *) dest, *destLen,
3305 "%c%c%c%c%c%c%c%c%c%c",
3306 gz_magic[0], gz_magic[1], Z_DEFLATED,
3307 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3310 /* normal deflate */
3313 stream.next_in = (Bytef *) source;
3314 stream.avail_in = (uInt) sourceLen;
3315 stream.next_out = dest + 10L; // after header
3316 stream.avail_out = (uInt) * destLen;
3317 if ((uLong) stream.avail_out != *destLen)
3320 stream.zalloc = (alloc_func) 0;
3321 stream.zfree = (free_func) 0;
3322 stream.opaque = (voidpf) 0;
3324 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3325 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3329 err = deflate(&stream, Z_FINISH);
3330 if (err != Z_STREAM_END) {
3331 deflateEnd(&stream);
3332 return err == Z_OK ? Z_BUF_ERROR : err;
3334 *destLen = stream.total_out + 10L;
3336 /* write CRC and Length */
3337 uLong crc = crc32(0L, source, sourceLen);
3339 for (n = 0; n < 4; ++n, ++*destLen) {
3340 dest[*destLen] = (int) (crc & 0xff);
3343 uLong len = stream.total_in;
3344 for (n = 0; n < 4; ++n, ++*destLen) {
3345 dest[*destLen] = (int) (len & 0xff);
3348 err = deflateEnd(&stream);
3355 * @ingroup StrBuf_DeEnCoder
3356 * @brief compress the buffer with gzip
3357 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3358 * @param Buf buffer whose content is to be gzipped
3360 int CompressBuffer(StrBuf *Buf)
3363 char *compressed_data = NULL;
3364 size_t compressed_len, bufsize;
3367 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3368 compressed_data = malloc(compressed_len);
3370 if (compressed_data == NULL)
3372 /* Flush some space after the used payload so valgrind shuts up... */
3373 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3374 Buf->buf[Buf->BufUsed + i++] = '\0';
3375 if (compress_gzip((Bytef *) compressed_data,
3378 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3381 Buf->buf = compressed_data;
3382 Buf->BufUsed = compressed_len;
3383 Buf->BufSize = bufsize;
3384 /* Flush some space after the used payload so valgrind shuts up... */
3386 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3387 Buf->buf[Buf->BufUsed + i++] = '\0';
3390 free(compressed_data);
3392 #endif /* HAVE_ZLIB */
3398 /*******************************************************************************
3399 * File I/O; Prefer buffered read since its faster! *
3400 *******************************************************************************/
3403 * @ingroup StrBuf_IO
3404 * @brief Read a line from socket
3405 * flushes and closes the FD on error
3406 * @param buf the buffer to get the input to
3407 * @param fd pointer to the filedescriptor to read
3408 * @param append Append to an existing string or replace?
3409 * @param Error strerror() on error
3410 * @returns numbers of chars read
3412 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3414 int len, rlen, slen;
3419 slen = len = buf->BufUsed;
3421 rlen = read(*fd, &buf->buf[len], 1);
3423 *Error = strerror(errno);
3430 if (buf->buf[len] == '\n')
3432 if (buf->buf[len] != '\r')
3434 if (len + 2 >= buf->BufSize) {
3436 buf->buf[len+1] = '\0';
3437 IncreaseBuf(buf, 1, -1);
3441 buf->buf[len] = '\0';
3446 * @ingroup StrBuf_BufferedIO
3447 * @brief Read a line from socket
3448 * flushes and closes the FD on error
3449 * @param Line the line to read from the fd / I/O Buffer
3450 * @param buf the buffer to get the input to
3451 * @param fd pointer to the filedescriptor to read
3452 * @param timeout number of successless selects until we bail out
3453 * @param selectresolution how long to wait on each select
3454 * @param Error strerror() on error
3455 * @returns numbers of chars read
3457 int StrBufTCP_read_buffered_line(StrBuf *Line,
3461 int selectresolution,
3465 int nSuccessLess = 0;
3472 if (buf->BufUsed > 0) {
3473 pch = strchr(buf->buf, '\n');
3476 len = pch - buf->buf;
3477 if (len > 0 && (*(pch - 1) == '\r') )
3479 StrBufSub(Line, buf, 0, len - rlen);
3480 StrBufCutLeft(buf, len + 1);
3485 if (buf->BufSize - buf->BufUsed < 10)
3486 IncreaseBuf(buf, 1, -1);
3488 fdflags = fcntl(*fd, F_GETFL);
3489 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3491 while ((nSuccessLess < timeout) && (pch == NULL)) {
3493 tv.tv_sec = selectresolution;
3498 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3499 *Error = strerror(errno);
3505 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3510 &buf->buf[buf->BufUsed],
3511 buf->BufSize - buf->BufUsed - 1);
3513 *Error = strerror(errno);
3518 else if (rlen > 0) {
3520 buf->BufUsed += rlen;
3521 buf->buf[buf->BufUsed] = '\0';
3522 if (buf->BufUsed + 10 > buf->BufSize) {
3523 IncreaseBuf(buf, 1, -1);
3525 pch = strchr(buf->buf, '\n');
3532 len = pch - buf->buf;
3533 if (len > 0 && (*(pch - 1) == '\r') )
3535 StrBufSub(Line, buf, 0, len - rlen);
3536 StrBufCutLeft(buf, len + 1);
3543 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3544 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3545 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3547 * @ingroup StrBuf_BufferedIO
3548 * @brief Read a line from socket
3549 * flushes and closes the FD on error
3550 * @param Line where to append our Line read from the fd / I/O Buffer;
3551 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3552 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3553 * @param fd pointer to the filedescriptor to read
3554 * @param timeout number of successless selects until we bail out
3555 * @param selectresolution how long to wait on each select
3556 * @param Error strerror() on error
3557 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3559 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3564 int selectresolution,
3567 const char *pche = NULL;
3568 const char *pos = NULL;
3570 int len, rlen, retlen;
3571 int nSuccessLess = 0;
3573 const char *pch = NULL;
3579 if ((Line == NULL) ||
3586 *Error = ErrRBLF_PreConditionFailed;
3591 if ((IOBuf->BufUsed > 0) &&
3593 (pos < IOBuf->buf + IOBuf->BufUsed))
3597 pche = IOBuf->buf + IOBuf->BufUsed;
3601 while ((pch < pche) && (*pch != '\n'))
3603 if (Line->BufUsed + 10 > Line->BufSize)
3606 apos = pcht - Line->buf;
3608 IncreaseBuf(Line, 1, -1);
3609 pcht = Line->buf + apos;
3617 if (len > 0 && (*(pch - 1) == '\r') )
3626 if ((pch >= pche) || (*pch == '\0'))
3634 if ((pch != NULL) &&
3637 if (pch + 1 >= pche) {
3650 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3652 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3653 IncreaseBuf(IOBuf, 1, -1);
3655 fdflags = fcntl(*fd, F_GETFL);
3656 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3659 while ((nSuccessLess < timeout) &&
3669 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3670 *Error = strerror(errno);
3674 *Error = ErrRBLF_SelectFailed;
3677 if (! FD_ISSET(*fd, &rfds) != 0) {
3683 &IOBuf->buf[IOBuf->BufUsed],
3684 IOBuf->BufSize - IOBuf->BufUsed - 1);
3686 *Error = strerror(errno);
3691 else if (rlen > 0) {
3693 pLF = IOBuf->buf + IOBuf->BufUsed;
3694 IOBuf->BufUsed += rlen;
3695 IOBuf->buf[IOBuf->BufUsed] = '\0';
3697 pche = IOBuf->buf + IOBuf->BufUsed;
3699 while ((pLF < pche) && (*pLF != '\n'))
3701 if ((pLF >= pche) || (*pLF == '\0'))
3704 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3708 if (pLF != NULL) apos = pLF - IOBuf->buf;
3709 IncreaseBuf(IOBuf, 1, -1);
3710 if (pLF != NULL) pLF = IOBuf->buf + apos;
3720 if (len > 0 && (*(pLF - 1) == '\r') )
3722 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3723 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3729 return retlen + len;
3731 *Error = ErrRBLF_NotEnoughSentFromServer;
3736 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3738 * @ingroup StrBuf_IO
3739 * @brief Input binary data from socket
3740 * flushes and closes the FD on error
3741 * @param Buf the buffer to get the input to
3742 * @param fd pointer to the filedescriptor to read
3743 * @param append Append to an existing string or replace?
3744 * @param nBytes the maximal number of bytes to read
3745 * @param Error strerror() on error
3746 * @returns numbers of chars read
3748 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3751 int len, rlen, slen;
3759 if ((Buf == NULL) || (*fd == -1))
3761 *Error = ErrRBLF_BLOBPreConditionFailed;
3766 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3767 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3769 ptr = Buf->buf + Buf->BufUsed;
3771 slen = len = Buf->BufUsed;
3773 fdflags = fcntl(*fd, F_GETFL);
3774 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3776 while ((nRead < nBytes) &&
3786 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3787 *Error = strerror(errno);
3791 *Error = ErrRBLF_SelectFailed;
3794 if (! FD_ISSET(*fd, &rfds) != 0) {
3800 if ((rlen = read(*fd,
3802 nBytes - nRead)) == -1) {
3805 *Error = strerror(errno);
3810 Buf->BufUsed += rlen;
3812 Buf->buf[Buf->BufUsed] = '\0';
3816 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3817 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3819 * @ingroup StrBuf_BufferedIO
3820 * @brief Input binary data from socket
3821 * flushes and closes the FD on error
3822 * @param Blob put binary thing here
3823 * @param IOBuf the buffer to get the input to
3824 * @param Pos offset inside of IOBuf
3825 * @param fd pointer to the filedescriptor to read
3826 * @param append Append to an existing string or replace?
3827 * @param nBytes the maximal number of bytes to read
3828 * @param check whether we should search for '000\n' terminators in case of timeouts
3829 * @param Error strerror() on error
3830 * @returns numbers of chars read
3832 int StrBufReadBLOBBuffered(StrBuf *Blob,
3847 int nAlreadyRead = 0;
3853 int nSuccessLess = 0;
3856 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3860 *Error = ErrRBB_BLOBFPreConditionFailed;
3866 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3867 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3872 len = pos - IOBuf->buf;
3873 rlen = IOBuf->BufUsed - len;
3876 if ((IOBuf->BufUsed > 0) &&
3878 (pos < IOBuf->buf + IOBuf->BufUsed))
3880 pche = IOBuf->buf + IOBuf->BufUsed;
3883 if (rlen < nBytes) {
3884 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3885 Blob->BufUsed += rlen;
3886 Blob->buf[Blob->BufUsed] = '\0';
3887 nAlreadyRead = nRead = rlen;
3890 if (rlen >= nBytes) {
3891 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3892 Blob->BufUsed += nBytes;
3893 Blob->buf[Blob->BufUsed] = '\0';
3894 if (rlen == nBytes) {
3906 if (IOBuf->BufSize < nBytes - nRead)
3907 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3910 slen = len = Blob->BufUsed;
3912 fdflags = fcntl(*fd, F_GETFL);
3913 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3921 while ((nSuccessLess < MaxTries) &&
3931 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3932 *Error = strerror(errno);
3936 *Error = ErrRBLF_SelectFailed;
3939 if (! FD_ISSET(*fd, &rfds) != 0) {
3946 IOBuf->BufSize - (ptr - IOBuf->buf));
3950 *Error = strerror(errno);
3953 else if (rlen == 0){
3954 if ((check == NNN_TERM) &&
3956 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3958 StrBufPlain(Blob, HKEY("\n000\n"));
3959 StrBufCutRight(Blob, 5);
3960 return Blob->BufUsed;
3962 else if (!IsNonBlock)
3964 else if (nSuccessLess > MaxTries) {
3966 *Error = ErrRBB_too_many_selects;
3970 else if (rlen > 0) {
3974 IOBuf->BufUsed += rlen;
3977 if (nSuccessLess >= MaxTries) {
3979 *Error = ErrRBB_too_many_selects;
3983 if (nRead > nBytes) {
3984 *Pos = IOBuf->buf + nBytes;
3986 Blob->buf[Blob->BufUsed] = '\0';
3987 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3991 return nRead + nAlreadyRead;
3995 * @ingroup StrBuf_IO
3996 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3997 * @param LineBuf your line will be copied here.
3998 * @param Buf BLOB with lines of text...
3999 * @param Ptr moved arround to keep the next-line across several iterations
4000 * has to be &NULL on start; will be &NotNULL on end of buffer
4001 * @returns size of copied buffer
4003 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
4005 const char *aptr, *ptr, *eptr;
4008 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
4009 *Ptr = StrBufNOTNULL;
4013 FlushStrBuf(LineBuf);
4015 ptr = aptr = Buf->buf;
4019 optr = LineBuf->buf;
4020 eptr = Buf->buf + Buf->BufUsed;
4021 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4023 while ((ptr <= eptr) &&
4030 LineBuf->BufUsed = optr - LineBuf->buf;
4031 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
4032 optr = LineBuf->buf + LineBuf->BufUsed;
4033 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4037 if ((ptr >= eptr) && (optr > LineBuf->buf))
4039 LineBuf->BufUsed = optr - LineBuf->buf;
4041 if ((ptr <= eptr) && (*ptr == '\r'))
4043 if ((ptr <= eptr) && (*ptr == '\n'))
4050 *Ptr = StrBufNOTNULL;
4053 return Buf->BufUsed - (ptr - Buf->buf);
4058 * @ingroup StrBuf_IO
4059 * @brief removes double slashes from pathnames
4060 * @param Dir directory string to filter
4061 * @param RemoveTrailingSlash allows / disallows trailing slashes
4063 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
4069 while (!IsEmptyStr(a)) {
4081 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4086 Dir->BufUsed = b - Dir->buf;