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 * Private Structure for the Stringbuffer
36 char *buf; /**< the pointer to the dynamic buffer */
37 long BufSize; /**< how many spcae do we optain */
38 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
39 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
43 char bt_lastinc [SIZ];
49 static void StrBufBacktrace(StrBuf *Buf, int which)
53 void *stack_frames[50];
58 pstart = pch = Buf->bt;
60 pstart = pch = Buf->bt_lastinc;
61 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
62 strings = backtrace_symbols(stack_frames, size);
63 for (i = 0; i < size; i++) {
65 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
67 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
78 * @brief Cast operator to Plain String
79 * Note: if the buffer is altered by StrBuf operations, this pointer may become
80 * invalid. So don't lean on it after altering the buffer!
81 * Since this operation is considered cheap, rather call it often than risking
82 * your pointer to become invalid!
83 * @param Str the string we want to get the c-string representation for
84 * @returns the Pointer to the Content. Don't mess with it!
86 inline const char *ChrPtr(const StrBuf *Str)
94 * @brief since we know strlen()'s result, provide it here.
95 * @param Str the string to return the length to
96 * @returns contentlength of the buffer
98 inline int StrLength(const StrBuf *Str)
100 return (Str != NULL) ? Str->BufUsed : 0;
104 * @brief local utility function to resize the buffer
105 * @param Buf the buffer whichs storage we should increase
106 * @param KeepOriginal should we copy the original buffer or just start over with a new one
107 * @param DestSize what should fit in after?
109 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
112 size_t NewSize = Buf->BufSize * 2;
118 while (NewSize <= DestSize)
121 NewBuf= (char*) malloc(NewSize);
125 if (KeepOriginal && (Buf->BufUsed > 0))
127 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
136 Buf->BufSize = NewSize;
139 #ifdef HAVE_BACKTRACE
140 StrBufBacktrace(Buf, 1);
147 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
148 * @param Buf Buffer to shrink (has to be empty)
149 * @param ThreshHold if the buffer is bigger then this, its readjusted
150 * @param NewSize if we Shrink it, how big are we going to be afterwards?
152 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
154 if (Buf->BufUsed > ThreshHold) {
156 Buf->buf = (char*) malloc(NewSize);
158 Buf->BufSize = NewSize;
163 * @brief shrink long term buffers to their real size so they don't waste memory
164 * @param Buf buffer to shrink
165 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
166 * @returns physical size of the buffer
168 long StrBufShrinkToFit(StrBuf *Buf, int Force)
171 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
173 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
174 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
175 Buf->BufSize = Buf->BufUsed + 1;
183 * @brief Allocate a new buffer with default buffer size
184 * @returns the new stringbuffer
186 StrBuf* NewStrBuf(void)
190 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
191 NewBuf->buf = (char*) malloc(BaseStrBufSize);
192 NewBuf->buf[0] = '\0';
193 NewBuf->BufSize = BaseStrBufSize;
195 NewBuf->ConstBuf = 0;
197 NewBuf->nIncreases = 0;
198 NewBuf->bt[0] = '\0';
199 NewBuf->bt_lastinc[0] = '\0';
200 #ifdef HAVE_BACKTRACE
201 StrBufBacktrace(NewBuf, 0);
208 * @brief Copy Constructor; returns a duplicate of CopyMe
209 * @params CopyMe Buffer to faxmilate
210 * @returns the new stringbuffer
212 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
219 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
220 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
221 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
222 NewBuf->BufUsed = CopyMe->BufUsed;
223 NewBuf->BufSize = CopyMe->BufSize;
224 NewBuf->ConstBuf = 0;
226 NewBuf->nIncreases = 0;
227 NewBuf->bt[0] = '\0';
228 NewBuf->bt_lastinc[0] = '\0';
229 #ifdef HAVE_BACKTRACE
230 StrBufBacktrace(NewBuf, 0);
237 * @brief create a new Buffer using an existing c-string
238 * this function should also be used if you want to pre-suggest
239 * the buffer size to allocate in conjunction with ptr == NULL
240 * @param ptr the c-string to copy; may be NULL to create a blank instance
241 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
242 * @returns the new stringbuffer
244 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
247 size_t Siz = BaseStrBufSize;
250 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
252 CopySize = strlen((ptr != NULL)?ptr:"");
256 while (Siz <= CopySize)
259 NewBuf->buf = (char*) malloc(Siz);
260 NewBuf->BufSize = Siz;
262 memcpy(NewBuf->buf, ptr, CopySize);
263 NewBuf->buf[CopySize] = '\0';
264 NewBuf->BufUsed = CopySize;
267 NewBuf->buf[0] = '\0';
270 NewBuf->ConstBuf = 0;
272 NewBuf->nIncreases = 0;
273 NewBuf->bt[0] = '\0';
274 NewBuf->bt_lastinc[0] = '\0';
275 #ifdef HAVE_BACKTRACE
276 StrBufBacktrace(NewBuf, 0);
283 * @brief Set an existing buffer from a c-string
284 * @param ptr c-string to put into
285 * @param nChars set to -1 if we should work 0-terminated
286 * @returns the new length of the string
288 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
290 size_t Siz = Buf->BufSize;
294 CopySize = strlen(ptr);
298 while (Siz <= CopySize)
301 if (Siz != Buf->BufSize)
302 IncreaseBuf(Buf, 0, Siz);
303 memcpy(Buf->buf, ptr, CopySize);
304 Buf->buf[CopySize] = '\0';
305 Buf->BufUsed = CopySize;
312 * @brief use strbuf as wrapper for a string constant for easy handling
313 * @param StringConstant a string to wrap
314 * @param SizeOfConstant should be sizeof(StringConstant)-1
316 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
320 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
321 NewBuf->buf = (char*) StringConstant;
322 NewBuf->BufSize = SizeOfStrConstant;
323 NewBuf->BufUsed = SizeOfStrConstant;
324 NewBuf->ConstBuf = 1;
326 NewBuf->nIncreases = 0;
327 NewBuf->bt[0] = '\0';
328 NewBuf->bt_lastinc[0] = '\0';
335 * @brief flush the content of a Buf; keep its struct
336 * @param buf Buffer to flush
338 int FlushStrBuf(StrBuf *buf)
350 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
351 * @param buf Buffer to wipe
353 int FLUSHStrBuf(StrBuf *buf)
359 if (buf->BufUsed > 0) {
360 memset(buf->buf, 0, buf->BufUsed);
367 int hFreeDbglog = -1;
370 * @brief Release a Buffer
371 * Its a double pointer, so it can NULL your pointer
372 * so fancy SIG11 appear instead of random results
373 * @param FreeMe Pointer Pointer to the buffer to free
375 void FreeStrBuf (StrBuf **FreeMe)
380 if (hFreeDbglog == -1){
381 pid_t pid = getpid();
383 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
384 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
386 if ((*FreeMe)->nIncreases > 0)
390 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
391 (*FreeMe)->nIncreases,
395 (*FreeMe)->bt_lastinc);
396 n = write(hFreeDbglog, buf, n);
402 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
405 n = write(hFreeDbglog, buf, n);
408 if (!(*FreeMe)->ConstBuf)
409 free((*FreeMe)->buf);
415 * @brief flatten a Buffer to the Char * we return
416 * Its a double pointer, so it can NULL your pointer
417 * so fancy SIG11 appear instead of random results
418 * The Callee then owns the buffer and is responsible for freeing it.
419 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
420 * @returns the pointer of the buffer; Callee owns the memory thereafter.
422 char *SmashStrBuf (StrBuf **SmashMe)
426 if (*SmashMe == NULL)
429 if (hFreeDbglog == -1){
430 pid_t pid = getpid();
432 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
433 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
435 if ((*SmashMe)->nIncreases > 0)
439 n = snprintf(buf, SIZ * 3, "S+|%ld|%ld|%ld|%s|%s|\n",
440 (*SmashMe)->nIncreases,
444 (*SmashMe)->bt_lastinc);
445 n = write(hFreeDbglog, buf, n);
451 n = snprintf(buf, 128, "S_|0|%ld%ld|\n",
453 (*SmashMe)->BufSize);
454 n = write(hFreeDbglog, buf, n);
457 Ret = (*SmashMe)->buf;
464 * @brief Release the buffer
465 * If you want put your StrBuf into a Hash, use this as Destructor.
466 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
468 void HFreeStrBuf (void *VFreeMe)
470 StrBuf *FreeMe = (StrBuf*)VFreeMe;
474 if (hFreeDbglog == -1){
475 pid_t pid = getpid();
477 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
478 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
480 if (FreeMe->nIncreases > 0)
484 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
490 write(hFreeDbglog, buf, n);
496 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
502 if (!FreeMe->ConstBuf)
508 * @brief Wrapper around atol
510 long StrTol(const StrBuf *Buf)
515 return atol(Buf->buf);
521 * @brief Wrapper around atoi
523 int StrToi(const StrBuf *Buf)
527 if (Buf->BufUsed > 0)
528 return atoi(Buf->buf);
534 * @brief Checks to see if the string is a pure number
536 int StrBufIsNumber(const StrBuf *Buf) {
541 strtoll(Buf->buf, &pEnd, 10);
542 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
548 * @brief modifies a Single char of the Buf
549 * You can point to it via char* or a zero-based integer
550 * @param ptr char* to zero; use NULL if unused
551 * @param nThChar zero based pointer into the string; use -1 if unused
552 * @param PeekValue The Character to place into the position
554 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
559 nThChar = ptr - Buf->buf;
560 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
562 Buf->buf[nThChar] = PeekValue;
567 * @brief Append a StringBuffer to the buffer
568 * @param Buf Buffer to modify
569 * @param AppendBuf Buffer to copy at the end of our buffer
570 * @param Offset Should we start copying from an offset?
572 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
574 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
577 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
580 AppendBuf->BufUsed + Buf->BufUsed);
582 memcpy(Buf->buf + Buf->BufUsed,
583 AppendBuf->buf + Offset,
584 AppendBuf->BufUsed - Offset);
585 Buf->BufUsed += AppendBuf->BufUsed - Offset;
586 Buf->buf[Buf->BufUsed] = '\0';
591 * @brief Append a C-String to the buffer
592 * @param Buf Buffer to modify
593 * @param AppendBuf Buffer to copy at the end of our buffer
594 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
595 * @param Offset Should we start copying from an offset?
597 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
600 long BufSizeRequired;
602 if ((AppendBuf == NULL) || (Buf == NULL))
606 aps = strlen(AppendBuf + Offset);
608 aps = AppendSize - Offset;
610 BufSizeRequired = Buf->BufUsed + aps + 1;
611 if (Buf->BufSize <= BufSizeRequired)
612 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
614 memcpy(Buf->buf + Buf->BufUsed,
618 Buf->buf[Buf->BufUsed] = '\0';
622 * @brief Callback for cURL to append the webserver reply to a buffer
623 * @params pre-defined by the cURL API; see man 3 curl for mre info
625 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
634 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
640 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
641 * @param outbuf the output buffer
642 * @param oblen the size of outbuf to sanitize
643 * @param strbuf the input buffer
645 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
647 const char *pch, *pche;
650 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
651 int eclen = sizeof(ec) -1;
653 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
655 if (PlainIn != NULL) {
656 len = strlen(PlainIn);
662 pche = pch + In->BufUsed;
669 pt = OutBuf->buf + OutBuf->BufUsed;
670 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
674 IncreaseBuf(OutBuf, 1, -1);
675 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
676 pt = OutBuf->buf + OutBuf->BufUsed;
680 for (b = 0; b < eclen; ++b) {
687 sprintf(pt,"%%%02X", *pch);
689 OutBuf->BufUsed += 3;
701 * @brief Append a string, escaping characters which have meaning in HTML.
703 * @param Target target buffer
704 * @param Source source buffer; set to NULL if you just have a C-String
705 * @param PlainIn Plain-C string to append; set to NULL if unused
706 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
707 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
708 * if set to 2, linebreaks are replaced by <br/>
710 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
712 const char *aptr, *eiptr;
716 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
719 if (PlainIn != NULL) {
721 len = strlen(PlainIn);
726 eiptr = aptr + Source->BufUsed;
727 len = Source->BufUsed;
733 bptr = Target->buf + Target->BufUsed;
734 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
736 while (aptr < eiptr){
738 IncreaseBuf(Target, 1, -1);
739 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
740 bptr = Target->buf + Target->BufUsed;
743 memcpy(bptr, "<", 4);
745 Target->BufUsed += 4;
747 else if (*aptr == '>') {
748 memcpy(bptr, ">", 4);
750 Target->BufUsed += 4;
752 else if (*aptr == '&') {
753 memcpy(bptr, "&", 5);
755 Target->BufUsed += 5;
757 else if (*aptr == '"') {
758 memcpy(bptr, """, 6);
760 Target->BufUsed += 6;
762 else if (*aptr == '\'') {
763 memcpy(bptr, "'", 5);
765 Target->BufUsed += 5;
767 else if (*aptr == LB) {
772 else if (*aptr == RB) {
777 else if (*aptr == QU) {
782 else if ((*aptr == 32) && (nbsp == 1)) {
783 memcpy(bptr, " ", 6);
785 Target->BufUsed += 6;
787 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
788 *bptr='\0'; /* nothing */
790 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
791 memcpy(bptr, "<br/>", 11);
793 Target->BufUsed += 11;
797 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
798 *bptr='\0'; /* nothing */
808 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
810 return Target->BufUsed;
814 * @brief Append a string, escaping characters which have meaning in HTML.
815 * Converts linebreaks into blanks; escapes single quotes
816 * @param Target target buffer
817 * @param Source source buffer; set to NULL if you just have a C-String
818 * @param PlainIn Plain-C string to append; set to NULL if unused
820 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
822 const char *aptr, *eiptr;
826 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
829 if (PlainIn != NULL) {
831 len = strlen(PlainIn);
836 eiptr = aptr + Source->BufUsed;
837 len = Source->BufUsed;
843 eptr = Target->buf + Target->BufSize - 8;
844 tptr = Target->buf + Target->BufUsed;
846 while (aptr < eiptr){
848 IncreaseBuf(Target, 1, -1);
849 eptr = Target->buf + Target->BufSize - 8;
850 tptr = Target->buf + Target->BufUsed;
857 else if (*aptr == '\r') {
861 else if (*aptr == '\'') {
867 Target->BufUsed += 5;
880 * @brief Append a string, escaping characters which have meaning in ICAL.
882 * @param Target target buffer
883 * @param Source source buffer; set to NULL if you just have a C-String
884 * @param PlainIn Plain-C string to append; set to NULL if unused
886 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
888 const char *aptr, *eiptr;
892 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
895 if (PlainIn != NULL) {
897 len = strlen(PlainIn);
902 eiptr = aptr + Source->BufUsed;
903 len = Source->BufUsed;
909 eptr = Target->buf + Target->BufSize - 8;
910 tptr = Target->buf + Target->BufUsed;
912 while (aptr < eiptr){
913 if(tptr + 3 >= eptr) {
914 IncreaseBuf(Target, 1, -1);
915 eptr = Target->buf + Target->BufSize - 8;
916 tptr = Target->buf + Target->BufUsed;
926 else if (*aptr == '\r') {
933 else if (*aptr == ',') {
949 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
951 * @param Target target buffer
952 * @param Source source buffer; set to NULL if you just have a C-String
953 * @param PlainIn Plain-C string to append; set to NULL if unused
954 * @returns size of result or -1
956 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
958 const char *aptr, *eiptr;
962 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
965 if (PlainIn != NULL) {
967 len = strlen(PlainIn);
972 eiptr = aptr + Source->BufUsed;
973 len = Source->BufUsed;
979 bptr = Target->buf + Target->BufUsed;
980 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
982 while (aptr < eiptr){
984 IncreaseBuf(Target, 1, -1);
985 eptr = Target->buf + Target->BufSize - 3;
986 bptr = Target->buf + Target->BufUsed;
993 Target->BufUsed += 2;
994 } else if (*aptr == '\\') {
999 Target->BufUsed += 2;
1009 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1011 return Target->BufUsed;
1015 * @brief extracts a substring from Source into dest
1016 * @param dest buffer to place substring into
1017 * @param Source string to copy substring from
1018 * @param Offset chars to skip from start
1019 * @param nChars number of chars to copy
1020 * @returns the number of chars copied; may be different from nChars due to the size of Source
1022 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1024 size_t NCharsRemain;
1025 if (Offset > Source->BufUsed)
1030 if (Offset + nChars < Source->BufUsed)
1032 if (nChars >= dest->BufSize)
1033 IncreaseBuf(dest, 0, nChars + 1);
1034 memcpy(dest->buf, Source->buf + Offset, nChars);
1035 dest->BufUsed = nChars;
1036 dest->buf[dest->BufUsed] = '\0';
1039 NCharsRemain = Source->BufUsed - Offset;
1040 if (NCharsRemain >= dest->BufSize)
1041 IncreaseBuf(dest, 0, NCharsRemain + 1);
1042 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1043 dest->BufUsed = NCharsRemain;
1044 dest->buf[dest->BufUsed] = '\0';
1045 return NCharsRemain;
1049 * @brief sprintf like function appending the formated string to the buffer
1050 * vsnprintf version to wrap into own calls
1051 * @param Buf Buffer to extend by format and @params
1052 * @param format printf alike format to add
1053 * @param ap va_list containing the items for format
1055 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1063 if ((Buf == NULL) || (format == NULL))
1066 BufSize = Buf->BufSize;
1067 nWritten = Buf->BufSize + 1;
1068 Offset = Buf->BufUsed;
1069 newused = Offset + nWritten;
1071 while (newused >= BufSize) {
1073 nWritten = vsnprintf(Buf->buf + Offset,
1074 Buf->BufSize - Offset,
1077 newused = Offset + nWritten;
1078 if (newused >= Buf->BufSize) {
1079 IncreaseBuf(Buf, 1, newused);
1080 newused = Buf->BufSize + 1;
1083 Buf->BufUsed = Offset + nWritten;
1084 BufSize = Buf->BufSize;
1091 * @brief sprintf like function appending the formated string to the buffer
1092 * @param Buf Buffer to extend by format and @params
1093 * @param format printf alike format to add
1094 * @param ap va_list containing the items for format
1096 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1104 if ((Buf == NULL) || (format == NULL))
1107 BufSize = Buf->BufSize;
1108 nWritten = Buf->BufSize + 1;
1109 Offset = Buf->BufUsed;
1110 newused = Offset + nWritten;
1112 while (newused >= BufSize) {
1113 va_start(arg_ptr, format);
1114 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1115 Buf->BufSize - Buf->BufUsed,
1118 newused = Buf->BufUsed + nWritten;
1119 if (newused >= Buf->BufSize) {
1120 IncreaseBuf(Buf, 1, newused);
1121 newused = Buf->BufSize + 1;
1124 Buf->BufUsed += nWritten;
1125 BufSize = Buf->BufSize;
1132 * @brief sprintf like function putting the formated string into the buffer
1133 * @param Buf Buffer to extend by format and @params
1134 * @param format printf alike format to add
1135 * @param ap va_list containing the items for format
1137 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1142 if ((Buf == NULL) || (format == NULL))
1145 nWritten = Buf->BufSize + 1;
1146 while (nWritten >= Buf->BufSize) {
1147 va_start(arg_ptr, format);
1148 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1150 if (nWritten >= Buf->BufSize) {
1151 IncreaseBuf(Buf, 0, 0);
1152 nWritten = Buf->BufSize + 1;
1155 Buf->BufUsed = nWritten ;
1161 * @brief Counts the numbmer of tokens in a buffer
1162 * @param Source String to count tokens in
1163 * @param tok Tokenizer char to count
1164 * @returns numbers of tokenizer chars found
1166 int StrBufNum_tokens(const StrBuf *source, char tok)
1170 return num_tokens(source->buf, tok);
1174 * remove_token() - a tokenizer that kills, maims, and destroys
1177 * @brief a string tokenizer
1178 * @param Source StringBuffer to read into
1179 * @param parmnum n'th @parameter to remove
1180 * @param separator tokenizer @param
1181 * @returns -1 if not found, else length of token.
1183 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1186 char *d, *s, *end; /* dest, source */
1189 /* Find desired @parameter */
1190 end = Source->buf + Source->BufUsed;
1192 while ((count < parmnum) &&
1195 /* End of string, bail! */
1200 if (*d == separator) {
1205 if ((d == NULL) || (d >= end))
1206 return 0; /* @Parameter not found */
1208 /* Find next @parameter */
1210 while ((*s && *s != separator) &&
1215 if (*s == separator)
1219 /* Hack and slash */
1221 memmove(d, s, Source->BufUsed - (s - Source->buf));
1222 Source->BufUsed += ReducedBy;
1224 else if (d == Source->buf) {
1226 Source->BufUsed = 0;
1230 Source->BufUsed += ReducedBy;
1243 * @brief a string tokenizer
1244 * @param dest Destination StringBuffer
1245 * @param Source StringBuffer to read into
1246 * @param parmnum n'th @parameter to extract
1247 * @param separator tokenizer @param
1248 * @returns -1 if not found, else length of token.
1250 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1252 const char *s, *e; //* source * /
1253 int len = 0; //* running total length of extracted string * /
1254 int current_token = 0; //* token currently being processed * /
1257 dest->buf[0] = '\0';
1263 if ((Source == NULL) || (Source->BufUsed ==0)) {
1267 e = s + Source->BufUsed;
1270 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1272 while ((s<e) && !IsEmptyStr(s)) {
1273 if (*s == separator) {
1276 if (len >= dest->BufSize) {
1277 dest->BufUsed = len;
1278 if (IncreaseBuf(dest, 1, -1) < 0) {
1283 if ( (current_token == parmnum) &&
1284 (*s != separator)) {
1285 dest->buf[len] = *s;
1288 else if (current_token > parmnum) {
1294 dest->buf[len] = '\0';
1295 dest->BufUsed = len;
1297 if (current_token < parmnum) {
1298 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1301 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1310 * @brief a string tokenizer to fetch an integer
1311 * @param dest Destination StringBuffer
1312 * @param parmnum n'th @parameter to extract
1313 * @param separator tokenizer @param
1314 * @returns 0 if not found, else integer representation of the token
1316 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1326 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1333 * @brief a string tokenizer to fetch a long integer
1334 * @param dest Destination StringBuffer
1335 * @param parmnum n'th @parameter to extract
1336 * @param separator tokenizer @param
1337 * @returns 0 if not found, else long integer representation of the token
1339 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1349 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1357 * @brief a string tokenizer to fetch an unsigned long
1358 * @param dest Destination StringBuffer
1359 * @param parmnum n'th @parameter to extract
1360 * @param separator tokenizer @param
1361 * @returns 0 if not found, else unsigned long representation of the token
1363 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1374 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1378 return (unsigned long) atol(pnum);
1387 * @briefa string tokenizer; Bounds checker
1388 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1389 * @param Source our tokenbuffer
1390 * @param pStart the token iterator pointer to inspect
1391 * @returns whether the revolving pointer is inside of the search range
1393 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1395 if ((Source == NULL) ||
1396 (*pStart == StrBufNOTNULL) ||
1397 (Source->BufUsed == 0))
1401 if (*pStart == NULL)
1405 else if (*pStart > Source->buf + Source->BufUsed)
1409 else if (*pStart <= Source->buf)
1418 * @brief a string tokenizer
1419 * @param dest Destination StringBuffer
1420 * @param Source StringBuffer to read into
1421 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1422 * @param separator tokenizer @param
1423 * @returns -1 if not found, else length of token.
1425 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1427 const char *s; /* source */
1428 const char *EndBuffer; /* end stop of source buffer */
1429 int current_token = 0; /* token currently being processed */
1430 int len = 0; /* running total length of extracted string */
1432 if ((Source == NULL) ||
1433 (Source->BufUsed == 0) )
1435 *pStart = StrBufNOTNULL;
1439 EndBuffer = Source->buf + Source->BufUsed;
1443 dest->buf[0] = '\0';
1448 *pStart = EndBuffer + 1;
1452 if (*pStart == NULL)
1454 *pStart = Source->buf; /* we're starting to examine this buffer. */
1456 else if ((*pStart < Source->buf) ||
1457 (*pStart > EndBuffer ) )
1459 return -1; /* no more tokens to find. */
1463 /* start to find the next token */
1464 while ((s <= EndBuffer) &&
1465 (current_token == 0) )
1467 if (*s == separator)
1469 /* we found the next token */
1473 if (len >= dest->BufSize)
1475 /* our Dest-buffer isn't big enough, increase it. */
1476 dest->BufUsed = len;
1478 if (IncreaseBuf(dest, 1, -1) < 0) {
1479 /* WHUT? no more mem? bail out. */
1486 if ( (current_token == 0 ) && /* are we in our target token? */
1487 (!IsEmptyStr(s) ) &&
1488 (separator != *s) ) /* don't copy the token itself */
1490 dest->buf[len] = *s; /* Copy the payload */
1491 ++len; /* remember the bigger size. */
1497 /* did we reach the end? */
1498 if ((s > EndBuffer)) {
1499 EndBuffer = StrBufNOTNULL;
1500 *pStart = EndBuffer;
1503 *pStart = s; /* remember the position for the next run */
1506 /* sanitize our extracted token */
1507 dest->buf[len] = '\0';
1508 dest->BufUsed = len;
1515 * @brief a string tokenizer
1516 * @param dest Destination StringBuffer
1517 * @param Source StringBuffer to read into
1518 * @param pStart pointer to the end of the last token. Feed with NULL.
1519 * @param separator tokenizer @param
1520 * @returns -1 if not found, else length of token.
1522 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1524 const char *s, *EndBuffer; //* source * /
1525 int len = 0; //* running total length of extracted string * /
1526 int current_token = 0; //* token currently being processed * /
1528 if ((Source == NULL) ||
1529 (Source->BufUsed ==0)) {
1533 return Source->BufUsed;
1535 if (*pStart == NULL)
1536 *pStart = Source->buf;
1538 EndBuffer = Source->buf + Source->BufUsed;
1540 if ((*pStart < Source->buf) ||
1541 (*pStart > EndBuffer)) {
1549 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1551 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1552 if (*s == separator) {
1555 if (current_token >= nTokens) {
1567 * @brief a string tokenizer to fetch an integer
1568 * @param dest Destination StringBuffer
1569 * @param parmnum n'th @parameter to extract
1570 * @param separator tokenizer @param
1571 * @returns 0 if not found, else integer representation of the token
1573 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1583 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1590 * @brief a string tokenizer to fetch a long integer
1591 * @param dest Destination StringBuffer
1592 * @param parmnum n'th @parameter to extract
1593 * @param separator tokenizer @param
1594 * @returns 0 if not found, else long integer representation of the token
1596 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1606 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1614 * @brief a string tokenizer to fetch an unsigned long
1615 * @param dest Destination StringBuffer
1616 * @param parmnum n'th @parameter to extract
1617 * @param separator tokenizer @param
1618 * @returns 0 if not found, else unsigned long representation of the token
1620 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1631 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1635 return (unsigned long) atol(pnum);
1644 * @brief Read a line from socket
1645 * flushes and closes the FD on error
1646 * @param buf the buffer to get the input to
1647 * @param fd pointer to the filedescriptor to read
1648 * @param append Append to an existing string or replace?
1649 * @param Error strerror() on error
1650 * @returns numbers of chars read
1652 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1654 int len, rlen, slen;
1659 slen = len = buf->BufUsed;
1661 rlen = read(*fd, &buf->buf[len], 1);
1663 *Error = strerror(errno);
1670 if (buf->buf[len] == '\n')
1672 if (buf->buf[len] != '\r')
1674 if (len >= buf->BufSize) {
1676 buf->buf[len+1] = '\0';
1677 IncreaseBuf(buf, 1, -1);
1681 buf->buf[len] = '\0';
1686 * @brief Read a line from socket
1687 * flushes and closes the FD on error
1688 * @param buf the buffer to get the input to
1689 * @param fd pointer to the filedescriptor to read
1690 * @param append Append to an existing string or replace?
1691 * @param Error strerror() on error
1692 * @returns numbers of chars read
1694 int StrBufTCP_read_buffered_line(StrBuf *Line,
1698 int selectresolution,
1702 int nSuccessLess = 0;
1709 if (buf->BufUsed > 0) {
1710 pch = strchr(buf->buf, '\n');
1713 len = pch - buf->buf;
1714 if (len > 0 && (*(pch - 1) == '\r') )
1716 StrBufSub(Line, buf, 0, len - rlen);
1717 StrBufCutLeft(buf, len + 1);
1722 if (buf->BufSize - buf->BufUsed < 10)
1723 IncreaseBuf(buf, 1, -1);
1725 fdflags = fcntl(*fd, F_GETFL);
1726 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1728 while ((nSuccessLess < timeout) && (pch == NULL)) {
1730 tv.tv_sec = selectresolution;
1735 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1736 *Error = strerror(errno);
1742 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
1747 &buf->buf[buf->BufUsed],
1748 buf->BufSize - buf->BufUsed - 1);
1750 *Error = strerror(errno);
1755 else if (rlen > 0) {
1757 buf->BufUsed += rlen;
1758 buf->buf[buf->BufUsed] = '\0';
1759 if (buf->BufUsed + 10 > buf->BufSize) {
1760 IncreaseBuf(buf, 1, -1);
1762 pch = strchr(buf->buf, '\n');
1769 len = pch - buf->buf;
1770 if (len > 0 && (*(pch - 1) == '\r') )
1772 StrBufSub(Line, buf, 0, len - rlen);
1773 StrBufCutLeft(buf, len + 1);
1780 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1781 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1783 * @brief Read a line from socket
1784 * flushes and closes the FD on error
1785 * @param buf the buffer to get the input to
1786 * @param Pos pointer to the current read position, should be NULL initialized!
1787 * @param fd pointer to the filedescriptor to read
1788 * @param append Append to an existing string or replace?
1789 * @param Error strerror() on error
1790 * @returns numbers of chars read
1792 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1797 int selectresolution,
1800 const char *pche = NULL;
1801 const char *pos = NULL;
1803 int nSuccessLess = 0;
1805 const char *pch = NULL;
1811 if ((IOBuf->BufUsed > 0) &&
1813 (pos < IOBuf->buf + IOBuf->BufUsed))
1815 pche = IOBuf->buf + IOBuf->BufUsed;
1817 while ((pch < pche) && (*pch != '\n'))
1819 if ((pch >= pche) || (*pch == '\0'))
1821 if ((pch != NULL) &&
1826 if (len > 0 && (*(pch - 1) == '\r') )
1828 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1838 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1842 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1843 IncreaseBuf(IOBuf, 1, -1);
1846 fdflags = fcntl(*fd, F_GETFL);
1847 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1850 while ((nSuccessLess < timeout) &&
1860 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
1861 *Error = strerror(errno);
1865 *Error = ErrRBLF_SelectFailed;
1868 if (! FD_ISSET(*fd, &rfds) != 0) {
1874 &IOBuf->buf[IOBuf->BufUsed],
1875 IOBuf->BufSize - IOBuf->BufUsed - 1);
1877 *Error = strerror(errno);
1882 else if (rlen > 0) {
1884 IOBuf->BufUsed += rlen;
1885 IOBuf->buf[IOBuf->BufUsed] = '\0';
1886 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1887 IncreaseBuf(IOBuf, 1, -1);
1890 pche = IOBuf->buf + IOBuf->BufUsed;
1892 while ((pch < pche) && (*pch != '\n'))
1894 if ((pch >= pche) || (*pch == '\0'))
1903 if (len > 0 && (*(pch - 1) == '\r') )
1905 StrBufSub(Line, IOBuf, 0, len - rlen);
1906 *Pos = pos + len + 1;
1909 *Error = ErrRBLF_NotEnoughSentFromServer;
1915 * @brief Input binary data from socket
1916 * flushes and closes the FD on error
1917 * @param buf the buffer to get the input to
1918 * @param fd pointer to the filedescriptor to read
1919 * @param append Append to an existing string or replace?
1920 * @param nBytes the maximal number of bytes to read
1921 * @param Error strerror() on error
1922 * @returns numbers of chars read
1924 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1927 int len, rlen, slen;
1934 if ((Buf == NULL) || (*fd == -1))
1938 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1939 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1941 ptr = Buf->buf + Buf->BufUsed;
1943 slen = len = Buf->BufUsed;
1945 fdflags = fcntl(*fd, F_GETFL);
1946 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
1948 while ((nRead < nBytes) &&
1958 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
1959 *Error = strerror(errno);
1963 *Error = ErrRBLF_SelectFailed;
1966 if (! FD_ISSET(*fd, &rfds) != 0) {
1972 if ((rlen = read(*fd,
1974 nBytes - nRead)) == -1) {
1977 *Error = strerror(errno);
1982 Buf->BufUsed += rlen;
1984 Buf->buf[Buf->BufUsed] = '\0';
1988 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1990 * @brief Input binary data from socket
1991 * flushes and closes the FD on error
1992 * @param buf the buffer to get the input to
1993 * @param fd pointer to the filedescriptor to read
1994 * @param append Append to an existing string or replace?
1995 * @param nBytes the maximal number of bytes to read
1996 * @param Error strerror() on error
1997 * @returns numbers of chars read
1999 int StrBufReadBLOBBuffered(StrBuf *Blob,
2016 int nAlreadyRead = 0;
2024 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
2028 if (Blob->BufUsed + nBytes >= Blob->BufSize)
2029 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
2034 len = pos - IOBuf->buf;
2035 rlen = IOBuf->BufUsed - len;
2038 if ((IOBuf->BufUsed > 0) &&
2040 (pos < IOBuf->buf + IOBuf->BufUsed))
2042 pche = IOBuf->buf + IOBuf->BufUsed;
2045 if (rlen < nBytes) {
2046 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
2047 Blob->BufUsed += rlen;
2048 Blob->buf[Blob->BufUsed] = '\0';
2049 nAlreadyRead = nRead = rlen;
2052 if (rlen >= nBytes) {
2053 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
2054 Blob->BufUsed += nBytes;
2055 Blob->buf[Blob->BufUsed] = '\0';
2056 if (rlen == nBytes) {
2067 if (IOBuf->BufSize < nBytes - nRead)
2068 IncreaseBuf(IOBuf, 0, nBytes - nRead);
2071 slen = len = Blob->BufUsed;
2073 fdflags = fcntl(*fd, F_GETFL);
2074 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2079 while ((nRead < nBytes) &&
2088 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
2089 *Error = strerror(errno);
2093 *Error = ErrRBLF_SelectFailed;
2096 if (! FD_ISSET(*fd, &rfds) != 0) {
2108 *Error = strerror(errno);
2111 else if (rlen == 0){
2113 if ((check == NNN_TERM) &&
2115 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2117 StrBufPlain(Blob, HKEY("\n000\n"));
2118 StrBufCutRight(Blob, 5);
2119 return Blob->BufUsed;
2121 if (nSelects > 10) {
2123 *Error = ErrRBB_too_many_selects;
2127 else if (rlen > 0) {
2130 IOBuf->BufUsed += rlen;
2133 if (nRead > nBytes) {
2134 *Pos = IOBuf->buf + nBytes;
2136 Blob->buf[Blob->BufUsed] = '\0';
2137 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2141 return nRead + nAlreadyRead;
2145 * @brief Cut nChars from the start of the string
2146 * @param Buf Buffer to modify
2147 * @param nChars how many chars should be skipped?
2149 void StrBufCutLeft(StrBuf *Buf, int nChars)
2151 if (nChars >= Buf->BufUsed) {
2155 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2156 Buf->BufUsed -= nChars;
2157 Buf->buf[Buf->BufUsed] = '\0';
2161 * @brief Cut the trailing n Chars from the string
2162 * @param Buf Buffer to modify
2163 * @param nChars how many chars should be trunkated?
2165 void StrBufCutRight(StrBuf *Buf, int nChars)
2167 if (nChars >= Buf->BufUsed) {
2171 Buf->BufUsed -= nChars;
2172 Buf->buf[Buf->BufUsed] = '\0';
2176 * @brief Cut the string after n Chars
2177 * @param Buf Buffer to modify
2178 * @param AfternChars after how many chars should we trunkate the string?
2179 * @param At if non-null and points inside of our string, cut it there.
2181 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2184 AfternChars = At - Buf->buf;
2187 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2189 Buf->BufUsed = AfternChars;
2190 Buf->buf[Buf->BufUsed] = '\0';
2195 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2196 * @param buf the string to modify
2197 * @param len length of the string.
2199 void StrBufTrim(StrBuf *Buf)
2202 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2204 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2207 if (delta > 0) StrBufCutLeft(Buf, delta);
2209 if (Buf->BufUsed == 0) return;
2210 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2213 Buf->buf[Buf->BufUsed] = '\0';
2217 * @brief uppercase the contents of a buffer
2218 * @param Buf the buffer to translate
2220 void StrBufUpCase(StrBuf *Buf)
2225 pche = pch + Buf->BufUsed;
2226 while (pch < pche) {
2227 *pch = toupper(*pch);
2234 * @brief lowercase the contents of a buffer
2235 * @param Buf the buffer to translate
2237 void StrBufLowerCase(StrBuf *Buf)
2242 pche = pch + Buf->BufUsed;
2243 while (pch < pche) {
2244 *pch = tolower(*pch);
2250 * @brief removes double slashes from pathnames
2251 * @param Dir directory string to filter
2252 * @param RemoveTrailingSlash allows / disallows trailing slashes
2254 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2260 while (!IsEmptyStr(a)) {
2272 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2277 Dir->BufUsed = b - Dir->buf;
2281 * @brief unhide special chars hidden to the HTML escaper
2282 * @param target buffer to put the unescaped string in
2283 * @param source buffer to unescape
2285 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2291 FlushStrBuf(target);
2293 if (source == NULL ||target == NULL)
2298 len = source->BufUsed;
2299 for (a = 0; a < len; ++a) {
2300 if (target->BufUsed >= target->BufSize)
2301 IncreaseBuf(target, 1, -1);
2303 if (source->buf[a] == '=') {
2304 hex[0] = source->buf[a + 1];
2305 hex[1] = source->buf[a + 2];
2308 sscanf(hex, "%02x", &b);
2309 target->buf[target->BufUsed] = b;
2310 target->buf[++target->BufUsed] = 0;
2314 target->buf[target->BufUsed] = source->buf[a];
2315 target->buf[++target->BufUsed] = 0;
2322 * @brief hide special chars from the HTML escapers and friends
2323 * @param target buffer to put the escaped string in
2324 * @param source buffer to escape
2326 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2331 FlushStrBuf(target);
2333 if (source == NULL ||target == NULL)
2338 len = source->BufUsed;
2339 for (i=0; i<len; ++i) {
2340 if (target->BufUsed + 4 >= target->BufSize)
2341 IncreaseBuf(target, 1, -1);
2342 if ( (isalnum(source->buf[i])) ||
2343 (source->buf[i]=='-') ||
2344 (source->buf[i]=='_') ) {
2345 target->buf[target->BufUsed++] = source->buf[i];
2348 sprintf(&target->buf[target->BufUsed],
2350 (0xFF &source->buf[i]));
2351 target->BufUsed += 3;
2354 target->buf[target->BufUsed + 1] = '\0';
2358 * @brief uses the same calling syntax as compress2(), but it
2359 * creates a stream compatible with HTTP "Content-encoding: gzip"
2362 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2363 #define OS_CODE 0x03 /*< unix */
2364 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2365 size_t * destLen, /*< length of the compresed data */
2366 const Bytef * source, /*< source to encode */
2367 uLong sourceLen, /*< length of source to encode */
2368 int level) /*< compression level */
2370 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2372 /* write gzip header */
2373 snprintf((char *) dest, *destLen,
2374 "%c%c%c%c%c%c%c%c%c%c",
2375 gz_magic[0], gz_magic[1], Z_DEFLATED,
2376 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2379 /* normal deflate */
2382 stream.next_in = (Bytef *) source;
2383 stream.avail_in = (uInt) sourceLen;
2384 stream.next_out = dest + 10L; // after header
2385 stream.avail_out = (uInt) * destLen;
2386 if ((uLong) stream.avail_out != *destLen)
2389 stream.zalloc = (alloc_func) 0;
2390 stream.zfree = (free_func) 0;
2391 stream.opaque = (voidpf) 0;
2393 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2394 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2398 err = deflate(&stream, Z_FINISH);
2399 if (err != Z_STREAM_END) {
2400 deflateEnd(&stream);
2401 return err == Z_OK ? Z_BUF_ERROR : err;
2403 *destLen = stream.total_out + 10L;
2405 /* write CRC and Length */
2406 uLong crc = crc32(0L, source, sourceLen);
2408 for (n = 0; n < 4; ++n, ++*destLen) {
2409 dest[*destLen] = (int) (crc & 0xff);
2412 uLong len = stream.total_in;
2413 for (n = 0; n < 4; ++n, ++*destLen) {
2414 dest[*destLen] = (int) (len & 0xff);
2417 err = deflateEnd(&stream);
2424 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2426 int CompressBuffer(StrBuf *Buf)
2429 char *compressed_data = NULL;
2430 size_t compressed_len, bufsize;
2433 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2434 compressed_data = malloc(compressed_len);
2436 if (compressed_data == NULL)
2438 /* Flush some space after the used payload so valgrind shuts up... */
2439 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2440 Buf->buf[Buf->BufUsed + i++] = '\0';
2441 if (compress_gzip((Bytef *) compressed_data,
2444 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2447 Buf->buf = compressed_data;
2448 Buf->BufUsed = compressed_len;
2449 Buf->BufSize = bufsize;
2450 /* Flush some space after the used payload so valgrind shuts up... */
2452 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2453 Buf->buf[Buf->BufUsed + i++] = '\0';
2456 free(compressed_data);
2458 #endif /* HAVE_ZLIB */
2463 * @brief decode a buffer from base 64 encoding; destroys original
2464 * @param Buf Buffor to transform
2466 int StrBufDecodeBase64(StrBuf *Buf)
2470 if (Buf == NULL) return -1;
2472 xferbuf = (char*) malloc(Buf->BufSize);
2473 siz = CtdlDecodeBase64(xferbuf,
2483 * @brief decode a buffer from base 64 encoding; destroys original
2484 * @param Buf Buffor to transform
2486 int StrBufDecodeHex(StrBuf *Buf)
2489 char *pch, *pche, *pchi;
2491 if (Buf == NULL) return -1;
2493 pch = pchi = Buf->buf;
2494 pche = pch + Buf->BufUsed;
2496 while (pchi < pche){
2497 ch = decode_hex(pchi);
2504 Buf->BufUsed = pch - Buf->buf;
2505 return Buf->BufUsed;
2509 * @brief replace all chars >0x20 && < 0x7F with Mute
2510 * @param Mute char to put over invalid chars
2511 * @param Buf Buffor to transform
2513 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2517 if (Buf == NULL) return -1;
2518 pch = (unsigned char *)Buf->buf;
2519 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2520 if ((*pch < 0x20) || (*pch > 0x7F))
2524 return Buf->BufUsed;
2529 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2530 * @param Buf Buffer to translate
2531 * @param StripBlanks Reduce several blanks to one?
2533 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2539 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2540 Buf->buf[Buf->BufUsed - 1] = '\0';
2545 while (a < Buf->BufUsed) {
2546 if (Buf->buf[a] == '+')
2548 else if (Buf->buf[a] == '%') {
2549 /* don't let % chars through, rather truncate the input. */
2550 if (a + 2 > Buf->BufUsed) {
2555 hex[0] = Buf->buf[a + 1];
2556 hex[1] = Buf->buf[a + 2];
2559 sscanf(hex, "%02x", &b);
2560 Buf->buf[a] = (char) b;
2561 len = Buf->BufUsed - a - 2;
2563 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2575 * @brief RFC2047-encode a header field if necessary.
2576 * If no non-ASCII characters are found, the string
2577 * will be copied verbatim without encoding.
2579 * @param target Target buffer.
2580 * @param source Source string to be encoded.
2581 * @returns encoded length; -1 if non success.
2583 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2585 const char headerStr[] = "=?UTF-8?Q?";
2586 int need_to_encode = 0;
2590 if ((source == NULL) ||
2594 while ((i < source->BufUsed) &&
2595 (!IsEmptyStr (&source->buf[i])) &&
2596 (need_to_encode == 0)) {
2597 if (((unsigned char) source->buf[i] < 32) ||
2598 ((unsigned char) source->buf[i] > 126)) {
2604 if (!need_to_encode) {
2605 if (*target == NULL) {
2606 *target = NewStrBufPlain(source->buf, source->BufUsed);
2609 FlushStrBuf(*target);
2610 StrBufAppendBuf(*target, source, 0);
2612 return (*target)->BufUsed;
2614 if (*target == NULL)
2615 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2616 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2617 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2618 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2619 (*target)->BufUsed = sizeof(headerStr) - 1;
2620 for (i=0; (i < source->BufUsed); ++i) {
2621 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2622 IncreaseBuf(*target, 1, 0);
2623 ch = (unsigned char) source->buf[i];
2624 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2625 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2626 (*target)->BufUsed += 3;
2629 (*target)->buf[(*target)->BufUsed] = ch;
2630 (*target)->BufUsed++;
2634 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2635 IncreaseBuf(*target, 1, 0);
2637 (*target)->buf[(*target)->BufUsed++] = '?';
2638 (*target)->buf[(*target)->BufUsed++] = '=';
2639 (*target)->buf[(*target)->BufUsed] = '\0';
2640 return (*target)->BufUsed;;
2644 * @brief replaces all occurances of 'search' by 'replace'
2645 * @param buf Buffer to modify
2646 * @param search character to search
2647 * @param relpace character to replace search by
2649 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2654 for (i=0; i<buf->BufUsed; i++)
2655 if (buf->buf[i] == search)
2656 buf->buf[i] = replace;
2663 * @brief Wrapper around iconv_open()
2664 * Our version adds aliases for non-standard Microsoft charsets
2665 * such as 'MS950', aliasing them to names like 'CP950'
2667 * @param tocode Target encoding
2668 * @param fromcode Source encoding
2670 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2673 iconv_t ic = (iconv_t)(-1) ;
2674 ic = iconv_open(tocode, fromcode);
2675 if (ic == (iconv_t)(-1) ) {
2676 char alias_fromcode[64];
2677 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2678 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2679 alias_fromcode[0] = 'C';
2680 alias_fromcode[1] = 'P';
2681 ic = iconv_open(tocode, alias_fromcode);
2684 *(iconv_t *)pic = ic;
2690 * @brief find one chunk of a RFC822 encoded string
2691 * @param Buffer where to search
2692 * @param bptr where to start searching
2693 * @returns found position, NULL if none.
2695 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2698 /* Find the next ?Q? */
2699 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2702 end = strchr(bptr + 2, '?');
2707 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2708 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2709 (*(end + 2) == '?')) {
2710 /* skip on to the end of the cluster, the next ?= */
2711 end = strstr(end + 3, "?=");
2714 /* sort of half valid encoding, try to find an end. */
2715 end = strstr(bptr, "?=");
2720 * @brief swaps the contents of two StrBufs
2721 * this is to be used to have cheap switched between a work-buffer and a target buffer
2722 * @param A First one
2723 * @param B second one
2725 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2729 memcpy(&C, A, sizeof(*A));
2730 memcpy(A, B, sizeof(*B));
2731 memcpy(B, &C, sizeof(C));
2737 * @brief convert one buffer according to the preselected iconv pointer PIC
2738 * @param ConvertBuf buffer we need to translate
2739 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2740 * @param pic Pointer to the iconv-session Object
2742 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2748 char *ibuf; /**< Buffer of characters to be converted */
2749 char *obuf; /**< Buffer for converted characters */
2750 size_t ibuflen; /**< Length of input buffer */
2751 size_t obuflen; /**< Length of output buffer */
2754 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2755 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2756 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2758 ic = *(iconv_t*)pic;
2759 ibuf = ConvertBuf->buf;
2760 ibuflen = ConvertBuf->BufUsed;
2762 obuflen = TmpBuf->BufSize;
2764 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2767 if (errno == E2BIG) {
2769 IncreaseBuf(TmpBuf, 0, 0);
2774 else if (errno == EILSEQ){
2775 /* hm, invalid utf8 sequence... what to do now? */
2776 /* An invalid multibyte sequence has been encountered in the input */
2778 else if (errno == EINVAL) {
2779 /* An incomplete multibyte sequence has been encountered in the input. */
2782 FlushStrBuf(TmpBuf);
2785 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2786 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2788 /* little card game: wheres the red lady? */
2789 SwapBuffers(ConvertBuf, TmpBuf);
2790 FlushStrBuf(TmpBuf);
2797 * @brief catches one RFC822 encoded segment, and decodes it.
2798 * @param Target buffer to fill with result
2799 * @param DecodeMe buffer with stuff to process
2800 * @param SegmentStart points to our current segment in DecodeMe
2801 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2802 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2803 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2804 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2806 inline static void DecodeSegment(StrBuf *Target,
2807 const StrBuf *DecodeMe,
2811 StrBuf *ConvertBuf2,
2812 StrBuf *FoundCharset)
2818 iconv_t ic = (iconv_t)(-1);
2820 /* Now we handle foreign character sets properly encoded
2821 * in RFC2047 format.
2823 StaticBuf.buf = SegmentStart;
2824 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2825 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2826 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2827 if (FoundCharset != NULL) {
2828 FlushStrBuf(FoundCharset);
2829 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2831 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2832 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2834 *encoding = toupper(*encoding);
2835 if (*encoding == 'B') { /**< base64 */
2836 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2838 ConvertBuf->BufUsed);
2840 else if (*encoding == 'Q') { /**< quoted-printable */
2844 while (pos < ConvertBuf->BufUsed)
2846 if (ConvertBuf->buf[pos] == '_')
2847 ConvertBuf->buf[pos] = ' ';
2851 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2854 ConvertBuf->BufUsed);
2857 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2860 ctdl_iconv_open("UTF-8", charset, &ic);
2861 if (ic != (iconv_t)(-1) ) {
2863 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2864 StrBufAppendBuf(Target, ConvertBuf2, 0);
2869 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2875 * @brief Handle subjects with RFC2047 encoding such as:
2876 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2877 * @param Target where to put the decoded string to
2878 * @param DecodeMe buffer with encoded string
2879 * @param DefaultCharset if we don't find one, which should we use?
2880 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2881 * put it here for later use where no string might be known.
2883 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2885 StrBuf *DecodedInvalidBuf = NULL;
2886 StrBuf *ConvertBuf, *ConvertBuf2;
2887 const StrBuf *DecodeMee = DecodeMe;
2888 char *start, *end, *next, *nextend, *ptr = NULL;
2890 iconv_t ic = (iconv_t)(-1) ;
2895 int illegal_non_rfc2047_encoding = 0;
2897 /* Sometimes, badly formed messages contain strings which were simply
2898 * written out directly in some foreign character set instead of
2899 * using RFC2047 encoding. This is illegal but we will attempt to
2900 * handle it anyway by converting from a user-specified default
2901 * charset to UTF-8 if we see any nonprintable characters.
2904 len = StrLength(DecodeMe);
2905 for (i=0; i<DecodeMe->BufUsed; ++i) {
2906 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2907 illegal_non_rfc2047_encoding = 1;
2912 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2913 if ((illegal_non_rfc2047_encoding) &&
2914 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2915 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2918 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2919 if (ic != (iconv_t)(-1) ) {
2920 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2921 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2922 DecodeMee = DecodedInvalidBuf;
2928 /* pre evaluate the first pair */
2929 nextend = end = NULL;
2930 len = StrLength(DecodeMee);
2931 start = strstr(DecodeMee->buf, "=?");
2932 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2934 end = FindNextEnd (DecodeMee, start);
2936 StrBufAppendBuf(Target, DecodeMee, 0);
2937 FreeStrBuf(&ConvertBuf);
2938 FreeStrBuf(&DecodedInvalidBuf);
2942 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2944 if (start != DecodeMee->buf) {
2947 nFront = start - DecodeMee->buf;
2948 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2952 * Since spammers will go to all sorts of absurd lengths to get their
2953 * messages through, there are LOTS of corrupt headers out there.
2954 * So, prevent a really badly formed RFC2047 header from throwing
2955 * this function into an infinite loop.
2957 while ((start != NULL) &&
2964 DecodeSegment(Target,
2972 next = strstr(end, "=?");
2974 if ((next != NULL) &&
2976 nextend = FindNextEnd(DecodeMee, next);
2977 if (nextend == NULL)
2980 /* did we find two partitions */
2981 if ((next != NULL) &&
2985 while ((ptr < next) &&
2991 /* did we find a gab just filled with blanks? */
2994 long gap = next - start;
2999 /* now terminate the gab at the end */
3000 delta = (next - end) - 2; ////TODO: const!
3001 ((StrBuf*)DecodeMee)->BufUsed -= delta;
3002 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
3004 /* move next to its new location. */
3009 /* our next-pair is our new first pair now. */
3015 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3016 if ((end != NULL) && (end < nextend)) {
3018 while ( (ptr < nextend) &&
3025 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3027 FreeStrBuf(&ConvertBuf);
3028 FreeStrBuf(&ConvertBuf2);
3029 FreeStrBuf(&DecodedInvalidBuf);
3033 * @brief evaluate the length of an utf8 special character sequence
3034 * @param Char the character to examine
3035 * @returns width of utf8 chars in bytes
3037 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
3042 while ((n < 8) && ((test & *CharS) != 0)) {
3046 if ((n > 6) || ((CharE - CharS) > n))
3052 * @brief detect whether this char starts an utf-8 encoded char
3053 * @param Char character to inspect
3054 * @returns yes or no
3056 static inline int Ctdl_IsUtf8SequenceStart(char Char)
3058 /** 11??.???? indicates an UTF8 Sequence. */
3059 return ((Char & 0xC0) != 0);
3063 * @brief measure the number of glyphs in an UTF8 string...
3064 * @param str string to measure
3065 * @returns the length of str
3067 long StrBuf_Utf8StrLen(StrBuf *Buf)
3073 if ((Buf == NULL) || (Buf->BufUsed == 0))
3076 eptr = Buf->buf + Buf->BufUsed;
3077 while ((aptr < eptr) && (*aptr != '\0')) {
3078 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3079 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3080 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
3093 * @brief cuts a string after maxlen glyphs
3094 * @param str string to cut to maxlen glyphs
3095 * @param maxlen how long may the string become?
3096 * @returns pointer to maxlen or the end of the string
3098 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3104 eptr = Buf->buf + Buf->BufUsed;
3105 while ((aptr < eptr) && (*aptr != '\0')) {
3106 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3107 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3108 while ((m-- > 0) && (*aptr++ != '\0'))
3117 Buf->BufUsed = aptr - Buf->buf;
3118 return Buf->BufUsed;
3121 return Buf->BufUsed;
3127 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3128 * @param LineBuf your line will be copied here.
3129 * @param Buf BLOB with lines of text...
3130 * @param Ptr moved arround to keep the next-line across several iterations
3131 * has to be &NULL on start; will be &NotNULL on end of buffer
3132 * @returns size of copied buffer
3134 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3136 const char *aptr, *ptr, *eptr;
3139 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3140 *Ptr = StrBufNOTNULL;
3144 FlushStrBuf(LineBuf);
3146 ptr = aptr = Buf->buf;
3150 optr = LineBuf->buf;
3151 eptr = Buf->buf + Buf->BufUsed;
3152 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3154 while ((ptr <= eptr) &&
3161 LineBuf->BufUsed = optr - LineBuf->buf;
3162 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3163 optr = LineBuf->buf + LineBuf->BufUsed;
3164 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3168 if ((ptr >= eptr) && (optr > LineBuf->buf))
3170 LineBuf->BufUsed = optr - LineBuf->buf;
3172 if ((ptr <= eptr) && (*ptr == '\r'))
3174 if ((ptr <= eptr) && (*ptr == '\n'))
3181 *Ptr = StrBufNOTNULL;
3184 return Buf->BufUsed - (ptr - Buf->buf);