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 CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
396 * @param CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe
397 * @param KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
398 * @returns the new stringbuffer
400 void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, int KeepOriginal)
404 if (CreateRelpaceMe == NULL)
406 if (CopyFlushMe == NULL)
408 if (*CreateRelpaceMe != NULL)
409 FlushStrBuf(*CreateRelpaceMe);
411 *CreateRelpaceMe = NewStrBuf();
416 * Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
417 * else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
418 * be a big IO-Buffer...
420 if (KeepOriginal || (StrLength(CopyFlushMe) > 64))
422 if (*CreateRelpaceMe == NULL)
424 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed + 1);
429 NewBuf = *CreateRelpaceMe;
432 StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
436 if (*CreateRelpaceMe == NULL)
438 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufSize);
442 NewBuf = *CreateRelpaceMe;
443 SwapBuffers (NewBuf, CopyFlushMe);
446 FlushStrBuf(CopyFlushMe);
451 * @ingroup StrBuf_DeConstructors
452 * @brief create a new Buffer using an existing c-string
453 * this function should also be used if you want to pre-suggest
454 * the buffer size to allocate in conjunction with ptr == NULL
455 * @param ptr the c-string to copy; may be NULL to create a blank instance
456 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
457 * @returns the new stringbuffer
459 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
462 size_t Siz = BaseStrBufSize;
465 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
467 CopySize = strlen((ptr != NULL)?ptr:"");
471 while (Siz <= CopySize)
474 NewBuf->buf = (char*) malloc(Siz);
475 NewBuf->BufSize = Siz;
477 memcpy(NewBuf->buf, ptr, CopySize);
478 NewBuf->buf[CopySize] = '\0';
479 NewBuf->BufUsed = CopySize;
482 NewBuf->buf[0] = '\0';
485 NewBuf->ConstBuf = 0;
493 * @ingroup StrBuf_DeConstructors
494 * @brief Set an existing buffer from a c-string
495 * @param Buf buffer to load
496 * @param ptr c-string to put into
497 * @param nChars set to -1 if we should work 0-terminated
498 * @returns the new length of the string
500 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
515 CopySize = strlen(ptr);
519 while (Siz <= CopySize)
522 if (Siz != Buf->BufSize)
523 IncreaseBuf(Buf, 0, Siz);
524 memcpy(Buf->buf, ptr, CopySize);
525 Buf->buf[CopySize] = '\0';
526 Buf->BufUsed = CopySize;
533 * @ingroup StrBuf_DeConstructors
534 * @brief use strbuf as wrapper for a string constant for easy handling
535 * @param StringConstant a string to wrap
536 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
538 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
542 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
543 NewBuf->buf = (char*) StringConstant;
544 NewBuf->BufSize = SizeOfStrConstant;
545 NewBuf->BufUsed = SizeOfStrConstant;
546 NewBuf->ConstBuf = 1;
555 * @ingroup StrBuf_DeConstructors
556 * @brief flush the content of a Buf; keep its struct
557 * @param buf Buffer to flush
559 int FlushStrBuf(StrBuf *buf)
571 * @ingroup StrBuf_DeConstructors
572 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
573 * @param buf Buffer to wipe
575 int FLUSHStrBuf(StrBuf *buf)
581 if (buf->BufUsed > 0) {
582 memset(buf->buf, 0, buf->BufUsed);
589 int hFreeDbglog = -1;
592 * @ingroup StrBuf_DeConstructors
593 * @brief Release a Buffer
594 * Its a double pointer, so it can NULL your pointer
595 * so fancy SIG11 appear instead of random results
596 * @param FreeMe Pointer Pointer to the buffer to free
598 void FreeStrBuf (StrBuf **FreeMe)
603 dbg_FreeStrBuf(FreeMe, 'F');
605 if (!(*FreeMe)->ConstBuf)
606 free((*FreeMe)->buf);
612 * @ingroup StrBuf_DeConstructors
613 * @brief flatten a Buffer to the Char * we return
614 * Its a double pointer, so it can NULL your pointer
615 * so fancy SIG11 appear instead of random results
616 * The Callee then owns the buffer and is responsible for freeing it.
617 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
618 * @returns the pointer of the buffer; Callee owns the memory thereafter.
620 char *SmashStrBuf (StrBuf **SmashMe)
624 if ((SmashMe == NULL) || (*SmashMe == NULL))
627 dbg_FreeStrBuf(SmashMe, 'S');
629 Ret = (*SmashMe)->buf;
636 * @ingroup StrBuf_DeConstructors
637 * @brief Release the buffer
638 * If you want put your StrBuf into a Hash, use this as Destructor.
639 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
641 void HFreeStrBuf (void *VFreeMe)
643 StrBuf *FreeMe = (StrBuf*)VFreeMe;
647 dbg_FreeStrBuf(SmashMe, 'H');
649 if (!FreeMe->ConstBuf)
655 /*******************************************************************************
656 * Simple string transformations *
657 *******************************************************************************/
661 * @brief Wrapper around atol
663 long StrTol(const StrBuf *Buf)
668 return atol(Buf->buf);
675 * @brief Wrapper around atoi
677 int StrToi(const StrBuf *Buf)
681 if (Buf->BufUsed > 0)
682 return atoi(Buf->buf);
689 * @brief Checks to see if the string is a pure number
690 * @param Buf The buffer to inspect
691 * @returns 1 if its a pure number, 0, if not.
693 int StrBufIsNumber(const StrBuf *Buf) {
695 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
698 strtoll(Buf->buf, &pEnd, 10);
699 if (pEnd == Buf->buf)
701 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
703 if (Buf->buf == pEnd)
709 * @ingroup StrBuf_Filler
710 * @brief modifies a Single char of the Buf
711 * You can point to it via char* or a zero-based integer
712 * @param Buf The buffer to manipulate
713 * @param ptr char* to zero; use NULL if unused
714 * @param nThChar zero based pointer into the string; use -1 if unused
715 * @param PeekValue The Character to place into the position
717 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
722 nThChar = ptr - Buf->buf;
723 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
725 Buf->buf[nThChar] = PeekValue;
730 * @ingroup StrBuf_Filler
731 * @brief modifies a range of chars of the Buf
732 * You can point to it via char* or a zero-based integer
733 * @param Buf The buffer to manipulate
734 * @param ptr char* to zero; use NULL if unused
735 * @param nThChar zero based pointer into the string; use -1 if unused
736 * @param nChars how many chars are to be flushed?
737 * @param PookValue The Character to place into that area
739 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
744 nThChar = ptr - Buf->buf;
745 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
747 if (nThChar + nChars > Buf->BufUsed)
748 nChars = Buf->BufUsed - nThChar;
750 memset(Buf->buf + nThChar, PookValue, nChars);
751 /* just to be shure... */
752 Buf->buf[Buf->BufUsed] = 0;
757 * @ingroup StrBuf_Filler
758 * @brief Append a StringBuffer to the buffer
759 * @param Buf Buffer to modify
760 * @param AppendBuf Buffer to copy at the end of our buffer
761 * @param Offset Should we start copying from an offset?
763 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
765 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
768 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
771 AppendBuf->BufUsed + Buf->BufUsed);
773 memcpy(Buf->buf + Buf->BufUsed,
774 AppendBuf->buf + Offset,
775 AppendBuf->BufUsed - Offset);
776 Buf->BufUsed += AppendBuf->BufUsed - Offset;
777 Buf->buf[Buf->BufUsed] = '\0';
782 * @ingroup StrBuf_Filler
783 * @brief Append a C-String to the buffer
784 * @param Buf Buffer to modify
785 * @param AppendBuf Buffer to copy at the end of our buffer
786 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
787 * @param Offset Should we start copying from an offset?
789 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
792 long BufSizeRequired;
794 if ((AppendBuf == NULL) || (Buf == NULL))
798 aps = strlen(AppendBuf + Offset);
800 aps = AppendSize - Offset;
802 BufSizeRequired = Buf->BufUsed + aps + 1;
803 if (Buf->BufSize <= BufSizeRequired)
804 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
806 memcpy(Buf->buf + Buf->BufUsed,
810 Buf->buf[Buf->BufUsed] = '\0';
814 * @ingroup StrBuf_Filler
815 * @brief sprintf like function appending the formated string to the buffer
816 * vsnprintf version to wrap into own calls
817 * @param Buf Buffer to extend by format and Params
818 * @param format printf alike format to add
819 * @param ap va_list containing the items for format
821 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
829 if ((Buf == NULL) || (format == NULL))
832 BufSize = Buf->BufSize;
833 nWritten = Buf->BufSize + 1;
834 Offset = Buf->BufUsed;
835 newused = Offset + nWritten;
837 while (newused >= BufSize) {
839 nWritten = vsnprintf(Buf->buf + Offset,
840 Buf->BufSize - Offset,
843 newused = Offset + nWritten;
844 if (newused >= Buf->BufSize) {
845 IncreaseBuf(Buf, 1, newused);
846 newused = Buf->BufSize + 1;
849 Buf->BufUsed = Offset + nWritten;
850 BufSize = Buf->BufSize;
857 * @ingroup StrBuf_Filler
858 * @brief sprintf like function appending the formated string to the buffer
859 * @param Buf Buffer to extend by format and Params
860 * @param format printf alike format to add
862 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
870 if ((Buf == NULL) || (format == NULL))
873 BufSize = Buf->BufSize;
874 nWritten = Buf->BufSize + 1;
875 Offset = Buf->BufUsed;
876 newused = Offset + nWritten;
878 while (newused >= BufSize) {
879 va_start(arg_ptr, format);
880 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
881 Buf->BufSize - Buf->BufUsed,
884 newused = Buf->BufUsed + nWritten;
885 if (newused >= Buf->BufSize) {
886 IncreaseBuf(Buf, 1, newused);
887 newused = Buf->BufSize + 1;
890 Buf->BufUsed += nWritten;
891 BufSize = Buf->BufSize;
898 * @ingroup StrBuf_Filler
899 * @brief sprintf like function putting the formated string into the buffer
900 * @param Buf Buffer to extend by format and Parameters
901 * @param format printf alike format to add
903 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
908 if ((Buf == NULL) || (format == NULL))
911 nWritten = Buf->BufSize + 1;
912 while (nWritten >= Buf->BufSize) {
913 va_start(arg_ptr, format);
914 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
916 if (nWritten >= Buf->BufSize) {
917 IncreaseBuf(Buf, 0, 0);
918 nWritten = Buf->BufSize + 1;
921 Buf->BufUsed = nWritten ;
926 * @ingroup StrBuf_Filler
927 * @brief Callback for cURL to append the webserver reply to a buffer
928 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
929 * @param size pre-defined by the cURL API; see man 3 curl for mre info
930 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
931 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
933 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
942 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
949 * @brief extracts a substring from Source into dest
950 * @param dest buffer to place substring into
951 * @param Source string to copy substring from
952 * @param Offset chars to skip from start
953 * @param nChars number of chars to copy
954 * @returns the number of chars copied; may be different from nChars due to the size of Source
956 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
959 if (Offset > Source->BufUsed)
965 if (Offset + nChars < Source->BufUsed)
967 if (nChars >= dest->BufSize)
968 IncreaseBuf(dest, 0, nChars + 1);
969 memcpy(dest->buf, Source->buf + Offset, nChars);
970 dest->BufUsed = nChars;
971 dest->buf[dest->BufUsed] = '\0';
974 NCharsRemain = Source->BufUsed - Offset;
975 if (NCharsRemain >= dest->BufSize)
976 IncreaseBuf(dest, 0, NCharsRemain + 1);
977 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
978 dest->BufUsed = NCharsRemain;
979 dest->buf[dest->BufUsed] = '\0';
985 * @brief Cut nChars from the start of the string
986 * @param Buf Buffer to modify
987 * @param nChars how many chars should be skipped?
989 void StrBufCutLeft(StrBuf *Buf, int nChars)
991 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
992 if (nChars >= Buf->BufUsed) {
996 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
997 Buf->BufUsed -= nChars;
998 Buf->buf[Buf->BufUsed] = '\0';
1003 * @brief Cut the trailing n Chars from the string
1004 * @param Buf Buffer to modify
1005 * @param nChars how many chars should be trunkated?
1007 void StrBufCutRight(StrBuf *Buf, int nChars)
1009 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1010 if (nChars >= Buf->BufUsed) {
1014 Buf->BufUsed -= nChars;
1015 Buf->buf[Buf->BufUsed] = '\0';
1020 * @brief Cut the string after n Chars
1021 * @param Buf Buffer to modify
1022 * @param AfternChars after how many chars should we trunkate the string?
1023 * @param At if non-null and points inside of our string, cut it there.
1025 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1027 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1029 AfternChars = At - Buf->buf;
1032 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1034 Buf->BufUsed = AfternChars;
1035 Buf->buf[Buf->BufUsed] = '\0';
1041 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1042 * @param Buf the string to modify
1044 void StrBufTrim(StrBuf *Buf)
1047 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1049 while ((Buf->BufUsed > 0) &&
1050 isspace(Buf->buf[Buf->BufUsed - 1]))
1054 Buf->buf[Buf->BufUsed] = '\0';
1056 if (Buf->BufUsed == 0) return;
1058 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1061 if (delta > 0) StrBufCutLeft(Buf, delta);
1064 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
1072 pLeft = pBuff = Buf->buf;
1073 while (pBuff != NULL) {
1075 pBuff = strchr(pBuff, leftboundary);
1084 pRight = strchr(pBuff, rightboundary);
1086 StrBufCutAt(Buf, 0, pRight);
1088 StrBufCutLeft(Buf, pLeft - Buf->buf);
1093 * @ingroup StrBuf_Filler
1094 * @brief uppercase the contents of a buffer
1095 * @param Buf the buffer to translate
1097 void StrBufUpCase(StrBuf *Buf)
1101 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1104 pche = pch + Buf->BufUsed;
1105 while (pch < pche) {
1106 *pch = toupper(*pch);
1113 * @ingroup StrBuf_Filler
1114 * @brief lowercase the contents of a buffer
1115 * @param Buf the buffer to translate
1117 void StrBufLowerCase(StrBuf *Buf)
1121 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1124 pche = pch + Buf->BufUsed;
1125 while (pch < pche) {
1126 *pch = tolower(*pch);
1132 /*******************************************************************************
1133 * a tokenizer that kills, maims, and destroys *
1134 *******************************************************************************/
1137 * @ingroup StrBuf_Tokenizer
1138 * @brief Replace a token at a given place with a given length by another token with given length
1139 * @param Buf String where to work on
1140 * @param where where inside of the Buf is the search-token
1141 * @param HowLong How long is the token to be replaced
1142 * @param Repl Token to insert at 'where'
1143 * @param ReplLen Length of repl
1144 * @returns -1 if fail else length of resulting Buf
1146 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1147 const char *Repl, long ReplLen)
1150 if ((Buf == NULL) ||
1151 (where > Buf->BufUsed) ||
1152 (where + HowLong > Buf->BufUsed))
1155 if (where + ReplLen - HowLong > Buf->BufSize)
1156 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1159 memmove(Buf->buf + where + ReplLen,
1160 Buf->buf + where + HowLong,
1161 Buf->BufUsed - where - HowLong);
1163 memcpy(Buf->buf + where,
1166 Buf->BufUsed += ReplLen - HowLong;
1168 return Buf->BufUsed;
1172 * @ingroup StrBuf_Tokenizer
1173 * @brief Counts the numbmer of tokens in a buffer
1174 * @param source String to count tokens in
1175 * @param tok Tokenizer char to count
1176 * @returns numbers of tokenizer chars found
1178 int StrBufNum_tokens(const StrBuf *source, char tok)
1182 if ((source == NULL) || (source->BufUsed == 0))
1184 if ((source->BufUsed == 1) && (*source->buf == tok))
1188 pche = pch + source->BufUsed;
1199 * @ingroup StrBuf_Tokenizer
1200 * @brief a string tokenizer
1201 * @param Source StringBuffer to read into
1202 * @param parmnum n'th Parameter to remove
1203 * @param separator tokenizer character
1204 * @returns -1 if not found, else length of token.
1206 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1209 char *d, *s, *end; /* dest, source */
1212 /* Find desired @parameter */
1213 end = Source->buf + Source->BufUsed;
1215 while ((d <= end) &&
1218 /* End of string, bail! */
1223 if (*d == separator) {
1228 if ((d == NULL) || (d >= end))
1229 return 0; /* @Parameter not found */
1231 /* Find next @parameter */
1233 while ((s <= end) &&
1234 (*s && *s != separator))
1238 if (*s == separator)
1242 /* Hack and slash */
1247 memmove(d, s, Source->BufUsed - (s - Source->buf));
1248 Source->BufUsed += ReducedBy;
1249 Source->buf[Source->BufUsed] = '\0';
1251 else if (d == Source->buf) {
1253 Source->BufUsed = 0;
1257 Source->BufUsed += ReducedBy;
1270 * @ingroup StrBuf_Tokenizer
1271 * @brief a string tokenizer
1272 * @param dest Destination StringBuffer
1273 * @param Source StringBuffer to read into
1274 * @param parmnum n'th Parameter to extract
1275 * @param separator tokenizer character
1276 * @returns -1 if not found, else length of token.
1278 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1280 const char *s, *e; //* source * /
1281 int len = 0; //* running total length of extracted string * /
1282 int current_token = 0; //* token currently being processed * /
1285 dest->buf[0] = '\0';
1291 if ((Source == NULL) || (Source->BufUsed ==0)) {
1295 e = s + Source->BufUsed;
1298 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1300 while ((s<e) && !IsEmptyStr(s)) {
1301 if (*s == separator) {
1304 if (len >= dest->BufSize) {
1305 dest->BufUsed = len;
1306 if (IncreaseBuf(dest, 1, -1) < 0) {
1311 if ( (current_token == parmnum) &&
1312 (*s != separator)) {
1313 dest->buf[len] = *s;
1316 else if (current_token > parmnum) {
1322 dest->buf[len] = '\0';
1323 dest->BufUsed = len;
1325 if (current_token < parmnum) {
1326 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1329 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1338 * @ingroup StrBuf_Tokenizer
1339 * @brief a string tokenizer to fetch an integer
1340 * @param Source String containing tokens
1341 * @param parmnum n'th Parameter to extract
1342 * @param separator tokenizer character
1343 * @returns 0 if not found, else integer representation of the token
1345 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1355 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1362 * @ingroup StrBuf_Tokenizer
1363 * @brief a string tokenizer to fetch a long integer
1364 * @param Source String containing tokens
1365 * @param parmnum n'th Parameter to extract
1366 * @param separator tokenizer character
1367 * @returns 0 if not found, else long integer representation of the token
1369 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1379 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1387 * @ingroup StrBuf_Tokenizer
1388 * @brief a string tokenizer to fetch an unsigned long
1389 * @param Source String containing tokens
1390 * @param parmnum n'th Parameter to extract
1391 * @param separator tokenizer character
1392 * @returns 0 if not found, else unsigned long representation of the token
1394 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1405 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1409 return (unsigned long) atol(pnum);
1418 * @ingroup StrBuf_NextTokenizer
1419 * @brief a string tokenizer; Bounds checker
1420 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1421 * @param Source our tokenbuffer
1422 * @param pStart the token iterator pointer to inspect
1423 * @returns whether the revolving pointer is inside of the search range
1425 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1427 if ((Source == NULL) ||
1428 (*pStart == StrBufNOTNULL) ||
1429 (Source->BufUsed == 0))
1433 if (*pStart == NULL)
1437 else if (*pStart > Source->buf + Source->BufUsed)
1441 else if (*pStart <= Source->buf)
1450 * @ingroup StrBuf_NextTokenizer
1451 * @brief a string tokenizer
1452 * @param dest Destination StringBuffer
1453 * @param Source StringBuffer to read into
1454 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1455 * @param separator tokenizer
1456 * @returns -1 if not found, else length of token.
1458 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1460 const char *s; /* source */
1461 const char *EndBuffer; /* end stop of source buffer */
1462 int current_token = 0; /* token currently being processed */
1463 int len = 0; /* running total length of extracted string */
1465 if ((Source == NULL) ||
1466 (Source->BufUsed == 0) )
1468 *pStart = StrBufNOTNULL;
1472 EndBuffer = Source->buf + Source->BufUsed;
1476 dest->buf[0] = '\0';
1481 *pStart = EndBuffer + 1;
1485 if (*pStart == NULL)
1487 *pStart = Source->buf; /* we're starting to examine this buffer. */
1489 else if ((*pStart < Source->buf) ||
1490 (*pStart > EndBuffer ) )
1492 return -1; /* no more tokens to find. */
1496 /* start to find the next token */
1497 while ((s <= EndBuffer) &&
1498 (current_token == 0) )
1500 if (*s == separator)
1502 /* we found the next token */
1506 if (len >= dest->BufSize)
1508 /* our Dest-buffer isn't big enough, increase it. */
1509 dest->BufUsed = len;
1511 if (IncreaseBuf(dest, 1, -1) < 0) {
1512 /* WHUT? no more mem? bail out. */
1519 if ( (current_token == 0 ) && /* are we in our target token? */
1520 (!IsEmptyStr(s) ) &&
1521 (separator != *s) ) /* don't copy the token itself */
1523 dest->buf[len] = *s; /* Copy the payload */
1524 ++len; /* remember the bigger size. */
1530 /* did we reach the end? */
1531 if ((s > EndBuffer)) {
1532 EndBuffer = StrBufNOTNULL;
1533 *pStart = EndBuffer;
1536 *pStart = s; /* remember the position for the next run */
1539 /* sanitize our extracted token */
1540 dest->buf[len] = '\0';
1541 dest->BufUsed = len;
1548 * @ingroup StrBuf_NextTokenizer
1549 * @brief a string tokenizer
1550 * @param Source StringBuffer to read from
1551 * @param pStart pointer to the end of the last token. Feed with NULL.
1552 * @param separator tokenizer character
1553 * @param nTokens number of tokens to fastforward over
1554 * @returns -1 if not found, else length of token.
1556 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1558 const char *s, *EndBuffer; //* source * /
1559 int len = 0; //* running total length of extracted string * /
1560 int current_token = 0; //* token currently being processed * /
1562 if ((Source == NULL) ||
1563 (Source->BufUsed ==0)) {
1567 return Source->BufUsed;
1569 if (*pStart == NULL)
1570 *pStart = Source->buf;
1572 EndBuffer = Source->buf + Source->BufUsed;
1574 if ((*pStart < Source->buf) ||
1575 (*pStart > EndBuffer)) {
1583 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1585 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1586 if (*s == separator) {
1589 if (current_token >= nTokens) {
1601 * @ingroup StrBuf_NextTokenizer
1602 * @brief a string tokenizer to fetch an integer
1603 * @param Source StringBuffer to read from
1604 * @param pStart Cursor on the tokenstring
1605 * @param separator tokenizer character
1606 * @returns 0 if not found, else integer representation of the token
1608 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1618 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1625 * @ingroup StrBuf_NextTokenizer
1626 * @brief a string tokenizer to fetch a long integer
1627 * @param Source StringBuffer to read from
1628 * @param pStart Cursor on the tokenstring
1629 * @param separator tokenizer character
1630 * @returns 0 if not found, else long integer representation of the token
1632 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1642 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1650 * @ingroup StrBuf_NextTokenizer
1651 * @brief a string tokenizer to fetch an unsigned long
1652 * @param Source StringBuffer to read from
1653 * @param pStart Cursor on the tokenstring
1654 * @param separator tokenizer character
1655 * @returns 0 if not found, else unsigned long representation of the token
1657 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1668 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1672 return (unsigned long) atol(pnum);
1682 /*******************************************************************************
1683 * Escape Appending *
1684 *******************************************************************************/
1687 * @ingroup StrBuf_DeEnCoder
1688 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1689 * @param OutBuf the output buffer
1690 * @param In Buffer to encode
1691 * @param PlainIn way in from plain old c strings
1693 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1695 const char *pch, *pche;
1699 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1701 if (PlainIn != NULL) {
1702 len = strlen(PlainIn);
1708 pche = pch + In->BufUsed;
1715 pt = OutBuf->buf + OutBuf->BufUsed;
1716 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1718 while (pch < pche) {
1720 IncreaseBuf(OutBuf, 1, -1);
1721 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1722 pt = OutBuf->buf + OutBuf->BufUsed;
1725 if((*pch >= 'a' && *pch <= 'z') ||
1726 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1727 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1728 (*pch == '!') || (*pch == '_') ||
1729 (*pch == ',') || (*pch == '.'))
1736 *(pt + 1) = HexList[(unsigned char)*pch][0];
1737 *(pt + 2) = HexList[(unsigned char)*pch][1];
1739 OutBuf->BufUsed += 3;
1747 * @ingroup StrBuf_DeEnCoder
1748 * @brief append a string in hex encoding to the buffer
1749 * @param OutBuf the output buffer
1750 * @param In Buffer to encode
1751 * @param PlainIn way in from plain old c strings
1753 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1755 const char *pch, *pche;
1759 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1761 if (PlainIn != NULL) {
1762 len = strlen(PlainIn);
1768 pche = pch + In->BufUsed;
1775 pt = OutBuf->buf + OutBuf->BufUsed;
1776 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1778 while (pch < pche) {
1780 IncreaseBuf(OutBuf, 1, -1);
1781 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1782 pt = OutBuf->buf + OutBuf->BufUsed;
1785 *pt = HexList[(unsigned char)*pch][0];
1787 *pt = HexList[(unsigned char)*pch][1];
1788 pt ++; pch ++; OutBuf->BufUsed += 2;
1794 * @ingroup StrBuf_DeEnCoder
1795 * @brief Append a string, escaping characters which have meaning in HTML.
1797 * @param Target target buffer
1798 * @param Source source buffer; set to NULL if you just have a C-String
1799 * @param PlainIn Plain-C string to append; set to NULL if unused
1800 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1801 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1802 * if set to 2, linebreaks are replaced by <br/>
1804 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
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 - 11; /* our biggest unit to put in... */
1830 while (aptr < eiptr){
1832 IncreaseBuf(Target, 1, -1);
1833 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1834 bptr = Target->buf + Target->BufUsed;
1837 memcpy(bptr, "<", 4);
1839 Target->BufUsed += 4;
1841 else if (*aptr == '>') {
1842 memcpy(bptr, ">", 4);
1844 Target->BufUsed += 4;
1846 else if (*aptr == '&') {
1847 memcpy(bptr, "&", 5);
1849 Target->BufUsed += 5;
1851 else if (*aptr == '"') {
1852 memcpy(bptr, """, 6);
1854 Target->BufUsed += 6;
1856 else if (*aptr == '\'') {
1857 memcpy(bptr, "'", 5);
1859 Target->BufUsed += 5;
1861 else if (*aptr == LB) {
1866 else if (*aptr == RB) {
1871 else if (*aptr == QU) {
1876 else if ((*aptr == 32) && (nbsp == 1)) {
1877 memcpy(bptr, " ", 6);
1879 Target->BufUsed += 6;
1881 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1882 *bptr='\0'; /* nothing */
1884 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1885 memcpy(bptr, "<br/>", 11);
1887 Target->BufUsed += 11;
1891 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1892 *bptr='\0'; /* nothing */
1902 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1904 return Target->BufUsed;
1908 * @ingroup StrBuf_DeEnCoder
1909 * @brief Append a string, escaping characters which have meaning in HTML.
1910 * Converts linebreaks into blanks; escapes single quotes
1911 * @param Target target buffer
1912 * @param Source source buffer; set to NULL if you just have a C-String
1913 * @param PlainIn Plain-C string to append; set to NULL if unused
1915 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1917 const char *aptr, *eiptr;
1921 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1924 if (PlainIn != NULL) {
1926 len = strlen(PlainIn);
1931 eiptr = aptr + Source->BufUsed;
1932 len = Source->BufUsed;
1938 eptr = Target->buf + Target->BufSize - 8;
1939 tptr = Target->buf + Target->BufUsed;
1941 while (aptr < eiptr){
1943 IncreaseBuf(Target, 1, -1);
1944 eptr = Target->buf + Target->BufSize - 8;
1945 tptr = Target->buf + Target->BufUsed;
1948 if (*aptr == '\n') {
1952 else if (*aptr == '\r') {
1956 else if (*aptr == '\'') {
1962 Target->BufUsed += 5;
1975 * @ingroup StrBuf_DeEnCoder
1976 * @brief Append a string, escaping characters which have meaning in ICAL.
1978 * @param Target target buffer
1979 * @param Source source buffer; set to NULL if you just have a C-String
1980 * @param PlainIn Plain-C string to append; set to NULL if unused
1982 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1984 const char *aptr, *eiptr;
1988 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1991 if (PlainIn != NULL) {
1993 len = strlen(PlainIn);
1998 eiptr = aptr + Source->BufUsed;
1999 len = Source->BufUsed;
2005 eptr = Target->buf + Target->BufSize - 8;
2006 tptr = Target->buf + Target->BufUsed;
2008 while (aptr < eiptr){
2009 if(tptr + 3 >= eptr) {
2010 IncreaseBuf(Target, 1, -1);
2011 eptr = Target->buf + Target->BufSize - 8;
2012 tptr = Target->buf + Target->BufUsed;
2015 if (*aptr == '\n') {
2022 else if (*aptr == '\r') {
2029 else if (*aptr == ',') {
2045 * @ingroup StrBuf_DeEnCoder
2046 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
2048 * @param Target target buffer
2049 * @param Source source buffer; set to NULL if you just have a C-String
2050 * @param PlainIn Plain-C string to append; set to NULL if unused
2051 * @returns size of result or -1
2053 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2055 const char *aptr, *eiptr;
2059 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2062 if (PlainIn != NULL) {
2064 len = strlen(PlainIn);
2069 eiptr = aptr + Source->BufUsed;
2070 len = Source->BufUsed;
2076 bptr = Target->buf + Target->BufUsed;
2077 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
2079 while (aptr < eiptr){
2081 IncreaseBuf(Target, 1, -1);
2082 eptr = Target->buf + Target->BufSize - 3;
2083 bptr = Target->buf + Target->BufUsed;
2090 Target->BufUsed += 2;
2091 } else if (*aptr == '\\') {
2096 Target->BufUsed += 2;
2106 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2108 return Target->BufUsed;
2112 * @ingroup StrBuf_DeEnCoder
2113 * @brief Append a string, escaping characters which have meaning in HTML + json.
2115 * @param Target target buffer
2116 * @param Source source buffer; set to NULL if you just have a C-String
2117 * @param PlainIn Plain-C string to append; set to NULL if unused
2118 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2119 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2120 * if set to 2, linebreaks are replaced by <br/>
2122 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2124 const char *aptr, *eiptr;
2127 int IsUtf8Sequence = 0;
2129 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2132 if (PlainIn != NULL) {
2134 len = strlen(PlainIn);
2139 eiptr = aptr + Source->BufUsed;
2140 len = Source->BufUsed;
2146 bptr = Target->buf + Target->BufUsed;
2147 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2149 while (aptr < eiptr){
2151 IncreaseBuf(Target, 1, -1);
2152 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2153 bptr = Target->buf + Target->BufUsed;
2156 memcpy(bptr, "<", 4);
2158 Target->BufUsed += 4;
2160 else if (*aptr == '>') {
2161 memcpy(bptr, ">", 4);
2163 Target->BufUsed += 4;
2165 else if (*aptr == '&') {
2166 memcpy(bptr, "&", 5);
2168 Target->BufUsed += 5;
2170 else if (*aptr == LB) {
2175 else if (*aptr == RB) {
2180 else if ((*aptr == 32) && (nbsp == 1)) {
2181 memcpy(bptr, " ", 6);
2183 Target->BufUsed += 6;
2185 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2186 *bptr='\0'; /* nothing */
2188 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2189 memcpy(bptr, "<br/>", 11);
2191 Target->BufUsed += 11;
2194 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2195 *bptr='\0'; /* nothing */
2198 else if ((*aptr == '"') || (*aptr == QU)) {
2203 Target->BufUsed += 2;
2204 } else if (*aptr == '\\') {
2209 Target->BufUsed += 2;
2212 if (((unsigned char)*aptr) >= 0x20)
2214 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2218 while (IsUtf8Sequence > 1){
2219 if(bptr + IsUtf8Sequence >= eptr) {
2220 IncreaseBuf(Target, 1, -1);
2221 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2222 bptr = Target->buf + Target->BufUsed - 1;
2236 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2238 return Target->BufUsed;
2242 * @ingroup StrBuf_DeEnCoder
2243 * @brief unhide special chars hidden to the HTML escaper
2244 * @param target buffer to put the unescaped string in
2245 * @param source buffer to unescape
2247 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2253 FlushStrBuf(target);
2255 if (source == NULL ||target == NULL)
2260 len = source->BufUsed;
2261 for (a = 0; a < len; ++a) {
2262 if (target->BufUsed >= target->BufSize)
2263 IncreaseBuf(target, 1, -1);
2265 if (source->buf[a] == '=') {
2266 hex[0] = source->buf[a + 1];
2267 hex[1] = source->buf[a + 2];
2270 sscanf(hex, "%02x", &b);
2271 target->buf[target->BufUsed] = b;
2272 target->buf[++target->BufUsed] = 0;
2276 target->buf[target->BufUsed] = source->buf[a];
2277 target->buf[++target->BufUsed] = 0;
2284 * @ingroup StrBuf_DeEnCoder
2285 * @brief hide special chars from the HTML escapers and friends
2286 * @param target buffer to put the escaped string in
2287 * @param source buffer to escape
2289 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2294 FlushStrBuf(target);
2296 if (source == NULL ||target == NULL)
2301 len = source->BufUsed;
2302 for (i=0; i<len; ++i) {
2303 if (target->BufUsed + 4 >= target->BufSize)
2304 IncreaseBuf(target, 1, -1);
2305 if ( (isalnum(source->buf[i])) ||
2306 (source->buf[i]=='-') ||
2307 (source->buf[i]=='_') ) {
2308 target->buf[target->BufUsed++] = source->buf[i];
2311 sprintf(&target->buf[target->BufUsed],
2313 (0xFF &source->buf[i]));
2314 target->BufUsed += 3;
2317 target->buf[target->BufUsed + 1] = '\0';
2321 /*******************************************************************************
2322 * Quoted Printable de/encoding *
2323 *******************************************************************************/
2326 * @ingroup StrBuf_DeEnCoder
2327 * @brief decode a buffer from base 64 encoding; destroys original
2328 * @param Buf Buffor to transform
2330 int StrBufDecodeBase64(StrBuf *Buf)
2334 if (Buf == NULL) return -1;
2336 xferbuf = (char*) malloc(Buf->BufSize);
2338 siz = CtdlDecodeBase64(xferbuf,
2348 * @ingroup StrBuf_DeEnCoder
2349 * @brief decode a buffer from base 64 encoding; destroys original
2350 * @param Buf Buffor to transform
2352 int StrBufDecodeHex(StrBuf *Buf)
2355 char *pch, *pche, *pchi;
2357 if (Buf == NULL) return -1;
2359 pch = pchi = Buf->buf;
2360 pche = pch + Buf->BufUsed;
2362 while (pchi < pche){
2363 ch = decode_hex(pchi);
2370 Buf->BufUsed = pch - Buf->buf;
2371 return Buf->BufUsed;
2375 * @ingroup StrBuf_DeEnCoder
2376 * @brief replace all chars >0x20 && < 0x7F with Mute
2377 * @param Mute char to put over invalid chars
2378 * @param Buf Buffor to transform
2380 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2384 if (Buf == NULL) return -1;
2385 pch = (unsigned char *)Buf->buf;
2386 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2387 if ((*pch < 0x20) || (*pch > 0x7F))
2391 return Buf->BufUsed;
2396 * @ingroup StrBuf_DeEnCoder
2397 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2398 * @param Buf Buffer to translate
2399 * @param StripBlanks Reduce several blanks to one?
2401 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2410 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2411 Buf->buf[Buf->BufUsed - 1] = '\0';
2416 while (a < Buf->BufUsed) {
2417 if (Buf->buf[a] == '+')
2419 else if (Buf->buf[a] == '%') {
2420 /* don't let % chars through, rather truncate the input. */
2421 if (a + 2 > Buf->BufUsed) {
2426 hex[0] = Buf->buf[a + 1];
2427 hex[1] = Buf->buf[a + 2];
2430 sscanf(hex, "%02x", &b);
2431 Buf->buf[a] = (char) b;
2432 len = Buf->BufUsed - a - 2;
2434 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2446 * @ingroup StrBuf_DeEnCoder
2447 * @brief RFC2047-encode a header field if necessary.
2448 * If no non-ASCII characters are found, the string
2449 * will be copied verbatim without encoding.
2451 * @param target Target buffer.
2452 * @param source Source string to be encoded.
2453 * @returns encoded length; -1 if non success.
2455 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2457 const char headerStr[] = "=?UTF-8?Q?";
2458 int need_to_encode = 0;
2462 if ((source == NULL) ||
2466 while ((i < source->BufUsed) &&
2467 (!IsEmptyStr (&source->buf[i])) &&
2468 (need_to_encode == 0)) {
2469 if (((unsigned char) source->buf[i] < 32) ||
2470 ((unsigned char) source->buf[i] > 126)) {
2476 if (!need_to_encode) {
2477 if (*target == NULL) {
2478 *target = NewStrBufPlain(source->buf, source->BufUsed);
2481 FlushStrBuf(*target);
2482 StrBufAppendBuf(*target, source, 0);
2484 return (*target)->BufUsed;
2486 if (*target == NULL)
2487 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2488 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2489 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2490 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2491 (*target)->BufUsed = sizeof(headerStr) - 1;
2492 for (i=0; (i < source->BufUsed); ++i) {
2493 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2494 IncreaseBuf(*target, 1, 0);
2495 ch = (unsigned char) source->buf[i];
2496 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2497 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2498 (*target)->BufUsed += 3;
2501 (*target)->buf[(*target)->BufUsed] = ch;
2502 (*target)->BufUsed++;
2506 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2507 IncreaseBuf(*target, 1, 0);
2509 (*target)->buf[(*target)->BufUsed++] = '?';
2510 (*target)->buf[(*target)->BufUsed++] = '=';
2511 (*target)->buf[(*target)->BufUsed] = '\0';
2512 return (*target)->BufUsed;;
2517 static void AddRecipient(StrBuf *Target,
2519 StrBuf *EmailAddress,
2524 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2525 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2527 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
2528 StrBufRFC2047encode(&EncBuf, UserName);
2529 StrBufAppendBuf(Target, EncBuf, 0);
2530 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2531 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
2533 if (StrLength(EmailAddress) > 0){
2534 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2535 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2536 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2542 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2543 * \param Recp Source list of email recipients
2544 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2545 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2546 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2547 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2549 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp,
2551 StrBuf *EmailAddress,
2557 const char *pch, *pche;
2558 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2560 if ((Recp == NULL) || (StrLength(Recp) == 0))
2565 pche = pch + StrLength(Recp);
2567 if (!CheckEncode(pch, -1, pche))
2568 return NewStrBufDup(Recp);
2570 Target = NewStrBufPlain(NULL, StrLength(Recp));
2572 while ((pch != NULL) && (pch < pche))
2576 while (isspace(*pch)) pch++;
2577 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2579 if ((*pch == '"') || (*pch == '\'')) {
2580 UserStart = pch + 1;
2582 UserEnd = strchr(UserStart, *pch);
2583 if (UserEnd == NULL)
2584 break; ///TODO: Userfeedback??
2585 EmailStart = UserEnd + 1;
2586 while (isspace(*EmailStart))
2588 if (UserEnd == UserStart) {
2589 UserStart = UserEnd = NULL;
2592 if (*EmailStart == '<') {
2594 EmailEnd = strchr(EmailStart, '>');
2595 if (EmailEnd == NULL)
2596 EmailEnd = strchr(EmailStart, ',');
2600 EmailEnd = strchr(EmailStart, ',');
2602 if (EmailEnd == NULL)
2610 EmailEnd = strchr(UserStart, ',');
2611 if (EmailEnd == NULL) {
2612 EmailEnd = strchr(pch, '>');
2614 if (EmailEnd != NULL) {
2625 while ((EmailEnd > UserStart) && !gt &&
2626 ((*EmailEnd == ',') ||
2627 (*EmailEnd == '>') ||
2628 (isspace(*EmailEnd))))
2630 if (*EmailEnd == '>')
2635 if (EmailEnd == UserStart)
2639 EmailStart = strchr(UserStart, '<');
2640 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2642 UserEnd = EmailStart - 1;
2644 if (UserStart >= UserEnd)
2645 UserStart = UserEnd = NULL;
2646 At = strchr(EmailStart, '@');
2648 else { /* this is a local recipient... no domain, just a realname */
2649 EmailStart = UserStart;
2650 At = strchr(EmailStart, '@');
2656 EmailStart = UserStart;
2662 if ((UserStart != NULL) && (UserEnd != NULL))
2663 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2664 else if ((UserStart != NULL) && (UserEnd == NULL))
2665 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2667 FlushStrBuf(UserName);
2669 if ((EmailStart != NULL) && (EmailEnd != NULL))
2670 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2671 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2672 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2674 FlushStrBuf(EmailAddress);
2676 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2681 if ((pch != NULL) && (*pch == ','))
2683 if (pch != NULL) while (isspace(*pch))
2692 * @brief replaces all occurances of 'search' by 'replace'
2693 * @param buf Buffer to modify
2694 * @param search character to search
2695 * @param replace character to replace search by
2697 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2702 for (i=0; i<buf->BufUsed; i++)
2703 if (buf->buf[i] == search)
2704 buf->buf[i] = replace;
2710 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2711 * @param buf Buffer to modify
2713 void StrBufToUnixLF(StrBuf *buf)
2715 char *pche, *pchS, *pchT;
2719 pche = buf->buf + buf->BufUsed;
2720 pchS = pchT = buf->buf;
2726 if (*pchS != '\n') {
2735 buf->BufUsed = pchT - buf->buf;
2739 /*******************************************************************************
2740 * Iconv Wrapper; RFC822 de/encoding *
2741 *******************************************************************************/
2744 * @ingroup StrBuf_DeEnCoder
2745 * @brief Wrapper around iconv_open()
2746 * Our version adds aliases for non-standard Microsoft charsets
2747 * such as 'MS950', aliasing them to names like 'CP950'
2749 * @param tocode Target encoding
2750 * @param fromcode Source encoding
2751 * @param pic anonimized pointer to iconv struct
2753 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2756 iconv_t ic = (iconv_t)(-1) ;
2757 ic = iconv_open(tocode, fromcode);
2758 if (ic == (iconv_t)(-1) ) {
2759 char alias_fromcode[64];
2760 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2761 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2762 alias_fromcode[0] = 'C';
2763 alias_fromcode[1] = 'P';
2764 ic = iconv_open(tocode, alias_fromcode);
2767 *(iconv_t *)pic = ic;
2773 * @ingroup StrBuf_DeEnCoder
2774 * @brief find one chunk of a RFC822 encoded string
2775 * @param Buffer where to search
2776 * @param bptr where to start searching
2777 * @returns found position, NULL if none.
2779 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2782 /* Find the next ?Q? */
2783 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2786 end = strchr(bptr + 2, '?');
2791 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2792 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2793 (*(end + 2) == '?')) {
2794 /* skip on to the end of the cluster, the next ?= */
2795 end = strstr(end + 3, "?=");
2798 /* sort of half valid encoding, try to find an end. */
2799 end = strstr(bptr, "?=");
2806 * @ingroup StrBuf_DeEnCoder
2807 * @brief convert one buffer according to the preselected iconv pointer PIC
2808 * @param ConvertBuf buffer we need to translate
2809 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2810 * @param pic Pointer to the iconv-session Object
2812 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2818 char *ibuf; /**< Buffer of characters to be converted */
2819 char *obuf; /**< Buffer for converted characters */
2820 size_t ibuflen; /**< Length of input buffer */
2821 size_t obuflen; /**< Length of output buffer */
2824 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2825 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2826 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2828 ic = *(iconv_t*)pic;
2829 ibuf = ConvertBuf->buf;
2830 ibuflen = ConvertBuf->BufUsed;
2832 obuflen = TmpBuf->BufSize;
2834 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2837 if (errno == E2BIG) {
2839 IncreaseBuf(TmpBuf, 0, 0);
2844 else if (errno == EILSEQ){
2845 /* hm, invalid utf8 sequence... what to do now? */
2846 /* An invalid multibyte sequence has been encountered in the input */
2848 else if (errno == EINVAL) {
2849 /* An incomplete multibyte sequence has been encountered in the input. */
2852 FlushStrBuf(TmpBuf);
2855 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2856 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2858 /* little card game: wheres the red lady? */
2859 SwapBuffers(ConvertBuf, TmpBuf);
2860 FlushStrBuf(TmpBuf);
2867 * @ingroup StrBuf_DeEnCoder
2868 * @brief catches one RFC822 encoded segment, and decodes it.
2869 * @param Target buffer to fill with result
2870 * @param DecodeMe buffer with stuff to process
2871 * @param SegmentStart points to our current segment in DecodeMe
2872 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2873 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2874 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2875 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2877 inline static void DecodeSegment(StrBuf *Target,
2878 const StrBuf *DecodeMe,
2879 const char *SegmentStart,
2880 const char *SegmentEnd,
2882 StrBuf *ConvertBuf2,
2883 StrBuf *FoundCharset)
2889 iconv_t ic = (iconv_t)(-1);
2893 /* Now we handle foreign character sets properly encoded
2894 * in RFC2047 format.
2896 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2897 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2898 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2899 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2900 if (FoundCharset != NULL) {
2901 FlushStrBuf(FoundCharset);
2902 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2904 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2905 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2907 *encoding = toupper(*encoding);
2908 if (*encoding == 'B') { /**< base64 */
2909 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2911 ConvertBuf->BufUsed);
2913 else if (*encoding == 'Q') { /**< quoted-printable */
2917 while (pos < ConvertBuf->BufUsed)
2919 if (ConvertBuf->buf[pos] == '_')
2920 ConvertBuf->buf[pos] = ' ';
2924 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2927 ConvertBuf->BufUsed);
2930 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2933 ctdl_iconv_open("UTF-8", charset, &ic);
2934 if (ic != (iconv_t)(-1) ) {
2936 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2937 StrBufAppendBuf(Target, ConvertBuf2, 0);
2942 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2948 * @ingroup StrBuf_DeEnCoder
2949 * @brief Handle subjects with RFC2047 encoding such as:
2950 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2951 * @param Target where to put the decoded string to
2952 * @param DecodeMe buffer with encoded string
2953 * @param DefaultCharset if we don't find one, which should we use?
2954 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2955 * put it here for later use where no string might be known.
2957 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2959 StrBuf *DecodedInvalidBuf = NULL;
2960 StrBuf *ConvertBuf, *ConvertBuf2;
2961 const StrBuf *DecodeMee = DecodeMe;
2962 const char *start, *end, *next, *nextend, *ptr = NULL;
2964 iconv_t ic = (iconv_t)(-1) ;
2969 int illegal_non_rfc2047_encoding = 0;
2971 /* Sometimes, badly formed messages contain strings which were simply
2972 * written out directly in some foreign character set instead of
2973 * using RFC2047 encoding. This is illegal but we will attempt to
2974 * handle it anyway by converting from a user-specified default
2975 * charset to UTF-8 if we see any nonprintable characters.
2978 len = StrLength(DecodeMe);
2979 for (i=0; i<DecodeMe->BufUsed; ++i) {
2980 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2981 illegal_non_rfc2047_encoding = 1;
2986 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2987 if ((illegal_non_rfc2047_encoding) &&
2988 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2989 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2992 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2993 if (ic != (iconv_t)(-1) ) {
2994 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2995 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2996 DecodeMee = DecodedInvalidBuf;
3002 /* pre evaluate the first pair */
3003 nextend = end = NULL;
3004 len = StrLength(DecodeMee);
3005 start = strstr(DecodeMee->buf, "=?");
3006 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3008 end = FindNextEnd (DecodeMee, start);
3010 StrBufAppendBuf(Target, DecodeMee, 0);
3011 FreeStrBuf(&ConvertBuf);
3012 FreeStrBuf(&DecodedInvalidBuf);
3016 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3018 if (start != DecodeMee->buf) {
3021 nFront = start - DecodeMee->buf;
3022 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3026 * Since spammers will go to all sorts of absurd lengths to get their
3027 * messages through, there are LOTS of corrupt headers out there.
3028 * So, prevent a really badly formed RFC2047 header from throwing
3029 * this function into an infinite loop.
3031 while ((start != NULL) &&
3038 DecodeSegment(Target,
3046 next = strstr(end, "=?");
3048 if ((next != NULL) &&
3050 nextend = FindNextEnd(DecodeMee, next);
3051 if (nextend == NULL)
3054 /* did we find two partitions */
3055 if ((next != NULL) &&
3059 while ((ptr < next) &&
3066 * did we find a gab just filled with blanks?
3067 * if not, copy its stuff over.
3071 StrBufAppendBufPlain(Target,
3077 /* our next-pair is our new first pair now. */
3083 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3084 if ((end != NULL) && (end < nextend)) {
3086 while ( (ptr < nextend) &&
3093 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3095 FreeStrBuf(&ConvertBuf);
3096 FreeStrBuf(&ConvertBuf2);
3097 FreeStrBuf(&DecodedInvalidBuf);
3100 /*******************************************************************************
3101 * Manipulating UTF-8 Strings *
3102 *******************************************************************************/
3106 * @brief evaluate the length of an utf8 special character sequence
3107 * @param Char the character to examine
3108 * @returns width of utf8 chars in bytes
3110 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3115 while ((n < 8) && ((test & *CharS) != 0)) {
3119 if ((n > 6) || ((CharE - CharS) < n))
3126 * @brief detect whether this char starts an utf-8 encoded char
3127 * @param Char character to inspect
3128 * @returns yes or no
3130 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3132 /** 11??.???? indicates an UTF8 Sequence. */
3133 return ((Char & 0xC0) != 0);
3138 * @brief measure the number of glyphs in an UTF8 string...
3139 * @param Buf string to measure
3140 * @returns the number of glyphs in Buf
3142 long StrBuf_Utf8StrLen(StrBuf *Buf)
3148 if ((Buf == NULL) || (Buf->BufUsed == 0))
3151 eptr = Buf->buf + Buf->BufUsed;
3152 while ((aptr < eptr) && (*aptr != '\0')) {
3153 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3154 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3155 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3168 * @brief cuts a string after maxlen glyphs
3169 * @param Buf string to cut to maxlen glyphs
3170 * @param maxlen how long may the string become?
3171 * @returns current length of the string
3173 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3179 eptr = Buf->buf + Buf->BufUsed;
3180 while ((aptr < eptr) && (*aptr != '\0')) {
3181 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3182 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3183 while ((*aptr++ != '\0') && (m-- > 0));
3192 Buf->BufUsed = aptr - Buf->buf;
3193 return Buf->BufUsed;
3196 return Buf->BufUsed;
3204 /*******************************************************************************
3206 *******************************************************************************/
3209 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3210 #define OS_CODE 0x03 /*< unix */
3213 * @ingroup StrBuf_DeEnCoder
3214 * @brief uses the same calling syntax as compress2(), but it
3215 * creates a stream compatible with HTTP "Content-encoding: gzip"
3216 * @param dest compressed buffer
3217 * @param destLen length of the compresed data
3218 * @param source source to encode
3219 * @param sourceLen length of source to encode
3220 * @param level compression level
3222 int ZEXPORT compress_gzip(Bytef * dest,
3224 const Bytef * source,
3228 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3230 /* write gzip header */
3231 snprintf((char *) dest, *destLen,
3232 "%c%c%c%c%c%c%c%c%c%c",
3233 gz_magic[0], gz_magic[1], Z_DEFLATED,
3234 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3237 /* normal deflate */
3240 stream.next_in = (Bytef *) source;
3241 stream.avail_in = (uInt) sourceLen;
3242 stream.next_out = dest + 10L; // after header
3243 stream.avail_out = (uInt) * destLen;
3244 if ((uLong) stream.avail_out != *destLen)
3247 stream.zalloc = (alloc_func) 0;
3248 stream.zfree = (free_func) 0;
3249 stream.opaque = (voidpf) 0;
3251 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3252 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3256 err = deflate(&stream, Z_FINISH);
3257 if (err != Z_STREAM_END) {
3258 deflateEnd(&stream);
3259 return err == Z_OK ? Z_BUF_ERROR : err;
3261 *destLen = stream.total_out + 10L;
3263 /* write CRC and Length */
3264 uLong crc = crc32(0L, source, sourceLen);
3266 for (n = 0; n < 4; ++n, ++*destLen) {
3267 dest[*destLen] = (int) (crc & 0xff);
3270 uLong len = stream.total_in;
3271 for (n = 0; n < 4; ++n, ++*destLen) {
3272 dest[*destLen] = (int) (len & 0xff);
3275 err = deflateEnd(&stream);
3282 * @ingroup StrBuf_DeEnCoder
3283 * @brief compress the buffer with gzip
3284 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3285 * @param Buf buffer whose content is to be gzipped
3287 int CompressBuffer(StrBuf *Buf)
3290 char *compressed_data = NULL;
3291 size_t compressed_len, bufsize;
3294 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3295 compressed_data = malloc(compressed_len);
3297 if (compressed_data == NULL)
3299 /* Flush some space after the used payload so valgrind shuts up... */
3300 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3301 Buf->buf[Buf->BufUsed + i++] = '\0';
3302 if (compress_gzip((Bytef *) compressed_data,
3305 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3308 Buf->buf = compressed_data;
3309 Buf->BufUsed = compressed_len;
3310 Buf->BufSize = bufsize;
3311 /* Flush some space after the used payload so valgrind shuts up... */
3313 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3314 Buf->buf[Buf->BufUsed + i++] = '\0';
3317 free(compressed_data);
3319 #endif /* HAVE_ZLIB */
3325 /*******************************************************************************
3326 * File I/O; Prefer buffered read since its faster! *
3327 *******************************************************************************/
3330 * @ingroup StrBuf_IO
3331 * @brief Read a line from socket
3332 * flushes and closes the FD on error
3333 * @param buf the buffer to get the input to
3334 * @param fd pointer to the filedescriptor to read
3335 * @param append Append to an existing string or replace?
3336 * @param Error strerror() on error
3337 * @returns numbers of chars read
3339 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3341 int len, rlen, slen;
3346 slen = len = buf->BufUsed;
3348 rlen = read(*fd, &buf->buf[len], 1);
3350 *Error = strerror(errno);
3357 if (buf->buf[len] == '\n')
3359 if (buf->buf[len] != '\r')
3361 if (len + 2 >= buf->BufSize) {
3363 buf->buf[len+1] = '\0';
3364 IncreaseBuf(buf, 1, -1);
3368 buf->buf[len] = '\0';
3373 * @ingroup StrBuf_BufferedIO
3374 * @brief Read a line from socket
3375 * flushes and closes the FD on error
3376 * @param Line the line to read from the fd / I/O Buffer
3377 * @param buf the buffer to get the input to
3378 * @param fd pointer to the filedescriptor to read
3379 * @param timeout number of successless selects until we bail out
3380 * @param selectresolution how long to wait on each select
3381 * @param Error strerror() on error
3382 * @returns numbers of chars read
3384 int StrBufTCP_read_buffered_line(StrBuf *Line,
3388 int selectresolution,
3392 int nSuccessLess = 0;
3399 if (buf->BufUsed > 0) {
3400 pch = strchr(buf->buf, '\n');
3403 len = pch - buf->buf;
3404 if (len > 0 && (*(pch - 1) == '\r') )
3406 StrBufSub(Line, buf, 0, len - rlen);
3407 StrBufCutLeft(buf, len + 1);
3412 if (buf->BufSize - buf->BufUsed < 10)
3413 IncreaseBuf(buf, 1, -1);
3415 fdflags = fcntl(*fd, F_GETFL);
3416 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3418 while ((nSuccessLess < timeout) && (pch == NULL)) {
3420 tv.tv_sec = selectresolution;
3425 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3426 *Error = strerror(errno);
3432 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3437 &buf->buf[buf->BufUsed],
3438 buf->BufSize - buf->BufUsed - 1);
3440 *Error = strerror(errno);
3445 else if (rlen > 0) {
3447 buf->BufUsed += rlen;
3448 buf->buf[buf->BufUsed] = '\0';
3449 if (buf->BufUsed + 10 > buf->BufSize) {
3450 IncreaseBuf(buf, 1, -1);
3452 pch = strchr(buf->buf, '\n');
3459 len = pch - buf->buf;
3460 if (len > 0 && (*(pch - 1) == '\r') )
3462 StrBufSub(Line, buf, 0, len - rlen);
3463 StrBufCutLeft(buf, len + 1);
3470 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3471 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3472 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3474 * @ingroup StrBuf_BufferedIO
3475 * @brief Read a line from socket
3476 * flushes and closes the FD on error
3477 * @param Line where to append our Line read from the fd / I/O Buffer;
3478 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3479 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3480 * @param fd pointer to the filedescriptor to read
3481 * @param timeout number of successless selects until we bail out
3482 * @param selectresolution how long to wait on each select
3483 * @param Error strerror() on error
3484 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3486 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3491 int selectresolution,
3494 const char *pche = NULL;
3495 const char *pos = NULL;
3497 int len, rlen, retlen;
3498 int nSuccessLess = 0;
3500 const char *pch = NULL;
3506 if ((Line == NULL) ||
3513 *Error = ErrRBLF_PreConditionFailed;
3518 if ((IOBuf->BufUsed > 0) &&
3520 (pos < IOBuf->buf + IOBuf->BufUsed))
3524 pche = IOBuf->buf + IOBuf->BufUsed;
3528 while ((pch < pche) && (*pch != '\n'))
3530 if (Line->BufUsed + 10 > Line->BufSize)
3533 apos = pcht - Line->buf;
3535 IncreaseBuf(Line, 1, -1);
3536 pcht = Line->buf + apos;
3544 if (len > 0 && (*(pch - 1) == '\r') )
3553 if ((pch >= pche) || (*pch == '\0'))
3561 if ((pch != NULL) &&
3564 if (pch + 1 >= pche) {
3577 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3579 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3580 IncreaseBuf(IOBuf, 1, -1);
3582 fdflags = fcntl(*fd, F_GETFL);
3583 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3586 while ((nSuccessLess < timeout) &&
3596 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3597 *Error = strerror(errno);
3601 *Error = ErrRBLF_SelectFailed;
3604 if (! FD_ISSET(*fd, &rfds) != 0) {
3610 &IOBuf->buf[IOBuf->BufUsed],
3611 IOBuf->BufSize - IOBuf->BufUsed - 1);
3613 *Error = strerror(errno);
3618 else if (rlen > 0) {
3620 pLF = IOBuf->buf + IOBuf->BufUsed;
3621 IOBuf->BufUsed += rlen;
3622 IOBuf->buf[IOBuf->BufUsed] = '\0';
3624 pche = IOBuf->buf + IOBuf->BufUsed;
3626 while ((pLF < pche) && (*pLF != '\n'))
3628 if ((pLF >= pche) || (*pLF == '\0'))
3631 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3635 if (pLF != NULL) apos = pLF - IOBuf->buf;
3636 IncreaseBuf(IOBuf, 1, -1);
3637 if (pLF != NULL) pLF = IOBuf->buf + apos;
3647 if (len > 0 && (*(pLF - 1) == '\r') )
3649 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3650 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3656 return retlen + len;
3658 *Error = ErrRBLF_NotEnoughSentFromServer;
3663 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3665 * @ingroup StrBuf_IO
3666 * @brief Input binary data from socket
3667 * flushes and closes the FD on error
3668 * @param Buf the buffer to get the input to
3669 * @param fd pointer to the filedescriptor to read
3670 * @param append Append to an existing string or replace?
3671 * @param nBytes the maximal number of bytes to read
3672 * @param Error strerror() on error
3673 * @returns numbers of chars read
3675 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3678 int len, rlen, slen;
3686 if ((Buf == NULL) || (*fd == -1))
3688 *Error = ErrRBLF_BLOBPreConditionFailed;
3693 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3694 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3696 ptr = Buf->buf + Buf->BufUsed;
3698 slen = len = Buf->BufUsed;
3700 fdflags = fcntl(*fd, F_GETFL);
3701 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3703 while ((nRead < nBytes) &&
3713 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3714 *Error = strerror(errno);
3718 *Error = ErrRBLF_SelectFailed;
3721 if (! FD_ISSET(*fd, &rfds) != 0) {
3727 if ((rlen = read(*fd,
3729 nBytes - nRead)) == -1) {
3732 *Error = strerror(errno);
3737 Buf->BufUsed += rlen;
3739 Buf->buf[Buf->BufUsed] = '\0';
3743 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3744 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3746 * @ingroup StrBuf_BufferedIO
3747 * @brief Input binary data from socket
3748 * flushes and closes the FD on error
3749 * @param Blob put binary thing here
3750 * @param IOBuf the buffer to get the input to
3751 * @param Pos offset inside of IOBuf
3752 * @param fd pointer to the filedescriptor to read
3753 * @param append Append to an existing string or replace?
3754 * @param nBytes the maximal number of bytes to read
3755 * @param check whether we should search for '000\n' terminators in case of timeouts
3756 * @param Error strerror() on error
3757 * @returns numbers of chars read
3759 int StrBufReadBLOBBuffered(StrBuf *Blob,
3774 int nAlreadyRead = 0;
3780 int nSuccessLess = 0;
3783 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3787 *Error = ErrRBB_BLOBFPreConditionFailed;
3793 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3794 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3799 len = pos - IOBuf->buf;
3800 rlen = IOBuf->BufUsed - len;
3803 if ((IOBuf->BufUsed > 0) &&
3805 (pos < IOBuf->buf + IOBuf->BufUsed))
3807 pche = IOBuf->buf + IOBuf->BufUsed;
3810 if (rlen < nBytes) {
3811 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3812 Blob->BufUsed += rlen;
3813 Blob->buf[Blob->BufUsed] = '\0';
3814 nAlreadyRead = nRead = rlen;
3817 if (rlen >= nBytes) {
3818 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3819 Blob->BufUsed += nBytes;
3820 Blob->buf[Blob->BufUsed] = '\0';
3821 if (rlen == nBytes) {
3833 if (IOBuf->BufSize < nBytes - nRead)
3834 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3837 slen = len = Blob->BufUsed;
3839 fdflags = fcntl(*fd, F_GETFL);
3840 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3848 while ((nSuccessLess < MaxTries) &&
3858 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3859 *Error = strerror(errno);
3863 *Error = ErrRBLF_SelectFailed;
3866 if (! FD_ISSET(*fd, &rfds) != 0) {
3873 IOBuf->BufSize - (ptr - IOBuf->buf));
3877 *Error = strerror(errno);
3880 else if (rlen == 0){
3881 if ((check == NNN_TERM) &&
3883 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3885 StrBufPlain(Blob, HKEY("\n000\n"));
3886 StrBufCutRight(Blob, 5);
3887 return Blob->BufUsed;
3889 else if (!IsNonBlock)
3891 else if (nSuccessLess > MaxTries) {
3893 *Error = ErrRBB_too_many_selects;
3897 else if (rlen > 0) {
3901 IOBuf->BufUsed += rlen;
3904 if (nSuccessLess >= MaxTries) {
3906 *Error = ErrRBB_too_many_selects;
3910 if (nRead > nBytes) {
3911 *Pos = IOBuf->buf + nBytes;
3913 Blob->buf[Blob->BufUsed] = '\0';
3914 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3918 return nRead + nAlreadyRead;
3922 * @ingroup StrBuf_IO
3923 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3924 * @param LineBuf your line will be copied here.
3925 * @param Buf BLOB with lines of text...
3926 * @param Ptr moved arround to keep the next-line across several iterations
3927 * has to be &NULL on start; will be &NotNULL on end of buffer
3928 * @returns size of copied buffer
3930 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3932 const char *aptr, *ptr, *eptr;
3935 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3936 *Ptr = StrBufNOTNULL;
3940 FlushStrBuf(LineBuf);
3942 ptr = aptr = Buf->buf;
3946 optr = LineBuf->buf;
3947 eptr = Buf->buf + Buf->BufUsed;
3948 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3950 while ((ptr <= eptr) &&
3957 LineBuf->BufUsed = optr - LineBuf->buf;
3958 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3959 optr = LineBuf->buf + LineBuf->BufUsed;
3960 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3964 if ((ptr >= eptr) && (optr > LineBuf->buf))
3966 LineBuf->BufUsed = optr - LineBuf->buf;
3968 if ((ptr <= eptr) && (*ptr == '\r'))
3970 if ((ptr <= eptr) && (*ptr == '\n'))
3977 *Ptr = StrBufNOTNULL;
3980 return Buf->BufUsed - (ptr - Buf->buf);
3985 * @ingroup StrBuf_IO
3986 * @brief removes double slashes from pathnames
3987 * @param Dir directory string to filter
3988 * @param RemoveTrailingSlash allows / disallows trailing slashes
3990 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3996 while (!IsEmptyStr(a)) {
4008 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4013 Dir->BufUsed = b - Dir->buf;