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;
33 * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
37 * Private Structure for the Stringbuffer
40 char *buf; /**< the pointer to the dynamic buffer */
41 long BufSize; /**< how many spcae do we optain */
42 long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
43 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
47 char bt_lastinc [SIZ];
52 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
53 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
57 static void StrBufBacktrace(StrBuf *Buf, int which)
61 void *stack_frames[50];
66 pstart = pch = Buf->bt;
68 pstart = pch = Buf->bt_lastinc;
69 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
70 strings = backtrace_symbols(stack_frames, size);
71 for (i = 0; i < size; i++) {
73 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
75 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
87 * @brief Cast operator to Plain String
88 * @note if the buffer is altered by StrBuf operations, this pointer may become
89 * invalid. So don't lean on it after altering the buffer!
90 * Since this operation is considered cheap, rather call it often than risking
91 * your pointer to become invalid!
92 * @param Str the string we want to get the c-string representation for
93 * @returns the Pointer to the Content. Don't mess with it!
95 inline const char *ChrPtr(const StrBuf *Str)
104 * @brief since we know strlen()'s result, provide it here.
105 * @param Str the string to return the length to
106 * @returns contentlength of the buffer
108 inline int StrLength(const StrBuf *Str)
110 return (Str != NULL) ? Str->BufUsed : 0;
115 * @brief local utility function to resize the buffer
116 * @param Buf the buffer whichs storage we should increase
117 * @param KeepOriginal should we copy the original buffer or just start over with a new one
118 * @param DestSize what should fit in after?
120 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
123 size_t NewSize = Buf->BufSize * 2;
129 while (NewSize <= DestSize)
132 NewBuf= (char*) malloc(NewSize);
136 if (KeepOriginal && (Buf->BufUsed > 0))
138 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
147 Buf->BufSize = NewSize;
150 #ifdef HAVE_BACKTRACE
151 StrBufBacktrace(Buf, 1);
159 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
160 * @param Buf Buffer to shrink (has to be empty)
161 * @param ThreshHold if the buffer is bigger then this, its readjusted
162 * @param NewSize if we Shrink it, how big are we going to be afterwards?
164 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
166 if (Buf->BufUsed > ThreshHold) {
168 Buf->buf = (char*) malloc(NewSize);
170 Buf->BufSize = NewSize;
176 * @brief shrink long term buffers to their real size so they don't waste memory
177 * @param Buf buffer to shrink
178 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
179 * @returns physical size of the buffer
181 long StrBufShrinkToFit(StrBuf *Buf, int Force)
184 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
186 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
187 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
188 Buf->BufSize = Buf->BufUsed + 1;
197 * @brief Allocate a new buffer with default buffer size
198 * @returns the new stringbuffer
200 StrBuf* NewStrBuf(void)
204 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
205 NewBuf->buf = (char*) malloc(BaseStrBufSize);
206 NewBuf->buf[0] = '\0';
207 NewBuf->BufSize = BaseStrBufSize;
209 NewBuf->ConstBuf = 0;
211 NewBuf->nIncreases = 0;
212 NewBuf->bt[0] = '\0';
213 NewBuf->bt_lastinc[0] = '\0';
214 #ifdef HAVE_BACKTRACE
215 StrBufBacktrace(NewBuf, 0);
223 * @brief Copy Constructor; returns a duplicate of CopyMe
224 * @param CopyMe Buffer to faxmilate
225 * @returns the new stringbuffer
227 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
234 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
235 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
236 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
237 NewBuf->BufUsed = CopyMe->BufUsed;
238 NewBuf->BufSize = CopyMe->BufSize;
239 NewBuf->ConstBuf = 0;
241 NewBuf->nIncreases = 0;
242 NewBuf->bt[0] = '\0';
243 NewBuf->bt_lastinc[0] = '\0';
244 #ifdef HAVE_BACKTRACE
245 StrBufBacktrace(NewBuf, 0);
253 * @brief create a new Buffer using an existing c-string
254 * this function should also be used if you want to pre-suggest
255 * the buffer size to allocate in conjunction with ptr == NULL
256 * @param ptr the c-string to copy; may be NULL to create a blank instance
257 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
258 * @returns the new stringbuffer
260 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
263 size_t Siz = BaseStrBufSize;
266 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
268 CopySize = strlen((ptr != NULL)?ptr:"");
272 while (Siz <= CopySize)
275 NewBuf->buf = (char*) malloc(Siz);
276 NewBuf->BufSize = Siz;
278 memcpy(NewBuf->buf, ptr, CopySize);
279 NewBuf->buf[CopySize] = '\0';
280 NewBuf->BufUsed = CopySize;
283 NewBuf->buf[0] = '\0';
286 NewBuf->ConstBuf = 0;
288 NewBuf->nIncreases = 0;
289 NewBuf->bt[0] = '\0';
290 NewBuf->bt_lastinc[0] = '\0';
291 #ifdef HAVE_BACKTRACE
292 StrBufBacktrace(NewBuf, 0);
300 * @brief Set an existing buffer from a c-string
301 * @param ptr c-string to put into
302 * @param nChars set to -1 if we should work 0-terminated
303 * @returns the new length of the string
305 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
307 size_t Siz = Buf->BufSize;
311 CopySize = strlen(ptr);
315 while (Siz <= CopySize)
318 if (Siz != Buf->BufSize)
319 IncreaseBuf(Buf, 0, Siz);
320 memcpy(Buf->buf, ptr, CopySize);
321 Buf->buf[CopySize] = '\0';
322 Buf->BufUsed = CopySize;
330 * @brief use strbuf as wrapper for a string constant for easy handling
331 * @param StringConstant a string to wrap
332 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
334 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
338 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
339 NewBuf->buf = (char*) StringConstant;
340 NewBuf->BufSize = SizeOfStrConstant;
341 NewBuf->BufUsed = SizeOfStrConstant;
342 NewBuf->ConstBuf = 1;
344 NewBuf->nIncreases = 0;
345 NewBuf->bt[0] = '\0';
346 NewBuf->bt_lastinc[0] = '\0';
354 * @brief flush the content of a Buf; keep its struct
355 * @param buf Buffer to flush
357 int FlushStrBuf(StrBuf *buf)
369 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
370 * @param buf Buffer to wipe
372 int FLUSHStrBuf(StrBuf *buf)
378 if (buf->BufUsed > 0) {
379 memset(buf->buf, 0, buf->BufUsed);
386 int hFreeDbglog = -1;
390 * @brief Release a Buffer
391 * Its a double pointer, so it can NULL your pointer
392 * so fancy SIG11 appear instead of random results
393 * @param FreeMe Pointer Pointer to the buffer to free
395 void FreeStrBuf (StrBuf **FreeMe)
400 if (hFreeDbglog == -1){
401 pid_t pid = getpid();
403 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
404 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
406 if ((*FreeMe)->nIncreases > 0)
410 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
411 (*FreeMe)->nIncreases,
415 (*FreeMe)->bt_lastinc);
416 n = write(hFreeDbglog, buf, n);
422 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
425 n = write(hFreeDbglog, buf, n);
428 if (!(*FreeMe)->ConstBuf)
429 free((*FreeMe)->buf);
436 * @brief flatten a Buffer to the Char * we return
437 * Its a double pointer, so it can NULL your pointer
438 * so fancy SIG11 appear instead of random results
439 * The Callee then owns the buffer and is responsible for freeing it.
440 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
441 * @returns the pointer of the buffer; Callee owns the memory thereafter.
443 char *SmashStrBuf (StrBuf **SmashMe)
447 if (*SmashMe == NULL)
450 if (hFreeDbglog == -1){
451 pid_t pid = getpid();
453 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
454 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
456 if ((*SmashMe)->nIncreases > 0)
460 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
461 (*SmashMe)->nIncreases,
465 (*SmashMe)->bt_lastinc);
466 n = write(hFreeDbglog, buf, n);
472 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
474 (*SmashMe)->BufSize);
475 n = write(hFreeDbglog, buf, n);
478 Ret = (*SmashMe)->buf;
486 * @brief Release the buffer
487 * If you want put your StrBuf into a Hash, use this as Destructor.
488 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
490 void HFreeStrBuf (void *VFreeMe)
492 StrBuf *FreeMe = (StrBuf*)VFreeMe;
496 if (hFreeDbglog == -1){
497 pid_t pid = getpid();
499 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
500 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
502 if (FreeMe->nIncreases > 0)
506 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
512 write(hFreeDbglog, buf, n);
518 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
524 if (!FreeMe->ConstBuf)
531 * @brief Wrapper around atol
533 long StrTol(const StrBuf *Buf)
538 return atol(Buf->buf);
545 * @brief Wrapper around atoi
547 int StrToi(const StrBuf *Buf)
551 if (Buf->BufUsed > 0)
552 return atoi(Buf->buf);
559 * @brief Checks to see if the string is a pure number
561 int StrBufIsNumber(const StrBuf *Buf) {
566 strtoll(Buf->buf, &pEnd, 10);
567 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
574 * @brief modifies a Single char of the Buf
575 * You can point to it via char* or a zero-based integer
576 * @param Buf The buffer to manipulate
577 * @param ptr char* to zero; use NULL if unused
578 * @param nThChar zero based pointer into the string; use -1 if unused
579 * @param PeekValue The Character to place into the position
581 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
586 nThChar = ptr - Buf->buf;
587 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
589 Buf->buf[nThChar] = PeekValue;
595 * @brief Append a StringBuffer to the buffer
596 * @param Buf Buffer to modify
597 * @param AppendBuf Buffer to copy at the end of our buffer
598 * @param Offset Should we start copying from an offset?
600 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
602 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
605 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
608 AppendBuf->BufUsed + Buf->BufUsed);
610 memcpy(Buf->buf + Buf->BufUsed,
611 AppendBuf->buf + Offset,
612 AppendBuf->BufUsed - Offset);
613 Buf->BufUsed += AppendBuf->BufUsed - Offset;
614 Buf->buf[Buf->BufUsed] = '\0';
620 * @brief Append a C-String to the buffer
621 * @param Buf Buffer to modify
622 * @param AppendBuf Buffer to copy at the end of our buffer
623 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
624 * @param Offset Should we start copying from an offset?
626 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
629 long BufSizeRequired;
631 if ((AppendBuf == NULL) || (Buf == NULL))
635 aps = strlen(AppendBuf + Offset);
637 aps = AppendSize - Offset;
639 BufSizeRequired = Buf->BufUsed + aps + 1;
640 if (Buf->BufSize <= BufSizeRequired)
641 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
643 memcpy(Buf->buf + Buf->BufUsed,
647 Buf->buf[Buf->BufUsed] = '\0';
652 * @brief Callback for cURL to append the webserver reply to a buffer
653 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
654 * @param size pre-defined by the cURL API; see man 3 curl for mre info
655 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
656 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
658 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
667 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
674 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
675 * @param outbuf the output buffer
676 * @param oblen the size of outbuf to sanitize
677 * @param strbuf the input buffer
679 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
681 const char *pch, *pche;
684 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
685 int eclen = sizeof(ec) -1;
687 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
689 if (PlainIn != NULL) {
690 len = strlen(PlainIn);
696 pche = pch + In->BufUsed;
703 pt = OutBuf->buf + OutBuf->BufUsed;
704 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
708 IncreaseBuf(OutBuf, 1, -1);
709 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
710 pt = OutBuf->buf + OutBuf->BufUsed;
714 for (b = 0; b < eclen; ++b) {
721 sprintf(pt,"%%%02X", *pch);
723 OutBuf->BufUsed += 3;
736 * @brief Append a string, escaping characters which have meaning in HTML.
738 * @param Target target buffer
739 * @param Source source buffer; set to NULL if you just have a C-String
740 * @param PlainIn Plain-C string to append; set to NULL if unused
741 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
742 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
743 * if set to 2, linebreaks are replaced by <br/>
745 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
747 const char *aptr, *eiptr;
751 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
754 if (PlainIn != NULL) {
756 len = strlen(PlainIn);
761 eiptr = aptr + Source->BufUsed;
762 len = Source->BufUsed;
768 bptr = Target->buf + Target->BufUsed;
769 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
771 while (aptr < eiptr){
773 IncreaseBuf(Target, 1, -1);
774 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
775 bptr = Target->buf + Target->BufUsed;
778 memcpy(bptr, "<", 4);
780 Target->BufUsed += 4;
782 else if (*aptr == '>') {
783 memcpy(bptr, ">", 4);
785 Target->BufUsed += 4;
787 else if (*aptr == '&') {
788 memcpy(bptr, "&", 5);
790 Target->BufUsed += 5;
792 else if (*aptr == '"') {
793 memcpy(bptr, """, 6);
795 Target->BufUsed += 6;
797 else if (*aptr == '\'') {
798 memcpy(bptr, "'", 5);
800 Target->BufUsed += 5;
802 else if (*aptr == LB) {
807 else if (*aptr == RB) {
812 else if (*aptr == QU) {
817 else if ((*aptr == 32) && (nbsp == 1)) {
818 memcpy(bptr, " ", 6);
820 Target->BufUsed += 6;
822 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
823 *bptr='\0'; /* nothing */
825 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
826 memcpy(bptr, "<br/>", 11);
828 Target->BufUsed += 11;
832 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
833 *bptr='\0'; /* nothing */
843 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
845 return Target->BufUsed;
850 * @brief Append a string, escaping characters which have meaning in HTML.
851 * Converts linebreaks into blanks; escapes single quotes
852 * @param Target target buffer
853 * @param Source source buffer; set to NULL if you just have a C-String
854 * @param PlainIn Plain-C string to append; set to NULL if unused
856 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
858 const char *aptr, *eiptr;
862 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
865 if (PlainIn != NULL) {
867 len = strlen(PlainIn);
872 eiptr = aptr + Source->BufUsed;
873 len = Source->BufUsed;
879 eptr = Target->buf + Target->BufSize - 8;
880 tptr = Target->buf + Target->BufUsed;
882 while (aptr < eiptr){
884 IncreaseBuf(Target, 1, -1);
885 eptr = Target->buf + Target->BufSize - 8;
886 tptr = Target->buf + Target->BufUsed;
893 else if (*aptr == '\r') {
897 else if (*aptr == '\'') {
903 Target->BufUsed += 5;
917 * @brief Append a string, escaping characters which have meaning in ICAL.
919 * @param Target target buffer
920 * @param Source source buffer; set to NULL if you just have a C-String
921 * @param PlainIn Plain-C string to append; set to NULL if unused
923 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
925 const char *aptr, *eiptr;
929 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
932 if (PlainIn != NULL) {
934 len = strlen(PlainIn);
939 eiptr = aptr + Source->BufUsed;
940 len = Source->BufUsed;
946 eptr = Target->buf + Target->BufSize - 8;
947 tptr = Target->buf + Target->BufUsed;
949 while (aptr < eiptr){
950 if(tptr + 3 >= eptr) {
951 IncreaseBuf(Target, 1, -1);
952 eptr = Target->buf + Target->BufSize - 8;
953 tptr = Target->buf + Target->BufUsed;
963 else if (*aptr == '\r') {
970 else if (*aptr == ',') {
987 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
989 * @param Target target buffer
990 * @param Source source buffer; set to NULL if you just have a C-String
991 * @param PlainIn Plain-C string to append; set to NULL if unused
992 * @returns size of result or -1
994 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
996 const char *aptr, *eiptr;
1000 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1003 if (PlainIn != NULL) {
1005 len = strlen(PlainIn);
1010 eiptr = aptr + Source->BufUsed;
1011 len = Source->BufUsed;
1017 bptr = Target->buf + Target->BufUsed;
1018 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1020 while (aptr < eiptr){
1022 IncreaseBuf(Target, 1, -1);
1023 eptr = Target->buf + Target->BufSize - 3;
1024 bptr = Target->buf + Target->BufUsed;
1031 Target->BufUsed += 2;
1032 } else if (*aptr == '\\') {
1037 Target->BufUsed += 2;
1047 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1049 return Target->BufUsed;
1054 * @brief Append a string, escaping characters which have meaning in HTML + json.
1056 * @param Target target buffer
1057 * @param Source source buffer; set to NULL if you just have a C-String
1058 * @param PlainIn Plain-C string to append; set to NULL if unused
1059 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1060 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1061 * if set to 2, linebreaks are replaced by <br/>
1063 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1065 const char *aptr, *eiptr;
1068 int IsUtf8Sequence = 0;
1070 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1073 if (PlainIn != NULL) {
1075 len = strlen(PlainIn);
1080 eiptr = aptr + Source->BufUsed;
1081 len = Source->BufUsed;
1087 bptr = Target->buf + Target->BufUsed;
1088 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1090 while (aptr < eiptr){
1092 IncreaseBuf(Target, 1, -1);
1093 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1094 bptr = Target->buf + Target->BufUsed;
1097 memcpy(bptr, "<", 4);
1099 Target->BufUsed += 4;
1101 else if (*aptr == '>') {
1102 memcpy(bptr, ">", 4);
1104 Target->BufUsed += 4;
1106 else if (*aptr == '&') {
1107 memcpy(bptr, "&", 5);
1109 Target->BufUsed += 5;
1111 else if (*aptr == LB) {
1116 else if (*aptr == RB) {
1121 else if ((*aptr == 32) && (nbsp == 1)) {
1122 memcpy(bptr, " ", 6);
1124 Target->BufUsed += 6;
1126 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1127 *bptr='\0'; /* nothing */
1129 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1130 memcpy(bptr, "<br/>", 11);
1132 Target->BufUsed += 11;
1135 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1136 *bptr='\0'; /* nothing */
1139 else if ((*aptr == '"') || (*aptr == QU)) {
1144 Target->BufUsed += 2;
1145 } else if (*aptr == '\\') {
1150 Target->BufUsed += 2;
1153 if (IsUtf8Sequence != 0) {
1162 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1174 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1176 return Target->BufUsed;
1182 * @brief extracts a substring from Source into dest
1183 * @param dest buffer to place substring into
1184 * @param Source string to copy substring from
1185 * @param Offset chars to skip from start
1186 * @param nChars number of chars to copy
1187 * @returns the number of chars copied; may be different from nChars due to the size of Source
1189 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1191 size_t NCharsRemain;
1192 if (Offset > Source->BufUsed)
1197 if (Offset + nChars < Source->BufUsed)
1199 if (nChars >= dest->BufSize)
1200 IncreaseBuf(dest, 0, nChars + 1);
1201 memcpy(dest->buf, Source->buf + Offset, nChars);
1202 dest->BufUsed = nChars;
1203 dest->buf[dest->BufUsed] = '\0';
1206 NCharsRemain = Source->BufUsed - Offset;
1207 if (NCharsRemain >= dest->BufSize)
1208 IncreaseBuf(dest, 0, NCharsRemain + 1);
1209 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1210 dest->BufUsed = NCharsRemain;
1211 dest->buf[dest->BufUsed] = '\0';
1212 return NCharsRemain;
1217 * @brief sprintf like function appending the formated string to the buffer
1218 * vsnprintf version to wrap into own calls
1219 * @param Buf Buffer to extend by format and @params
1220 * @param format printf alike format to add
1221 * @param ap va_list containing the items for format
1223 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1231 if ((Buf == NULL) || (format == NULL))
1234 BufSize = Buf->BufSize;
1235 nWritten = Buf->BufSize + 1;
1236 Offset = Buf->BufUsed;
1237 newused = Offset + nWritten;
1239 while (newused >= BufSize) {
1241 nWritten = vsnprintf(Buf->buf + Offset,
1242 Buf->BufSize - Offset,
1245 newused = Offset + nWritten;
1246 if (newused >= Buf->BufSize) {
1247 IncreaseBuf(Buf, 1, newused);
1248 newused = Buf->BufSize + 1;
1251 Buf->BufUsed = Offset + nWritten;
1252 BufSize = Buf->BufSize;
1260 * @brief sprintf like function appending the formated string to the buffer
1261 * @param Buf Buffer to extend by format and Params
1262 * @param format printf alike format to add
1264 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1272 if ((Buf == NULL) || (format == NULL))
1275 BufSize = Buf->BufSize;
1276 nWritten = Buf->BufSize + 1;
1277 Offset = Buf->BufUsed;
1278 newused = Offset + nWritten;
1280 while (newused >= BufSize) {
1281 va_start(arg_ptr, format);
1282 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1283 Buf->BufSize - Buf->BufUsed,
1286 newused = Buf->BufUsed + nWritten;
1287 if (newused >= Buf->BufSize) {
1288 IncreaseBuf(Buf, 1, newused);
1289 newused = Buf->BufSize + 1;
1292 Buf->BufUsed += nWritten;
1293 BufSize = Buf->BufSize;
1301 * @brief sprintf like function putting the formated string into the buffer
1302 * @param Buf Buffer to extend by format and Parameters
1303 * @param format printf alike format to add
1304 * @param ap va_list containing the items for format
1306 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1311 if ((Buf == NULL) || (format == NULL))
1314 nWritten = Buf->BufSize + 1;
1315 while (nWritten >= Buf->BufSize) {
1316 va_start(arg_ptr, format);
1317 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1319 if (nWritten >= Buf->BufSize) {
1320 IncreaseBuf(Buf, 0, 0);
1321 nWritten = Buf->BufSize + 1;
1324 Buf->BufUsed = nWritten ;
1331 * @brief Counts the numbmer of tokens in a buffer
1332 * @param source String to count tokens in
1333 * @param tok Tokenizer char to count
1334 * @returns numbers of tokenizer chars found
1336 int StrBufNum_tokens(const StrBuf *source, char tok)
1340 return num_tokens(source->buf, tok);
1344 * remove_token() - a tokenizer that kills, maims, and destroys
1348 * @brief a string tokenizer
1349 * @param Source StringBuffer to read into
1350 * @param parmnum n'th @parameter to remove
1351 * @param separator tokenizer @param
1352 * @returns -1 if not found, else length of token.
1354 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1357 char *d, *s, *end; /* dest, source */
1360 /* Find desired @parameter */
1361 end = Source->buf + Source->BufUsed;
1363 while ((count < parmnum) &&
1366 /* End of string, bail! */
1371 if (*d == separator) {
1376 if ((d == NULL) || (d >= end))
1377 return 0; /* @Parameter not found */
1379 /* Find next @parameter */
1381 while ((*s && *s != separator) &&
1386 if (*s == separator)
1390 /* Hack and slash */
1392 memmove(d, s, Source->BufUsed - (s - Source->buf));
1393 Source->BufUsed += ReducedBy;
1395 else if (d == Source->buf) {
1397 Source->BufUsed = 0;
1401 Source->BufUsed += ReducedBy;
1415 * @brief a string tokenizer
1416 * @param dest Destination StringBuffer
1417 * @param Source StringBuffer to read into
1418 * @param parmnum n'th Parameter to extract
1419 * @param separator tokenizer character
1420 * @returns -1 if not found, else length of token.
1422 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1424 const char *s, *e; //* source * /
1425 int len = 0; //* running total length of extracted string * /
1426 int current_token = 0; //* token currently being processed * /
1429 dest->buf[0] = '\0';
1435 if ((Source == NULL) || (Source->BufUsed ==0)) {
1439 e = s + Source->BufUsed;
1442 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1444 while ((s<e) && !IsEmptyStr(s)) {
1445 if (*s == separator) {
1448 if (len >= dest->BufSize) {
1449 dest->BufUsed = len;
1450 if (IncreaseBuf(dest, 1, -1) < 0) {
1455 if ( (current_token == parmnum) &&
1456 (*s != separator)) {
1457 dest->buf[len] = *s;
1460 else if (current_token > parmnum) {
1466 dest->buf[len] = '\0';
1467 dest->BufUsed = len;
1469 if (current_token < parmnum) {
1470 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1473 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1483 * @brief a string tokenizer to fetch an integer
1484 * @param Source String containing tokens
1485 * @param parmnum n'th Parameter to extract
1486 * @param separator tokenizer character
1487 * @returns 0 if not found, else integer representation of the token
1489 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1499 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1507 * @brief a string tokenizer to fetch a long integer
1508 * @param Source String containing tokens
1509 * @param parmnum n'th Parameter to extract
1510 * @param separator tokenizer character
1511 * @returns 0 if not found, else long integer representation of the token
1513 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1523 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1532 * @brief a string tokenizer to fetch an unsigned long
1533 * @param Source String containing tokens
1534 * @param parmnum n'th Parameter to extract
1535 * @param separator tokenizer character
1536 * @returns 0 if not found, else unsigned long representation of the token
1538 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1549 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1553 return (unsigned long) atol(pnum);
1563 * @brief a string tokenizer; Bounds checker
1564 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1565 * @param Source our tokenbuffer
1566 * @param pStart the token iterator pointer to inspect
1567 * @returns whether the revolving pointer is inside of the search range
1569 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1571 if ((Source == NULL) ||
1572 (*pStart == StrBufNOTNULL) ||
1573 (Source->BufUsed == 0))
1577 if (*pStart == NULL)
1581 else if (*pStart > Source->buf + Source->BufUsed)
1585 else if (*pStart <= Source->buf)
1595 * @brief a string tokenizer
1596 * @param dest Destination StringBuffer
1597 * @param Source StringBuffer to read into
1598 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1599 * @param separator tokenizer
1600 * @returns -1 if not found, else length of token.
1602 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1604 const char *s; /* source */
1605 const char *EndBuffer; /* end stop of source buffer */
1606 int current_token = 0; /* token currently being processed */
1607 int len = 0; /* running total length of extracted string */
1609 if ((Source == NULL) ||
1610 (Source->BufUsed == 0) )
1612 *pStart = StrBufNOTNULL;
1616 EndBuffer = Source->buf + Source->BufUsed;
1620 dest->buf[0] = '\0';
1625 *pStart = EndBuffer + 1;
1629 if (*pStart == NULL)
1631 *pStart = Source->buf; /* we're starting to examine this buffer. */
1633 else if ((*pStart < Source->buf) ||
1634 (*pStart > EndBuffer ) )
1636 return -1; /* no more tokens to find. */
1640 /* start to find the next token */
1641 while ((s <= EndBuffer) &&
1642 (current_token == 0) )
1644 if (*s == separator)
1646 /* we found the next token */
1650 if (len >= dest->BufSize)
1652 /* our Dest-buffer isn't big enough, increase it. */
1653 dest->BufUsed = len;
1655 if (IncreaseBuf(dest, 1, -1) < 0) {
1656 /* WHUT? no more mem? bail out. */
1663 if ( (current_token == 0 ) && /* are we in our target token? */
1664 (!IsEmptyStr(s) ) &&
1665 (separator != *s) ) /* don't copy the token itself */
1667 dest->buf[len] = *s; /* Copy the payload */
1668 ++len; /* remember the bigger size. */
1674 /* did we reach the end? */
1675 if ((s > EndBuffer)) {
1676 EndBuffer = StrBufNOTNULL;
1677 *pStart = EndBuffer;
1680 *pStart = s; /* remember the position for the next run */
1683 /* sanitize our extracted token */
1684 dest->buf[len] = '\0';
1685 dest->BufUsed = len;
1693 * @brief a string tokenizer
1694 * @param dest Destination StringBuffer
1695 * @param Source StringBuffer to read from
1696 * @param pStart pointer to the end of the last token. Feed with NULL.
1697 * @param separator tokenizer @param
1698 * @returns -1 if not found, else length of token.
1700 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1702 const char *s, *EndBuffer; //* source * /
1703 int len = 0; //* running total length of extracted string * /
1704 int current_token = 0; //* token currently being processed * /
1706 if ((Source == NULL) ||
1707 (Source->BufUsed ==0)) {
1711 return Source->BufUsed;
1713 if (*pStart == NULL)
1714 *pStart = Source->buf;
1716 EndBuffer = Source->buf + Source->BufUsed;
1718 if ((*pStart < Source->buf) ||
1719 (*pStart > EndBuffer)) {
1727 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1729 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1730 if (*s == separator) {
1733 if (current_token >= nTokens) {
1746 * @brief a string tokenizer to fetch an integer
1747 * @param Source StringBuffer to read from
1748 * @param pStart Cursor on the tokenstring
1749 * @param separator tokenizer character
1750 * @returns 0 if not found, else integer representation of the token
1752 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1762 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1770 * @brief a string tokenizer to fetch a long integer
1771 * @param Source StringBuffer to read from
1772 * @param pStart Cursor on the tokenstring
1773 * @param separator tokenizer character
1774 * @returns 0 if not found, else long integer representation of the token
1776 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1786 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1795 * @brief a string tokenizer to fetch an unsigned long
1796 * @param Source StringBuffer to read from
1797 * @param pStart Cursor on the tokenstring
1798 * @param separator tokenizer character
1799 * @returns 0 if not found, else unsigned long representation of the token
1801 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1812 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1816 return (unsigned long) atol(pnum);
1826 * @brief Read a line from socket
1827 * flushes and closes the FD on error
1828 * @param buf the buffer to get the input to
1829 * @param fd pointer to the filedescriptor to read
1830 * @param append Append to an existing string or replace?
1831 * @param Error strerror() on error
1832 * @returns numbers of chars read
1834 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1836 int len, rlen, slen;
1841 slen = len = buf->BufUsed;
1843 rlen = read(*fd, &buf->buf[len], 1);
1845 *Error = strerror(errno);
1852 if (buf->buf[len] == '\n')
1854 if (buf->buf[len] != '\r')
1856 if (len + 2 >= buf->BufSize) {
1858 buf->buf[len+1] = '\0';
1859 IncreaseBuf(buf, 1, -1);
1863 buf->buf[len] = '\0';
1869 * @brief Read a line from socket
1870 * flushes and closes the FD on error
1871 * @param buf the buffer to get the input to
1872 * @param fd pointer to the filedescriptor to read
1873 * @param append Append to an existing string or replace?
1874 * @param Error strerror() on error
1875 * @returns numbers of chars read
1877 int StrBufTCP_read_buffered_line(StrBuf *Line,
1881 int selectresolution,
1885 int nSuccessLess = 0;
1892 if (buf->BufUsed > 0) {
1893 pch = strchr(buf->buf, '\n');
1896 len = pch - buf->buf;
1897 if (len > 0 && (*(pch - 1) == '\r') )
1899 StrBufSub(Line, buf, 0, len - rlen);
1900 StrBufCutLeft(buf, len + 1);
1905 if (buf->BufSize - buf->BufUsed < 10)
1906 IncreaseBuf(buf, 1, -1);
1908 fdflags = fcntl(*fd, F_GETFL);
1909 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1911 while ((nSuccessLess < timeout) && (pch == NULL)) {
1913 tv.tv_sec = selectresolution;
1918 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1919 *Error = strerror(errno);
1925 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
1930 &buf->buf[buf->BufUsed],
1931 buf->BufSize - buf->BufUsed - 1);
1933 *Error = strerror(errno);
1938 else if (rlen > 0) {
1940 buf->BufUsed += rlen;
1941 buf->buf[buf->BufUsed] = '\0';
1942 if (buf->BufUsed + 10 > buf->BufSize) {
1943 IncreaseBuf(buf, 1, -1);
1945 pch = strchr(buf->buf, '\n');
1952 len = pch - buf->buf;
1953 if (len > 0 && (*(pch - 1) == '\r') )
1955 StrBufSub(Line, buf, 0, len - rlen);
1956 StrBufCutLeft(buf, len + 1);
1963 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1964 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1967 * @brief Read a line from socket
1968 * flushes and closes the FD on error
1969 * @param buf the buffer to get the input to
1970 * @param Pos pointer to the current read position, should be NULL initialized!
1971 * @param fd pointer to the filedescriptor to read
1972 * @param append Append to an existing string or replace?
1973 * @param Error strerror() on error
1974 * @returns numbers of chars read
1976 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1981 int selectresolution,
1984 const char *pche = NULL;
1985 const char *pos = NULL;
1987 int nSuccessLess = 0;
1989 const char *pch = NULL;
1995 if ((IOBuf->BufUsed > 0) &&
1997 (pos < IOBuf->buf + IOBuf->BufUsed))
1999 pche = IOBuf->buf + IOBuf->BufUsed;
2001 while ((pch < pche) && (*pch != '\n'))
2003 if ((pch >= pche) || (*pch == '\0'))
2005 if ((pch != NULL) &&
2010 if (len > 0 && (*(pch - 1) == '\r') )
2012 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
2022 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
2026 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
2027 IncreaseBuf(IOBuf, 1, -1);
2030 fdflags = fcntl(*fd, F_GETFL);
2031 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2034 while ((nSuccessLess < timeout) &&
2044 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
2045 *Error = strerror(errno);
2049 *Error = ErrRBLF_SelectFailed;
2052 if (! FD_ISSET(*fd, &rfds) != 0) {
2058 &IOBuf->buf[IOBuf->BufUsed],
2059 IOBuf->BufSize - IOBuf->BufUsed - 1);
2061 *Error = strerror(errno);
2066 else if (rlen > 0) {
2068 IOBuf->BufUsed += rlen;
2069 IOBuf->buf[IOBuf->BufUsed] = '\0';
2070 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
2071 IncreaseBuf(IOBuf, 1, -1);
2074 pche = IOBuf->buf + IOBuf->BufUsed;
2076 while ((pch < pche) && (*pch != '\n'))
2078 if ((pch >= pche) || (*pch == '\0'))
2087 if (len > 0 && (*(pch - 1) == '\r') )
2089 StrBufSub(Line, IOBuf, 0, len - rlen);
2090 *Pos = pos + len + 1;
2093 *Error = ErrRBLF_NotEnoughSentFromServer;
2099 * @brief Input binary data from socket
2100 * flushes and closes the FD on error
2101 * @param buf the buffer to get the input to
2102 * @param fd pointer to the filedescriptor to read
2103 * @param append Append to an existing string or replace?
2104 * @param nBytes the maximal number of bytes to read
2105 * @param Error strerror() on error
2106 * @returns numbers of chars read
2108 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
2111 int len, rlen, slen;
2118 if ((Buf == NULL) || (*fd == -1))
2122 if (Buf->BufUsed + nBytes >= Buf->BufSize)
2123 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
2125 ptr = Buf->buf + Buf->BufUsed;
2127 slen = len = Buf->BufUsed;
2129 fdflags = fcntl(*fd, F_GETFL);
2130 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2132 while ((nRead < nBytes) &&
2142 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2143 *Error = strerror(errno);
2147 *Error = ErrRBLF_SelectFailed;
2150 if (! FD_ISSET(*fd, &rfds) != 0) {
2156 if ((rlen = read(*fd,
2158 nBytes - nRead)) == -1) {
2161 *Error = strerror(errno);
2166 Buf->BufUsed += rlen;
2168 Buf->buf[Buf->BufUsed] = '\0';
2172 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
2174 * @brief Input binary data from socket
2175 * flushes and closes the FD on error
2176 * @param buf the buffer to get the input to
2177 * @param fd pointer to the filedescriptor to read
2178 * @param append Append to an existing string or replace?
2179 * @param nBytes the maximal number of bytes to read
2180 * @param Error strerror() on error
2181 * @returns numbers of chars read
2183 int StrBufReadBLOBBuffered(StrBuf *Blob,
2200 int nAlreadyRead = 0;
2208 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2212 if (Blob->BufUsed + nBytes >= Blob->BufSize)
2213 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2218 len = pos - IOBuf->buf;
2219 rlen = IOBuf->BufUsed - len;
2222 if ((IOBuf->BufUsed > 0) &&
2224 (pos < IOBuf->buf + IOBuf->BufUsed))
2226 pche = IOBuf->buf + IOBuf->BufUsed;
2229 if (rlen < nBytes) {
2230 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2231 Blob->BufUsed += rlen;
2232 Blob->buf[Blob->BufUsed] = '\0';
2233 nAlreadyRead = nRead = rlen;
2236 if (rlen >= nBytes) {
2237 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2238 Blob->BufUsed += nBytes;
2239 Blob->buf[Blob->BufUsed] = '\0';
2240 if (rlen == nBytes) {
2251 if (IOBuf->BufSize < nBytes - nRead)
2252 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2255 slen = len = Blob->BufUsed;
2257 fdflags = fcntl(*fd, F_GETFL);
2258 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2263 while ((nRead < nBytes) &&
2272 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2273 *Error = strerror(errno);
2277 *Error = ErrRBLF_SelectFailed;
2280 if (! FD_ISSET(*fd, &rfds) != 0) {
2292 *Error = strerror(errno);
2295 else if (rlen == 0){
2297 if ((check == NNN_TERM) &&
2299 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2301 StrBufPlain(Blob, HKEY("\n000\n"));
2302 StrBufCutRight(Blob, 5);
2303 return Blob->BufUsed;
2305 if (nSelects > 10) {
2307 *Error = ErrRBB_too_many_selects;
2311 else if (rlen > 0) {
2314 IOBuf->BufUsed += rlen;
2317 if (nRead > nBytes) {
2318 *Pos = IOBuf->buf + nBytes;
2320 Blob->buf[Blob->BufUsed] = '\0';
2321 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2325 return nRead + nAlreadyRead;
2329 * @brief Cut nChars from the start of the string
2330 * @param Buf Buffer to modify
2331 * @param nChars how many chars should be skipped?
2333 void StrBufCutLeft(StrBuf *Buf, int nChars)
2335 if (nChars >= Buf->BufUsed) {
2339 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2340 Buf->BufUsed -= nChars;
2341 Buf->buf[Buf->BufUsed] = '\0';
2345 * @brief Cut the trailing n Chars from the string
2346 * @param Buf Buffer to modify
2347 * @param nChars how many chars should be trunkated?
2349 void StrBufCutRight(StrBuf *Buf, int nChars)
2351 if (nChars >= Buf->BufUsed) {
2355 Buf->BufUsed -= nChars;
2356 Buf->buf[Buf->BufUsed] = '\0';
2360 * @brief Cut the string after n Chars
2361 * @param Buf Buffer to modify
2362 * @param AfternChars after how many chars should we trunkate the string?
2363 * @param At if non-null and points inside of our string, cut it there.
2365 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2368 AfternChars = At - Buf->buf;
2371 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2373 Buf->BufUsed = AfternChars;
2374 Buf->buf[Buf->BufUsed] = '\0';
2379 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2380 * @param buf the string to modify
2381 * @param len length of the string.
2383 void StrBufTrim(StrBuf *Buf)
2386 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2388 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2391 if (delta > 0) StrBufCutLeft(Buf, delta);
2393 if (Buf->BufUsed == 0) return;
2394 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2397 Buf->buf[Buf->BufUsed] = '\0';
2401 * @brief uppercase the contents of a buffer
2402 * @param Buf the buffer to translate
2404 void StrBufUpCase(StrBuf *Buf)
2409 pche = pch + Buf->BufUsed;
2410 while (pch < pche) {
2411 *pch = toupper(*pch);
2418 * @brief lowercase the contents of a buffer
2419 * @param Buf the buffer to translate
2421 void StrBufLowerCase(StrBuf *Buf)
2426 pche = pch + Buf->BufUsed;
2427 while (pch < pche) {
2428 *pch = tolower(*pch);
2434 * @brief removes double slashes from pathnames
2435 * @param Dir directory string to filter
2436 * @param RemoveTrailingSlash allows / disallows trailing slashes
2438 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2444 while (!IsEmptyStr(a)) {
2456 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2461 Dir->BufUsed = b - Dir->buf;
2465 * @brief unhide special chars hidden to the HTML escaper
2466 * @param target buffer to put the unescaped string in
2467 * @param source buffer to unescape
2469 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2475 FlushStrBuf(target);
2477 if (source == NULL ||target == NULL)
2482 len = source->BufUsed;
2483 for (a = 0; a < len; ++a) {
2484 if (target->BufUsed >= target->BufSize)
2485 IncreaseBuf(target, 1, -1);
2487 if (source->buf[a] == '=') {
2488 hex[0] = source->buf[a + 1];
2489 hex[1] = source->buf[a + 2];
2492 sscanf(hex, "%02x", &b);
2493 target->buf[target->BufUsed] = b;
2494 target->buf[++target->BufUsed] = 0;
2498 target->buf[target->BufUsed] = source->buf[a];
2499 target->buf[++target->BufUsed] = 0;
2506 * @brief hide special chars from the HTML escapers and friends
2507 * @param target buffer to put the escaped string in
2508 * @param source buffer to escape
2510 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2515 FlushStrBuf(target);
2517 if (source == NULL ||target == NULL)
2522 len = source->BufUsed;
2523 for (i=0; i<len; ++i) {
2524 if (target->BufUsed + 4 >= target->BufSize)
2525 IncreaseBuf(target, 1, -1);
2526 if ( (isalnum(source->buf[i])) ||
2527 (source->buf[i]=='-') ||
2528 (source->buf[i]=='_') ) {
2529 target->buf[target->BufUsed++] = source->buf[i];
2532 sprintf(&target->buf[target->BufUsed],
2534 (0xFF &source->buf[i]));
2535 target->BufUsed += 3;
2538 target->buf[target->BufUsed + 1] = '\0';
2542 * @brief uses the same calling syntax as compress2(), but it
2543 * creates a stream compatible with HTTP "Content-encoding: gzip"
2546 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2547 #define OS_CODE 0x03 /*< unix */
2548 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2549 size_t * destLen, /*< length of the compresed data */
2550 const Bytef * source, /*< source to encode */
2551 uLong sourceLen, /*< length of source to encode */
2552 int level) /*< compression level */
2554 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2556 /* write gzip header */
2557 snprintf((char *) dest, *destLen,
2558 "%c%c%c%c%c%c%c%c%c%c",
2559 gz_magic[0], gz_magic[1], Z_DEFLATED,
2560 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2563 /* normal deflate */
2566 stream.next_in = (Bytef *) source;
2567 stream.avail_in = (uInt) sourceLen;
2568 stream.next_out = dest + 10L; // after header
2569 stream.avail_out = (uInt) * destLen;
2570 if ((uLong) stream.avail_out != *destLen)
2573 stream.zalloc = (alloc_func) 0;
2574 stream.zfree = (free_func) 0;
2575 stream.opaque = (voidpf) 0;
2577 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2578 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2582 err = deflate(&stream, Z_FINISH);
2583 if (err != Z_STREAM_END) {
2584 deflateEnd(&stream);
2585 return err == Z_OK ? Z_BUF_ERROR : err;
2587 *destLen = stream.total_out + 10L;
2589 /* write CRC and Length */
2590 uLong crc = crc32(0L, source, sourceLen);
2592 for (n = 0; n < 4; ++n, ++*destLen) {
2593 dest[*destLen] = (int) (crc & 0xff);
2596 uLong len = stream.total_in;
2597 for (n = 0; n < 4; ++n, ++*destLen) {
2598 dest[*destLen] = (int) (len & 0xff);
2601 err = deflateEnd(&stream);
2608 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2610 int CompressBuffer(StrBuf *Buf)
2613 char *compressed_data = NULL;
2614 size_t compressed_len, bufsize;
2617 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2618 compressed_data = malloc(compressed_len);
2620 if (compressed_data == NULL)
2622 /* Flush some space after the used payload so valgrind shuts up... */
2623 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2624 Buf->buf[Buf->BufUsed + i++] = '\0';
2625 if (compress_gzip((Bytef *) compressed_data,
2628 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2631 Buf->buf = compressed_data;
2632 Buf->BufUsed = compressed_len;
2633 Buf->BufSize = bufsize;
2634 /* Flush some space after the used payload so valgrind shuts up... */
2636 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2637 Buf->buf[Buf->BufUsed + i++] = '\0';
2640 free(compressed_data);
2642 #endif /* HAVE_ZLIB */
2647 * @brief decode a buffer from base 64 encoding; destroys original
2648 * @param Buf Buffor to transform
2650 int StrBufDecodeBase64(StrBuf *Buf)
2654 if (Buf == NULL) return -1;
2656 xferbuf = (char*) malloc(Buf->BufSize);
2657 siz = CtdlDecodeBase64(xferbuf,
2667 * @brief decode a buffer from base 64 encoding; destroys original
2668 * @param Buf Buffor to transform
2670 int StrBufDecodeHex(StrBuf *Buf)
2673 char *pch, *pche, *pchi;
2675 if (Buf == NULL) return -1;
2677 pch = pchi = Buf->buf;
2678 pche = pch + Buf->BufUsed;
2680 while (pchi < pche){
2681 ch = decode_hex(pchi);
2688 Buf->BufUsed = pch - Buf->buf;
2689 return Buf->BufUsed;
2693 * @brief replace all chars >0x20 && < 0x7F with Mute
2694 * @param Mute char to put over invalid chars
2695 * @param Buf Buffor to transform
2697 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2701 if (Buf == NULL) return -1;
2702 pch = (unsigned char *)Buf->buf;
2703 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2704 if ((*pch < 0x20) || (*pch > 0x7F))
2708 return Buf->BufUsed;
2713 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2714 * @param Buf Buffer to translate
2715 * @param StripBlanks Reduce several blanks to one?
2717 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2723 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2724 Buf->buf[Buf->BufUsed - 1] = '\0';
2729 while (a < Buf->BufUsed) {
2730 if (Buf->buf[a] == '+')
2732 else if (Buf->buf[a] == '%') {
2733 /* don't let % chars through, rather truncate the input. */
2734 if (a + 2 > Buf->BufUsed) {
2739 hex[0] = Buf->buf[a + 1];
2740 hex[1] = Buf->buf[a + 2];
2743 sscanf(hex, "%02x", &b);
2744 Buf->buf[a] = (char) b;
2745 len = Buf->BufUsed - a - 2;
2747 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2759 * @brief RFC2047-encode a header field if necessary.
2760 * If no non-ASCII characters are found, the string
2761 * will be copied verbatim without encoding.
2763 * @param target Target buffer.
2764 * @param source Source string to be encoded.
2765 * @returns encoded length; -1 if non success.
2767 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2769 const char headerStr[] = "=?UTF-8?Q?";
2770 int need_to_encode = 0;
2774 if ((source == NULL) ||
2778 while ((i < source->BufUsed) &&
2779 (!IsEmptyStr (&source->buf[i])) &&
2780 (need_to_encode == 0)) {
2781 if (((unsigned char) source->buf[i] < 32) ||
2782 ((unsigned char) source->buf[i] > 126)) {
2788 if (!need_to_encode) {
2789 if (*target == NULL) {
2790 *target = NewStrBufPlain(source->buf, source->BufUsed);
2793 FlushStrBuf(*target);
2794 StrBufAppendBuf(*target, source, 0);
2796 return (*target)->BufUsed;
2798 if (*target == NULL)
2799 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2800 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2801 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2802 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2803 (*target)->BufUsed = sizeof(headerStr) - 1;
2804 for (i=0; (i < source->BufUsed); ++i) {
2805 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2806 IncreaseBuf(*target, 1, 0);
2807 ch = (unsigned char) source->buf[i];
2808 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2809 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2810 (*target)->BufUsed += 3;
2813 (*target)->buf[(*target)->BufUsed] = ch;
2814 (*target)->BufUsed++;
2818 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2819 IncreaseBuf(*target, 1, 0);
2821 (*target)->buf[(*target)->BufUsed++] = '?';
2822 (*target)->buf[(*target)->BufUsed++] = '=';
2823 (*target)->buf[(*target)->BufUsed] = '\0';
2824 return (*target)->BufUsed;;
2828 * @brief replaces all occurances of 'search' by 'replace'
2829 * @param buf Buffer to modify
2830 * @param search character to search
2831 * @param relpace character to replace search by
2833 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2838 for (i=0; i<buf->BufUsed; i++)
2839 if (buf->buf[i] == search)
2840 buf->buf[i] = replace;
2847 * @brief Wrapper around iconv_open()
2848 * Our version adds aliases for non-standard Microsoft charsets
2849 * such as 'MS950', aliasing them to names like 'CP950'
2851 * @param tocode Target encoding
2852 * @param fromcode Source encoding
2854 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2857 iconv_t ic = (iconv_t)(-1) ;
2858 ic = iconv_open(tocode, fromcode);
2859 if (ic == (iconv_t)(-1) ) {
2860 char alias_fromcode[64];
2861 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2862 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2863 alias_fromcode[0] = 'C';
2864 alias_fromcode[1] = 'P';
2865 ic = iconv_open(tocode, alias_fromcode);
2868 *(iconv_t *)pic = ic;
2874 * @brief find one chunk of a RFC822 encoded string
2875 * @param Buffer where to search
2876 * @param bptr where to start searching
2877 * @returns found position, NULL if none.
2879 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2882 /* Find the next ?Q? */
2883 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2886 end = strchr(bptr + 2, '?');
2891 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2892 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2893 (*(end + 2) == '?')) {
2894 /* skip on to the end of the cluster, the next ?= */
2895 end = strstr(end + 3, "?=");
2898 /* sort of half valid encoding, try to find an end. */
2899 end = strstr(bptr, "?=");
2904 * @brief swaps the contents of two StrBufs
2905 * this is to be used to have cheap switched between a work-buffer and a target buffer
2906 * @param A First one
2907 * @param B second one
2909 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2913 memcpy(&C, A, sizeof(*A));
2914 memcpy(A, B, sizeof(*B));
2915 memcpy(B, &C, sizeof(C));
2921 * @brief convert one buffer according to the preselected iconv pointer PIC
2922 * @param ConvertBuf buffer we need to translate
2923 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2924 * @param pic Pointer to the iconv-session Object
2926 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2932 char *ibuf; /**< Buffer of characters to be converted */
2933 char *obuf; /**< Buffer for converted characters */
2934 size_t ibuflen; /**< Length of input buffer */
2935 size_t obuflen; /**< Length of output buffer */
2938 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2939 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2940 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2942 ic = *(iconv_t*)pic;
2943 ibuf = ConvertBuf->buf;
2944 ibuflen = ConvertBuf->BufUsed;
2946 obuflen = TmpBuf->BufSize;
2948 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2951 if (errno == E2BIG) {
2953 IncreaseBuf(TmpBuf, 0, 0);
2958 else if (errno == EILSEQ){
2959 /* hm, invalid utf8 sequence... what to do now? */
2960 /* An invalid multibyte sequence has been encountered in the input */
2962 else if (errno == EINVAL) {
2963 /* An incomplete multibyte sequence has been encountered in the input. */
2966 FlushStrBuf(TmpBuf);
2969 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2970 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2972 /* little card game: wheres the red lady? */
2973 SwapBuffers(ConvertBuf, TmpBuf);
2974 FlushStrBuf(TmpBuf);
2981 * @brief catches one RFC822 encoded segment, and decodes it.
2982 * @param Target buffer to fill with result
2983 * @param DecodeMe buffer with stuff to process
2984 * @param SegmentStart points to our current segment in DecodeMe
2985 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2986 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2987 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2988 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2990 inline static void DecodeSegment(StrBuf *Target,
2991 const StrBuf *DecodeMe,
2995 StrBuf *ConvertBuf2,
2996 StrBuf *FoundCharset)
3002 iconv_t ic = (iconv_t)(-1);
3006 /* Now we handle foreign character sets properly encoded
3007 * in RFC2047 format.
3009 StaticBuf.buf = SegmentStart;
3010 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3011 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3012 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3013 if (FoundCharset != NULL) {
3014 FlushStrBuf(FoundCharset);
3015 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3017 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3018 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3020 *encoding = toupper(*encoding);
3021 if (*encoding == 'B') { /**< base64 */
3022 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
3024 ConvertBuf->BufUsed);
3026 else if (*encoding == 'Q') { /**< quoted-printable */
3030 while (pos < ConvertBuf->BufUsed)
3032 if (ConvertBuf->buf[pos] == '_')
3033 ConvertBuf->buf[pos] = ' ';
3037 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3040 ConvertBuf->BufUsed);
3043 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3046 ctdl_iconv_open("UTF-8", charset, &ic);
3047 if (ic != (iconv_t)(-1) ) {
3049 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3050 StrBufAppendBuf(Target, ConvertBuf2, 0);
3055 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3061 * @brief Handle subjects with RFC2047 encoding such as:
3062 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3063 * @param Target where to put the decoded string to
3064 * @param DecodeMe buffer with encoded string
3065 * @param DefaultCharset if we don't find one, which should we use?
3066 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3067 * put it here for later use where no string might be known.
3069 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3071 StrBuf *DecodedInvalidBuf = NULL;
3072 StrBuf *ConvertBuf, *ConvertBuf2;
3073 const StrBuf *DecodeMee = DecodeMe;
3074 char *start, *end, *next, *nextend, *ptr = NULL;
3076 iconv_t ic = (iconv_t)(-1) ;
3081 int illegal_non_rfc2047_encoding = 0;
3083 /* Sometimes, badly formed messages contain strings which were simply
3084 * written out directly in some foreign character set instead of
3085 * using RFC2047 encoding. This is illegal but we will attempt to
3086 * handle it anyway by converting from a user-specified default
3087 * charset to UTF-8 if we see any nonprintable characters.
3090 len = StrLength(DecodeMe);
3091 for (i=0; i<DecodeMe->BufUsed; ++i) {
3092 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3093 illegal_non_rfc2047_encoding = 1;
3098 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3099 if ((illegal_non_rfc2047_encoding) &&
3100 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3101 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3104 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3105 if (ic != (iconv_t)(-1) ) {
3106 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3107 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3108 DecodeMee = DecodedInvalidBuf;
3114 /* pre evaluate the first pair */
3115 nextend = end = NULL;
3116 len = StrLength(DecodeMee);
3117 start = strstr(DecodeMee->buf, "=?");
3118 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3120 end = FindNextEnd (DecodeMee, start);
3122 StrBufAppendBuf(Target, DecodeMee, 0);
3123 FreeStrBuf(&ConvertBuf);
3124 FreeStrBuf(&DecodedInvalidBuf);
3128 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
3130 if (start != DecodeMee->buf) {
3133 nFront = start - DecodeMee->buf;
3134 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3138 * Since spammers will go to all sorts of absurd lengths to get their
3139 * messages through, there are LOTS of corrupt headers out there.
3140 * So, prevent a really badly formed RFC2047 header from throwing
3141 * this function into an infinite loop.
3143 while ((start != NULL) &&
3150 DecodeSegment(Target,
3158 next = strstr(end, "=?");
3160 if ((next != NULL) &&
3162 nextend = FindNextEnd(DecodeMee, next);
3163 if (nextend == NULL)
3166 /* did we find two partitions */
3167 if ((next != NULL) &&
3171 while ((ptr < next) &&
3177 /* did we find a gab just filled with blanks? */
3180 long gap = next - start;
3185 /* now terminate the gab at the end */
3186 delta = (next - end) - 2; ////TODO: const!
3187 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3188 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3190 /* move next to its new location. */
3195 /* our next-pair is our new first pair now. */
3201 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3202 if ((end != NULL) && (end < nextend)) {
3204 while ( (ptr < nextend) &&
3211 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3213 FreeStrBuf(&ConvertBuf);
3214 FreeStrBuf(&ConvertBuf2);
3215 FreeStrBuf(&DecodedInvalidBuf);
3219 * @brief evaluate the length of an utf8 special character sequence
3220 * @param Char the character to examine
3221 * @returns width of utf8 chars in bytes
3223 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3228 while ((n < 8) && ((test & *CharS) != 0)) {
3232 if ((n > 6) || ((CharE - CharS) > n))
3238 * @brief detect whether this char starts an utf-8 encoded char
3239 * @param Char character to inspect
3240 * @returns yes or no
3242 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3244 /** 11??.???? indicates an UTF8 Sequence. */
3245 return ((Char & 0xC0) != 0);
3249 * @brief measure the number of glyphs in an UTF8 string...
3250 * @param str string to measure
3251 * @returns the length of str
3253 long StrBuf_Utf8StrLen(StrBuf *Buf)
3259 if ((Buf == NULL) || (Buf->BufUsed == 0))
3262 eptr = Buf->buf + Buf->BufUsed;
3263 while ((aptr < eptr) && (*aptr != '\0')) {
3264 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3265 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3266 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3279 * @brief cuts a string after maxlen glyphs
3280 * @param str string to cut to maxlen glyphs
3281 * @param maxlen how long may the string become?
3282 * @returns pointer to maxlen or the end of the string
3284 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3290 eptr = Buf->buf + Buf->BufUsed;
3291 while ((aptr < eptr) && (*aptr != '\0')) {
3292 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3293 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3294 while ((m-- > 0) && (*aptr++ != '\0'))
3303 Buf->BufUsed = aptr - Buf->buf;
3304 return Buf->BufUsed;
3307 return Buf->BufUsed;
3313 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3314 * @param LineBuf your line will be copied here.
3315 * @param Buf BLOB with lines of text...
3316 * @param Ptr moved arround to keep the next-line across several iterations
3317 * has to be &NULL on start; will be &NotNULL on end of buffer
3318 * @returns size of copied buffer
3320 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3322 const char *aptr, *ptr, *eptr;
3325 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3326 *Ptr = StrBufNOTNULL;
3330 FlushStrBuf(LineBuf);
3332 ptr = aptr = Buf->buf;
3336 optr = LineBuf->buf;
3337 eptr = Buf->buf + Buf->BufUsed;
3338 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3340 while ((ptr <= eptr) &&
3347 LineBuf->BufUsed = optr - LineBuf->buf;
3348 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3349 optr = LineBuf->buf + LineBuf->BufUsed;
3350 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3354 if ((ptr >= eptr) && (optr > LineBuf->buf))
3356 LineBuf->BufUsed = optr - LineBuf->buf;
3358 if ((ptr <= eptr) && (*ptr == '\r'))
3360 if ((ptr <= eptr) && (*ptr == '\n'))
3367 *Ptr = StrBufNOTNULL;
3370 return Buf->BufUsed - (ptr - Buf->buf);