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 == '"') {
846 memcpy(bptr, "\\\"", 2);
848 Target->BufUsed += 2;
849 } else if (*aptr == '\\') {
850 memcpy(bptr, "\\\\", 2);
852 Target->BufUsed += 2;
862 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
864 return Target->BufUsed;
868 * \brief extracts a substring from Source into dest
869 * \param dest buffer to place substring into
870 * \param Source string to copy substring from
871 * \param Offset chars to skip from start
872 * \param nChars number of chars to copy
873 * \returns the number of chars copied; may be different from nChars due to the size of Source
875 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
878 if (Offset > Source->BufUsed)
883 if (Offset + nChars < Source->BufUsed)
885 if (nChars >= dest->BufSize)
886 IncreaseBuf(dest, 0, nChars + 1);
887 memcpy(dest->buf, Source->buf + Offset, nChars);
888 dest->BufUsed = nChars;
889 dest->buf[dest->BufUsed] = '\0';
892 NCharsRemain = Source->BufUsed - Offset;
893 if (NCharsRemain >= dest->BufSize)
894 IncreaseBuf(dest, 0, NCharsRemain + 1);
895 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
896 dest->BufUsed = NCharsRemain;
897 dest->buf[dest->BufUsed] = '\0';
902 * \brief sprintf like function appending the formated string to the buffer
903 * vsnprintf version to wrap into own calls
904 * \param Buf Buffer to extend by format and params
905 * \param format printf alike format to add
906 * \param ap va_list containing the items for format
908 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
911 size_t BufSize = Buf->BufSize;
912 size_t nWritten = Buf->BufSize + 1;
913 size_t Offset = Buf->BufUsed;
914 size_t newused = Offset + nWritten;
916 while (newused >= BufSize) {
918 nWritten = vsnprintf(Buf->buf + Offset,
919 Buf->BufSize - Offset,
922 newused = Offset + nWritten;
923 if (newused >= Buf->BufSize) {
924 IncreaseBuf(Buf, 1, newused);
925 newused = Buf->BufSize + 1;
928 Buf->BufUsed = Offset + nWritten;
929 BufSize = Buf->BufSize;
936 * \brief sprintf like function appending the formated string to the buffer
937 * \param Buf Buffer to extend by format and params
938 * \param format printf alike format to add
939 * \param ap va_list containing the items for format
941 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
943 size_t BufSize = Buf->BufSize;
944 size_t nWritten = Buf->BufSize + 1;
945 size_t Offset = Buf->BufUsed;
946 size_t newused = Offset + nWritten;
949 while (newused >= BufSize) {
950 va_start(arg_ptr, format);
951 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
952 Buf->BufSize - Buf->BufUsed,
955 newused = Buf->BufUsed + nWritten;
956 if (newused >= Buf->BufSize) {
957 IncreaseBuf(Buf, 1, newused);
958 newused = Buf->BufSize + 1;
961 Buf->BufUsed += nWritten;
962 BufSize = Buf->BufSize;
969 * \brief sprintf like function putting the formated string into the buffer
970 * \param Buf Buffer to extend by format and params
971 * \param format printf alike format to add
972 * \param ap va_list containing the items for format
974 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
976 size_t nWritten = Buf->BufSize + 1;
979 while (nWritten >= Buf->BufSize) {
980 va_start(arg_ptr, format);
981 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
983 if (nWritten >= Buf->BufSize) {
984 IncreaseBuf(Buf, 0, 0);
985 nWritten = Buf->BufSize + 1;
988 Buf->BufUsed = nWritten ;
994 * \brief Counts the numbmer of tokens in a buffer
995 * \param Source String to count tokens in
996 * \param tok Tokenizer char to count
997 * \returns numbers of tokenizer chars found
999 int StrBufNum_tokens(const StrBuf *source, char tok)
1003 return num_tokens(source->buf, tok);
1007 * remove_token() - a tokenizer that kills, maims, and destroys
1010 * \brief a string tokenizer
1011 * \param Source StringBuffer to read into
1012 * \param parmnum n'th parameter to remove
1013 * \param separator tokenizer param
1014 * \returns -1 if not found, else length of token.
1016 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1019 char *d, *s; /* dest, source */
1022 /* Find desired parameter */
1024 while (count < parmnum) {
1025 /* End of string, bail! */
1030 if (*d == separator) {
1035 if (!d) return 0; /* Parameter not found */
1037 /* Find next parameter */
1039 while (*s && *s != separator) {
1042 if (*s == separator)
1046 /* Hack and slash */
1048 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1049 Source->BufUsed -= (ReducedBy + 1);
1051 else if (d == Source->buf) {
1053 Source->BufUsed = 0;
1057 Source->BufUsed -= (ReducedBy + 1);
1070 * \brief a string tokenizer
1071 * \param dest Destination StringBuffer
1072 * \param Source StringBuffer to read into
1073 * \param parmnum n'th parameter to extract
1074 * \param separator tokenizer param
1075 * \returns -1 if not found, else length of token.
1077 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1079 const char *s, *e; //* source * /
1080 int len = 0; //* running total length of extracted string * /
1081 int current_token = 0; //* token currently being processed * /
1084 dest->buf[0] = '\0';
1090 if ((Source == NULL) || (Source->BufUsed ==0)) {
1094 e = s + Source->BufUsed;
1097 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1099 while ((s<e) && !IsEmptyStr(s)) {
1100 if (*s == separator) {
1103 if (len >= dest->BufSize)
1104 if (!IncreaseBuf(dest, 1, -1))
1106 if ( (current_token == parmnum) &&
1107 (*s != separator)) {
1108 dest->buf[len] = *s;
1111 else if (current_token > parmnum) {
1117 dest->buf[len] = '\0';
1118 dest->BufUsed = len;
1120 if (current_token < parmnum) {
1121 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1124 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1133 * \brief a string tokenizer to fetch an integer
1134 * \param dest Destination StringBuffer
1135 * \param parmnum n'th parameter to extract
1136 * \param separator tokenizer param
1137 * \returns 0 if not found, else integer representation of the token
1139 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1149 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1156 * \brief a string tokenizer to fetch a long integer
1157 * \param dest Destination StringBuffer
1158 * \param parmnum n'th parameter to extract
1159 * \param separator tokenizer param
1160 * \returns 0 if not found, else long integer representation of the token
1162 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1172 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1180 * \brief a string tokenizer to fetch an unsigned long
1181 * \param dest Destination StringBuffer
1182 * \param parmnum n'th parameter to extract
1183 * \param separator tokenizer param
1184 * \returns 0 if not found, else unsigned long representation of the token
1186 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1197 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1201 return (unsigned long) atol(pnum);
1210 * \brief a string tokenizer
1211 * \param dest Destination StringBuffer
1212 * \param Source StringBuffer to read into
1213 * \param pStart pointer to the end of the last token. Feed with NULL.
1214 * \param separator tokenizer param
1215 * \returns -1 if not found, else length of token.
1217 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1219 const char *s, *EndBuffer; //* source * /
1220 int len = 0; //* running total length of extracted string * /
1221 int current_token = 0; //* token currently being processed * /
1224 dest->buf[0] = '\0';
1230 if ((Source == NULL) ||
1231 (Source->BufUsed ==0)) {
1234 if (*pStart == NULL)
1235 *pStart = Source->buf;
1237 EndBuffer = Source->buf + Source->BufUsed;
1239 if ((*pStart < Source->buf) ||
1240 (*pStart > EndBuffer)) {
1248 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1250 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1251 if (*s == separator) {
1254 if (len >= dest->BufSize)
1255 if (!IncreaseBuf(dest, 1, -1)) {
1256 *pStart = EndBuffer + 1;
1259 if ( (current_token == 0) &&
1260 (*s != separator)) {
1261 dest->buf[len] = *s;
1264 else if (current_token > 0) {
1273 dest->buf[len] = '\0';
1274 dest->BufUsed = len;
1275 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1276 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1282 * \brief a string tokenizer
1283 * \param dest Destination StringBuffer
1284 * \param Source StringBuffer to read into
1285 * \param pStart pointer to the end of the last token. Feed with NULL.
1286 * \param separator tokenizer param
1287 * \returns -1 if not found, else length of token.
1289 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1291 const char *s, *EndBuffer; //* source * /
1292 int len = 0; //* running total length of extracted string * /
1293 int current_token = 0; //* token currently being processed * /
1295 if ((Source == NULL) ||
1296 (Source->BufUsed ==0)) {
1300 return Source->BufUsed;
1302 if (*pStart == NULL)
1303 *pStart = Source->buf;
1305 EndBuffer = Source->buf + Source->BufUsed;
1307 if ((*pStart < Source->buf) ||
1308 (*pStart > EndBuffer)) {
1316 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1318 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1319 if (*s == separator) {
1322 if (current_token >= nTokens) {
1334 * \brief a string tokenizer to fetch an integer
1335 * \param dest Destination StringBuffer
1336 * \param parmnum n'th parameter to extract
1337 * \param separator tokenizer param
1338 * \returns 0 if not found, else integer representation of the token
1340 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1350 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1357 * \brief a string tokenizer to fetch a long integer
1358 * \param dest Destination StringBuffer
1359 * \param parmnum n'th parameter to extract
1360 * \param separator tokenizer param
1361 * \returns 0 if not found, else long integer representation of the token
1363 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1373 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1381 * \brief a string tokenizer to fetch an unsigned long
1382 * \param dest Destination StringBuffer
1383 * \param parmnum n'th parameter to extract
1384 * \param separator tokenizer param
1385 * \returns 0 if not found, else unsigned long representation of the token
1387 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1398 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1402 return (unsigned long) atol(pnum);
1411 * \brief Read a line from socket
1412 * flushes and closes the FD on error
1413 * \param buf the buffer to get the input to
1414 * \param fd pointer to the filedescriptor to read
1415 * \param append Append to an existing string or replace?
1416 * \param Error strerror() on error
1417 * \returns numbers of chars read
1419 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1421 int len, rlen, slen;
1426 slen = len = buf->BufUsed;
1428 rlen = read(*fd, &buf->buf[len], 1);
1430 *Error = strerror(errno);
1437 if (buf->buf[len] == '\n')
1439 if (buf->buf[len] != '\r')
1441 if (len >= buf->BufSize) {
1443 buf->buf[len+1] = '\0';
1444 IncreaseBuf(buf, 1, -1);
1448 buf->buf[len] = '\0';
1453 * \brief Read a line from socket
1454 * flushes and closes the FD on error
1455 * \param buf the buffer to get the input to
1456 * \param fd pointer to the filedescriptor to read
1457 * \param append Append to an existing string or replace?
1458 * \param Error strerror() on error
1459 * \returns numbers of chars read
1461 int StrBufTCP_read_buffered_line(StrBuf *Line,
1465 int selectresolution,
1469 int nSuccessLess = 0;
1475 if (buf->BufUsed > 0) {
1476 pch = strchr(buf->buf, '\n');
1479 len = pch - buf->buf;
1480 if (len > 0 && (*(pch - 1) == '\r') )
1482 StrBufSub(Line, buf, 0, len - rlen);
1483 StrBufCutLeft(buf, len + 1);
1488 if (buf->BufSize - buf->BufUsed < 10)
1489 IncreaseBuf(buf, 1, -1);
1491 fdflags = fcntl(*fd, F_GETFL);
1492 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1495 while ((nSuccessLess < timeout) && (pch == NULL)) {
1496 tv.tv_sec = selectresolution;
1501 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1502 *Error = strerror(errno);
1507 if (FD_ISSET(*fd, &rfds)) {
1509 &buf->buf[buf->BufUsed],
1510 buf->BufSize - buf->BufUsed - 1);
1512 *Error = strerror(errno);
1517 else if (rlen > 0) {
1519 buf->BufUsed += rlen;
1520 buf->buf[buf->BufUsed] = '\0';
1521 if (buf->BufUsed + 10 > buf->BufSize) {
1522 IncreaseBuf(buf, 1, -1);
1524 pch = strchr(buf->buf, '\n');
1532 len = pch - buf->buf;
1533 if (len > 0 && (*(pch - 1) == '\r') )
1535 StrBufSub(Line, buf, 0, len - rlen);
1536 StrBufCutLeft(buf, len + 1);
1544 * \brief Read a line from socket
1545 * flushes and closes the FD on error
1546 * \param buf the buffer to get the input to
1547 * \param Pos pointer to the current read position, should be NULL initialized!
1548 * \param fd pointer to the filedescriptor to read
1549 * \param append Append to an existing string or replace?
1550 * \param Error strerror() on error
1551 * \returns numbers of chars read
1553 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1558 int selectresolution,
1561 const char *pche = NULL;
1562 const char *pos = NULL;
1564 int nSuccessLess = 0;
1566 const char *pch = NULL;
1571 if ((IOBuf->BufUsed > 0) &&
1573 (pos < IOBuf->buf + IOBuf->BufUsed))
1575 pche = IOBuf->buf + IOBuf->BufUsed;
1577 while ((pch < pche) && (*pch != '\n'))
1579 if ((pch >= pche) || (*pch == '\0'))
1581 if ((pch != NULL) &&
1586 if (len > 0 && (*(pch - 1) == '\r') )
1588 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1598 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1602 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1603 IncreaseBuf(IOBuf, 1, -1);
1606 fdflags = fcntl(*fd, F_GETFL);
1607 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1611 while ((nSuccessLess < timeout) && (pch == NULL)) {
1612 tv.tv_sec = selectresolution;
1617 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1618 *Error = strerror(errno);
1623 if (FD_ISSET(*fd, &rfds) != 0) {
1625 &IOBuf->buf[IOBuf->BufUsed],
1626 IOBuf->BufSize - IOBuf->BufUsed - 1);
1628 *Error = strerror(errno);
1633 else if (rlen > 0) {
1635 IOBuf->BufUsed += rlen;
1636 IOBuf->buf[IOBuf->BufUsed] = '\0';
1637 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1638 IncreaseBuf(IOBuf, 1, -1);
1641 pche = IOBuf->buf + IOBuf->BufUsed;
1643 while ((pch < pche) && (*pch != '\n'))
1645 if ((pch >= pche) || (*pch == '\0'))
1656 if (len > 0 && (*(pch - 1) == '\r') )
1658 StrBufSub(Line, IOBuf, 0, len - rlen);
1659 *Pos = pos + len + 1;
1667 * \brief Input binary data from socket
1668 * flushes and closes the FD on error
1669 * \param buf the buffer to get the input to
1670 * \param fd pointer to the filedescriptor to read
1671 * \param append Append to an existing string or replace?
1672 * \param nBytes the maximal number of bytes to read
1673 * \param Error strerror() on error
1674 * \returns numbers of chars read
1676 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1680 int len, rlen, slen;
1684 if ((Buf == NULL) || (*fd == -1))
1688 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1689 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1691 ptr = Buf->buf + Buf->BufUsed;
1693 slen = len = Buf->BufUsed;
1695 fdflags = fcntl(*fd, F_GETFL);
1697 while (nRead < nBytes) {
1698 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1701 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1702 *Error = strerror(errno);
1707 if ((rlen = read(*fd,
1709 nBytes - nRead)) == -1) {
1712 *Error = strerror(errno);
1717 Buf->BufUsed += rlen;
1719 Buf->buf[Buf->BufUsed] = '\0';
1724 * \brief Input binary data from socket
1725 * flushes and closes the FD on error
1726 * \param buf the buffer to get the input to
1727 * \param fd pointer to the filedescriptor to read
1728 * \param append Append to an existing string or replace?
1729 * \param nBytes the maximal number of bytes to read
1730 * \param Error strerror() on error
1731 * \returns numbers of chars read
1733 int StrBufReadBLOBBuffered(StrBuf *Blob,
1754 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1758 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1759 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1764 len = pos - IOBuf->buf;
1765 rlen = IOBuf->BufUsed - len;
1768 if ((IOBuf->BufUsed > 0) &&
1770 (pos < IOBuf->buf + IOBuf->BufUsed))
1772 pche = IOBuf->buf + IOBuf->BufUsed;
1775 if (rlen < nBytes) {
1776 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1777 Blob->BufUsed += rlen;
1778 Blob->buf[Blob->BufUsed] = '\0';
1782 if (rlen >= nBytes) {
1783 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1784 Blob->BufUsed += nBytes;
1785 Blob->buf[Blob->BufUsed] = '\0';
1786 if (rlen == nBytes) {
1797 if (IOBuf->BufSize < nBytes - nRead)
1798 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1801 slen = len = Blob->BufUsed;
1803 fdflags = fcntl(*fd, F_GETFL);
1808 while (nRead < nBytes) {
1809 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1812 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1815 *Error = strerror(errno);
1826 *Error = strerror(errno);
1832 if ((check == NNN_TERM) &&
1834 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1836 StrBufPlain(Blob, HKEY("\n000\n"));
1837 StrBufCutRight(Blob, 5);
1838 return Blob->BufUsed;
1840 if (nSelects > 10) {
1848 IOBuf->BufUsed += rlen;
1851 if (nRead > nBytes) {
1852 *Pos = IOBuf->buf + nBytes;
1854 Blob->buf[Blob->BufUsed] = '\0';
1855 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1860 * \brief Cut nChars from the start of the string
1861 * \param Buf Buffer to modify
1862 * \param nChars how many chars should be skipped?
1864 void StrBufCutLeft(StrBuf *Buf, int nChars)
1866 if (nChars >= Buf->BufUsed) {
1870 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1871 Buf->BufUsed -= nChars;
1872 Buf->buf[Buf->BufUsed] = '\0';
1876 * \brief Cut the trailing n Chars from the string
1877 * \param Buf Buffer to modify
1878 * \param nChars how many chars should be trunkated?
1880 void StrBufCutRight(StrBuf *Buf, int nChars)
1882 if (nChars >= Buf->BufUsed) {
1886 Buf->BufUsed -= nChars;
1887 Buf->buf[Buf->BufUsed] = '\0';
1891 * \brief Cut the string after n Chars
1892 * \param Buf Buffer to modify
1893 * \param AfternChars after how many chars should we trunkate the string?
1894 * \param At if non-null and points inside of our string, cut it there.
1896 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1899 AfternChars = At - Buf->buf;
1902 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1904 Buf->BufUsed = AfternChars;
1905 Buf->buf[Buf->BufUsed] = '\0';
1910 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1911 * buf - the string to modify
1912 * len - length of the string.
1914 void StrBufTrim(StrBuf *Buf)
1917 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1919 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1922 if (delta > 0) StrBufCutLeft(Buf, delta);
1924 if (Buf->BufUsed == 0) return;
1925 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1928 Buf->buf[Buf->BufUsed] = '\0';
1932 void StrBufUpCase(StrBuf *Buf)
1937 pche = pch + Buf->BufUsed;
1938 while (pch < pche) {
1939 *pch = toupper(*pch);
1945 void StrBufLowerCase(StrBuf *Buf)
1950 pche = pch + Buf->BufUsed;
1951 while (pch < pche) {
1952 *pch = tolower(*pch);
1959 * \brief unhide special chars hidden to the HTML escaper
1960 * \param target buffer to put the unescaped string in
1961 * \param source buffer to unescape
1963 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1969 FlushStrBuf(target);
1971 if (source == NULL ||target == NULL)
1976 len = source->BufUsed;
1977 for (a = 0; a < len; ++a) {
1978 if (target->BufUsed >= target->BufSize)
1979 IncreaseBuf(target, 1, -1);
1981 if (source->buf[a] == '=') {
1982 hex[0] = source->buf[a + 1];
1983 hex[1] = source->buf[a + 2];
1986 sscanf(hex, "%02x", &b);
1987 target->buf[target->BufUsed] = b;
1988 target->buf[++target->BufUsed] = 0;
1992 target->buf[target->BufUsed] = source->buf[a];
1993 target->buf[++target->BufUsed] = 0;
2000 * \brief hide special chars from the HTML escapers and friends
2001 * \param target buffer to put the escaped string in
2002 * \param source buffer to escape
2004 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2009 FlushStrBuf(target);
2011 if (source == NULL ||target == NULL)
2016 len = source->BufUsed;
2017 for (i=0; i<len; ++i) {
2018 if (target->BufUsed + 4 >= target->BufSize)
2019 IncreaseBuf(target, 1, -1);
2020 if ( (isalnum(source->buf[i])) ||
2021 (source->buf[i]=='-') ||
2022 (source->buf[i]=='_') ) {
2023 target->buf[target->BufUsed++] = source->buf[i];
2026 sprintf(&target->buf[target->BufUsed],
2028 (0xFF &source->buf[i]));
2029 target->BufUsed += 3;
2032 target->buf[target->BufUsed + 1] = '\0';
2036 * \brief uses the same calling syntax as compress2(), but it
2037 * creates a stream compatible with HTTP "Content-encoding: gzip"
2040 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2041 #define OS_CODE 0x03 /*< unix */
2042 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2043 size_t * destLen, /*< length of the compresed data */
2044 const Bytef * source, /*< source to encode */
2045 uLong sourceLen, /*< length of source to encode */
2046 int level) /*< compression level */
2048 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2050 /* write gzip header */
2051 snprintf((char *) dest, *destLen,
2052 "%c%c%c%c%c%c%c%c%c%c",
2053 gz_magic[0], gz_magic[1], Z_DEFLATED,
2054 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2057 /* normal deflate */
2060 stream.next_in = (Bytef *) source;
2061 stream.avail_in = (uInt) sourceLen;
2062 stream.next_out = dest + 10L; // after header
2063 stream.avail_out = (uInt) * destLen;
2064 if ((uLong) stream.avail_out != *destLen)
2067 stream.zalloc = (alloc_func) 0;
2068 stream.zfree = (free_func) 0;
2069 stream.opaque = (voidpf) 0;
2071 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2072 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2076 err = deflate(&stream, Z_FINISH);
2077 if (err != Z_STREAM_END) {
2078 deflateEnd(&stream);
2079 return err == Z_OK ? Z_BUF_ERROR : err;
2081 *destLen = stream.total_out + 10L;
2083 /* write CRC and Length */
2084 uLong crc = crc32(0L, source, sourceLen);
2086 for (n = 0; n < 4; ++n, ++*destLen) {
2087 dest[*destLen] = (int) (crc & 0xff);
2090 uLong len = stream.total_in;
2091 for (n = 0; n < 4; ++n, ++*destLen) {
2092 dest[*destLen] = (int) (len & 0xff);
2095 err = deflateEnd(&stream);
2102 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2104 int CompressBuffer(StrBuf *Buf)
2107 char *compressed_data = NULL;
2108 size_t compressed_len, bufsize;
2111 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2112 compressed_data = malloc(compressed_len);
2114 /* Flush some space after the used payload so valgrind shuts up... */
2115 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2116 Buf->buf[Buf->BufUsed + i++] = '\0';
2117 if (compress_gzip((Bytef *) compressed_data,
2120 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2123 Buf->buf = compressed_data;
2124 Buf->BufUsed = compressed_len;
2125 Buf->BufSize = bufsize;
2126 /* Flush some space after the used payload so valgrind shuts up... */
2128 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2129 Buf->buf[Buf->BufUsed + i++] = '\0';
2132 free(compressed_data);
2134 #endif /* HAVE_ZLIB */
2139 * \brief decode a buffer from base 64 encoding; destroys original
2140 * \param Buf Buffor to transform
2142 int StrBufDecodeBase64(StrBuf *Buf)
2146 if (Buf == NULL) return -1;
2148 xferbuf = (char*) malloc(Buf->BufSize);
2149 siz = CtdlDecodeBase64(xferbuf,
2159 * \brief decode a buffer from base 64 encoding; destroys original
2160 * \param Buf Buffor to transform
2162 int StrBufDecodeHex(StrBuf *Buf)
2165 char *pch, *pche, *pchi;
2167 if (Buf == NULL) return -1;
2169 pch = pchi = Buf->buf;
2170 pche = pch + Buf->BufUsed;
2172 while (pchi < pche){
2173 ch = decode_hex(pchi);
2180 Buf->BufUsed = pch - Buf->buf;
2181 return Buf->BufUsed;
2185 * \brief replace all chars >0x20 && < 0x7F with Mute
2186 * \param Mute char to put over invalid chars
2187 * \param Buf Buffor to transform
2189 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2193 if (Buf == NULL) return -1;
2194 pch = (unsigned char *)Buf->buf;
2195 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2196 if ((*pch < 0x20) || (*pch > 0x7F))
2200 return Buf->BufUsed;
2205 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2206 * \param Buf Buffer to translate
2207 * \param StripBlanks Reduce several blanks to one?
2209 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2215 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2216 Buf->buf[Buf->BufUsed - 1] = '\0';
2221 while (a < Buf->BufUsed) {
2222 if (Buf->buf[a] == '+')
2224 else if (Buf->buf[a] == '%') {
2225 /* don't let % chars through, rather truncate the input. */
2226 if (a + 2 > Buf->BufUsed) {
2231 hex[0] = Buf->buf[a + 1];
2232 hex[1] = Buf->buf[a + 2];
2235 sscanf(hex, "%02x", &b);
2236 Buf->buf[a] = (char) b;
2237 len = Buf->BufUsed - a - 2;
2239 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2251 * \brief RFC2047-encode a header field if necessary.
2252 * If no non-ASCII characters are found, the string
2253 * will be copied verbatim without encoding.
2255 * \param target Target buffer.
2256 * \param source Source string to be encoded.
2257 * \returns encoded length; -1 if non success.
2259 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2261 const char headerStr[] = "=?UTF-8?Q?";
2262 int need_to_encode = 0;
2266 if ((source == NULL) ||
2270 while ((i < source->BufUsed) &&
2271 (!IsEmptyStr (&source->buf[i])) &&
2272 (need_to_encode == 0)) {
2273 if (((unsigned char) source->buf[i] < 32) ||
2274 ((unsigned char) source->buf[i] > 126)) {
2280 if (!need_to_encode) {
2281 if (*target == NULL) {
2282 *target = NewStrBufPlain(source->buf, source->BufUsed);
2285 FlushStrBuf(*target);
2286 StrBufAppendBuf(*target, source, 0);
2288 return (*target)->BufUsed;
2290 if (*target == NULL)
2291 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2292 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2293 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2294 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2295 (*target)->BufUsed = sizeof(headerStr) - 1;
2296 for (i=0; (i < source->BufUsed); ++i) {
2297 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2298 IncreaseBuf(*target, 1, 0);
2299 ch = (unsigned char) source->buf[i];
2300 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2301 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2302 (*target)->BufUsed += 3;
2305 (*target)->buf[(*target)->BufUsed] = ch;
2306 (*target)->BufUsed++;
2310 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2311 IncreaseBuf(*target, 1, 0);
2313 (*target)->buf[(*target)->BufUsed++] = '?';
2314 (*target)->buf[(*target)->BufUsed++] = '=';
2315 (*target)->buf[(*target)->BufUsed] = '\0';
2316 return (*target)->BufUsed;;
2320 * \brief replaces all occurances of 'search' by 'replace'
2321 * \param buf Buffer to modify
2322 * \param search character to search
2323 * \param relpace character to replace search by
2325 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2330 for (i=0; i<buf->BufUsed; i++)
2331 if (buf->buf[i] == search)
2332 buf->buf[i] = replace;
2339 * Wrapper around iconv_open()
2340 * Our version adds aliases for non-standard Microsoft charsets
2341 * such as 'MS950', aliasing them to names like 'CP950'
2343 * tocode Target encoding
2344 * fromcode Source encoding
2346 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2349 iconv_t ic = (iconv_t)(-1) ;
2350 ic = iconv_open(tocode, fromcode);
2351 if (ic == (iconv_t)(-1) ) {
2352 char alias_fromcode[64];
2353 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2354 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2355 alias_fromcode[0] = 'C';
2356 alias_fromcode[1] = 'P';
2357 ic = iconv_open(tocode, alias_fromcode);
2360 *(iconv_t *)pic = ic;
2366 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2369 /* Find the next ?Q? */
2370 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2373 end = strchr(bptr + 2, '?');
2378 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2379 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2380 (*(end + 2) == '?')) {
2381 /* skip on to the end of the cluster, the next ?= */
2382 end = strstr(end + 3, "?=");
2385 /* sort of half valid encoding, try to find an end. */
2386 end = strstr(bptr, "?=");
2391 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2396 char *ibuf; /**< Buffer of characters to be converted */
2397 char *obuf; /**< Buffer for converted characters */
2398 size_t ibuflen; /**< Length of input buffer */
2399 size_t obuflen; /**< Length of output buffer */
2402 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2403 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2405 ic = *(iconv_t*)pic;
2406 ibuf = ConvertBuf->buf;
2407 ibuflen = ConvertBuf->BufUsed;
2409 obuflen = TmpBuf->BufSize;
2411 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2413 /* little card game: wheres the red lady? */
2414 ibuf = ConvertBuf->buf;
2415 BufSize = ConvertBuf->BufSize;
2417 ConvertBuf->buf = TmpBuf->buf;
2418 ConvertBuf->BufSize = TmpBuf->BufSize;
2419 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2420 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2423 TmpBuf->BufSize = BufSize;
2424 TmpBuf->BufUsed = 0;
2425 TmpBuf->buf[0] = '\0';
2432 inline static void DecodeSegment(StrBuf *Target,
2433 const StrBuf *DecodeMe,
2437 StrBuf *ConvertBuf2,
2438 StrBuf *FoundCharset)
2444 iconv_t ic = (iconv_t)(-1);
2446 /* Now we handle foreign character sets properly encoded
2447 * in RFC2047 format.
2449 StaticBuf.buf = SegmentStart;
2450 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2451 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2452 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2453 if (FoundCharset != NULL) {
2454 FlushStrBuf(FoundCharset);
2455 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2457 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2458 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2460 *encoding = toupper(*encoding);
2461 if (*encoding == 'B') { /**< base64 */
2462 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2464 ConvertBuf->BufUsed);
2466 else if (*encoding == 'Q') { /**< quoted-printable */
2470 while (pos < ConvertBuf->BufUsed)
2472 if (ConvertBuf->buf[pos] == '_')
2473 ConvertBuf->buf[pos] = ' ';
2477 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2480 ConvertBuf->BufUsed);
2483 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2486 ctdl_iconv_open("UTF-8", charset, &ic);
2487 if (ic != (iconv_t)(-1) ) {
2489 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2490 StrBufAppendBuf(Target, ConvertBuf2, 0);
2495 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2500 * Handle subjects with RFC2047 encoding such as:
2501 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2503 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2505 StrBuf *ConvertBuf, *ConvertBuf2;
2506 char *start, *end, *next, *nextend, *ptr = NULL;
2508 iconv_t ic = (iconv_t)(-1) ;
2513 int illegal_non_rfc2047_encoding = 0;
2515 /* Sometimes, badly formed messages contain strings which were simply
2516 * written out directly in some foreign character set instead of
2517 * using RFC2047 encoding. This is illegal but we will attempt to
2518 * handle it anyway by converting from a user-specified default
2519 * charset to UTF-8 if we see any nonprintable characters.
2522 len = StrLength(DecodeMe);
2523 for (i=0; i<DecodeMe->BufUsed; ++i) {
2524 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2525 illegal_non_rfc2047_encoding = 1;
2530 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2531 if ((illegal_non_rfc2047_encoding) &&
2532 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2533 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2536 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2537 if (ic != (iconv_t)(-1) ) {
2538 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2544 /* pre evaluate the first pair */
2545 nextend = end = NULL;
2546 len = StrLength(DecodeMe);
2547 start = strstr(DecodeMe->buf, "=?");
2548 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2550 end = FindNextEnd (DecodeMe, start);
2552 StrBufAppendBuf(Target, DecodeMe, 0);
2553 FreeStrBuf(&ConvertBuf);
2557 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2559 if (start != DecodeMe->buf)
2560 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2562 * Since spammers will go to all sorts of absurd lengths to get their
2563 * messages through, there are LOTS of corrupt headers out there.
2564 * So, prevent a really badly formed RFC2047 header from throwing
2565 * this function into an infinite loop.
2567 while ((start != NULL) &&
2574 DecodeSegment(Target,
2582 next = strstr(end, "=?");
2584 if ((next != NULL) &&
2586 nextend = FindNextEnd(DecodeMe, next);
2587 if (nextend == NULL)
2590 /* did we find two partitions */
2591 if ((next != NULL) &&
2595 while ((ptr < next) &&
2601 /* did we find a gab just filled with blanks? */
2606 len - (next - start));
2608 /* now terminate the gab at the end */
2609 delta = (next - end) - 2; ////TODO: const!
2610 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2611 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2613 /* move next to its new location. */
2618 /* our next-pair is our new first pair now. */
2624 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2625 if ((end != NULL) && (end < nextend)) {
2627 while ( (ptr < nextend) &&
2634 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2636 FreeStrBuf(&ConvertBuf);
2637 FreeStrBuf(&ConvertBuf2);
2642 long StrBuf_Utf8StrLen(StrBuf *Buf)
2644 return Ctdl_Utf8StrLen(Buf->buf);
2647 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2651 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2652 if (CutAt != NULL) {
2653 Buf->BufUsed = CutAt - Buf->buf;
2654 Buf->buf[Buf->BufUsed] = '\0';
2656 return Buf->BufUsed;
2661 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2663 const char *aptr, *ptr, *eptr;
2670 ptr = aptr = Buf->buf;
2674 optr = LineBuf->buf;
2675 eptr = Buf->buf + Buf->BufUsed;
2676 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2678 while ((*ptr != '\n') &&
2685 LineBuf->BufUsed = optr - LineBuf->buf;
2686 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2687 optr = LineBuf->buf + LineBuf->BufUsed;
2688 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2691 LineBuf->BufUsed = optr - LineBuf->buf;
2700 return Buf->BufUsed - (ptr - Buf->buf);