1 // Copyright (c) 1987-2024 by the citadel.org team
3 // This program is open source software. Use, duplication, or disclosure is subject to the GNU General Public License, version 3.
13 #include <sys/select.h>
15 #include <sys/types.h>
16 #define SHOW_ME_VAPPEND_PRINTF
19 #include "libcitadel.h"
35 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen, const Bytef * source, uLong sourceLen, int level);
37 int BaseStrBufSize = 64;
39 int ZLibCompressionRatio = -1; // defaults to 6
41 #define DEF_MEM_LEVEL 8 // memlevel???
42 #define OS_CODE 0x03 // unix
43 const int gz_magic[2] = { 0x1f, 0x8b }; // gzip magic header
46 const char *StrBufNOTNULL = ((char*) NULL) - 1;
48 const char HexList[256][3] = {
49 "00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
50 "10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
51 "20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
52 "30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
53 "40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
54 "50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
55 "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
56 "70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
57 "80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
58 "90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
59 "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
60 "B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
61 "C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
62 "D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
63 "E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
64 "F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};
67 // Private Structure for the Stringbuffer
69 char *buf; // the pointer to the dynamic buffer
70 long BufSize; // how many spcae do we optain
71 long BufUsed; // Number of Chars used excluding the trailing \\0
72 int ConstBuf; // are we just a wrapper arround a static buffer and musn't we be changed?
74 long nIncreases; // for profiling; cound how many times we needed more
75 char bt [SIZ]; // Stacktrace of last increase
76 char bt_lastinc[SIZ]; // How much did we increase last time?
81 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
82 static inline int Ctdl_IsUtf8SequenceStart(const char Char);
86 static void StrBufBacktrace(StrBuf *Buf, int which) {
89 void *stack_frames[50];
94 pstart = pch = Buf->bt;
97 pstart = pch = Buf->bt_lastinc;
99 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
100 strings = backtrace_symbols(stack_frames, size);
101 for (i = 0; i < size; i++) {
102 if (strings != NULL) {
103 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
106 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
115 void dbg_FreeStrBuf(StrBuf *FreeMe, char *FromWhere) {
116 if (hFreeDbglog == -1) {
117 pid_t pid = getpid();
119 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
120 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
122 if ((*FreeMe)->nIncreases > 0) {
125 n = snprintf(buf, SIZ * 3, "%c+|%ld|%ld|%ld|%s|%s|\n",
127 (*FreeMe)->nIncreases,
131 (*FreeMe)->bt_lastinc
133 n = write(hFreeDbglog, buf, n);
138 n = snprintf(buf, 128, "%c_|0|%ld%ld|\n",
143 n = write(hFreeDbglog, buf, n);
148 void dbg_IncreaseBuf(StrBuf *IncMe) {
150 #ifdef HAVE_BACKTRACE
151 StrBufBacktrace(Buf, 1);
156 void dbg_Init(StrBuf *Buf) {
159 Buf->bt_lastinc[0] = '\0';
160 #ifdef HAVE_BACKTRACE
161 StrBufBacktrace(Buf, 0);
167 #define dbg_FreeStrBuf(a, b)
168 #define dbg_IncreaseBuf(a)
173 // swaps the contents of two StrBufs
174 // this is to be used to have cheap switched between a work-buffer and a target buffer
177 static inline void iSwapBuffers(StrBuf *A, StrBuf *B) {
180 memcpy(&C, A, sizeof(*A));
181 memcpy(A, B, sizeof(*B));
182 memcpy(B, &C, sizeof(C));
187 void SwapBuffers(StrBuf *A, StrBuf *B) {
192 // Cast operator to Plain String
193 // note: if the buffer is altered by StrBuf operations, this pointer may become
194 // invalid. So don't lean on it after altering the buffer!
195 // Since this operation is considered cheap, rather call it often than risking
196 // your pointer to become invalid!
197 // Str the string we want to get the c-string representation for
198 // returns the Pointer to the Content. Don't mess with it!
199 inline const char *ChrPtr(const StrBuf *Str) {
206 // since we know strlen()'s result, provide it here.
207 // Str the string to return the length to
208 // returns contentlength of the buffer
209 inline int StrLength(const StrBuf *Str) {
210 return (Str != NULL) ? Str->BufUsed : 0;
214 // local utility function to resize the buffer
215 // Buf the buffer whichs storage we should increase
216 // KeepOriginal should we copy the original buffer or just start over with a new one
217 // DestSize what should fit in after?
218 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize) {
220 size_t NewSize = Buf->BufSize * 2;
227 while ((NewSize <= DestSize) && (NewSize != 0)) {
236 NewBuf = (char*) malloc(NewSize);
237 if (NewBuf == NULL) {
241 if (KeepOriginal && (Buf->BufUsed > 0)) {
242 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
250 Buf->BufSize = NewSize;
252 dbg_IncreaseBuf(Buf);
258 // shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
259 // Buf Buffer to shrink (has to be empty)
260 // ThreshHold if the buffer is bigger then this, its readjusted
261 // NewSize if we Shrink it, how big are we going to be afterwards?
262 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize) {
263 if ((Buf != NULL) && (Buf->BufUsed == 0) && (Buf->BufSize < ThreshHold)) {
265 Buf->buf = (char*) malloc(NewSize);
267 Buf->BufSize = NewSize;
272 // shrink long term buffers to their real size so they don't waste memory
273 // Buf buffer to shrink
274 // Force if not set, will just executed if the buffer is much to big; set for lifetime strings
275 // returns physical size of the buffer
276 long StrBufShrinkToFit(StrBuf *Buf, int Force) {
279 if (Force || (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize)) {
282 TmpBuf = (char*) malloc(Buf->BufUsed + 1);
286 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
287 Buf->BufSize = Buf->BufUsed + 1;
295 // Allocate a new buffer with default buffer size
296 // returns the new stringbuffer
297 StrBuf *NewStrBuf(void) {
300 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
304 NewBuf->buf = (char*) malloc(BaseStrBufSize);
305 if (NewBuf->buf == NULL) {
309 NewBuf->buf[0] = '\0';
310 NewBuf->BufSize = BaseStrBufSize;
312 NewBuf->ConstBuf = 0;
319 // Copy Constructor; returns a duplicate of CopyMe
320 // CopyMe Buffer to faxmilate
321 // returns the new stringbuffer
322 StrBuf *NewStrBufDup(const StrBuf *CopyMe) {
328 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
332 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
333 if (NewBuf->buf == NULL) {
338 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
339 NewBuf->BufUsed = CopyMe->BufUsed;
340 NewBuf->BufSize = CopyMe->BufSize;
341 NewBuf->ConstBuf = 0;
349 // Copy Constructor; CreateRelpaceMe will contain CopyFlushMe afterwards.
350 // NoMe if non-NULL, we will use that buffer as value; KeepOriginal will abused as len.
351 // CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
352 // CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe
353 // KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
354 // returns the new stringbuffer
355 void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, const char *NoMe, int KeepOriginal) {
358 if (CreateRelpaceMe == NULL)
362 if (*CreateRelpaceMe != NULL)
363 StrBufPlain(*CreateRelpaceMe, NoMe, KeepOriginal);
365 *CreateRelpaceMe = NewStrBufPlain(NoMe, KeepOriginal);
369 if (CopyFlushMe == NULL) {
370 if (*CreateRelpaceMe != NULL)
371 FlushStrBuf(*CreateRelpaceMe);
373 *CreateRelpaceMe = NewStrBuf();
377 // Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
378 // else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
379 // be a big IO-Buffer...
380 if (KeepOriginal || (StrLength(CopyFlushMe) < 256)) {
381 if (*CreateRelpaceMe == NULL) {
382 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
386 NewBuf = *CreateRelpaceMe;
389 StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
392 if (*CreateRelpaceMe == NULL) {
393 *CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
397 NewBuf = *CreateRelpaceMe;
399 iSwapBuffers (NewBuf, CopyFlushMe);
402 FlushStrBuf(CopyFlushMe);
408 // create a new Buffer using an existing c-string
409 // this function should also be used if you want to pre-suggest
410 // the buffer size to allocate in conjunction with ptr == NULL
411 // ptr the c-string to copy; may be NULL to create a blank instance
412 // nChars How many chars should we copy; -1 if we should measure the length ourselves
413 // returns the new stringbuffer
414 StrBuf *NewStrBufPlain(const char* ptr, int nChars) {
416 size_t Siz = BaseStrBufSize;
419 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
424 CopySize = strlen((ptr != NULL)?ptr:"");
428 while ((Siz <= CopySize) && (Siz != 0))
436 NewBuf->buf = (char*) malloc(Siz);
437 if (NewBuf->buf == NULL) {
441 NewBuf->BufSize = Siz;
443 memcpy(NewBuf->buf, ptr, CopySize);
444 NewBuf->buf[CopySize] = '\0';
445 NewBuf->BufUsed = CopySize;
448 NewBuf->buf[0] = '\0';
451 NewBuf->ConstBuf = 0;
460 // Set an existing buffer from a c-string
461 // Buf buffer to load
462 // ptr c-string to put into
463 // nChars set to -1 if we should work 0-terminated
464 // @returns the new length of the string
466 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars) {
480 CopySize = strlen(ptr);
484 while ((Siz <= CopySize) && (Siz != 0))
492 if (Siz != Buf->BufSize)
493 IncreaseBuf(Buf, 0, Siz);
494 memcpy(Buf->buf, ptr, CopySize);
495 Buf->buf[CopySize] = '\0';
496 Buf->BufUsed = CopySize;
503 // use strbuf as wrapper for a string constant for easy handling
504 // StringConstant a string to wrap
505 // SizeOfStrConstant should be sizeof(StringConstant)-1
507 StrBuf *_NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant) {
510 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
513 NewBuf->buf = (char*) StringConstant;
514 NewBuf->BufSize = SizeOfStrConstant;
515 NewBuf->BufUsed = SizeOfStrConstant;
516 NewBuf->ConstBuf = 1;
525 // flush the content of a Buf; keep its struct
526 // buf Buffer to flush
528 int FlushStrBuf(StrBuf *buf) {
529 if ((buf == NULL) || (buf->buf == NULL)) {
541 // wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
542 // buf Buffer to wipe
544 int FLUSHStrBuf(StrBuf *buf) {
549 if (buf->BufUsed > 0) {
550 memset(buf->buf, 0, buf->BufUsed);
557 int hFreeDbglog = -1;
561 // Its a double pointer, so it can NULL your pointer
562 // so fancy SIG11 appear instead of random results
563 // FreeMe Pointer Pointer to the buffer to free
565 void FreeStrBuf (StrBuf **FreeMe) {
569 dbg_FreeStrBuf(FreeMe, 'F');
571 if (!(*FreeMe)->ConstBuf)
572 free((*FreeMe)->buf);
578 // flatten a Buffer to the Char * we return
579 // Its a double pointer, so it can NULL your pointer
580 // so fancy SIG11 appear instead of random results
581 // The Callee then owns the buffer and is responsible for freeing it.
582 // SmashMe Pointer Pointer to the buffer to release Buf from and free
583 // @returns the pointer of the buffer; Callee owns the memory thereafter.
585 char *SmashStrBuf (StrBuf **SmashMe) {
588 if ((SmashMe == NULL) || (*SmashMe == NULL))
591 dbg_FreeStrBuf(SmashMe, 'S');
593 Ret = (*SmashMe)->buf;
600 // Release the buffer
601 // If you want put your StrBuf into a Hash, use this as Destructor.
602 // VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
603 void HFreeStrBuf (void *VFreeMe) {
604 StrBuf *FreeMe = (StrBuf*)VFreeMe;
608 dbg_FreeStrBuf(SmashMe, 'H');
610 if (!FreeMe->ConstBuf)
616 //******************************************************************************
617 // Simple string transformations *
618 //******************************************************************************/
620 // Wrapper around atol
621 long StrTol(const StrBuf *Buf) {
625 return atol(Buf->buf);
631 // Wrapper around atoi
632 int StrToi(const StrBuf *Buf) {
635 if (Buf->BufUsed > 0)
636 return atoi(Buf->buf);
642 // Checks to see if the string is a pure number
643 // Buf The buffer to inspect
644 // returns 1 if its a pure number, 0, if not.
645 int StrBufIsNumber(const StrBuf *Buf) {
647 if ((Buf == NULL) || (Buf->BufUsed == 0)) {
650 strtoll(Buf->buf, &pEnd, 10);
651 if (pEnd == Buf->buf)
653 if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
655 if (Buf->buf == pEnd)
661 // modifies a Single char of the Buf
662 // You can point to it via char* or a zero-based integer
663 // Buf The buffer to manipulate
664 // ptr char* to zero; use NULL if unused
665 // nThChar zero based pointer into the string; use -1 if unused
666 // PeekValue The Character to place into the position
667 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue) {
671 nThChar = ptr - Buf->buf;
672 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
674 Buf->buf[nThChar] = PeekValue;
679 // modifies a range of chars of the Buf
680 // You can point to it via char* or a zero-based integer
681 // Buf The buffer to manipulate
682 // ptr char* to zero; use NULL if unused
683 // nThChar zero based pointer into the string; use -1 if unused
684 // nChars how many chars are to be flushed?
685 // PookValue The Character to place into that area
686 long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue) {
690 nThChar = ptr - Buf->buf;
691 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
693 if (nThChar + nChars > Buf->BufUsed)
694 nChars = Buf->BufUsed - nThChar;
696 memset(Buf->buf + nThChar, PookValue, nChars);
697 // just to be sure...
698 Buf->buf[Buf->BufUsed] = 0;
703 // Append a StringBuffer to the buffer
704 // Buf Buffer to modify
705 // AppendBuf Buffer to copy at the end of our buffer
706 // Offset Should we start copying from an offset?
707 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset) {
708 if ((AppendBuf == NULL) || (AppendBuf->buf == NULL) || (Buf == NULL) || (Buf->buf == NULL)) {
712 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
713 IncreaseBuf(Buf, (Buf->BufUsed > 0), AppendBuf->BufUsed + Buf->BufUsed);
715 memcpy(Buf->buf + Buf->BufUsed, AppendBuf->buf + Offset, AppendBuf->BufUsed - Offset);
716 Buf->BufUsed += AppendBuf->BufUsed - Offset;
717 Buf->buf[Buf->BufUsed] = '\0';
721 // Append a C-String to the buffer
722 // Buf Buffer to modify
723 // AppendBuf Buffer to copy at the end of our buffer
724 // AppendSize number of bytes to copy; set to -1 if we should count it in advance
725 // Offset Should we start copying from an offset?
726 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset) {
728 long BufSizeRequired;
730 if ((AppendBuf == NULL) || (Buf == NULL))
733 if (AppendSize < 0) {
734 aps = strlen(AppendBuf + Offset);
737 aps = AppendSize - Offset;
740 BufSizeRequired = Buf->BufUsed + aps + 1;
741 if (Buf->BufSize <= BufSizeRequired) {
742 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
745 memcpy(Buf->buf + Buf->BufUsed, AppendBuf + Offset, aps);
747 Buf->buf[Buf->BufUsed] = '\0';
751 // sprintf like function appending the formated string to the buffer
752 // vsnprintf version to wrap into own calls
753 // Buf Buffer to extend by format and Params
754 // format printf alike format to add
755 // ap va_list containing the items for format
756 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap) {
763 if ((Buf == NULL) || (format == NULL))
766 BufSize = Buf->BufSize;
767 nWritten = Buf->BufSize + 1;
768 Offset = Buf->BufUsed;
769 newused = Offset + nWritten;
771 while (newused >= BufSize) {
773 nWritten = vsnprintf(Buf->buf + Offset, Buf->BufSize - Offset, format, apl);
775 newused = Offset + nWritten;
776 if (newused >= Buf->BufSize) {
777 if (IncreaseBuf(Buf, 1, newused) == -1)
778 return; // TODO: error handling?
779 newused = Buf->BufSize + 1;
782 Buf->BufUsed = Offset + nWritten;
783 BufSize = Buf->BufSize;
790 // sprintf like function appending the formated string to the buffer
791 // Buf Buffer to extend by format and Params
792 // format printf alike format to add
793 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...) {
800 if ((Buf == NULL) || (format == NULL))
803 BufSize = Buf->BufSize;
804 nWritten = Buf->BufSize + 1;
805 Offset = Buf->BufUsed;
806 newused = Offset + nWritten;
808 while (newused >= BufSize) {
809 va_start(arg_ptr, format);
810 nWritten = vsnprintf(Buf->buf + Buf->BufUsed, Buf->BufSize - Buf->BufUsed, format, arg_ptr);
812 newused = Buf->BufUsed + nWritten;
813 if (newused >= Buf->BufSize) {
814 if (IncreaseBuf(Buf, 1, newused) == -1)
815 return; // TODO: error handling?
816 newused = Buf->BufSize + 1;
819 Buf->BufUsed += nWritten;
820 BufSize = Buf->BufSize;
827 // sprintf like function putting the formated string into the buffer
828 // Buf Buffer to extend by format and Parameters
829 // format printf alike format to add
830 void StrBufPrintf(StrBuf *Buf, const char *format, ...) {
834 if ((Buf == NULL) || (format == NULL))
837 nWritten = Buf->BufSize + 1;
838 while (nWritten >= Buf->BufSize) {
839 va_start(arg_ptr, format);
840 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
842 if (nWritten >= Buf->BufSize) {
843 if (IncreaseBuf(Buf, 0, 0) == -1)
844 return; // TODO: error handling?
845 nWritten = Buf->BufSize + 1;
848 Buf->BufUsed = nWritten ;
853 // Callback for cURL to append the webserver reply to a buffer
854 // ptr, size, nmemb, and stream are pre-defined by the cURL API; see man 3 curl for more info
855 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream) {
863 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
868 // extracts a substring from Source into dest
869 // dest buffer to place substring into
870 // Source string to copy substring from
871 // Offset chars to skip from start
872 // nChars number of chars to copy
873 // returns the number of chars copied; may be different from nChars due to the size of Source
874 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars) {
876 if (Offset > Source->BufUsed) {
881 if (Offset + nChars < Source->BufUsed) {
882 if ((nChars >= dest->BufSize) && (IncreaseBuf(dest, 0, nChars + 1) == -1)) {
885 memcpy(dest->buf, Source->buf + Offset, nChars);
886 dest->BufUsed = nChars;
887 dest->buf[dest->BufUsed] = '\0';
890 NCharsRemain = Source->BufUsed - Offset;
891 if ((NCharsRemain >= dest->BufSize) && (IncreaseBuf(dest, 0, NCharsRemain + 1) == -1)) {
894 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
895 dest->BufUsed = NCharsRemain;
896 dest->buf[dest->BufUsed] = '\0';
900 // Cut nChars from the start of the string
901 // Buf Buffer to modify
902 // nChars how many chars should be skipped?
903 void StrBufCutLeft(StrBuf *Buf, int nChars) {
904 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
905 if (nChars >= Buf->BufUsed) {
909 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
910 Buf->BufUsed -= nChars;
911 Buf->buf[Buf->BufUsed] = '\0';
914 // Cut the trailing n Chars from the string
915 // Buf Buffer to modify
916 // nChars how many chars should be truncated?
917 void StrBufCutRight(StrBuf *Buf, int nChars) {
918 if ((Buf == NULL) || (Buf->BufUsed == 0) || (Buf->buf == NULL))
921 if (nChars >= Buf->BufUsed) {
925 Buf->BufUsed -= nChars;
926 Buf->buf[Buf->BufUsed] = '\0';
930 // Cut the string after n Chars
931 // Buf Buffer to modify
932 // AfternChars after how many chars should we truncate the string?
933 // At if non-null and points inside of our string, cut it there.
934 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At) {
935 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
937 AfternChars = At - Buf->buf;
940 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
942 Buf->BufUsed = AfternChars;
943 Buf->buf[Buf->BufUsed] = '\0';
947 // Strip leading and trailing spaces from a string; with premeasured and adjusted length.
948 // Buf the string to modify
949 void StrBufTrim(StrBuf *Buf) {
951 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
953 while ((Buf->BufUsed > 0) && isspace(Buf->buf[Buf->BufUsed - 1])) {
956 Buf->buf[Buf->BufUsed] = '\0';
958 if (Buf->BufUsed == 0) return;
960 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
963 if (delta > 0) StrBufCutLeft(Buf, delta);
967 // changes all spaces in the string (tab, linefeed...) to Blank (0x20)
968 // Buf the string to modify
969 void StrBufSpaceToBlank(StrBuf *Buf) {
972 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
975 pche = pch + Buf->BufUsed;
984 void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary) {
988 if ((Buf == NULL) || (Buf->buf == NULL)) {
992 pRight = strchr(Buf->buf, rightboundary);
993 if (pRight != NULL) {
994 StrBufCutAt(Buf, 0, pRight);
997 pLeft = strrchr(ChrPtr(Buf), leftboundary);
999 StrBufCutLeft(Buf, pLeft - Buf->buf + 1);
1004 // uppercase the contents of a buffer
1005 // Buf the buffer to translate
1006 void StrBufUpCase(StrBuf *Buf) {
1009 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1012 pche = pch + Buf->BufUsed;
1013 while (pch < pche) {
1014 *pch = toupper(*pch);
1020 // lowercase the contents of a buffer
1021 // Buf the buffer to translate
1022 void StrBufLowerCase(StrBuf *Buf) {
1025 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1028 pche = pch + Buf->BufUsed;
1029 while (pch < pche) {
1030 *pch = tolower(*pch);
1036 //******************************************************************************
1037 // a tokenizer that kills, maims, and destroys *
1038 //******************************************************************************/
1041 // Replace a token at a given place with a given length by another token with given length
1042 // Buf String where to work on
1043 // where where inside of the Buf is the search-token
1044 // HowLong How long is the token to be replaced
1045 // Repl Token to insert at 'where'
1046 // ReplLen Length of repl
1047 // @returns -1 if fail else length of resulting Buf
1049 int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong, const char *Repl, long ReplLen) {
1051 if ((Buf == NULL) || (where > Buf->BufUsed) || (where + HowLong > Buf->BufUsed)) {
1055 if (where + ReplLen - HowLong > Buf->BufSize) {
1056 if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0) {
1061 memmove(Buf->buf + where + ReplLen, Buf->buf + where + HowLong, Buf->BufUsed - where - HowLong);
1062 memcpy(Buf->buf + where, Repl, ReplLen);
1063 Buf->BufUsed += ReplLen - HowLong;
1064 Buf->buf[Buf->BufUsed] = 0;
1065 return Buf->BufUsed;
1069 int StrBufReplaceAllOccurrences(StrBuf *Buf, const char *fromstr, const char *tostr) {
1072 while (found = strstr(Buf->buf, fromstr), (found != NULL)) {
1073 StrBufReplaceToken(Buf, (found - Buf->buf), strlen(fromstr), tostr, strlen(tostr));
1076 return Buf->BufUsed;
1081 // Counts the numbmer of tokens in a buffer
1082 // source String to count tokens in
1083 // tok Tokenizer char to count
1084 // @returns numbers of tokenizer chars found
1085 int StrBufNum_tokens(const StrBuf *source, char tok) {
1088 if ((source == NULL) || (source->BufUsed == 0))
1090 if ((source->BufUsed == 1) && (*source->buf == tok))
1094 pche = pch + source->BufUsed;
1105 // a string tokenizer
1106 // Source StringBuffer to read into
1107 // parmnum n'th Parameter to remove
1108 // separator tokenizer character
1109 // @returns -1 if not found, else length of token.
1110 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator) {
1112 char *d, *s, *end; // dest, source
1115 // Find desired eter
1116 end = Source->buf + Source->BufUsed;
1118 while ((d <= end) && (count < parmnum)) {
1119 // End of string, bail!
1124 if (*d == separator) {
1129 if ((d == NULL) || (d >= end))
1130 return 0; // Parameter not found
1134 while ((s <= end) && (*s && *s != separator)) {
1137 if (*s == separator)
1146 memmove(d, s, Source->BufUsed - (s - Source->buf));
1147 Source->BufUsed += ReducedBy;
1148 Source->buf[Source->BufUsed] = '\0';
1150 else if (d == Source->buf) {
1152 Source->BufUsed = 0;
1156 Source->BufUsed += ReducedBy;
1167 int StrBufExtract_tokenFromStr(StrBuf *dest, const char *Source, long SourceLen, int parmnum, char separator) {
1168 const StrBuf Temp = {
1181 return StrBufExtract_token(dest, &Temp, parmnum, separator);
1184 // a string tokenizer
1185 // dest Destination StringBuffer
1186 // Source StringBuffer to read into
1187 // parmnum n'th Parameter to extract
1188 // separator tokenizer character
1189 // returns -1 if not found, else length of token.
1190 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator) {
1191 const char *s, *e; // source
1192 int len = 0; // running total length of extracted string
1193 int current_token = 0; // token currently being processed
1196 dest->buf[0] = '\0';
1202 if ((Source == NULL) || (Source->BufUsed ==0)) {
1206 e = s + Source->BufUsed;
1209 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1211 while ((s < e) && !IsEmptyStr(s)) {
1212 if (*s == separator) {
1215 if (len >= dest->BufSize) {
1216 dest->BufUsed = len;
1217 if (IncreaseBuf(dest, 1, -1) < 0) {
1222 if ( (current_token == parmnum) && (*s != separator)) {
1223 dest->buf[len] = *s;
1226 else if (current_token > parmnum) {
1232 dest->buf[len] = '\0';
1233 dest->BufUsed = len;
1235 if (current_token < parmnum) {
1236 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1239 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1244 // a string tokenizer to fetch an integer
1245 // Source String containing tokens
1246 // parmnum n'th Parameter to extract
1247 // separator tokenizer character
1248 // @returns 0 if not found, else integer representation of the token
1249 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator) {
1258 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1265 // a string tokenizer to fetch a long integer
1266 // Source String containing tokens
1267 // parmnum n'th Parameter to extract
1268 // separator tokenizer character
1269 // returns 0 if not found, else long integer representation of the token
1270 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator) {
1279 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1286 // a string tokenizer to fetch an unsigned long
1287 // Source String containing tokens
1288 // parmnum n'th Parameter to extract
1289 // separator tokenizer character
1290 // returns 0 if not found, else unsigned long representation of the token
1291 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator) {
1301 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1305 return (unsigned long) atol(pnum);
1312 // a string tokenizer; Bounds checker
1313 // function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1314 // Source our tokenbuffer
1315 // pStart the token iterator pointer to inspect
1316 // returns whether the revolving pointer is inside of the search range
1317 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart) {
1318 if ((Source == NULL) || (*pStart == StrBufNOTNULL) || (Source->BufUsed == 0)) {
1321 if (*pStart == NULL) {
1324 else if (*pStart > Source->buf + Source->BufUsed) {
1327 else if (*pStart <= Source->buf) {
1335 * a string tokenizer
1336 * dest Destination StringBuffer
1337 * Source StringBuffer to read into
1338 * pStart pointer to the end of the last token. Feed with NULL on start.
1339 * separator tokenizer
1340 * @returns -1 if not found, else length of token.
1342 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator) {
1343 const char *s; /* source */
1344 const char *EndBuffer; /* end stop of source buffer */
1345 int current_token = 0; /* token currently being processed */
1346 int len = 0; /* running total length of extracted string */
1348 if ((Source == NULL) || (Source->BufUsed == 0)) {
1349 *pStart = StrBufNOTNULL;
1356 EndBuffer = Source->buf + Source->BufUsed;
1359 dest->buf[0] = '\0';
1363 *pStart = EndBuffer + 1;
1367 if (*pStart == NULL) {
1368 *pStart = Source->buf; /* we're starting to examine this buffer. */
1370 else if ((*pStart < Source->buf) || (*pStart > EndBuffer ) ) {
1371 return -1; /* no more tokens to find. */
1375 /* start to find the next token */
1376 while ((s <= EndBuffer) && (current_token == 0) ) {
1377 if (*s == separator) {
1378 /* we found the next token */
1382 if (len >= dest->BufSize) {
1383 /* our Dest-buffer isn't big enough, increase it. */
1384 dest->BufUsed = len;
1386 if (IncreaseBuf(dest, 1, -1) < 0) {
1387 /* WHUT? no more mem? bail out. */
1394 if ( (current_token == 0 ) && /* are we in our target token? */
1395 (!IsEmptyStr(s) ) &&
1396 (separator != *s) ) /* don't copy the token itself */
1398 dest->buf[len] = *s; /* Copy the payload */
1399 ++len; /* remember the bigger size. */
1405 /* did we reach the end? */
1406 if ((s > EndBuffer)) {
1407 EndBuffer = StrBufNOTNULL;
1408 *pStart = EndBuffer;
1411 *pStart = s; /* remember the position for the next run */
1414 /* sanitize our extracted token */
1415 dest->buf[len] = '\0';
1416 dest->BufUsed = len;
1423 * a string tokenizer
1424 * Source StringBuffer to read from
1425 * pStart pointer to the end of the last token. Feed with NULL.
1426 * separator tokenizer character
1427 * nTokens number of tokens to fastforward over
1428 * @returns -1 if not found, else length of token.
1430 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens) {
1431 const char *s, *EndBuffer; //* source * /
1432 int len = 0; //* running total length of extracted string * /
1433 int current_token = 0; //* token currently being processed * /
1435 if ((Source == NULL) || (Source->BufUsed ==0)) {
1439 return Source->BufUsed;
1441 if (*pStart == NULL)
1442 *pStart = Source->buf;
1444 EndBuffer = Source->buf + Source->BufUsed;
1446 if ((*pStart < Source->buf) ||
1447 (*pStart > EndBuffer)) {
1453 while ((s < EndBuffer) && !IsEmptyStr(s)) {
1454 if (*s == separator) {
1457 if (current_token >= nTokens) {
1469 // a string tokenizer to fetch an integer
1470 // Source StringBuffer to read from
1471 // pStart Cursor on the tokenstring
1472 // separator tokenizer character
1473 // returns 0 if not found, else integer representation of the token
1474 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator) {
1483 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1490 // a string tokenizer to fetch a long integer
1491 // Source StringBuffer to read from
1492 // pStart Cursor on the tokenstring
1493 // separator tokenizer character
1494 // returns 0 if not found, else long integer representation of the token
1495 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator) {
1504 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1511 // a string tokenizer to fetch an unsigned long
1512 // Source StringBuffer to read from
1513 // pStart Cursor on the tokenstring
1514 // separator tokenizer character
1515 // returns 0 if not found, else unsigned long representation of the token
1516 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator) {
1526 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1530 return (unsigned long) atol(pnum);
1537 /*******************************************************************************
1538 * Escape Appending *
1539 *******************************************************************************/
1541 // Escape a string for feeding out as a URL while appending it to a Buffer
1542 // OutBuf the output buffer
1543 // In Buffer to encode
1544 // PlainIn way in from plain old c strings
1545 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1546 const char *pch, *pche;
1550 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) ) {
1553 if (PlainIn != NULL) {
1554 len = strlen(PlainIn);
1560 pche = pch + In->BufUsed;
1567 pt = OutBuf->buf + OutBuf->BufUsed;
1568 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1570 while (pch < pche) {
1572 IncreaseBuf(OutBuf, 1, -1);
1573 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1574 pt = OutBuf->buf + OutBuf->BufUsed;
1577 if((*pch >= 'a' && *pch <= 'z') ||
1578 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1579 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1580 (*pch == '!') || (*pch == '_') ||
1581 (*pch == ',') || (*pch == '.'))
1588 *(pt + 1) = HexList[(unsigned char)*pch][0];
1589 *(pt + 2) = HexList[(unsigned char)*pch][1];
1591 OutBuf->BufUsed += 3;
1599 // Escape a string for feeding out as a the username/password part of an URL while appending it to a Buffer
1600 // OutBuf the output buffer
1601 // In Buffer to encode
1602 // PlainIn way in from plain old c strings
1603 void StrBufUrlescUPAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1604 const char *pch, *pche;
1608 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1610 if (PlainIn != NULL) {
1611 len = strlen(PlainIn);
1617 pche = pch + In->BufUsed;
1624 pt = OutBuf->buf + OutBuf->BufUsed;
1625 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1627 while (pch < pche) {
1629 IncreaseBuf(OutBuf, 1, -1);
1630 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1631 pt = OutBuf->buf + OutBuf->BufUsed;
1634 if((*pch >= 'a' && *pch <= 'z') ||
1635 (*pch >= 'A' && *pch <= 'Z') || /* A-Z */
1636 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1637 (*pch == '!') || (*pch == '_') ||
1638 (*pch == ',') || (*pch == '.'))
1645 *(pt + 1) = HexList[(unsigned char)*pch][0];
1646 *(pt + 2) = HexList[(unsigned char)*pch][1];
1648 OutBuf->BufUsed += 3;
1656 // append a string with characters having a special meaning in xml encoded to the buffer
1657 // OutBuf the output buffer
1658 // In Buffer to encode
1659 // PlainIn way in from plain old c strings
1660 // PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
1661 // OverrideLowChars should chars < 0x20 be replaced by _ or escaped as xml entity?
1662 void StrBufXMLEscAppend(StrBuf *OutBuf,
1664 const char *PlainIn,
1666 int OverrideLowChars)
1668 const char *pch, *pche;
1673 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1675 if (PlainIn != NULL) {
1677 len = strlen((const char*)PlainIn);
1684 pch = (const char*)In->buf;
1685 pche = pch + In->BufUsed;
1692 pt = OutBuf->buf + OutBuf->BufUsed;
1693 /**< we max append 6 chars at once plus the \0 */
1694 pte = OutBuf->buf + OutBuf->BufSize - 6;
1696 while (pch < pche) {
1698 OutBuf->BufUsed = pt - OutBuf->buf;
1699 IncreaseBuf(OutBuf, 1, -1);
1700 pte = OutBuf->buf + OutBuf->BufSize - 6;
1701 /**< we max append 3 chars at once plus the \0 */
1703 pt = OutBuf->buf + OutBuf->BufUsed;
1707 memcpy(pt, HKEY("<"));
1711 else if (*pch == '>') {
1712 memcpy(pt, HKEY(">"));
1716 else if (*pch == '&') {
1717 memcpy(pt, HKEY("&"));
1721 else if ((*pch >= 0x20) && (*pch <= 0x7F)) {
1726 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(pch, pche);
1729 while ((IsUtf8Sequence > 0) &&
1742 *pt = HexList[*(unsigned char*)pch][0];
1744 *pt = HexList[*(unsigned char*)pch][1];
1753 OutBuf->BufUsed = pt - OutBuf->buf;
1758 * append a string in hex encoding to the buffer
1759 * OutBuf the output buffer
1760 * In Buffer to encode
1761 * PlainIn way in from plain old c strings
1762 * PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
1764 void StrBufHexEscAppend(StrBuf *OutBuf, const StrBuf *In, const unsigned char *PlainIn, long PlainInLen) {
1765 const unsigned char *pch, *pche;
1769 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1771 if (PlainIn != NULL) {
1773 len = strlen((const char*)PlainIn);
1780 pch = (const unsigned char*)In->buf;
1781 pche = pch + In->BufUsed;
1788 pt = OutBuf->buf + OutBuf->BufUsed;
1789 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1791 while (pch < pche) {
1793 IncreaseBuf(OutBuf, 1, -1);
1794 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1795 pt = OutBuf->buf + OutBuf->BufUsed;
1798 *pt = HexList[*pch][0];
1800 *pt = HexList[*pch][1];
1801 pt ++; pch ++; OutBuf->BufUsed += 2;
1807 void StrBufBase64Append(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn, long PlainInLen, int linebreaks) {
1813 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1815 if (PlainIn != NULL) {
1817 len = strlen(PlainIn);
1830 ExpectLen = ((len * 134) / 100) + OutBuf->BufUsed;
1832 if (ExpectLen > OutBuf->BufSize)
1833 if (IncreaseBuf(OutBuf, 1, ExpectLen) < ExpectLen)
1836 pt = OutBuf->buf + OutBuf->BufUsed;
1838 len = CtdlEncodeBase64(pt, pch, len, linebreaks);
1841 OutBuf->BufUsed += len;
1846 // append a string in hex encoding to the buffer
1847 // OutBuf the output buffer
1848 // In Buffer to encode
1849 // PlainIn way in from plain old c strings
1850 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1851 StrBufHexEscAppend(OutBuf, In, (const unsigned char*) PlainIn, -1);
1855 * Append a string, escaping characters which have meaning in HTML.
1857 * Target target buffer
1858 * Source source buffer; set to NULL if you just have a C-String
1859 * PlainIn Plain-C string to append; set to NULL if unused
1860 * nbsp If nonzero, spaces are converted to non-breaking spaces.
1861 * nolinebreaks if set to 1, linebreaks are removed from the string.
1862 * if set to 2, linebreaks are replaced by <br/>
1864 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks) {
1865 const char *aptr, *eiptr;
1869 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1872 if (PlainIn != NULL) {
1874 len = strlen(PlainIn);
1879 eiptr = aptr + Source->BufUsed;
1880 len = Source->BufUsed;
1886 bptr = Target->buf + Target->BufUsed;
1887 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1889 while (aptr < eiptr){
1891 IncreaseBuf(Target, 1, -1);
1892 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1893 bptr = Target->buf + Target->BufUsed;
1896 memcpy(bptr, "<", 4);
1898 Target->BufUsed += 4;
1900 else if (*aptr == '>') {
1901 memcpy(bptr, ">", 4);
1903 Target->BufUsed += 4;
1905 else if (*aptr == '&') {
1906 memcpy(bptr, "&", 5);
1908 Target->BufUsed += 5;
1910 else if (*aptr == '"') {
1911 memcpy(bptr, """, 6);
1913 Target->BufUsed += 6;
1915 else if (*aptr == '\'') {
1916 memcpy(bptr, "'", 5);
1918 Target->BufUsed += 5;
1920 else if (*aptr == LB) {
1925 else if (*aptr == RB) {
1930 else if (*aptr == QU) {
1935 else if ((*aptr == 32) && (nbsp == 1)) {
1936 memcpy(bptr, " ", 6);
1938 Target->BufUsed += 6;
1940 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1941 *bptr='\0'; /* nothing */
1943 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1944 memcpy(bptr, "<br/>", 11);
1946 Target->BufUsed += 11;
1950 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1951 *bptr='\0'; /* nothing */
1961 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1963 return Target->BufUsed;
1967 * Append a string, escaping characters which have meaning in HTML.
1968 * Converts linebreaks into blanks; escapes single quotes
1969 * Target target buffer
1970 * Source source buffer; set to NULL if you just have a C-String
1971 * PlainIn Plain-C string to append; set to NULL if unused
1973 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
1974 const char *aptr, *eiptr;
1978 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1981 if (PlainIn != NULL) {
1983 len = strlen(PlainIn);
1988 eiptr = aptr + Source->BufUsed;
1989 len = Source->BufUsed;
1995 eptr = Target->buf + Target->BufSize - 8;
1996 tptr = Target->buf + Target->BufUsed;
1998 while (aptr < eiptr){
2000 IncreaseBuf(Target, 1, -1);
2001 eptr = Target->buf + Target->BufSize - 8;
2002 tptr = Target->buf + Target->BufUsed;
2005 if (*aptr == '\n') {
2009 else if (*aptr == '\r') {
2013 else if (*aptr == '\'') {
2019 Target->BufUsed += 5;
2032 * Append a string, escaping characters which have meaning in ICAL.
2034 * Target target buffer
2035 * Source source buffer; set to NULL if you just have a C-String
2036 * PlainIn Plain-C string to append; set to NULL if unused
2038 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
2039 const char *aptr, *eiptr;
2043 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2046 if (PlainIn != NULL) {
2048 len = strlen(PlainIn);
2053 eiptr = aptr + Source->BufUsed;
2054 len = Source->BufUsed;
2060 eptr = Target->buf + Target->BufSize - 8;
2061 tptr = Target->buf + Target->BufUsed;
2063 while (aptr < eiptr){
2064 if(tptr + 3 >= eptr) {
2065 IncreaseBuf(Target, 1, -1);
2066 eptr = Target->buf + Target->BufSize - 8;
2067 tptr = Target->buf + Target->BufUsed;
2070 if (*aptr == '\n') {
2077 else if (*aptr == '\r') {
2084 else if (*aptr == ',') {
2100 * Append a string, escaping characters which have meaning in JavaScript strings .
2102 * Target target buffer
2103 * Source source buffer; set to NULL if you just have a C-String
2104 * PlainIn Plain-C string to append; set to NULL if unused
2105 * @returns size of result or -1
2107 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
2108 const char *aptr, *eiptr;
2113 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2116 if (PlainIn != NULL) {
2118 len = strlen(PlainIn);
2123 eiptr = aptr + Source->BufUsed;
2124 len = Source->BufUsed;
2130 bptr = Target->buf + Target->BufUsed;
2131 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2133 while (aptr < eiptr){
2135 IncreaseBuf(Target, 1, -1);
2136 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2137 bptr = Target->buf + Target->BufUsed;
2141 memcpy(bptr, HKEY("\\n"));
2143 Target->BufUsed += 2;
2146 memcpy(bptr, HKEY("\\r"));
2148 Target->BufUsed += 2;
2155 Target->BufUsed += 2;
2158 if ((*(aptr + 1) == 'u') &&
2159 isxdigit(*(aptr + 2)) &&
2160 isxdigit(*(aptr + 3)) &&
2161 isxdigit(*(aptr + 4)) &&
2162 isxdigit(*(aptr + 5)))
2163 { /* oh, a unicode escaper. let it pass through. */
2164 memcpy(bptr, aptr, 6);
2167 Target->BufUsed += 6;
2175 Target->BufUsed += 2;
2183 Target->BufUsed += 2;
2190 Target->BufUsed += 2;
2197 Target->BufUsed += 2;
2200 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2201 while (IsUtf8Sequence > 0){
2204 if (--IsUtf8Sequence)
2212 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2214 return Target->BufUsed;
2217 // Append a string, escaping characters which have meaning in HTML + json.
2219 // Target target buffer
2220 // Source source buffer; set to NULL if you just have a C-String
2221 // PlainIn Plain-C string to append; set to NULL if unused
2222 // nbsp If nonzero, spaces are converted to non-breaking spaces.
2223 // nolinebreaks if set to 1, linebreaks are removed from the string.
2224 // if set to 2, linebreaks are replaced by <br/>
2225 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks) {
2226 const char *aptr, *eiptr;
2229 int IsUtf8Sequence = 0;
2231 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL)) {
2234 if (PlainIn != NULL) {
2236 len = strlen(PlainIn);
2241 eiptr = aptr + Source->BufUsed;
2242 len = Source->BufUsed;
2249 bptr = Target->buf + Target->BufUsed;
2250 eptr = Target->buf + Target->BufSize - 11; // our biggest unit to put in...
2252 while (aptr < eiptr) {
2254 IncreaseBuf(Target, 1, -1);
2255 eptr = Target->buf + Target->BufSize - 11; // our biggest unit to put in...
2256 bptr = Target->buf + Target->BufUsed;
2260 memcpy(bptr, HKEY("<"));
2262 Target->BufUsed += 4;
2265 memcpy(bptr, HKEY(">"));
2267 Target->BufUsed += 4;
2270 memcpy(bptr, HKEY("&"));
2272 Target->BufUsed += 5;
2285 switch (nolinebreaks) {
2287 *bptr='\0'; /* nothing */
2290 memcpy(bptr, HKEY("<br/>"));
2292 Target->BufUsed += 11;
2295 memcpy(bptr, HKEY("\\n"));
2297 Target->BufUsed += 2;
2301 switch (nolinebreaks) {
2304 *bptr='\0'; /* nothing */
2307 memcpy(bptr, HKEY("\\r"));
2309 Target->BufUsed += 2;
2319 Target->BufUsed += 2;
2322 if ((*(aptr + 1) == 'u') &&
2323 isxdigit(*(aptr + 2)) &&
2324 isxdigit(*(aptr + 3)) &&
2325 isxdigit(*(aptr + 4)) &&
2326 isxdigit(*(aptr + 5)))
2327 { /* oh, a unicode escaper. let it pass through. */
2328 memcpy(bptr, aptr, 6);
2331 Target->BufUsed += 6;
2338 Target->BufUsed += 2;
2346 Target->BufUsed += 2;
2353 Target->BufUsed += 2;
2360 Target->BufUsed += 2;
2364 memcpy(bptr, HKEY(" "));
2366 Target->BufUsed += 6;
2370 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2371 while (IsUtf8Sequence > 0){
2374 if (--IsUtf8Sequence)
2382 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2384 return Target->BufUsed;
2389 * replace all non-Ascii characters by another
2390 * Buf buffer to inspect
2391 * repl charater to stamp over non ascii chars
2393 void StrBufAsciify(StrBuf *Buf, const char repl) {
2396 for (offset = 0; offset < Buf->BufUsed; offset ++)
2397 if (!isascii(Buf->buf[offset]))
2398 Buf->buf[offset] = repl;
2403 // unhide special chars hidden to the HTML escaper
2404 // target buffer to put the unescaped string in
2405 // source buffer to unescape
2406 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) {
2410 if ((source == NULL) || (target == NULL) || (target->buf == NULL)) {
2415 FlushStrBuf(target);
2417 len = source->BufUsed;
2418 for (a = 0; a < len; ++a) {
2419 if (target->BufUsed >= target->BufSize)
2420 IncreaseBuf(target, 1, -1);
2422 if (source->buf[a] == '=') {
2423 hex[0] = source->buf[a + 1];
2424 hex[1] = source->buf[a + 2];
2427 sscanf(hex, "%02x", &b);
2428 target->buf[target->BufUsed] = b;
2429 target->buf[++target->BufUsed] = 0;
2433 target->buf[target->BufUsed] = source->buf[a];
2434 target->buf[++target->BufUsed] = 0;
2441 * hide special chars from the HTML escapers and friends
2442 * target buffer to put the escaped string in
2443 * source buffer to escape
2445 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) {
2449 FlushStrBuf(target);
2451 if ((source == NULL) || (target == NULL) || (target->buf == NULL)) {
2455 len = source->BufUsed;
2456 for (i=0; i<len; ++i) {
2457 if (target->BufUsed + 4 >= target->BufSize)
2458 IncreaseBuf(target, 1, -1);
2459 if ( (isalnum(source->buf[i])) ||
2460 (source->buf[i]=='-') ||
2461 (source->buf[i]=='_') ) {
2462 target->buf[target->BufUsed++] = source->buf[i];
2465 sprintf(&target->buf[target->BufUsed],
2467 (0xFF &source->buf[i]));
2468 target->BufUsed += 3;
2471 target->buf[target->BufUsed + 1] = '\0';
2475 /*******************************************************************************
2476 * Quoted Printable de/encoding *
2477 *******************************************************************************/
2480 * decode a buffer from base 64 encoding; destroys original
2481 * Buf Buffor to transform
2483 int StrBufDecodeBase64(StrBuf *Buf) {
2491 xferbuf = (char*) malloc(Buf->BufSize);
2492 if (xferbuf == NULL)
2496 siz = CtdlDecodeBase64(xferbuf, Buf->buf, Buf->BufUsed);
2501 Buf->buf[Buf->BufUsed] = '\0';
2507 * decode a buffer from base 64 encoding; expects targetbuffer
2508 * BufIn Buffor to transform
2509 * BufOut Buffer to put result into
2511 int StrBufDecodeBase64To(const StrBuf *BufIn, StrBuf *BufOut) {
2512 if ((BufIn == NULL) || (BufOut == NULL))
2515 if (BufOut->BufSize < BufIn->BufUsed) {
2516 IncreaseBuf(BufOut, 0, BufIn->BufUsed);
2519 BufOut->BufUsed = CtdlDecodeBase64(BufOut->buf, BufIn->buf, BufIn->BufUsed);
2520 return BufOut->BufUsed;
2523 typedef struct __z_enc_stream {
2529 vStreamT *StrBufNewStreamContext(eStreamType type, const char **Err) {
2536 z_enc_stream *stream;
2539 stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
2540 memset(stream, 0, sizeof(z_enc_stream));
2541 stream->OutBuf.BufSize = 4*SIZ; /// TODO 64
2542 stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
2544 err = inflateInit(&stream->zstream);
2547 StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
2551 return (vStreamT*) stream;
2556 z_enc_stream *stream;
2559 stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
2560 memset(stream, 0, sizeof(z_enc_stream));
2561 stream->OutBuf.BufSize = 4*SIZ; /// todo 64
2562 stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
2563 /* write gzip header */
2564 stream->OutBuf.BufUsed = snprintf
2565 (stream->OutBuf.buf,
2566 stream->OutBuf.BufSize,
2567 "%c%c%c%c%c%c%c%c%c%c",
2568 gz_magic[0], gz_magic[1], Z_DEFLATED,
2569 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2572 err = deflateInit2(&stream->zstream,
2573 ZLibCompressionRatio,
2577 Z_DEFAULT_STRATEGY);
2579 StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
2583 return (vStreamT*) stream;
2594 int StrBufDestroyStreamContext(eStreamType type, vStreamT **vStream, const char **Err) {
2599 if ((vStream == NULL) || (*vStream==NULL)) {
2600 *Err = strerror(EINVAL);
2605 //case eBase64Encode:
2606 //case eBase64Decode:
2612 z_enc_stream *stream = (z_enc_stream *)*vStream;
2613 (void)inflateEnd(&stream->zstream);
2614 free(stream->OutBuf.buf);
2619 z_enc_stream *stream = (z_enc_stream *)*vStream;
2620 err = deflateEnd(&stream->zstream);
2625 free(stream->OutBuf.buf);
2636 int StrBufStreamTranscode(eStreamType type, IOBuffer *Target, IOBuffer *In, const char* pIn, long pInLen, vStreamT *vStream, int LastChunk, const char **Err) {
2640 //case eBase64Encode:
2645 //case eBase64Decode:
2652 z_enc_stream *stream = (z_enc_stream *)vStream;
2653 int org_outbuf_len = stream->OutBuf.BufUsed;
2655 unsigned int chunkavail;
2657 if (In->ReadWritePointer != NULL)
2659 stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
2660 stream->zstream.avail_in = (uInt) In->Buf->BufUsed -
2661 (In->ReadWritePointer - In->Buf->buf);
2665 stream->zstream.next_in = (Bytef *) In->Buf->buf;
2666 stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
2669 stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
2670 stream->zstream.avail_out = chunkavail = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
2672 err = deflate(&stream->zstream, (LastChunk) ? Z_FINISH : Z_NO_FLUSH);
2674 stream->OutBuf.BufUsed += (chunkavail - stream->zstream.avail_out);
2676 if (Target && (LastChunk || (stream->OutBuf.BufUsed != org_outbuf_len))) {
2677 iSwapBuffers(Target->Buf, &stream->OutBuf);
2680 if (stream->zstream.avail_in == 0) {
2681 FlushStrBuf(In->Buf);
2682 In->ReadWritePointer = NULL;
2685 if (stream->zstream.avail_in < 64) {
2686 memmove(In->Buf->buf,
2687 In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
2688 stream->zstream.avail_in);
2690 In->Buf->BufUsed = stream->zstream.avail_in;
2691 In->Buf->buf[In->Buf->BufUsed] = '\0';
2694 In->ReadWritePointer = In->Buf->buf + (In->Buf->BufUsed - stream->zstream.avail_in);
2697 rc = (LastChunk && (err != Z_FINISH));
2698 if (!rc && (err != Z_OK)) {
2705 z_enc_stream *stream = (z_enc_stream *)vStream;
2706 int org_outbuf_len = stream->zstream.total_out;
2709 if ((stream->zstream.avail_out != 0) && (stream->zstream.next_in != NULL)) {
2710 if (In->ReadWritePointer != NULL) {
2711 stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
2712 stream->zstream.avail_in = (uInt) In->Buf->BufUsed - (In->ReadWritePointer - In->Buf->buf);
2715 stream->zstream.next_in = (Bytef *) In->Buf->buf;
2716 stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
2720 stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
2721 stream->zstream.avail_out = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
2723 err = inflate(&stream->zstream, Z_NO_FLUSH);
2725 ///assert(ret != Z_STREAM_ERROR); /* state not clobbered * /
2728 err = Z_DATA_ERROR; /* and fall through */
2733 (void)inflateEnd(&stream->zstream);
2737 stream->OutBuf.BufUsed += stream->zstream.total_out + org_outbuf_len;
2739 if (Target) iSwapBuffers(Target->Buf, &stream->OutBuf);
2741 if (stream->zstream.avail_in == 0) {
2742 FlushStrBuf(In->Buf);
2743 In->ReadWritePointer = NULL;
2746 if (stream->zstream.avail_in < 64) {
2747 memmove(In->Buf->buf,
2748 In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
2749 stream->zstream.avail_in);
2751 In->Buf->BufUsed = stream->zstream.avail_in;
2752 In->Buf->buf[In->Buf->BufUsed] = '\0';
2756 In->ReadWritePointer = In->Buf->buf + (In->Buf->BufUsed - stream->zstream.avail_in);
2770 * decode a buffer from base 64 encoding; destroys original
2771 * Buf Buffor to transform
2773 int StrBufDecodeHex(StrBuf *Buf) {
2775 char *pch, *pche, *pchi;
2777 if (Buf == NULL) return -1;
2779 pch = pchi = Buf->buf;
2780 pche = pch + Buf->BufUsed;
2782 while (pchi < pche){
2783 ch = decode_hex(pchi);
2790 Buf->BufUsed = pch - Buf->buf;
2791 return Buf->BufUsed;
2795 * replace all chars >0x20 && < 0x7F with Mute
2796 * Mute char to put over invalid chars
2797 * Buf Buffor to transform
2799 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute) {
2802 if (Buf == NULL) return -1;
2803 pch = (unsigned char *)Buf->buf;
2804 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2805 if ((*pch < 0x20) || (*pch > 0x7F))
2809 return Buf->BufUsed;
2814 * remove escaped strings from i.e. the url string (like %20 for blanks)
2815 * Buf Buffer to translate
2816 * StripBlanks Reduce several blanks to one?
2818 long StrBufUnescape(StrBuf *Buf, int StripBlanks) {
2826 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2827 Buf->buf[Buf->BufUsed - 1] = '\0';
2832 while (a < Buf->BufUsed) {
2833 if (Buf->buf[a] == '+')
2835 else if (Buf->buf[a] == '%') {
2836 /* don't let % chars through, rather truncate the input. */
2837 if (a + 2 > Buf->BufUsed) {
2842 hex[0] = Buf->buf[a + 1];
2843 hex[1] = Buf->buf[a + 2];
2846 sscanf(hex, "%02x", &b);
2847 Buf->buf[a] = (char) b;
2848 len = Buf->BufUsed - a - 2;
2850 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2862 * RFC2047-encode a header field if necessary.
2863 * If no non-ASCII characters are found, the string
2864 * will be copied verbatim without encoding.
2866 * target Target buffer.
2867 * source Source string to be encoded.
2868 * @returns encoded length; -1 if non success.
2870 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source) {
2871 const char headerStr[] = "=?UTF-8?Q?";
2872 int need_to_encode = 0;
2876 if ((source == NULL) ||
2880 while ((i < source->BufUsed) &&
2881 (!IsEmptyStr (&source->buf[i])) &&
2882 (need_to_encode == 0)) {
2883 if (((unsigned char) source->buf[i] < 32) ||
2884 ((unsigned char) source->buf[i] > 126)) {
2890 if (!need_to_encode) {
2891 if (*target == NULL) {
2892 *target = NewStrBufPlain(source->buf, source->BufUsed);
2895 FlushStrBuf(*target);
2896 StrBufAppendBuf(*target, source, 0);
2899 return (*target)->BufUsed;
2903 if (*target == NULL)
2904 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2905 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2906 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2907 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2908 (*target)->BufUsed = sizeof(headerStr) - 1;
2909 for (i=0; (i < source->BufUsed); ++i) {
2910 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2911 IncreaseBuf(*target, 1, 0);
2912 ch = (unsigned char) source->buf[i];
2921 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2922 (*target)->BufUsed += 3;
2926 (*target)->buf[(*target)->BufUsed] = '_';
2928 (*target)->buf[(*target)->BufUsed] = ch;
2929 (*target)->BufUsed++;
2933 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2934 IncreaseBuf(*target, 1, 0);
2936 (*target)->buf[(*target)->BufUsed++] = '?';
2937 (*target)->buf[(*target)->BufUsed++] = '=';
2938 (*target)->buf[(*target)->BufUsed] = '\0';
2939 return (*target)->BufUsed;;
2942 // Quoted-Printable encode a message; make it < 80 columns width.
2943 // source Source string to be encoded.
2944 // returns buffer with encoded message.
2945 StrBuf *StrBufQuotedPrintableEncode(const StrBuf *EncodeMe) {
2948 const char *ptr, *eptr;
2952 OutBuf = NewStrBufPlain(NULL, StrLength(EncodeMe) * 4);
2954 OEptr = OutBuf->buf + OutBuf->BufSize;
2955 ptr = EncodeMe->buf;
2956 eptr = EncodeMe->buf + EncodeMe->BufUsed;
2959 while (ptr < eptr) {
2960 if (Optr + 4 >= OEptr) {
2962 Offset = Optr - OutBuf->buf;
2963 OutBuf->BufUsed = Optr - OutBuf->buf;
2964 IncreaseBuf(OutBuf, 1, 0);
2965 Optr = OutBuf->buf + Offset;
2966 OEptr = OutBuf->buf + OutBuf->BufSize;
2968 if (*ptr == '\r') { // ignore carriage returns
2971 else if (*ptr == '\n') { // hard line break
2972 memcpy(Optr, HKEY("=0A"));
2977 else if (( (*ptr >= 32) && (*ptr <= 60) ) || ( (*ptr >= 62) && (*ptr <= 126) )) {
2987 *Optr = HexList[ch][0];
2989 *Optr = HexList[ch][1];
2995 if (LinePos > 72) { // soft line break
2996 if (isspace(*(Optr - 1))) {
3001 *Optr = HexList[ch][0];
3003 *Optr = HexList[ch][1];
3015 OutBuf->BufUsed = Optr - OutBuf->buf;
3021 static void AddRecipient(StrBuf *Target, StrBuf *UserName, StrBuf *EmailAddress, StrBuf *EncBuf) {
3024 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
3025 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
3027 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
3028 StrBufRFC2047encode(&EncBuf, UserName);
3029 StrBufAppendBuf(Target, EncBuf, 0);
3030 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
3031 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
3033 if (StrLength(EmailAddress) > 0){
3034 StrBufAppendBufPlain(Target, HKEY("<"), 0);
3035 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
3036 StrBufAppendBufPlain(Target, HKEY(">"), 0);
3042 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
3043 * \param Recp Source list of email recipients
3044 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
3045 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
3046 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
3047 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
3049 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp, StrBuf *UserName, StrBuf *EmailAddress, StrBuf *EncBuf) {
3051 const char *pch, *pche;
3052 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
3054 if ((Recp == NULL) || (StrLength(Recp) == 0))
3058 pche = pch + StrLength(Recp);
3060 if (!CheckEncode(pch, -1, pche))
3061 return NewStrBufDup(Recp);
3063 Target = NewStrBufPlain(NULL, StrLength(Recp));
3065 while ((pch != NULL) && (pch < pche))
3067 while (isspace(*pch)) pch++;
3068 UserEnd = EmailStart = EmailEnd = NULL;
3070 if ((*pch == '"') || (*pch == '\'')) {
3071 UserStart = pch + 1;
3073 UserEnd = strchr(UserStart, *pch);
3074 if (UserEnd == NULL)
3075 break; ///TODO: Userfeedback??
3076 EmailStart = UserEnd + 1;
3077 while (isspace(*EmailStart))
3079 if (UserEnd == UserStart) {
3080 UserStart = UserEnd = NULL;
3083 if (*EmailStart == '<') {
3085 EmailEnd = strchr(EmailStart, '>');
3086 if (EmailEnd == NULL)
3087 EmailEnd = strchr(EmailStart, ',');
3091 EmailEnd = strchr(EmailStart, ',');
3093 if (EmailEnd == NULL)
3100 EmailEnd = strchr(UserStart, ',');
3101 if (EmailEnd == NULL) {
3102 EmailEnd = strchr(pch, '>');
3104 if (EmailEnd != NULL) {
3114 while ((EmailEnd > UserStart) && !gt &&
3115 ((*EmailEnd == ',') ||
3116 (*EmailEnd == '>') ||
3117 (isspace(*EmailEnd))))
3119 if (*EmailEnd == '>')
3124 if (EmailEnd == UserStart)
3128 EmailStart = strchr(UserStart, '<');
3129 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
3131 UserEnd = EmailStart;
3133 while ((UserEnd > UserStart) &&
3134 isspace (*(UserEnd - 1)))
3137 if (UserStart >= UserEnd)
3138 UserStart = UserEnd = NULL;
3140 else { /* this is a local recipient... no domain, just a realname */
3141 EmailStart = UserStart;
3142 At = strchr(EmailStart, '@');
3148 EmailStart = UserStart;
3154 if ((UserStart != NULL) && (UserEnd != NULL))
3155 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
3156 else if ((UserStart != NULL) && (UserEnd == NULL))
3157 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
3159 FlushStrBuf(UserName);
3161 if ((EmailStart != NULL) && (EmailEnd != NULL))
3162 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
3163 else if ((EmailStart != NULL) && (EmailEnd == NULL))
3164 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
3166 FlushStrBuf(EmailAddress);
3168 AddRecipient(Target, UserName, EmailAddress, EncBuf);
3173 if ((pch != NULL) && (*pch == ','))
3175 if (pch != NULL) while (isspace(*pch))
3183 * replaces all occurances of 'search' by 'replace'
3184 * buf Buffer to modify
3185 * search character to search
3186 * replace character to replace search by
3188 void StrBufReplaceChars(StrBuf *buf, char search, char replace) {
3192 for (i=0; i<buf->BufUsed; i++)
3193 if (buf->buf[i] == search)
3194 buf->buf[i] = replace;
3199 * removes all \\r s from the string, or replaces them with \n if its not a combination of both.
3200 * buf Buffer to modify
3202 void StrBufToUnixLF(StrBuf *buf) {
3203 char *pche, *pchS, *pchT;
3207 pche = buf->buf + buf->BufUsed;
3208 pchS = pchT = buf->buf;
3214 if (*pchS != '\n') {
3223 buf->BufUsed = pchT - buf->buf;
3227 /*******************************************************************************
3228 * Iconv Wrapper; RFC822 de/encoding *
3229 *******************************************************************************/
3232 * Wrapper around iconv_open()
3233 * Our version adds aliases for non-standard Microsoft charsets
3234 * such as 'MS950', aliasing them to names like 'CP950'
3236 * tocode Target encoding
3237 * fromcode Source encoding
3238 * pic anonimized pointer to iconv struct
3240 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic) {
3242 iconv_t ic = (iconv_t)(-1) ;
3243 ic = iconv_open(tocode, fromcode);
3244 if (ic == (iconv_t)(-1) ) {
3245 char alias_fromcode[64];
3246 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
3247 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
3248 alias_fromcode[0] = 'C';
3249 alias_fromcode[1] = 'P';
3250 ic = iconv_open(tocode, alias_fromcode);
3253 *(iconv_t *)pic = ic;
3259 * find one chunk of a RFC822 encoded string
3260 * Buffer where to search
3261 * bptr where to start searching
3262 * @returns found position, NULL if none.
3264 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr) {
3266 /* Find the next ?Q? */
3267 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
3270 end = strchr(bptr + 2, '?');
3275 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
3276 (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
3277 ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) &&
3278 (*(end + 2) == '?')) {
3279 /* skip on to the end of the cluster, the next ?= */
3280 end = strstr(end + 3, "?=");
3283 /* sort of half valid encoding, try to find an end. */
3284 end = strstr(bptr, "?=");
3291 * convert one buffer according to the preselected iconv pointer PIC
3292 * ConvertBuf buffer we need to translate
3293 * TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3294 * pic Pointer to the iconv-session Object
3296 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic) {
3301 char *ibuf; /**< Buffer of characters to be converted */
3302 char *obuf; /**< Buffer for converted characters */
3303 size_t ibuflen; /**< Length of input buffer */
3304 size_t obuflen; /**< Length of output buffer */
3307 if ((ConvertBuf == NULL) || (TmpBuf == NULL))
3310 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3311 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3312 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3314 ic = *(iconv_t*)pic;
3315 ibuf = ConvertBuf->buf;
3316 ibuflen = ConvertBuf->BufUsed;
3318 obuflen = TmpBuf->BufSize;
3320 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3323 if (errno == E2BIG) {
3325 IncreaseBuf(TmpBuf, 0, 0);
3330 else if (errno == EILSEQ){
3331 /* hm, invalid utf8 sequence... what to do now? */
3332 /* An invalid multibyte sequence has been encountered in the input */
3334 else if (errno == EINVAL) {
3335 /* An incomplete multibyte sequence has been encountered in the input. */
3338 FlushStrBuf(TmpBuf);
3341 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3342 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3344 /* little card game: wheres the red lady? */
3345 iSwapBuffers(ConvertBuf, TmpBuf);
3346 FlushStrBuf(TmpBuf);
3353 * catches one RFC822 encoded segment, and decodes it.
3354 * Target buffer to fill with result
3355 * DecodeMe buffer with stuff to process
3356 * SegmentStart points to our current segment in DecodeMe
3357 * SegmentEnd Points to the end of our current segment in DecodeMe
3358 * ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3359 * ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3360 * FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3362 inline static void DecodeSegment(StrBuf *Target,
3363 const StrBuf *DecodeMe,
3364 const char *SegmentStart,
3365 const char *SegmentEnd,
3367 StrBuf *ConvertBuf2,
3368 StrBuf *FoundCharset)
3374 iconv_t ic = (iconv_t)(-1);
3378 /* Now we handle foreign character sets properly encoded
3379 * in RFC2047 format.
3381 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
3382 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3383 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3384 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3385 if (FoundCharset != NULL) {
3386 FlushStrBuf(FoundCharset);
3387 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3389 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3390 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3392 *encoding = toupper(*encoding);
3393 if (*encoding == 'B') { /**< base64 */
3394 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3395 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3396 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
3398 ConvertBuf->BufUsed);
3400 else if (*encoding == 'Q') { /**< quoted-printable */
3404 while (pos < ConvertBuf->BufUsed)
3406 if (ConvertBuf->buf[pos] == '_')
3407 ConvertBuf->buf[pos] = ' ';
3411 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3412 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3414 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3417 ConvertBuf->BufUsed);
3420 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3423 ctdl_iconv_open("UTF-8", charset, &ic);
3424 if (ic != (iconv_t)(-1) ) {
3426 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3427 StrBufAppendBuf(Target, ConvertBuf2, 0);
3432 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3438 * Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
3439 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3440 * Target where to put the decoded string to
3441 * DecodeMe buffer with encoded string
3442 * DefaultCharset if we don't find one, which should we use?
3443 * FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3444 * put it here for later use where no string might be known.
3446 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset) {
3448 StrBuf *ConvertBuf2;
3449 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3450 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3452 StrBuf_RFC822_2_Utf8(Target,
3458 FreeStrBuf(&ConvertBuf);
3459 FreeStrBuf(&ConvertBuf2);
3463 * Handle subjects with RFC2047 encoding such as:
3464 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3465 * Target where to put the decoded string to
3466 * DecodeMe buffer with encoded string
3467 * DefaultCharset if we don't find one, which should we use?
3468 * FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3469 * put it here for later use where no string might be known.
3470 * ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3471 * ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3473 void StrBuf_RFC822_2_Utf8(StrBuf *Target,
3474 const StrBuf *DecodeMe,
3475 const StrBuf* DefaultCharset,
3476 StrBuf *FoundCharset,
3478 StrBuf *ConvertBuf2)
3480 StrBuf *DecodedInvalidBuf = NULL;
3481 const StrBuf *DecodeMee = DecodeMe;
3482 const char *start, *end, *next, *nextend, *ptr = NULL;
3484 iconv_t ic = (iconv_t)(-1) ;
3489 int illegal_non_rfc2047_encoding = 0;
3492 if (DecodeMe == NULL)
3494 /* Sometimes, badly formed messages contain strings which were simply
3495 * written out directly in some foreign character set instead of
3496 * using RFC2047 encoding. This is illegal but we will attempt to
3497 * handle it anyway by converting from a user-specified default
3498 * charset to UTF-8 if we see any nonprintable characters.
3501 for (i=0; i<DecodeMe->BufUsed; ++i) {
3502 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3503 illegal_non_rfc2047_encoding = 1;
3508 if ((illegal_non_rfc2047_encoding) &&
3509 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3510 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3513 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3514 if (ic != (iconv_t)(-1) ) {
3515 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3516 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3517 DecodeMee = DecodedInvalidBuf;
3523 /* pre evaluate the first pair */
3525 start = strstr(DecodeMee->buf, "=?");
3526 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3528 end = FindNextEnd (DecodeMee, start + 2);
3530 StrBufAppendBuf(Target, DecodeMee, 0);
3531 FreeStrBuf(&DecodedInvalidBuf);
3536 if (start != DecodeMee->buf) {
3539 nFront = start - DecodeMee->buf;
3540 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3543 * Since spammers will go to all sorts of absurd lengths to get their
3544 * messages through, there are LOTS of corrupt headers out there.
3545 * So, prevent a really badly formed RFC2047 header from throwing
3546 * this function into an infinite loop.
3548 while ((start != NULL) &&
3555 DecodeSegment(Target,
3563 next = strstr(end, "=?");
3565 if ((next != NULL) &&
3567 nextend = FindNextEnd(DecodeMee, next);
3568 if (nextend == NULL)
3571 /* did we find two partitions */
3572 if ((next != NULL) &&
3576 while ((ptr < next) &&
3583 * did we find a gab just filled with blanks?
3584 * if not, copy its stuff over.
3588 StrBufAppendBufPlain(Target,
3594 /* our next-pair is our new first pair now. */
3600 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3601 if ((end != NULL) && (end < nextend)) {
3603 while ( (ptr < nextend) &&
3610 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3612 FreeStrBuf(&DecodedInvalidBuf);
3615 /*******************************************************************************
3616 * Manipulating UTF-8 Strings *
3617 *******************************************************************************/
3620 * evaluate the length of an utf8 special character sequence
3621 * Char the character to examine
3622 * @returns width of utf8 chars in bytes; if the sequence is broken 0 is returned; 1 if its simply ASCII.
3624 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE) {
3626 unsigned char test = (1<<7);
3628 if ((*CharS & 0xC0) != 0xC0)
3632 ((test & ((unsigned char)*CharS)) != 0))
3637 if ((n > 6) || ((CharE - CharS) < n))
3643 * detect whether this char starts an utf-8 encoded char
3644 * Char character to inspect
3645 * @returns yes or no
3647 static inline int Ctdl_IsUtf8SequenceStart(const char Char) {
3648 /** 11??.???? indicates an UTF8 Sequence. */
3649 return ((Char & 0xC0) == 0xC0);
3653 * measure the number of glyphs in an UTF8 string...
3654 * Buf string to measure
3655 * @returns the number of glyphs in Buf
3657 long StrBuf_Utf8StrLen(StrBuf *Buf) {
3662 if ((Buf == NULL) || (Buf->BufUsed == 0))
3665 eptr = Buf->buf + Buf->BufUsed;
3666 while ((aptr < eptr) && (*aptr != '\0')) {
3667 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3668 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3669 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3681 * cuts a string after maxlen glyphs
3682 * Buf string to cut to maxlen glyphs
3683 * maxlen how long may the string become?
3684 * @returns current length of the string
3686 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen) {
3691 eptr = Buf->buf + Buf->BufUsed;
3692 while ((aptr < eptr) && (*aptr != '\0')) {
3693 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3694 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3695 while ((*aptr++ != '\0') && (m-- > 0));
3704 Buf->BufUsed = aptr - Buf->buf;
3705 return Buf->BufUsed;
3708 return Buf->BufUsed;
3713 /*******************************************************************************
3715 *******************************************************************************/
3718 * uses the same calling syntax as compress2(), but it
3719 * creates a stream compatible with HTTP "Content-encoding: gzip"
3720 * dest compressed buffer
3721 * destLen length of the compresed data
3722 * source source to encode
3723 * sourceLen length of source to encode
3724 * level compression level
3727 int ZEXPORT compress_gzip(Bytef * dest,
3729 const Bytef * source,
3733 /* write gzip header */
3734 snprintf((char *) dest, *destLen,
3735 "%c%c%c%c%c%c%c%c%c%c",
3736 gz_magic[0], gz_magic[1], Z_DEFLATED,
3737 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3740 /* normal deflate */
3743 stream.next_in = (Bytef *) source;
3744 stream.avail_in = (uInt) sourceLen;
3745 stream.next_out = dest + 10L; // after header
3746 stream.avail_out = (uInt) * destLen;
3747 if ((uLong) stream.avail_out != *destLen)
3750 stream.zalloc = (alloc_func) 0;
3751 stream.zfree = (free_func) 0;
3752 stream.opaque = (voidpf) 0;
3754 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3755 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3759 err = deflate(&stream, Z_FINISH);
3760 if (err != Z_STREAM_END) {
3761 deflateEnd(&stream);
3762 return err == Z_OK ? Z_BUF_ERROR : err;
3764 *destLen = stream.total_out + 10L;
3766 /* write CRC and Length */
3767 uLong crc = crc32(0L, source, sourceLen);
3769 for (n = 0; n < 4; ++n, ++*destLen) {
3770 dest[*destLen] = (int) (crc & 0xff);
3773 uLong len = stream.total_in;
3774 for (n = 0; n < 4; ++n, ++*destLen) {
3775 dest[*destLen] = (int) (len & 0xff);
3778 err = deflateEnd(&stream);
3785 * compress the buffer with gzip
3786 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3787 * Buf buffer whose content is to be gzipped
3789 int CompressBuffer(StrBuf *Buf) {
3791 char *compressed_data = NULL;
3792 size_t compressed_len, bufsize;
3795 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3796 compressed_data = malloc(compressed_len);
3798 if (compressed_data == NULL)
3800 /* Flush some space after the used payload so valgrind shuts up... */
3801 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3802 Buf->buf[Buf->BufUsed + i++] = '\0';
3803 if (compress_gzip((Bytef *) compressed_data,
3806 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3809 Buf->buf = compressed_data;
3810 Buf->BufUsed = compressed_len;
3811 Buf->BufSize = bufsize;
3812 /* Flush some space after the used payload so valgrind shuts up... */
3814 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3815 Buf->buf[Buf->BufUsed + i++] = '\0';
3818 free(compressed_data);
3820 #endif /* HAVE_ZLIB */
3825 /*******************************************************************************
3826 * File I/O; Callbacks to libevent *
3827 *******************************************************************************/
3829 long StrBuf_read_one_chunk_callback (int fd, short event, IOBuffer *FB) {
3833 if ((FB == NULL) || (FB->Buf == NULL))
3837 * check whether the read pointer is somewhere in a range
3838 * where a cut left is inexpensive
3841 if (FB->ReadWritePointer != NULL) {
3844 already_read = FB->ReadWritePointer - FB->Buf->buf;
3845 bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3847 if (already_read != 0) {
3850 unread = FB->Buf->BufUsed - already_read;
3852 /* else nothing to compact... */
3854 FB->ReadWritePointer = FB->Buf->buf;
3855 bufremain = FB->Buf->BufSize;
3857 else if ((unread < 64) || (bufremain < already_read)) {
3859 * if its just a tiny bit remaining, or we run out of space...
3862 FB->Buf->BufUsed = unread;
3863 if (unread < already_read)
3864 memcpy(FB->Buf->buf, FB->ReadWritePointer, unread);
3866 memmove(FB->Buf->buf, FB->ReadWritePointer, unread);
3867 FB->ReadWritePointer = FB->Buf->buf;
3868 bufremain = FB->Buf->BufSize - unread - 1;
3870 else if (bufremain < (FB->Buf->BufSize / 10)) {
3871 /* get a bigger buffer */
3873 IncreaseBuf(FB->Buf, 0, FB->Buf->BufUsed + 1);
3875 FB->ReadWritePointer = FB->Buf->buf + unread;
3877 bufremain = FB->Buf->BufSize - unread - 1;
3878 /*TODO: special increase function that won't copy the already read! */
3881 else if (bufremain < 10) {
3882 IncreaseBuf(FB->Buf, 1, FB->Buf->BufUsed + 10);
3884 FB->ReadWritePointer = FB->Buf->buf;
3886 bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3891 FB->ReadWritePointer = FB->Buf->buf;
3892 bufremain = FB->Buf->BufSize - 1;
3895 n = read(fd, FB->Buf->buf + FB->Buf->BufUsed, bufremain);
3898 FB->Buf->BufUsed += n;
3899 FB->Buf->buf[FB->Buf->BufUsed] = '\0';
3905 int StrBuf_write_one_chunk_callback(int fd, short event, IOBuffer *FB) {
3909 if ((FB == NULL) || (FB->Buf == NULL))
3912 if (FB->ReadWritePointer != NULL)
3914 WriteRemain = FB->Buf->BufUsed -
3915 (FB->ReadWritePointer -
3919 FB->ReadWritePointer = FB->Buf->buf;
3920 WriteRemain = FB->Buf->BufUsed;
3923 n = write(fd, FB->ReadWritePointer, WriteRemain);
3925 FB->ReadWritePointer += n;
3927 if (FB->ReadWritePointer ==
3928 FB->Buf->buf + FB->Buf->BufUsed)
3930 FlushStrBuf(FB->Buf);
3931 FB->ReadWritePointer = NULL;
3934 // check whether we've got something to write
3935 // get the maximum chunk plus the pointer we can send
3936 // write whats there
3937 // if not all was sent, remember the send pointer for the next time
3938 return FB->ReadWritePointer - FB->Buf->buf + FB->Buf->BufUsed;
3944 // extract a "next line" from Buf; Ptr to persist across several iterations
3945 // LineBuf your line will be copied here.
3946 // FB BLOB with lines of text...
3947 // Ptr moved arround to keep the next-line across several iterations
3948 // has to be &NULL on start; will be &NotNULL on end of buffer
3949 // returns size of copied buffer
3950 eReadState StrBufChunkSipLine(StrBuf *LineBuf, IOBuffer *FB) {
3951 const char *aptr, *ptr, *eptr;
3954 if ((FB == NULL) || (LineBuf == NULL) || (LineBuf->buf == NULL))
3958 if ((FB->Buf == NULL) || (FB->ReadWritePointer == StrBufNOTNULL)) {
3959 FB->ReadWritePointer = StrBufNOTNULL;
3963 FlushStrBuf(LineBuf);
3964 if (FB->ReadWritePointer == NULL)
3965 ptr = aptr = FB->Buf->buf;
3967 ptr = aptr = FB->ReadWritePointer;
3969 optr = LineBuf->buf;
3970 eptr = FB->Buf->buf + FB->Buf->BufUsed;
3971 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3973 while ((ptr <= eptr) && (*ptr != '\n') && (*ptr != '\r') ) {
3977 LineBuf->BufUsed = optr - LineBuf->buf;
3978 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3979 optr = LineBuf->buf + LineBuf->BufUsed;
3980 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3985 if (optr > LineBuf->buf)
3987 if ((*(ptr - 1) != '\r') && (*(ptr - 1) != '\n')) {
3988 LineBuf->BufUsed = optr - LineBuf->buf;
3990 if ((FB->ReadWritePointer != NULL) && (FB->ReadWritePointer != FB->Buf->buf)) {
3991 // Ok, the client application read all the data
3992 // it was interested in so far. Since there is more to read,
3993 // we now shrink the buffer, and move the rest over.
3994 StrBufCutLeft(FB->Buf, FB->ReadWritePointer - FB->Buf->buf);
3995 FB->ReadWritePointer = FB->Buf->buf;
3997 return eMustReadMore;
4000 LineBuf->BufUsed = optr - LineBuf->buf;
4002 if ((ptr <= eptr) && (*ptr == '\r'))
4004 if ((ptr <= eptr) && (*ptr == '\n'))
4008 FB->ReadWritePointer = ptr;
4011 FlushStrBuf(FB->Buf);
4012 FB->ReadWritePointer = NULL;
4015 return eReadSuccess;
4019 * check whether the chunk-buffer has more data waiting or not.
4020 * FB Chunk-Buffer to inspect
4022 eReadState StrBufCheckBuffer(IOBuffer *FB) {
4025 if (FB->Buf->BufUsed == 0)
4026 return eReadSuccess;
4027 if (FB->ReadWritePointer == NULL)
4028 return eBufferNotEmpty;
4029 if (FB->Buf->buf + FB->Buf->BufUsed > FB->ReadWritePointer)
4030 return eBufferNotEmpty;
4031 return eReadSuccess;
4035 long IOBufferStrLength(IOBuffer *FB) {
4036 if ((FB == NULL) || (FB->Buf == NULL))
4038 if (FB->ReadWritePointer == NULL)
4039 return StrLength(FB->Buf);
4041 return StrLength(FB->Buf) - (FB->ReadWritePointer - FB->Buf->buf);
4045 /*******************************************************************************
4046 * File I/O; Prefer buffered read since its faster! *
4047 *******************************************************************************/
4050 * Read a line from socket
4051 * flushes and closes the FD on error
4052 * buf the buffer to get the input to
4053 * fd pointer to the filedescriptor to read
4054 * append Append to an existing string or replace?
4055 * Error strerror() on error
4056 * @returns numbers of chars read
4058 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error) {
4059 int len, rlen, slen;
4061 if ((buf == NULL) || (buf->buf == NULL)) {
4062 *Error = strerror(EINVAL);
4069 slen = len = buf->BufUsed;
4071 rlen = read(*fd, &buf->buf[len], 1);
4073 *Error = strerror(errno);
4080 if (buf->buf[len] == '\n')
4082 if (buf->buf[len] != '\r')
4084 if (len + 2 >= buf->BufSize) {
4086 buf->buf[len+1] = '\0';
4087 IncreaseBuf(buf, 1, -1);
4091 buf->buf[len] = '\0';
4096 // Read a line from socket
4097 // flushes and closes the FD on error
4098 // Line the line to read from the fd / I/O Buffer
4099 // buf the buffer to get the input to
4100 // fd pointer to the filedescriptor to read
4101 // timeout number of successless selects until we bail out
4102 // selectresolution how long to wait on each select
4103 // Error strerror() on error
4104 // returns numbers of chars read
4105 int StrBufTCP_read_buffered_line(StrBuf *Line,
4109 int selectresolution,
4113 int nSuccessLess = 0;
4120 if (buf->BufUsed > 0) {
4121 pch = strchr(buf->buf, '\n');
4124 len = pch - buf->buf;
4125 if (len > 0 && (*(pch - 1) == '\r') ) {
4128 StrBufSub(Line, buf, 0, len - rlen);
4129 StrBufCutLeft(buf, len + 1);
4134 if (buf->BufSize - buf->BufUsed < 10) {
4135 IncreaseBuf(buf, 1, -1);
4138 fdflags = fcntl(*fd, F_GETFL);
4139 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4141 while ((nSuccessLess < timeout) && (pch == NULL)) {
4143 tv.tv_sec = selectresolution;
4148 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
4149 *Error = strerror(errno);
4155 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
4159 rlen = read(*fd, &buf->buf[buf->BufUsed], buf->BufSize - buf->BufUsed - 1);
4161 *Error = strerror(errno);
4166 else if (rlen > 0) {
4168 buf->BufUsed += rlen;
4169 buf->buf[buf->BufUsed] = '\0';
4170 pch = strchr(buf->buf, '\n');
4171 if ((pch == NULL) && (buf->BufUsed + 10 > buf->BufSize) && (IncreaseBuf(buf, 1, -1) == -1)) {
4180 len = pch - buf->buf;
4181 if (len > 0 && (*(pch - 1) == '\r') )
4183 StrBufSub(Line, buf, 0, len - rlen);
4184 StrBufCutLeft(buf, len + 1);
4191 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
4192 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
4193 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
4196 // Read a line from socket
4197 // flushes and closes the FD on error
4198 // Line where to append our Line read from the fd / I/O Buffer;
4199 // IOBuf the buffer to get the input to; lifetime pair to FD
4200 // Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
4201 // fd pointer to the filedescriptor to read
4202 // timeout number of successless selects until we bail out
4203 // selectresolution how long to wait on each select
4204 // Error strerror() on error
4205 // returns numbers of chars read or -1 in case of error. "\n" will become 0
4206 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
4211 int selectresolution,
4214 const char *pche = NULL;
4215 const char *pos = NULL;
4217 int len, rlen, retlen;
4218 int nSuccessLess = 0;
4220 const char *pch = NULL;
4226 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL) || (*fd == -1)) {
4230 *Error = ErrRBLF_PreConditionFailed;
4235 if ((IOBuf->BufUsed > 0) && (pos != NULL) && (pos < IOBuf->buf + IOBuf->BufUsed)) {
4238 pche = IOBuf->buf + IOBuf->BufUsed;
4242 while ((pch < pche) && (*pch != '\n')) {
4243 if (Line->BufUsed + 10 > Line->BufSize) {
4245 apos = pcht - Line->buf;
4247 IncreaseBuf(Line, 1, -1);
4248 pcht = Line->buf + apos;
4256 if (len > 0 && (*(pch - 1) == '\r') ) {
4264 if ((pch >= pche) || (*pch == '\0')) {
4271 if ((pch != NULL) && (pch <= pche)) {
4272 if (pch + 1 >= pche) {
4285 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
4287 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
4288 IncreaseBuf(IOBuf, 1, -1);
4291 fdflags = fcntl(*fd, F_GETFL);
4292 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4295 while ((nSuccessLess < timeout) &&
4304 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
4305 *Error = strerror(errno);
4309 *Error = ErrRBLF_SelectFailed;
4312 if (! FD_ISSET(*fd, &rfds) != 0) {
4317 rlen = read(*fd, &IOBuf->buf[IOBuf->BufUsed], IOBuf->BufSize - IOBuf->BufUsed - 1);
4319 *Error = strerror(errno);
4324 else if (rlen > 0) {
4326 pLF = IOBuf->buf + IOBuf->BufUsed;
4327 IOBuf->BufUsed += rlen;
4328 IOBuf->buf[IOBuf->BufUsed] = '\0';
4330 pche = IOBuf->buf + IOBuf->BufUsed;
4332 while ((pLF < pche) && (*pLF != '\n'))
4334 if ((pLF >= pche) || (*pLF == '\0'))
4337 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
4340 if (pLF != NULL) apos = pLF - IOBuf->buf;
4341 IncreaseBuf(IOBuf, 1, -1);
4342 if (pLF != NULL) pLF = IOBuf->buf + apos;
4355 if (len > 0 && (*(pLF - 1) == '\r') ) {
4358 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
4359 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed) {
4364 return retlen + len;
4366 *Error = ErrRBLF_NotEnoughSentFromServer;
4371 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
4373 * Input binary data from socket
4374 * flushes and closes the FD on error
4375 * Buf the buffer to get the input to
4376 * fd pointer to the filedescriptor to read
4377 * append Append to an existing string or replace?
4378 * nBytes the maximal number of bytes to read
4379 * Error strerror() on error
4380 * @returns numbers of chars read
4382 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error) {
4392 if ((Buf == NULL) || (Buf->buf == NULL) || (*fd == -1)) {
4393 *Error = ErrRBLF_BLOBPreConditionFailed;
4399 if (Buf->BufUsed + nBytes >= Buf->BufSize) {
4400 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
4402 ptr = Buf->buf + Buf->BufUsed;
4404 fdflags = fcntl(*fd, F_GETFL);
4405 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4407 while ((nRead < nBytes) && (*fd != -1)) {
4414 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4415 *Error = strerror(errno);
4418 if (*Error == NULL) {
4419 *Error = ErrRBLF_SelectFailed;
4423 if (! FD_ISSET(*fd, &rfds) != 0) {
4429 if ((rlen = read(*fd,
4431 nBytes - nRead)) == -1) {
4434 *Error = strerror(errno);
4439 Buf->BufUsed += rlen;
4441 Buf->buf[Buf->BufUsed] = '\0';
4445 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
4446 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
4449 // Input binary data from socket
4450 // flushes and closes the FD on error
4451 // Blob put binary thing here
4452 // IOBuf the buffer to get the input to
4453 // Pos offset inside of IOBuf
4454 // fd pointer to the filedescriptor to read
4455 // append Append to an existing string or replace?
4456 // nBytes the maximal number of bytes to read
4457 // check whether we should search for '000\n' terminators in case of timeouts
4458 // Error strerror() on error
4459 // returns numbers of chars read
4460 int StrBufReadBLOBBuffered(StrBuf *Blob,
4473 int nAlreadyRead = 0;
4478 int nSuccessLess = 0;
4481 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL)) {
4484 *Error = ErrRBB_BLOBFPreConditionFailed;
4490 if (Blob->BufUsed + nBytes >= Blob->BufSize)
4491 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
4496 rlen = pos - IOBuf->buf;
4498 rlen = IOBuf->BufUsed - rlen;
4501 if ((IOBuf->BufUsed > 0) && (pos != NULL) && (pos < IOBuf->buf + IOBuf->BufUsed)) {
4502 if (rlen < nBytes) {
4503 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
4504 Blob->BufUsed += rlen;
4505 Blob->buf[Blob->BufUsed] = '\0';
4506 nAlreadyRead = nRead = rlen;
4509 if (rlen >= nBytes) {
4510 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
4511 Blob->BufUsed += nBytes;
4512 Blob->buf[Blob->BufUsed] = '\0';
4513 if (rlen == nBytes) {
4525 if (IOBuf->BufSize < nBytes - nRead) {
4526 IncreaseBuf(IOBuf, 0, nBytes - nRead);
4530 fdflags = fcntl(*fd, F_GETFL);
4531 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4539 while ((nSuccessLess < MaxTries) && (nRead < nBytes) && (*fd != -1)) {
4546 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4547 *Error = strerror(errno);
4550 if (*Error == NULL) {
4551 *Error = ErrRBLF_SelectFailed;
4555 if (! FD_ISSET(*fd, &rfds) != 0) {
4560 rlen = read(*fd, ptr, IOBuf->BufSize - (ptr - IOBuf->buf));
4561 if (rlen < 1) { // We will always get at least 1 byte unless the connection is broken
4564 *Error = strerror(errno);
4567 else if (rlen == 0){
4568 if ((check == NNN_TERM) && (nRead > 5) && (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) {
4569 StrBufPlain(Blob, HKEY("\n000\n"));
4570 StrBufCutRight(Blob, 5);
4571 return Blob->BufUsed;
4573 else if (!IsNonBlock)
4575 else if (nSuccessLess > MaxTries) {
4577 *Error = ErrRBB_too_many_selects;
4581 else if (rlen > 0) {
4585 IOBuf->BufUsed += rlen;
4588 if (nSuccessLess >= MaxTries) {
4590 *Error = ErrRBB_too_many_selects;
4594 if (nRead > nBytes) {
4595 *Pos = IOBuf->buf + nBytes;
4597 Blob->buf[Blob->BufUsed] = '\0';
4598 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
4602 return nRead + nAlreadyRead;
4606 // extract a "next line" from Buf; Ptr to persist across several iterations
4607 // LineBuf your line will be copied here.
4608 // Buf BLOB with lines of text...
4609 // Ptr moved arround to keep the next-line across several iterations
4610 // has to be &NULL on start; will be &NotNULL on end of buffer
4611 // returns size of remaining buffer
4612 int StrBufSipLine(StrBuf *LineBuf, const StrBuf *Buf, const char **Ptr) {
4613 const char *aptr, *ptr, *eptr;
4616 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL) || (LineBuf == NULL)|| (LineBuf->buf == NULL)) {
4617 *Ptr = StrBufNOTNULL;
4621 FlushStrBuf(LineBuf);
4623 ptr = aptr = Buf->buf;
4627 optr = LineBuf->buf;
4628 eptr = Buf->buf + Buf->BufUsed;
4629 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4631 while ((ptr <= eptr) && (*ptr != '\n') && (*ptr != '\r') ) {
4635 LineBuf->BufUsed = optr - LineBuf->buf;
4636 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
4637 optr = LineBuf->buf + LineBuf->BufUsed;
4638 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4642 if ((ptr >= eptr) && (optr > LineBuf->buf))
4644 LineBuf->BufUsed = optr - LineBuf->buf;
4646 if ((ptr <= eptr) && (*ptr == '\r'))
4648 if ((ptr <= eptr) && (*ptr == '\n'))
4655 *Ptr = StrBufNOTNULL;
4658 return Buf->BufUsed - (ptr - Buf->buf);
4662 // removes double slashes from pathnames
4663 // Dir directory string to filter
4664 // RemoveTrailingSlash allows / disallows trailing slashes
4665 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash) {
4670 while (!IsEmptyStr(a)) {
4682 if ((RemoveTrailingSlash) &&
4688 Dir->BufUsed = b - Dir->buf;
4692 // Decode a quoted-printable encoded StrBuf buffer "in place"
4693 // This is possible because the decoded will always be shorter than the encoded
4694 // so we don't have to worry about the buffer being to small.
4695 void StrBufDecodeQP(StrBuf *Buf) {
4696 if (!Buf) { // sanity check #1
4700 int source_len = StrLength(Buf);
4701 if (source_len < 1) { // sanity check #2
4705 int spos = 0; // source position
4706 int tpos = 0; // target position
4708 while (spos < source_len) {
4709 if (!strncmp(&Buf->buf[spos], "=\r\n", 3)) {
4712 else if (!strncmp(&Buf->buf[spos], "=\n", 2)) {
4715 else if (Buf->buf[spos] == '=') {
4718 sscanf(&Buf->buf[spos], "%02x", &ch);
4719 Buf->buf[tpos++] = ch;
4723 Buf->buf[tpos++] = Buf->buf[spos++];
4728 Buf->BufUsed = tpos;