2 * Copyright (c) 1987-2011 by the citadel.org team
4 * This program is open source software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include <sys/select.h>
28 #include <sys/types.h>
29 #define SHOW_ME_VAPPEND_PRINTF
31 #include "libcitadel.h"
43 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
44 const Bytef * source, uLong sourceLen, int level);
46 int BaseStrBufSize = 64;
48 const char *StrBufNOTNULL = ((char*) NULL) - 1;
50 const char HexList[256][3] = {
51 "00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
52 "10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
53 "20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
54 "30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
55 "40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
56 "50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
57 "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
58 "70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
59 "80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
60 "90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
61 "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
62 "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
63 "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
64 "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
65 "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
66 "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};
69 * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
70 * StrBuf is a versatile class, aiding the handling of dynamic strings
71 * * reduce de/reallocations
72 * * reduce the need to remeasure it
73 * * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
74 * * allow asyncroneous IO for line and Blob based operations
75 * * reduce the use of memove in those
76 * * Quick filling in several operations with append functions
80 * @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
85 * @defgroup StrBuf_Cast Cast operators to interact with char* based code
87 * use these operators to interfere with code demanding char*;
88 * if you need to own the content, smash me. Avoid, since we loose the length information.
92 * @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
94 * operations to get your Strings into a StrBuf, manipulating them, or appending
97 * @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence
99 * Quick tokenizer; demands of the user to pull its tokens in sequence
103 * @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
105 * versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
109 * @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
111 * File IO to fill StrBufs; Works with work-buffer shared across several calls;
112 * External Cursor to maintain the current read position inside of the buffer
113 * the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower)
117 * @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
123 * @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
125 * these functions translate the content of a buffer into another representation;
126 * some are combined Fillers and encoders
130 * Private Structure for the Stringbuffer
133 char *buf; /**< the pointer to the dynamic buffer */
134 long BufSize; /**< how many spcae do we optain */
135 long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
136 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
138 long nIncreases; /**< for profiling; cound how many times we needed more */
139 char bt [SIZ]; /**< Stacktrace of last increase */
140 char bt_lastinc [SIZ]; /**< How much did we increase last time? */
145 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
146 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
149 #ifdef HAVE_BACKTRACE
150 static void StrBufBacktrace(StrBuf *Buf, int which)
154 void *stack_frames[50];
159 pstart = pch = Buf->bt;
161 pstart = pch = Buf->bt_lastinc;
162 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
163 strings = backtrace_symbols(stack_frames, size);
164 for (i = 0; i < size; i++) {
166 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
168 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
177 void dbg_FreeStrBuf(StrBuf *FreeMe, char *FromWhere)
179 if (hFreeDbglog == -1){
180 pid_t pid = getpid();
182 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
183 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
185 if ((*FreeMe)->nIncreases > 0)
189 n = snprintf(buf, SIZ * 3, "%c+|%ld|%ld|%ld|%s|%s|\n",
191 (*FreeMe)->nIncreases,
195 (*FreeMe)->bt_lastinc);
196 n = write(hFreeDbglog, buf, n);
202 n = snprintf(buf, 128, "%c_|0|%ld%ld|\n",
206 n = write(hFreeDbglog, buf, n);
210 void dbg_IncreaseBuf(StrBuf *IncMe)
213 #ifdef HAVE_BACKTRACE
214 StrBufBacktrace(Buf, 1);
218 void dbg_Init(StrBuf *Buf)
222 Buf->bt_lastinc[0] = '\0';
223 #ifdef HAVE_BACKTRACE
224 StrBufBacktrace(Buf, 0);
230 #define dbg_FreeStrBuf(a, b)
231 #define dbg_IncreaseBuf(a)
238 * @brief swaps the contents of two StrBufs
239 * this is to be used to have cheap switched between a work-buffer and a target buffer
241 * @param B second one
243 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
247 memcpy(&C, A, sizeof(*A));
248 memcpy(A, B, sizeof(*B));
249 memcpy(B, &C, sizeof(C));
254 * @ingroup StrBuf_Cast
255 * @brief Cast operator to Plain String
256 * @note if the buffer is altered by StrBuf operations, this pointer may become
257 * invalid. So don't lean on it after altering the buffer!
258 * Since this operation is considered cheap, rather call it often than risking
259 * your pointer to become invalid!
260 * @param Str the string we want to get the c-string representation for
261 * @returns the Pointer to the Content. Don't mess with it!
263 inline const char *ChrPtr(const StrBuf *Str)
271 * @ingroup StrBuf_Cast
272 * @brief since we know strlen()'s result, provide it here.
273 * @param Str the string to return the length to
274 * @returns contentlength of the buffer
276 inline int StrLength(const StrBuf *Str)
278 return (Str != NULL) ? Str->BufUsed : 0;
282 * @ingroup StrBuf_DeConstructors
283 * @brief local utility function to resize the buffer
284 * @param Buf the buffer whichs storage we should increase
285 * @param KeepOriginal should we copy the original buffer or just start over with a new one
286 * @param DestSize what should fit in after?
288 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
291 size_t NewSize = Buf->BufSize * 2;
297 while ((NewSize <= DestSize) && (NewSize != 0))
303 NewBuf= (char*) malloc(NewSize);
307 if (KeepOriginal && (Buf->BufUsed > 0))
309 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
318 Buf->BufSize = NewSize;
320 dbg_IncreaseBuf(Buf);
326 * @ingroup StrBuf_DeConstructors
327 * @brief shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
328 * @param Buf Buffer to shrink (has to be empty)
329 * @param ThreshHold if the buffer is bigger then this, its readjusted
330 * @param NewSize if we Shrink it, how big are we going to be afterwards?
332 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
335 (Buf->BufUsed == 0) &&
336 (Buf->BufSize < ThreshHold)) {
338 Buf->buf = (char*) malloc(NewSize);
340 Buf->BufSize = NewSize;
345 * @ingroup StrBuf_DeConstructors
346 * @brief shrink long term buffers to their real size so they don't waste memory
347 * @param Buf buffer to shrink
348 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
349 * @returns physical size of the buffer
351 long StrBufShrinkToFit(StrBuf *Buf, int Force)
356 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
358 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
359 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
360 Buf->BufSize = Buf->BufUsed + 1;
368 * @ingroup StrBuf_DeConstructors
369 * @brief Allocate a new buffer with default buffer size
370 * @returns the new stringbuffer
372 StrBuf* NewStrBuf(void)
376 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
377 NewBuf->buf = (char*) malloc(BaseStrBufSize);
378 NewBuf->buf[0] = '\0';
379 NewBuf->BufSize = BaseStrBufSize;
381 NewBuf->ConstBuf = 0;
389 * @ingroup StrBuf_DeConstructors
390 * @brief Copy Constructor; returns a duplicate of CopyMe
391 * @param CopyMe Buffer to faxmilate
392 * @returns the new stringbuffer
394 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
401 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
402 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
403 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
404 NewBuf->BufUsed = CopyMe->BufUsed;
405 NewBuf->BufSize = CopyMe->BufSize;
406 NewBuf->ConstBuf = 0;
414 * @ingroup StrBuf_DeConstructors
415 * @brief Copy Constructor; CreateRelpaceMe will contain CopyFlushMe afterwards.
416 * @param NoMe if non-NULL, we will use that buffer as value; KeepOriginal will abused as len.
417 * @param CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
418 * @param CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe
419 * @param KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
420 * @returns the new stringbuffer
422 void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, const char *NoMe, int KeepOriginal)
426 if (CreateRelpaceMe == NULL)
431 if (*CreateRelpaceMe != NULL)
432 StrBufPlain(*CreateRelpaceMe, NoMe, KeepOriginal);
434 *CreateRelpaceMe = NewStrBufPlain(NoMe, KeepOriginal);
438 if (CopyFlushMe == NULL)
440 if (*CreateRelpaceMe != NULL)
441 FlushStrBuf(*CreateRelpaceMe);
443 *CreateRelpaceMe = NewStrBuf();
448 * Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
449 * else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
450 * be a big IO-Buffer...
452 if (KeepOriginal || (StrLength(CopyFlushMe) < 256))
454 if (*CreateRelpaceMe == NULL)
456 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
461 NewBuf = *CreateRelpaceMe;
464 StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
468 if (*CreateRelpaceMe == NULL)
470 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
474 NewBuf = *CreateRelpaceMe;
475 SwapBuffers (NewBuf, CopyFlushMe);
478 FlushStrBuf(CopyFlushMe);
483 * @ingroup StrBuf_DeConstructors
484 * @brief create a new Buffer using an existing c-string
485 * this function should also be used if you want to pre-suggest
486 * the buffer size to allocate in conjunction with ptr == NULL
487 * @param ptr the c-string to copy; may be NULL to create a blank instance
488 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
489 * @returns the new stringbuffer
491 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
494 size_t Siz = BaseStrBufSize;
497 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
499 CopySize = strlen((ptr != NULL)?ptr:"");
503 while ((Siz <= CopySize) && (Siz != 0))
511 NewBuf->buf = (char*) malloc(Siz);
512 if (NewBuf->buf == NULL)
517 NewBuf->BufSize = Siz;
519 memcpy(NewBuf->buf, ptr, CopySize);
520 NewBuf->buf[CopySize] = '\0';
521 NewBuf->BufUsed = CopySize;
524 NewBuf->buf[0] = '\0';
527 NewBuf->ConstBuf = 0;
535 * @ingroup StrBuf_DeConstructors
536 * @brief Set an existing buffer from a c-string
537 * @param Buf buffer to load
538 * @param ptr c-string to put into
539 * @param nChars set to -1 if we should work 0-terminated
540 * @returns the new length of the string
542 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
557 CopySize = strlen(ptr);
561 while ((Siz <= CopySize) && (Siz != 0))
569 if (Siz != Buf->BufSize)
570 IncreaseBuf(Buf, 0, Siz);
571 memcpy(Buf->buf, ptr, CopySize);
572 Buf->buf[CopySize] = '\0';
573 Buf->BufUsed = CopySize;
580 * @ingroup StrBuf_DeConstructors
581 * @brief use strbuf as wrapper for a string constant for easy handling
582 * @param StringConstant a string to wrap
583 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
585 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
589 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
590 NewBuf->buf = (char*) StringConstant;
591 NewBuf->BufSize = SizeOfStrConstant;
592 NewBuf->BufUsed = SizeOfStrConstant;
593 NewBuf->ConstBuf = 1;
602 * @ingroup StrBuf_DeConstructors
603 * @brief flush the content of a Buf; keep its struct
604 * @param buf Buffer to flush
606 int FlushStrBuf(StrBuf *buf)
618 * @ingroup StrBuf_DeConstructors
619 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
620 * @param buf Buffer to wipe
622 int FLUSHStrBuf(StrBuf *buf)
628 if (buf->BufUsed > 0) {
629 memset(buf->buf, 0, buf->BufUsed);
636 int hFreeDbglog = -1;
639 * @ingroup StrBuf_DeConstructors
640 * @brief Release a Buffer
641 * Its a double pointer, so it can NULL your pointer
642 * so fancy SIG11 appear instead of random results
643 * @param FreeMe Pointer Pointer to the buffer to free
645 void FreeStrBuf (StrBuf **FreeMe)
650 dbg_FreeStrBuf(FreeMe, 'F');
652 if (!(*FreeMe)->ConstBuf)
653 free((*FreeMe)->buf);
659 * @ingroup StrBuf_DeConstructors
660 * @brief flatten a Buffer to the Char * we return
661 * Its a double pointer, so it can NULL your pointer
662 * so fancy SIG11 appear instead of random results
663 * The Callee then owns the buffer and is responsible for freeing it.
664 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
665 * @returns the pointer of the buffer; Callee owns the memory thereafter.
667 char *SmashStrBuf (StrBuf **SmashMe)
671 if ((SmashMe == NULL) || (*SmashMe == NULL))
674 dbg_FreeStrBuf(SmashMe, 'S');
676 Ret = (*SmashMe)->buf;
683 * @ingroup StrBuf_DeConstructors
684 * @brief Release the buffer
685 * If you want put your StrBuf into a Hash, use this as Destructor.
686 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
688 void HFreeStrBuf (void *VFreeMe)
690 StrBuf *FreeMe = (StrBuf*)VFreeMe;
694 dbg_FreeStrBuf(SmashMe, 'H');
696 if (!FreeMe->ConstBuf)
702 /*******************************************************************************
703 * Simple string transformations *
704 *******************************************************************************/
708 * @brief Wrapper around atol
710 long StrTol(const StrBuf *Buf)
715 return atol(Buf->buf);
722 * @brief Wrapper around atoi
724 int StrToi(const StrBuf *Buf)
728 if (Buf->BufUsed > 0)
729 return atoi(Buf->buf);
736 * @brief Checks to see if the string is a pure number
737 * @param Buf The buffer to inspect
738 * @returns 1 if its a pure number, 0, if not.
740 int StrBufIsNumber(const StrBuf *Buf) {
742 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
745 strtoll(Buf->buf, &pEnd, 10);
746 if (pEnd == Buf->buf)
748 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
750 if (Buf->buf == pEnd)
756 * @ingroup StrBuf_Filler
757 * @brief modifies a Single char of the Buf
758 * You can point to it via char* or a zero-based integer
759 * @param Buf The buffer to manipulate
760 * @param ptr char* to zero; use NULL if unused
761 * @param nThChar zero based pointer into the string; use -1 if unused
762 * @param PeekValue The Character to place into the position
764 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
769 nThChar = ptr - Buf->buf;
770 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
772 Buf->buf[nThChar] = PeekValue;
777 * @ingroup StrBuf_Filler
778 * @brief modifies a range of chars of the Buf
779 * You can point to it via char* or a zero-based integer
780 * @param Buf The buffer to manipulate
781 * @param ptr char* to zero; use NULL if unused
782 * @param nThChar zero based pointer into the string; use -1 if unused
783 * @param nChars how many chars are to be flushed?
784 * @param PookValue The Character to place into that area
786 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
791 nThChar = ptr - Buf->buf;
792 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
794 if (nThChar + nChars > Buf->BufUsed)
795 nChars = Buf->BufUsed - nThChar;
797 memset(Buf->buf + nThChar, PookValue, nChars);
798 /* just to be shure... */
799 Buf->buf[Buf->BufUsed] = 0;
804 * @ingroup StrBuf_Filler
805 * @brief Append a StringBuffer to the buffer
806 * @param Buf Buffer to modify
807 * @param AppendBuf Buffer to copy at the end of our buffer
808 * @param Offset Should we start copying from an offset?
810 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
812 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
815 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
818 AppendBuf->BufUsed + Buf->BufUsed);
820 memcpy(Buf->buf + Buf->BufUsed,
821 AppendBuf->buf + Offset,
822 AppendBuf->BufUsed - Offset);
823 Buf->BufUsed += AppendBuf->BufUsed - Offset;
824 Buf->buf[Buf->BufUsed] = '\0';
829 * @ingroup StrBuf_Filler
830 * @brief Append a C-String to the buffer
831 * @param Buf Buffer to modify
832 * @param AppendBuf Buffer to copy at the end of our buffer
833 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
834 * @param Offset Should we start copying from an offset?
836 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
839 long BufSizeRequired;
841 if ((AppendBuf == NULL) || (Buf == NULL))
845 aps = strlen(AppendBuf + Offset);
847 aps = AppendSize - Offset;
849 BufSizeRequired = Buf->BufUsed + aps + 1;
850 if (Buf->BufSize <= BufSizeRequired)
851 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
853 memcpy(Buf->buf + Buf->BufUsed,
857 Buf->buf[Buf->BufUsed] = '\0';
861 * @ingroup StrBuf_Filler
862 * @brief sprintf like function appending the formated string to the buffer
863 * vsnprintf version to wrap into own calls
864 * @param Buf Buffer to extend by format and Params
865 * @param format printf alike format to add
866 * @param ap va_list containing the items for format
868 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
876 if ((Buf == NULL) || (format == NULL))
879 BufSize = Buf->BufSize;
880 nWritten = Buf->BufSize + 1;
881 Offset = Buf->BufUsed;
882 newused = Offset + nWritten;
884 while (newused >= BufSize) {
886 nWritten = vsnprintf(Buf->buf + Offset,
887 Buf->BufSize - Offset,
890 newused = Offset + nWritten;
891 if (newused >= Buf->BufSize) {
892 if (IncreaseBuf(Buf, 1, newused) == -1)
893 return; /* TODO: error handling? */
894 newused = Buf->BufSize + 1;
897 Buf->BufUsed = Offset + nWritten;
898 BufSize = Buf->BufSize;
905 * @ingroup StrBuf_Filler
906 * @brief sprintf like function appending the formated string to the buffer
907 * @param Buf Buffer to extend by format and Params
908 * @param format printf alike format to add
910 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
918 if ((Buf == NULL) || (format == NULL))
921 BufSize = Buf->BufSize;
922 nWritten = Buf->BufSize + 1;
923 Offset = Buf->BufUsed;
924 newused = Offset + nWritten;
926 while (newused >= BufSize) {
927 va_start(arg_ptr, format);
928 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
929 Buf->BufSize - Buf->BufUsed,
932 newused = Buf->BufUsed + nWritten;
933 if (newused >= Buf->BufSize) {
934 if (IncreaseBuf(Buf, 1, newused) == -1)
935 return; /* TODO: error handling? */
936 newused = Buf->BufSize + 1;
939 Buf->BufUsed += nWritten;
940 BufSize = Buf->BufSize;
947 * @ingroup StrBuf_Filler
948 * @brief sprintf like function putting the formated string into the buffer
949 * @param Buf Buffer to extend by format and Parameters
950 * @param format printf alike format to add
952 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
957 if ((Buf == NULL) || (format == NULL))
960 nWritten = Buf->BufSize + 1;
961 while (nWritten >= Buf->BufSize) {
962 va_start(arg_ptr, format);
963 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
965 if (nWritten >= Buf->BufSize) {
966 if (IncreaseBuf(Buf, 0, 0) == -1)
967 return; /* TODO: error handling? */
968 nWritten = Buf->BufSize + 1;
971 Buf->BufUsed = nWritten ;
976 * @ingroup StrBuf_Filler
977 * @brief Callback for cURL to append the webserver reply to a buffer
978 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
979 * @param size pre-defined by the cURL API; see man 3 curl for mre info
980 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
981 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
983 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
992 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
999 * @brief extracts a substring from Source into dest
1000 * @param dest buffer to place substring into
1001 * @param Source string to copy substring from
1002 * @param Offset chars to skip from start
1003 * @param nChars number of chars to copy
1004 * @returns the number of chars copied; may be different from nChars due to the size of Source
1006 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
1008 size_t NCharsRemain;
1009 if (Offset > Source->BufUsed)
1015 if (Offset + nChars < Source->BufUsed)
1017 if (nChars >= dest->BufSize)
1018 IncreaseBuf(dest, 0, nChars + 1);
1019 memcpy(dest->buf, Source->buf + Offset, nChars);
1020 dest->BufUsed = nChars;
1021 dest->buf[dest->BufUsed] = '\0';
1024 NCharsRemain = Source->BufUsed - Offset;
1025 if (NCharsRemain >= dest->BufSize)
1026 IncreaseBuf(dest, 0, NCharsRemain + 1);
1027 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
1028 dest->BufUsed = NCharsRemain;
1029 dest->buf[dest->BufUsed] = '\0';
1030 return NCharsRemain;
1035 * @brief Cut nChars from the start of the string
1036 * @param Buf Buffer to modify
1037 * @param nChars how many chars should be skipped?
1039 void StrBufCutLeft(StrBuf *Buf, int nChars)
1041 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1042 if (nChars >= Buf->BufUsed) {
1046 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1047 Buf->BufUsed -= nChars;
1048 Buf->buf[Buf->BufUsed] = '\0';
1053 * @brief Cut the trailing n Chars from the string
1054 * @param Buf Buffer to modify
1055 * @param nChars how many chars should be trunkated?
1057 void StrBufCutRight(StrBuf *Buf, int nChars)
1059 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1060 if (nChars >= Buf->BufUsed) {
1064 Buf->BufUsed -= nChars;
1065 Buf->buf[Buf->BufUsed] = '\0';
1070 * @brief Cut the string after n Chars
1071 * @param Buf Buffer to modify
1072 * @param AfternChars after how many chars should we trunkate the string?
1073 * @param At if non-null and points inside of our string, cut it there.
1075 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1077 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1079 AfternChars = At - Buf->buf;
1082 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1084 Buf->BufUsed = AfternChars;
1085 Buf->buf[Buf->BufUsed] = '\0';
1091 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1092 * @param Buf the string to modify
1094 void StrBufTrim(StrBuf *Buf)
1097 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1099 while ((Buf->BufUsed > 0) &&
1100 isspace(Buf->buf[Buf->BufUsed - 1]))
1104 Buf->buf[Buf->BufUsed] = '\0';
1106 if (Buf->BufUsed == 0) return;
1108 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1111 if (delta > 0) StrBufCutLeft(Buf, delta);
1115 * @brief changes all spaces in the string (tab, linefeed...) to Blank (0x20)
1116 * @param Buf the string to modify
1118 void StrBufSpaceToBlank(StrBuf *Buf)
1122 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1125 pche = pch + Buf->BufUsed;
1134 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
1142 pLeft = pBuff = Buf->buf;
1143 while (pBuff != NULL) {
1145 pBuff = strchr(pBuff, leftboundary);
1154 pRight = strchr(pBuff, rightboundary);
1156 StrBufCutAt(Buf, 0, pRight);
1158 StrBufCutLeft(Buf, pLeft - Buf->buf);
1163 * @ingroup StrBuf_Filler
1164 * @brief uppercase the contents of a buffer
1165 * @param Buf the buffer to translate
1167 void StrBufUpCase(StrBuf *Buf)
1171 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1174 pche = pch + Buf->BufUsed;
1175 while (pch < pche) {
1176 *pch = toupper(*pch);
1183 * @ingroup StrBuf_Filler
1184 * @brief lowercase the contents of a buffer
1185 * @param Buf the buffer to translate
1187 void StrBufLowerCase(StrBuf *Buf)
1191 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1194 pche = pch + Buf->BufUsed;
1195 while (pch < pche) {
1196 *pch = tolower(*pch);
1202 /*******************************************************************************
1203 * a tokenizer that kills, maims, and destroys *
1204 *******************************************************************************/
1207 * @ingroup StrBuf_Tokenizer
1208 * @brief Replace a token at a given place with a given length by another token with given length
1209 * @param Buf String where to work on
1210 * @param where where inside of the Buf is the search-token
1211 * @param HowLong How long is the token to be replaced
1212 * @param Repl Token to insert at 'where'
1213 * @param ReplLen Length of repl
1214 * @returns -1 if fail else length of resulting Buf
1216 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
1217 const char *Repl, long ReplLen)
1220 if ((Buf == NULL) ||
1221 (where > Buf->BufUsed) ||
1222 (where + HowLong > Buf->BufUsed))
1225 if (where + ReplLen - HowLong > Buf->BufSize)
1226 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
1229 memmove(Buf->buf + where + ReplLen,
1230 Buf->buf + where + HowLong,
1231 Buf->BufUsed - where - HowLong);
1233 memcpy(Buf->buf + where,
1236 Buf->BufUsed += ReplLen - HowLong;
1238 return Buf->BufUsed;
1242 * @ingroup StrBuf_Tokenizer
1243 * @brief Counts the numbmer of tokens in a buffer
1244 * @param source String to count tokens in
1245 * @param tok Tokenizer char to count
1246 * @returns numbers of tokenizer chars found
1248 int StrBufNum_tokens(const StrBuf *source, char tok)
1252 if ((source == NULL) || (source->BufUsed == 0))
1254 if ((source->BufUsed == 1) && (*source->buf == tok))
1258 pche = pch + source->BufUsed;
1269 * @ingroup StrBuf_Tokenizer
1270 * @brief a string tokenizer
1271 * @param Source StringBuffer to read into
1272 * @param parmnum n'th Parameter to remove
1273 * @param separator tokenizer character
1274 * @returns -1 if not found, else length of token.
1276 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1279 char *d, *s, *end; /* dest, source */
1282 /* Find desired @parameter */
1283 end = Source->buf + Source->BufUsed;
1285 while ((d <= end) &&
1288 /* End of string, bail! */
1293 if (*d == separator) {
1298 if ((d == NULL) || (d >= end))
1299 return 0; /* @Parameter not found */
1301 /* Find next @parameter */
1303 while ((s <= end) &&
1304 (*s && *s != separator))
1308 if (*s == separator)
1312 /* Hack and slash */
1317 memmove(d, s, Source->BufUsed - (s - Source->buf));
1318 Source->BufUsed += ReducedBy;
1319 Source->buf[Source->BufUsed] = '\0';
1321 else if (d == Source->buf) {
1323 Source->BufUsed = 0;
1327 Source->BufUsed += ReducedBy;
1340 * @ingroup StrBuf_Tokenizer
1341 * @brief a string tokenizer
1342 * @param dest Destination StringBuffer
1343 * @param Source StringBuffer to read into
1344 * @param parmnum n'th Parameter to extract
1345 * @param separator tokenizer character
1346 * @returns -1 if not found, else length of token.
1348 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1350 const char *s, *e; //* source * /
1351 int len = 0; //* running total length of extracted string * /
1352 int current_token = 0; //* token currently being processed * /
1355 dest->buf[0] = '\0';
1361 if ((Source == NULL) || (Source->BufUsed ==0)) {
1365 e = s + Source->BufUsed;
1368 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1370 while ((s < e) && !IsEmptyStr(s)) {
1371 if (*s == separator) {
1374 if (len >= dest->BufSize) {
1375 dest->BufUsed = len;
1376 if (IncreaseBuf(dest, 1, -1) < 0) {
1381 if ( (current_token == parmnum) &&
1382 (*s != separator)) {
1383 dest->buf[len] = *s;
1386 else if (current_token > parmnum) {
1392 dest->buf[len] = '\0';
1393 dest->BufUsed = len;
1395 if (current_token < parmnum) {
1396 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1399 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1408 * @ingroup StrBuf_Tokenizer
1409 * @brief a string tokenizer to fetch an integer
1410 * @param Source String containing tokens
1411 * @param parmnum n'th Parameter to extract
1412 * @param separator tokenizer character
1413 * @returns 0 if not found, else integer representation of the token
1415 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1425 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1432 * @ingroup StrBuf_Tokenizer
1433 * @brief a string tokenizer to fetch a long integer
1434 * @param Source String containing tokens
1435 * @param parmnum n'th Parameter to extract
1436 * @param separator tokenizer character
1437 * @returns 0 if not found, else long integer representation of the token
1439 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1449 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1457 * @ingroup StrBuf_Tokenizer
1458 * @brief a string tokenizer to fetch an unsigned long
1459 * @param Source String containing tokens
1460 * @param parmnum n'th Parameter to extract
1461 * @param separator tokenizer character
1462 * @returns 0 if not found, else unsigned long representation of the token
1464 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1475 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1479 return (unsigned long) atol(pnum);
1488 * @ingroup StrBuf_NextTokenizer
1489 * @brief a string tokenizer; Bounds checker
1490 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1491 * @param Source our tokenbuffer
1492 * @param pStart the token iterator pointer to inspect
1493 * @returns whether the revolving pointer is inside of the search range
1495 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1497 if ((Source == NULL) ||
1498 (*pStart == StrBufNOTNULL) ||
1499 (Source->BufUsed == 0))
1503 if (*pStart == NULL)
1507 else if (*pStart > Source->buf + Source->BufUsed)
1511 else if (*pStart <= Source->buf)
1520 * @ingroup StrBuf_NextTokenizer
1521 * @brief a string tokenizer
1522 * @param dest Destination StringBuffer
1523 * @param Source StringBuffer to read into
1524 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1525 * @param separator tokenizer
1526 * @returns -1 if not found, else length of token.
1528 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1530 const char *s; /* source */
1531 const char *EndBuffer; /* end stop of source buffer */
1532 int current_token = 0; /* token currently being processed */
1533 int len = 0; /* running total length of extracted string */
1535 if ((Source == NULL) ||
1536 (Source->BufUsed == 0) )
1538 *pStart = StrBufNOTNULL;
1542 EndBuffer = Source->buf + Source->BufUsed;
1546 dest->buf[0] = '\0';
1551 *pStart = EndBuffer + 1;
1555 if (*pStart == NULL)
1557 *pStart = Source->buf; /* we're starting to examine this buffer. */
1559 else if ((*pStart < Source->buf) ||
1560 (*pStart > EndBuffer ) )
1562 return -1; /* no more tokens to find. */
1566 /* start to find the next token */
1567 while ((s <= EndBuffer) &&
1568 (current_token == 0) )
1570 if (*s == separator)
1572 /* we found the next token */
1576 if (len >= dest->BufSize)
1578 /* our Dest-buffer isn't big enough, increase it. */
1579 dest->BufUsed = len;
1581 if (IncreaseBuf(dest, 1, -1) < 0) {
1582 /* WHUT? no more mem? bail out. */
1589 if ( (current_token == 0 ) && /* are we in our target token? */
1590 (!IsEmptyStr(s) ) &&
1591 (separator != *s) ) /* don't copy the token itself */
1593 dest->buf[len] = *s; /* Copy the payload */
1594 ++len; /* remember the bigger size. */
1600 /* did we reach the end? */
1601 if ((s > EndBuffer)) {
1602 EndBuffer = StrBufNOTNULL;
1603 *pStart = EndBuffer;
1606 *pStart = s; /* remember the position for the next run */
1609 /* sanitize our extracted token */
1610 dest->buf[len] = '\0';
1611 dest->BufUsed = len;
1618 * @ingroup StrBuf_NextTokenizer
1619 * @brief a string tokenizer
1620 * @param Source StringBuffer to read from
1621 * @param pStart pointer to the end of the last token. Feed with NULL.
1622 * @param separator tokenizer character
1623 * @param nTokens number of tokens to fastforward over
1624 * @returns -1 if not found, else length of token.
1626 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1628 const char *s, *EndBuffer; //* source * /
1629 int len = 0; //* running total length of extracted string * /
1630 int current_token = 0; //* token currently being processed * /
1632 if ((Source == NULL) ||
1633 (Source->BufUsed ==0)) {
1637 return Source->BufUsed;
1639 if (*pStart == NULL)
1640 *pStart = Source->buf;
1642 EndBuffer = Source->buf + Source->BufUsed;
1644 if ((*pStart < Source->buf) ||
1645 (*pStart > EndBuffer)) {
1653 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1655 while ((s < EndBuffer) && !IsEmptyStr(s)) {
1656 if (*s == separator) {
1659 if (current_token >= nTokens) {
1671 * @ingroup StrBuf_NextTokenizer
1672 * @brief a string tokenizer to fetch an integer
1673 * @param Source StringBuffer to read from
1674 * @param pStart Cursor on the tokenstring
1675 * @param separator tokenizer character
1676 * @returns 0 if not found, else integer representation of the token
1678 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1688 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1695 * @ingroup StrBuf_NextTokenizer
1696 * @brief a string tokenizer to fetch a long integer
1697 * @param Source StringBuffer to read from
1698 * @param pStart Cursor on the tokenstring
1699 * @param separator tokenizer character
1700 * @returns 0 if not found, else long integer representation of the token
1702 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1712 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1720 * @ingroup StrBuf_NextTokenizer
1721 * @brief a string tokenizer to fetch an unsigned long
1722 * @param Source StringBuffer to read from
1723 * @param pStart Cursor on the tokenstring
1724 * @param separator tokenizer character
1725 * @returns 0 if not found, else unsigned long representation of the token
1727 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1738 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1742 return (unsigned long) atol(pnum);
1752 /*******************************************************************************
1753 * Escape Appending *
1754 *******************************************************************************/
1757 * @ingroup StrBuf_DeEnCoder
1758 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1759 * @param OutBuf the output buffer
1760 * @param In Buffer to encode
1761 * @param PlainIn way in from plain old c strings
1763 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1765 const char *pch, *pche;
1769 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1771 if (PlainIn != NULL) {
1772 len = strlen(PlainIn);
1778 pche = pch + In->BufUsed;
1785 pt = OutBuf->buf + OutBuf->BufUsed;
1786 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1788 while (pch < pche) {
1790 IncreaseBuf(OutBuf, 1, -1);
1791 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1792 pt = OutBuf->buf + OutBuf->BufUsed;
1795 if((*pch >= 'a' && *pch <= 'z') ||
1796 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1797 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1798 (*pch == '!') || (*pch == '_') ||
1799 (*pch == ',') || (*pch == '.'))
1806 *(pt + 1) = HexList[(unsigned char)*pch][0];
1807 *(pt + 2) = HexList[(unsigned char)*pch][1];
1809 OutBuf->BufUsed += 3;
1817 * @ingroup StrBuf_DeEnCoder
1818 * @brief append a string in hex encoding to the buffer
1819 * @param OutBuf the output buffer
1820 * @param In Buffer to encode
1821 * @param PlainIn way in from plain old c strings
1823 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1825 const char *pch, *pche;
1829 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1831 if (PlainIn != NULL) {
1832 len = strlen(PlainIn);
1838 pche = pch + In->BufUsed;
1845 pt = OutBuf->buf + OutBuf->BufUsed;
1846 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1848 while (pch < pche) {
1850 IncreaseBuf(OutBuf, 1, -1);
1851 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1852 pt = OutBuf->buf + OutBuf->BufUsed;
1855 *pt = HexList[(unsigned char)*pch][0];
1857 *pt = HexList[(unsigned char)*pch][1];
1858 pt ++; pch ++; OutBuf->BufUsed += 2;
1864 * @ingroup StrBuf_DeEnCoder
1865 * @brief Append a string, escaping characters which have meaning in HTML.
1867 * @param Target target buffer
1868 * @param Source source buffer; set to NULL if you just have a C-String
1869 * @param PlainIn Plain-C string to append; set to NULL if unused
1870 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1871 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1872 * if set to 2, linebreaks are replaced by <br/>
1874 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1876 const char *aptr, *eiptr;
1880 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1883 if (PlainIn != NULL) {
1885 len = strlen(PlainIn);
1890 eiptr = aptr + Source->BufUsed;
1891 len = Source->BufUsed;
1897 bptr = Target->buf + Target->BufUsed;
1898 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1900 while (aptr < eiptr){
1902 IncreaseBuf(Target, 1, -1);
1903 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1904 bptr = Target->buf + Target->BufUsed;
1907 memcpy(bptr, "<", 4);
1909 Target->BufUsed += 4;
1911 else if (*aptr == '>') {
1912 memcpy(bptr, ">", 4);
1914 Target->BufUsed += 4;
1916 else if (*aptr == '&') {
1917 memcpy(bptr, "&", 5);
1919 Target->BufUsed += 5;
1921 else if (*aptr == '"') {
1922 memcpy(bptr, """, 6);
1924 Target->BufUsed += 6;
1926 else if (*aptr == '\'') {
1927 memcpy(bptr, "'", 5);
1929 Target->BufUsed += 5;
1931 else if (*aptr == LB) {
1936 else if (*aptr == RB) {
1941 else if (*aptr == QU) {
1946 else if ((*aptr == 32) && (nbsp == 1)) {
1947 memcpy(bptr, " ", 6);
1949 Target->BufUsed += 6;
1951 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1952 *bptr='\0'; /* nothing */
1954 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1955 memcpy(bptr, "<br/>", 11);
1957 Target->BufUsed += 11;
1961 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1962 *bptr='\0'; /* nothing */
1972 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1974 return Target->BufUsed;
1978 * @ingroup StrBuf_DeEnCoder
1979 * @brief Append a string, escaping characters which have meaning in HTML.
1980 * Converts linebreaks into blanks; escapes single quotes
1981 * @param Target target buffer
1982 * @param Source source buffer; set to NULL if you just have a C-String
1983 * @param PlainIn Plain-C string to append; set to NULL if unused
1985 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1987 const char *aptr, *eiptr;
1991 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1994 if (PlainIn != NULL) {
1996 len = strlen(PlainIn);
2001 eiptr = aptr + Source->BufUsed;
2002 len = Source->BufUsed;
2008 eptr = Target->buf + Target->BufSize - 8;
2009 tptr = Target->buf + Target->BufUsed;
2011 while (aptr < eiptr){
2013 IncreaseBuf(Target, 1, -1);
2014 eptr = Target->buf + Target->BufSize - 8;
2015 tptr = Target->buf + Target->BufUsed;
2018 if (*aptr == '\n') {
2022 else if (*aptr == '\r') {
2026 else if (*aptr == '\'') {
2032 Target->BufUsed += 5;
2045 * @ingroup StrBuf_DeEnCoder
2046 * @brief Append a string, escaping characters which have meaning in ICAL.
2048 * @param Target target buffer
2049 * @param Source source buffer; set to NULL if you just have a C-String
2050 * @param PlainIn Plain-C string to append; set to NULL if unused
2052 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2054 const char *aptr, *eiptr;
2058 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2061 if (PlainIn != NULL) {
2063 len = strlen(PlainIn);
2068 eiptr = aptr + Source->BufUsed;
2069 len = Source->BufUsed;
2075 eptr = Target->buf + Target->BufSize - 8;
2076 tptr = Target->buf + Target->BufUsed;
2078 while (aptr < eiptr){
2079 if(tptr + 3 >= eptr) {
2080 IncreaseBuf(Target, 1, -1);
2081 eptr = Target->buf + Target->BufSize - 8;
2082 tptr = Target->buf + Target->BufUsed;
2085 if (*aptr == '\n') {
2092 else if (*aptr == '\r') {
2099 else if (*aptr == ',') {
2115 * @ingroup StrBuf_DeEnCoder
2116 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
2118 * @param Target target buffer
2119 * @param Source source buffer; set to NULL if you just have a C-String
2120 * @param PlainIn Plain-C string to append; set to NULL if unused
2121 * @returns size of result or -1
2123 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
2125 const char *aptr, *eiptr;
2129 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2132 if (PlainIn != NULL) {
2134 len = strlen(PlainIn);
2139 eiptr = aptr + Source->BufUsed;
2140 len = Source->BufUsed;
2146 bptr = Target->buf + Target->BufUsed;
2147 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
2149 while (aptr < eiptr){
2151 IncreaseBuf(Target, 1, -1);
2152 eptr = Target->buf + Target->BufSize - 3;
2153 bptr = Target->buf + Target->BufUsed;
2160 Target->BufUsed += 2;
2161 } else if (*aptr == '\\') {
2166 Target->BufUsed += 2;
2176 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2178 return Target->BufUsed;
2182 * @ingroup StrBuf_DeEnCoder
2183 * @brief Append a string, escaping characters which have meaning in HTML + json.
2185 * @param Target target buffer
2186 * @param Source source buffer; set to NULL if you just have a C-String
2187 * @param PlainIn Plain-C string to append; set to NULL if unused
2188 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
2189 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
2190 * if set to 2, linebreaks are replaced by <br/>
2192 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
2194 const char *aptr, *eiptr;
2197 int IsUtf8Sequence = 0;
2199 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2202 if (PlainIn != NULL) {
2204 len = strlen(PlainIn);
2209 eiptr = aptr + Source->BufUsed;
2210 len = Source->BufUsed;
2216 bptr = Target->buf + Target->BufUsed;
2217 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2219 while (aptr < eiptr){
2221 IncreaseBuf(Target, 1, -1);
2222 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2223 bptr = Target->buf + Target->BufUsed;
2226 memcpy(bptr, "<", 4);
2228 Target->BufUsed += 4;
2230 else if (*aptr == '>') {
2231 memcpy(bptr, ">", 4);
2233 Target->BufUsed += 4;
2235 else if (*aptr == '&') {
2236 memcpy(bptr, "&", 5);
2238 Target->BufUsed += 5;
2240 else if (*aptr == LB) {
2245 else if (*aptr == RB) {
2250 else if ((*aptr == 32) && (nbsp == 1)) {
2251 memcpy(bptr, " ", 6);
2253 Target->BufUsed += 6;
2255 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
2256 *bptr='\0'; /* nothing */
2258 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
2259 memcpy(bptr, "<br/>", 11);
2261 Target->BufUsed += 11;
2264 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
2265 *bptr='\0'; /* nothing */
2268 else if ((*aptr == '"') || (*aptr == QU)) {
2273 Target->BufUsed += 2;
2274 } else if (*aptr == '\\') {
2279 Target->BufUsed += 2;
2282 if (((unsigned char)*aptr) >= 0x20)
2284 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2288 if (IsUtf8Sequence > 1) while (IsUtf8Sequence > 0){
2289 if(bptr + IsUtf8Sequence >= eptr) {
2290 IncreaseBuf(Target, 1, -1);
2291 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
2292 bptr = Target->buf + Target->BufUsed - 1;
2306 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2308 return Target->BufUsed;
2312 * @ingroup StrBuf_DeEnCoder
2313 * @brief unhide special chars hidden to the HTML escaper
2314 * @param target buffer to put the unescaped string in
2315 * @param source buffer to unescape
2317 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2323 FlushStrBuf(target);
2325 if (source == NULL ||target == NULL)
2330 len = source->BufUsed;
2331 for (a = 0; a < len; ++a) {
2332 if (target->BufUsed >= target->BufSize)
2333 IncreaseBuf(target, 1, -1);
2335 if (source->buf[a] == '=') {
2336 hex[0] = source->buf[a + 1];
2337 hex[1] = source->buf[a + 2];
2340 sscanf(hex, "%02x", &b);
2341 target->buf[target->BufUsed] = b;
2342 target->buf[++target->BufUsed] = 0;
2346 target->buf[target->BufUsed] = source->buf[a];
2347 target->buf[++target->BufUsed] = 0;
2354 * @ingroup StrBuf_DeEnCoder
2355 * @brief hide special chars from the HTML escapers and friends
2356 * @param target buffer to put the escaped string in
2357 * @param source buffer to escape
2359 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2364 FlushStrBuf(target);
2366 if (source == NULL ||target == NULL)
2371 len = source->BufUsed;
2372 for (i=0; i<len; ++i) {
2373 if (target->BufUsed + 4 >= target->BufSize)
2374 IncreaseBuf(target, 1, -1);
2375 if ( (isalnum(source->buf[i])) ||
2376 (source->buf[i]=='-') ||
2377 (source->buf[i]=='_') ) {
2378 target->buf[target->BufUsed++] = source->buf[i];
2381 sprintf(&target->buf[target->BufUsed],
2383 (0xFF &source->buf[i]));
2384 target->BufUsed += 3;
2387 target->buf[target->BufUsed + 1] = '\0';
2391 /*******************************************************************************
2392 * Quoted Printable de/encoding *
2393 *******************************************************************************/
2396 * @ingroup StrBuf_DeEnCoder
2397 * @brief decode a buffer from base 64 encoding; destroys original
2398 * @param Buf Buffor to transform
2400 int StrBufDecodeBase64(StrBuf *Buf)
2404 if (Buf == NULL) return -1;
2406 xferbuf = (char*) malloc(Buf->BufSize);
2408 siz = CtdlDecodeBase64(xferbuf,
2418 * @ingroup StrBuf_DeEnCoder
2419 * @brief decode a buffer from base 64 encoding; destroys original
2420 * @param Buf Buffor to transform
2422 int StrBufDecodeHex(StrBuf *Buf)
2425 char *pch, *pche, *pchi;
2427 if (Buf == NULL) return -1;
2429 pch = pchi = Buf->buf;
2430 pche = pch + Buf->BufUsed;
2432 while (pchi < pche){
2433 ch = decode_hex(pchi);
2440 Buf->BufUsed = pch - Buf->buf;
2441 return Buf->BufUsed;
2445 * @ingroup StrBuf_DeEnCoder
2446 * @brief replace all chars >0x20 && < 0x7F with Mute
2447 * @param Mute char to put over invalid chars
2448 * @param Buf Buffor to transform
2450 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2454 if (Buf == NULL) return -1;
2455 pch = (unsigned char *)Buf->buf;
2456 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2457 if ((*pch < 0x20) || (*pch > 0x7F))
2461 return Buf->BufUsed;
2466 * @ingroup StrBuf_DeEnCoder
2467 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2468 * @param Buf Buffer to translate
2469 * @param StripBlanks Reduce several blanks to one?
2471 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2480 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2481 Buf->buf[Buf->BufUsed - 1] = '\0';
2486 while (a < Buf->BufUsed) {
2487 if (Buf->buf[a] == '+')
2489 else if (Buf->buf[a] == '%') {
2490 /* don't let % chars through, rather truncate the input. */
2491 if (a + 2 > Buf->BufUsed) {
2496 hex[0] = Buf->buf[a + 1];
2497 hex[1] = Buf->buf[a + 2];
2500 sscanf(hex, "%02x", &b);
2501 Buf->buf[a] = (char) b;
2502 len = Buf->BufUsed - a - 2;
2504 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2516 * @ingroup StrBuf_DeEnCoder
2517 * @brief RFC2047-encode a header field if necessary.
2518 * If no non-ASCII characters are found, the string
2519 * will be copied verbatim without encoding.
2521 * @param target Target buffer.
2522 * @param source Source string to be encoded.
2523 * @returns encoded length; -1 if non success.
2525 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2527 const char headerStr[] = "=?UTF-8?Q?";
2528 int need_to_encode = 0;
2532 if ((source == NULL) ||
2536 while ((i < source->BufUsed) &&
2537 (!IsEmptyStr (&source->buf[i])) &&
2538 (need_to_encode == 0)) {
2539 if (((unsigned char) source->buf[i] < 32) ||
2540 ((unsigned char) source->buf[i] > 126)) {
2546 if (!need_to_encode) {
2547 if (*target == NULL) {
2548 *target = NewStrBufPlain(source->buf, source->BufUsed);
2551 FlushStrBuf(*target);
2552 StrBufAppendBuf(*target, source, 0);
2554 return (*target)->BufUsed;
2556 if (*target == NULL)
2557 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2558 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2559 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2560 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2561 (*target)->BufUsed = sizeof(headerStr) - 1;
2562 for (i=0; (i < source->BufUsed); ++i) {
2563 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2564 IncreaseBuf(*target, 1, 0);
2565 ch = (unsigned char) source->buf[i];
2572 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2573 (*target)->BufUsed += 3;
2576 (*target)->buf[(*target)->BufUsed] = ch;
2577 (*target)->BufUsed++;
2581 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2582 IncreaseBuf(*target, 1, 0);
2584 (*target)->buf[(*target)->BufUsed++] = '?';
2585 (*target)->buf[(*target)->BufUsed++] = '=';
2586 (*target)->buf[(*target)->BufUsed] = '\0';
2587 return (*target)->BufUsed;;
2592 static void AddRecipient(StrBuf *Target,
2594 StrBuf *EmailAddress,
2599 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
2600 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
2602 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
2603 StrBufRFC2047encode(&EncBuf, UserName);
2604 StrBufAppendBuf(Target, EncBuf, 0);
2605 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
2606 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
2608 if (StrLength(EmailAddress) > 0){
2609 StrBufAppendBufPlain(Target, HKEY("<"), 0);
2610 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
2611 StrBufAppendBufPlain(Target, HKEY(">"), 0);
2617 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
2618 * \param Recp Source list of email recipients
2619 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
2620 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
2621 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
2622 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
2624 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp,
2626 StrBuf *EmailAddress,
2630 const char *pch, *pche;
2631 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
2633 if ((Recp == NULL) || (StrLength(Recp) == 0))
2637 pche = pch + StrLength(Recp);
2639 if (!CheckEncode(pch, -1, pche))
2640 return NewStrBufDup(Recp);
2642 Target = NewStrBufPlain(NULL, StrLength(Recp));
2644 while ((pch != NULL) && (pch < pche))
2646 while (isspace(*pch)) pch++;
2647 UserStart = UserEnd = EmailStart = EmailEnd = NULL;
2649 if ((*pch == '"') || (*pch == '\'')) {
2650 UserStart = pch + 1;
2652 UserEnd = strchr(UserStart, *pch);
2653 if (UserEnd == NULL)
2654 break; ///TODO: Userfeedback??
2655 EmailStart = UserEnd + 1;
2656 while (isspace(*EmailStart))
2658 if (UserEnd == UserStart) {
2659 UserStart = UserEnd = NULL;
2662 if (*EmailStart == '<') {
2664 EmailEnd = strchr(EmailStart, '>');
2665 if (EmailEnd == NULL)
2666 EmailEnd = strchr(EmailStart, ',');
2670 EmailEnd = strchr(EmailStart, ',');
2672 if (EmailEnd == NULL)
2679 EmailEnd = strchr(UserStart, ',');
2680 if (EmailEnd == NULL) {
2681 EmailEnd = strchr(pch, '>');
2683 if (EmailEnd != NULL) {
2693 while ((EmailEnd > UserStart) && !gt &&
2694 ((*EmailEnd == ',') ||
2695 (*EmailEnd == '>') ||
2696 (isspace(*EmailEnd))))
2698 if (*EmailEnd == '>')
2703 if (EmailEnd == UserStart)
2707 EmailStart = strchr(UserStart, '<');
2708 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
2710 UserEnd = EmailStart;
2712 while ((UserEnd > UserStart) &&
2713 isspace (*(UserEnd - 1)))
2716 if (UserStart >= UserEnd)
2717 UserStart = UserEnd = NULL;
2718 At = strchr(EmailStart, '@');
2720 else { /* this is a local recipient... no domain, just a realname */
2721 EmailStart = UserStart;
2722 At = strchr(EmailStart, '@');
2728 EmailStart = UserStart;
2734 if ((UserStart != NULL) && (UserEnd != NULL))
2735 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2736 else if ((UserStart != NULL) && (UserEnd == NULL))
2737 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
2739 FlushStrBuf(UserName);
2741 if ((EmailStart != NULL) && (EmailEnd != NULL))
2742 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
2743 else if ((EmailStart != NULL) && (EmailEnd == NULL))
2744 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
2746 FlushStrBuf(EmailAddress);
2748 AddRecipient(Target, UserName, EmailAddress, EncBuf);
2753 if ((pch != NULL) && (*pch == ','))
2755 if (pch != NULL) while (isspace(*pch))
2764 * @brief replaces all occurances of 'search' by 'replace'
2765 * @param buf Buffer to modify
2766 * @param search character to search
2767 * @param replace character to replace search by
2769 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2774 for (i=0; i<buf->BufUsed; i++)
2775 if (buf->buf[i] == search)
2776 buf->buf[i] = replace;
2782 * @brief removes all \r s from the string, or replaces them with \n if its not a combination of both.
2783 * @param buf Buffer to modify
2785 void StrBufToUnixLF(StrBuf *buf)
2787 char *pche, *pchS, *pchT;
2791 pche = buf->buf + buf->BufUsed;
2792 pchS = pchT = buf->buf;
2798 if (*pchS != '\n') {
2807 buf->BufUsed = pchT - buf->buf;
2811 /*******************************************************************************
2812 * Iconv Wrapper; RFC822 de/encoding *
2813 *******************************************************************************/
2816 * @ingroup StrBuf_DeEnCoder
2817 * @brief Wrapper around iconv_open()
2818 * Our version adds aliases for non-standard Microsoft charsets
2819 * such as 'MS950', aliasing them to names like 'CP950'
2821 * @param tocode Target encoding
2822 * @param fromcode Source encoding
2823 * @param pic anonimized pointer to iconv struct
2825 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2828 iconv_t ic = (iconv_t)(-1) ;
2829 ic = iconv_open(tocode, fromcode);
2830 if (ic == (iconv_t)(-1) ) {
2831 char alias_fromcode[64];
2832 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2833 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2834 alias_fromcode[0] = 'C';
2835 alias_fromcode[1] = 'P';
2836 ic = iconv_open(tocode, alias_fromcode);
2839 *(iconv_t *)pic = ic;
2845 * @ingroup StrBuf_DeEnCoder
2846 * @brief find one chunk of a RFC822 encoded string
2847 * @param Buffer where to search
2848 * @param bptr where to start searching
2849 * @returns found position, NULL if none.
2851 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
2854 /* Find the next ?Q? */
2855 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2858 end = strchr(bptr + 2, '?');
2863 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2864 (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
2865 ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) &&
2866 (*(end + 2) == '?')) {
2867 /* skip on to the end of the cluster, the next ?= */
2868 end = strstr(end + 3, "?=");
2871 /* sort of half valid encoding, try to find an end. */
2872 end = strstr(bptr, "?=");
2879 * @ingroup StrBuf_DeEnCoder
2880 * @brief convert one buffer according to the preselected iconv pointer PIC
2881 * @param ConvertBuf buffer we need to translate
2882 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2883 * @param pic Pointer to the iconv-session Object
2885 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2891 char *ibuf; /**< Buffer of characters to be converted */
2892 char *obuf; /**< Buffer for converted characters */
2893 size_t ibuflen; /**< Length of input buffer */
2894 size_t obuflen; /**< Length of output buffer */
2897 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2898 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2899 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2901 ic = *(iconv_t*)pic;
2902 ibuf = ConvertBuf->buf;
2903 ibuflen = ConvertBuf->BufUsed;
2905 obuflen = TmpBuf->BufSize;
2907 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2910 if (errno == E2BIG) {
2912 IncreaseBuf(TmpBuf, 0, 0);
2917 else if (errno == EILSEQ){
2918 /* hm, invalid utf8 sequence... what to do now? */
2919 /* An invalid multibyte sequence has been encountered in the input */
2921 else if (errno == EINVAL) {
2922 /* An incomplete multibyte sequence has been encountered in the input. */
2925 FlushStrBuf(TmpBuf);
2928 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2929 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2931 /* little card game: wheres the red lady? */
2932 SwapBuffers(ConvertBuf, TmpBuf);
2933 FlushStrBuf(TmpBuf);
2940 * @ingroup StrBuf_DeEnCoder
2941 * @brief catches one RFC822 encoded segment, and decodes it.
2942 * @param Target buffer to fill with result
2943 * @param DecodeMe buffer with stuff to process
2944 * @param SegmentStart points to our current segment in DecodeMe
2945 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2946 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2947 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2948 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2950 inline static void DecodeSegment(StrBuf *Target,
2951 const StrBuf *DecodeMe,
2952 const char *SegmentStart,
2953 const char *SegmentEnd,
2955 StrBuf *ConvertBuf2,
2956 StrBuf *FoundCharset)
2962 iconv_t ic = (iconv_t)(-1);
2966 /* Now we handle foreign character sets properly encoded
2967 * in RFC2047 format.
2969 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
2970 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2971 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2972 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2973 if (FoundCharset != NULL) {
2974 FlushStrBuf(FoundCharset);
2975 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2977 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2978 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2980 *encoding = toupper(*encoding);
2981 if (*encoding == 'B') { /**< base64 */
2982 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
2983 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
2984 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2986 ConvertBuf->BufUsed);
2988 else if (*encoding == 'Q') { /**< quoted-printable */
2992 while (pos < ConvertBuf->BufUsed)
2994 if (ConvertBuf->buf[pos] == '_')
2995 ConvertBuf->buf[pos] = ' ';
2999 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3000 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3002 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3005 ConvertBuf->BufUsed);
3008 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3011 ctdl_iconv_open("UTF-8", charset, &ic);
3012 if (ic != (iconv_t)(-1) ) {
3014 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3015 StrBufAppendBuf(Target, ConvertBuf2, 0);
3020 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3026 * @ingroup StrBuf_DeEnCoder
3027 * @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
3028 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3029 * @param Target where to put the decoded string to
3030 * @param DecodeMe buffer with encoded string
3031 * @param DefaultCharset if we don't find one, which should we use?
3032 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3033 * put it here for later use where no string might be known.
3035 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
3038 StrBuf *ConvertBuf2;
3039 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3040 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3042 StrBuf_RFC822_2_Utf8(Target,
3048 FreeStrBuf(&ConvertBuf);
3049 FreeStrBuf(&ConvertBuf2);
3053 * @ingroup StrBuf_DeEnCoder
3054 * @brief Handle subjects with RFC2047 encoding such as:
3055 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3056 * @param Target where to put the decoded string to
3057 * @param DecodeMe buffer with encoded string
3058 * @param DefaultCharset if we don't find one, which should we use?
3059 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3060 * put it here for later use where no string might be known.
3061 * @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3062 * @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3064 void StrBuf_RFC822_2_Utf8(StrBuf *Target,
3065 const StrBuf *DecodeMe,
3066 const StrBuf* DefaultCharset,
3067 StrBuf *FoundCharset,
3069 StrBuf *ConvertBuf2)
3071 StrBuf *DecodedInvalidBuf = NULL;
3072 const StrBuf *DecodeMee = DecodeMe;
3073 const char *start, *end, *next, *nextend, *ptr = NULL;
3075 iconv_t ic = (iconv_t)(-1) ;
3080 int illegal_non_rfc2047_encoding = 0;
3082 /* Sometimes, badly formed messages contain strings which were simply
3083 * written out directly in some foreign character set instead of
3084 * using RFC2047 encoding. This is illegal but we will attempt to
3085 * handle it anyway by converting from a user-specified default
3086 * charset to UTF-8 if we see any nonprintable characters.
3089 len = StrLength(DecodeMe);
3090 for (i=0; i<DecodeMe->BufUsed; ++i) {
3091 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3092 illegal_non_rfc2047_encoding = 1;
3097 if ((illegal_non_rfc2047_encoding) &&
3098 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3099 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3102 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3103 if (ic != (iconv_t)(-1) ) {
3104 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3105 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3106 DecodeMee = DecodedInvalidBuf;
3112 /* pre evaluate the first pair */
3113 nextend = end = NULL;
3114 len = StrLength(DecodeMee);
3115 start = strstr(DecodeMee->buf, "=?");
3116 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3118 end = FindNextEnd (DecodeMee, start + 2);
3120 StrBufAppendBuf(Target, DecodeMee, 0);
3121 FreeStrBuf(&DecodedInvalidBuf);
3126 if (start != DecodeMee->buf) {
3129 nFront = start - DecodeMee->buf;
3130 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3134 * Since spammers will go to all sorts of absurd lengths to get their
3135 * messages through, there are LOTS of corrupt headers out there.
3136 * So, prevent a really badly formed RFC2047 header from throwing
3137 * this function into an infinite loop.
3139 while ((start != NULL) &&
3146 DecodeSegment(Target,
3154 next = strstr(end, "=?");
3156 if ((next != NULL) &&
3158 nextend = FindNextEnd(DecodeMee, next);
3159 if (nextend == NULL)
3162 /* did we find two partitions */
3163 if ((next != NULL) &&
3167 while ((ptr < next) &&
3174 * did we find a gab just filled with blanks?
3175 * if not, copy its stuff over.
3179 StrBufAppendBufPlain(Target,
3185 /* our next-pair is our new first pair now. */
3191 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3192 if ((end != NULL) && (end < nextend)) {
3194 while ( (ptr < nextend) &&
3201 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3203 FreeStrBuf(&DecodedInvalidBuf);
3206 /*******************************************************************************
3207 * Manipulating UTF-8 Strings *
3208 *******************************************************************************/
3212 * @brief evaluate the length of an utf8 special character sequence
3213 * @param Char the character to examine
3214 * @returns width of utf8 chars in bytes
3216 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
3221 while ((n < 8) && ((test & *CharS) != 0)) {
3225 if ((n > 6) || ((CharE - CharS) < n))
3232 * @brief detect whether this char starts an utf-8 encoded char
3233 * @param Char character to inspect
3234 * @returns yes or no
3236 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
3238 /** 11??.???? indicates an UTF8 Sequence. */
3239 return ((Char & 0xC0) != 0);
3244 * @brief measure the number of glyphs in an UTF8 string...
3245 * @param Buf string to measure
3246 * @returns the number of glyphs in Buf
3248 long StrBuf_Utf8StrLen(StrBuf *Buf)
3254 if ((Buf == NULL) || (Buf->BufUsed == 0))
3257 eptr = Buf->buf + Buf->BufUsed;
3258 while ((aptr < eptr) && (*aptr != '\0')) {
3259 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3260 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3261 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3274 * @brief cuts a string after maxlen glyphs
3275 * @param Buf string to cut to maxlen glyphs
3276 * @param maxlen how long may the string become?
3277 * @returns current length of the string
3279 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
3285 eptr = Buf->buf + Buf->BufUsed;
3286 while ((aptr < eptr) && (*aptr != '\0')) {
3287 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3288 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3289 while ((*aptr++ != '\0') && (m-- > 0));
3298 Buf->BufUsed = aptr - Buf->buf;
3299 return Buf->BufUsed;
3302 return Buf->BufUsed;
3310 /*******************************************************************************
3312 *******************************************************************************/
3315 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
3316 #define OS_CODE 0x03 /*< unix */
3319 * @ingroup StrBuf_DeEnCoder
3320 * @brief uses the same calling syntax as compress2(), but it
3321 * creates a stream compatible with HTTP "Content-encoding: gzip"
3322 * @param dest compressed buffer
3323 * @param destLen length of the compresed data
3324 * @param source source to encode
3325 * @param sourceLen length of source to encode
3326 * @param level compression level
3328 int ZEXPORT compress_gzip(Bytef * dest,
3330 const Bytef * source,
3334 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
3336 /* write gzip header */
3337 snprintf((char *) dest, *destLen,
3338 "%c%c%c%c%c%c%c%c%c%c",
3339 gz_magic[0], gz_magic[1], Z_DEFLATED,
3340 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3343 /* normal deflate */
3346 stream.next_in = (Bytef *) source;
3347 stream.avail_in = (uInt) sourceLen;
3348 stream.next_out = dest + 10L; // after header
3349 stream.avail_out = (uInt) * destLen;
3350 if ((uLong) stream.avail_out != *destLen)
3353 stream.zalloc = (alloc_func) 0;
3354 stream.zfree = (free_func) 0;
3355 stream.opaque = (voidpf) 0;
3357 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3358 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3362 err = deflate(&stream, Z_FINISH);
3363 if (err != Z_STREAM_END) {
3364 deflateEnd(&stream);
3365 return err == Z_OK ? Z_BUF_ERROR : err;
3367 *destLen = stream.total_out + 10L;
3369 /* write CRC and Length */
3370 uLong crc = crc32(0L, source, sourceLen);
3372 for (n = 0; n < 4; ++n, ++*destLen) {
3373 dest[*destLen] = (int) (crc & 0xff);
3376 uLong len = stream.total_in;
3377 for (n = 0; n < 4; ++n, ++*destLen) {
3378 dest[*destLen] = (int) (len & 0xff);
3381 err = deflateEnd(&stream);
3388 * @ingroup StrBuf_DeEnCoder
3389 * @brief compress the buffer with gzip
3390 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3391 * @param Buf buffer whose content is to be gzipped
3393 int CompressBuffer(StrBuf *Buf)
3396 char *compressed_data = NULL;
3397 size_t compressed_len, bufsize;
3400 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3401 compressed_data = malloc(compressed_len);
3403 if (compressed_data == NULL)
3405 /* Flush some space after the used payload so valgrind shuts up... */
3406 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3407 Buf->buf[Buf->BufUsed + i++] = '\0';
3408 if (compress_gzip((Bytef *) compressed_data,
3411 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3414 Buf->buf = compressed_data;
3415 Buf->BufUsed = compressed_len;
3416 Buf->BufSize = bufsize;
3417 /* Flush some space after the used payload so valgrind shuts up... */
3419 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3420 Buf->buf[Buf->BufUsed + i++] = '\0';
3423 free(compressed_data);
3425 #endif /* HAVE_ZLIB */
3431 /*******************************************************************************
3432 * File I/O; Prefer buffered read since its faster! *
3433 *******************************************************************************/
3436 * @ingroup StrBuf_IO
3437 * @brief Read a line from socket
3438 * flushes and closes the FD on error
3439 * @param buf the buffer to get the input to
3440 * @param fd pointer to the filedescriptor to read
3441 * @param append Append to an existing string or replace?
3442 * @param Error strerror() on error
3443 * @returns numbers of chars read
3445 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
3447 int len, rlen, slen;
3452 slen = len = buf->BufUsed;
3454 rlen = read(*fd, &buf->buf[len], 1);
3456 *Error = strerror(errno);
3463 if (buf->buf[len] == '\n')
3465 if (buf->buf[len] != '\r')
3467 if (len + 2 >= buf->BufSize) {
3469 buf->buf[len+1] = '\0';
3470 IncreaseBuf(buf, 1, -1);
3474 buf->buf[len] = '\0';
3479 * @ingroup StrBuf_BufferedIO
3480 * @brief Read a line from socket
3481 * flushes and closes the FD on error
3482 * @param Line the line to read from the fd / I/O Buffer
3483 * @param buf the buffer to get the input to
3484 * @param fd pointer to the filedescriptor to read
3485 * @param timeout number of successless selects until we bail out
3486 * @param selectresolution how long to wait on each select
3487 * @param Error strerror() on error
3488 * @returns numbers of chars read
3490 int StrBufTCP_read_buffered_line(StrBuf *Line,
3494 int selectresolution,
3498 int nSuccessLess = 0;
3505 if (buf->BufUsed > 0) {
3506 pch = strchr(buf->buf, '\n');
3509 len = pch - buf->buf;
3510 if (len > 0 && (*(pch - 1) == '\r') )
3512 StrBufSub(Line, buf, 0, len - rlen);
3513 StrBufCutLeft(buf, len + 1);
3518 if (buf->BufSize - buf->BufUsed < 10)
3519 IncreaseBuf(buf, 1, -1);
3521 fdflags = fcntl(*fd, F_GETFL);
3522 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3524 while ((nSuccessLess < timeout) && (pch == NULL)) {
3526 tv.tv_sec = selectresolution;
3531 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
3532 *Error = strerror(errno);
3538 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
3543 &buf->buf[buf->BufUsed],
3544 buf->BufSize - buf->BufUsed - 1);
3546 *Error = strerror(errno);
3551 else if (rlen > 0) {
3553 buf->BufUsed += rlen;
3554 buf->buf[buf->BufUsed] = '\0';
3555 if (buf->BufUsed + 10 > buf->BufSize) {
3556 IncreaseBuf(buf, 1, -1);
3558 pch = strchr(buf->buf, '\n');
3565 len = pch - buf->buf;
3566 if (len > 0 && (*(pch - 1) == '\r') )
3568 StrBufSub(Line, buf, 0, len - rlen);
3569 StrBufCutLeft(buf, len + 1);
3576 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3577 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3578 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3580 * @ingroup StrBuf_BufferedIO
3581 * @brief Read a line from socket
3582 * flushes and closes the FD on error
3583 * @param Line where to append our Line read from the fd / I/O Buffer;
3584 * @param IOBuf the buffer to get the input to; lifetime pair to FD
3585 * @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
3586 * @param fd pointer to the filedescriptor to read
3587 * @param timeout number of successless selects until we bail out
3588 * @param selectresolution how long to wait on each select
3589 * @param Error strerror() on error
3590 * @returns numbers of chars read or -1 in case of error. "\n" will become 0
3592 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3597 int selectresolution,
3600 const char *pche = NULL;
3601 const char *pos = NULL;
3603 int len, rlen, retlen;
3604 int nSuccessLess = 0;
3606 const char *pch = NULL;
3612 if ((Line == NULL) ||
3619 *Error = ErrRBLF_PreConditionFailed;
3624 if ((IOBuf->BufUsed > 0) &&
3626 (pos < IOBuf->buf + IOBuf->BufUsed))
3630 pche = IOBuf->buf + IOBuf->BufUsed;
3634 while ((pch < pche) && (*pch != '\n'))
3636 if (Line->BufUsed + 10 > Line->BufSize)
3639 apos = pcht - Line->buf;
3641 IncreaseBuf(Line, 1, -1);
3642 pcht = Line->buf + apos;
3650 if (len > 0 && (*(pch - 1) == '\r') )
3659 if ((pch >= pche) || (*pch == '\0'))
3667 if ((pch != NULL) &&
3670 if (pch + 1 >= pche) {
3683 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
3685 if (IOBuf->BufSize - IOBuf->BufUsed < 10)
3686 IncreaseBuf(IOBuf, 1, -1);
3688 fdflags = fcntl(*fd, F_GETFL);
3689 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3692 while ((nSuccessLess < timeout) &&
3702 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3703 *Error = strerror(errno);
3707 *Error = ErrRBLF_SelectFailed;
3710 if (! FD_ISSET(*fd, &rfds) != 0) {
3716 &IOBuf->buf[IOBuf->BufUsed],
3717 IOBuf->BufSize - IOBuf->BufUsed - 1);
3719 *Error = strerror(errno);
3724 else if (rlen > 0) {
3726 pLF = IOBuf->buf + IOBuf->BufUsed;
3727 IOBuf->BufUsed += rlen;
3728 IOBuf->buf[IOBuf->BufUsed] = '\0';
3730 pche = IOBuf->buf + IOBuf->BufUsed;
3732 while ((pLF < pche) && (*pLF != '\n'))
3734 if ((pLF >= pche) || (*pLF == '\0'))
3737 if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
3741 if (pLF != NULL) apos = pLF - IOBuf->buf;
3742 IncreaseBuf(IOBuf, 1, -1);
3743 if (pLF != NULL) pLF = IOBuf->buf + apos;
3753 if (len > 0 && (*(pLF - 1) == '\r') )
3755 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
3756 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
3762 return retlen + len;
3764 *Error = ErrRBLF_NotEnoughSentFromServer;
3769 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3771 * @ingroup StrBuf_IO
3772 * @brief Input binary data from socket
3773 * flushes and closes the FD on error
3774 * @param Buf the buffer to get the input to
3775 * @param fd pointer to the filedescriptor to read
3776 * @param append Append to an existing string or replace?
3777 * @param nBytes the maximal number of bytes to read
3778 * @param Error strerror() on error
3779 * @returns numbers of chars read
3781 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3792 if ((Buf == NULL) || (*fd == -1))
3794 *Error = ErrRBLF_BLOBPreConditionFailed;
3799 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3800 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3802 ptr = Buf->buf + Buf->BufUsed;
3804 fdflags = fcntl(*fd, F_GETFL);
3805 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3807 while ((nRead < nBytes) &&
3817 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3818 *Error = strerror(errno);
3822 *Error = ErrRBLF_SelectFailed;
3825 if (! FD_ISSET(*fd, &rfds) != 0) {
3831 if ((rlen = read(*fd,
3833 nBytes - nRead)) == -1) {
3836 *Error = strerror(errno);
3841 Buf->BufUsed += rlen;
3843 Buf->buf[Buf->BufUsed] = '\0';
3847 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3848 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3850 * @ingroup StrBuf_BufferedIO
3851 * @brief Input binary data from socket
3852 * flushes and closes the FD on error
3853 * @param Blob put binary thing here
3854 * @param IOBuf the buffer to get the input to
3855 * @param Pos offset inside of IOBuf
3856 * @param fd pointer to the filedescriptor to read
3857 * @param append Append to an existing string or replace?
3858 * @param nBytes the maximal number of bytes to read
3859 * @param check whether we should search for '000\n' terminators in case of timeouts
3860 * @param Error strerror() on error
3861 * @returns numbers of chars read
3863 int StrBufReadBLOBBuffered(StrBuf *Blob,
3877 int nAlreadyRead = 0;
3882 int nSuccessLess = 0;
3885 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3889 *Error = ErrRBB_BLOBFPreConditionFailed;
3895 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3896 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3901 len = pos - IOBuf->buf;
3902 rlen = IOBuf->BufUsed - len;
3905 if ((IOBuf->BufUsed > 0) &&
3907 (pos < IOBuf->buf + IOBuf->BufUsed))
3909 if (rlen < nBytes) {
3910 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3911 Blob->BufUsed += rlen;
3912 Blob->buf[Blob->BufUsed] = '\0';
3913 nAlreadyRead = nRead = rlen;
3916 if (rlen >= nBytes) {
3917 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3918 Blob->BufUsed += nBytes;
3919 Blob->buf[Blob->BufUsed] = '\0';
3920 if (rlen == nBytes) {
3932 if (IOBuf->BufSize < nBytes - nRead)
3933 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3936 len = Blob->BufUsed;
3938 fdflags = fcntl(*fd, F_GETFL);
3939 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3947 while ((nSuccessLess < MaxTries) &&
3957 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3958 *Error = strerror(errno);
3962 *Error = ErrRBLF_SelectFailed;
3965 if (! FD_ISSET(*fd, &rfds) != 0) {
3972 IOBuf->BufSize - (ptr - IOBuf->buf));
3976 *Error = strerror(errno);
3979 else if (rlen == 0){
3980 if ((check == NNN_TERM) &&
3982 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3984 StrBufPlain(Blob, HKEY("\n000\n"));
3985 StrBufCutRight(Blob, 5);
3986 return Blob->BufUsed;
3988 else if (!IsNonBlock)
3990 else if (nSuccessLess > MaxTries) {
3992 *Error = ErrRBB_too_many_selects;
3996 else if (rlen > 0) {
4000 IOBuf->BufUsed += rlen;
4003 if (nSuccessLess >= MaxTries) {
4005 *Error = ErrRBB_too_many_selects;
4009 if (nRead > nBytes) {
4010 *Pos = IOBuf->buf + nBytes;
4012 Blob->buf[Blob->BufUsed] = '\0';
4013 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
4017 return nRead + nAlreadyRead;
4021 * @ingroup StrBuf_IO
4022 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
4023 * @param LineBuf your line will be copied here.
4024 * @param Buf BLOB with lines of text...
4025 * @param Ptr moved arround to keep the next-line across several iterations
4026 * has to be &NULL on start; will be &NotNULL on end of buffer
4027 * @returns size of copied buffer
4029 int StrBufSipLine(StrBuf *LineBuf, const StrBuf *Buf, const char **Ptr)
4031 const char *aptr, *ptr, *eptr;
4034 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
4035 *Ptr = StrBufNOTNULL;
4039 FlushStrBuf(LineBuf);
4041 ptr = aptr = Buf->buf;
4045 optr = LineBuf->buf;
4046 eptr = Buf->buf + Buf->BufUsed;
4047 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4049 while ((ptr <= eptr) &&
4056 LineBuf->BufUsed = optr - LineBuf->buf;
4057 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
4058 optr = LineBuf->buf + LineBuf->BufUsed;
4059 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4063 if ((ptr >= eptr) && (optr > LineBuf->buf))
4065 LineBuf->BufUsed = optr - LineBuf->buf;
4067 if ((ptr <= eptr) && (*ptr == '\r'))
4069 if ((ptr <= eptr) && (*ptr == '\n'))
4076 *Ptr = StrBufNOTNULL;
4079 return Buf->BufUsed - (ptr - Buf->buf);
4084 * @ingroup StrBuf_IO
4085 * @brief removes double slashes from pathnames
4086 * @param Dir directory string to filter
4087 * @param RemoveTrailingSlash allows / disallows trailing slashes
4089 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
4095 while (!IsEmptyStr(a)) {
4107 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
4112 Dir->BufUsed = b - Dir->buf;