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 = SIZ;
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);
135 StrBufBacktrace(Buf, 1);
142 * \brief shrink long term buffers to their real size so they don't waste memory
143 * \param Buf buffer to shrink
144 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
145 * \returns physical size of the buffer
147 long StrBufShrinkToFit(StrBuf *Buf, int Force)
150 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
152 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
153 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
154 Buf->BufSize = Buf->BufUsed + 1;
162 * Allocate a new buffer with default buffer size
163 * \returns the new stringbuffer
165 StrBuf* NewStrBuf(void)
169 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
170 NewBuf->buf = (char*) malloc(BaseStrBufSize);
171 NewBuf->buf[0] = '\0';
172 NewBuf->BufSize = BaseStrBufSize;
174 NewBuf->ConstBuf = 0;
176 NewBuf->nIncreases = 0;
177 NewBuf->bt[0] = '\0';
178 NewBuf->bt_lastinc[0] = '\0';
180 StrBufBacktrace(NewBuf, 0);
187 * \brief Copy Constructor; returns a duplicate of CopyMe
188 * \params CopyMe Buffer to faxmilate
189 * \returns the new stringbuffer
191 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
198 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
199 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
200 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
201 NewBuf->BufUsed = CopyMe->BufUsed;
202 NewBuf->BufSize = CopyMe->BufSize;
203 NewBuf->ConstBuf = 0;
205 NewBuf->nIncreases = 0;
206 NewBuf->bt[0] = '\0';
207 NewBuf->bt_lastinc[0] = '\0';
209 StrBufBacktrace(NewBuf, 0);
216 * \brief create a new Buffer using an existing c-string
217 * this function should also be used if you want to pre-suggest
218 * the buffer size to allocate in conjunction with ptr == NULL
219 * \param ptr the c-string to copy; may be NULL to create a blank instance
220 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
221 * \returns the new stringbuffer
223 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
226 size_t Siz = BaseStrBufSize;
229 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
231 CopySize = strlen((ptr != NULL)?ptr:"");
235 while (Siz <= CopySize)
238 NewBuf->buf = (char*) malloc(Siz);
239 NewBuf->BufSize = Siz;
241 memcpy(NewBuf->buf, ptr, CopySize);
242 NewBuf->buf[CopySize] = '\0';
243 NewBuf->BufUsed = CopySize;
246 NewBuf->buf[0] = '\0';
249 NewBuf->ConstBuf = 0;
251 NewBuf->nIncreases = 0;
252 NewBuf->bt[0] = '\0';
253 NewBuf->bt_lastinc[0] = '\0';
255 StrBufBacktrace(NewBuf, 0);
262 * \brief Set an existing buffer from a c-string
263 * \param ptr c-string to put into
264 * \param nChars set to -1 if we should work 0-terminated
265 * \returns the new length of the string
267 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
269 size_t Siz = Buf->BufSize;
273 CopySize = strlen(ptr);
277 while (Siz <= CopySize)
280 if (Siz != Buf->BufSize)
281 IncreaseBuf(Buf, 0, Siz);
282 memcpy(Buf->buf, ptr, CopySize);
283 Buf->buf[CopySize] = '\0';
284 Buf->BufUsed = CopySize;
291 * \brief use strbuf as wrapper for a string constant for easy handling
292 * \param StringConstant a string to wrap
293 * \param SizeOfConstant should be sizeof(StringConstant)-1
295 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
299 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
300 NewBuf->buf = (char*) StringConstant;
301 NewBuf->BufSize = SizeOfStrConstant;
302 NewBuf->BufUsed = SizeOfStrConstant;
303 NewBuf->ConstBuf = 1;
305 NewBuf->nIncreases = 0;
306 NewBuf->bt[0] = '\0';
307 NewBuf->bt_lastinc[0] = '\0';
314 * \brief flush the content of a Buf; keep its struct
315 * \param buf Buffer to flush
317 int FlushStrBuf(StrBuf *buf)
329 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
330 * \param buf Buffer to wipe
332 int FLUSHStrBuf(StrBuf *buf)
338 if (buf->BufUsed > 0) {
339 memset(buf->buf, 0, buf->BufUsed);
346 int hFreeDbglog = -1;
349 * \brief Release a Buffer
350 * Its a double pointer, so it can NULL your pointer
351 * so fancy SIG11 appear instead of random results
352 * \param FreeMe Pointer Pointer to the buffer to free
354 void FreeStrBuf (StrBuf **FreeMe)
359 if (hFreeDbglog == -1){
360 pid_t pid = getpid();
362 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
363 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
365 if ((*FreeMe)->nIncreases > 0)
369 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
370 (*FreeMe)->nIncreases,
374 (*FreeMe)->bt_lastinc);
375 n = write(hFreeDbglog, buf, n);
381 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
384 n = write(hFreeDbglog, buf, n);
387 if (!(*FreeMe)->ConstBuf)
388 free((*FreeMe)->buf);
394 * \brief Release the buffer
395 * If you want put your StrBuf into a Hash, use this as Destructor.
396 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
398 void HFreeStrBuf (void *VFreeMe)
400 StrBuf *FreeMe = (StrBuf*)VFreeMe;
404 if (hFreeDbglog == -1){
405 pid_t pid = getpid();
407 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
408 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
410 if (FreeMe->nIncreases > 0)
414 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
420 write(hFreeDbglog, buf, n);
426 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
432 if (!FreeMe->ConstBuf)
438 * \brief Wrapper around atol
440 long StrTol(const StrBuf *Buf)
445 return atol(Buf->buf);
451 * \brief Wrapper around atoi
453 int StrToi(const StrBuf *Buf)
457 if (Buf->BufUsed > 0)
458 return atoi(Buf->buf);
464 * \brief Checks to see if the string is a pure number
466 int StrBufIsNumber(const StrBuf *Buf) {
471 strtoll(Buf->buf, &pEnd, 10);
472 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
478 * \brief modifies a Single char of the Buf
479 * You can point to it via char* or a zero-based integer
480 * \param ptr char* to zero; use NULL if unused
481 * \param nThChar zero based pointer into the string; use -1 if unused
482 * \param PeekValue The Character to place into the position
484 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
489 nThChar = ptr - Buf->buf;
490 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
492 Buf->buf[nThChar] = PeekValue;
497 * \brief Append a StringBuffer to the buffer
498 * \param Buf Buffer to modify
499 * \param AppendBuf Buffer to copy at the end of our buffer
500 * \param Offset Should we start copying from an offset?
502 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
504 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
507 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
510 AppendBuf->BufUsed + Buf->BufUsed);
512 memcpy(Buf->buf + Buf->BufUsed,
513 AppendBuf->buf + Offset,
514 AppendBuf->BufUsed - Offset);
515 Buf->BufUsed += AppendBuf->BufUsed - Offset;
516 Buf->buf[Buf->BufUsed] = '\0';
521 * \brief Append a C-String to the buffer
522 * \param Buf Buffer to modify
523 * \param AppendBuf Buffer to copy at the end of our buffer
524 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
525 * \param Offset Should we start copying from an offset?
527 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
530 long BufSizeRequired;
532 if ((AppendBuf == NULL) || (Buf == NULL))
536 aps = strlen(AppendBuf + Offset);
538 aps = AppendSize - Offset;
540 BufSizeRequired = Buf->BufUsed + aps + 1;
541 if (Buf->BufSize <= BufSizeRequired)
542 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
544 memcpy(Buf->buf + Buf->BufUsed,
548 Buf->buf[Buf->BufUsed] = '\0';
553 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
554 * \param outbuf the output buffer
555 * \param oblen the size of outbuf to sanitize
556 * \param strbuf the input buffer
558 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
560 const char *pch, *pche;
563 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
564 int eclen = sizeof(ec) -1;
566 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
568 if (PlainIn != NULL) {
569 len = strlen(PlainIn);
575 pche = pch + In->BufUsed;
582 pt = OutBuf->buf + OutBuf->BufUsed;
583 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
587 IncreaseBuf(OutBuf, 1, -1);
588 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
589 pt = OutBuf->buf + OutBuf->BufUsed;
593 for (b = 0; b < eclen; ++b) {
600 sprintf(pt,"%%%02X", *pch);
602 OutBuf->BufUsed += 3;
614 * \brief Append a string, escaping characters which have meaning in HTML.
616 * \param Target target buffer
617 * \param Source source buffer; set to NULL if you just have a C-String
618 * \param PlainIn Plain-C string to append; set to NULL if unused
619 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
620 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
621 * if set to 2, linebreaks are replaced by <br/>
623 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
625 const char *aptr, *eiptr;
629 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
632 if (PlainIn != NULL) {
634 len = strlen(PlainIn);
639 eiptr = aptr + Source->BufUsed;
640 len = Source->BufUsed;
646 bptr = Target->buf + Target->BufUsed;
647 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
649 while (aptr < eiptr){
651 IncreaseBuf(Target, 1, -1);
652 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
653 bptr = Target->buf + Target->BufUsed;
656 memcpy(bptr, "<", 4);
658 Target->BufUsed += 4;
660 else if (*aptr == '>') {
661 memcpy(bptr, ">", 4);
663 Target->BufUsed += 4;
665 else if (*aptr == '&') {
666 memcpy(bptr, "&", 5);
668 Target->BufUsed += 5;
670 else if (*aptr == '"') {
671 memcpy(bptr, """, 6);
673 Target->BufUsed += 6;
675 else if (*aptr == '\'') {
676 memcpy(bptr, "'", 5);
678 Target->BufUsed += 5;
680 else if (*aptr == LB) {
685 else if (*aptr == RB) {
690 else if (*aptr == QU) {
695 else if ((*aptr == 32) && (nbsp == 1)) {
696 memcpy(bptr, " ", 6);
698 Target->BufUsed += 6;
700 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
701 *bptr='\0'; /* nothing */
703 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
704 memcpy(bptr, "<br/>", 11);
706 Target->BufUsed += 11;
710 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
711 *bptr='\0'; /* nothing */
721 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
723 return Target->BufUsed;
727 * \brief Append a string, escaping characters which have meaning in HTML.
728 * Converts linebreaks into blanks; escapes single quotes
729 * \param Target target buffer
730 * \param Source source buffer; set to NULL if you just have a C-String
731 * \param PlainIn Plain-C string to append; set to NULL if unused
733 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
735 const char *aptr, *eiptr;
739 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
742 if (PlainIn != NULL) {
744 len = strlen(PlainIn);
749 eiptr = aptr + Source->BufUsed;
750 len = Source->BufUsed;
756 eptr = Target->buf + Target->BufSize - 8;
757 tptr = Target->buf + Target->BufUsed;
759 while (aptr < eiptr){
761 IncreaseBuf(Target, 1, -1);
762 eptr = Target->buf + Target->BufSize - 8;
763 tptr = Target->buf + Target->BufUsed;
770 else if (*aptr == '\r') {
774 else if (*aptr == '\'') {
780 Target->BufUsed += 5;
791 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
793 * \param Target target buffer
794 * \param Source source buffer; set to NULL if you just have a C-String
795 * \param PlainIn Plain-C string to append; set to NULL if unused
797 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
799 const char *aptr, *eiptr;
803 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
806 if (PlainIn != NULL) {
808 len = strlen(PlainIn);
813 eiptr = aptr + Source->BufUsed;
814 len = Source->BufUsed;
820 bptr = Target->buf + Target->BufUsed;
821 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
823 while (aptr < eiptr){
825 IncreaseBuf(Target, 1, -1);
826 eptr = Target->buf + Target->BufSize - 3;
827 bptr = Target->buf + Target->BufUsed;
829 else if (*aptr == '"') {
830 memcpy(bptr, "\\\"", 2);
832 Target->BufUsed += 2;
833 } else if (*aptr == '\\') {
834 memcpy(bptr, "\\\\", 2);
836 Target->BufUsed += 2;
846 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
848 return Target->BufUsed;
852 * \brief extracts a substring from Source into dest
853 * \param dest buffer to place substring into
854 * \param Source string to copy substring from
855 * \param Offset chars to skip from start
856 * \param nChars number of chars to copy
857 * \returns the number of chars copied; may be different from nChars due to the size of Source
859 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
862 if (Offset > Source->BufUsed)
867 if (Offset + nChars < Source->BufUsed)
869 if (nChars >= dest->BufSize)
870 IncreaseBuf(dest, 0, nChars + 1);
871 memcpy(dest->buf, Source->buf + Offset, nChars);
872 dest->BufUsed = nChars;
873 dest->buf[dest->BufUsed] = '\0';
876 NCharsRemain = Source->BufUsed - Offset;
877 if (NCharsRemain >= dest->BufSize)
878 IncreaseBuf(dest, 0, NCharsRemain + 1);
879 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
880 dest->BufUsed = NCharsRemain;
881 dest->buf[dest->BufUsed] = '\0';
886 * \brief sprintf like function appending the formated string to the buffer
887 * vsnprintf version to wrap into own calls
888 * \param Buf Buffer to extend by format and params
889 * \param format printf alike format to add
890 * \param ap va_list containing the items for format
892 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
895 size_t BufSize = Buf->BufSize;
896 size_t nWritten = Buf->BufSize + 1;
897 size_t Offset = Buf->BufUsed;
898 size_t newused = Offset + nWritten;
900 while (newused >= BufSize) {
902 nWritten = vsnprintf(Buf->buf + Offset,
903 Buf->BufSize - Offset,
906 newused = Offset + nWritten;
907 if (newused >= Buf->BufSize) {
908 IncreaseBuf(Buf, 1, newused);
911 Buf->BufUsed = Offset + nWritten;
912 BufSize = Buf->BufSize;
919 * \brief sprintf like function appending the formated string to the buffer
920 * \param Buf Buffer to extend by format and params
921 * \param format printf alike format to add
922 * \param ap va_list containing the items for format
924 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
926 size_t BufSize = Buf->BufSize;
927 size_t nWritten = Buf->BufSize + 1;
928 size_t Offset = Buf->BufUsed;
929 size_t newused = Offset + nWritten;
932 while (newused >= BufSize) {
933 va_start(arg_ptr, format);
934 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
935 Buf->BufSize - Buf->BufUsed,
938 newused = Buf->BufUsed + nWritten;
939 if (newused >= Buf->BufSize) {
940 IncreaseBuf(Buf, 1, newused);
943 Buf->BufUsed += nWritten;
944 BufSize = Buf->BufSize;
951 * \brief sprintf like function putting the formated string into the buffer
952 * \param Buf Buffer to extend by format and params
953 * \param format printf alike format to add
954 * \param ap va_list containing the items for format
956 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
958 size_t nWritten = Buf->BufSize + 1;
961 while (nWritten >= Buf->BufSize) {
962 va_start(arg_ptr, format);
963 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
965 Buf->BufUsed = nWritten ;
966 if (nWritten >= Buf->BufSize)
967 IncreaseBuf(Buf, 0, 0);
973 * \brief Counts the numbmer of tokens in a buffer
974 * \param Source String to count tokens in
975 * \param tok Tokenizer char to count
976 * \returns numbers of tokenizer chars found
978 int StrBufNum_tokens(const StrBuf *source, char tok)
982 return num_tokens(source->buf, tok);
986 * remove_token() - a tokenizer that kills, maims, and destroys
989 * \brief a string tokenizer
990 * \param Source StringBuffer to read into
991 * \param parmnum n'th parameter to remove
992 * \param separator tokenizer param
993 * \returns -1 if not found, else length of token.
995 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
998 char *d, *s; /* dest, source */
1001 /* Find desired parameter */
1003 while (count < parmnum) {
1004 /* End of string, bail! */
1009 if (*d == separator) {
1014 if (!d) return 0; /* Parameter not found */
1016 /* Find next parameter */
1018 while (*s && *s != separator) {
1021 if (*s == separator)
1025 /* Hack and slash */
1027 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1028 Source->BufUsed -= (ReducedBy + 1);
1030 else if (d == Source->buf) {
1032 Source->BufUsed = 0;
1036 Source->BufUsed -= (ReducedBy + 1);
1049 * \brief a string tokenizer
1050 * \param dest Destination StringBuffer
1051 * \param Source StringBuffer to read into
1052 * \param parmnum n'th parameter to extract
1053 * \param separator tokenizer param
1054 * \returns -1 if not found, else length of token.
1056 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1058 const char *s, *e; //* source * /
1059 int len = 0; //* running total length of extracted string * /
1060 int current_token = 0; //* token currently being processed * /
1063 dest->buf[0] = '\0';
1069 if ((Source == NULL) || (Source->BufUsed ==0)) {
1073 e = s + Source->BufUsed;
1076 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1078 while ((s<e) && !IsEmptyStr(s)) {
1079 if (*s == separator) {
1082 if (len >= dest->BufSize)
1083 if (!IncreaseBuf(dest, 1, -1))
1085 if ( (current_token == parmnum) &&
1086 (*s != separator)) {
1087 dest->buf[len] = *s;
1090 else if (current_token > parmnum) {
1096 dest->buf[len] = '\0';
1097 dest->BufUsed = len;
1099 if (current_token < parmnum) {
1100 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1103 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1112 * \brief a string tokenizer to fetch an integer
1113 * \param dest Destination StringBuffer
1114 * \param parmnum n'th parameter to extract
1115 * \param separator tokenizer param
1116 * \returns 0 if not found, else integer representation of the token
1118 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1128 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1135 * \brief a string tokenizer to fetch a long integer
1136 * \param dest Destination StringBuffer
1137 * \param parmnum n'th parameter to extract
1138 * \param separator tokenizer param
1139 * \returns 0 if not found, else long integer representation of the token
1141 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1151 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1159 * \brief a string tokenizer to fetch an unsigned long
1160 * \param dest Destination StringBuffer
1161 * \param parmnum n'th parameter to extract
1162 * \param separator tokenizer param
1163 * \returns 0 if not found, else unsigned long representation of the token
1165 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1176 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1180 return (unsigned long) atol(pnum);
1189 * \brief a string tokenizer
1190 * \param dest Destination StringBuffer
1191 * \param Source StringBuffer to read into
1192 * \param pStart pointer to the end of the last token. Feed with NULL.
1193 * \param separator tokenizer param
1194 * \returns -1 if not found, else length of token.
1196 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1198 const char *s, *EndBuffer; //* source * /
1199 int len = 0; //* running total length of extracted string * /
1200 int current_token = 0; //* token currently being processed * /
1203 dest->buf[0] = '\0';
1209 if ((Source == NULL) ||
1210 (Source->BufUsed ==0)) {
1213 if (*pStart == NULL)
1214 *pStart = Source->buf;
1216 EndBuffer = Source->buf + Source->BufUsed;
1218 if ((*pStart < Source->buf) ||
1219 (*pStart > EndBuffer)) {
1227 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1229 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1230 if (*s == separator) {
1233 if (len >= dest->BufSize)
1234 if (!IncreaseBuf(dest, 1, -1)) {
1235 *pStart = EndBuffer + 1;
1238 if ( (current_token == 0) &&
1239 (*s != separator)) {
1240 dest->buf[len] = *s;
1243 else if (current_token > 0) {
1252 dest->buf[len] = '\0';
1253 dest->BufUsed = len;
1254 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1255 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1261 * \brief a string tokenizer
1262 * \param dest Destination StringBuffer
1263 * \param Source StringBuffer to read into
1264 * \param pStart pointer to the end of the last token. Feed with NULL.
1265 * \param separator tokenizer param
1266 * \returns -1 if not found, else length of token.
1268 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1270 const char *s, *EndBuffer; //* source * /
1271 int len = 0; //* running total length of extracted string * /
1272 int current_token = 0; //* token currently being processed * /
1274 if ((Source == NULL) ||
1275 (Source->BufUsed ==0)) {
1279 return Source->BufUsed;
1281 if (*pStart == NULL)
1282 *pStart = Source->buf;
1284 EndBuffer = Source->buf + Source->BufUsed;
1286 if ((*pStart < Source->buf) ||
1287 (*pStart > EndBuffer)) {
1295 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1297 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1298 if (*s == separator) {
1301 if (current_token >= nTokens) {
1313 * \brief a string tokenizer to fetch an integer
1314 * \param dest Destination StringBuffer
1315 * \param parmnum n'th parameter to extract
1316 * \param separator tokenizer param
1317 * \returns 0 if not found, else integer representation of the token
1319 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1329 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1336 * \brief a string tokenizer to fetch a long integer
1337 * \param dest Destination StringBuffer
1338 * \param parmnum n'th parameter to extract
1339 * \param separator tokenizer param
1340 * \returns 0 if not found, else long integer representation of the token
1342 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1352 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1360 * \brief a string tokenizer to fetch an unsigned long
1361 * \param dest Destination StringBuffer
1362 * \param parmnum n'th parameter to extract
1363 * \param separator tokenizer param
1364 * \returns 0 if not found, else unsigned long representation of the token
1366 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1377 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1381 return (unsigned long) atol(pnum);
1390 * \brief Read a line from socket
1391 * flushes and closes the FD on error
1392 * \param buf the buffer to get the input to
1393 * \param fd pointer to the filedescriptor to read
1394 * \param append Append to an existing string or replace?
1395 * \param Error strerror() on error
1396 * \returns numbers of chars read
1398 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1400 int len, rlen, slen;
1405 slen = len = buf->BufUsed;
1407 rlen = read(*fd, &buf->buf[len], 1);
1409 *Error = strerror(errno);
1416 if (buf->buf[len] == '\n')
1418 if (buf->buf[len] != '\r')
1420 if (len >= buf->BufSize) {
1422 buf->buf[len+1] = '\0';
1423 IncreaseBuf(buf, 1, -1);
1427 buf->buf[len] = '\0';
1432 * \brief Read a line from socket
1433 * flushes and closes the FD on error
1434 * \param buf the buffer to get the input to
1435 * \param fd pointer to the filedescriptor to read
1436 * \param append Append to an existing string or replace?
1437 * \param Error strerror() on error
1438 * \returns numbers of chars read
1440 int StrBufTCP_read_buffered_line(StrBuf *Line,
1444 int selectresolution,
1448 int nSuccessLess = 0;
1454 if (buf->BufUsed > 0) {
1455 pch = strchr(buf->buf, '\n');
1458 len = pch - buf->buf;
1459 if (len > 0 && (*(pch - 1) == '\r') )
1461 StrBufSub(Line, buf, 0, len - rlen);
1462 StrBufCutLeft(buf, len + 1);
1467 if (buf->BufSize - buf->BufUsed < 10)
1468 IncreaseBuf(buf, 1, -1);
1470 fdflags = fcntl(*fd, F_GETFL);
1471 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1474 while ((nSuccessLess < timeout) && (pch == NULL)) {
1475 tv.tv_sec = selectresolution;
1480 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1481 *Error = strerror(errno);
1486 if (FD_ISSET(*fd, &rfds)) {
1488 &buf->buf[buf->BufUsed],
1489 buf->BufSize - buf->BufUsed - 1);
1491 *Error = strerror(errno);
1496 else if (rlen > 0) {
1498 buf->BufUsed += rlen;
1499 buf->buf[buf->BufUsed] = '\0';
1500 if (buf->BufUsed + 10 > buf->BufSize) {
1501 IncreaseBuf(buf, 1, -1);
1503 pch = strchr(buf->buf, '\n');
1511 len = pch - buf->buf;
1512 if (len > 0 && (*(pch - 1) == '\r') )
1514 StrBufSub(Line, buf, 0, len - rlen);
1515 StrBufCutLeft(buf, len + 1);
1523 * \brief Read a line from socket
1524 * flushes and closes the FD on error
1525 * \param buf the buffer to get the input to
1526 * \param Pos pointer to the current read position, should be NULL initialized!
1527 * \param fd pointer to the filedescriptor to read
1528 * \param append Append to an existing string or replace?
1529 * \param Error strerror() on error
1530 * \returns numbers of chars read
1532 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1537 int selectresolution,
1543 int nSuccessLess = 0;
1545 const char *pch = NULL;
1550 if ((buf->BufUsed > 0) &&
1552 (pos < buf->buf + buf->BufUsed))
1554 pche = buf->buf + buf->BufUsed;
1556 while ((pch <= pche) && (*pch != '\n'))
1560 if ((pch != NULL) &&
1565 if (len > 0 && (*(pch - 1) == '\r') )
1567 StrBufSub(Line, buf, (pos - buf->buf), len - rlen);
1574 StrBufCutLeft(buf, (pos - buf->buf));
1578 if (buf->BufSize - buf->BufUsed < 10) {
1579 IncreaseBuf(buf, 1, -1);
1582 fdflags = fcntl(*fd, F_GETFL);
1583 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1586 while ((nSuccessLess < timeout) && (pch == NULL)) {
1587 tv.tv_sec = selectresolution;
1592 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1593 *Error = strerror(errno);
1598 if (FD_ISSET(*fd, &rfds) != 0) {
1600 &buf->buf[buf->BufUsed],
1601 buf->BufSize - buf->BufUsed - 1);
1603 *Error = strerror(errno);
1608 else if (rlen > 0) {
1610 buf->BufUsed += rlen;
1611 buf->buf[buf->BufUsed] = '\0';
1612 if (buf->BufUsed + 10 > buf->BufSize) {
1613 IncreaseBuf(buf, 1, -1);
1615 pch = strchr(buf->buf, '\n');
1625 if (len > 0 && (*(pch - 1) == '\r') )
1627 StrBufSub(Line, buf, 0, len - rlen);
1628 *Pos = pos + len + 1;
1636 * \brief Input binary data from socket
1637 * flushes and closes the FD on error
1638 * \param buf the buffer to get the input to
1639 * \param fd pointer to the filedescriptor to read
1640 * \param append Append to an existing string or replace?
1641 * \param nBytes the maximal number of bytes to read
1642 * \param Error strerror() on error
1643 * \returns numbers of chars read
1645 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1649 int len, rlen, slen;
1653 if ((Buf == NULL) || (*fd == -1))
1657 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1658 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1660 ptr = Buf->buf + Buf->BufUsed;
1662 slen = len = Buf->BufUsed;
1664 fdflags = fcntl(*fd, F_GETFL);
1666 while (nRead < nBytes) {
1667 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1670 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1671 *Error = strerror(errno);
1676 if ((rlen = read(*fd,
1678 nBytes - nRead)) == -1) {
1681 *Error = strerror(errno);
1686 Buf->BufUsed += rlen;
1688 Buf->buf[Buf->BufUsed] = '\0';
1693 * \brief Input binary data from socket
1694 * flushes and closes the FD on error
1695 * \param buf the buffer to get the input to
1696 * \param fd pointer to the filedescriptor to read
1697 * \param append Append to an existing string or replace?
1698 * \param nBytes the maximal number of bytes to read
1699 * \param Error strerror() on error
1700 * \returns numbers of chars read
1702 int StrBufReadBLOBBuffered(StrBuf *Buf,
1704 const char **BufPos,
1720 if ((Buf == NULL) || (*fd == -1) || (IOBuf == NULL) || (BufPos == NULL))
1724 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1725 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1729 len = *BufPos - IOBuf->buf;
1730 rlen = IOBuf->BufUsed - len;
1732 if ((IOBuf->BufUsed > 0) &&
1733 ((IOBuf->BufUsed - len > 0))) {
1734 if (rlen < nBytes) {
1735 memcpy(Buf->buf + Buf->BufUsed, *BufPos, rlen);
1736 Buf->BufUsed += rlen;
1737 Buf->buf[Buf->BufUsed] = '\0';
1742 if (rlen >= nBytes) {
1743 memcpy(Buf->buf + Buf->BufUsed, *BufPos, nBytes);
1744 Buf->BufUsed += nBytes;
1745 Buf->buf[Buf->BufUsed] = '\0';
1746 if (rlen == nBytes) {
1756 ptr = IOBuf->buf + Buf->BufUsed;
1758 slen = len = Buf->BufUsed;
1760 fdflags = fcntl(*fd, F_GETFL);
1763 while (nRead < nBytes) {
1764 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1767 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1770 *Error = strerror(errno);
1775 if ((rlen = read(*fd,
1777 nBytes - nRead)) == -1) {
1780 *Error = strerror(errno);
1786 if ((check == NNN_TERM) &&
1788 (strncmp(Buf->buf + Buf->BufUsed - 5, "\n000\n", 5) == 0))
1790 StrBufPlain(IOBuf, HKEY("\n000\n"));
1791 StrBufCutRight(Buf, 5);
1792 return Buf->BufUsed;
1794 if (nSelects > 10) {
1801 Buf->BufUsed += rlen;
1803 Buf->buf[Buf->BufUsed] = '\0';
1808 * \brief Cut nChars from the start of the string
1809 * \param Buf Buffer to modify
1810 * \param nChars how many chars should be skipped?
1812 void StrBufCutLeft(StrBuf *Buf, int nChars)
1814 if (nChars >= Buf->BufUsed) {
1818 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1819 Buf->BufUsed -= nChars;
1820 Buf->buf[Buf->BufUsed] = '\0';
1824 * \brief Cut the trailing n Chars from the string
1825 * \param Buf Buffer to modify
1826 * \param nChars how many chars should be trunkated?
1828 void StrBufCutRight(StrBuf *Buf, int nChars)
1830 if (nChars >= Buf->BufUsed) {
1834 Buf->BufUsed -= nChars;
1835 Buf->buf[Buf->BufUsed] = '\0';
1839 * \brief Cut the string after n Chars
1840 * \param Buf Buffer to modify
1841 * \param AfternChars after how many chars should we trunkate the string?
1842 * \param At if non-null and points inside of our string, cut it there.
1844 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1847 AfternChars = At - Buf->buf;
1850 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1852 Buf->BufUsed = AfternChars;
1853 Buf->buf[Buf->BufUsed] = '\0';
1858 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1859 * buf - the string to modify
1860 * len - length of the string.
1862 void StrBufTrim(StrBuf *Buf)
1865 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1867 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1870 if (delta > 0) StrBufCutLeft(Buf, delta);
1872 if (Buf->BufUsed == 0) return;
1873 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1876 Buf->buf[Buf->BufUsed] = '\0';
1880 void StrBufUpCase(StrBuf *Buf)
1885 pche = pch + Buf->BufUsed;
1886 while (pch < pche) {
1887 *pch = toupper(*pch);
1893 void StrBufLowerCase(StrBuf *Buf)
1898 pche = pch + Buf->BufUsed;
1899 while (pch < pche) {
1900 *pch = tolower(*pch);
1907 * \brief unhide special chars hidden to the HTML escaper
1908 * \param target buffer to put the unescaped string in
1909 * \param source buffer to unescape
1911 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1917 FlushStrBuf(target);
1919 if (source == NULL ||target == NULL)
1924 len = source->BufUsed;
1925 for (a = 0; a < len; ++a) {
1926 if (target->BufUsed >= target->BufSize)
1927 IncreaseBuf(target, 1, -1);
1929 if (source->buf[a] == '=') {
1930 hex[0] = source->buf[a + 1];
1931 hex[1] = source->buf[a + 2];
1934 sscanf(hex, "%02x", &b);
1935 target->buf[target->BufUsed] = b;
1936 target->buf[++target->BufUsed] = 0;
1940 target->buf[target->BufUsed] = source->buf[a];
1941 target->buf[++target->BufUsed] = 0;
1948 * \brief hide special chars from the HTML escapers and friends
1949 * \param target buffer to put the escaped string in
1950 * \param source buffer to escape
1952 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1957 FlushStrBuf(target);
1959 if (source == NULL ||target == NULL)
1964 len = source->BufUsed;
1965 for (i=0; i<len; ++i) {
1966 if (target->BufUsed + 4 >= target->BufSize)
1967 IncreaseBuf(target, 1, -1);
1968 if ( (isalnum(source->buf[i])) ||
1969 (source->buf[i]=='-') ||
1970 (source->buf[i]=='_') ) {
1971 target->buf[target->BufUsed++] = source->buf[i];
1974 sprintf(&target->buf[target->BufUsed],
1976 (0xFF &source->buf[i]));
1977 target->BufUsed += 3;
1980 target->buf[target->BufUsed + 1] = '\0';
1984 * \brief uses the same calling syntax as compress2(), but it
1985 * creates a stream compatible with HTTP "Content-encoding: gzip"
1988 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1989 #define OS_CODE 0x03 /*< unix */
1990 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1991 size_t * destLen, /*< length of the compresed data */
1992 const Bytef * source, /*< source to encode */
1993 uLong sourceLen, /*< length of source to encode */
1994 int level) /*< compression level */
1996 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1998 /* write gzip header */
1999 snprintf((char *) dest, *destLen,
2000 "%c%c%c%c%c%c%c%c%c%c",
2001 gz_magic[0], gz_magic[1], Z_DEFLATED,
2002 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2005 /* normal deflate */
2008 stream.next_in = (Bytef *) source;
2009 stream.avail_in = (uInt) sourceLen;
2010 stream.next_out = dest + 10L; // after header
2011 stream.avail_out = (uInt) * destLen;
2012 if ((uLong) stream.avail_out != *destLen)
2015 stream.zalloc = (alloc_func) 0;
2016 stream.zfree = (free_func) 0;
2017 stream.opaque = (voidpf) 0;
2019 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2020 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2024 err = deflate(&stream, Z_FINISH);
2025 if (err != Z_STREAM_END) {
2026 deflateEnd(&stream);
2027 return err == Z_OK ? Z_BUF_ERROR : err;
2029 *destLen = stream.total_out + 10L;
2031 /* write CRC and Length */
2032 uLong crc = crc32(0L, source, sourceLen);
2034 for (n = 0; n < 4; ++n, ++*destLen) {
2035 dest[*destLen] = (int) (crc & 0xff);
2038 uLong len = stream.total_in;
2039 for (n = 0; n < 4; ++n, ++*destLen) {
2040 dest[*destLen] = (int) (len & 0xff);
2043 err = deflateEnd(&stream);
2050 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2052 int CompressBuffer(StrBuf *Buf)
2055 char *compressed_data = NULL;
2056 size_t compressed_len, bufsize;
2059 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
2060 compressed_data = malloc(compressed_len);
2062 /* Flush some space after the used payload so valgrind shuts up... */
2063 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2064 Buf->buf[Buf->BufUsed + i++] = '\0';
2065 if (compress_gzip((Bytef *) compressed_data,
2068 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2071 Buf->buf = compressed_data;
2072 Buf->BufUsed = compressed_len;
2073 Buf->BufSize = bufsize;
2074 /* Flush some space after the used payload so valgrind shuts up... */
2076 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2077 Buf->buf[Buf->BufUsed + i++] = '\0';
2080 free(compressed_data);
2082 #endif /* HAVE_ZLIB */
2087 * \brief decode a buffer from base 64 encoding; destroys original
2088 * \param Buf Buffor to transform
2090 int StrBufDecodeBase64(StrBuf *Buf)
2094 if (Buf == NULL) return -1;
2096 xferbuf = (char*) malloc(Buf->BufSize);
2097 siz = CtdlDecodeBase64(xferbuf,
2107 * \brief decode a buffer from base 64 encoding; destroys original
2108 * \param Buf Buffor to transform
2110 int StrBufDecodeHex(StrBuf *Buf)
2113 char *pch, *pche, *pchi;
2115 if (Buf == NULL) return -1;
2117 pch = pchi = Buf->buf;
2118 pche = pch + Buf->BufUsed;
2120 while (pchi < pche){
2121 ch = decode_hex(pchi);
2128 Buf->BufUsed = pch - Buf->buf;
2129 return Buf->BufUsed;
2133 * \brief replace all chars >0x20 && < 0x7F with Mute
2134 * \param Mute char to put over invalid chars
2135 * \param Buf Buffor to transform
2137 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2141 if (Buf == NULL) return -1;
2142 pch = (unsigned char *)Buf->buf;
2143 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2144 if ((*pch < 0x20) || (*pch > 0x7F))
2148 return Buf->BufUsed;
2153 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2154 * \param Buf Buffer to translate
2155 * \param StripBlanks Reduce several blanks to one?
2157 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2163 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2164 Buf->buf[Buf->BufUsed - 1] = '\0';
2169 while (a < Buf->BufUsed) {
2170 if (Buf->buf[a] == '+')
2172 else if (Buf->buf[a] == '%') {
2173 /* don't let % chars through, rather truncate the input. */
2174 if (a + 2 > Buf->BufUsed) {
2179 hex[0] = Buf->buf[a + 1];
2180 hex[1] = Buf->buf[a + 2];
2183 sscanf(hex, "%02x", &b);
2184 Buf->buf[a] = (char) b;
2185 len = Buf->BufUsed - a - 2;
2187 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2199 * \brief RFC2047-encode a header field if necessary.
2200 * If no non-ASCII characters are found, the string
2201 * will be copied verbatim without encoding.
2203 * \param target Target buffer.
2204 * \param source Source string to be encoded.
2205 * \returns encoded length; -1 if non success.
2207 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2209 const char headerStr[] = "=?UTF-8?Q?";
2210 int need_to_encode = 0;
2214 if ((source == NULL) ||
2218 while ((i < source->BufUsed) &&
2219 (!IsEmptyStr (&source->buf[i])) &&
2220 (need_to_encode == 0)) {
2221 if (((unsigned char) source->buf[i] < 32) ||
2222 ((unsigned char) source->buf[i] > 126)) {
2228 if (!need_to_encode) {
2229 if (*target == NULL) {
2230 *target = NewStrBufPlain(source->buf, source->BufUsed);
2233 FlushStrBuf(*target);
2234 StrBufAppendBuf(*target, source, 0);
2236 return (*target)->BufUsed;
2238 if (*target == NULL)
2239 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2240 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2241 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2242 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2243 (*target)->BufUsed = sizeof(headerStr) - 1;
2244 for (i=0; (i < source->BufUsed); ++i) {
2245 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2246 IncreaseBuf(*target, 1, 0);
2247 ch = (unsigned char) source->buf[i];
2248 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2249 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2250 (*target)->BufUsed += 3;
2253 (*target)->buf[(*target)->BufUsed] = ch;
2254 (*target)->BufUsed++;
2258 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2259 IncreaseBuf(*target, 1, 0);
2261 (*target)->buf[(*target)->BufUsed++] = '?';
2262 (*target)->buf[(*target)->BufUsed++] = '=';
2263 (*target)->buf[(*target)->BufUsed] = '\0';
2264 return (*target)->BufUsed;;
2268 * \brief replaces all occurances of 'search' by 'replace'
2269 * \param buf Buffer to modify
2270 * \param search character to search
2271 * \param relpace character to replace search by
2273 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2278 for (i=0; i<buf->BufUsed; i++)
2279 if (buf->buf[i] == search)
2280 buf->buf[i] = replace;
2287 * Wrapper around iconv_open()
2288 * Our version adds aliases for non-standard Microsoft charsets
2289 * such as 'MS950', aliasing them to names like 'CP950'
2291 * tocode Target encoding
2292 * fromcode Source encoding
2294 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2297 iconv_t ic = (iconv_t)(-1) ;
2298 ic = iconv_open(tocode, fromcode);
2299 if (ic == (iconv_t)(-1) ) {
2300 char alias_fromcode[64];
2301 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2302 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2303 alias_fromcode[0] = 'C';
2304 alias_fromcode[1] = 'P';
2305 ic = iconv_open(tocode, alias_fromcode);
2308 *(iconv_t *)pic = ic;
2314 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2317 /* Find the next ?Q? */
2318 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2321 end = strchr(bptr + 2, '?');
2326 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2327 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2328 (*(end + 2) == '?')) {
2329 /* skip on to the end of the cluster, the next ?= */
2330 end = strstr(end + 3, "?=");
2333 /* sort of half valid encoding, try to find an end. */
2334 end = strstr(bptr, "?=");
2339 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2344 char *ibuf; /**< Buffer of characters to be converted */
2345 char *obuf; /**< Buffer for converted characters */
2346 size_t ibuflen; /**< Length of input buffer */
2347 size_t obuflen; /**< Length of output buffer */
2350 if (ConvertBuf->BufUsed >= TmpBuf->BufSize)
2351 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
2353 ic = *(iconv_t*)pic;
2354 ibuf = ConvertBuf->buf;
2355 ibuflen = ConvertBuf->BufUsed;
2357 obuflen = TmpBuf->BufSize;
2359 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2361 /* little card game: wheres the red lady? */
2362 ibuf = ConvertBuf->buf;
2363 BufSize = ConvertBuf->BufSize;
2365 ConvertBuf->buf = TmpBuf->buf;
2366 ConvertBuf->BufSize = TmpBuf->BufSize;
2367 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
2368 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
2371 TmpBuf->BufSize = BufSize;
2372 TmpBuf->BufUsed = 0;
2373 TmpBuf->buf[0] = '\0';
2380 inline static void DecodeSegment(StrBuf *Target,
2381 const StrBuf *DecodeMe,
2385 StrBuf *ConvertBuf2,
2386 StrBuf *FoundCharset)
2392 iconv_t ic = (iconv_t)(-1);
2394 /* Now we handle foreign character sets properly encoded
2395 * in RFC2047 format.
2397 StaticBuf.buf = SegmentStart;
2398 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2399 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2400 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2401 if (FoundCharset != NULL) {
2402 FlushStrBuf(FoundCharset);
2403 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2405 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2406 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2408 *encoding = toupper(*encoding);
2409 if (*encoding == 'B') { /**< base64 */
2410 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2412 ConvertBuf->BufUsed);
2414 else if (*encoding == 'Q') { /**< quoted-printable */
2418 while (pos < ConvertBuf->BufUsed)
2420 if (ConvertBuf->buf[pos] == '_')
2421 ConvertBuf->buf[pos] = ' ';
2425 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2428 ConvertBuf->BufUsed);
2431 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2434 ctdl_iconv_open("UTF-8", charset, &ic);
2435 if (ic != (iconv_t)(-1) ) {
2437 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2438 StrBufAppendBuf(Target, ConvertBuf2, 0);
2443 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2448 * Handle subjects with RFC2047 encoding such as:
2449 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2451 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2453 StrBuf *ConvertBuf, *ConvertBuf2;
2454 char *start, *end, *next, *nextend, *ptr = NULL;
2456 iconv_t ic = (iconv_t)(-1) ;
2461 int illegal_non_rfc2047_encoding = 0;
2463 /* Sometimes, badly formed messages contain strings which were simply
2464 * written out directly in some foreign character set instead of
2465 * using RFC2047 encoding. This is illegal but we will attempt to
2466 * handle it anyway by converting from a user-specified default
2467 * charset to UTF-8 if we see any nonprintable characters.
2470 len = StrLength(DecodeMe);
2471 for (i=0; i<DecodeMe->BufUsed; ++i) {
2472 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2473 illegal_non_rfc2047_encoding = 1;
2478 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2479 if ((illegal_non_rfc2047_encoding) &&
2480 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2481 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2484 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2485 if (ic != (iconv_t)(-1) ) {
2486 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2492 /* pre evaluate the first pair */
2493 nextend = end = NULL;
2494 len = StrLength(DecodeMe);
2495 start = strstr(DecodeMe->buf, "=?");
2496 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2498 end = FindNextEnd (DecodeMe, start);
2500 StrBufAppendBuf(Target, DecodeMe, 0);
2501 FreeStrBuf(&ConvertBuf);
2505 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2507 if (start != DecodeMe->buf)
2508 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
2510 * Since spammers will go to all sorts of absurd lengths to get their
2511 * messages through, there are LOTS of corrupt headers out there.
2512 * So, prevent a really badly formed RFC2047 header from throwing
2513 * this function into an infinite loop.
2515 while ((start != NULL) &&
2522 DecodeSegment(Target,
2530 next = strstr(end, "=?");
2532 if ((next != NULL) &&
2534 nextend = FindNextEnd(DecodeMe, next);
2535 if (nextend == NULL)
2538 /* did we find two partitions */
2539 if ((next != NULL) &&
2543 while ((ptr < next) &&
2549 /* did we find a gab just filled with blanks? */
2554 len - (next - start));
2556 /* now terminate the gab at the end */
2557 delta = (next - end) - 2; ////TODO: const!
2558 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2559 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2561 /* move next to its new location. */
2566 /* our next-pair is our new first pair now. */
2572 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2573 if ((end != NULL) && (end < nextend)) {
2575 while ( (ptr < nextend) &&
2582 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2584 FreeStrBuf(&ConvertBuf);
2585 FreeStrBuf(&ConvertBuf2);
2590 long StrBuf_Utf8StrLen(StrBuf *Buf)
2592 return Ctdl_Utf8StrLen(Buf->buf);
2595 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2599 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
2600 if (CutAt != NULL) {
2601 Buf->BufUsed = CutAt - Buf->buf;
2602 Buf->buf[Buf->BufUsed] = '\0';
2604 return Buf->BufUsed;
2609 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2611 const char *aptr, *ptr, *eptr;
2618 ptr = aptr = Buf->buf;
2622 optr = LineBuf->buf;
2623 eptr = Buf->buf + Buf->BufUsed;
2624 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2626 while ((*ptr != '\n') &&
2633 LineBuf->BufUsed = optr - LineBuf->buf;
2634 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2635 optr = LineBuf->buf + LineBuf->BufUsed;
2636 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2639 LineBuf->BufUsed = optr - LineBuf->buf;
2648 return Buf->BufUsed - (ptr - Buf->buf);