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 if (!IncreaseBuf(dest, 1, -1))
1110 if ( (current_token == parmnum) &&
1111 (*s != separator)) {
1112 dest->buf[len] = *s;
1115 else if (current_token > parmnum) {
1121 dest->buf[len] = '\0';
1122 dest->BufUsed = len;
1124 if (current_token < parmnum) {
1125 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1128 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1137 * \brief a string tokenizer to fetch an integer
1138 * \param dest Destination StringBuffer
1139 * \param parmnum n'th parameter to extract
1140 * \param separator tokenizer param
1141 * \returns 0 if not found, else integer representation of the token
1143 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1153 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1160 * \brief a string tokenizer to fetch a long integer
1161 * \param dest Destination StringBuffer
1162 * \param parmnum n'th parameter to extract
1163 * \param separator tokenizer param
1164 * \returns 0 if not found, else long integer representation of the token
1166 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1176 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1184 * \brief a string tokenizer to fetch an unsigned long
1185 * \param dest Destination StringBuffer
1186 * \param parmnum n'th parameter to extract
1187 * \param separator tokenizer param
1188 * \returns 0 if not found, else unsigned long representation of the token
1190 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1201 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1205 return (unsigned long) atol(pnum);
1214 * \brief a string tokenizer
1215 * \param dest Destination StringBuffer
1216 * \param Source StringBuffer to read into
1217 * \param pStart pointer to the end of the last token. Feed with NULL.
1218 * \param separator tokenizer param
1219 * \returns -1 if not found, else length of token.
1221 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1223 const char *s, *EndBuffer; //* source * /
1224 int len = 0; //* running total length of extracted string * /
1225 int current_token = 0; //* token currently being processed * /
1228 dest->buf[0] = '\0';
1234 if ((Source == NULL) ||
1235 (Source->BufUsed ==0)) {
1238 if (*pStart == NULL)
1239 *pStart = Source->buf;
1241 EndBuffer = Source->buf + Source->BufUsed;
1243 if ((*pStart < Source->buf) ||
1244 (*pStart > EndBuffer)) {
1252 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1254 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1255 if (*s == separator) {
1258 if (len >= dest->BufSize)
1259 if (!IncreaseBuf(dest, 1, -1)) {
1260 *pStart = EndBuffer + 1;
1263 if ( (current_token == 0) &&
1264 (*s != separator)) {
1265 dest->buf[len] = *s;
1268 else if (current_token > 0) {
1277 dest->buf[len] = '\0';
1278 dest->BufUsed = len;
1279 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1280 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1286 * \brief a string tokenizer
1287 * \param dest Destination StringBuffer
1288 * \param Source StringBuffer to read into
1289 * \param pStart pointer to the end of the last token. Feed with NULL.
1290 * \param separator tokenizer param
1291 * \returns -1 if not found, else length of token.
1293 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1295 const char *s, *EndBuffer; //* source * /
1296 int len = 0; //* running total length of extracted string * /
1297 int current_token = 0; //* token currently being processed * /
1299 if ((Source == NULL) ||
1300 (Source->BufUsed ==0)) {
1304 return Source->BufUsed;
1306 if (*pStart == NULL)
1307 *pStart = Source->buf;
1309 EndBuffer = Source->buf + Source->BufUsed;
1311 if ((*pStart < Source->buf) ||
1312 (*pStart > EndBuffer)) {
1320 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1322 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1323 if (*s == separator) {
1326 if (current_token >= nTokens) {
1338 * \brief a string tokenizer to fetch an integer
1339 * \param dest Destination StringBuffer
1340 * \param parmnum n'th parameter to extract
1341 * \param separator tokenizer param
1342 * \returns 0 if not found, else integer representation of the token
1344 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1354 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1361 * \brief a string tokenizer to fetch a long integer
1362 * \param dest Destination StringBuffer
1363 * \param parmnum n'th parameter to extract
1364 * \param separator tokenizer param
1365 * \returns 0 if not found, else long integer representation of the token
1367 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1377 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1385 * \brief a string tokenizer to fetch an unsigned long
1386 * \param dest Destination StringBuffer
1387 * \param parmnum n'th parameter to extract
1388 * \param separator tokenizer param
1389 * \returns 0 if not found, else unsigned long representation of the token
1391 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1402 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1406 return (unsigned long) atol(pnum);
1415 * \brief Read a line from socket
1416 * flushes and closes the FD on error
1417 * \param buf the buffer to get the input to
1418 * \param fd pointer to the filedescriptor to read
1419 * \param append Append to an existing string or replace?
1420 * \param Error strerror() on error
1421 * \returns numbers of chars read
1423 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1425 int len, rlen, slen;
1430 slen = len = buf->BufUsed;
1432 rlen = read(*fd, &buf->buf[len], 1);
1434 *Error = strerror(errno);
1441 if (buf->buf[len] == '\n')
1443 if (buf->buf[len] != '\r')
1445 if (len >= buf->BufSize) {
1447 buf->buf[len+1] = '\0';
1448 IncreaseBuf(buf, 1, -1);
1452 buf->buf[len] = '\0';
1457 * \brief Read a line from socket
1458 * flushes and closes the FD on error
1459 * \param buf the buffer to get the input to
1460 * \param fd pointer to the filedescriptor to read
1461 * \param append Append to an existing string or replace?
1462 * \param Error strerror() on error
1463 * \returns numbers of chars read
1465 int StrBufTCP_read_buffered_line(StrBuf *Line,
1469 int selectresolution,
1473 int nSuccessLess = 0;
1479 if (buf->BufUsed > 0) {
1480 pch = strchr(buf->buf, '\n');
1483 len = pch - buf->buf;
1484 if (len > 0 && (*(pch - 1) == '\r') )
1486 StrBufSub(Line, buf, 0, len - rlen);
1487 StrBufCutLeft(buf, len + 1);
1492 if (buf->BufSize - buf->BufUsed < 10)
1493 IncreaseBuf(buf, 1, -1);
1495 fdflags = fcntl(*fd, F_GETFL);
1496 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1499 while ((nSuccessLess < timeout) && (pch == NULL)) {
1500 tv.tv_sec = selectresolution;
1505 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1506 *Error = strerror(errno);
1511 if (FD_ISSET(*fd, &rfds)) {
1513 &buf->buf[buf->BufUsed],
1514 buf->BufSize - buf->BufUsed - 1);
1516 *Error = strerror(errno);
1521 else if (rlen > 0) {
1523 buf->BufUsed += rlen;
1524 buf->buf[buf->BufUsed] = '\0';
1525 if (buf->BufUsed + 10 > buf->BufSize) {
1526 IncreaseBuf(buf, 1, -1);
1528 pch = strchr(buf->buf, '\n');
1536 len = pch - buf->buf;
1537 if (len > 0 && (*(pch - 1) == '\r') )
1539 StrBufSub(Line, buf, 0, len - rlen);
1540 StrBufCutLeft(buf, len + 1);
1548 * \brief Read a line from socket
1549 * flushes and closes the FD on error
1550 * \param buf the buffer to get the input to
1551 * \param Pos pointer to the current read position, should be NULL initialized!
1552 * \param fd pointer to the filedescriptor to read
1553 * \param append Append to an existing string or replace?
1554 * \param Error strerror() on error
1555 * \returns numbers of chars read
1557 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1562 int selectresolution,
1565 const char *pche = NULL;
1566 const char *pos = NULL;
1568 int nSuccessLess = 0;
1570 const char *pch = NULL;
1575 if ((IOBuf->BufUsed > 0) &&
1577 (pos < IOBuf->buf + IOBuf->BufUsed))
1579 pche = IOBuf->buf + IOBuf->BufUsed;
1581 while ((pch < pche) && (*pch != '\n'))
1583 if ((pch >= pche) || (*pch == '\0'))
1585 if ((pch != NULL) &&
1590 if (len > 0 && (*(pch - 1) == '\r') )
1592 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1602 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1606 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1607 IncreaseBuf(IOBuf, 1, -1);
1610 fdflags = fcntl(*fd, F_GETFL);
1611 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1615 while ((nSuccessLess < timeout) && (pch == NULL)) {
1616 tv.tv_sec = selectresolution;
1621 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1622 *Error = strerror(errno);
1627 if (FD_ISSET(*fd, &rfds) != 0) {
1629 &IOBuf->buf[IOBuf->BufUsed],
1630 IOBuf->BufSize - IOBuf->BufUsed - 1);
1632 *Error = strerror(errno);
1637 else if (rlen > 0) {
1639 IOBuf->BufUsed += rlen;
1640 IOBuf->buf[IOBuf->BufUsed] = '\0';
1641 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1642 IncreaseBuf(IOBuf, 1, -1);
1645 pche = IOBuf->buf + IOBuf->BufUsed;
1647 while ((pch < pche) && (*pch != '\n'))
1649 if ((pch >= pche) || (*pch == '\0'))
1660 if (len > 0 && (*(pch - 1) == '\r') )
1662 StrBufSub(Line, IOBuf, 0, len - rlen);
1663 *Pos = pos + len + 1;
1671 * \brief Input binary data from socket
1672 * flushes and closes the FD on error
1673 * \param buf the buffer to get the input to
1674 * \param fd pointer to the filedescriptor to read
1675 * \param append Append to an existing string or replace?
1676 * \param nBytes the maximal number of bytes to read
1677 * \param Error strerror() on error
1678 * \returns numbers of chars read
1680 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1684 int len, rlen, slen;
1688 if ((Buf == NULL) || (*fd == -1))
1692 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1693 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1695 ptr = Buf->buf + Buf->BufUsed;
1697 slen = len = Buf->BufUsed;
1699 fdflags = fcntl(*fd, F_GETFL);
1701 while (nRead < nBytes) {
1702 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1705 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1706 *Error = strerror(errno);
1711 if ((rlen = read(*fd,
1713 nBytes - nRead)) == -1) {
1716 *Error = strerror(errno);
1721 Buf->BufUsed += rlen;
1723 Buf->buf[Buf->BufUsed] = '\0';
1728 * \brief Input binary data from socket
1729 * flushes and closes the FD on error
1730 * \param buf the buffer to get the input to
1731 * \param fd pointer to the filedescriptor to read
1732 * \param append Append to an existing string or replace?
1733 * \param nBytes the maximal number of bytes to read
1734 * \param Error strerror() on error
1735 * \returns numbers of chars read
1737 int StrBufReadBLOBBuffered(StrBuf *Blob,
1758 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1762 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1763 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1768 len = pos - IOBuf->buf;
1769 rlen = IOBuf->BufUsed - len;
1772 if ((IOBuf->BufUsed > 0) &&
1774 (pos < IOBuf->buf + IOBuf->BufUsed))
1776 pche = IOBuf->buf + IOBuf->BufUsed;
1779 if (rlen < nBytes) {
1780 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1781 Blob->BufUsed += rlen;
1782 Blob->buf[Blob->BufUsed] = '\0';
1786 if (rlen >= nBytes) {
1787 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1788 Blob->BufUsed += nBytes;
1789 Blob->buf[Blob->BufUsed] = '\0';
1790 if (rlen == nBytes) {
1801 if (IOBuf->BufSize < nBytes - nRead)
1802 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1805 slen = len = Blob->BufUsed;
1807 fdflags = fcntl(*fd, F_GETFL);
1812 while (nRead < nBytes) {
1813 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1816 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1819 *Error = strerror(errno);
1830 *Error = strerror(errno);
1836 if ((check == NNN_TERM) &&
1838 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1840 StrBufPlain(Blob, HKEY("\n000\n"));
1841 StrBufCutRight(Blob, 5);
1842 return Blob->BufUsed;
1844 if (nSelects > 10) {
1852 IOBuf->BufUsed += rlen;
1855 if (nRead > nBytes) {
1856 *Pos = IOBuf->buf + nBytes;
1858 Blob->buf[Blob->BufUsed] = '\0';
1859 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1864 * \brief Cut nChars from the start of the string
1865 * \param Buf Buffer to modify
1866 * \param nChars how many chars should be skipped?
1868 void StrBufCutLeft(StrBuf *Buf, int nChars)
1870 if (nChars >= Buf->BufUsed) {
1874 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1875 Buf->BufUsed -= nChars;
1876 Buf->buf[Buf->BufUsed] = '\0';
1880 * \brief Cut the trailing n Chars from the string
1881 * \param Buf Buffer to modify
1882 * \param nChars how many chars should be trunkated?
1884 void StrBufCutRight(StrBuf *Buf, int nChars)
1886 if (nChars >= Buf->BufUsed) {
1890 Buf->BufUsed -= nChars;
1891 Buf->buf[Buf->BufUsed] = '\0';
1895 * \brief Cut the string after n Chars
1896 * \param Buf Buffer to modify
1897 * \param AfternChars after how many chars should we trunkate the string?
1898 * \param At if non-null and points inside of our string, cut it there.
1900 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1903 AfternChars = At - Buf->buf;
1906 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1908 Buf->BufUsed = AfternChars;
1909 Buf->buf[Buf->BufUsed] = '\0';
1914 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1915 * buf - the string to modify
1916 * len - length of the string.
1918 void StrBufTrim(StrBuf *Buf)
1921 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1923 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1926 if (delta > 0) StrBufCutLeft(Buf, delta);
1928 if (Buf->BufUsed == 0) return;
1929 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1932 Buf->buf[Buf->BufUsed] = '\0';
1936 void StrBufUpCase(StrBuf *Buf)
1941 pche = pch + Buf->BufUsed;
1942 while (pch < pche) {
1943 *pch = toupper(*pch);
1949 void StrBufLowerCase(StrBuf *Buf)
1954 pche = pch + Buf->BufUsed;
1955 while (pch < pche) {
1956 *pch = tolower(*pch);
1963 * \brief unhide special chars hidden to the HTML escaper
1964 * \param target buffer to put the unescaped string in
1965 * \param source buffer to unescape
1967 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1973 FlushStrBuf(target);
1975 if (source == NULL ||target == NULL)
1980 len = source->BufUsed;
1981 for (a = 0; a < len; ++a) {
1982 if (target->BufUsed >= target->BufSize)
1983 IncreaseBuf(target, 1, -1);
1985 if (source->buf[a] == '=') {
1986 hex[0] = source->buf[a + 1];
1987 hex[1] = source->buf[a + 2];
1990 sscanf(hex, "%02x", &b);
1991 target->buf[target->BufUsed] = b;
1992 target->buf[++target->BufUsed] = 0;
1996 target->buf[target->BufUsed] = source->buf[a];
1997 target->buf[++target->BufUsed] = 0;
2004 * \brief hide special chars from the HTML escapers and friends
2005 * \param target buffer to put the escaped string in
2006 * \param source buffer to escape
2008 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2013 FlushStrBuf(target);
2015 if (source == NULL ||target == NULL)
2020 len = source->BufUsed;
2021 for (i=0; i<len; ++i) {
2022 if (target->BufUsed + 4 >= target->BufSize)
2023 IncreaseBuf(target, 1, -1);
2024 if ( (isalnum(source->buf[i])) ||
2025 (source->buf[i]=='-') ||
2026 (source->buf[i]=='_') ) {
2027 target->buf[target->BufUsed++] = source->buf[i];
2030 sprintf(&target->buf[target->BufUsed],
2032 (0xFF &source->buf[i]));
2033 target->BufUsed += 3;
2036 target->buf[target->BufUsed + 1] = '\0';
2040 * \brief uses the same calling syntax as compress2(), but it
2041 * creates a stream compatible with HTTP "Content-encoding: gzip"
2044 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2045 #define OS_CODE 0x03 /*< unix */
2046 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2047 size_t * destLen, /*< length of the compresed data */
2048 const Bytef * source, /*< source to encode */
2049 uLong sourceLen, /*< length of source to encode */
2050 int level) /*< compression level */
2052 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2054 /* write gzip header */
2055 snprintf((char *) dest, *destLen,
2056 "%c%c%c%c%c%c%c%c%c%c",
2057 gz_magic[0], gz_magic[1], Z_DEFLATED,
2058 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2061 /* normal deflate */
2064 stream.next_in = (Bytef *) source;
2065 stream.avail_in = (uInt) sourceLen;
2066 stream.next_out = dest + 10L; // after header
2067 stream.avail_out = (uInt) * destLen;
2068 if ((uLong) stream.avail_out != *destLen)
2071 stream.zalloc = (alloc_func) 0;
2072 stream.zfree = (free_func) 0;
2073 stream.opaque = (voidpf) 0;
2075 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2076 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2080 err = deflate(&stream, Z_FINISH);
2081 if (err != Z_STREAM_END) {
2082 deflateEnd(&stream);
2083 return err == Z_OK ? Z_BUF_ERROR : err;
2085 *destLen = stream.total_out + 10L;
2087 /* write CRC and Length */
2088 uLong crc = crc32(0L, source, sourceLen);
2090 for (n = 0; n < 4; ++n, ++*destLen) {
2091 dest[*destLen] = (int) (crc & 0xff);
2094 uLong len = stream.total_in;
2095 for (n = 0; n < 4; ++n, ++*destLen) {
2096 dest[*destLen] = (int) (len & 0xff);
2099 err = deflateEnd(&stream);
2106 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2108 int CompressBuffer(StrBuf *Buf)
2111 char *compressed_data = NULL;
2112 size_t compressed_len, bufsize;
2115 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2116 compressed_data = malloc(compressed_len);
2118 /* Flush some space after the used payload so valgrind shuts up... */
2119 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2120 Buf->buf[Buf->BufUsed + i++] = '\0';
2121 if (compress_gzip((Bytef *) compressed_data,
2124 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2127 Buf->buf = compressed_data;
2128 Buf->BufUsed = compressed_len;
2129 Buf->BufSize = bufsize;
2130 /* Flush some space after the used payload so valgrind shuts up... */
2132 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2133 Buf->buf[Buf->BufUsed + i++] = '\0';
2136 free(compressed_data);
2138 #endif /* HAVE_ZLIB */
2143 * \brief decode a buffer from base 64 encoding; destroys original
2144 * \param Buf Buffor to transform
2146 int StrBufDecodeBase64(StrBuf *Buf)
2150 if (Buf == NULL) return -1;
2152 xferbuf = (char*) malloc(Buf->BufSize);
2153 siz = CtdlDecodeBase64(xferbuf,
2163 * \brief decode a buffer from base 64 encoding; destroys original
2164 * \param Buf Buffor to transform
2166 int StrBufDecodeHex(StrBuf *Buf)
2169 char *pch, *pche, *pchi;
2171 if (Buf == NULL) return -1;
2173 pch = pchi = Buf->buf;
2174 pche = pch + Buf->BufUsed;
2176 while (pchi < pche){
2177 ch = decode_hex(pchi);
2184 Buf->BufUsed = pch - Buf->buf;
2185 return Buf->BufUsed;
2189 * \brief replace all chars >0x20 && < 0x7F with Mute
2190 * \param Mute char to put over invalid chars
2191 * \param Buf Buffor to transform
2193 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2197 if (Buf == NULL) return -1;
2198 pch = (unsigned char *)Buf->buf;
2199 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2200 if ((*pch < 0x20) || (*pch > 0x7F))
2204 return Buf->BufUsed;
2209 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2210 * \param Buf Buffer to translate
2211 * \param StripBlanks Reduce several blanks to one?
2213 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2219 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2220 Buf->buf[Buf->BufUsed - 1] = '\0';
2225 while (a < Buf->BufUsed) {
2226 if (Buf->buf[a] == '+')
2228 else if (Buf->buf[a] == '%') {
2229 /* don't let % chars through, rather truncate the input. */
2230 if (a + 2 > Buf->BufUsed) {
2235 hex[0] = Buf->buf[a + 1];
2236 hex[1] = Buf->buf[a + 2];
2239 sscanf(hex, "%02x", &b);
2240 Buf->buf[a] = (char) b;
2241 len = Buf->BufUsed - a - 2;
2243 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2255 * \brief RFC2047-encode a header field if necessary.
2256 * If no non-ASCII characters are found, the string
2257 * will be copied verbatim without encoding.
2259 * \param target Target buffer.
2260 * \param source Source string to be encoded.
2261 * \returns encoded length; -1 if non success.
2263 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2265 const char headerStr[] = "=?UTF-8?Q?";
2266 int need_to_encode = 0;
2270 if ((source == NULL) ||
2274 while ((i < source->BufUsed) &&
2275 (!IsEmptyStr (&source->buf[i])) &&
2276 (need_to_encode == 0)) {
2277 if (((unsigned char) source->buf[i] < 32) ||
2278 ((unsigned char) source->buf[i] > 126)) {
2284 if (!need_to_encode) {
2285 if (*target == NULL) {
2286 *target = NewStrBufPlain(source->buf, source->BufUsed);
2289 FlushStrBuf(*target);
2290 StrBufAppendBuf(*target, source, 0);
2292 return (*target)->BufUsed;
2294 if (*target == NULL)
2295 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2296 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2297 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2298 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2299 (*target)->BufUsed = sizeof(headerStr) - 1;
2300 for (i=0; (i < source->BufUsed); ++i) {
2301 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2302 IncreaseBuf(*target, 1, 0);
2303 ch = (unsigned char) source->buf[i];
2304 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2305 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2306 (*target)->BufUsed += 3;
2309 (*target)->buf[(*target)->BufUsed] = ch;
2310 (*target)->BufUsed++;
2314 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2315 IncreaseBuf(*target, 1, 0);
2317 (*target)->buf[(*target)->BufUsed++] = '?';
2318 (*target)->buf[(*target)->BufUsed++] = '=';
2319 (*target)->buf[(*target)->BufUsed] = '\0';
2320 return (*target)->BufUsed;;
2324 * \brief replaces all occurances of 'search' by 'replace'
2325 * \param buf Buffer to modify
2326 * \param search character to search
2327 * \param relpace character to replace search by
2329 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2334 for (i=0; i<buf->BufUsed; i++)
2335 if (buf->buf[i] == search)
2336 buf->buf[i] = replace;
2343 * Wrapper around iconv_open()
2344 * Our version adds aliases for non-standard Microsoft charsets
2345 * such as 'MS950', aliasing them to names like 'CP950'
2347 * tocode Target encoding
2348 * fromcode Source encoding
2350 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2353 iconv_t ic = (iconv_t)(-1) ;
2354 ic = iconv_open(tocode, fromcode);
2355 if (ic == (iconv_t)(-1) ) {
2356 char alias_fromcode[64];
2357 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2358 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2359 alias_fromcode[0] = 'C';
2360 alias_fromcode[1] = 'P';
2361 ic = iconv_open(tocode, alias_fromcode);
2364 *(iconv_t *)pic = ic;
2370 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2373 /* Find the next ?Q? */
2374 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2377 end = strchr(bptr + 2, '?');
2382 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2383 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2384 (*(end + 2) == '?')) {
2385 /* skip on to the end of the cluster, the next ?= */
2386 end = strstr(end + 3, "?=");
2389 /* sort of half valid encoding, try to find an end. */
2390 end = strstr(bptr, "?=");
2395 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2400 char *ibuf; /**< Buffer of characters to be converted */
2401 char *obuf; /**< Buffer for converted characters */
2402 size_t ibuflen; /**< Length of input buffer */
2403 size_t obuflen; /**< Length of output buffer */
2406 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2407 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2409 ic = *(iconv_t*)pic;
2410 ibuf = ConvertBuf->buf;
2411 ibuflen = ConvertBuf->BufUsed;
2413 obuflen = TmpBuf->BufSize;
2415 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2417 /* little card game: wheres the red lady? */
2418 ibuf = ConvertBuf->buf;
2419 BufSize = ConvertBuf->BufSize;
2421 ConvertBuf->buf = TmpBuf->buf;
2422 ConvertBuf->BufSize = TmpBuf->BufSize;
2423 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2424 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2427 TmpBuf->BufSize = BufSize;
2428 TmpBuf->BufUsed = 0;
2429 TmpBuf->buf[0] = '\0';
2436 inline static void DecodeSegment(StrBuf *Target,
2437 const StrBuf *DecodeMe,
2441 StrBuf *ConvertBuf2,
2442 StrBuf *FoundCharset)
2448 iconv_t ic = (iconv_t)(-1);
2450 /* Now we handle foreign character sets properly encoded
2451 * in RFC2047 format.
2453 StaticBuf.buf = SegmentStart;
2454 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2455 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2456 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2457 if (FoundCharset != NULL) {
2458 FlushStrBuf(FoundCharset);
2459 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2461 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2462 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2464 *encoding = toupper(*encoding);
2465 if (*encoding == 'B') { /**< base64 */
2466 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2468 ConvertBuf->BufUsed);
2470 else if (*encoding == 'Q') { /**< quoted-printable */
2474 while (pos < ConvertBuf->BufUsed)
2476 if (ConvertBuf->buf[pos] == '_')
2477 ConvertBuf->buf[pos] = ' ';
2481 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2484 ConvertBuf->BufUsed);
2487 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2490 ctdl_iconv_open("UTF-8", charset, &ic);
2491 if (ic != (iconv_t)(-1) ) {
2493 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2494 StrBufAppendBuf(Target, ConvertBuf2, 0);
2499 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2504 * Handle subjects with RFC2047 encoding such as:
2505 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2507 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2509 StrBuf *ConvertBuf, *ConvertBuf2;
2510 char *start, *end, *next, *nextend, *ptr = NULL;
2512 iconv_t ic = (iconv_t)(-1) ;
2517 int illegal_non_rfc2047_encoding = 0;
2519 /* Sometimes, badly formed messages contain strings which were simply
2520 * written out directly in some foreign character set instead of
2521 * using RFC2047 encoding. This is illegal but we will attempt to
2522 * handle it anyway by converting from a user-specified default
2523 * charset to UTF-8 if we see any nonprintable characters.
2526 len = StrLength(DecodeMe);
2527 for (i=0; i<DecodeMe->BufUsed; ++i) {
2528 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2529 illegal_non_rfc2047_encoding = 1;
2534 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2535 if ((illegal_non_rfc2047_encoding) &&
2536 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2537 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2540 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2541 if (ic != (iconv_t)(-1) ) {
2542 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2548 /* pre evaluate the first pair */
2549 nextend = end = NULL;
2550 len = StrLength(DecodeMe);
2551 start = strstr(DecodeMe->buf, "=?");
2552 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2554 end = FindNextEnd (DecodeMe, start);
2556 StrBufAppendBuf(Target, DecodeMe, 0);
2557 FreeStrBuf(&ConvertBuf);
2561 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2563 if (start != DecodeMe->buf)
2564 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2566 * Since spammers will go to all sorts of absurd lengths to get their
2567 * messages through, there are LOTS of corrupt headers out there.
2568 * So, prevent a really badly formed RFC2047 header from throwing
2569 * this function into an infinite loop.
2571 while ((start != NULL) &&
2578 DecodeSegment(Target,
2586 next = strstr(end, "=?");
2588 if ((next != NULL) &&
2590 nextend = FindNextEnd(DecodeMe, next);
2591 if (nextend == NULL)
2594 /* did we find two partitions */
2595 if ((next != NULL) &&
2599 while ((ptr < next) &&
2605 /* did we find a gab just filled with blanks? */
2610 len - (next - start));
2612 /* now terminate the gab at the end */
2613 delta = (next - end) - 2; ////TODO: const!
2614 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2615 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2617 /* move next to its new location. */
2622 /* our next-pair is our new first pair now. */
2628 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2629 if ((end != NULL) && (end < nextend)) {
2631 while ( (ptr < nextend) &&
2638 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2640 FreeStrBuf(&ConvertBuf);
2641 FreeStrBuf(&ConvertBuf2);
2645 * \brief evaluate the length of an utf8 special character sequence
2646 * \param Char the character to examine
2647 * \returns width of utf8 chars in bytes
2649 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2654 while ((n < 8) && ((test & *CharS) != 0)) {
2658 if ((n > 6) || ((CharE - CharS) > n))
2664 * \brief detect whether this char starts an utf-8 encoded char
2665 * \param Char character to inspect
2666 * \returns yes or no
2668 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2670 /** 11??.???? indicates an UTF8 Sequence. */
2671 return ((Char & 0xC0) != 0);
2675 * \brief measure the number of glyphs in an UTF8 string...
2676 * \param str string to measure
2677 * \returns the length of str
2679 long StrBuf_Utf8StrLen(StrBuf *Buf)
2685 if ((Buf == NULL) || (Buf->BufUsed == 0))
2688 eptr = Buf->buf + Buf->BufUsed;
2689 while ((aptr < eptr) && (*aptr != '\0')) {
2690 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2691 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2692 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2705 * \brief cuts a string after maxlen glyphs
2706 * \param str string to cut to maxlen glyphs
2707 * \param maxlen how long may the string become?
2708 * \returns pointer to maxlen or the end of the string
2710 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2716 eptr = Buf->buf + Buf->BufUsed;
2717 while ((aptr < eptr) && (*aptr != '\0')) {
2718 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2719 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2720 while ((m-- > 0) && (*aptr++ != '\0'))
2729 Buf->BufUsed = aptr - Buf->buf;
2730 return Buf->BufUsed;
2733 return Buf->BufUsed;
2739 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2741 const char *aptr, *ptr, *eptr;
2748 ptr = aptr = Buf->buf;
2752 optr = LineBuf->buf;
2753 eptr = Buf->buf + Buf->BufUsed;
2754 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2756 while ((*ptr != '\n') &&
2763 LineBuf->BufUsed = optr - LineBuf->buf;
2764 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2765 optr = LineBuf->buf + LineBuf->BufUsed;
2766 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2769 LineBuf->BufUsed = optr - LineBuf->buf;
2778 return Buf->BufUsed - (ptr - Buf->buf);