8 #include <sys/select.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
13 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
28 int BaseStrBufSize = 64;
31 * Private Structure for the Stringbuffer
34 char *buf; /**< the pointer to the dynamic buffer */
35 long BufSize; /**< how many spcae do we optain */
36 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
37 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 char bt_lastinc [SIZ];
47 static void StrBufBacktrace(StrBuf *Buf, int which)
51 void *stack_frames[50];
56 pstart = pch = Buf->bt;
58 pstart = pch = Buf->bt_lastinc;
59 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
60 strings = backtrace_symbols(stack_frames, size);
61 for (i = 0; i < size; i++) {
63 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
65 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
76 * \Brief Cast operator to Plain String
77 * Note: if the buffer is altered by StrBuf operations, this pointer may become
78 * invalid. So don't lean on it after altering the buffer!
79 * Since this operation is considered cheap, rather call it often than risking
80 * your pointer to become invalid!
81 * \param Str the string we want to get the c-string representation for
82 * \returns the Pointer to the Content. Don't mess with it!
84 inline const char *ChrPtr(const StrBuf *Str)
92 * \brief since we know strlen()'s result, provide it here.
93 * \param Str the string to return the length to
94 * \returns contentlength of the buffer
96 inline int StrLength(const StrBuf *Str)
98 return (Str != NULL) ? Str->BufUsed : 0;
102 * \brief local utility function to resize the buffer
103 * \param Buf the buffer whichs storage we should increase
104 * \param KeepOriginal should we copy the original buffer or just start over with a new one
105 * \param DestSize what should fit in after?
107 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
110 size_t NewSize = Buf->BufSize * 2;
116 while (NewSize <= DestSize)
119 NewBuf= (char*) malloc(NewSize);
120 if (KeepOriginal && (Buf->BufUsed > 0))
122 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
131 Buf->BufSize = NewSize;
135 StrBufBacktrace(Buf, 1);
142 * \brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
143 * \param Buf Buffer to shrink (has to be empty)
144 * \param ThreshHold if the buffer is bigger then this, its readjusted
145 * \param NewSize if we Shrink it, how big are we going to be afterwards?
147 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
149 if (Buf->BufUsed > ThreshHold) {
151 Buf->buf = (char*) malloc(NewSize);
153 Buf->BufSize = NewSize;
158 * \brief shrink long term buffers to their real size so they don't waste memory
159 * \param Buf buffer to shrink
160 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
161 * \returns physical size of the buffer
163 long StrBufShrinkToFit(StrBuf *Buf, int Force)
166 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
168 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
169 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
170 Buf->BufSize = Buf->BufUsed + 1;
178 * Allocate a new buffer with default buffer size
179 * \returns the new stringbuffer
181 StrBuf* NewStrBuf(void)
185 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
186 NewBuf->buf = (char*) malloc(BaseStrBufSize);
187 NewBuf->buf[0] = '\0';
188 NewBuf->BufSize = BaseStrBufSize;
190 NewBuf->ConstBuf = 0;
192 NewBuf->nIncreases = 0;
193 NewBuf->bt[0] = '\0';
194 NewBuf->bt_lastinc[0] = '\0';
196 StrBufBacktrace(NewBuf, 0);
203 * \brief Copy Constructor; returns a duplicate of CopyMe
204 * \params CopyMe Buffer to faxmilate
205 * \returns the new stringbuffer
207 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
216 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
217 NewBuf->BufUsed = CopyMe->BufUsed;
218 NewBuf->BufSize = CopyMe->BufSize;
219 NewBuf->ConstBuf = 0;
221 NewBuf->nIncreases = 0;
222 NewBuf->bt[0] = '\0';
223 NewBuf->bt_lastinc[0] = '\0';
225 StrBufBacktrace(NewBuf, 0);
232 * \brief create a new Buffer using an existing c-string
233 * this function should also be used if you want to pre-suggest
234 * the buffer size to allocate in conjunction with ptr == NULL
235 * \param ptr the c-string to copy; may be NULL to create a blank instance
236 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
237 * \returns the new stringbuffer
239 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
242 size_t Siz = BaseStrBufSize;
245 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
247 CopySize = strlen((ptr != NULL)?ptr:"");
251 while (Siz <= CopySize)
254 NewBuf->buf = (char*) malloc(Siz);
255 NewBuf->BufSize = Siz;
257 memcpy(NewBuf->buf, ptr, CopySize);
258 NewBuf->buf[CopySize] = '\0';
259 NewBuf->BufUsed = CopySize;
262 NewBuf->buf[0] = '\0';
265 NewBuf->ConstBuf = 0;
267 NewBuf->nIncreases = 0;
268 NewBuf->bt[0] = '\0';
269 NewBuf->bt_lastinc[0] = '\0';
271 StrBufBacktrace(NewBuf, 0);
278 * \brief Set an existing buffer from a c-string
279 * \param ptr c-string to put into
280 * \param nChars set to -1 if we should work 0-terminated
281 * \returns the new length of the string
283 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
285 size_t Siz = Buf->BufSize;
289 CopySize = strlen(ptr);
293 while (Siz <= CopySize)
296 if (Siz != Buf->BufSize)
297 IncreaseBuf(Buf, 0, Siz);
298 memcpy(Buf->buf, ptr, CopySize);
299 Buf->buf[CopySize] = '\0';
300 Buf->BufUsed = CopySize;
307 * \brief use strbuf as wrapper for a string constant for easy handling
308 * \param StringConstant a string to wrap
309 * \param SizeOfConstant should be sizeof(StringConstant)-1
311 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
315 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
316 NewBuf->buf = (char*) StringConstant;
317 NewBuf->BufSize = SizeOfStrConstant;
318 NewBuf->BufUsed = SizeOfStrConstant;
319 NewBuf->ConstBuf = 1;
321 NewBuf->nIncreases = 0;
322 NewBuf->bt[0] = '\0';
323 NewBuf->bt_lastinc[0] = '\0';
330 * \brief flush the content of a Buf; keep its struct
331 * \param buf Buffer to flush
333 int FlushStrBuf(StrBuf *buf)
345 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
346 * \param buf Buffer to wipe
348 int FLUSHStrBuf(StrBuf *buf)
354 if (buf->BufUsed > 0) {
355 memset(buf->buf, 0, buf->BufUsed);
362 int hFreeDbglog = -1;
365 * \brief Release a Buffer
366 * Its a double pointer, so it can NULL your pointer
367 * so fancy SIG11 appear instead of random results
368 * \param FreeMe Pointer Pointer to the buffer to free
370 void FreeStrBuf (StrBuf **FreeMe)
375 if (hFreeDbglog == -1){
376 pid_t pid = getpid();
378 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
379 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
381 if ((*FreeMe)->nIncreases > 0)
385 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
386 (*FreeMe)->nIncreases,
390 (*FreeMe)->bt_lastinc);
391 n = write(hFreeDbglog, buf, n);
397 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
400 n = write(hFreeDbglog, buf, n);
403 if (!(*FreeMe)->ConstBuf)
404 free((*FreeMe)->buf);
410 * \brief Release the buffer
411 * If you want put your StrBuf into a Hash, use this as Destructor.
412 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
414 void HFreeStrBuf (void *VFreeMe)
416 StrBuf *FreeMe = (StrBuf*)VFreeMe;
420 if (hFreeDbglog == -1){
421 pid_t pid = getpid();
423 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
424 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
426 if (FreeMe->nIncreases > 0)
430 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
436 write(hFreeDbglog, buf, n);
442 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
448 if (!FreeMe->ConstBuf)
454 * \brief Wrapper around atol
456 long StrTol(const StrBuf *Buf)
461 return atol(Buf->buf);
467 * \brief Wrapper around atoi
469 int StrToi(const StrBuf *Buf)
473 if (Buf->BufUsed > 0)
474 return atoi(Buf->buf);
480 * \brief Checks to see if the string is a pure number
482 int StrBufIsNumber(const StrBuf *Buf) {
487 strtoll(Buf->buf, &pEnd, 10);
488 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
494 * \brief modifies a Single char of the Buf
495 * You can point to it via char* or a zero-based integer
496 * \param ptr char* to zero; use NULL if unused
497 * \param nThChar zero based pointer into the string; use -1 if unused
498 * \param PeekValue The Character to place into the position
500 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
505 nThChar = ptr - Buf->buf;
506 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
508 Buf->buf[nThChar] = PeekValue;
513 * \brief Append a StringBuffer to the buffer
514 * \param Buf Buffer to modify
515 * \param AppendBuf Buffer to copy at the end of our buffer
516 * \param Offset Should we start copying from an offset?
518 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
520 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
523 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
526 AppendBuf->BufUsed + Buf->BufUsed);
528 memcpy(Buf->buf + Buf->BufUsed,
529 AppendBuf->buf + Offset,
530 AppendBuf->BufUsed - Offset);
531 Buf->BufUsed += AppendBuf->BufUsed - Offset;
532 Buf->buf[Buf->BufUsed] = '\0';
537 * \brief Append a C-String to the buffer
538 * \param Buf Buffer to modify
539 * \param AppendBuf Buffer to copy at the end of our buffer
540 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
541 * \param Offset Should we start copying from an offset?
543 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
546 long BufSizeRequired;
548 if ((AppendBuf == NULL) || (Buf == NULL))
552 aps = strlen(AppendBuf + Offset);
554 aps = AppendSize - Offset;
556 BufSizeRequired = Buf->BufUsed + aps + 1;
557 if (Buf->BufSize <= BufSizeRequired)
558 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
560 memcpy(Buf->buf + Buf->BufUsed,
564 Buf->buf[Buf->BufUsed] = '\0';
569 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
570 * \param outbuf the output buffer
571 * \param oblen the size of outbuf to sanitize
572 * \param strbuf the input buffer
574 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
576 const char *pch, *pche;
579 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
580 int eclen = sizeof(ec) -1;
582 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
584 if (PlainIn != NULL) {
585 len = strlen(PlainIn);
591 pche = pch + In->BufUsed;
598 pt = OutBuf->buf + OutBuf->BufUsed;
599 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
603 IncreaseBuf(OutBuf, 1, -1);
604 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
605 pt = OutBuf->buf + OutBuf->BufUsed;
609 for (b = 0; b < eclen; ++b) {
616 sprintf(pt,"%%%02X", *pch);
618 OutBuf->BufUsed += 3;
630 * \brief Append a string, escaping characters which have meaning in HTML.
632 * \param Target target buffer
633 * \param Source source buffer; set to NULL if you just have a C-String
634 * \param PlainIn Plain-C string to append; set to NULL if unused
635 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
636 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
637 * if set to 2, linebreaks are replaced by <br/>
639 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
641 const char *aptr, *eiptr;
645 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
648 if (PlainIn != NULL) {
650 len = strlen(PlainIn);
655 eiptr = aptr + Source->BufUsed;
656 len = Source->BufUsed;
662 bptr = Target->buf + Target->BufUsed;
663 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
665 while (aptr < eiptr){
667 IncreaseBuf(Target, 1, -1);
668 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
669 bptr = Target->buf + Target->BufUsed;
672 memcpy(bptr, "<", 4);
674 Target->BufUsed += 4;
676 else if (*aptr == '>') {
677 memcpy(bptr, ">", 4);
679 Target->BufUsed += 4;
681 else if (*aptr == '&') {
682 memcpy(bptr, "&", 5);
684 Target->BufUsed += 5;
686 else if (*aptr == '"') {
687 memcpy(bptr, """, 6);
689 Target->BufUsed += 6;
691 else if (*aptr == '\'') {
692 memcpy(bptr, "'", 5);
694 Target->BufUsed += 5;
696 else if (*aptr == LB) {
701 else if (*aptr == RB) {
706 else if (*aptr == QU) {
711 else if ((*aptr == 32) && (nbsp == 1)) {
712 memcpy(bptr, " ", 6);
714 Target->BufUsed += 6;
716 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
717 *bptr='\0'; /* nothing */
719 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
720 memcpy(bptr, "<br/>", 11);
722 Target->BufUsed += 11;
726 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
727 *bptr='\0'; /* nothing */
737 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
739 return Target->BufUsed;
743 * \brief Append a string, escaping characters which have meaning in HTML.
744 * Converts linebreaks into blanks; escapes single quotes
745 * \param Target target buffer
746 * \param Source source buffer; set to NULL if you just have a C-String
747 * \param PlainIn Plain-C string to append; set to NULL if unused
749 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
751 const char *aptr, *eiptr;
755 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
758 if (PlainIn != NULL) {
760 len = strlen(PlainIn);
765 eiptr = aptr + Source->BufUsed;
766 len = Source->BufUsed;
772 eptr = Target->buf + Target->BufSize - 8;
773 tptr = Target->buf + Target->BufUsed;
775 while (aptr < eiptr){
777 IncreaseBuf(Target, 1, -1);
778 eptr = Target->buf + Target->BufSize - 8;
779 tptr = Target->buf + Target->BufUsed;
786 else if (*aptr == '\r') {
790 else if (*aptr == '\'') {
796 Target->BufUsed += 5;
807 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
809 * \param Target target buffer
810 * \param Source source buffer; set to NULL if you just have a C-String
811 * \param PlainIn Plain-C string to append; set to NULL if unused
813 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
815 const char *aptr, *eiptr;
819 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
822 if (PlainIn != NULL) {
824 len = strlen(PlainIn);
829 eiptr = aptr + Source->BufUsed;
830 len = Source->BufUsed;
836 bptr = Target->buf + Target->BufUsed;
837 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
839 while (aptr < eiptr){
841 IncreaseBuf(Target, 1, -1);
842 eptr = Target->buf + Target->BufSize - 3;
843 bptr = Target->buf + Target->BufUsed;
845 else if (*aptr == '"') {
850 Target->BufUsed += 2;
851 } else if (*aptr == '\\') {
856 Target->BufUsed += 2;
866 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
868 return Target->BufUsed;
872 * \brief extracts a substring from Source into dest
873 * \param dest buffer to place substring into
874 * \param Source string to copy substring from
875 * \param Offset chars to skip from start
876 * \param nChars number of chars to copy
877 * \returns the number of chars copied; may be different from nChars due to the size of Source
879 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
882 if (Offset > Source->BufUsed)
887 if (Offset + nChars < Source->BufUsed)
889 if (nChars >= dest->BufSize)
890 IncreaseBuf(dest, 0, nChars + 1);
891 memcpy(dest->buf, Source->buf + Offset, nChars);
892 dest->BufUsed = nChars;
893 dest->buf[dest->BufUsed] = '\0';
896 NCharsRemain = Source->BufUsed - Offset;
897 if (NCharsRemain >= dest->BufSize)
898 IncreaseBuf(dest, 0, NCharsRemain + 1);
899 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
900 dest->BufUsed = NCharsRemain;
901 dest->buf[dest->BufUsed] = '\0';
906 * \brief sprintf like function appending the formated string to the buffer
907 * vsnprintf version to wrap into own calls
908 * \param Buf Buffer to extend by format and params
909 * \param format printf alike format to add
910 * \param ap va_list containing the items for format
912 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
915 size_t BufSize = Buf->BufSize;
916 size_t nWritten = Buf->BufSize + 1;
917 size_t Offset = Buf->BufUsed;
918 size_t newused = Offset + nWritten;
920 while (newused >= BufSize) {
922 nWritten = vsnprintf(Buf->buf + Offset,
923 Buf->BufSize - Offset,
926 newused = Offset + nWritten;
927 if (newused >= Buf->BufSize) {
928 IncreaseBuf(Buf, 1, newused);
929 newused = Buf->BufSize + 1;
932 Buf->BufUsed = Offset + nWritten;
933 BufSize = Buf->BufSize;
940 * \brief sprintf like function appending the formated string to the buffer
941 * \param Buf Buffer to extend by format and params
942 * \param format printf alike format to add
943 * \param ap va_list containing the items for format
945 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
947 size_t BufSize = Buf->BufSize;
948 size_t nWritten = Buf->BufSize + 1;
949 size_t Offset = Buf->BufUsed;
950 size_t newused = Offset + nWritten;
953 while (newused >= BufSize) {
954 va_start(arg_ptr, format);
955 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
956 Buf->BufSize - Buf->BufUsed,
959 newused = Buf->BufUsed + nWritten;
960 if (newused >= Buf->BufSize) {
961 IncreaseBuf(Buf, 1, newused);
962 newused = Buf->BufSize + 1;
965 Buf->BufUsed += nWritten;
966 BufSize = Buf->BufSize;
973 * \brief sprintf like function putting the formated string into the buffer
974 * \param Buf Buffer to extend by format and params
975 * \param format printf alike format to add
976 * \param ap va_list containing the items for format
978 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
980 size_t nWritten = Buf->BufSize + 1;
983 while (nWritten >= Buf->BufSize) {
984 va_start(arg_ptr, format);
985 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
987 if (nWritten >= Buf->BufSize) {
988 IncreaseBuf(Buf, 0, 0);
989 nWritten = Buf->BufSize + 1;
992 Buf->BufUsed = nWritten ;
998 * \brief Counts the numbmer of tokens in a buffer
999 * \param Source String to count tokens in
1000 * \param tok Tokenizer char to count
1001 * \returns numbers of tokenizer chars found
1003 int StrBufNum_tokens(const StrBuf *source, char tok)
1007 return num_tokens(source->buf, tok);
1011 * remove_token() - a tokenizer that kills, maims, and destroys
1014 * \brief a string tokenizer
1015 * \param Source StringBuffer to read into
1016 * \param parmnum n'th parameter to remove
1017 * \param separator tokenizer param
1018 * \returns -1 if not found, else length of token.
1020 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1023 char *d, *s; /* dest, source */
1026 /* Find desired parameter */
1028 while (count < parmnum) {
1029 /* End of string, bail! */
1034 if (*d == separator) {
1039 if (!d) return 0; /* Parameter not found */
1041 /* Find next parameter */
1043 while (*s && *s != separator) {
1046 if (*s == separator)
1050 /* Hack and slash */
1052 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1053 Source->BufUsed -= (ReducedBy + 1);
1055 else if (d == Source->buf) {
1057 Source->BufUsed = 0;
1061 Source->BufUsed -= (ReducedBy + 1);
1074 * \brief a string tokenizer
1075 * \param dest Destination StringBuffer
1076 * \param Source StringBuffer to read into
1077 * \param parmnum n'th parameter to extract
1078 * \param separator tokenizer param
1079 * \returns -1 if not found, else length of token.
1081 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1083 const char *s, *e; //* source * /
1084 int len = 0; //* running total length of extracted string * /
1085 int current_token = 0; //* token currently being processed * /
1088 dest->buf[0] = '\0';
1094 if ((Source == NULL) || (Source->BufUsed ==0)) {
1098 e = s + Source->BufUsed;
1101 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1103 while ((s<e) && !IsEmptyStr(s)) {
1104 if (*s == separator) {
1107 if (len >= dest->BufSize) {
1108 dest->BufUsed = len;
1109 if (!IncreaseBuf(dest, 1, -1))
1112 if ( (current_token == parmnum) &&
1113 (*s != separator)) {
1114 dest->buf[len] = *s;
1117 else if (current_token > parmnum) {
1123 dest->buf[len] = '\0';
1124 dest->BufUsed = len;
1126 if (current_token < parmnum) {
1127 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1130 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1139 * \brief a string tokenizer to fetch an integer
1140 * \param dest Destination StringBuffer
1141 * \param parmnum n'th parameter to extract
1142 * \param separator tokenizer param
1143 * \returns 0 if not found, else integer representation of the token
1145 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1155 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1162 * \brief a string tokenizer to fetch a long integer
1163 * \param dest Destination StringBuffer
1164 * \param parmnum n'th parameter to extract
1165 * \param separator tokenizer param
1166 * \returns 0 if not found, else long integer representation of the token
1168 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1178 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1186 * \brief a string tokenizer to fetch an unsigned long
1187 * \param dest Destination StringBuffer
1188 * \param parmnum n'th parameter to extract
1189 * \param separator tokenizer param
1190 * \returns 0 if not found, else unsigned long representation of the token
1192 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1203 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1207 return (unsigned long) atol(pnum);
1216 * \brief a string tokenizer
1217 * \param dest Destination StringBuffer
1218 * \param Source StringBuffer to read into
1219 * \param pStart pointer to the end of the last token. Feed with NULL.
1220 * \param separator tokenizer param
1221 * \returns -1 if not found, else length of token.
1223 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1225 const char *s, *EndBuffer; //* source * /
1226 int len = 0; //* running total length of extracted string * /
1227 int current_token = 0; //* token currently being processed * /
1230 dest->buf[0] = '\0';
1236 if ((Source == NULL) ||
1237 (Source->BufUsed ==0)) {
1240 if (*pStart == NULL)
1241 *pStart = Source->buf;
1243 EndBuffer = Source->buf + Source->BufUsed;
1245 if ((*pStart < Source->buf) ||
1246 (*pStart > EndBuffer)) {
1254 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1256 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1257 if (*s == separator) {
1260 if (len >= dest->BufSize) {
1261 dest->BufUsed = len;
1262 if (!IncreaseBuf(dest, 1, -1)) {
1263 *pStart = EndBuffer + 1;
1267 if ( (current_token == 0) &&
1268 (*s != separator)) {
1269 dest->buf[len] = *s;
1272 else if (current_token > 0) {
1281 dest->buf[len] = '\0';
1282 dest->BufUsed = len;
1283 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1284 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1290 * \brief a string tokenizer
1291 * \param dest Destination StringBuffer
1292 * \param Source StringBuffer to read into
1293 * \param pStart pointer to the end of the last token. Feed with NULL.
1294 * \param separator tokenizer param
1295 * \returns -1 if not found, else length of token.
1297 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1299 const char *s, *EndBuffer; //* source * /
1300 int len = 0; //* running total length of extracted string * /
1301 int current_token = 0; //* token currently being processed * /
1303 if ((Source == NULL) ||
1304 (Source->BufUsed ==0)) {
1308 return Source->BufUsed;
1310 if (*pStart == NULL)
1311 *pStart = Source->buf;
1313 EndBuffer = Source->buf + Source->BufUsed;
1315 if ((*pStart < Source->buf) ||
1316 (*pStart > EndBuffer)) {
1324 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1326 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1327 if (*s == separator) {
1330 if (current_token >= nTokens) {
1342 * \brief a string tokenizer to fetch an integer
1343 * \param dest Destination StringBuffer
1344 * \param parmnum n'th parameter to extract
1345 * \param separator tokenizer param
1346 * \returns 0 if not found, else integer representation of the token
1348 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1358 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1365 * \brief a string tokenizer to fetch a long integer
1366 * \param dest Destination StringBuffer
1367 * \param parmnum n'th parameter to extract
1368 * \param separator tokenizer param
1369 * \returns 0 if not found, else long integer representation of the token
1371 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1381 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1389 * \brief a string tokenizer to fetch an unsigned long
1390 * \param dest Destination StringBuffer
1391 * \param parmnum n'th parameter to extract
1392 * \param separator tokenizer param
1393 * \returns 0 if not found, else unsigned long representation of the token
1395 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1406 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1410 return (unsigned long) atol(pnum);
1419 * \brief Read a line from socket
1420 * flushes and closes the FD on error
1421 * \param buf the buffer to get the input to
1422 * \param fd pointer to the filedescriptor to read
1423 * \param append Append to an existing string or replace?
1424 * \param Error strerror() on error
1425 * \returns numbers of chars read
1427 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1429 int len, rlen, slen;
1434 slen = len = buf->BufUsed;
1436 rlen = read(*fd, &buf->buf[len], 1);
1438 *Error = strerror(errno);
1445 if (buf->buf[len] == '\n')
1447 if (buf->buf[len] != '\r')
1449 if (len >= buf->BufSize) {
1451 buf->buf[len+1] = '\0';
1452 IncreaseBuf(buf, 1, -1);
1456 buf->buf[len] = '\0';
1461 * \brief Read a line from socket
1462 * flushes and closes the FD on error
1463 * \param buf the buffer to get the input to
1464 * \param fd pointer to the filedescriptor to read
1465 * \param append Append to an existing string or replace?
1466 * \param Error strerror() on error
1467 * \returns numbers of chars read
1469 int StrBufTCP_read_buffered_line(StrBuf *Line,
1473 int selectresolution,
1477 int nSuccessLess = 0;
1483 if (buf->BufUsed > 0) {
1484 pch = strchr(buf->buf, '\n');
1487 len = pch - buf->buf;
1488 if (len > 0 && (*(pch - 1) == '\r') )
1490 StrBufSub(Line, buf, 0, len - rlen);
1491 StrBufCutLeft(buf, len + 1);
1496 if (buf->BufSize - buf->BufUsed < 10)
1497 IncreaseBuf(buf, 1, -1);
1499 fdflags = fcntl(*fd, F_GETFL);
1500 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1503 while ((nSuccessLess < timeout) && (pch == NULL)) {
1504 tv.tv_sec = selectresolution;
1509 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1510 *Error = strerror(errno);
1515 if (FD_ISSET(*fd, &rfds)) {
1517 &buf->buf[buf->BufUsed],
1518 buf->BufSize - buf->BufUsed - 1);
1520 *Error = strerror(errno);
1525 else if (rlen > 0) {
1527 buf->BufUsed += rlen;
1528 buf->buf[buf->BufUsed] = '\0';
1529 if (buf->BufUsed + 10 > buf->BufSize) {
1530 IncreaseBuf(buf, 1, -1);
1532 pch = strchr(buf->buf, '\n');
1540 len = pch - buf->buf;
1541 if (len > 0 && (*(pch - 1) == '\r') )
1543 StrBufSub(Line, buf, 0, len - rlen);
1544 StrBufCutLeft(buf, len + 1);
1552 * \brief Read a line from socket
1553 * flushes and closes the FD on error
1554 * \param buf the buffer to get the input to
1555 * \param Pos pointer to the current read position, should be NULL initialized!
1556 * \param fd pointer to the filedescriptor to read
1557 * \param append Append to an existing string or replace?
1558 * \param Error strerror() on error
1559 * \returns numbers of chars read
1561 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1566 int selectresolution,
1569 const char *pche = NULL;
1570 const char *pos = NULL;
1572 int nSuccessLess = 0;
1574 const char *pch = NULL;
1579 if ((IOBuf->BufUsed > 0) &&
1581 (pos < IOBuf->buf + IOBuf->BufUsed))
1583 pche = IOBuf->buf + IOBuf->BufUsed;
1585 while ((pch < pche) && (*pch != '\n'))
1587 if ((pch >= pche) || (*pch == '\0'))
1589 if ((pch != NULL) &&
1594 if (len > 0 && (*(pch - 1) == '\r') )
1596 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1606 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1610 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1611 IncreaseBuf(IOBuf, 1, -1);
1614 fdflags = fcntl(*fd, F_GETFL);
1615 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1619 while ((nSuccessLess < timeout) && (pch == NULL)) {
1620 tv.tv_sec = selectresolution;
1625 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1626 *Error = strerror(errno);
1631 if (FD_ISSET(*fd, &rfds) != 0) {
1633 &IOBuf->buf[IOBuf->BufUsed],
1634 IOBuf->BufSize - IOBuf->BufUsed - 1);
1636 *Error = strerror(errno);
1641 else if (rlen > 0) {
1643 IOBuf->BufUsed += rlen;
1644 IOBuf->buf[IOBuf->BufUsed] = '\0';
1645 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1646 IncreaseBuf(IOBuf, 1, -1);
1649 pche = IOBuf->buf + IOBuf->BufUsed;
1651 while ((pch < pche) && (*pch != '\n'))
1653 if ((pch >= pche) || (*pch == '\0'))
1664 if (len > 0 && (*(pch - 1) == '\r') )
1666 StrBufSub(Line, IOBuf, 0, len - rlen);
1667 *Pos = pos + len + 1;
1675 * \brief Input binary data from socket
1676 * flushes and closes the FD on error
1677 * \param buf the buffer to get the input to
1678 * \param fd pointer to the filedescriptor to read
1679 * \param append Append to an existing string or replace?
1680 * \param nBytes the maximal number of bytes to read
1681 * \param Error strerror() on error
1682 * \returns numbers of chars read
1684 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1688 int len, rlen, slen;
1692 if ((Buf == NULL) || (*fd == -1))
1696 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1697 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1699 ptr = Buf->buf + Buf->BufUsed;
1701 slen = len = Buf->BufUsed;
1703 fdflags = fcntl(*fd, F_GETFL);
1705 while (nRead < nBytes) {
1706 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1709 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1710 *Error = strerror(errno);
1715 if ((rlen = read(*fd,
1717 nBytes - nRead)) == -1) {
1720 *Error = strerror(errno);
1725 Buf->BufUsed += rlen;
1727 Buf->buf[Buf->BufUsed] = '\0';
1732 * \brief Input binary data from socket
1733 * flushes and closes the FD on error
1734 * \param buf the buffer to get the input to
1735 * \param fd pointer to the filedescriptor to read
1736 * \param append Append to an existing string or replace?
1737 * \param nBytes the maximal number of bytes to read
1738 * \param Error strerror() on error
1739 * \returns numbers of chars read
1741 int StrBufReadBLOBBuffered(StrBuf *Blob,
1762 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1766 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1767 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1772 len = pos - IOBuf->buf;
1773 rlen = IOBuf->BufUsed - len;
1776 if ((IOBuf->BufUsed > 0) &&
1778 (pos < IOBuf->buf + IOBuf->BufUsed))
1780 pche = IOBuf->buf + IOBuf->BufUsed;
1783 if (rlen < nBytes) {
1784 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1785 Blob->BufUsed += rlen;
1786 Blob->buf[Blob->BufUsed] = '\0';
1790 if (rlen >= nBytes) {
1791 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1792 Blob->BufUsed += nBytes;
1793 Blob->buf[Blob->BufUsed] = '\0';
1794 if (rlen == nBytes) {
1805 if (IOBuf->BufSize < nBytes - nRead)
1806 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1809 slen = len = Blob->BufUsed;
1811 fdflags = fcntl(*fd, F_GETFL);
1816 while (nRead < nBytes) {
1817 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1820 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1823 *Error = strerror(errno);
1834 *Error = strerror(errno);
1840 if ((check == NNN_TERM) &&
1842 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1844 StrBufPlain(Blob, HKEY("\n000\n"));
1845 StrBufCutRight(Blob, 5);
1846 return Blob->BufUsed;
1848 if (nSelects > 10) {
1856 IOBuf->BufUsed += rlen;
1859 if (nRead > nBytes) {
1860 *Pos = IOBuf->buf + nBytes;
1862 Blob->buf[Blob->BufUsed] = '\0';
1863 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1868 * \brief Cut nChars from the start of the string
1869 * \param Buf Buffer to modify
1870 * \param nChars how many chars should be skipped?
1872 void StrBufCutLeft(StrBuf *Buf, int nChars)
1874 if (nChars >= Buf->BufUsed) {
1878 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1879 Buf->BufUsed -= nChars;
1880 Buf->buf[Buf->BufUsed] = '\0';
1884 * \brief Cut the trailing n Chars from the string
1885 * \param Buf Buffer to modify
1886 * \param nChars how many chars should be trunkated?
1888 void StrBufCutRight(StrBuf *Buf, int nChars)
1890 if (nChars >= Buf->BufUsed) {
1894 Buf->BufUsed -= nChars;
1895 Buf->buf[Buf->BufUsed] = '\0';
1899 * \brief Cut the string after n Chars
1900 * \param Buf Buffer to modify
1901 * \param AfternChars after how many chars should we trunkate the string?
1902 * \param At if non-null and points inside of our string, cut it there.
1904 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1907 AfternChars = At - Buf->buf;
1910 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1912 Buf->BufUsed = AfternChars;
1913 Buf->buf[Buf->BufUsed] = '\0';
1918 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1919 * buf - the string to modify
1920 * len - length of the string.
1922 void StrBufTrim(StrBuf *Buf)
1925 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1927 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1930 if (delta > 0) StrBufCutLeft(Buf, delta);
1932 if (Buf->BufUsed == 0) return;
1933 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1936 Buf->buf[Buf->BufUsed] = '\0';
1940 void StrBufUpCase(StrBuf *Buf)
1945 pche = pch + Buf->BufUsed;
1946 while (pch < pche) {
1947 *pch = toupper(*pch);
1953 void StrBufLowerCase(StrBuf *Buf)
1958 pche = pch + Buf->BufUsed;
1959 while (pch < pche) {
1960 *pch = tolower(*pch);
1966 * \Brief removes double slashes from pathnames
1967 * \param Dir directory string to filter
1968 * \param RemoveTrailingSlash allows / disallows trailing slashes
1970 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
1976 while (!IsEmptyStr(a)) {
1988 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
1993 Dir->BufUsed = b - Dir->buf;
1997 * \brief unhide special chars hidden to the HTML escaper
1998 * \param target buffer to put the unescaped string in
1999 * \param source buffer to unescape
2001 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2007 FlushStrBuf(target);
2009 if (source == NULL ||target == NULL)
2014 len = source->BufUsed;
2015 for (a = 0; a < len; ++a) {
2016 if (target->BufUsed >= target->BufSize)
2017 IncreaseBuf(target, 1, -1);
2019 if (source->buf[a] == '=') {
2020 hex[0] = source->buf[a + 1];
2021 hex[1] = source->buf[a + 2];
2024 sscanf(hex, "%02x", &b);
2025 target->buf[target->BufUsed] = b;
2026 target->buf[++target->BufUsed] = 0;
2030 target->buf[target->BufUsed] = source->buf[a];
2031 target->buf[++target->BufUsed] = 0;
2038 * \brief hide special chars from the HTML escapers and friends
2039 * \param target buffer to put the escaped string in
2040 * \param source buffer to escape
2042 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2047 FlushStrBuf(target);
2049 if (source == NULL ||target == NULL)
2054 len = source->BufUsed;
2055 for (i=0; i<len; ++i) {
2056 if (target->BufUsed + 4 >= target->BufSize)
2057 IncreaseBuf(target, 1, -1);
2058 if ( (isalnum(source->buf[i])) ||
2059 (source->buf[i]=='-') ||
2060 (source->buf[i]=='_') ) {
2061 target->buf[target->BufUsed++] = source->buf[i];
2064 sprintf(&target->buf[target->BufUsed],
2066 (0xFF &source->buf[i]));
2067 target->BufUsed += 3;
2070 target->buf[target->BufUsed + 1] = '\0';
2074 * \brief uses the same calling syntax as compress2(), but it
2075 * creates a stream compatible with HTTP "Content-encoding: gzip"
2078 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2079 #define OS_CODE 0x03 /*< unix */
2080 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2081 size_t * destLen, /*< length of the compresed data */
2082 const Bytef * source, /*< source to encode */
2083 uLong sourceLen, /*< length of source to encode */
2084 int level) /*< compression level */
2086 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2088 /* write gzip header */
2089 snprintf((char *) dest, *destLen,
2090 "%c%c%c%c%c%c%c%c%c%c",
2091 gz_magic[0], gz_magic[1], Z_DEFLATED,
2092 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2095 /* normal deflate */
2098 stream.next_in = (Bytef *) source;
2099 stream.avail_in = (uInt) sourceLen;
2100 stream.next_out = dest + 10L; // after header
2101 stream.avail_out = (uInt) * destLen;
2102 if ((uLong) stream.avail_out != *destLen)
2105 stream.zalloc = (alloc_func) 0;
2106 stream.zfree = (free_func) 0;
2107 stream.opaque = (voidpf) 0;
2109 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2110 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2114 err = deflate(&stream, Z_FINISH);
2115 if (err != Z_STREAM_END) {
2116 deflateEnd(&stream);
2117 return err == Z_OK ? Z_BUF_ERROR : err;
2119 *destLen = stream.total_out + 10L;
2121 /* write CRC and Length */
2122 uLong crc = crc32(0L, source, sourceLen);
2124 for (n = 0; n < 4; ++n, ++*destLen) {
2125 dest[*destLen] = (int) (crc & 0xff);
2128 uLong len = stream.total_in;
2129 for (n = 0; n < 4; ++n, ++*destLen) {
2130 dest[*destLen] = (int) (len & 0xff);
2133 err = deflateEnd(&stream);
2140 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2142 int CompressBuffer(StrBuf *Buf)
2145 char *compressed_data = NULL;
2146 size_t compressed_len, bufsize;
2149 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2150 compressed_data = malloc(compressed_len);
2152 /* Flush some space after the used payload so valgrind shuts up... */
2153 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2154 Buf->buf[Buf->BufUsed + i++] = '\0';
2155 if (compress_gzip((Bytef *) compressed_data,
2158 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2161 Buf->buf = compressed_data;
2162 Buf->BufUsed = compressed_len;
2163 Buf->BufSize = bufsize;
2164 /* Flush some space after the used payload so valgrind shuts up... */
2166 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2167 Buf->buf[Buf->BufUsed + i++] = '\0';
2170 free(compressed_data);
2172 #endif /* HAVE_ZLIB */
2177 * \brief decode a buffer from base 64 encoding; destroys original
2178 * \param Buf Buffor to transform
2180 int StrBufDecodeBase64(StrBuf *Buf)
2184 if (Buf == NULL) return -1;
2186 xferbuf = (char*) malloc(Buf->BufSize);
2187 siz = CtdlDecodeBase64(xferbuf,
2197 * \brief decode a buffer from base 64 encoding; destroys original
2198 * \param Buf Buffor to transform
2200 int StrBufDecodeHex(StrBuf *Buf)
2203 char *pch, *pche, *pchi;
2205 if (Buf == NULL) return -1;
2207 pch = pchi = Buf->buf;
2208 pche = pch + Buf->BufUsed;
2210 while (pchi < pche){
2211 ch = decode_hex(pchi);
2218 Buf->BufUsed = pch - Buf->buf;
2219 return Buf->BufUsed;
2223 * \brief replace all chars >0x20 && < 0x7F with Mute
2224 * \param Mute char to put over invalid chars
2225 * \param Buf Buffor to transform
2227 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2231 if (Buf == NULL) return -1;
2232 pch = (unsigned char *)Buf->buf;
2233 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2234 if ((*pch < 0x20) || (*pch > 0x7F))
2238 return Buf->BufUsed;
2243 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2244 * \param Buf Buffer to translate
2245 * \param StripBlanks Reduce several blanks to one?
2247 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2253 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2254 Buf->buf[Buf->BufUsed - 1] = '\0';
2259 while (a < Buf->BufUsed) {
2260 if (Buf->buf[a] == '+')
2262 else if (Buf->buf[a] == '%') {
2263 /* don't let % chars through, rather truncate the input. */
2264 if (a + 2 > Buf->BufUsed) {
2269 hex[0] = Buf->buf[a + 1];
2270 hex[1] = Buf->buf[a + 2];
2273 sscanf(hex, "%02x", &b);
2274 Buf->buf[a] = (char) b;
2275 len = Buf->BufUsed - a - 2;
2277 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2289 * \brief RFC2047-encode a header field if necessary.
2290 * If no non-ASCII characters are found, the string
2291 * will be copied verbatim without encoding.
2293 * \param target Target buffer.
2294 * \param source Source string to be encoded.
2295 * \returns encoded length; -1 if non success.
2297 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2299 const char headerStr[] = "=?UTF-8?Q?";
2300 int need_to_encode = 0;
2304 if ((source == NULL) ||
2308 while ((i < source->BufUsed) &&
2309 (!IsEmptyStr (&source->buf[i])) &&
2310 (need_to_encode == 0)) {
2311 if (((unsigned char) source->buf[i] < 32) ||
2312 ((unsigned char) source->buf[i] > 126)) {
2318 if (!need_to_encode) {
2319 if (*target == NULL) {
2320 *target = NewStrBufPlain(source->buf, source->BufUsed);
2323 FlushStrBuf(*target);
2324 StrBufAppendBuf(*target, source, 0);
2326 return (*target)->BufUsed;
2328 if (*target == NULL)
2329 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2330 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2331 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2332 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2333 (*target)->BufUsed = sizeof(headerStr) - 1;
2334 for (i=0; (i < source->BufUsed); ++i) {
2335 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2336 IncreaseBuf(*target, 1, 0);
2337 ch = (unsigned char) source->buf[i];
2338 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2339 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2340 (*target)->BufUsed += 3;
2343 (*target)->buf[(*target)->BufUsed] = ch;
2344 (*target)->BufUsed++;
2348 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2349 IncreaseBuf(*target, 1, 0);
2351 (*target)->buf[(*target)->BufUsed++] = '?';
2352 (*target)->buf[(*target)->BufUsed++] = '=';
2353 (*target)->buf[(*target)->BufUsed] = '\0';
2354 return (*target)->BufUsed;;
2358 * \brief replaces all occurances of 'search' by 'replace'
2359 * \param buf Buffer to modify
2360 * \param search character to search
2361 * \param relpace character to replace search by
2363 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2368 for (i=0; i<buf->BufUsed; i++)
2369 if (buf->buf[i] == search)
2370 buf->buf[i] = replace;
2377 * Wrapper around iconv_open()
2378 * Our version adds aliases for non-standard Microsoft charsets
2379 * such as 'MS950', aliasing them to names like 'CP950'
2381 * tocode Target encoding
2382 * fromcode Source encoding
2384 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2387 iconv_t ic = (iconv_t)(-1) ;
2388 ic = iconv_open(tocode, fromcode);
2389 if (ic == (iconv_t)(-1) ) {
2390 char alias_fromcode[64];
2391 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2392 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2393 alias_fromcode[0] = 'C';
2394 alias_fromcode[1] = 'P';
2395 ic = iconv_open(tocode, alias_fromcode);
2398 *(iconv_t *)pic = ic;
2404 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2407 /* Find the next ?Q? */
2408 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2411 end = strchr(bptr + 2, '?');
2416 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2417 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2418 (*(end + 2) == '?')) {
2419 /* skip on to the end of the cluster, the next ?= */
2420 end = strstr(end + 3, "?=");
2423 /* sort of half valid encoding, try to find an end. */
2424 end = strstr(bptr, "?=");
2428 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2432 memcpy(&C, A, sizeof(*A));
2433 memcpy(A, B, sizeof(*B));
2434 memcpy(B, &C, sizeof(C));
2438 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2444 char *ibuf; /**< Buffer of characters to be converted */
2445 char *obuf; /**< Buffer for converted characters */
2446 size_t ibuflen; /**< Length of input buffer */
2447 size_t obuflen; /**< Length of output buffer */
2450 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2451 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2453 ic = *(iconv_t*)pic;
2454 ibuf = ConvertBuf->buf;
2455 ibuflen = ConvertBuf->BufUsed;
2457 obuflen = TmpBuf->BufSize;
2459 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2462 if (errno == E2BIG) {
2464 IncreaseBuf(TmpBuf, 0, 0);
2469 else if (errno == EILSEQ){
2470 /* hm, invalid utf8 sequence... what to do now? */
2471 /* An invalid multibyte sequence has been encountered in the input */
2473 else if (errno == EINVAL) {
2474 /* An incomplete multibyte sequence has been encountered in the input. */
2477 FlushStrBuf(TmpBuf);
2480 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2481 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2483 /* little card game: wheres the red lady? */
2484 SwapBuffers(ConvertBuf, TmpBuf);
2485 FlushStrBuf(TmpBuf);
2493 inline static void DecodeSegment(StrBuf *Target,
2494 const StrBuf *DecodeMe,
2498 StrBuf *ConvertBuf2,
2499 StrBuf *FoundCharset)
2505 iconv_t ic = (iconv_t)(-1);
2507 /* Now we handle foreign character sets properly encoded
2508 * in RFC2047 format.
2510 StaticBuf.buf = SegmentStart;
2511 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2512 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2513 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2514 if (FoundCharset != NULL) {
2515 FlushStrBuf(FoundCharset);
2516 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2518 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2519 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2521 *encoding = toupper(*encoding);
2522 if (*encoding == 'B') { /**< base64 */
2523 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2525 ConvertBuf->BufUsed);
2527 else if (*encoding == 'Q') { /**< quoted-printable */
2531 while (pos < ConvertBuf->BufUsed)
2533 if (ConvertBuf->buf[pos] == '_')
2534 ConvertBuf->buf[pos] = ' ';
2538 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2541 ConvertBuf->BufUsed);
2544 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2547 ctdl_iconv_open("UTF-8", charset, &ic);
2548 if (ic != (iconv_t)(-1) ) {
2550 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2551 StrBufAppendBuf(Target, ConvertBuf2, 0);
2556 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2561 * Handle subjects with RFC2047 encoding such as:
2562 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2564 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2566 StrBuf *ConvertBuf, *ConvertBuf2;
2567 char *start, *end, *next, *nextend, *ptr = NULL;
2569 iconv_t ic = (iconv_t)(-1) ;
2574 int illegal_non_rfc2047_encoding = 0;
2576 /* Sometimes, badly formed messages contain strings which were simply
2577 * written out directly in some foreign character set instead of
2578 * using RFC2047 encoding. This is illegal but we will attempt to
2579 * handle it anyway by converting from a user-specified default
2580 * charset to UTF-8 if we see any nonprintable characters.
2583 len = StrLength(DecodeMe);
2584 for (i=0; i<DecodeMe->BufUsed; ++i) {
2585 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2586 illegal_non_rfc2047_encoding = 1;
2591 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2592 if ((illegal_non_rfc2047_encoding) &&
2593 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2594 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2597 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2598 if (ic != (iconv_t)(-1) ) {
2599 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2605 /* pre evaluate the first pair */
2606 nextend = end = NULL;
2607 len = StrLength(DecodeMe);
2608 start = strstr(DecodeMe->buf, "=?");
2609 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2611 end = FindNextEnd (DecodeMe, start);
2613 StrBufAppendBuf(Target, DecodeMe, 0);
2614 FreeStrBuf(&ConvertBuf);
2618 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2620 if (start != DecodeMe->buf)
2621 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2623 * Since spammers will go to all sorts of absurd lengths to get their
2624 * messages through, there are LOTS of corrupt headers out there.
2625 * So, prevent a really badly formed RFC2047 header from throwing
2626 * this function into an infinite loop.
2628 while ((start != NULL) &&
2635 DecodeSegment(Target,
2643 next = strstr(end, "=?");
2645 if ((next != NULL) &&
2647 nextend = FindNextEnd(DecodeMe, next);
2648 if (nextend == NULL)
2651 /* did we find two partitions */
2652 if ((next != NULL) &&
2656 while ((ptr < next) &&
2662 /* did we find a gab just filled with blanks? */
2665 long gap = next - start;
2670 /* now terminate the gab at the end */
2671 delta = (next - end) - 2; ////TODO: const!
2672 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2673 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2675 /* move next to its new location. */
2680 /* our next-pair is our new first pair now. */
2686 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2687 if ((end != NULL) && (end < nextend)) {
2689 while ( (ptr < nextend) &&
2696 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2698 FreeStrBuf(&ConvertBuf);
2699 FreeStrBuf(&ConvertBuf2);
2703 * \brief evaluate the length of an utf8 special character sequence
2704 * \param Char the character to examine
2705 * \returns width of utf8 chars in bytes
2707 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2712 while ((n < 8) && ((test & *CharS) != 0)) {
2716 if ((n > 6) || ((CharE - CharS) > n))
2722 * \brief detect whether this char starts an utf-8 encoded char
2723 * \param Char character to inspect
2724 * \returns yes or no
2726 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2728 /** 11??.???? indicates an UTF8 Sequence. */
2729 return ((Char & 0xC0) != 0);
2733 * \brief measure the number of glyphs in an UTF8 string...
2734 * \param str string to measure
2735 * \returns the length of str
2737 long StrBuf_Utf8StrLen(StrBuf *Buf)
2743 if ((Buf == NULL) || (Buf->BufUsed == 0))
2746 eptr = Buf->buf + Buf->BufUsed;
2747 while ((aptr < eptr) && (*aptr != '\0')) {
2748 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2749 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2750 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2763 * \brief cuts a string after maxlen glyphs
2764 * \param str string to cut to maxlen glyphs
2765 * \param maxlen how long may the string become?
2766 * \returns pointer to maxlen or the end of the string
2768 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2774 eptr = Buf->buf + Buf->BufUsed;
2775 while ((aptr < eptr) && (*aptr != '\0')) {
2776 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2777 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2778 while ((m-- > 0) && (*aptr++ != '\0'))
2787 Buf->BufUsed = aptr - Buf->buf;
2788 return Buf->BufUsed;
2791 return Buf->BufUsed;
2797 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2799 const char *aptr, *ptr, *eptr;
2806 ptr = aptr = Buf->buf;
2810 optr = LineBuf->buf;
2811 eptr = Buf->buf + Buf->BufUsed;
2812 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2814 while ((*ptr != '\n') &&
2821 LineBuf->BufUsed = optr - LineBuf->buf;
2822 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2823 optr = LineBuf->buf + LineBuf->BufUsed;
2824 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2827 LineBuf->BufUsed = optr - LineBuf->buf;
2836 return Buf->BufUsed - (ptr - Buf->buf);