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 trunkated?
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 trunkate 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;
1068 // Counts the numbmer of tokens in a buffer
1069 // source String to count tokens in
1070 // tok Tokenizer char to count
1071 // @returns numbers of tokenizer chars found
1072 int StrBufNum_tokens(const StrBuf *source, char tok) {
1075 if ((source == NULL) || (source->BufUsed == 0))
1077 if ((source->BufUsed == 1) && (*source->buf == tok))
1081 pche = pch + source->BufUsed;
1092 // a string tokenizer
1093 // Source StringBuffer to read into
1094 // parmnum n'th Parameter to remove
1095 // separator tokenizer character
1096 // @returns -1 if not found, else length of token.
1097 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator) {
1099 char *d, *s, *end; // dest, source
1102 // Find desired eter
1103 end = Source->buf + Source->BufUsed;
1105 while ((d <= end) && (count < parmnum)) {
1106 // End of string, bail!
1111 if (*d == separator) {
1116 if ((d == NULL) || (d >= end))
1117 return 0; // Parameter not found
1121 while ((s <= end) && (*s && *s != separator)) {
1124 if (*s == separator)
1133 memmove(d, s, Source->BufUsed - (s - Source->buf));
1134 Source->BufUsed += ReducedBy;
1135 Source->buf[Source->BufUsed] = '\0';
1137 else if (d == Source->buf) {
1139 Source->BufUsed = 0;
1143 Source->BufUsed += ReducedBy;
1154 int StrBufExtract_tokenFromStr(StrBuf *dest, const char *Source, long SourceLen, int parmnum, char separator) {
1155 const StrBuf Temp = {
1168 return StrBufExtract_token(dest, &Temp, parmnum, separator);
1171 // a string tokenizer
1172 // dest Destination StringBuffer
1173 // Source StringBuffer to read into
1174 // parmnum n'th Parameter to extract
1175 // separator tokenizer character
1176 // returns -1 if not found, else length of token.
1177 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator) {
1178 const char *s, *e; // source
1179 int len = 0; // running total length of extracted string
1180 int current_token = 0; // token currently being processed
1183 dest->buf[0] = '\0';
1189 if ((Source == NULL) || (Source->BufUsed ==0)) {
1193 e = s + Source->BufUsed;
1196 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1198 while ((s < e) && !IsEmptyStr(s)) {
1199 if (*s == separator) {
1202 if (len >= dest->BufSize) {
1203 dest->BufUsed = len;
1204 if (IncreaseBuf(dest, 1, -1) < 0) {
1209 if ( (current_token == parmnum) && (*s != separator)) {
1210 dest->buf[len] = *s;
1213 else if (current_token > parmnum) {
1219 dest->buf[len] = '\0';
1220 dest->BufUsed = len;
1222 if (current_token < parmnum) {
1223 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1226 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1231 // a string tokenizer to fetch an integer
1232 // Source String containing tokens
1233 // parmnum n'th Parameter to extract
1234 // separator tokenizer character
1235 // @returns 0 if not found, else integer representation of the token
1236 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator) {
1245 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1252 // a string tokenizer to fetch a long integer
1253 // Source String containing tokens
1254 // parmnum n'th Parameter to extract
1255 // separator tokenizer character
1256 // returns 0 if not found, else long integer representation of the token
1257 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator) {
1266 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1273 // a string tokenizer to fetch an unsigned long
1274 // Source String containing tokens
1275 // parmnum n'th Parameter to extract
1276 // separator tokenizer character
1277 // returns 0 if not found, else unsigned long representation of the token
1278 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator) {
1288 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1292 return (unsigned long) atol(pnum);
1299 // a string tokenizer; Bounds checker
1300 // function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1301 // Source our tokenbuffer
1302 // pStart the token iterator pointer to inspect
1303 // returns whether the revolving pointer is inside of the search range
1304 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart) {
1305 if ((Source == NULL) || (*pStart == StrBufNOTNULL) || (Source->BufUsed == 0)) {
1308 if (*pStart == NULL) {
1311 else if (*pStart > Source->buf + Source->BufUsed) {
1314 else if (*pStart <= Source->buf) {
1322 * a string tokenizer
1323 * dest Destination StringBuffer
1324 * Source StringBuffer to read into
1325 * pStart pointer to the end of the last token. Feed with NULL on start.
1326 * separator tokenizer
1327 * @returns -1 if not found, else length of token.
1329 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator) {
1330 const char *s; /* source */
1331 const char *EndBuffer; /* end stop of source buffer */
1332 int current_token = 0; /* token currently being processed */
1333 int len = 0; /* running total length of extracted string */
1335 if ((Source == NULL) || (Source->BufUsed == 0)) {
1336 *pStart = StrBufNOTNULL;
1343 EndBuffer = Source->buf + Source->BufUsed;
1346 dest->buf[0] = '\0';
1350 *pStart = EndBuffer + 1;
1354 if (*pStart == NULL) {
1355 *pStart = Source->buf; /* we're starting to examine this buffer. */
1357 else if ((*pStart < Source->buf) || (*pStart > EndBuffer ) ) {
1358 return -1; /* no more tokens to find. */
1362 /* start to find the next token */
1363 while ((s <= EndBuffer) && (current_token == 0) ) {
1364 if (*s == separator) {
1365 /* we found the next token */
1369 if (len >= dest->BufSize) {
1370 /* our Dest-buffer isn't big enough, increase it. */
1371 dest->BufUsed = len;
1373 if (IncreaseBuf(dest, 1, -1) < 0) {
1374 /* WHUT? no more mem? bail out. */
1381 if ( (current_token == 0 ) && /* are we in our target token? */
1382 (!IsEmptyStr(s) ) &&
1383 (separator != *s) ) /* don't copy the token itself */
1385 dest->buf[len] = *s; /* Copy the payload */
1386 ++len; /* remember the bigger size. */
1392 /* did we reach the end? */
1393 if ((s > EndBuffer)) {
1394 EndBuffer = StrBufNOTNULL;
1395 *pStart = EndBuffer;
1398 *pStart = s; /* remember the position for the next run */
1401 /* sanitize our extracted token */
1402 dest->buf[len] = '\0';
1403 dest->BufUsed = len;
1410 * a string tokenizer
1411 * Source StringBuffer to read from
1412 * pStart pointer to the end of the last token. Feed with NULL.
1413 * separator tokenizer character
1414 * nTokens number of tokens to fastforward over
1415 * @returns -1 if not found, else length of token.
1417 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens) {
1418 const char *s, *EndBuffer; //* source * /
1419 int len = 0; //* running total length of extracted string * /
1420 int current_token = 0; //* token currently being processed * /
1422 if ((Source == NULL) || (Source->BufUsed ==0)) {
1426 return Source->BufUsed;
1428 if (*pStart == NULL)
1429 *pStart = Source->buf;
1431 EndBuffer = Source->buf + Source->BufUsed;
1433 if ((*pStart < Source->buf) ||
1434 (*pStart > EndBuffer)) {
1440 while ((s < EndBuffer) && !IsEmptyStr(s)) {
1441 if (*s == separator) {
1444 if (current_token >= nTokens) {
1456 // a string tokenizer to fetch an integer
1457 // Source StringBuffer to read from
1458 // pStart Cursor on the tokenstring
1459 // separator tokenizer character
1460 // returns 0 if not found, else integer representation of the token
1461 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator) {
1470 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1477 // a string tokenizer to fetch a long integer
1478 // Source StringBuffer to read from
1479 // pStart Cursor on the tokenstring
1480 // separator tokenizer character
1481 // returns 0 if not found, else long integer representation of the token
1482 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator) {
1491 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1498 // a string tokenizer to fetch an unsigned long
1499 // Source StringBuffer to read from
1500 // pStart Cursor on the tokenstring
1501 // separator tokenizer character
1502 // returns 0 if not found, else unsigned long representation of the token
1503 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator) {
1513 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1517 return (unsigned long) atol(pnum);
1524 /*******************************************************************************
1525 * Escape Appending *
1526 *******************************************************************************/
1528 // Escape a string for feeding out as a URL while appending it to a Buffer
1529 // OutBuf the output buffer
1530 // In Buffer to encode
1531 // PlainIn way in from plain old c strings
1532 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1533 const char *pch, *pche;
1537 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) ) {
1540 if (PlainIn != NULL) {
1541 len = strlen(PlainIn);
1547 pche = pch + In->BufUsed;
1554 pt = OutBuf->buf + OutBuf->BufUsed;
1555 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1557 while (pch < pche) {
1559 IncreaseBuf(OutBuf, 1, -1);
1560 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1561 pt = OutBuf->buf + OutBuf->BufUsed;
1564 if((*pch >= 'a' && *pch <= 'z') ||
1565 (*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
1566 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1567 (*pch == '!') || (*pch == '_') ||
1568 (*pch == ',') || (*pch == '.'))
1575 *(pt + 1) = HexList[(unsigned char)*pch][0];
1576 *(pt + 2) = HexList[(unsigned char)*pch][1];
1578 OutBuf->BufUsed += 3;
1586 // Escape a string for feeding out as a the username/password part of an URL while appending it to a Buffer
1587 // OutBuf the output buffer
1588 // In Buffer to encode
1589 // PlainIn way in from plain old c strings
1590 void StrBufUrlescUPAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1591 const char *pch, *pche;
1595 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1597 if (PlainIn != NULL) {
1598 len = strlen(PlainIn);
1604 pche = pch + In->BufUsed;
1611 pt = OutBuf->buf + OutBuf->BufUsed;
1612 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1614 while (pch < pche) {
1616 IncreaseBuf(OutBuf, 1, -1);
1617 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
1618 pt = OutBuf->buf + OutBuf->BufUsed;
1621 if((*pch >= 'a' && *pch <= 'z') ||
1622 (*pch >= 'A' && *pch <= 'Z') || /* A-Z */
1623 (*pch >= '0' && *pch <= ':') || /* 0-9 : */
1624 (*pch == '!') || (*pch == '_') ||
1625 (*pch == ',') || (*pch == '.'))
1632 *(pt + 1) = HexList[(unsigned char)*pch][0];
1633 *(pt + 2) = HexList[(unsigned char)*pch][1];
1635 OutBuf->BufUsed += 3;
1643 // append a string with characters having a special meaning in xml encoded to the buffer
1644 // OutBuf the output buffer
1645 // In Buffer to encode
1646 // PlainIn way in from plain old c strings
1647 // PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
1648 // OverrideLowChars should chars < 0x20 be replaced by _ or escaped as xml entity?
1649 void StrBufXMLEscAppend(StrBuf *OutBuf,
1651 const char *PlainIn,
1653 int OverrideLowChars)
1655 const char *pch, *pche;
1660 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1662 if (PlainIn != NULL) {
1664 len = strlen((const char*)PlainIn);
1671 pch = (const char*)In->buf;
1672 pche = pch + In->BufUsed;
1679 pt = OutBuf->buf + OutBuf->BufUsed;
1680 /**< we max append 6 chars at once plus the \0 */
1681 pte = OutBuf->buf + OutBuf->BufSize - 6;
1683 while (pch < pche) {
1685 OutBuf->BufUsed = pt - OutBuf->buf;
1686 IncreaseBuf(OutBuf, 1, -1);
1687 pte = OutBuf->buf + OutBuf->BufSize - 6;
1688 /**< we max append 3 chars at once plus the \0 */
1690 pt = OutBuf->buf + OutBuf->BufUsed;
1694 memcpy(pt, HKEY("<"));
1698 else if (*pch == '>') {
1699 memcpy(pt, HKEY(">"));
1703 else if (*pch == '&') {
1704 memcpy(pt, HKEY("&"));
1708 else if ((*pch >= 0x20) && (*pch <= 0x7F)) {
1713 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(pch, pche);
1716 while ((IsUtf8Sequence > 0) &&
1729 *pt = HexList[*(unsigned char*)pch][0];
1731 *pt = HexList[*(unsigned char*)pch][1];
1740 OutBuf->BufUsed = pt - OutBuf->buf;
1745 * append a string in hex encoding to the buffer
1746 * OutBuf the output buffer
1747 * In Buffer to encode
1748 * PlainIn way in from plain old c strings
1749 * PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
1751 void StrBufHexEscAppend(StrBuf *OutBuf, const StrBuf *In, const unsigned char *PlainIn, long PlainInLen) {
1752 const unsigned char *pch, *pche;
1756 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1758 if (PlainIn != NULL) {
1760 len = strlen((const char*)PlainIn);
1767 pch = (const unsigned char*)In->buf;
1768 pche = pch + In->BufUsed;
1775 pt = OutBuf->buf + OutBuf->BufUsed;
1776 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1778 while (pch < pche) {
1780 IncreaseBuf(OutBuf, 1, -1);
1781 pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
1782 pt = OutBuf->buf + OutBuf->BufUsed;
1785 *pt = HexList[*pch][0];
1787 *pt = HexList[*pch][1];
1788 pt ++; pch ++; OutBuf->BufUsed += 2;
1794 void StrBufBase64Append(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn, long PlainInLen, int linebreaks) {
1800 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
1802 if (PlainIn != NULL) {
1804 len = strlen(PlainIn);
1817 ExpectLen = ((len * 134) / 100) + OutBuf->BufUsed;
1819 if (ExpectLen > OutBuf->BufSize)
1820 if (IncreaseBuf(OutBuf, 1, ExpectLen) < ExpectLen)
1823 pt = OutBuf->buf + OutBuf->BufUsed;
1825 len = CtdlEncodeBase64(pt, pch, len, linebreaks);
1828 OutBuf->BufUsed += len;
1833 // append a string in hex encoding to the buffer
1834 // OutBuf the output buffer
1835 // In Buffer to encode
1836 // PlainIn way in from plain old c strings
1837 void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn) {
1838 StrBufHexEscAppend(OutBuf, In, (const unsigned char*) PlainIn, -1);
1842 * Append a string, escaping characters which have meaning in HTML.
1844 * Target target buffer
1845 * Source source buffer; set to NULL if you just have a C-String
1846 * PlainIn Plain-C string to append; set to NULL if unused
1847 * nbsp If nonzero, spaces are converted to non-breaking spaces.
1848 * nolinebreaks if set to 1, linebreaks are removed from the string.
1849 * if set to 2, linebreaks are replaced by <br/>
1851 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks) {
1852 const char *aptr, *eiptr;
1856 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1859 if (PlainIn != NULL) {
1861 len = strlen(PlainIn);
1866 eiptr = aptr + Source->BufUsed;
1867 len = Source->BufUsed;
1873 bptr = Target->buf + Target->BufUsed;
1874 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1876 while (aptr < eiptr){
1878 IncreaseBuf(Target, 1, -1);
1879 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
1880 bptr = Target->buf + Target->BufUsed;
1883 memcpy(bptr, "<", 4);
1885 Target->BufUsed += 4;
1887 else if (*aptr == '>') {
1888 memcpy(bptr, ">", 4);
1890 Target->BufUsed += 4;
1892 else if (*aptr == '&') {
1893 memcpy(bptr, "&", 5);
1895 Target->BufUsed += 5;
1897 else if (*aptr == '"') {
1898 memcpy(bptr, """, 6);
1900 Target->BufUsed += 6;
1902 else if (*aptr == '\'') {
1903 memcpy(bptr, "'", 5);
1905 Target->BufUsed += 5;
1907 else if (*aptr == LB) {
1912 else if (*aptr == RB) {
1917 else if (*aptr == QU) {
1922 else if ((*aptr == 32) && (nbsp == 1)) {
1923 memcpy(bptr, " ", 6);
1925 Target->BufUsed += 6;
1927 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
1928 *bptr='\0'; /* nothing */
1930 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
1931 memcpy(bptr, "<br/>", 11);
1933 Target->BufUsed += 11;
1937 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
1938 *bptr='\0'; /* nothing */
1948 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
1950 return Target->BufUsed;
1954 * Append a string, escaping characters which have meaning in HTML.
1955 * Converts linebreaks into blanks; escapes single quotes
1956 * Target target buffer
1957 * Source source buffer; set to NULL if you just have a C-String
1958 * PlainIn Plain-C string to append; set to NULL if unused
1960 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
1961 const char *aptr, *eiptr;
1965 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
1968 if (PlainIn != NULL) {
1970 len = strlen(PlainIn);
1975 eiptr = aptr + Source->BufUsed;
1976 len = Source->BufUsed;
1982 eptr = Target->buf + Target->BufSize - 8;
1983 tptr = Target->buf + Target->BufUsed;
1985 while (aptr < eiptr){
1987 IncreaseBuf(Target, 1, -1);
1988 eptr = Target->buf + Target->BufSize - 8;
1989 tptr = Target->buf + Target->BufUsed;
1992 if (*aptr == '\n') {
1996 else if (*aptr == '\r') {
2000 else if (*aptr == '\'') {
2006 Target->BufUsed += 5;
2019 * Append a string, escaping characters which have meaning in ICAL.
2021 * Target target buffer
2022 * Source source buffer; set to NULL if you just have a C-String
2023 * PlainIn Plain-C string to append; set to NULL if unused
2025 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
2026 const char *aptr, *eiptr;
2030 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2033 if (PlainIn != NULL) {
2035 len = strlen(PlainIn);
2040 eiptr = aptr + Source->BufUsed;
2041 len = Source->BufUsed;
2047 eptr = Target->buf + Target->BufSize - 8;
2048 tptr = Target->buf + Target->BufUsed;
2050 while (aptr < eiptr){
2051 if(tptr + 3 >= eptr) {
2052 IncreaseBuf(Target, 1, -1);
2053 eptr = Target->buf + Target->BufSize - 8;
2054 tptr = Target->buf + Target->BufUsed;
2057 if (*aptr == '\n') {
2064 else if (*aptr == '\r') {
2071 else if (*aptr == ',') {
2087 * Append a string, escaping characters which have meaning in JavaScript strings .
2089 * Target target buffer
2090 * Source source buffer; set to NULL if you just have a C-String
2091 * PlainIn Plain-C string to append; set to NULL if unused
2092 * @returns size of result or -1
2094 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn) {
2095 const char *aptr, *eiptr;
2100 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
2103 if (PlainIn != NULL) {
2105 len = strlen(PlainIn);
2110 eiptr = aptr + Source->BufUsed;
2111 len = Source->BufUsed;
2117 bptr = Target->buf + Target->BufUsed;
2118 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2120 while (aptr < eiptr){
2122 IncreaseBuf(Target, 1, -1);
2123 eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
2124 bptr = Target->buf + Target->BufUsed;
2128 memcpy(bptr, HKEY("\\n"));
2130 Target->BufUsed += 2;
2133 memcpy(bptr, HKEY("\\r"));
2135 Target->BufUsed += 2;
2142 Target->BufUsed += 2;
2145 if ((*(aptr + 1) == 'u') &&
2146 isxdigit(*(aptr + 2)) &&
2147 isxdigit(*(aptr + 3)) &&
2148 isxdigit(*(aptr + 4)) &&
2149 isxdigit(*(aptr + 5)))
2150 { /* oh, a unicode escaper. let it pass through. */
2151 memcpy(bptr, aptr, 6);
2154 Target->BufUsed += 6;
2162 Target->BufUsed += 2;
2170 Target->BufUsed += 2;
2177 Target->BufUsed += 2;
2184 Target->BufUsed += 2;
2187 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2188 while (IsUtf8Sequence > 0){
2191 if (--IsUtf8Sequence)
2199 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
2201 return Target->BufUsed;
2204 // Append a string, escaping characters which have meaning in HTML + json.
2206 // Target target buffer
2207 // Source source buffer; set to NULL if you just have a C-String
2208 // PlainIn Plain-C string to append; set to NULL if unused
2209 // nbsp If nonzero, spaces are converted to non-breaking spaces.
2210 // nolinebreaks if set to 1, linebreaks are removed from the string.
2211 // if set to 2, linebreaks are replaced by <br/>
2212 long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks) {
2213 const char *aptr, *eiptr;
2216 int IsUtf8Sequence = 0;
2218 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL)) {
2221 if (PlainIn != NULL) {
2223 len = strlen(PlainIn);
2228 eiptr = aptr + Source->BufUsed;
2229 len = Source->BufUsed;
2236 bptr = Target->buf + Target->BufUsed;
2237 eptr = Target->buf + Target->BufSize - 11; // our biggest unit to put in...
2239 while (aptr < eiptr) {
2241 IncreaseBuf(Target, 1, -1);
2242 eptr = Target->buf + Target->BufSize - 11; // our biggest unit to put in...
2243 bptr = Target->buf + Target->BufUsed;
2247 memcpy(bptr, HKEY("<"));
2249 Target->BufUsed += 4;
2252 memcpy(bptr, HKEY(">"));
2254 Target->BufUsed += 4;
2257 memcpy(bptr, HKEY("&"));
2259 Target->BufUsed += 5;
2272 switch (nolinebreaks) {
2274 *bptr='\0'; /* nothing */
2277 memcpy(bptr, HKEY("<br/>"));
2279 Target->BufUsed += 11;
2282 memcpy(bptr, HKEY("\\n"));
2284 Target->BufUsed += 2;
2288 switch (nolinebreaks) {
2291 *bptr='\0'; /* nothing */
2294 memcpy(bptr, HKEY("\\r"));
2296 Target->BufUsed += 2;
2306 Target->BufUsed += 2;
2309 if ((*(aptr + 1) == 'u') &&
2310 isxdigit(*(aptr + 2)) &&
2311 isxdigit(*(aptr + 3)) &&
2312 isxdigit(*(aptr + 4)) &&
2313 isxdigit(*(aptr + 5)))
2314 { /* oh, a unicode escaper. let it pass through. */
2315 memcpy(bptr, aptr, 6);
2318 Target->BufUsed += 6;
2325 Target->BufUsed += 2;
2333 Target->BufUsed += 2;
2340 Target->BufUsed += 2;
2347 Target->BufUsed += 2;
2351 memcpy(bptr, HKEY(" "));
2353 Target->BufUsed += 6;
2357 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
2358 while (IsUtf8Sequence > 0){
2361 if (--IsUtf8Sequence)
2369 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
2371 return Target->BufUsed;
2376 * replace all non-Ascii characters by another
2377 * Buf buffer to inspect
2378 * repl charater to stamp over non ascii chars
2380 void StrBufAsciify(StrBuf *Buf, const char repl) {
2383 for (offset = 0; offset < Buf->BufUsed; offset ++)
2384 if (!isascii(Buf->buf[offset]))
2385 Buf->buf[offset] = repl;
2390 // unhide special chars hidden to the HTML escaper
2391 // target buffer to put the unescaped string in
2392 // source buffer to unescape
2393 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source) {
2397 if ((source == NULL) || (target == NULL) || (target->buf == NULL)) {
2402 FlushStrBuf(target);
2404 len = source->BufUsed;
2405 for (a = 0; a < len; ++a) {
2406 if (target->BufUsed >= target->BufSize)
2407 IncreaseBuf(target, 1, -1);
2409 if (source->buf[a] == '=') {
2410 hex[0] = source->buf[a + 1];
2411 hex[1] = source->buf[a + 2];
2414 sscanf(hex, "%02x", &b);
2415 target->buf[target->BufUsed] = b;
2416 target->buf[++target->BufUsed] = 0;
2420 target->buf[target->BufUsed] = source->buf[a];
2421 target->buf[++target->BufUsed] = 0;
2428 * hide special chars from the HTML escapers and friends
2429 * target buffer to put the escaped string in
2430 * source buffer to escape
2432 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source) {
2436 FlushStrBuf(target);
2438 if ((source == NULL) || (target == NULL) || (target->buf == NULL)) {
2442 len = source->BufUsed;
2443 for (i=0; i<len; ++i) {
2444 if (target->BufUsed + 4 >= target->BufSize)
2445 IncreaseBuf(target, 1, -1);
2446 if ( (isalnum(source->buf[i])) ||
2447 (source->buf[i]=='-') ||
2448 (source->buf[i]=='_') ) {
2449 target->buf[target->BufUsed++] = source->buf[i];
2452 sprintf(&target->buf[target->BufUsed],
2454 (0xFF &source->buf[i]));
2455 target->BufUsed += 3;
2458 target->buf[target->BufUsed + 1] = '\0';
2462 /*******************************************************************************
2463 * Quoted Printable de/encoding *
2464 *******************************************************************************/
2467 * decode a buffer from base 64 encoding; destroys original
2468 * Buf Buffor to transform
2470 int StrBufDecodeBase64(StrBuf *Buf) {
2478 xferbuf = (char*) malloc(Buf->BufSize);
2479 if (xferbuf == NULL)
2483 siz = CtdlDecodeBase64(xferbuf, Buf->buf, Buf->BufUsed);
2488 Buf->buf[Buf->BufUsed] = '\0';
2494 * decode a buffer from base 64 encoding; expects targetbuffer
2495 * BufIn Buffor to transform
2496 * BufOut Buffer to put result into
2498 int StrBufDecodeBase64To(const StrBuf *BufIn, StrBuf *BufOut) {
2499 if ((BufIn == NULL) || (BufOut == NULL))
2502 if (BufOut->BufSize < BufIn->BufUsed) {
2503 IncreaseBuf(BufOut, 0, BufIn->BufUsed);
2506 BufOut->BufUsed = CtdlDecodeBase64(BufOut->buf, BufIn->buf, BufIn->BufUsed);
2507 return BufOut->BufUsed;
2510 typedef struct __z_enc_stream {
2516 vStreamT *StrBufNewStreamContext(eStreamType type, const char **Err) {
2523 z_enc_stream *stream;
2526 stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
2527 memset(stream, 0, sizeof(z_enc_stream));
2528 stream->OutBuf.BufSize = 4*SIZ; /// TODO 64
2529 stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
2531 err = inflateInit(&stream->zstream);
2534 StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
2538 return (vStreamT*) stream;
2543 z_enc_stream *stream;
2546 stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
2547 memset(stream, 0, sizeof(z_enc_stream));
2548 stream->OutBuf.BufSize = 4*SIZ; /// todo 64
2549 stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
2550 /* write gzip header */
2551 stream->OutBuf.BufUsed = snprintf
2552 (stream->OutBuf.buf,
2553 stream->OutBuf.BufSize,
2554 "%c%c%c%c%c%c%c%c%c%c",
2555 gz_magic[0], gz_magic[1], Z_DEFLATED,
2556 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2559 err = deflateInit2(&stream->zstream,
2560 ZLibCompressionRatio,
2564 Z_DEFAULT_STRATEGY);
2566 StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
2570 return (vStreamT*) stream;
2581 int StrBufDestroyStreamContext(eStreamType type, vStreamT **vStream, const char **Err) {
2586 if ((vStream == NULL) || (*vStream==NULL)) {
2587 *Err = strerror(EINVAL);
2592 //case eBase64Encode:
2593 //case eBase64Decode:
2599 z_enc_stream *stream = (z_enc_stream *)*vStream;
2600 (void)inflateEnd(&stream->zstream);
2601 free(stream->OutBuf.buf);
2606 z_enc_stream *stream = (z_enc_stream *)*vStream;
2607 err = deflateEnd(&stream->zstream);
2612 free(stream->OutBuf.buf);
2623 int StrBufStreamTranscode(eStreamType type, IOBuffer *Target, IOBuffer *In, const char* pIn, long pInLen, vStreamT *vStream, int LastChunk, const char **Err) {
2627 //case eBase64Encode:
2632 //case eBase64Decode:
2639 z_enc_stream *stream = (z_enc_stream *)vStream;
2640 int org_outbuf_len = stream->OutBuf.BufUsed;
2642 unsigned int chunkavail;
2644 if (In->ReadWritePointer != NULL)
2646 stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
2647 stream->zstream.avail_in = (uInt) In->Buf->BufUsed -
2648 (In->ReadWritePointer - In->Buf->buf);
2652 stream->zstream.next_in = (Bytef *) In->Buf->buf;
2653 stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
2656 stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
2657 stream->zstream.avail_out = chunkavail = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
2659 err = deflate(&stream->zstream, (LastChunk) ? Z_FINISH : Z_NO_FLUSH);
2661 stream->OutBuf.BufUsed += (chunkavail - stream->zstream.avail_out);
2663 if (Target && (LastChunk || (stream->OutBuf.BufUsed != org_outbuf_len))) {
2664 iSwapBuffers(Target->Buf, &stream->OutBuf);
2667 if (stream->zstream.avail_in == 0) {
2668 FlushStrBuf(In->Buf);
2669 In->ReadWritePointer = NULL;
2672 if (stream->zstream.avail_in < 64) {
2673 memmove(In->Buf->buf,
2674 In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
2675 stream->zstream.avail_in);
2677 In->Buf->BufUsed = stream->zstream.avail_in;
2678 In->Buf->buf[In->Buf->BufUsed] = '\0';
2681 In->ReadWritePointer = In->Buf->buf + (In->Buf->BufUsed - stream->zstream.avail_in);
2684 rc = (LastChunk && (err != Z_FINISH));
2685 if (!rc && (err != Z_OK)) {
2692 z_enc_stream *stream = (z_enc_stream *)vStream;
2693 int org_outbuf_len = stream->zstream.total_out;
2696 if ((stream->zstream.avail_out != 0) && (stream->zstream.next_in != NULL)) {
2697 if (In->ReadWritePointer != NULL) {
2698 stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
2699 stream->zstream.avail_in = (uInt) In->Buf->BufUsed - (In->ReadWritePointer - In->Buf->buf);
2702 stream->zstream.next_in = (Bytef *) In->Buf->buf;
2703 stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
2707 stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
2708 stream->zstream.avail_out = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
2710 err = inflate(&stream->zstream, Z_NO_FLUSH);
2712 ///assert(ret != Z_STREAM_ERROR); /* state not clobbered * /
2715 err = Z_DATA_ERROR; /* and fall through */
2720 (void)inflateEnd(&stream->zstream);
2724 stream->OutBuf.BufUsed += stream->zstream.total_out + org_outbuf_len;
2726 if (Target) iSwapBuffers(Target->Buf, &stream->OutBuf);
2728 if (stream->zstream.avail_in == 0) {
2729 FlushStrBuf(In->Buf);
2730 In->ReadWritePointer = NULL;
2733 if (stream->zstream.avail_in < 64) {
2734 memmove(In->Buf->buf,
2735 In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
2736 stream->zstream.avail_in);
2738 In->Buf->BufUsed = stream->zstream.avail_in;
2739 In->Buf->buf[In->Buf->BufUsed] = '\0';
2743 In->ReadWritePointer = In->Buf->buf + (In->Buf->BufUsed - stream->zstream.avail_in);
2757 * decode a buffer from base 64 encoding; destroys original
2758 * Buf Buffor to transform
2760 int StrBufDecodeHex(StrBuf *Buf) {
2762 char *pch, *pche, *pchi;
2764 if (Buf == NULL) return -1;
2766 pch = pchi = Buf->buf;
2767 pche = pch + Buf->BufUsed;
2769 while (pchi < pche){
2770 ch = decode_hex(pchi);
2777 Buf->BufUsed = pch - Buf->buf;
2778 return Buf->BufUsed;
2782 * replace all chars >0x20 && < 0x7F with Mute
2783 * Mute char to put over invalid chars
2784 * Buf Buffor to transform
2786 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute) {
2789 if (Buf == NULL) return -1;
2790 pch = (unsigned char *)Buf->buf;
2791 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2792 if ((*pch < 0x20) || (*pch > 0x7F))
2796 return Buf->BufUsed;
2801 * remove escaped strings from i.e. the url string (like %20 for blanks)
2802 * Buf Buffer to translate
2803 * StripBlanks Reduce several blanks to one?
2805 long StrBufUnescape(StrBuf *Buf, int StripBlanks) {
2813 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2814 Buf->buf[Buf->BufUsed - 1] = '\0';
2819 while (a < Buf->BufUsed) {
2820 if (Buf->buf[a] == '+')
2822 else if (Buf->buf[a] == '%') {
2823 /* don't let % chars through, rather truncate the input. */
2824 if (a + 2 > Buf->BufUsed) {
2829 hex[0] = Buf->buf[a + 1];
2830 hex[1] = Buf->buf[a + 2];
2833 sscanf(hex, "%02x", &b);
2834 Buf->buf[a] = (char) b;
2835 len = Buf->BufUsed - a - 2;
2837 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2849 * RFC2047-encode a header field if necessary.
2850 * If no non-ASCII characters are found, the string
2851 * will be copied verbatim without encoding.
2853 * target Target buffer.
2854 * source Source string to be encoded.
2855 * @returns encoded length; -1 if non success.
2857 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source) {
2858 const char headerStr[] = "=?UTF-8?Q?";
2859 int need_to_encode = 0;
2863 if ((source == NULL) ||
2867 while ((i < source->BufUsed) &&
2868 (!IsEmptyStr (&source->buf[i])) &&
2869 (need_to_encode == 0)) {
2870 if (((unsigned char) source->buf[i] < 32) ||
2871 ((unsigned char) source->buf[i] > 126)) {
2877 if (!need_to_encode) {
2878 if (*target == NULL) {
2879 *target = NewStrBufPlain(source->buf, source->BufUsed);
2882 FlushStrBuf(*target);
2883 StrBufAppendBuf(*target, source, 0);
2886 return (*target)->BufUsed;
2890 if (*target == NULL)
2891 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2892 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2893 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2894 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2895 (*target)->BufUsed = sizeof(headerStr) - 1;
2896 for (i=0; (i < source->BufUsed); ++i) {
2897 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2898 IncreaseBuf(*target, 1, 0);
2899 ch = (unsigned char) source->buf[i];
2908 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2909 (*target)->BufUsed += 3;
2913 (*target)->buf[(*target)->BufUsed] = '_';
2915 (*target)->buf[(*target)->BufUsed] = ch;
2916 (*target)->BufUsed++;
2920 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2921 IncreaseBuf(*target, 1, 0);
2923 (*target)->buf[(*target)->BufUsed++] = '?';
2924 (*target)->buf[(*target)->BufUsed++] = '=';
2925 (*target)->buf[(*target)->BufUsed] = '\0';
2926 return (*target)->BufUsed;;
2929 // Quoted-Printable encode a message; make it < 80 columns width.
2930 // source Source string to be encoded.
2931 // returns buffer with encoded message.
2932 StrBuf *StrBufQuotedPrintableEncode(const StrBuf *EncodeMe) {
2935 const char *ptr, *eptr;
2939 OutBuf = NewStrBufPlain(NULL, StrLength(EncodeMe) * 4);
2941 OEptr = OutBuf->buf + OutBuf->BufSize;
2942 ptr = EncodeMe->buf;
2943 eptr = EncodeMe->buf + EncodeMe->BufUsed;
2946 while (ptr < eptr) {
2947 if (Optr + 4 >= OEptr) {
2949 Offset = Optr - OutBuf->buf;
2950 OutBuf->BufUsed = Optr - OutBuf->buf;
2951 IncreaseBuf(OutBuf, 1, 0);
2952 Optr = OutBuf->buf + Offset;
2953 OEptr = OutBuf->buf + OutBuf->BufSize;
2955 if (*ptr == '\r') { // ignore carriage returns
2958 else if (*ptr == '\n') { // hard line break
2959 memcpy(Optr, HKEY("=0A"));
2964 else if (( (*ptr >= 32) && (*ptr <= 60) ) || ( (*ptr >= 62) && (*ptr <= 126) )) {
2974 *Optr = HexList[ch][0];
2976 *Optr = HexList[ch][1];
2982 if (LinePos > 72) { // soft line break
2983 if (isspace(*(Optr - 1))) {
2988 *Optr = HexList[ch][0];
2990 *Optr = HexList[ch][1];
3002 OutBuf->BufUsed = Optr - OutBuf->buf;
3008 static void AddRecipient(StrBuf *Target, StrBuf *UserName, StrBuf *EmailAddress, StrBuf *EncBuf) {
3011 if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
3012 if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
3014 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
3015 StrBufRFC2047encode(&EncBuf, UserName);
3016 StrBufAppendBuf(Target, EncBuf, 0);
3017 if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
3018 else StrBufAppendBufPlain(Target, HKEY(" "), 0);
3020 if (StrLength(EmailAddress) > 0){
3021 StrBufAppendBufPlain(Target, HKEY("<"), 0);
3022 StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
3023 StrBufAppendBufPlain(Target, HKEY(">"), 0);
3029 * \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
3030 * \param Recp Source list of email recipients
3031 * \param UserName Temporary buffer for internal use; Please provide valid buffer.
3032 * \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
3033 * \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
3034 * \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
3036 StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp, StrBuf *UserName, StrBuf *EmailAddress, StrBuf *EncBuf) {
3038 const char *pch, *pche;
3039 const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
3041 if ((Recp == NULL) || (StrLength(Recp) == 0))
3045 pche = pch + StrLength(Recp);
3047 if (!CheckEncode(pch, -1, pche))
3048 return NewStrBufDup(Recp);
3050 Target = NewStrBufPlain(NULL, StrLength(Recp));
3052 while ((pch != NULL) && (pch < pche))
3054 while (isspace(*pch)) pch++;
3055 UserEnd = EmailStart = EmailEnd = NULL;
3057 if ((*pch == '"') || (*pch == '\'')) {
3058 UserStart = pch + 1;
3060 UserEnd = strchr(UserStart, *pch);
3061 if (UserEnd == NULL)
3062 break; ///TODO: Userfeedback??
3063 EmailStart = UserEnd + 1;
3064 while (isspace(*EmailStart))
3066 if (UserEnd == UserStart) {
3067 UserStart = UserEnd = NULL;
3070 if (*EmailStart == '<') {
3072 EmailEnd = strchr(EmailStart, '>');
3073 if (EmailEnd == NULL)
3074 EmailEnd = strchr(EmailStart, ',');
3078 EmailEnd = strchr(EmailStart, ',');
3080 if (EmailEnd == NULL)
3087 EmailEnd = strchr(UserStart, ',');
3088 if (EmailEnd == NULL) {
3089 EmailEnd = strchr(pch, '>');
3091 if (EmailEnd != NULL) {
3101 while ((EmailEnd > UserStart) && !gt &&
3102 ((*EmailEnd == ',') ||
3103 (*EmailEnd == '>') ||
3104 (isspace(*EmailEnd))))
3106 if (*EmailEnd == '>')
3111 if (EmailEnd == UserStart)
3115 EmailStart = strchr(UserStart, '<');
3116 if ((EmailStart == NULL) || (EmailStart > EmailEnd))
3118 UserEnd = EmailStart;
3120 while ((UserEnd > UserStart) &&
3121 isspace (*(UserEnd - 1)))
3124 if (UserStart >= UserEnd)
3125 UserStart = UserEnd = NULL;
3127 else { /* this is a local recipient... no domain, just a realname */
3128 EmailStart = UserStart;
3129 At = strchr(EmailStart, '@');
3135 EmailStart = UserStart;
3141 if ((UserStart != NULL) && (UserEnd != NULL))
3142 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
3143 else if ((UserStart != NULL) && (UserEnd == NULL))
3144 StrBufPlain(UserName, UserStart, UserEnd - UserStart);
3146 FlushStrBuf(UserName);
3148 if ((EmailStart != NULL) && (EmailEnd != NULL))
3149 StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
3150 else if ((EmailStart != NULL) && (EmailEnd == NULL))
3151 StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
3153 FlushStrBuf(EmailAddress);
3155 AddRecipient(Target, UserName, EmailAddress, EncBuf);
3160 if ((pch != NULL) && (*pch == ','))
3162 if (pch != NULL) while (isspace(*pch))
3170 * replaces all occurances of 'search' by 'replace'
3171 * buf Buffer to modify
3172 * search character to search
3173 * replace character to replace search by
3175 void StrBufReplaceChars(StrBuf *buf, char search, char replace) {
3179 for (i=0; i<buf->BufUsed; i++)
3180 if (buf->buf[i] == search)
3181 buf->buf[i] = replace;
3186 * removes all \\r s from the string, or replaces them with \n if its not a combination of both.
3187 * buf Buffer to modify
3189 void StrBufToUnixLF(StrBuf *buf) {
3190 char *pche, *pchS, *pchT;
3194 pche = buf->buf + buf->BufUsed;
3195 pchS = pchT = buf->buf;
3201 if (*pchS != '\n') {
3210 buf->BufUsed = pchT - buf->buf;
3214 /*******************************************************************************
3215 * Iconv Wrapper; RFC822 de/encoding *
3216 *******************************************************************************/
3219 * Wrapper around iconv_open()
3220 * Our version adds aliases for non-standard Microsoft charsets
3221 * such as 'MS950', aliasing them to names like 'CP950'
3223 * tocode Target encoding
3224 * fromcode Source encoding
3225 * pic anonimized pointer to iconv struct
3227 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic) {
3229 iconv_t ic = (iconv_t)(-1) ;
3230 ic = iconv_open(tocode, fromcode);
3231 if (ic == (iconv_t)(-1) ) {
3232 char alias_fromcode[64];
3233 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
3234 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
3235 alias_fromcode[0] = 'C';
3236 alias_fromcode[1] = 'P';
3237 ic = iconv_open(tocode, alias_fromcode);
3240 *(iconv_t *)pic = ic;
3246 * find one chunk of a RFC822 encoded string
3247 * Buffer where to search
3248 * bptr where to start searching
3249 * @returns found position, NULL if none.
3251 static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr) {
3253 /* Find the next ?Q? */
3254 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
3257 end = strchr(bptr + 2, '?');
3262 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
3263 (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
3264 ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) &&
3265 (*(end + 2) == '?')) {
3266 /* skip on to the end of the cluster, the next ?= */
3267 end = strstr(end + 3, "?=");
3270 /* sort of half valid encoding, try to find an end. */
3271 end = strstr(bptr, "?=");
3278 * convert one buffer according to the preselected iconv pointer PIC
3279 * ConvertBuf buffer we need to translate
3280 * TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
3281 * pic Pointer to the iconv-session Object
3283 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic) {
3288 char *ibuf; /**< Buffer of characters to be converted */
3289 char *obuf; /**< Buffer for converted characters */
3290 size_t ibuflen; /**< Length of input buffer */
3291 size_t obuflen; /**< Length of output buffer */
3294 if ((ConvertBuf == NULL) || (TmpBuf == NULL))
3297 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
3298 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
3299 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
3301 ic = *(iconv_t*)pic;
3302 ibuf = ConvertBuf->buf;
3303 ibuflen = ConvertBuf->BufUsed;
3305 obuflen = TmpBuf->BufSize;
3307 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
3310 if (errno == E2BIG) {
3312 IncreaseBuf(TmpBuf, 0, 0);
3317 else if (errno == EILSEQ){
3318 /* hm, invalid utf8 sequence... what to do now? */
3319 /* An invalid multibyte sequence has been encountered in the input */
3321 else if (errno == EINVAL) {
3322 /* An incomplete multibyte sequence has been encountered in the input. */
3325 FlushStrBuf(TmpBuf);
3328 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
3329 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
3331 /* little card game: wheres the red lady? */
3332 iSwapBuffers(ConvertBuf, TmpBuf);
3333 FlushStrBuf(TmpBuf);
3340 * catches one RFC822 encoded segment, and decodes it.
3341 * Target buffer to fill with result
3342 * DecodeMe buffer with stuff to process
3343 * SegmentStart points to our current segment in DecodeMe
3344 * SegmentEnd Points to the end of our current segment in DecodeMe
3345 * ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
3346 * ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
3347 * FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
3349 inline static void DecodeSegment(StrBuf *Target,
3350 const StrBuf *DecodeMe,
3351 const char *SegmentStart,
3352 const char *SegmentEnd,
3354 StrBuf *ConvertBuf2,
3355 StrBuf *FoundCharset)
3361 iconv_t ic = (iconv_t)(-1);
3365 /* Now we handle foreign character sets properly encoded
3366 * in RFC2047 format.
3368 StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
3369 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
3370 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
3371 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
3372 if (FoundCharset != NULL) {
3373 FlushStrBuf(FoundCharset);
3374 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
3376 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
3377 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
3379 *encoding = toupper(*encoding);
3380 if (*encoding == 'B') { /**< base64 */
3381 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3382 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3383 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
3385 ConvertBuf->BufUsed);
3387 else if (*encoding == 'Q') { /**< quoted-printable */
3391 while (pos < ConvertBuf->BufUsed)
3393 if (ConvertBuf->buf[pos] == '_')
3394 ConvertBuf->buf[pos] = ' ';
3398 if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
3399 IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
3401 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
3404 ConvertBuf->BufUsed);
3407 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
3410 ctdl_iconv_open("UTF-8", charset, &ic);
3411 if (ic != (iconv_t)(-1) ) {
3413 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
3414 StrBufAppendBuf(Target, ConvertBuf2, 0);
3419 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
3425 * Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
3426 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3427 * Target where to put the decoded string to
3428 * DecodeMe buffer with encoded string
3429 * DefaultCharset if we don't find one, which should we use?
3430 * FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3431 * put it here for later use where no string might be known.
3433 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset) {
3435 StrBuf *ConvertBuf2;
3436 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
3437 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
3439 StrBuf_RFC822_2_Utf8(Target,
3445 FreeStrBuf(&ConvertBuf);
3446 FreeStrBuf(&ConvertBuf2);
3450 * Handle subjects with RFC2047 encoding such as:
3451 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
3452 * Target where to put the decoded string to
3453 * DecodeMe buffer with encoded string
3454 * DefaultCharset if we don't find one, which should we use?
3455 * FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
3456 * put it here for later use where no string might be known.
3457 * ConvertBuf workbuffer. feed in, you shouldn't care about its content.
3458 * ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
3460 void StrBuf_RFC822_2_Utf8(StrBuf *Target,
3461 const StrBuf *DecodeMe,
3462 const StrBuf* DefaultCharset,
3463 StrBuf *FoundCharset,
3465 StrBuf *ConvertBuf2)
3467 StrBuf *DecodedInvalidBuf = NULL;
3468 const StrBuf *DecodeMee = DecodeMe;
3469 const char *start, *end, *next, *nextend, *ptr = NULL;
3471 iconv_t ic = (iconv_t)(-1) ;
3476 int illegal_non_rfc2047_encoding = 0;
3479 if (DecodeMe == NULL)
3481 /* Sometimes, badly formed messages contain strings which were simply
3482 * written out directly in some foreign character set instead of
3483 * using RFC2047 encoding. This is illegal but we will attempt to
3484 * handle it anyway by converting from a user-specified default
3485 * charset to UTF-8 if we see any nonprintable characters.
3488 for (i=0; i<DecodeMe->BufUsed; ++i) {
3489 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
3490 illegal_non_rfc2047_encoding = 1;
3495 if ((illegal_non_rfc2047_encoding) &&
3496 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
3497 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
3500 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
3501 if (ic != (iconv_t)(-1) ) {
3502 DecodedInvalidBuf = NewStrBufDup(DecodeMe);
3503 StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
3504 DecodeMee = DecodedInvalidBuf;
3510 /* pre evaluate the first pair */
3512 start = strstr(DecodeMee->buf, "=?");
3513 eptr = DecodeMee->buf + DecodeMee->BufUsed;
3515 end = FindNextEnd (DecodeMee, start + 2);
3517 StrBufAppendBuf(Target, DecodeMee, 0);
3518 FreeStrBuf(&DecodedInvalidBuf);
3523 if (start != DecodeMee->buf) {
3526 nFront = start - DecodeMee->buf;
3527 StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
3530 * Since spammers will go to all sorts of absurd lengths to get their
3531 * messages through, there are LOTS of corrupt headers out there.
3532 * So, prevent a really badly formed RFC2047 header from throwing
3533 * this function into an infinite loop.
3535 while ((start != NULL) &&
3542 DecodeSegment(Target,
3550 next = strstr(end, "=?");
3552 if ((next != NULL) &&
3554 nextend = FindNextEnd(DecodeMee, next);
3555 if (nextend == NULL)
3558 /* did we find two partitions */
3559 if ((next != NULL) &&
3563 while ((ptr < next) &&
3570 * did we find a gab just filled with blanks?
3571 * if not, copy its stuff over.
3575 StrBufAppendBufPlain(Target,
3581 /* our next-pair is our new first pair now. */
3587 nextend = DecodeMee->buf + DecodeMee->BufUsed;
3588 if ((end != NULL) && (end < nextend)) {
3590 while ( (ptr < nextend) &&
3597 StrBufAppendBufPlain(Target, end, nextend - end, 0);
3599 FreeStrBuf(&DecodedInvalidBuf);
3602 /*******************************************************************************
3603 * Manipulating UTF-8 Strings *
3604 *******************************************************************************/
3607 * evaluate the length of an utf8 special character sequence
3608 * Char the character to examine
3609 * @returns width of utf8 chars in bytes; if the sequence is broken 0 is returned; 1 if its simply ASCII.
3611 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE) {
3613 unsigned char test = (1<<7);
3615 if ((*CharS & 0xC0) != 0xC0)
3619 ((test & ((unsigned char)*CharS)) != 0))
3624 if ((n > 6) || ((CharE - CharS) < n))
3630 * detect whether this char starts an utf-8 encoded char
3631 * Char character to inspect
3632 * @returns yes or no
3634 static inline int Ctdl_IsUtf8SequenceStart(const char Char) {
3635 /** 11??.???? indicates an UTF8 Sequence. */
3636 return ((Char & 0xC0) == 0xC0);
3640 * measure the number of glyphs in an UTF8 string...
3641 * Buf string to measure
3642 * @returns the number of glyphs in Buf
3644 long StrBuf_Utf8StrLen(StrBuf *Buf) {
3649 if ((Buf == NULL) || (Buf->BufUsed == 0))
3652 eptr = Buf->buf + Buf->BufUsed;
3653 while ((aptr < eptr) && (*aptr != '\0')) {
3654 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3655 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3656 while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
3668 * cuts a string after maxlen glyphs
3669 * Buf string to cut to maxlen glyphs
3670 * maxlen how long may the string become?
3671 * @returns current length of the string
3673 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen) {
3678 eptr = Buf->buf + Buf->BufUsed;
3679 while ((aptr < eptr) && (*aptr != '\0')) {
3680 if (Ctdl_IsUtf8SequenceStart(*aptr)){
3681 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
3682 while ((*aptr++ != '\0') && (m-- > 0));
3691 Buf->BufUsed = aptr - Buf->buf;
3692 return Buf->BufUsed;
3695 return Buf->BufUsed;
3700 /*******************************************************************************
3702 *******************************************************************************/
3705 * uses the same calling syntax as compress2(), but it
3706 * creates a stream compatible with HTTP "Content-encoding: gzip"
3707 * dest compressed buffer
3708 * destLen length of the compresed data
3709 * source source to encode
3710 * sourceLen length of source to encode
3711 * level compression level
3714 int ZEXPORT compress_gzip(Bytef * dest,
3716 const Bytef * source,
3720 /* write gzip header */
3721 snprintf((char *) dest, *destLen,
3722 "%c%c%c%c%c%c%c%c%c%c",
3723 gz_magic[0], gz_magic[1], Z_DEFLATED,
3724 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
3727 /* normal deflate */
3730 stream.next_in = (Bytef *) source;
3731 stream.avail_in = (uInt) sourceLen;
3732 stream.next_out = dest + 10L; // after header
3733 stream.avail_out = (uInt) * destLen;
3734 if ((uLong) stream.avail_out != *destLen)
3737 stream.zalloc = (alloc_func) 0;
3738 stream.zfree = (free_func) 0;
3739 stream.opaque = (voidpf) 0;
3741 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
3742 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
3746 err = deflate(&stream, Z_FINISH);
3747 if (err != Z_STREAM_END) {
3748 deflateEnd(&stream);
3749 return err == Z_OK ? Z_BUF_ERROR : err;
3751 *destLen = stream.total_out + 10L;
3753 /* write CRC and Length */
3754 uLong crc = crc32(0L, source, sourceLen);
3756 for (n = 0; n < 4; ++n, ++*destLen) {
3757 dest[*destLen] = (int) (crc & 0xff);
3760 uLong len = stream.total_in;
3761 for (n = 0; n < 4; ++n, ++*destLen) {
3762 dest[*destLen] = (int) (len & 0xff);
3765 err = deflateEnd(&stream);
3772 * compress the buffer with gzip
3773 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
3774 * Buf buffer whose content is to be gzipped
3776 int CompressBuffer(StrBuf *Buf) {
3778 char *compressed_data = NULL;
3779 size_t compressed_len, bufsize;
3782 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
3783 compressed_data = malloc(compressed_len);
3785 if (compressed_data == NULL)
3787 /* Flush some space after the used payload so valgrind shuts up... */
3788 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
3789 Buf->buf[Buf->BufUsed + i++] = '\0';
3790 if (compress_gzip((Bytef *) compressed_data,
3793 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
3796 Buf->buf = compressed_data;
3797 Buf->BufUsed = compressed_len;
3798 Buf->BufSize = bufsize;
3799 /* 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';
3805 free(compressed_data);
3807 #endif /* HAVE_ZLIB */
3812 /*******************************************************************************
3813 * File I/O; Callbacks to libevent *
3814 *******************************************************************************/
3816 long StrBuf_read_one_chunk_callback (int fd, short event, IOBuffer *FB) {
3820 if ((FB == NULL) || (FB->Buf == NULL))
3824 * check whether the read pointer is somewhere in a range
3825 * where a cut left is inexpensive
3828 if (FB->ReadWritePointer != NULL) {
3831 already_read = FB->ReadWritePointer - FB->Buf->buf;
3832 bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3834 if (already_read != 0) {
3837 unread = FB->Buf->BufUsed - already_read;
3839 /* else nothing to compact... */
3841 FB->ReadWritePointer = FB->Buf->buf;
3842 bufremain = FB->Buf->BufSize;
3844 else if ((unread < 64) || (bufremain < already_read)) {
3846 * if its just a tiny bit remaining, or we run out of space...
3849 FB->Buf->BufUsed = unread;
3850 if (unread < already_read)
3851 memcpy(FB->Buf->buf, FB->ReadWritePointer, unread);
3853 memmove(FB->Buf->buf, FB->ReadWritePointer, unread);
3854 FB->ReadWritePointer = FB->Buf->buf;
3855 bufremain = FB->Buf->BufSize - unread - 1;
3857 else if (bufremain < (FB->Buf->BufSize / 10)) {
3858 /* get a bigger buffer */
3860 IncreaseBuf(FB->Buf, 0, FB->Buf->BufUsed + 1);
3862 FB->ReadWritePointer = FB->Buf->buf + unread;
3864 bufremain = FB->Buf->BufSize - unread - 1;
3865 /*TODO: special increase function that won't copy the already read! */
3868 else if (bufremain < 10) {
3869 IncreaseBuf(FB->Buf, 1, FB->Buf->BufUsed + 10);
3871 FB->ReadWritePointer = FB->Buf->buf;
3873 bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
3878 FB->ReadWritePointer = FB->Buf->buf;
3879 bufremain = FB->Buf->BufSize - 1;
3882 n = read(fd, FB->Buf->buf + FB->Buf->BufUsed, bufremain);
3885 FB->Buf->BufUsed += n;
3886 FB->Buf->buf[FB->Buf->BufUsed] = '\0';
3892 int StrBuf_write_one_chunk_callback(int fd, short event, IOBuffer *FB) {
3896 if ((FB == NULL) || (FB->Buf == NULL))
3899 if (FB->ReadWritePointer != NULL)
3901 WriteRemain = FB->Buf->BufUsed -
3902 (FB->ReadWritePointer -
3906 FB->ReadWritePointer = FB->Buf->buf;
3907 WriteRemain = FB->Buf->BufUsed;
3910 n = write(fd, FB->ReadWritePointer, WriteRemain);
3912 FB->ReadWritePointer += n;
3914 if (FB->ReadWritePointer ==
3915 FB->Buf->buf + FB->Buf->BufUsed)
3917 FlushStrBuf(FB->Buf);
3918 FB->ReadWritePointer = NULL;
3921 // check whether we've got something to write
3922 // get the maximum chunk plus the pointer we can send
3923 // write whats there
3924 // if not all was sent, remember the send pointer for the next time
3925 return FB->ReadWritePointer - FB->Buf->buf + FB->Buf->BufUsed;
3931 // extract a "next line" from Buf; Ptr to persist across several iterations
3932 // LineBuf your line will be copied here.
3933 // FB BLOB with lines of text...
3934 // Ptr moved arround to keep the next-line across several iterations
3935 // has to be &NULL on start; will be &NotNULL on end of buffer
3936 // returns size of copied buffer
3937 eReadState StrBufChunkSipLine(StrBuf *LineBuf, IOBuffer *FB) {
3938 const char *aptr, *ptr, *eptr;
3941 if ((FB == NULL) || (LineBuf == NULL) || (LineBuf->buf == NULL))
3945 if ((FB->Buf == NULL) || (FB->ReadWritePointer == StrBufNOTNULL)) {
3946 FB->ReadWritePointer = StrBufNOTNULL;
3950 FlushStrBuf(LineBuf);
3951 if (FB->ReadWritePointer == NULL)
3952 ptr = aptr = FB->Buf->buf;
3954 ptr = aptr = FB->ReadWritePointer;
3956 optr = LineBuf->buf;
3957 eptr = FB->Buf->buf + FB->Buf->BufUsed;
3958 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3960 while ((ptr <= eptr) && (*ptr != '\n') && (*ptr != '\r') ) {
3964 LineBuf->BufUsed = optr - LineBuf->buf;
3965 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
3966 optr = LineBuf->buf + LineBuf->BufUsed;
3967 xptr = LineBuf->buf + LineBuf->BufSize - 1;
3972 if (optr > LineBuf->buf)
3974 if ((*(ptr - 1) != '\r') && (*(ptr - 1) != '\n')) {
3975 LineBuf->BufUsed = optr - LineBuf->buf;
3977 if ((FB->ReadWritePointer != NULL) && (FB->ReadWritePointer != FB->Buf->buf)) {
3978 // Ok, the client application read all the data
3979 // it was interested in so far. Since there is more to read,
3980 // we now shrink the buffer, and move the rest over.
3981 StrBufCutLeft(FB->Buf, FB->ReadWritePointer - FB->Buf->buf);
3982 FB->ReadWritePointer = FB->Buf->buf;
3984 return eMustReadMore;
3987 LineBuf->BufUsed = optr - LineBuf->buf;
3989 if ((ptr <= eptr) && (*ptr == '\r'))
3991 if ((ptr <= eptr) && (*ptr == '\n'))
3995 FB->ReadWritePointer = ptr;
3998 FlushStrBuf(FB->Buf);
3999 FB->ReadWritePointer = NULL;
4002 return eReadSuccess;
4006 * check whether the chunk-buffer has more data waiting or not.
4007 * FB Chunk-Buffer to inspect
4009 eReadState StrBufCheckBuffer(IOBuffer *FB) {
4012 if (FB->Buf->BufUsed == 0)
4013 return eReadSuccess;
4014 if (FB->ReadWritePointer == NULL)
4015 return eBufferNotEmpty;
4016 if (FB->Buf->buf + FB->Buf->BufUsed > FB->ReadWritePointer)
4017 return eBufferNotEmpty;
4018 return eReadSuccess;
4022 long IOBufferStrLength(IOBuffer *FB) {
4023 if ((FB == NULL) || (FB->Buf == NULL))
4025 if (FB->ReadWritePointer == NULL)
4026 return StrLength(FB->Buf);
4028 return StrLength(FB->Buf) - (FB->ReadWritePointer - FB->Buf->buf);
4032 /*******************************************************************************
4033 * File I/O; Prefer buffered read since its faster! *
4034 *******************************************************************************/
4037 * Read a line from socket
4038 * flushes and closes the FD on error
4039 * buf the buffer to get the input to
4040 * fd pointer to the filedescriptor to read
4041 * append Append to an existing string or replace?
4042 * Error strerror() on error
4043 * @returns numbers of chars read
4045 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error) {
4046 int len, rlen, slen;
4048 if ((buf == NULL) || (buf->buf == NULL)) {
4049 *Error = strerror(EINVAL);
4056 slen = len = buf->BufUsed;
4058 rlen = read(*fd, &buf->buf[len], 1);
4060 *Error = strerror(errno);
4067 if (buf->buf[len] == '\n')
4069 if (buf->buf[len] != '\r')
4071 if (len + 2 >= buf->BufSize) {
4073 buf->buf[len+1] = '\0';
4074 IncreaseBuf(buf, 1, -1);
4078 buf->buf[len] = '\0';
4083 // Read a line from socket
4084 // flushes and closes the FD on error
4085 // Line the line to read from the fd / I/O Buffer
4086 // buf the buffer to get the input to
4087 // fd pointer to the filedescriptor to read
4088 // timeout number of successless selects until we bail out
4089 // selectresolution how long to wait on each select
4090 // Error strerror() on error
4091 // returns numbers of chars read
4092 int StrBufTCP_read_buffered_line(StrBuf *Line,
4096 int selectresolution,
4100 int nSuccessLess = 0;
4107 if (buf->BufUsed > 0) {
4108 pch = strchr(buf->buf, '\n');
4111 len = pch - buf->buf;
4112 if (len > 0 && (*(pch - 1) == '\r') ) {
4115 StrBufSub(Line, buf, 0, len - rlen);
4116 StrBufCutLeft(buf, len + 1);
4121 if (buf->BufSize - buf->BufUsed < 10) {
4122 IncreaseBuf(buf, 1, -1);
4125 fdflags = fcntl(*fd, F_GETFL);
4126 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4128 while ((nSuccessLess < timeout) && (pch == NULL)) {
4130 tv.tv_sec = selectresolution;
4135 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
4136 *Error = strerror(errno);
4142 if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
4146 rlen = read(*fd, &buf->buf[buf->BufUsed], buf->BufSize - buf->BufUsed - 1);
4148 *Error = strerror(errno);
4153 else if (rlen > 0) {
4155 buf->BufUsed += rlen;
4156 buf->buf[buf->BufUsed] = '\0';
4157 pch = strchr(buf->buf, '\n');
4158 if ((pch == NULL) && (buf->BufUsed + 10 > buf->BufSize) && (IncreaseBuf(buf, 1, -1) == -1)) {
4167 len = pch - buf->buf;
4168 if (len > 0 && (*(pch - 1) == '\r') )
4170 StrBufSub(Line, buf, 0, len - rlen);
4171 StrBufCutLeft(buf, len + 1);
4178 static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
4179 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
4180 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
4183 // Read a line from socket
4184 // flushes and closes the FD on error
4185 // Line where to append our Line read from the fd / I/O Buffer;
4186 // IOBuf the buffer to get the input to; lifetime pair to FD
4187 // Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
4188 // fd pointer to the filedescriptor to read
4189 // timeout number of successless selects until we bail out
4190 // selectresolution how long to wait on each select
4191 // Error strerror() on error
4192 // returns numbers of chars read or -1 in case of error. "\n" will become 0
4193 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
4198 int selectresolution,
4201 const char *pche = NULL;
4202 const char *pos = NULL;
4204 int len, rlen, retlen;
4205 int nSuccessLess = 0;
4207 const char *pch = NULL;
4213 if ((Line == NULL) || (Pos == NULL) || (IOBuf == NULL) || (*fd == -1)) {
4217 *Error = ErrRBLF_PreConditionFailed;
4222 if ((IOBuf->BufUsed > 0) && (pos != NULL) && (pos < IOBuf->buf + IOBuf->BufUsed)) {
4225 pche = IOBuf->buf + IOBuf->BufUsed;
4229 while ((pch < pche) && (*pch != '\n')) {
4230 if (Line->BufUsed + 10 > Line->BufSize) {
4232 apos = pcht - Line->buf;
4234 IncreaseBuf(Line, 1, -1);
4235 pcht = Line->buf + apos;
4243 if (len > 0 && (*(pch - 1) == '\r') ) {
4251 if ((pch >= pche) || (*pch == '\0')) {
4258 if ((pch != NULL) && (pch <= pche)) {
4259 if (pch + 1 >= pche) {
4272 /* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
4274 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
4275 IncreaseBuf(IOBuf, 1, -1);
4278 fdflags = fcntl(*fd, F_GETFL);
4279 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4282 while ((nSuccessLess < timeout) &&
4291 if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
4292 *Error = strerror(errno);
4296 *Error = ErrRBLF_SelectFailed;
4299 if (! FD_ISSET(*fd, &rfds) != 0) {
4304 rlen = read(*fd, &IOBuf->buf[IOBuf->BufUsed], IOBuf->BufSize - IOBuf->BufUsed - 1);
4306 *Error = strerror(errno);
4311 else if (rlen > 0) {
4313 pLF = IOBuf->buf + IOBuf->BufUsed;
4314 IOBuf->BufUsed += rlen;
4315 IOBuf->buf[IOBuf->BufUsed] = '\0';
4317 pche = IOBuf->buf + IOBuf->BufUsed;
4319 while ((pLF < pche) && (*pLF != '\n'))
4321 if ((pLF >= pche) || (*pLF == '\0'))
4324 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
4327 if (pLF != NULL) apos = pLF - IOBuf->buf;
4328 IncreaseBuf(IOBuf, 1, -1);
4329 if (pLF != NULL) pLF = IOBuf->buf + apos;
4342 if (len > 0 && (*(pLF - 1) == '\r') ) {
4345 StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
4346 if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed) {
4351 return retlen + len;
4353 *Error = ErrRBLF_NotEnoughSentFromServer;
4358 static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
4360 * Input binary data from socket
4361 * flushes and closes the FD on error
4362 * Buf the buffer to get the input to
4363 * fd pointer to the filedescriptor to read
4364 * append Append to an existing string or replace?
4365 * nBytes the maximal number of bytes to read
4366 * Error strerror() on error
4367 * @returns numbers of chars read
4369 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error) {
4379 if ((Buf == NULL) || (Buf->buf == NULL) || (*fd == -1)) {
4380 *Error = ErrRBLF_BLOBPreConditionFailed;
4386 if (Buf->BufUsed + nBytes >= Buf->BufSize) {
4387 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
4389 ptr = Buf->buf + Buf->BufUsed;
4391 fdflags = fcntl(*fd, F_GETFL);
4392 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4394 while ((nRead < nBytes) && (*fd != -1)) {
4401 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4402 *Error = strerror(errno);
4405 if (*Error == NULL) {
4406 *Error = ErrRBLF_SelectFailed;
4410 if (! FD_ISSET(*fd, &rfds) != 0) {
4416 if ((rlen = read(*fd,
4418 nBytes - nRead)) == -1) {
4421 *Error = strerror(errno);
4426 Buf->BufUsed += rlen;
4428 Buf->buf[Buf->BufUsed] = '\0';
4432 const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
4433 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
4436 // Input binary data from socket
4437 // flushes and closes the FD on error
4438 // Blob put binary thing here
4439 // IOBuf the buffer to get the input to
4440 // Pos offset inside of IOBuf
4441 // fd pointer to the filedescriptor to read
4442 // append Append to an existing string or replace?
4443 // nBytes the maximal number of bytes to read
4444 // check whether we should search for '000\n' terminators in case of timeouts
4445 // Error strerror() on error
4446 // returns numbers of chars read
4447 int StrBufReadBLOBBuffered(StrBuf *Blob,
4460 int nAlreadyRead = 0;
4465 int nSuccessLess = 0;
4468 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL)) {
4471 *Error = ErrRBB_BLOBFPreConditionFailed;
4477 if (Blob->BufUsed + nBytes >= Blob->BufSize)
4478 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
4483 rlen = pos - IOBuf->buf;
4485 rlen = IOBuf->BufUsed - rlen;
4488 if ((IOBuf->BufUsed > 0) && (pos != NULL) && (pos < IOBuf->buf + IOBuf->BufUsed)) {
4489 if (rlen < nBytes) {
4490 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
4491 Blob->BufUsed += rlen;
4492 Blob->buf[Blob->BufUsed] = '\0';
4493 nAlreadyRead = nRead = rlen;
4496 if (rlen >= nBytes) {
4497 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
4498 Blob->BufUsed += nBytes;
4499 Blob->buf[Blob->BufUsed] = '\0';
4500 if (rlen == nBytes) {
4512 if (IOBuf->BufSize < nBytes - nRead) {
4513 IncreaseBuf(IOBuf, 0, nBytes - nRead);
4517 fdflags = fcntl(*fd, F_GETFL);
4518 IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
4526 while ((nSuccessLess < MaxTries) && (nRead < nBytes) && (*fd != -1)) {
4533 if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4534 *Error = strerror(errno);
4537 if (*Error == NULL) {
4538 *Error = ErrRBLF_SelectFailed;
4542 if (! FD_ISSET(*fd, &rfds) != 0) {
4547 rlen = read(*fd, ptr, IOBuf->BufSize - (ptr - IOBuf->buf));
4548 if (rlen < 1) { // We will always get at least 1 byte unless the connection is broken
4551 *Error = strerror(errno);
4554 else if (rlen == 0){
4555 if ((check == NNN_TERM) && (nRead > 5) && (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0)) {
4556 StrBufPlain(Blob, HKEY("\n000\n"));
4557 StrBufCutRight(Blob, 5);
4558 return Blob->BufUsed;
4560 else if (!IsNonBlock)
4562 else if (nSuccessLess > MaxTries) {
4564 *Error = ErrRBB_too_many_selects;
4568 else if (rlen > 0) {
4572 IOBuf->BufUsed += rlen;
4575 if (nSuccessLess >= MaxTries) {
4577 *Error = ErrRBB_too_many_selects;
4581 if (nRead > nBytes) {
4582 *Pos = IOBuf->buf + nBytes;
4584 Blob->buf[Blob->BufUsed] = '\0';
4585 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
4589 return nRead + nAlreadyRead;
4593 // extract a "next line" from Buf; Ptr to persist across several iterations
4594 // LineBuf your line will be copied here.
4595 // Buf BLOB with lines of text...
4596 // Ptr moved arround to keep the next-line across several iterations
4597 // has to be &NULL on start; will be &NotNULL on end of buffer
4598 // returns size of remaining buffer
4599 int StrBufSipLine(StrBuf *LineBuf, const StrBuf *Buf, const char **Ptr) {
4600 const char *aptr, *ptr, *eptr;
4603 if ((Buf == NULL) || (*Ptr == StrBufNOTNULL) || (LineBuf == NULL)|| (LineBuf->buf == NULL)) {
4604 *Ptr = StrBufNOTNULL;
4608 FlushStrBuf(LineBuf);
4610 ptr = aptr = Buf->buf;
4614 optr = LineBuf->buf;
4615 eptr = Buf->buf + Buf->BufUsed;
4616 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4618 while ((ptr <= eptr) && (*ptr != '\n') && (*ptr != '\r') ) {
4622 LineBuf->BufUsed = optr - LineBuf->buf;
4623 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
4624 optr = LineBuf->buf + LineBuf->BufUsed;
4625 xptr = LineBuf->buf + LineBuf->BufSize - 1;
4629 if ((ptr >= eptr) && (optr > LineBuf->buf))
4631 LineBuf->BufUsed = optr - LineBuf->buf;
4633 if ((ptr <= eptr) && (*ptr == '\r'))
4635 if ((ptr <= eptr) && (*ptr == '\n'))
4642 *Ptr = StrBufNOTNULL;
4645 return Buf->BufUsed - (ptr - Buf->buf);
4649 // removes double slashes from pathnames
4650 // Dir directory string to filter
4651 // RemoveTrailingSlash allows / disallows trailing slashes
4652 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash) {
4657 while (!IsEmptyStr(a)) {
4669 if ((RemoveTrailingSlash) &&
4675 Dir->BufUsed = b - Dir->buf;
4679 // Decode a quoted-printable encoded StrBuf buffer "in place"
4680 // This is possible because the decoded will always be shorter than the encoded
4681 // so we don't have to worry about the buffer being to small.
4682 void StrBufDecodeQP(StrBuf *Buf) {
4683 if (!Buf) { // sanity check #1
4687 int source_len = StrLength(Buf);
4688 if (source_len < 1) { // sanity check #2
4692 int spos = 0; // source position
4693 int tpos = 0; // target position
4695 while (spos < source_len) {
4696 if (!strncmp(&Buf->buf[spos], "=\r\n", 3)) {
4699 else if (!strncmp(&Buf->buf[spos], "=\n", 2)) {
4702 else if (Buf->buf[spos] == '=') {
4705 sscanf(&Buf->buf[spos], "%02x", &ch);
4706 Buf->buf[tpos++] = ch;
4710 Buf->buf[tpos++] = Buf->buf[spos++];
4715 Buf->BufUsed = tpos;