8 #include <sys/select.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
13 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
28 int BaseStrBufSize = 64;
30 const char *StrBufNOTNULL = ((char*) NULL) - 1;
32 const char HexList[256][3] = {
33 "00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
34 "10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
35 "20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
36 "30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
37 "40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
38 "50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
39 "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
40 "70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
41 "80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
42 "90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
43 "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
44 "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
45 "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
46 "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
47 "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
48 "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};
51 * @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
52 * StrBuf is a versatile class, aiding the handling of dynamic strings
53 * * reduce de/reallocations
54 * * reduce the need to remeasure it
55 * * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
56 * * allow asyncroneous IO for line and Blob based operations
57 * * reduce the use of memove in those
58 * * Quick filling in several operations with append functions
62 * @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
67 * @defgroup StrBuf_Cast Cast operators to interact with char* based code
69 * use these operators to interfere with code demanding char*;
70 * if you need to own the content, smash me. Avoid, since we loose the length information.
74 * @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
76 * operations to get your Strings into a StrBuf, manipulating them, or appending
79 * @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence
81 * Quick tokenizer; demands of the user to pull its tokens in sequence
85 * @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
87 * versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
91 * @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
93 * File IO to fill StrBufs; Works with work-buffer shared across several calls;
94 * External Cursor to maintain the current read position inside of the buffer
95 * the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower)
99 * @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
105 * @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
107 * these functions translate the content of a buffer into another representation;
108 * some are combined Fillers and encoders
112 * Private Structure for the Stringbuffer
115 char *buf; /**< the pointer to the dynamic buffer */
116 long BufSize; /**< how many spcae do we optain */
117 long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
118 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
120 long nIncreases; /**< for profiling; cound how many times we needed more */
121 char bt [SIZ]; /**< Stacktrace of last increase */
122 char bt_lastinc [SIZ]; /**< How much did we increase last time? */
127 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
128 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
131 #ifdef HAVE_BACKTRACE
132 static void StrBufBacktrace(StrBuf *Buf, int which)
136 void *stack_frames[50];
141 pstart = pch = Buf->bt;
143 pstart = pch = Buf->bt_lastinc;
144 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
145 strings = backtrace_symbols(stack_frames, size);
146 for (i = 0; i < size; i++) {
148 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
150 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
159 void dbg_FreeStrBuf(StrBuf *FreeMe, char *FromWhere)
161 if (hFreeDbglog == -1){
162 pid_t pid = getpid();
164 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
165 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
167 if ((*FreeMe)->nIncreases > 0)
171 n = snprintf(buf, SIZ * 3, "%c+|%ld|%ld|%ld|%s|%s|\n",
173 (*FreeMe)->nIncreases,
177 (*FreeMe)->bt_lastinc);
178 n = write(hFreeDbglog, buf, n);
184 n = snprintf(buf, 128, "%c_|0|%ld%ld|\n",
188 n = write(hFreeDbglog, buf, n);
192 void dbg_IncreaseBuf(StrBuf *IncMe)
195 #ifdef HAVE_BACKTRACE
196 StrBufBacktrace(Buf, 1);
200 void dbg_Init(StrBuf *Buf)
204 Buf->bt_lastinc[0] = '\0';
205 #ifdef HAVE_BACKTRACE
206 StrBufBacktrace(Buf, 0);
212 #define dbg_FreeStrBuf(a, b)
213 #define dbg_IncreaseBuf(a)
219 * @ingroup StrBuf_Cast
220 * @brief Cast operator to Plain String
221 * @note if the buffer is altered by StrBuf operations, this pointer may become
222 * invalid. So don't lean on it after altering the buffer!
223 * Since this operation is considered cheap, rather call it often than risking
224 * your pointer to become invalid!
225 * @param Str the string we want to get the c-string representation for
226 * @returns the Pointer to the Content. Don't mess with it!
228 inline const char *ChrPtr(const StrBuf *Str)
236 * @ingroup StrBuf_Cast
237 * @brief since we know strlen()'s result, provide it here.
238 * @param Str the string to return the length to
239 * @returns contentlength of the buffer
241 inline int StrLength(const StrBuf *Str)
243 return (Str != NULL) ? Str->BufUsed : 0;
247 * @ingroup StrBuf_DeConstructors
248 * @brief local utility function to resize the buffer
249 * @param Buf the buffer whichs storage we should increase
250 * @param KeepOriginal should we copy the original buffer or just start over with a new one
251 * @param DestSize what should fit in after?
253 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
256 size_t NewSize = Buf->BufSize * 2;
262 while (NewSize <= DestSize)
265 NewBuf= (char*) malloc(NewSize);
269 if (KeepOriginal && (Buf->BufUsed > 0))
271 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
280 Buf->BufSize = NewSize;
282 dbg_IncreaseBuf(Buf);
288 * @ingroup StrBuf_DeConstructors
289 * @brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
290 * @param Buf Buffer to shrink (has to be empty)
291 * @param ThreshHold if the buffer is bigger then this, its readjusted
292 * @param NewSize if we Shrink it, how big are we going to be afterwards?
294 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
296 if (Buf->BufUsed > ThreshHold) {
298 Buf->buf = (char*) malloc(NewSize);
300 Buf->BufSize = NewSize;
305 * @ingroup StrBuf_DeConstructors
306 * @brief shrink long term buffers to their real size so they don't waste memory
307 * @param Buf buffer to shrink
308 * @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
309 * @returns physical size of the buffer
311 long StrBufShrinkToFit(StrBuf *Buf, int Force)
314 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
316 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
317 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
318 Buf->BufSize = Buf->BufUsed + 1;
326 * @ingroup StrBuf_DeConstructors
327 * @brief Allocate a new buffer with default buffer size
328 * @returns the new stringbuffer
330 StrBuf* NewStrBuf(void)
334 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
335 NewBuf->buf = (char*) malloc(BaseStrBufSize);
336 NewBuf->buf[0] = '\0';
337 NewBuf->BufSize = BaseStrBufSize;
339 NewBuf->ConstBuf = 0;
347 * @ingroup StrBuf_DeConstructors
348 * @brief Copy Constructor; returns a duplicate of CopyMe
349 * @param CopyMe Buffer to faxmilate
350 * @returns the new stringbuffer
352 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
359 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
360 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
361 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
362 NewBuf->BufUsed = CopyMe->BufUsed;
363 NewBuf->BufSize = CopyMe->BufSize;
364 NewBuf->ConstBuf = 0;
372 * @ingroup StrBuf_DeConstructors
373 * @brief create a new Buffer using an existing c-string
374 * this function should also be used if you want to pre-suggest
375 * the buffer size to allocate in conjunction with ptr == NULL
376 * @param ptr the c-string to copy; may be NULL to create a blank instance
377 * @param nChars How many chars should we copy; -1 if we should measure the length ourselves
378 * @returns the new stringbuffer
380 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
383 size_t Siz = BaseStrBufSize;
386 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
388 CopySize = strlen((ptr != NULL)?ptr:"");
392 while (Siz <= CopySize)
395 NewBuf->buf = (char*) malloc(Siz);
396 NewBuf->BufSize = Siz;
398 memcpy(NewBuf->buf, ptr, CopySize);
399 NewBuf->buf[CopySize] = '\0';
400 NewBuf->BufUsed = CopySize;
403 NewBuf->buf[0] = '\0';
406 NewBuf->ConstBuf = 0;
414 * @ingroup StrBuf_DeConstructors
415 * @brief Set an existing buffer from a c-string
416 * @param Buf buffer to load
417 * @param ptr c-string to put into
418 * @param nChars set to -1 if we should work 0-terminated
419 * @returns the new length of the string
421 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
423 size_t Siz = Buf->BufSize;
427 CopySize = strlen(ptr);
431 while (Siz <= CopySize)
434 if (Siz != Buf->BufSize)
435 IncreaseBuf(Buf, 0, Siz);
436 memcpy(Buf->buf, ptr, CopySize);
437 Buf->buf[CopySize] = '\0';
438 Buf->BufUsed = CopySize;
445 * @ingroup StrBuf_DeConstructors
446 * @brief use strbuf as wrapper for a string constant for easy handling
447 * @param StringConstant a string to wrap
448 * @param SizeOfStrConstant should be sizeof(StringConstant)-1
450 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
454 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
455 NewBuf->buf = (char*) StringConstant;
456 NewBuf->BufSize = SizeOfStrConstant;
457 NewBuf->BufUsed = SizeOfStrConstant;
458 NewBuf->ConstBuf = 1;
467 * @ingroup StrBuf_DeConstructors
468 * @brief flush the content of a Buf; keep its struct
469 * @param buf Buffer to flush
471 int FlushStrBuf(StrBuf *buf)
483 * @ingroup StrBuf_DeConstructors
484 * @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
485 * @param buf Buffer to wipe
487 int FLUSHStrBuf(StrBuf *buf)
493 if (buf->BufUsed > 0) {
494 memset(buf->buf, 0, buf->BufUsed);
501 int hFreeDbglog = -1;
504 * @ingroup StrBuf_DeConstructors
505 * @brief Release a Buffer
506 * Its a double pointer, so it can NULL your pointer
507 * so fancy SIG11 appear instead of random results
508 * @param FreeMe Pointer Pointer to the buffer to free
510 void FreeStrBuf (StrBuf **FreeMe)
515 dbg_FreeStrBuf(FreeMe, 'F');
517 if (!(*FreeMe)->ConstBuf)
518 free((*FreeMe)->buf);
524 * @ingroup StrBuf_DeConstructors
525 * @brief flatten a Buffer to the Char * we return
526 * Its a double pointer, so it can NULL your pointer
527 * so fancy SIG11 appear instead of random results
528 * The Callee then owns the buffer and is responsible for freeing it.
529 * @param SmashMe Pointer Pointer to the buffer to release Buf from and free
530 * @returns the pointer of the buffer; Callee owns the memory thereafter.
532 char *SmashStrBuf (StrBuf **SmashMe)
536 if ((SmashMe == NULL) || (*SmashMe == NULL))
539 dbg_FreeStrBuf(SmashMe, 'S');
541 Ret = (*SmashMe)->buf;
548 * @ingroup StrBuf_DeConstructors
549 * @brief Release the buffer
550 * If you want put your StrBuf into a Hash, use this as Destructor.
551 * @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
553 void HFreeStrBuf (void *VFreeMe)
555 StrBuf *FreeMe = (StrBuf*)VFreeMe;
559 dbg_FreeStrBuf(SmashMe, 'H');
561 if (!FreeMe->ConstBuf)
567 /*******************************************************************************
568 * Simple string transformations *
569 *******************************************************************************/
573 * @brief Wrapper around atol
575 long StrTol(const StrBuf *Buf)
580 return atol(Buf->buf);
587 * @brief Wrapper around atoi
589 int StrToi(const StrBuf *Buf)
593 if (Buf->BufUsed > 0)
594 return atoi(Buf->buf);
601 * @brief Checks to see if the string is a pure number
603 int StrBufIsNumber(const StrBuf *Buf) {
608 strtoll(Buf->buf, &pEnd, 10);
609 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
616 * @brief modifies a Single char of the Buf
617 * You can point to it via char* or a zero-based integer
618 * @param Buf The buffer to manipulate
619 * @param ptr char* to zero; use NULL if unused
620 * @param nThChar zero based pointer into the string; use -1 if unused
621 * @param PeekValue The Character to place into the position
623 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
628 nThChar = ptr - Buf->buf;
629 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
631 Buf->buf[nThChar] = PeekValue;
637 * @brief Append a StringBuffer to the buffer
638 * @param Buf Buffer to modify
639 * @param AppendBuf Buffer to copy at the end of our buffer
640 * @param Offset Should we start copying from an offset?
642 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
644 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
647 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
650 AppendBuf->BufUsed + Buf->BufUsed);
652 memcpy(Buf->buf + Buf->BufUsed,
653 AppendBuf->buf + Offset,
654 AppendBuf->BufUsed - Offset);
655 Buf->BufUsed += AppendBuf->BufUsed - Offset;
656 Buf->buf[Buf->BufUsed] = '\0';
662 * @brief Append a C-String to the buffer
663 * @param Buf Buffer to modify
664 * @param AppendBuf Buffer to copy at the end of our buffer
665 * @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
666 * @param Offset Should we start copying from an offset?
668 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
671 long BufSizeRequired;
673 if ((AppendBuf == NULL) || (Buf == NULL))
677 aps = strlen(AppendBuf + Offset);
679 aps = AppendSize - Offset;
681 BufSizeRequired = Buf->BufUsed + aps + 1;
682 if (Buf->BufSize <= BufSizeRequired)
683 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
685 memcpy(Buf->buf + Buf->BufUsed,
689 Buf->buf[Buf->BufUsed] = '\0';
694 * @brief sprintf like function appending the formated string to the buffer
695 * vsnprintf version to wrap into own calls
696 * @param Buf Buffer to extend by format and Params
697 * @param format printf alike format to add
698 * @param ap va_list containing the items for format
700 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
708 if ((Buf == NULL) || (format == NULL))
711 BufSize = Buf->BufSize;
712 nWritten = Buf->BufSize + 1;
713 Offset = Buf->BufUsed;
714 newused = Offset + nWritten;
716 while (newused >= BufSize) {
718 nWritten = vsnprintf(Buf->buf + Offset,
719 Buf->BufSize - Offset,
722 newused = Offset + nWritten;
723 if (newused >= Buf->BufSize) {
724 IncreaseBuf(Buf, 1, newused);
725 newused = Buf->BufSize + 1;
728 Buf->BufUsed = Offset + nWritten;
729 BufSize = Buf->BufSize;
737 * @brief sprintf like function appending the formated string to the buffer
738 * @param Buf Buffer to extend by format and Params
739 * @param format printf alike format to add
741 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
749 if ((Buf == NULL) || (format == NULL))
752 BufSize = Buf->BufSize;
753 nWritten = Buf->BufSize + 1;
754 Offset = Buf->BufUsed;
755 newused = Offset + nWritten;
757 while (newused >= BufSize) {
758 va_start(arg_ptr, format);
759 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
760 Buf->BufSize - Buf->BufUsed,
763 newused = Buf->BufUsed + nWritten;
764 if (newused >= Buf->BufSize) {
765 IncreaseBuf(Buf, 1, newused);
766 newused = Buf->BufSize + 1;
769 Buf->BufUsed += nWritten;
770 BufSize = Buf->BufSize;
778 * @brief sprintf like function putting the formated string into the buffer
779 * @param Buf Buffer to extend by format and Parameters
780 * @param format printf alike format to add
782 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
787 if ((Buf == NULL) || (format == NULL))
790 nWritten = Buf->BufSize + 1;
791 while (nWritten >= Buf->BufSize) {
792 va_start(arg_ptr, format);
793 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
795 if (nWritten >= Buf->BufSize) {
796 IncreaseBuf(Buf, 0, 0);
797 nWritten = Buf->BufSize + 1;
800 Buf->BufUsed = nWritten ;
806 * @brief Callback for cURL to append the webserver reply to a buffer
807 * @param ptr pre-defined by the cURL API; see man 3 curl for mre info
808 * @param size pre-defined by the cURL API; see man 3 curl for mre info
809 * @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
810 * @param stream pre-defined by the cURL API; see man 3 curl for mre info
812 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
821 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
828 * @brief extracts a substring from Source into dest
829 * @param dest buffer to place substring into
830 * @param Source string to copy substring from
831 * @param Offset chars to skip from start
832 * @param nChars number of chars to copy
833 * @returns the number of chars copied; may be different from nChars due to the size of Source
835 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
838 if (Offset > Source->BufUsed)
843 if (Offset + nChars < Source->BufUsed)
845 if (nChars >= dest->BufSize)
846 IncreaseBuf(dest, 0, nChars + 1);
847 memcpy(dest->buf, Source->buf + Offset, nChars);
848 dest->BufUsed = nChars;
849 dest->buf[dest->BufUsed] = '\0';
852 NCharsRemain = Source->BufUsed - Offset;
853 if (NCharsRemain >= dest->BufSize)
854 IncreaseBuf(dest, 0, NCharsRemain + 1);
855 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
856 dest->BufUsed = NCharsRemain;
857 dest->buf[dest->BufUsed] = '\0';
863 * @brief Cut nChars from the start of the string
864 * @param Buf Buffer to modify
865 * @param nChars how many chars should be skipped?
867 void StrBufCutLeft(StrBuf *Buf, int nChars)
869 if (nChars >= Buf->BufUsed) {
873 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
874 Buf->BufUsed -= nChars;
875 Buf->buf[Buf->BufUsed] = '\0';
880 * @brief Cut the trailing n Chars from the string
881 * @param Buf Buffer to modify
882 * @param nChars how many chars should be trunkated?
884 void StrBufCutRight(StrBuf *Buf, int nChars)
886 if (nChars >= Buf->BufUsed) {
890 Buf->BufUsed -= nChars;
891 Buf->buf[Buf->BufUsed] = '\0';
896 * @brief Cut the string after n Chars
897 * @param Buf Buffer to modify
898 * @param AfternChars after how many chars should we trunkate the string?
899 * @param At if non-null and points inside of our string, cut it there.
901 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
904 AfternChars = At - Buf->buf;
907 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
909 Buf->BufUsed = AfternChars;
910 Buf->buf[Buf->BufUsed] = '\0';
916 * @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
917 * @param Buf the string to modify
919 void StrBufTrim(StrBuf *Buf)
922 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
924 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
927 if (delta > 0) StrBufCutLeft(Buf, delta);
929 if (Buf->BufUsed == 0) return;
930 while (isspace(Buf->buf[Buf->BufUsed - 1])){
933 Buf->buf[Buf->BufUsed] = '\0';
938 * @brief uppercase the contents of a buffer
939 * @param Buf the buffer to translate
941 void StrBufUpCase(StrBuf *Buf)
946 pche = pch + Buf->BufUsed;
948 *pch = toupper(*pch);
956 * @brief lowercase the contents of a buffer
957 * @param Buf the buffer to translate
959 void StrBufLowerCase(StrBuf *Buf)
964 pche = pch + Buf->BufUsed;
966 *pch = tolower(*pch);
972 /*******************************************************************************
973 * a tokenizer that kills, maims, and destroys *
974 *******************************************************************************/
977 * @ingroup StrBuf_Tokenizer
978 * @brief Counts the numbmer of tokens in a buffer
979 * @param source String to count tokens in
980 * @param tok Tokenizer char to count
981 * @returns numbers of tokenizer chars found
983 int StrBufNum_tokens(const StrBuf *source, char tok)
987 return num_tokens(source->buf, tok);
991 * @ingroup StrBuf_Tokenizer
992 * @brief a string tokenizer
993 * @param Source StringBuffer to read into
994 * @param parmnum n'th Parameter to remove
995 * @param separator tokenizer character
996 * @returns -1 if not found, else length of token.
998 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1001 char *d, *s, *end; /* dest, source */
1004 /* Find desired @parameter */
1005 end = Source->buf + Source->BufUsed;
1007 while ((d <= end) &&
1010 /* End of string, bail! */
1015 if (*d == separator) {
1020 if ((d == NULL) || (d >= end))
1021 return 0; /* @Parameter not found */
1023 /* Find next @parameter */
1025 while ((s <= end) &&
1026 (*s && *s != separator))
1030 if (*s == separator)
1034 /* Hack and slash */
1039 memmove(d, s, Source->BufUsed - (s - Source->buf));
1040 Source->BufUsed += ReducedBy;
1041 Source->buf[Source->BufUsed] = '\0';
1043 else if (d == Source->buf) {
1045 Source->BufUsed = 0;
1049 Source->BufUsed += ReducedBy;
1062 * @ingroup StrBuf_Tokenizer
1063 * @brief a string tokenizer
1064 * @param dest Destination StringBuffer
1065 * @param Source StringBuffer to read into
1066 * @param parmnum n'th Parameter to extract
1067 * @param separator tokenizer character
1068 * @returns -1 if not found, else length of token.
1070 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1072 const char *s, *e; //* source * /
1073 int len = 0; //* running total length of extracted string * /
1074 int current_token = 0; //* token currently being processed * /
1077 dest->buf[0] = '\0';
1083 if ((Source == NULL) || (Source->BufUsed ==0)) {
1087 e = s + Source->BufUsed;
1090 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1092 while ((s<e) && !IsEmptyStr(s)) {
1093 if (*s == separator) {
1096 if (len >= dest->BufSize) {
1097 dest->BufUsed = len;
1098 if (IncreaseBuf(dest, 1, -1) < 0) {
1103 if ( (current_token == parmnum) &&
1104 (*s != separator)) {
1105 dest->buf[len] = *s;
1108 else if (current_token > parmnum) {
1114 dest->buf[len] = '\0';
1115 dest->BufUsed = len;
1117 if (current_token < parmnum) {
1118 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1121 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1130 * @ingroup StrBuf_Tokenizer
1131 * @brief a string tokenizer to fetch an integer
1132 * @param Source String containing tokens
1133 * @param parmnum n'th Parameter to extract
1134 * @param separator tokenizer character
1135 * @returns 0 if not found, else integer representation of the token
1137 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1147 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1154 * @ingroup StrBuf_Tokenizer
1155 * @brief a string tokenizer to fetch a long integer
1156 * @param Source String containing tokens
1157 * @param parmnum n'th Parameter to extract
1158 * @param separator tokenizer character
1159 * @returns 0 if not found, else long integer representation of the token
1161 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1171 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1179 * @ingroup StrBuf_Tokenizer
1180 * @brief a string tokenizer to fetch an unsigned long
1181 * @param Source String containing tokens
1182 * @param parmnum n'th Parameter to extract
1183 * @param separator tokenizer character
1184 * @returns 0 if not found, else unsigned long representation of the token
1186 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1197 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1201 return (unsigned long) atol(pnum);
1210 * @ingroup StrBuf_NextTokenizer
1211 * @brief a string tokenizer; Bounds checker
1212 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1213 * @param Source our tokenbuffer
1214 * @param pStart the token iterator pointer to inspect
1215 * @returns whether the revolving pointer is inside of the search range
1217 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1219 if ((Source == NULL) ||
1220 (*pStart == StrBufNOTNULL) ||
1221 (Source->BufUsed == 0))
1225 if (*pStart == NULL)
1229 else if (*pStart > Source->buf + Source->BufUsed)
1233 else if (*pStart <= Source->buf)
1242 * @ingroup StrBuf_NextTokenizer
1243 * @brief a string tokenizer
1244 * @param dest Destination StringBuffer
1245 * @param Source StringBuffer to read into
1246 * @param pStart pointer to the end of the last token. Feed with NULL on start.
1247 * @param separator tokenizer
1248 * @returns -1 if not found, else length of token.
1250 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1252 const char *s; /* source */
1253 const char *EndBuffer; /* end stop of source buffer */
1254 int current_token = 0; /* token currently being processed */
1255 int len = 0; /* running total length of extracted string */
1257 if ((Source == NULL) ||
1258 (Source->BufUsed == 0) )
1260 *pStart = StrBufNOTNULL;
1264 EndBuffer = Source->buf + Source->BufUsed;
1268 dest->buf[0] = '\0';
1273 *pStart = EndBuffer + 1;
1277 if (*pStart == NULL)
1279 *pStart = Source->buf; /* we're starting to examine this buffer. */
1281 else if ((*pStart < Source->buf) ||
1282 (*pStart > EndBuffer ) )
1284 return -1; /* no more tokens to find. */
1288 /* start to find the next token */
1289 while ((s <= EndBuffer) &&
1290 (current_token == 0) )
1292 if (*s == separator)
1294 /* we found the next token */
1298 if (len >= dest->BufSize)
1300 /* our Dest-buffer isn't big enough, increase it. */
1301 dest->BufUsed = len;
1303 if (IncreaseBuf(dest, 1, -1) < 0) {
1304 /* WHUT? no more mem? bail out. */
1311 if ( (current_token == 0 ) && /* are we in our target token? */
1312 (!IsEmptyStr(s) ) &&
1313 (separator != *s) ) /* don't copy the token itself */
1315 dest->buf[len] = *s; /* Copy the payload */
1316 ++len; /* remember the bigger size. */
1322 /* did we reach the end? */
1323 if ((s > EndBuffer)) {
1324 EndBuffer = StrBufNOTNULL;
1325 *pStart = EndBuffer;
1328 *pStart = s; /* remember the position for the next run */
1331 /* sanitize our extracted token */
1332 dest->buf[len] = '\0';
1333 dest->BufUsed = len;
1340 * @ingroup StrBuf_NextTokenizer
1341 * @brief a string tokenizer
1342 * @param Source StringBuffer to read from
1343 * @param pStart pointer to the end of the last token. Feed with NULL.
1344 * @param separator tokenizer character
1345 * @param nTokens number of tokens to fastforward over
1346 * @returns -1 if not found, else length of token.
1348 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1350 const char *s, *EndBuffer; //* source * /
1351 int len = 0; //* running total length of extracted string * /
1352 int current_token = 0; //* token currently being processed * /
1354 if ((Source == NULL) ||
1355 (Source->BufUsed ==0)) {
1359 return Source->BufUsed;
1361 if (*pStart == NULL)
1362 *pStart = Source->buf;
1364 EndBuffer = Source->buf + Source->BufUsed;
1366 if ((*pStart < Source->buf) ||
1367 (*pStart > EndBuffer)) {
1375 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1377 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1378 if (*s == separator) {
1381 if (current_token >= nTokens) {
1393 * @ingroup StrBuf_NextTokenizer
1394 * @brief a string tokenizer to fetch an integer
1395 * @param Source StringBuffer to read from
1396 * @param pStart Cursor on the tokenstring
1397 * @param separator tokenizer character
1398 * @returns 0 if not found, else integer representation of the token
1400 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1410 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1417 * @ingroup StrBuf_NextTokenizer
1418 * @brief a string tokenizer to fetch a long integer
1419 * @param Source StringBuffer to read from
1420 * @param pStart Cursor on the tokenstring
1421 * @param separator tokenizer character
1422 * @returns 0 if not found, else long integer representation of the token
1424 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1434 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1442 * @ingroup StrBuf_NextTokenizer
1443 * @brief a string tokenizer to fetch an unsigned long
1444 * @param Source StringBuffer to read from
1445 * @param pStart Cursor on the tokenstring
1446 * @param separator tokenizer character
1447 * @returns 0 if not found, else unsigned long representation of the token
1449 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1460 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1464 return (unsigned long) atol(pnum);
1474 /*******************************************************************************
1475 * Escape Appending *
1476 *******************************************************************************/
1479 * @ingroup StrBuf_DeEnCoder
1480 * @brief Escape a string for feeding out as a URL while appending it to a Buffer
1481 * @param OutBuf the output buffer
1482 * @param In Buffer to encode
1483 * @param PlainIn way in from plain old c strings
1485 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
1487 const char *pch, *pche;
1491 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1493 if (PlainIn != NULL) {
1494 len = strlen(PlainIn);
1500 pche = pch + In->BufUsed;
1507 pt = OutBuf->buf + OutBuf->BufUsed;
1508 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1510 while (pch < pche) {
1512 IncreaseBuf(OutBuf, 1, -1);
1513 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1514 pt = OutBuf->buf + OutBuf->BufUsed;
1517 if((*pch >= 'a' && *pch <= 'z') ||
1518 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1519 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1520 (*pch == '!') || (*pch == '_') ||
1521 (*pch == ',') || (*pch == '.') ||
1529 *(pt + 1) = HexList[(unsigned char)*pch][0];
1530 *(pt + 2) = HexList[(unsigned char)*pch][1];
1532 OutBuf->BufUsed += 3;
1540 * @ingroup StrBuf_DeEnCoder
1541 * @brief Append a string, escaping characters which have meaning in HTML.
1543 * @param Target target buffer
1544 * @param Source source buffer; set to NULL if you just have a C-String
1545 * @param PlainIn Plain-C string to append; set to NULL if unused
1546 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1547 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1548 * if set to 2, linebreaks are replaced by <br/>
1550 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1552 const char *aptr, *eiptr;
1556 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1559 if (PlainIn != NULL) {
1561 len = strlen(PlainIn);
1566 eiptr = aptr + Source->BufUsed;
1567 len = Source->BufUsed;
1573 bptr = Target->buf + Target->BufUsed;
1574 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1576 while (aptr < eiptr){
1578 IncreaseBuf(Target, 1, -1);
1579 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1580 bptr = Target->buf + Target->BufUsed;
1583 memcpy(bptr, "<", 4);
1585 Target->BufUsed += 4;
1587 else if (*aptr == '>') {
1588 memcpy(bptr, ">", 4);
1590 Target->BufUsed += 4;
1592 else if (*aptr == '&') {
1593 memcpy(bptr, "&", 5);
1595 Target->BufUsed += 5;
1597 else if (*aptr == '"') {
1598 memcpy(bptr, """, 6);
1600 Target->BufUsed += 6;
1602 else if (*aptr == '\'') {
1603 memcpy(bptr, "'", 5);
1605 Target->BufUsed += 5;
1607 else if (*aptr == LB) {
1612 else if (*aptr == RB) {
1617 else if (*aptr == QU) {
1622 else if ((*aptr == 32) && (nbsp == 1)) {
1623 memcpy(bptr, " ", 6);
1625 Target->BufUsed += 6;
1627 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1628 *bptr='\0'; /* nothing */
1630 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1631 memcpy(bptr, "<br/>", 11);
1633 Target->BufUsed += 11;
1637 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1638 *bptr='\0'; /* nothing */
1648 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1650 return Target->BufUsed;
1654 * @ingroup StrBuf_DeEnCoder
1655 * @brief Append a string, escaping characters which have meaning in HTML.
1656 * Converts linebreaks into blanks; escapes single quotes
1657 * @param Target target buffer
1658 * @param Source source buffer; set to NULL if you just have a C-String
1659 * @param PlainIn Plain-C string to append; set to NULL if unused
1661 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1663 const char *aptr, *eiptr;
1667 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1670 if (PlainIn != NULL) {
1672 len = strlen(PlainIn);
1677 eiptr = aptr + Source->BufUsed;
1678 len = Source->BufUsed;
1684 eptr = Target->buf + Target->BufSize - 8;
1685 tptr = Target->buf + Target->BufUsed;
1687 while (aptr < eiptr){
1689 IncreaseBuf(Target, 1, -1);
1690 eptr = Target->buf + Target->BufSize - 8;
1691 tptr = Target->buf + Target->BufUsed;
1694 if (*aptr == '\n') {
1698 else if (*aptr == '\r') {
1702 else if (*aptr == '\'') {
1708 Target->BufUsed += 5;
1721 * @ingroup StrBuf_DeEnCoder
1722 * @brief Append a string, escaping characters which have meaning in ICAL.
1724 * @param Target target buffer
1725 * @param Source source buffer; set to NULL if you just have a C-String
1726 * @param PlainIn Plain-C string to append; set to NULL if unused
1728 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1730 const char *aptr, *eiptr;
1734 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1737 if (PlainIn != NULL) {
1739 len = strlen(PlainIn);
1744 eiptr = aptr + Source->BufUsed;
1745 len = Source->BufUsed;
1751 eptr = Target->buf + Target->BufSize - 8;
1752 tptr = Target->buf + Target->BufUsed;
1754 while (aptr < eiptr){
1755 if(tptr + 3 >= eptr) {
1756 IncreaseBuf(Target, 1, -1);
1757 eptr = Target->buf + Target->BufSize - 8;
1758 tptr = Target->buf + Target->BufUsed;
1761 if (*aptr == '\n') {
1768 else if (*aptr == '\r') {
1775 else if (*aptr == ',') {
1791 * @ingroup StrBuf_DeEnCoder
1792 * @brief Append a string, escaping characters which have meaning in JavaScript strings .
1794 * @param Target target buffer
1795 * @param Source source buffer; set to NULL if you just have a C-String
1796 * @param PlainIn Plain-C string to append; set to NULL if unused
1797 * @returns size of result or -1
1799 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
1801 const char *aptr, *eiptr;
1805 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1808 if (PlainIn != NULL) {
1810 len = strlen(PlainIn);
1815 eiptr = aptr + Source->BufUsed;
1816 len = Source->BufUsed;
1822 bptr = Target->buf + Target->BufUsed;
1823 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
1825 while (aptr < eiptr){
1827 IncreaseBuf(Target, 1, -1);
1828 eptr = Target->buf + Target->BufSize - 3;
1829 bptr = Target->buf + Target->BufUsed;
1836 Target->BufUsed += 2;
1837 } else if (*aptr == '\\') {
1842 Target->BufUsed += 2;
1852 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
1854 return Target->BufUsed;
1858 * @ingroup StrBuf_DeEnCoder
1859 * @brief Append a string, escaping characters which have meaning in HTML + json.
1861 * @param Target target buffer
1862 * @param Source source buffer; set to NULL if you just have a C-String
1863 * @param PlainIn Plain-C string to append; set to NULL if unused
1864 * @param nbsp If nonzero, spaces are converted to non-breaking spaces.
1865 * @param nolinebreaks if set to 1, linebreaks are removed from the string.
1866 * if set to 2, linebreaks are replaced by <br/>
1868 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
1870 const char *aptr, *eiptr;
1873 int IsUtf8Sequence = 0;
1875 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1878 if (PlainIn != NULL) {
1880 len = strlen(PlainIn);
1885 eiptr = aptr + Source->BufUsed;
1886 len = Source->BufUsed;
1892 bptr = Target->buf + Target->BufUsed;
1893 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1895 while (aptr < eiptr){
1897 IncreaseBuf(Target, 1, -1);
1898 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1899 bptr = Target->buf + Target->BufUsed;
1902 memcpy(bptr, "<", 4);
1904 Target->BufUsed += 4;
1906 else if (*aptr == '>') {
1907 memcpy(bptr, ">", 4);
1909 Target->BufUsed += 4;
1911 else if (*aptr == '&') {
1912 memcpy(bptr, "&", 5);
1914 Target->BufUsed += 5;
1916 else if (*aptr == LB) {
1921 else if (*aptr == RB) {
1926 else if ((*aptr == 32) && (nbsp == 1)) {
1927 memcpy(bptr, " ", 6);
1929 Target->BufUsed += 6;
1931 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1932 *bptr='\0'; /* nothing */
1934 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1935 memcpy(bptr, "<br/>", 11);
1937 Target->BufUsed += 11;
1940 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1941 *bptr='\0'; /* nothing */
1944 else if ((*aptr == '"') || (*aptr == QU)) {
1949 Target->BufUsed += 2;
1950 } else if (*aptr == '\\') {
1955 Target->BufUsed += 2;
1958 if (((unsigned char)*aptr) >= 0x20)
1960 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
1964 while (IsUtf8Sequence > 1){
1965 if(bptr + IsUtf8Sequence >= eptr) {
1966 IncreaseBuf(Target, 1, -1);
1967 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1968 bptr = Target->buf + Target->BufUsed - 1;
1982 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1984 return Target->BufUsed;
1988 * @ingroup StrBuf_DeEnCoder
1989 * @brief unhide special chars hidden to the HTML escaper
1990 * @param target buffer to put the unescaped string in
1991 * @param source buffer to unescape
1993 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1999 FlushStrBuf(target);
2001 if (source == NULL ||target == NULL)
2006 len = source->BufUsed;
2007 for (a = 0; a < len; ++a) {
2008 if (target->BufUsed >= target->BufSize)
2009 IncreaseBuf(target, 1, -1);
2011 if (source->buf[a] == '=') {
2012 hex[0] = source->buf[a + 1];
2013 hex[1] = source->buf[a + 2];
2016 sscanf(hex, "%02x", &b);
2017 target->buf[target->BufUsed] = b;
2018 target->buf[++target->BufUsed] = 0;
2022 target->buf[target->BufUsed] = source->buf[a];
2023 target->buf[++target->BufUsed] = 0;
2030 * @ingroup StrBuf_DeEnCoder
2031 * @brief hide special chars from the HTML escapers and friends
2032 * @param target buffer to put the escaped string in
2033 * @param source buffer to escape
2035 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2040 FlushStrBuf(target);
2042 if (source == NULL ||target == NULL)
2047 len = source->BufUsed;
2048 for (i=0; i<len; ++i) {
2049 if (target->BufUsed + 4 >= target->BufSize)
2050 IncreaseBuf(target, 1, -1);
2051 if ( (isalnum(source->buf[i])) ||
2052 (source->buf[i]=='-') ||
2053 (source->buf[i]=='_') ) {
2054 target->buf[target->BufUsed++] = source->buf[i];
2057 sprintf(&target->buf[target->BufUsed],
2059 (0xFF &source->buf[i]));
2060 target->BufUsed += 3;
2063 target->buf[target->BufUsed + 1] = '\0';
2067 /*******************************************************************************
2068 * Quoted Printable de/encoding *
2069 *******************************************************************************/
2072 * @ingroup StrBuf_DeEnCoder
2073 * @brief decode a buffer from base 64 encoding; destroys original
2074 * @param Buf Buffor to transform
2076 int StrBufDecodeBase64(StrBuf *Buf)
2080 if (Buf == NULL) return -1;
2082 xferbuf = (char*) malloc(Buf->BufSize);
2083 siz = CtdlDecodeBase64(xferbuf,
2093 * @ingroup StrBuf_DeEnCoder
2094 * @brief decode a buffer from base 64 encoding; destroys original
2095 * @param Buf Buffor to transform
2097 int StrBufDecodeHex(StrBuf *Buf)
2100 char *pch, *pche, *pchi;
2102 if (Buf == NULL) return -1;
2104 pch = pchi = Buf->buf;
2105 pche = pch + Buf->BufUsed;
2107 while (pchi < pche){
2108 ch = decode_hex(pchi);
2115 Buf->BufUsed = pch - Buf->buf;
2116 return Buf->BufUsed;
2120 * @ingroup StrBuf_DeEnCoder
2121 * @brief replace all chars >0x20 && < 0x7F with Mute
2122 * @param Mute char to put over invalid chars
2123 * @param Buf Buffor to transform
2125 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2129 if (Buf == NULL) return -1;
2130 pch = (unsigned char *)Buf->buf;
2131 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2132 if ((*pch < 0x20) || (*pch > 0x7F))
2136 return Buf->BufUsed;
2141 * @ingroup StrBuf_DeEnCoder
2142 * @brief remove escaped strings from i.e. the url string (like %20 for blanks)
2143 * @param Buf Buffer to translate
2144 * @param StripBlanks Reduce several blanks to one?
2146 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2152 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2153 Buf->buf[Buf->BufUsed - 1] = '\0';
2158 while (a < Buf->BufUsed) {
2159 if (Buf->buf[a] == '+')
2161 else if (Buf->buf[a] == '%') {
2162 /* don't let % chars through, rather truncate the input. */
2163 if (a + 2 > Buf->BufUsed) {
2168 hex[0] = Buf->buf[a + 1];
2169 hex[1] = Buf->buf[a + 2];
2172 sscanf(hex, "%02x", &b);
2173 Buf->buf[a] = (char) b;
2174 len = Buf->BufUsed - a - 2;
2176 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2188 * @ingroup StrBuf_DeEnCoder
2189 * @brief RFC2047-encode a header field if necessary.
2190 * If no non-ASCII characters are found, the string
2191 * will be copied verbatim without encoding.
2193 * @param target Target buffer.
2194 * @param source Source string to be encoded.
2195 * @returns encoded length; -1 if non success.
2197 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2199 const char headerStr[] = "=?UTF-8?Q?";
2200 int need_to_encode = 0;
2204 if ((source == NULL) ||
2208 while ((i < source->BufUsed) &&
2209 (!IsEmptyStr (&source->buf[i])) &&
2210 (need_to_encode == 0)) {
2211 if (((unsigned char) source->buf[i] < 32) ||
2212 ((unsigned char) source->buf[i] > 126)) {
2218 if (!need_to_encode) {
2219 if (*target == NULL) {
2220 *target = NewStrBufPlain(source->buf, source->BufUsed);
2223 FlushStrBuf(*target);
2224 StrBufAppendBuf(*target, source, 0);
2226 return (*target)->BufUsed;
2228 if (*target == NULL)
2229 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2230 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2231 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2232 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2233 (*target)->BufUsed = sizeof(headerStr) - 1;
2234 for (i=0; (i < source->BufUsed); ++i) {
2235 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2236 IncreaseBuf(*target, 1, 0);
2237 ch = (unsigned char) source->buf[i];
2238 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2239 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2240 (*target)->BufUsed += 3;
2243 (*target)->buf[(*target)->BufUsed] = ch;
2244 (*target)->BufUsed++;
2248 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2249 IncreaseBuf(*target, 1, 0);
2251 (*target)->buf[(*target)->BufUsed++] = '?';
2252 (*target)->buf[(*target)->BufUsed++] = '=';
2253 (*target)->buf[(*target)->BufUsed] = '\0';
2254 return (*target)->BufUsed;;
2259 * @brief replaces all occurances of 'search' by 'replace'
2260 * @param buf Buffer to modify
2261 * @param search character to search
2262 * @param replace character to replace search by
2264 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2269 for (i=0; i<buf->BufUsed; i++)
2270 if (buf->buf[i] == search)
2271 buf->buf[i] = replace;
2276 /*******************************************************************************
2277 * Iconv Wrapper; RFC822 de/encoding *
2278 *******************************************************************************/
2281 * @ingroup StrBuf_DeEnCoder
2282 * @brief Wrapper around iconv_open()
2283 * Our version adds aliases for non-standard Microsoft charsets
2284 * such as 'MS950', aliasing them to names like 'CP950'
2286 * @param tocode Target encoding
2287 * @param fromcode Source encoding
2288 * @param pic anonimized pointer to iconv struct
2290 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2293 iconv_t ic = (iconv_t)(-1) ;
2294 ic = iconv_open(tocode, fromcode);
2295 if (ic == (iconv_t)(-1) ) {
2296 char alias_fromcode[64];
2297 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2298 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2299 alias_fromcode[0] = 'C';
2300 alias_fromcode[1] = 'P';
2301 ic = iconv_open(tocode, alias_fromcode);
2304 *(iconv_t *)pic = ic;
2310 * @ingroup StrBuf_DeEnCoder
2311 * @brief find one chunk of a RFC822 encoded string
2312 * @param Buffer where to search
2313 * @param bptr where to start searching
2314 * @returns found position, NULL if none.
2316 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2319 /* Find the next ?Q? */
2320 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2323 end = strchr(bptr + 2, '?');
2328 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2329 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2330 (*(end + 2) == '?')) {
2331 /* skip on to the end of the cluster, the next ?= */
2332 end = strstr(end + 3, "?=");
2335 /* sort of half valid encoding, try to find an end. */
2336 end = strstr(bptr, "?=");
2342 * @brief swaps the contents of two StrBufs
2343 * this is to be used to have cheap switched between a work-buffer and a target buffer
2344 * @param A First one
2345 * @param B second one
2347 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2351 memcpy(&C, A, sizeof(*A));
2352 memcpy(A, B, sizeof(*B));
2353 memcpy(B, &C, sizeof(C));
2359 * @ingroup StrBuf_DeEnCoder
2360 * @brief convert one buffer according to the preselected iconv pointer PIC
2361 * @param ConvertBuf buffer we need to translate
2362 * @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
2363 * @param pic Pointer to the iconv-session Object
2365 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2371 char *ibuf; /**< Buffer of characters to be converted */
2372 char *obuf; /**< Buffer for converted characters */
2373 size_t ibuflen; /**< Length of input buffer */
2374 size_t obuflen; /**< Length of output buffer */
2377 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2378 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2379 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2381 ic = *(iconv_t*)pic;
2382 ibuf = ConvertBuf->buf;
2383 ibuflen = ConvertBuf->BufUsed;
2385 obuflen = TmpBuf->BufSize;
2387 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2390 if (errno == E2BIG) {
2392 IncreaseBuf(TmpBuf, 0, 0);
2397 else if (errno == EILSEQ){
2398 /* hm, invalid utf8 sequence... what to do now? */
2399 /* An invalid multibyte sequence has been encountered in the input */
2401 else if (errno == EINVAL) {
2402 /* An incomplete multibyte sequence has been encountered in the input. */
2405 FlushStrBuf(TmpBuf);
2408 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2409 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2411 /* little card game: wheres the red lady? */
2412 SwapBuffers(ConvertBuf, TmpBuf);
2413 FlushStrBuf(TmpBuf);
2420 * @ingroup StrBuf_DeEnCoder
2421 * @brief catches one RFC822 encoded segment, and decodes it.
2422 * @param Target buffer to fill with result
2423 * @param DecodeMe buffer with stuff to process
2424 * @param SegmentStart points to our current segment in DecodeMe
2425 * @param SegmentEnd Points to the end of our current segment in DecodeMe
2426 * @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
2427 * @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
2428 * @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
2430 inline static void DecodeSegment(StrBuf *Target,
2431 const StrBuf *DecodeMe,
2435 StrBuf *ConvertBuf2,
2436 StrBuf *FoundCharset)
2442 iconv_t ic = (iconv_t)(-1);
2446 /* Now we handle foreign character sets properly encoded
2447 * in RFC2047 format.
2449 StaticBuf.buf = SegmentStart;
2450 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2451 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2452 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2453 if (FoundCharset != NULL) {
2454 FlushStrBuf(FoundCharset);
2455 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2457 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2458 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2460 *encoding = toupper(*encoding);
2461 if (*encoding == 'B') { /**< base64 */
2462 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2464 ConvertBuf->BufUsed);
2466 else if (*encoding == 'Q') { /**< quoted-printable */
2470 while (pos < ConvertBuf->BufUsed)
2472 if (ConvertBuf->buf[pos] == '_')
2473 ConvertBuf->buf[pos] = ' ';
2477 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2480 ConvertBuf->BufUsed);
2483 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2486 ctdl_iconv_open("UTF-8", charset, &ic);
2487 if (ic != (iconv_t)(-1) ) {
2489 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2490 StrBufAppendBuf(Target, ConvertBuf2, 0);
2495 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2501 * @ingroup StrBuf_DeEnCoder
2502 * @brief Handle subjects with RFC2047 encoding such as:
2503 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2504 * @param Target where to put the decoded string to
2505 * @param DecodeMe buffer with encoded string
2506 * @param DefaultCharset if we don't find one, which should we use?
2507 * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
2508 * put it here for later use where no string might be known.
2510 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2512 StrBuf *DecodedInvalidBuf = NULL;
2513 StrBuf *ConvertBuf, *ConvertBuf2;
2514 const StrBuf *DecodeMee = DecodeMe;
2515 char *start, *end, *next, *nextend, *ptr = NULL;
2517 iconv_t ic = (iconv_t)(-1) ;
2522 int illegal_non_rfc2047_encoding = 0;
2524 /* Sometimes, badly formed messages contain strings which were simply
2525 * written out directly in some foreign character set instead of
2526 * using RFC2047 encoding. This is illegal but we will attempt to
2527 * handle it anyway by converting from a user-specified default
2528 * charset to UTF-8 if we see any nonprintable characters.
2531 len = StrLength(DecodeMe);
2532 for (i=0; i<DecodeMe->BufUsed; ++i) {
2533 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2534 illegal_non_rfc2047_encoding = 1;
2539 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2540 if ((illegal_non_rfc2047_encoding) &&
2541 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2542 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2545 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2546 if (ic != (iconv_t)(-1) ) {
2547 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
2548 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
2549 DecodeMee = DecodedInvalidBuf;
2555 /* pre evaluate the first pair */
2556 nextend = end = NULL;
2557 len = StrLength(DecodeMee);
2558 start = strstr(DecodeMee->buf, "=?");
2559 eptr = DecodeMee->buf + DecodeMee->BufUsed;
2561 end = FindNextEnd (DecodeMee, start);
2563 StrBufAppendBuf(Target, DecodeMee, 0);
2564 FreeStrBuf(&ConvertBuf);
2565 FreeStrBuf(&DecodedInvalidBuf);
2569 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
2571 if (start != DecodeMee->buf) {
2574 nFront = start - DecodeMee->buf;
2575 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
2579 * Since spammers will go to all sorts of absurd lengths to get their
2580 * messages through, there are LOTS of corrupt headers out there.
2581 * So, prevent a really badly formed RFC2047 header from throwing
2582 * this function into an infinite loop.
2584 while ((start != NULL) &&
2591 DecodeSegment(Target,
2599 next = strstr(end, "=?");
2601 if ((next != NULL) &&
2603 nextend = FindNextEnd(DecodeMee, next);
2604 if (nextend == NULL)
2607 /* did we find two partitions */
2608 if ((next != NULL) &&
2612 while ((ptr < next) &&
2618 /* did we find a gab just filled with blanks? */
2621 long gap = next - start;
2626 /* now terminate the gab at the end */
2627 delta = (next - end) - 2; ////TODO: const!
2628 ((StrBuf*)DecodeMee)->BufUsed -= delta;
2629 ((StrBuf*)DecodeMee)->buf[DecodeMee->BufUsed] = '\0';
2631 /* move next to its new location. */
2636 /* our next-pair is our new first pair now. */
2642 nextend = DecodeMee->buf + DecodeMee->BufUsed;
2643 if ((end != NULL) && (end < nextend)) {
2645 while ( (ptr < nextend) &&
2652 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2654 FreeStrBuf(&ConvertBuf);
2655 FreeStrBuf(&ConvertBuf2);
2656 FreeStrBuf(&DecodedInvalidBuf);
2659 /*******************************************************************************
2660 * Manipulating UTF-8 Strings *
2661 *******************************************************************************/
2665 * @brief evaluate the length of an utf8 special character sequence
2666 * @param Char the character to examine
2667 * @returns width of utf8 chars in bytes
2669 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
2674 while ((n < 8) && ((test & *CharS) != 0)) {
2678 if ((n > 6) || ((CharE - CharS) < n))
2685 * @brief detect whether this char starts an utf-8 encoded char
2686 * @param Char character to inspect
2687 * @returns yes or no
2689 static inline int Ctdl_IsUtf8SequenceStart(const char Char)
2691 /** 11??.???? indicates an UTF8 Sequence. */
2692 return ((Char & 0xC0) != 0);
2697 * @brief measure the number of glyphs in an UTF8 string...
2698 * @param Buf string to measure
2699 * @returns the number of glyphs in Buf
2701 long StrBuf_Utf8StrLen(StrBuf *Buf)
2707 if ((Buf == NULL) || (Buf->BufUsed == 0))
2710 eptr = Buf->buf + Buf->BufUsed;
2711 while ((aptr < eptr) && (*aptr != '\0')) {
2712 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2713 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2714 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
2727 * @brief cuts a string after maxlen glyphs
2728 * @param Buf string to cut to maxlen glyphs
2729 * @param maxlen how long may the string become?
2730 * @returns current length of the string
2732 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2738 eptr = Buf->buf + Buf->BufUsed;
2739 while ((aptr < eptr) && (*aptr != '\0')) {
2740 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2741 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2742 while ((*aptr++ != '\0') && (m-- > 0));
2751 Buf->BufUsed = aptr - Buf->buf;
2752 return Buf->BufUsed;
2755 return Buf->BufUsed;
2763 /*******************************************************************************
2765 *******************************************************************************/
2768 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2769 #define OS_CODE 0x03 /*< unix */
2772 * @ingroup StrBuf_DeEnCoder
2773 * @brief uses the same calling syntax as compress2(), but it
2774 * creates a stream compatible with HTTP "Content-encoding: gzip"
2775 * @param dest compressed buffer
2776 * @param destLen length of the compresed data
2777 * @param source source to encode
2778 * @param sourceLen length of source to encode
2779 * @param level compression level
2781 int ZEXPORT compress_gzip(Bytef * dest,
2783 const Bytef * source,
2787 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2789 /* write gzip header */
2790 snprintf((char *) dest, *destLen,
2791 "%c%c%c%c%c%c%c%c%c%c",
2792 gz_magic[0], gz_magic[1], Z_DEFLATED,
2793 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2796 /* normal deflate */
2799 stream.next_in = (Bytef *) source;
2800 stream.avail_in = (uInt) sourceLen;
2801 stream.next_out = dest + 10L; // after header
2802 stream.avail_out = (uInt) * destLen;
2803 if ((uLong) stream.avail_out != *destLen)
2806 stream.zalloc = (alloc_func) 0;
2807 stream.zfree = (free_func) 0;
2808 stream.opaque = (voidpf) 0;
2810 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2811 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2815 err = deflate(&stream, Z_FINISH);
2816 if (err != Z_STREAM_END) {
2817 deflateEnd(&stream);
2818 return err == Z_OK ? Z_BUF_ERROR : err;
2820 *destLen = stream.total_out + 10L;
2822 /* write CRC and Length */
2823 uLong crc = crc32(0L, source, sourceLen);
2825 for (n = 0; n < 4; ++n, ++*destLen) {
2826 dest[*destLen] = (int) (crc & 0xff);
2829 uLong len = stream.total_in;
2830 for (n = 0; n < 4; ++n, ++*destLen) {
2831 dest[*destLen] = (int) (len & 0xff);
2834 err = deflateEnd(&stream);
2841 * @ingroup StrBuf_DeEnCoder
2842 * @brief compress the buffer with gzip
2843 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2844 * @param Buf buffer whose content is to be gzipped
2846 int CompressBuffer(StrBuf *Buf)
2849 char *compressed_data = NULL;
2850 size_t compressed_len, bufsize;
2853 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2854 compressed_data = malloc(compressed_len);
2856 if (compressed_data == NULL)
2858 /* Flush some space after the used payload so valgrind shuts up... */
2859 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2860 Buf->buf[Buf->BufUsed + i++] = '\0';
2861 if (compress_gzip((Bytef *) compressed_data,
2864 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2867 Buf->buf = compressed_data;
2868 Buf->BufUsed = compressed_len;
2869 Buf->BufSize = bufsize;
2870 /* Flush some space after the used payload so valgrind shuts up... */
2872 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2873 Buf->buf[Buf->BufUsed + i++] = '\0';
2876 free(compressed_data);
2878 #endif /* HAVE_ZLIB */
2884 /*******************************************************************************
2885 * File I/O; Prefer buffered read since its faster! *
2886 *******************************************************************************/
2889 * @ingroup StrBuf_IO
2890 * @brief Read a line from socket
2891 * flushes and closes the FD on error
2892 * @param buf the buffer to get the input to
2893 * @param fd pointer to the filedescriptor to read
2894 * @param append Append to an existing string or replace?
2895 * @param Error strerror() on error
2896 * @returns numbers of chars read
2898 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
2900 int len, rlen, slen;
2905 slen = len = buf->BufUsed;
2907 rlen = read(*fd, &buf->buf[len], 1);
2909 *Error = strerror(errno);
2916 if (buf->buf[len] == '\n')
2918 if (buf->buf[len] != '\r')
2920 if (len + 2 >= buf->BufSize) {
2922 buf->buf[len+1] = '\0';
2923 IncreaseBuf(buf, 1, -1);
2927 buf->buf[len] = '\0';
2932 * @ingroup StrBuf_BufferedIO
2933 * @brief Read a line from socket
2934 * flushes and closes the FD on error
2935 * @param Line the line to read from the fd / I/O Buffer
2936 * @param buf the buffer to get the input to
2937 * @param fd pointer to the filedescriptor to read
2938 * @param timeout number of successless selects until we bail out
2939 * @param selectresolution how long to wait on each select
2940 * @param Error strerror() on error
2941 * @returns numbers of chars read
2943 int StrBufTCP_read_buffered_line(StrBuf *Line,
2947 int selectresolution,
2951 int nSuccessLess = 0;
2958 if (buf->BufUsed > 0) {
2959 pch = strchr(buf->buf, '\n');
2962 len = pch - buf->buf;
2963 if (len > 0 && (*(pch - 1) == '\r') )
2965 StrBufSub(Line, buf, 0, len - rlen);
2966 StrBufCutLeft(buf, len + 1);
2971 if (buf->BufSize - buf->BufUsed < 10)
2972 IncreaseBuf(buf, 1, -1);
2974 fdflags = fcntl(*fd, F_GETFL);
2975 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
2977 while ((nSuccessLess < timeout) && (pch == NULL)) {
2979 tv.tv_sec = selectresolution;
2984 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
2985 *Error = strerror(errno);
2991 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
2996 &buf->buf[buf->BufUsed],
2997 buf->BufSize - buf->BufUsed - 1);
2999 *Error = strerror(errno);
3004 else if (rlen > 0) {
3006 buf->BufUsed += rlen;
3007 buf->buf[buf->BufUsed] = '\0';
3008 if (buf->BufUsed + 10 > buf->BufSize) {
3009 IncreaseBuf(buf, 1, -1);
3011 pch = strchr(buf->buf, '\n');
3018 len = pch - buf->buf;
3019 if (len > 0 && (*(pch - 1) == '\r') )
3021 StrBufSub(Line, buf, 0, len - rlen);
3022 StrBufCutLeft(buf, len + 1);
3029 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
3030 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
3031 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
3033 * @ingroup StrBuf_BufferedIO
3034 * @brief Read a line from socket
3035 * flushes and closes the FD on error
3036 * @param Line Line to read from the fd / I/O Buffer
3037 * @param IOBuf the buffer to get the input to
3038 * @param Pos pointer to the current read position, should be NULL initialized!
3039 * @param fd pointer to the filedescriptor to read
3040 * @param timeout number of successless selects until we bail out
3041 * @param selectresolution how long to wait on each select
3042 * @param Error strerror() on error
3043 * @returns numbers of chars read
3045 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
3050 int selectresolution,
3053 const char *pche = NULL;
3054 const char *pos = NULL;
3056 int nSuccessLess = 0;
3058 const char *pch = NULL;
3063 if ((Line == NULL) ||
3070 *Error = ErrRBLF_PreConditionFailed;
3075 if ((IOBuf->BufUsed > 0) &&
3077 (pos < IOBuf->buf + IOBuf->BufUsed))
3079 pche = IOBuf->buf + IOBuf->BufUsed;
3081 while ((pch < pche) && (*pch != '\n'))
3083 if ((pch >= pche) || (*pch == '\0'))
3085 if ((pch != NULL) &&
3090 if (len > 0 && (*(pch - 1) == '\r') )
3092 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
3102 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
3106 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
3107 IncreaseBuf(IOBuf, 1, -1);
3111 fdflags = fcntl(*fd, F_GETFL);
3112 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3115 while ((nSuccessLess < timeout) &&
3125 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
3126 *Error = strerror(errno);
3130 *Error = ErrRBLF_SelectFailed;
3133 if (! FD_ISSET(*fd, &rfds) != 0) {
3139 &IOBuf->buf[IOBuf->BufUsed],
3140 IOBuf->BufSize - IOBuf->BufUsed - 1);
3142 *Error = strerror(errno);
3147 else if (rlen > 0) {
3149 IOBuf->BufUsed += rlen;
3150 IOBuf->buf[IOBuf->BufUsed] = '\0';
3151 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
3152 IncreaseBuf(IOBuf, 1, -1);
3156 pche = IOBuf->buf + IOBuf->BufUsed;
3158 while ((pch < pche) && (*pch != '\n'))
3160 if ((pch >= pche) || (*pch == '\0'))
3169 if (len > 0 && (*(pch - 1) == '\r') )
3171 StrBufSub(Line, IOBuf, 0, len - rlen);
3172 *Pos = pos + len + 1;
3175 *Error = ErrRBLF_NotEnoughSentFromServer;
3180 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
3182 * @ingroup StrBuf_IO
3183 * @brief Input binary data from socket
3184 * flushes and closes the FD on error
3185 * @param Buf the buffer to get the input to
3186 * @param fd pointer to the filedescriptor to read
3187 * @param append Append to an existing string or replace?
3188 * @param nBytes the maximal number of bytes to read
3189 * @param Error strerror() on error
3190 * @returns numbers of chars read
3192 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
3195 int len, rlen, slen;
3203 if ((Buf == NULL) || (*fd == -1))
3205 *Error = ErrRBLF_BLOBPreConditionFailed;
3210 if (Buf->BufUsed + nBytes >= Buf->BufSize)
3211 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
3213 ptr = Buf->buf + Buf->BufUsed;
3215 slen = len = Buf->BufUsed;
3217 fdflags = fcntl(*fd, F_GETFL);
3218 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3220 while ((nRead < nBytes) &&
3230 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3231 *Error = strerror(errno);
3235 *Error = ErrRBLF_SelectFailed;
3238 if (! FD_ISSET(*fd, &rfds) != 0) {
3244 if ((rlen = read(*fd,
3246 nBytes - nRead)) == -1) {
3249 *Error = strerror(errno);
3254 Buf->BufUsed += rlen;
3256 Buf->buf[Buf->BufUsed] = '\0';
3260 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
3261 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
3263 * @ingroup StrBuf_BufferedIO
3264 * @brief Input binary data from socket
3265 * flushes and closes the FD on error
3266 * @param Blob put binary thing here
3267 * @param IOBuf the buffer to get the input to
3268 * @param Pos offset inside of IOBuf
3269 * @param fd pointer to the filedescriptor to read
3270 * @param append Append to an existing string or replace?
3271 * @param nBytes the maximal number of bytes to read
3272 * @param check whether we should search for '000\n' terminators in case of timeouts
3273 * @param Error strerror() on error
3274 * @returns numbers of chars read
3276 int StrBufReadBLOBBuffered(StrBuf *Blob,
3293 int nAlreadyRead = 0;
3301 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
3305 *Error = ErrRBB_BLOBFPreConditionFailed;
3311 if (Blob->BufUsed + nBytes >= Blob->BufSize)
3312 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
3317 len = pos - IOBuf->buf;
3318 rlen = IOBuf->BufUsed - len;
3321 if ((IOBuf->BufUsed > 0) &&
3323 (pos < IOBuf->buf + IOBuf->BufUsed))
3325 pche = IOBuf->buf + IOBuf->BufUsed;
3328 if (rlen < nBytes) {
3329 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
3330 Blob->BufUsed += rlen;
3331 Blob->buf[Blob->BufUsed] = '\0';
3332 nAlreadyRead = nRead = rlen;
3335 if (rlen >= nBytes) {
3336 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
3337 Blob->BufUsed += nBytes;
3338 Blob->buf[Blob->BufUsed] = '\0';
3339 if (rlen == nBytes) {
3351 if (IOBuf->BufSize < nBytes - nRead)
3352 IncreaseBuf(IOBuf, 0, nBytes - nRead);
3355 slen = len = Blob->BufUsed;
3357 fdflags = fcntl(*fd, F_GETFL);
3358 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
3363 while ((nRead < nBytes) &&
3372 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3373 *Error = strerror(errno);
3377 *Error = ErrRBLF_SelectFailed;
3380 if (! FD_ISSET(*fd, &rfds) != 0) {
3392 *Error = strerror(errno);
3395 else if (rlen == 0){
3397 if ((check == NNN_TERM) &&
3399 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
3401 StrBufPlain(Blob, HKEY("\n000\n"));
3402 StrBufCutRight(Blob, 5);
3403 return Blob->BufUsed;
3405 if (nSelects > 10) {
3407 *Error = ErrRBB_too_many_selects;
3411 else if (rlen > 0) {
3414 IOBuf->BufUsed += rlen;
3417 if (nRead > nBytes) {
3418 *Pos = IOBuf->buf + nBytes;
3420 Blob->buf[Blob->BufUsed] = '\0';
3421 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
3425 return nRead + nAlreadyRead;
3429 * @ingroup StrBuf_IO
3430 * @brief extract a "next line" from Buf; Ptr to persist across several iterations
3431 * @param LineBuf your line will be copied here.
3432 * @param Buf BLOB with lines of text...
3433 * @param Ptr moved arround to keep the next-line across several iterations
3434 * has to be &NULL on start; will be &NotNULL on end of buffer
3435 * @returns size of copied buffer
3437 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
3439 const char *aptr, *ptr, *eptr;
3442 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL)) {
3443 *Ptr = StrBufNOTNULL;
3447 FlushStrBuf(LineBuf);
3449 ptr = aptr = Buf->buf;
3453 optr = LineBuf->buf;
3454 eptr = Buf->buf + Buf->BufUsed;
3455 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3457 while ((ptr <= eptr) &&
3464 LineBuf->BufUsed = optr - LineBuf->buf;
3465 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3466 optr = LineBuf->buf + LineBuf->BufUsed;
3467 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3471 if ((ptr >= eptr) && (optr > LineBuf->buf))
3473 LineBuf->BufUsed = optr - LineBuf->buf;
3475 if ((ptr <= eptr) && (*ptr == '\r'))
3477 if ((ptr <= eptr) && (*ptr == '\n'))
3484 *Ptr = StrBufNOTNULL;
3487 return Buf->BufUsed - (ptr - Buf->buf);
3492 * @ingroup StrBuf_IO
3493 * @brief removes double slashes from pathnames
3494 * @param Dir directory string to filter
3495 * @param RemoveTrailingSlash allows / disallows trailing slashes
3497 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
3503 while (!IsEmptyStr(a)) {
3515 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
3520 Dir->BufUsed = b - Dir->buf;