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;
30 const char *StrBufNOTNULL = ((char*) NULL) - 1;
33 * Private Structure for the Stringbuffer
36 char *buf; /**< the pointer to the dynamic buffer */
37 long BufSize; /**< how many spcae do we optain */
38 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
39 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
43 char bt_lastinc [SIZ];
49 static void StrBufBacktrace(StrBuf *Buf, int which)
53 void *stack_frames[50];
58 pstart = pch = Buf->bt;
60 pstart = pch = Buf->bt_lastinc;
61 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
62 strings = backtrace_symbols(stack_frames, size);
63 for (i = 0; i < size; i++) {
65 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
67 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
78 * \Brief Cast operator to Plain String
79 * Note: if the buffer is altered by StrBuf operations, this pointer may become
80 * invalid. So don't lean on it after altering the buffer!
81 * Since this operation is considered cheap, rather call it often than risking
82 * your pointer to become invalid!
83 * \param Str the string we want to get the c-string representation for
84 * \returns the Pointer to the Content. Don't mess with it!
86 inline const char *ChrPtr(const StrBuf *Str)
94 * \brief since we know strlen()'s result, provide it here.
95 * \param Str the string to return the length to
96 * \returns contentlength of the buffer
98 inline int StrLength(const StrBuf *Str)
100 return (Str != NULL) ? Str->BufUsed : 0;
104 * \brief local utility function to resize the buffer
105 * \param Buf the buffer whichs storage we should increase
106 * \param KeepOriginal should we copy the original buffer or just start over with a new one
107 * \param DestSize what should fit in after?
109 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
112 size_t NewSize = Buf->BufSize * 2;
118 while (NewSize <= DestSize)
121 NewBuf= (char*) malloc(NewSize);
125 if (KeepOriginal && (Buf->BufUsed > 0))
127 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
136 Buf->BufSize = NewSize;
140 StrBufBacktrace(Buf, 1);
147 * \brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
148 * \param Buf Buffer to shrink (has to be empty)
149 * \param ThreshHold if the buffer is bigger then this, its readjusted
150 * \param NewSize if we Shrink it, how big are we going to be afterwards?
152 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
154 if (Buf->BufUsed > ThreshHold) {
156 Buf->buf = (char*) malloc(NewSize);
158 Buf->BufSize = NewSize;
163 * \brief shrink long term buffers to their real size so they don't waste memory
164 * \param Buf buffer to shrink
165 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
166 * \returns physical size of the buffer
168 long StrBufShrinkToFit(StrBuf *Buf, int Force)
171 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
173 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
174 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
175 Buf->BufSize = Buf->BufUsed + 1;
183 * Allocate a new buffer with default buffer size
184 * \returns the new stringbuffer
186 StrBuf* NewStrBuf(void)
190 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
191 NewBuf->buf = (char*) malloc(BaseStrBufSize);
192 NewBuf->buf[0] = '\0';
193 NewBuf->BufSize = BaseStrBufSize;
195 NewBuf->ConstBuf = 0;
197 NewBuf->nIncreases = 0;
198 NewBuf->bt[0] = '\0';
199 NewBuf->bt_lastinc[0] = '\0';
201 StrBufBacktrace(NewBuf, 0);
208 * \brief Copy Constructor; returns a duplicate of CopyMe
209 * \params CopyMe Buffer to faxmilate
210 * \returns the new stringbuffer
212 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
219 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
220 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
221 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
222 NewBuf->BufUsed = CopyMe->BufUsed;
223 NewBuf->BufSize = CopyMe->BufSize;
224 NewBuf->ConstBuf = 0;
226 NewBuf->nIncreases = 0;
227 NewBuf->bt[0] = '\0';
228 NewBuf->bt_lastinc[0] = '\0';
230 StrBufBacktrace(NewBuf, 0);
237 * \brief create a new Buffer using an existing c-string
238 * this function should also be used if you want to pre-suggest
239 * the buffer size to allocate in conjunction with ptr == NULL
240 * \param ptr the c-string to copy; may be NULL to create a blank instance
241 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
242 * \returns the new stringbuffer
244 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
247 size_t Siz = BaseStrBufSize;
250 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
252 CopySize = strlen((ptr != NULL)?ptr:"");
256 while (Siz <= CopySize)
259 NewBuf->buf = (char*) malloc(Siz);
260 NewBuf->BufSize = Siz;
262 memcpy(NewBuf->buf, ptr, CopySize);
263 NewBuf->buf[CopySize] = '\0';
264 NewBuf->BufUsed = CopySize;
267 NewBuf->buf[0] = '\0';
270 NewBuf->ConstBuf = 0;
272 NewBuf->nIncreases = 0;
273 NewBuf->bt[0] = '\0';
274 NewBuf->bt_lastinc[0] = '\0';
276 StrBufBacktrace(NewBuf, 0);
283 * \brief Set an existing buffer from a c-string
284 * \param ptr c-string to put into
285 * \param nChars set to -1 if we should work 0-terminated
286 * \returns the new length of the string
288 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
290 size_t Siz = Buf->BufSize;
294 CopySize = strlen(ptr);
298 while (Siz <= CopySize)
301 if (Siz != Buf->BufSize)
302 IncreaseBuf(Buf, 0, Siz);
303 memcpy(Buf->buf, ptr, CopySize);
304 Buf->buf[CopySize] = '\0';
305 Buf->BufUsed = CopySize;
312 * \brief use strbuf as wrapper for a string constant for easy handling
313 * \param StringConstant a string to wrap
314 * \param SizeOfConstant should be sizeof(StringConstant)-1
316 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
320 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
321 NewBuf->buf = (char*) StringConstant;
322 NewBuf->BufSize = SizeOfStrConstant;
323 NewBuf->BufUsed = SizeOfStrConstant;
324 NewBuf->ConstBuf = 1;
326 NewBuf->nIncreases = 0;
327 NewBuf->bt[0] = '\0';
328 NewBuf->bt_lastinc[0] = '\0';
335 * \brief flush the content of a Buf; keep its struct
336 * \param buf Buffer to flush
338 int FlushStrBuf(StrBuf *buf)
350 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
351 * \param buf Buffer to wipe
353 int FLUSHStrBuf(StrBuf *buf)
359 if (buf->BufUsed > 0) {
360 memset(buf->buf, 0, buf->BufUsed);
367 int hFreeDbglog = -1;
370 * \brief Release a Buffer
371 * Its a double pointer, so it can NULL your pointer
372 * so fancy SIG11 appear instead of random results
373 * \param FreeMe Pointer Pointer to the buffer to free
375 void FreeStrBuf (StrBuf **FreeMe)
380 if (hFreeDbglog == -1){
381 pid_t pid = getpid();
383 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
384 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
386 if ((*FreeMe)->nIncreases > 0)
390 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
391 (*FreeMe)->nIncreases,
395 (*FreeMe)->bt_lastinc);
396 n = write(hFreeDbglog, buf, n);
402 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
405 n = write(hFreeDbglog, buf, n);
408 if (!(*FreeMe)->ConstBuf)
409 free((*FreeMe)->buf);
415 * \brief Release the buffer
416 * If you want put your StrBuf into a Hash, use this as Destructor.
417 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
419 void HFreeStrBuf (void *VFreeMe)
421 StrBuf *FreeMe = (StrBuf*)VFreeMe;
425 if (hFreeDbglog == -1){
426 pid_t pid = getpid();
428 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
429 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
431 if (FreeMe->nIncreases > 0)
435 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
441 write(hFreeDbglog, buf, n);
447 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
453 if (!FreeMe->ConstBuf)
459 * \brief Wrapper around atol
461 long StrTol(const StrBuf *Buf)
466 return atol(Buf->buf);
472 * \brief Wrapper around atoi
474 int StrToi(const StrBuf *Buf)
478 if (Buf->BufUsed > 0)
479 return atoi(Buf->buf);
485 * \brief Checks to see if the string is a pure number
487 int StrBufIsNumber(const StrBuf *Buf) {
492 strtoll(Buf->buf, &pEnd, 10);
493 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
499 * \brief modifies a Single char of the Buf
500 * You can point to it via char* or a zero-based integer
501 * \param ptr char* to zero; use NULL if unused
502 * \param nThChar zero based pointer into the string; use -1 if unused
503 * \param PeekValue The Character to place into the position
505 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
510 nThChar = ptr - Buf->buf;
511 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
513 Buf->buf[nThChar] = PeekValue;
518 * \brief Append a StringBuffer to the buffer
519 * \param Buf Buffer to modify
520 * \param AppendBuf Buffer to copy at the end of our buffer
521 * \param Offset Should we start copying from an offset?
523 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
525 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
528 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
531 AppendBuf->BufUsed + Buf->BufUsed);
533 memcpy(Buf->buf + Buf->BufUsed,
534 AppendBuf->buf + Offset,
535 AppendBuf->BufUsed - Offset);
536 Buf->BufUsed += AppendBuf->BufUsed - Offset;
537 Buf->buf[Buf->BufUsed] = '\0';
542 * \brief Append a C-String to the buffer
543 * \param Buf Buffer to modify
544 * \param AppendBuf Buffer to copy at the end of our buffer
545 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
546 * \param Offset Should we start copying from an offset?
548 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
551 long BufSizeRequired;
553 if ((AppendBuf == NULL) || (Buf == NULL))
557 aps = strlen(AppendBuf + Offset);
559 aps = AppendSize - Offset;
561 BufSizeRequired = Buf->BufUsed + aps + 1;
562 if (Buf->BufSize <= BufSizeRequired)
563 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
565 memcpy(Buf->buf + Buf->BufUsed,
569 Buf->buf[Buf->BufUsed] = '\0';
573 * \brief Callback for cURL to append the webserver reply to a buffer
574 * params pre-defined by the cURL API; see man 3 curl for mre info
576 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
585 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
591 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
592 * \param outbuf the output buffer
593 * \param oblen the size of outbuf to sanitize
594 * \param strbuf the input buffer
596 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
598 const char *pch, *pche;
601 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
602 int eclen = sizeof(ec) -1;
604 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
606 if (PlainIn != NULL) {
607 len = strlen(PlainIn);
613 pche = pch + In->BufUsed;
620 pt = OutBuf->buf + OutBuf->BufUsed;
621 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
625 IncreaseBuf(OutBuf, 1, -1);
626 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
627 pt = OutBuf->buf + OutBuf->BufUsed;
631 for (b = 0; b < eclen; ++b) {
638 sprintf(pt,"%%%02X", *pch);
640 OutBuf->BufUsed += 3;
652 * \brief Append a string, escaping characters which have meaning in HTML.
654 * \param Target target buffer
655 * \param Source source buffer; set to NULL if you just have a C-String
656 * \param PlainIn Plain-C string to append; set to NULL if unused
657 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
658 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
659 * if set to 2, linebreaks are replaced by <br/>
661 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
663 const char *aptr, *eiptr;
667 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
670 if (PlainIn != NULL) {
672 len = strlen(PlainIn);
677 eiptr = aptr + Source->BufUsed;
678 len = Source->BufUsed;
684 bptr = Target->buf + Target->BufUsed;
685 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
687 while (aptr < eiptr){
689 IncreaseBuf(Target, 1, -1);
690 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
691 bptr = Target->buf + Target->BufUsed;
694 memcpy(bptr, "<", 4);
696 Target->BufUsed += 4;
698 else if (*aptr == '>') {
699 memcpy(bptr, ">", 4);
701 Target->BufUsed += 4;
703 else if (*aptr == '&') {
704 memcpy(bptr, "&", 5);
706 Target->BufUsed += 5;
708 else if (*aptr == '"') {
709 memcpy(bptr, """, 6);
711 Target->BufUsed += 6;
713 else if (*aptr == '\'') {
714 memcpy(bptr, "'", 5);
716 Target->BufUsed += 5;
718 else if (*aptr == LB) {
723 else if (*aptr == RB) {
728 else if (*aptr == QU) {
733 else if ((*aptr == 32) && (nbsp == 1)) {
734 memcpy(bptr, " ", 6);
736 Target->BufUsed += 6;
738 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
739 *bptr='\0'; /* nothing */
741 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
742 memcpy(bptr, "<br/>", 11);
744 Target->BufUsed += 11;
748 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
749 *bptr='\0'; /* nothing */
759 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
761 return Target->BufUsed;
765 * \brief Append a string, escaping characters which have meaning in HTML.
766 * Converts linebreaks into blanks; escapes single quotes
767 * \param Target target buffer
768 * \param Source source buffer; set to NULL if you just have a C-String
769 * \param PlainIn Plain-C string to append; set to NULL if unused
771 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
773 const char *aptr, *eiptr;
777 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
780 if (PlainIn != NULL) {
782 len = strlen(PlainIn);
787 eiptr = aptr + Source->BufUsed;
788 len = Source->BufUsed;
794 eptr = Target->buf + Target->BufSize - 8;
795 tptr = Target->buf + Target->BufUsed;
797 while (aptr < eiptr){
799 IncreaseBuf(Target, 1, -1);
800 eptr = Target->buf + Target->BufSize - 8;
801 tptr = Target->buf + Target->BufUsed;
808 else if (*aptr == '\r') {
812 else if (*aptr == '\'') {
818 Target->BufUsed += 5;
831 * \brief Append a string, escaping characters which have meaning in ICAL.
833 * \param Target target buffer
834 * \param Source source buffer; set to NULL if you just have a C-String
835 * \param PlainIn Plain-C string to append; set to NULL if unused
837 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
839 const char *aptr, *eiptr;
843 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
846 if (PlainIn != NULL) {
848 len = strlen(PlainIn);
853 eiptr = aptr + Source->BufUsed;
854 len = Source->BufUsed;
860 eptr = Target->buf + Target->BufSize - 8;
861 tptr = Target->buf + Target->BufUsed;
863 while (aptr < eiptr){
864 if(tptr + 3 >= eptr) {
865 IncreaseBuf(Target, 1, -1);
866 eptr = Target->buf + Target->BufSize - 8;
867 tptr = Target->buf + Target->BufUsed;
877 else if (*aptr == '\r') {
884 else if (*aptr == ',') {
900 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
902 * \param Target target buffer
903 * \param Source source buffer; set to NULL if you just have a C-String
904 * \param PlainIn Plain-C string to append; set to NULL if unused
906 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
908 const char *aptr, *eiptr;
912 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
915 if (PlainIn != NULL) {
917 len = strlen(PlainIn);
922 eiptr = aptr + Source->BufUsed;
923 len = Source->BufUsed;
929 bptr = Target->buf + Target->BufUsed;
930 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
932 while (aptr < eiptr){
934 IncreaseBuf(Target, 1, -1);
935 eptr = Target->buf + Target->BufSize - 3;
936 bptr = Target->buf + Target->BufUsed;
943 Target->BufUsed += 2;
944 } else if (*aptr == '\\') {
949 Target->BufUsed += 2;
959 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
961 return Target->BufUsed;
965 * \brief extracts a substring from Source into dest
966 * \param dest buffer to place substring into
967 * \param Source string to copy substring from
968 * \param Offset chars to skip from start
969 * \param nChars number of chars to copy
970 * \returns the number of chars copied; may be different from nChars due to the size of Source
972 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
975 if (Offset > Source->BufUsed)
980 if (Offset + nChars < Source->BufUsed)
982 if (nChars >= dest->BufSize)
983 IncreaseBuf(dest, 0, nChars + 1);
984 memcpy(dest->buf, Source->buf + Offset, nChars);
985 dest->BufUsed = nChars;
986 dest->buf[dest->BufUsed] = '\0';
989 NCharsRemain = Source->BufUsed - Offset;
990 if (NCharsRemain >= dest->BufSize)
991 IncreaseBuf(dest, 0, NCharsRemain + 1);
992 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
993 dest->BufUsed = NCharsRemain;
994 dest->buf[dest->BufUsed] = '\0';
999 * \brief sprintf like function appending the formated string to the buffer
1000 * vsnprintf version to wrap into own calls
1001 * \param Buf Buffer to extend by format and params
1002 * \param format printf alike format to add
1003 * \param ap va_list containing the items for format
1005 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1008 size_t BufSize = Buf->BufSize;
1009 size_t nWritten = Buf->BufSize + 1;
1010 size_t Offset = Buf->BufUsed;
1011 size_t newused = Offset + nWritten;
1013 while (newused >= BufSize) {
1015 nWritten = vsnprintf(Buf->buf + Offset,
1016 Buf->BufSize - Offset,
1019 newused = Offset + nWritten;
1020 if (newused >= Buf->BufSize) {
1021 IncreaseBuf(Buf, 1, newused);
1022 newused = Buf->BufSize + 1;
1025 Buf->BufUsed = Offset + nWritten;
1026 BufSize = Buf->BufSize;
1033 * \brief sprintf like function appending the formated string to the buffer
1034 * \param Buf Buffer to extend by format and params
1035 * \param format printf alike format to add
1036 * \param ap va_list containing the items for format
1038 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1040 size_t BufSize = Buf->BufSize;
1041 size_t nWritten = Buf->BufSize + 1;
1042 size_t Offset = Buf->BufUsed;
1043 size_t newused = Offset + nWritten;
1046 while (newused >= BufSize) {
1047 va_start(arg_ptr, format);
1048 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1049 Buf->BufSize - Buf->BufUsed,
1052 newused = Buf->BufUsed + nWritten;
1053 if (newused >= Buf->BufSize) {
1054 IncreaseBuf(Buf, 1, newused);
1055 newused = Buf->BufSize + 1;
1058 Buf->BufUsed += nWritten;
1059 BufSize = Buf->BufSize;
1066 * \brief sprintf like function putting the formated string into the buffer
1067 * \param Buf Buffer to extend by format and params
1068 * \param format printf alike format to add
1069 * \param ap va_list containing the items for format
1071 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1073 size_t nWritten = Buf->BufSize + 1;
1076 while (nWritten >= Buf->BufSize) {
1077 va_start(arg_ptr, format);
1078 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1080 if (nWritten >= Buf->BufSize) {
1081 IncreaseBuf(Buf, 0, 0);
1082 nWritten = Buf->BufSize + 1;
1085 Buf->BufUsed = nWritten ;
1091 * \brief Counts the numbmer of tokens in a buffer
1092 * \param Source String to count tokens in
1093 * \param tok Tokenizer char to count
1094 * \returns numbers of tokenizer chars found
1096 int StrBufNum_tokens(const StrBuf *source, char tok)
1100 return num_tokens(source->buf, tok);
1104 * remove_token() - a tokenizer that kills, maims, and destroys
1107 * \brief a string tokenizer
1108 * \param Source StringBuffer to read into
1109 * \param parmnum n'th parameter to remove
1110 * \param separator tokenizer param
1111 * \returns -1 if not found, else length of token.
1113 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1116 char *d, *s; /* dest, source */
1119 /* Find desired parameter */
1121 while (count < parmnum) {
1122 /* End of string, bail! */
1127 if (*d == separator) {
1132 if (!d) return 0; /* Parameter not found */
1134 /* Find next parameter */
1136 while (*s && *s != separator) {
1139 if (*s == separator)
1143 /* Hack and slash */
1145 memmove(d, s, Source->BufUsed - (s - Source->buf));
1146 Source->BufUsed += ReducedBy;
1148 else if (d == Source->buf) {
1150 Source->BufUsed = 0;
1154 Source->BufUsed += ReducedBy;
1167 * \brief a string tokenizer
1168 * \param dest Destination StringBuffer
1169 * \param Source StringBuffer to read into
1170 * \param parmnum n'th parameter to extract
1171 * \param separator tokenizer param
1172 * \returns -1 if not found, else length of token.
1174 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1176 const char *s, *e; //* source * /
1177 int len = 0; //* running total length of extracted string * /
1178 int current_token = 0; //* token currently being processed * /
1181 dest->buf[0] = '\0';
1187 if ((Source == NULL) || (Source->BufUsed ==0)) {
1191 e = s + Source->BufUsed;
1194 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1196 while ((s<e) && !IsEmptyStr(s)) {
1197 if (*s == separator) {
1200 if (len >= dest->BufSize) {
1201 dest->BufUsed = len;
1202 if (IncreaseBuf(dest, 1, -1) < 0) {
1207 if ( (current_token == parmnum) &&
1208 (*s != separator)) {
1209 dest->buf[len] = *s;
1212 else if (current_token > parmnum) {
1218 dest->buf[len] = '\0';
1219 dest->BufUsed = len;
1221 if (current_token < parmnum) {
1222 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1225 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1234 * \brief a string tokenizer to fetch an integer
1235 * \param dest Destination StringBuffer
1236 * \param parmnum n'th parameter to extract
1237 * \param separator tokenizer param
1238 * \returns 0 if not found, else integer representation of the token
1240 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1250 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1257 * \brief a string tokenizer to fetch a long integer
1258 * \param dest Destination StringBuffer
1259 * \param parmnum n'th parameter to extract
1260 * \param separator tokenizer param
1261 * \returns 0 if not found, else long integer representation of the token
1263 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1273 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1281 * \brief a string tokenizer to fetch an unsigned long
1282 * \param dest Destination StringBuffer
1283 * \param parmnum n'th parameter to extract
1284 * \param separator tokenizer param
1285 * \returns 0 if not found, else unsigned long representation of the token
1287 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1298 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1302 return (unsigned long) atol(pnum);
1311 * \briefa string tokenizer; Bounds checker
1312 * function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
1313 * \param Source our tokenbuffer
1314 * \param pStart the token iterator pointer to inspect
1315 * \returns whether the revolving pointer is inside of the search range
1317 int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
1319 if ((Source == NULL) ||
1320 (*pStart == StrBufNOTNULL) ||
1321 (Source->BufUsed == 0))
1325 if (*pStart == NULL)
1329 else if (*pStart > Source->buf + Source->BufUsed)
1333 else if (*pStart <= Source->buf)
1342 * \brief a string tokenizer
1343 * \param dest Destination StringBuffer
1344 * \param Source StringBuffer to read into
1345 * \param pStart pointer to the end of the last token. Feed with NULL on start.
1346 * \param separator tokenizer param
1347 * \returns -1 if not found, else length of token.
1349 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1351 const char *s; /* source */
1352 const char *EndBuffer; /* end stop of source buffer */
1353 int current_token = 0; /* token currently being processed */
1354 int len = 0; /* running total length of extracted string */
1356 if ((Source == NULL) ||
1357 (Source->BufUsed == 0) )
1359 *pStart = StrBufNOTNULL;
1363 EndBuffer = Source->buf + Source->BufUsed;
1367 dest->buf[0] = '\0';
1372 *pStart = EndBuffer + 1;
1376 if (*pStart == NULL)
1378 *pStart = Source->buf; /* we're starting to examine this buffer. */
1380 else if ((*pStart < Source->buf) ||
1381 (*pStart > EndBuffer ) )
1383 return -1; /* no more tokens to find. */
1387 /* start to find the next token */
1388 while ((s <= EndBuffer) &&
1389 (current_token == 0) )
1391 if (*s == separator)
1393 /* we found the next token */
1397 if (len >= dest->BufSize)
1399 /* our Dest-buffer isn't big enough, increase it. */
1400 dest->BufUsed = len;
1402 if (IncreaseBuf(dest, 1, -1) < 0) {
1403 /* WHUT? no more mem? bail out. */
1410 if ( (current_token == 0 ) && /* are we in our target token? */
1411 (!IsEmptyStr(s) ) &&
1412 (separator != *s) ) /* don't copy the token itself */
1414 dest->buf[len] = *s; /* Copy the payload */
1415 ++len; /* remember the bigger size. */
1421 /* did we reach the end? */
1422 if ((s > EndBuffer)) {
1423 EndBuffer = StrBufNOTNULL;
1424 *pStart = EndBuffer;
1427 *pStart = s; /* remember the position for the next run */
1430 /* sanitize our extracted token */
1431 dest->buf[len] = '\0';
1432 dest->BufUsed = len;
1439 * \brief a string tokenizer
1440 * \param dest Destination StringBuffer
1441 * \param Source StringBuffer to read into
1442 * \param pStart pointer to the end of the last token. Feed with NULL.
1443 * \param separator tokenizer param
1444 * \returns -1 if not found, else length of token.
1446 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1448 const char *s, *EndBuffer; //* source * /
1449 int len = 0; //* running total length of extracted string * /
1450 int current_token = 0; //* token currently being processed * /
1452 if ((Source == NULL) ||
1453 (Source->BufUsed ==0)) {
1457 return Source->BufUsed;
1459 if (*pStart == NULL)
1460 *pStart = Source->buf;
1462 EndBuffer = Source->buf + Source->BufUsed;
1464 if ((*pStart < Source->buf) ||
1465 (*pStart > EndBuffer)) {
1473 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1475 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1476 if (*s == separator) {
1479 if (current_token >= nTokens) {
1491 * \brief a string tokenizer to fetch an integer
1492 * \param dest Destination StringBuffer
1493 * \param parmnum n'th parameter to extract
1494 * \param separator tokenizer param
1495 * \returns 0 if not found, else integer representation of the token
1497 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1507 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1514 * \brief a string tokenizer to fetch a long integer
1515 * \param dest Destination StringBuffer
1516 * \param parmnum n'th parameter to extract
1517 * \param separator tokenizer param
1518 * \returns 0 if not found, else long integer representation of the token
1520 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1530 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1538 * \brief a string tokenizer to fetch an unsigned long
1539 * \param dest Destination StringBuffer
1540 * \param parmnum n'th parameter to extract
1541 * \param separator tokenizer param
1542 * \returns 0 if not found, else unsigned long representation of the token
1544 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1555 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1559 return (unsigned long) atol(pnum);
1568 * \brief Read a line from socket
1569 * flushes and closes the FD on error
1570 * \param buf the buffer to get the input to
1571 * \param fd pointer to the filedescriptor to read
1572 * \param append Append to an existing string or replace?
1573 * \param Error strerror() on error
1574 * \returns numbers of chars read
1576 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1578 int len, rlen, slen;
1583 slen = len = buf->BufUsed;
1585 rlen = read(*fd, &buf->buf[len], 1);
1587 *Error = strerror(errno);
1594 if (buf->buf[len] == '\n')
1596 if (buf->buf[len] != '\r')
1598 if (len >= buf->BufSize) {
1600 buf->buf[len+1] = '\0';
1601 IncreaseBuf(buf, 1, -1);
1605 buf->buf[len] = '\0';
1610 * \brief Read a line from socket
1611 * flushes and closes the FD on error
1612 * \param buf the buffer to get the input to
1613 * \param fd pointer to the filedescriptor to read
1614 * \param append Append to an existing string or replace?
1615 * \param Error strerror() on error
1616 * \returns numbers of chars read
1618 int StrBufTCP_read_buffered_line(StrBuf *Line,
1622 int selectresolution,
1626 int nSuccessLess = 0;
1632 if (buf->BufUsed > 0) {
1633 pch = strchr(buf->buf, '\n');
1636 len = pch - buf->buf;
1637 if (len > 0 && (*(pch - 1) == '\r') )
1639 StrBufSub(Line, buf, 0, len - rlen);
1640 StrBufCutLeft(buf, len + 1);
1645 if (buf->BufSize - buf->BufUsed < 10)
1646 IncreaseBuf(buf, 1, -1);
1648 fdflags = fcntl(*fd, F_GETFL);
1649 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1652 while ((nSuccessLess < timeout) && (pch == NULL)) {
1653 tv.tv_sec = selectresolution;
1658 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1659 *Error = strerror(errno);
1664 if (FD_ISSET(*fd, &rfds)) {
1666 &buf->buf[buf->BufUsed],
1667 buf->BufSize - buf->BufUsed - 1);
1669 *Error = strerror(errno);
1674 else if (rlen > 0) {
1676 buf->BufUsed += rlen;
1677 buf->buf[buf->BufUsed] = '\0';
1678 if (buf->BufUsed + 10 > buf->BufSize) {
1679 IncreaseBuf(buf, 1, -1);
1681 pch = strchr(buf->buf, '\n');
1689 len = pch - buf->buf;
1690 if (len > 0 && (*(pch - 1) == '\r') )
1692 StrBufSub(Line, buf, 0, len - rlen);
1693 StrBufCutLeft(buf, len + 1);
1700 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1701 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1702 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1704 * \brief Read a line from socket
1705 * flushes and closes the FD on error
1706 * \param buf the buffer to get the input to
1707 * \param Pos pointer to the current read position, should be NULL initialized!
1708 * \param fd pointer to the filedescriptor to read
1709 * \param append Append to an existing string or replace?
1710 * \param Error strerror() on error
1711 * \returns numbers of chars read
1713 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1718 int selectresolution,
1721 const char *pche = NULL;
1722 const char *pos = NULL;
1724 int nSuccessLess = 0;
1726 const char *pch = NULL;
1731 if ((IOBuf->BufUsed > 0) &&
1733 (pos < IOBuf->buf + IOBuf->BufUsed))
1735 pche = IOBuf->buf + IOBuf->BufUsed;
1737 while ((pch < pche) && (*pch != '\n'))
1739 if ((pch >= pche) || (*pch == '\0'))
1741 if ((pch != NULL) &&
1746 if (len > 0 && (*(pch - 1) == '\r') )
1748 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1758 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1762 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1763 IncreaseBuf(IOBuf, 1, -1);
1766 fdflags = fcntl(*fd, F_GETFL);
1767 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1768 *Error = ErrRBLF_WrongFDFlags;
1773 while ((nSuccessLess < timeout) && (pch == NULL)) {
1774 tv.tv_sec = selectresolution;
1779 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1780 *Error = strerror(errno);
1784 *Error = ErrRBLF_SelectFailed;
1787 if (FD_ISSET(*fd, &rfds) != 0) {
1789 &IOBuf->buf[IOBuf->BufUsed],
1790 IOBuf->BufSize - IOBuf->BufUsed - 1);
1792 *Error = strerror(errno);
1797 else if (rlen > 0) {
1799 IOBuf->BufUsed += rlen;
1800 IOBuf->buf[IOBuf->BufUsed] = '\0';
1801 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1802 IncreaseBuf(IOBuf, 1, -1);
1805 pche = IOBuf->buf + IOBuf->BufUsed;
1807 while ((pch < pche) && (*pch != '\n'))
1809 if ((pch >= pche) || (*pch == '\0'))
1820 if (len > 0 && (*(pch - 1) == '\r') )
1822 StrBufSub(Line, IOBuf, 0, len - rlen);
1823 *Pos = pos + len + 1;
1826 *Error = ErrRBLF_NotEnoughSentFromServer;
1832 * \brief Input binary data from socket
1833 * flushes and closes the FD on error
1834 * \param buf the buffer to get the input to
1835 * \param fd pointer to the filedescriptor to read
1836 * \param append Append to an existing string or replace?
1837 * \param nBytes the maximal number of bytes to read
1838 * \param Error strerror() on error
1839 * \returns numbers of chars read
1841 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1845 int len, rlen, slen;
1849 if ((Buf == NULL) || (*fd == -1))
1853 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1854 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1856 ptr = Buf->buf + Buf->BufUsed;
1858 slen = len = Buf->BufUsed;
1860 fdflags = fcntl(*fd, F_GETFL);
1862 while (nRead < nBytes) {
1863 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1866 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1867 *Error = strerror(errno);
1872 if ((rlen = read(*fd,
1874 nBytes - nRead)) == -1) {
1877 *Error = strerror(errno);
1882 Buf->BufUsed += rlen;
1884 Buf->buf[Buf->BufUsed] = '\0';
1888 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
1890 * \brief Input binary data from socket
1891 * flushes and closes the FD on error
1892 * \param buf the buffer to get the input to
1893 * \param fd pointer to the filedescriptor to read
1894 * \param append Append to an existing string or replace?
1895 * \param nBytes the maximal number of bytes to read
1896 * \param Error strerror() on error
1897 * \returns numbers of chars read
1899 int StrBufReadBLOBBuffered(StrBuf *Blob,
1920 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1924 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1925 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1930 len = pos - IOBuf->buf;
1931 rlen = IOBuf->BufUsed - len;
1934 if ((IOBuf->BufUsed > 0) &&
1936 (pos < IOBuf->buf + IOBuf->BufUsed))
1938 pche = IOBuf->buf + IOBuf->BufUsed;
1941 if (rlen < nBytes) {
1942 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1943 Blob->BufUsed += rlen;
1944 Blob->buf[Blob->BufUsed] = '\0';
1948 if (rlen >= nBytes) {
1949 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1950 Blob->BufUsed += nBytes;
1951 Blob->buf[Blob->BufUsed] = '\0';
1952 if (rlen == nBytes) {
1963 if (IOBuf->BufSize < nBytes - nRead)
1964 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1967 slen = len = Blob->BufUsed;
1969 fdflags = fcntl(*fd, F_GETFL);
1974 while (nRead < nBytes) {
1975 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1978 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1981 *Error = strerror(errno);
1992 *Error = strerror(errno);
1998 if ((check == NNN_TERM) &&
2000 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
2002 StrBufPlain(Blob, HKEY("\n000\n"));
2003 StrBufCutRight(Blob, 5);
2004 return Blob->BufUsed;
2006 if (nSelects > 10) {
2008 *Error = ErrRBB_too_many_selects;
2015 IOBuf->BufUsed += rlen;
2018 if (nRead > nBytes) {
2019 *Pos = IOBuf->buf + nBytes;
2021 Blob->buf[Blob->BufUsed] = '\0';
2022 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
2027 * \brief Cut nChars from the start of the string
2028 * \param Buf Buffer to modify
2029 * \param nChars how many chars should be skipped?
2031 void StrBufCutLeft(StrBuf *Buf, int nChars)
2033 if (nChars >= Buf->BufUsed) {
2037 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
2038 Buf->BufUsed -= nChars;
2039 Buf->buf[Buf->BufUsed] = '\0';
2043 * \brief Cut the trailing n Chars from the string
2044 * \param Buf Buffer to modify
2045 * \param nChars how many chars should be trunkated?
2047 void StrBufCutRight(StrBuf *Buf, int nChars)
2049 if (nChars >= Buf->BufUsed) {
2053 Buf->BufUsed -= nChars;
2054 Buf->buf[Buf->BufUsed] = '\0';
2058 * \brief Cut the string after n Chars
2059 * \param Buf Buffer to modify
2060 * \param AfternChars after how many chars should we trunkate the string?
2061 * \param At if non-null and points inside of our string, cut it there.
2063 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2066 AfternChars = At - Buf->buf;
2069 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2071 Buf->BufUsed = AfternChars;
2072 Buf->buf[Buf->BufUsed] = '\0';
2077 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2078 * buf - the string to modify
2079 * len - length of the string.
2081 void StrBufTrim(StrBuf *Buf)
2084 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2086 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2089 if (delta > 0) StrBufCutLeft(Buf, delta);
2091 if (Buf->BufUsed == 0) return;
2092 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2095 Buf->buf[Buf->BufUsed] = '\0';
2099 void StrBufUpCase(StrBuf *Buf)
2104 pche = pch + Buf->BufUsed;
2105 while (pch < pche) {
2106 *pch = toupper(*pch);
2112 void StrBufLowerCase(StrBuf *Buf)
2117 pche = pch + Buf->BufUsed;
2118 while (pch < pche) {
2119 *pch = tolower(*pch);
2125 * \Brief removes double slashes from pathnames
2126 * \param Dir directory string to filter
2127 * \param RemoveTrailingSlash allows / disallows trailing slashes
2129 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2135 while (!IsEmptyStr(a)) {
2147 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2152 Dir->BufUsed = b - Dir->buf;
2156 * \brief unhide special chars hidden to the HTML escaper
2157 * \param target buffer to put the unescaped string in
2158 * \param source buffer to unescape
2160 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2166 FlushStrBuf(target);
2168 if (source == NULL ||target == NULL)
2173 len = source->BufUsed;
2174 for (a = 0; a < len; ++a) {
2175 if (target->BufUsed >= target->BufSize)
2176 IncreaseBuf(target, 1, -1);
2178 if (source->buf[a] == '=') {
2179 hex[0] = source->buf[a + 1];
2180 hex[1] = source->buf[a + 2];
2183 sscanf(hex, "%02x", &b);
2184 target->buf[target->BufUsed] = b;
2185 target->buf[++target->BufUsed] = 0;
2189 target->buf[target->BufUsed] = source->buf[a];
2190 target->buf[++target->BufUsed] = 0;
2197 * \brief hide special chars from the HTML escapers and friends
2198 * \param target buffer to put the escaped string in
2199 * \param source buffer to escape
2201 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2206 FlushStrBuf(target);
2208 if (source == NULL ||target == NULL)
2213 len = source->BufUsed;
2214 for (i=0; i<len; ++i) {
2215 if (target->BufUsed + 4 >= target->BufSize)
2216 IncreaseBuf(target, 1, -1);
2217 if ( (isalnum(source->buf[i])) ||
2218 (source->buf[i]=='-') ||
2219 (source->buf[i]=='_') ) {
2220 target->buf[target->BufUsed++] = source->buf[i];
2223 sprintf(&target->buf[target->BufUsed],
2225 (0xFF &source->buf[i]));
2226 target->BufUsed += 3;
2229 target->buf[target->BufUsed + 1] = '\0';
2233 * \brief uses the same calling syntax as compress2(), but it
2234 * creates a stream compatible with HTTP "Content-encoding: gzip"
2237 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2238 #define OS_CODE 0x03 /*< unix */
2239 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2240 size_t * destLen, /*< length of the compresed data */
2241 const Bytef * source, /*< source to encode */
2242 uLong sourceLen, /*< length of source to encode */
2243 int level) /*< compression level */
2245 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2247 /* write gzip header */
2248 snprintf((char *) dest, *destLen,
2249 "%c%c%c%c%c%c%c%c%c%c",
2250 gz_magic[0], gz_magic[1], Z_DEFLATED,
2251 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2254 /* normal deflate */
2257 stream.next_in = (Bytef *) source;
2258 stream.avail_in = (uInt) sourceLen;
2259 stream.next_out = dest + 10L; // after header
2260 stream.avail_out = (uInt) * destLen;
2261 if ((uLong) stream.avail_out != *destLen)
2264 stream.zalloc = (alloc_func) 0;
2265 stream.zfree = (free_func) 0;
2266 stream.opaque = (voidpf) 0;
2268 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2269 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2273 err = deflate(&stream, Z_FINISH);
2274 if (err != Z_STREAM_END) {
2275 deflateEnd(&stream);
2276 return err == Z_OK ? Z_BUF_ERROR : err;
2278 *destLen = stream.total_out + 10L;
2280 /* write CRC and Length */
2281 uLong crc = crc32(0L, source, sourceLen);
2283 for (n = 0; n < 4; ++n, ++*destLen) {
2284 dest[*destLen] = (int) (crc & 0xff);
2287 uLong len = stream.total_in;
2288 for (n = 0; n < 4; ++n, ++*destLen) {
2289 dest[*destLen] = (int) (len & 0xff);
2292 err = deflateEnd(&stream);
2299 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2301 int CompressBuffer(StrBuf *Buf)
2304 char *compressed_data = NULL;
2305 size_t compressed_len, bufsize;
2308 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2309 compressed_data = malloc(compressed_len);
2311 if (compressed_data == NULL)
2313 /* Flush some space after the used payload so valgrind shuts up... */
2314 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2315 Buf->buf[Buf->BufUsed + i++] = '\0';
2316 if (compress_gzip((Bytef *) compressed_data,
2319 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2322 Buf->buf = compressed_data;
2323 Buf->BufUsed = compressed_len;
2324 Buf->BufSize = bufsize;
2325 /* Flush some space after the used payload so valgrind shuts up... */
2327 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2328 Buf->buf[Buf->BufUsed + i++] = '\0';
2331 free(compressed_data);
2333 #endif /* HAVE_ZLIB */
2338 * \brief decode a buffer from base 64 encoding; destroys original
2339 * \param Buf Buffor to transform
2341 int StrBufDecodeBase64(StrBuf *Buf)
2345 if (Buf == NULL) return -1;
2347 xferbuf = (char*) malloc(Buf->BufSize);
2348 siz = CtdlDecodeBase64(xferbuf,
2358 * \brief decode a buffer from base 64 encoding; destroys original
2359 * \param Buf Buffor to transform
2361 int StrBufDecodeHex(StrBuf *Buf)
2364 char *pch, *pche, *pchi;
2366 if (Buf == NULL) return -1;
2368 pch = pchi = Buf->buf;
2369 pche = pch + Buf->BufUsed;
2371 while (pchi < pche){
2372 ch = decode_hex(pchi);
2379 Buf->BufUsed = pch - Buf->buf;
2380 return Buf->BufUsed;
2384 * \brief replace all chars >0x20 && < 0x7F with Mute
2385 * \param Mute char to put over invalid chars
2386 * \param Buf Buffor to transform
2388 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2392 if (Buf == NULL) return -1;
2393 pch = (unsigned char *)Buf->buf;
2394 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2395 if ((*pch < 0x20) || (*pch > 0x7F))
2399 return Buf->BufUsed;
2404 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2405 * \param Buf Buffer to translate
2406 * \param StripBlanks Reduce several blanks to one?
2408 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2414 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2415 Buf->buf[Buf->BufUsed - 1] = '\0';
2420 while (a < Buf->BufUsed) {
2421 if (Buf->buf[a] == '+')
2423 else if (Buf->buf[a] == '%') {
2424 /* don't let % chars through, rather truncate the input. */
2425 if (a + 2 > Buf->BufUsed) {
2430 hex[0] = Buf->buf[a + 1];
2431 hex[1] = Buf->buf[a + 2];
2434 sscanf(hex, "%02x", &b);
2435 Buf->buf[a] = (char) b;
2436 len = Buf->BufUsed - a - 2;
2438 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2450 * \brief RFC2047-encode a header field if necessary.
2451 * If no non-ASCII characters are found, the string
2452 * will be copied verbatim without encoding.
2454 * \param target Target buffer.
2455 * \param source Source string to be encoded.
2456 * \returns encoded length; -1 if non success.
2458 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2460 const char headerStr[] = "=?UTF-8?Q?";
2461 int need_to_encode = 0;
2465 if ((source == NULL) ||
2469 while ((i < source->BufUsed) &&
2470 (!IsEmptyStr (&source->buf[i])) &&
2471 (need_to_encode == 0)) {
2472 if (((unsigned char) source->buf[i] < 32) ||
2473 ((unsigned char) source->buf[i] > 126)) {
2479 if (!need_to_encode) {
2480 if (*target == NULL) {
2481 *target = NewStrBufPlain(source->buf, source->BufUsed);
2484 FlushStrBuf(*target);
2485 StrBufAppendBuf(*target, source, 0);
2487 return (*target)->BufUsed;
2489 if (*target == NULL)
2490 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2491 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2492 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2493 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2494 (*target)->BufUsed = sizeof(headerStr) - 1;
2495 for (i=0; (i < source->BufUsed); ++i) {
2496 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2497 IncreaseBuf(*target, 1, 0);
2498 ch = (unsigned char) source->buf[i];
2499 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2500 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2501 (*target)->BufUsed += 3;
2504 (*target)->buf[(*target)->BufUsed] = ch;
2505 (*target)->BufUsed++;
2509 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2510 IncreaseBuf(*target, 1, 0);
2512 (*target)->buf[(*target)->BufUsed++] = '?';
2513 (*target)->buf[(*target)->BufUsed++] = '=';
2514 (*target)->buf[(*target)->BufUsed] = '\0';
2515 return (*target)->BufUsed;;
2519 * \brief replaces all occurances of 'search' by 'replace'
2520 * \param buf Buffer to modify
2521 * \param search character to search
2522 * \param relpace character to replace search by
2524 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2529 for (i=0; i<buf->BufUsed; i++)
2530 if (buf->buf[i] == search)
2531 buf->buf[i] = replace;
2538 * Wrapper around iconv_open()
2539 * Our version adds aliases for non-standard Microsoft charsets
2540 * such as 'MS950', aliasing them to names like 'CP950'
2542 * tocode Target encoding
2543 * fromcode Source encoding
2545 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2548 iconv_t ic = (iconv_t)(-1) ;
2549 ic = iconv_open(tocode, fromcode);
2550 if (ic == (iconv_t)(-1) ) {
2551 char alias_fromcode[64];
2552 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2553 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2554 alias_fromcode[0] = 'C';
2555 alias_fromcode[1] = 'P';
2556 ic = iconv_open(tocode, alias_fromcode);
2559 *(iconv_t *)pic = ic;
2565 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2568 /* Find the next ?Q? */
2569 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2572 end = strchr(bptr + 2, '?');
2577 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2578 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2579 (*(end + 2) == '?')) {
2580 /* skip on to the end of the cluster, the next ?= */
2581 end = strstr(end + 3, "?=");
2584 /* sort of half valid encoding, try to find an end. */
2585 end = strstr(bptr, "?=");
2589 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2593 memcpy(&C, A, sizeof(*A));
2594 memcpy(A, B, sizeof(*B));
2595 memcpy(B, &C, sizeof(C));
2599 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2605 char *ibuf; /**< Buffer of characters to be converted */
2606 char *obuf; /**< Buffer for converted characters */
2607 size_t ibuflen; /**< Length of input buffer */
2608 size_t obuflen; /**< Length of output buffer */
2611 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2612 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2613 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2615 ic = *(iconv_t*)pic;
2616 ibuf = ConvertBuf->buf;
2617 ibuflen = ConvertBuf->BufUsed;
2619 obuflen = TmpBuf->BufSize;
2621 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2624 if (errno == E2BIG) {
2626 IncreaseBuf(TmpBuf, 0, 0);
2631 else if (errno == EILSEQ){
2632 /* hm, invalid utf8 sequence... what to do now? */
2633 /* An invalid multibyte sequence has been encountered in the input */
2635 else if (errno == EINVAL) {
2636 /* An incomplete multibyte sequence has been encountered in the input. */
2639 FlushStrBuf(TmpBuf);
2642 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2643 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2645 /* little card game: wheres the red lady? */
2646 SwapBuffers(ConvertBuf, TmpBuf);
2647 FlushStrBuf(TmpBuf);
2655 inline static void DecodeSegment(StrBuf *Target,
2656 const StrBuf *DecodeMe,
2660 StrBuf *ConvertBuf2,
2661 StrBuf *FoundCharset)
2667 iconv_t ic = (iconv_t)(-1);
2669 /* Now we handle foreign character sets properly encoded
2670 * in RFC2047 format.
2672 StaticBuf.buf = SegmentStart;
2673 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2674 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2675 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2676 if (FoundCharset != NULL) {
2677 FlushStrBuf(FoundCharset);
2678 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2680 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2681 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2683 *encoding = toupper(*encoding);
2684 if (*encoding == 'B') { /**< base64 */
2685 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2687 ConvertBuf->BufUsed);
2689 else if (*encoding == 'Q') { /**< quoted-printable */
2693 while (pos < ConvertBuf->BufUsed)
2695 if (ConvertBuf->buf[pos] == '_')
2696 ConvertBuf->buf[pos] = ' ';
2700 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2703 ConvertBuf->BufUsed);
2706 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2709 ctdl_iconv_open("UTF-8", charset, &ic);
2710 if (ic != (iconv_t)(-1) ) {
2712 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2713 StrBufAppendBuf(Target, ConvertBuf2, 0);
2718 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2723 * Handle subjects with RFC2047 encoding such as:
2724 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2726 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2728 StrBuf *ConvertBuf, *ConvertBuf2;
2729 char *start, *end, *next, *nextend, *ptr = NULL;
2731 iconv_t ic = (iconv_t)(-1) ;
2736 int illegal_non_rfc2047_encoding = 0;
2738 /* Sometimes, badly formed messages contain strings which were simply
2739 * written out directly in some foreign character set instead of
2740 * using RFC2047 encoding. This is illegal but we will attempt to
2741 * handle it anyway by converting from a user-specified default
2742 * charset to UTF-8 if we see any nonprintable characters.
2745 len = StrLength(DecodeMe);
2746 for (i=0; i<DecodeMe->BufUsed; ++i) {
2747 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2748 illegal_non_rfc2047_encoding = 1;
2753 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2754 if ((illegal_non_rfc2047_encoding) &&
2755 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2756 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2759 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2760 if (ic != (iconv_t)(-1) ) {
2761 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2767 /* pre evaluate the first pair */
2768 nextend = end = NULL;
2769 len = StrLength(DecodeMe);
2770 start = strstr(DecodeMe->buf, "=?");
2771 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2773 end = FindNextEnd (DecodeMe, start);
2775 StrBufAppendBuf(Target, DecodeMe, 0);
2776 FreeStrBuf(&ConvertBuf);
2780 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2782 if (start != DecodeMe->buf) {
2785 nFront = start - DecodeMe->buf;
2786 StrBufAppendBufPlain(Target, DecodeMe->buf, nFront, 0);
2790 * Since spammers will go to all sorts of absurd lengths to get their
2791 * messages through, there are LOTS of corrupt headers out there.
2792 * So, prevent a really badly formed RFC2047 header from throwing
2793 * this function into an infinite loop.
2795 while ((start != NULL) &&
2802 DecodeSegment(Target,
2810 next = strstr(end, "=?");
2812 if ((next != NULL) &&
2814 nextend = FindNextEnd(DecodeMe, next);
2815 if (nextend == NULL)
2818 /* did we find two partitions */
2819 if ((next != NULL) &&
2823 while ((ptr < next) &&
2829 /* did we find a gab just filled with blanks? */
2832 long gap = next - start;
2837 /* now terminate the gab at the end */
2838 delta = (next - end) - 2; ////TODO: const!
2839 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2840 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2842 /* move next to its new location. */
2847 /* our next-pair is our new first pair now. */
2853 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2854 if ((end != NULL) && (end < nextend)) {
2856 while ( (ptr < nextend) &&
2863 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2865 FreeStrBuf(&ConvertBuf);
2866 FreeStrBuf(&ConvertBuf2);
2870 * \brief evaluate the length of an utf8 special character sequence
2871 * \param Char the character to examine
2872 * \returns width of utf8 chars in bytes
2874 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2879 while ((n < 8) && ((test & *CharS) != 0)) {
2883 if ((n > 6) || ((CharE - CharS) > n))
2889 * \brief detect whether this char starts an utf-8 encoded char
2890 * \param Char character to inspect
2891 * \returns yes or no
2893 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2895 /** 11??.???? indicates an UTF8 Sequence. */
2896 return ((Char & 0xC0) != 0);
2900 * \brief measure the number of glyphs in an UTF8 string...
2901 * \param str string to measure
2902 * \returns the length of str
2904 long StrBuf_Utf8StrLen(StrBuf *Buf)
2910 if ((Buf == NULL) || (Buf->BufUsed == 0))
2913 eptr = Buf->buf + Buf->BufUsed;
2914 while ((aptr < eptr) && (*aptr != '\0')) {
2915 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2916 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2917 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2930 * \brief cuts a string after maxlen glyphs
2931 * \param str string to cut to maxlen glyphs
2932 * \param maxlen how long may the string become?
2933 * \returns pointer to maxlen or the end of the string
2935 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2941 eptr = Buf->buf + Buf->BufUsed;
2942 while ((aptr < eptr) && (*aptr != '\0')) {
2943 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2944 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2945 while ((m-- > 0) && (*aptr++ != '\0'))
2954 Buf->BufUsed = aptr - Buf->buf;
2955 return Buf->BufUsed;
2958 return Buf->BufUsed;
2964 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2966 const char *aptr, *ptr, *eptr;
2973 ptr = aptr = Buf->buf;
2977 optr = LineBuf->buf;
2978 eptr = Buf->buf + Buf->BufUsed;
2979 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2981 while ((*ptr != '\n') &&
2988 LineBuf->BufUsed = optr - LineBuf->buf;
2989 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2990 optr = LineBuf->buf + LineBuf->BufUsed;
2991 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2994 LineBuf->BufUsed = optr - LineBuf->buf;
3003 return Buf->BufUsed - (ptr - Buf->buf);