8 #include <sys/select.h>
10 #include <sys/types.h>
11 #define SHOW_ME_VAPPEND_PRINTF
13 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
28 int BaseStrBufSize = 64;
31 * Private Structure for the Stringbuffer
34 char *buf; /**< the pointer to the dynamic buffer */
35 long BufSize; /**< how many spcae do we optain */
36 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
37 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 char bt_lastinc [SIZ];
47 static void StrBufBacktrace(StrBuf *Buf, int which)
51 void *stack_frames[50];
56 pstart = pch = Buf->bt;
58 pstart = pch = Buf->bt_lastinc;
59 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
60 strings = backtrace_symbols(stack_frames, size);
61 for (i = 0; i < size; i++) {
63 n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
65 n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
76 * \Brief Cast operator to Plain String
77 * Note: if the buffer is altered by StrBuf operations, this pointer may become
78 * invalid. So don't lean on it after altering the buffer!
79 * Since this operation is considered cheap, rather call it often than risking
80 * your pointer to become invalid!
81 * \param Str the string we want to get the c-string representation for
82 * \returns the Pointer to the Content. Don't mess with it!
84 inline const char *ChrPtr(const StrBuf *Str)
92 * \brief since we know strlen()'s result, provide it here.
93 * \param Str the string to return the length to
94 * \returns contentlength of the buffer
96 inline int StrLength(const StrBuf *Str)
98 return (Str != NULL) ? Str->BufUsed : 0;
102 * \brief local utility function to resize the buffer
103 * \param Buf the buffer whichs storage we should increase
104 * \param KeepOriginal should we copy the original buffer or just start over with a new one
105 * \param DestSize what should fit in after?
107 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
110 size_t NewSize = Buf->BufSize * 2;
116 while (NewSize <= DestSize)
119 NewBuf= (char*) malloc(NewSize);
120 if (KeepOriginal && (Buf->BufUsed > 0))
122 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
131 Buf->BufSize = NewSize;
135 StrBufBacktrace(Buf, 1);
142 * \brief shrink an _EMPTY_ buffer if its Buffer superseeds threshhold to NewSize. Buffercontent is thoroughly ignored and flushed.
143 * \param Buf Buffer to shrink (has to be empty)
144 * \param ThreshHold if the buffer is bigger then this, its readjusted
145 * \param NewSize if we Shrink it, how big are we going to be afterwards?
147 void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
149 if (Buf->BufUsed > ThreshHold) {
151 Buf->buf = (char*) malloc(NewSize);
153 Buf->BufSize = NewSize;
158 * \brief shrink long term buffers to their real size so they don't waste memory
159 * \param Buf buffer to shrink
160 * \param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
161 * \returns physical size of the buffer
163 long StrBufShrinkToFit(StrBuf *Buf, int Force)
166 (Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
168 char *TmpBuf = (char*) malloc(Buf->BufUsed + 1);
169 memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
170 Buf->BufSize = Buf->BufUsed + 1;
178 * Allocate a new buffer with default buffer size
179 * \returns the new stringbuffer
181 StrBuf* NewStrBuf(void)
185 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
186 NewBuf->buf = (char*) malloc(BaseStrBufSize);
187 NewBuf->buf[0] = '\0';
188 NewBuf->BufSize = BaseStrBufSize;
190 NewBuf->ConstBuf = 0;
192 NewBuf->nIncreases = 0;
193 NewBuf->bt[0] = '\0';
194 NewBuf->bt_lastinc[0] = '\0';
196 StrBufBacktrace(NewBuf, 0);
203 * \brief Copy Constructor; returns a duplicate of CopyMe
204 * \params CopyMe Buffer to faxmilate
205 * \returns the new stringbuffer
207 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
216 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
217 NewBuf->BufUsed = CopyMe->BufUsed;
218 NewBuf->BufSize = CopyMe->BufSize;
219 NewBuf->ConstBuf = 0;
221 NewBuf->nIncreases = 0;
222 NewBuf->bt[0] = '\0';
223 NewBuf->bt_lastinc[0] = '\0';
225 StrBufBacktrace(NewBuf, 0);
232 * \brief create a new Buffer using an existing c-string
233 * this function should also be used if you want to pre-suggest
234 * the buffer size to allocate in conjunction with ptr == NULL
235 * \param ptr the c-string to copy; may be NULL to create a blank instance
236 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
237 * \returns the new stringbuffer
239 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
242 size_t Siz = BaseStrBufSize;
245 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
247 CopySize = strlen((ptr != NULL)?ptr:"");
251 while (Siz <= CopySize)
254 NewBuf->buf = (char*) malloc(Siz);
255 NewBuf->BufSize = Siz;
257 memcpy(NewBuf->buf, ptr, CopySize);
258 NewBuf->buf[CopySize] = '\0';
259 NewBuf->BufUsed = CopySize;
262 NewBuf->buf[0] = '\0';
265 NewBuf->ConstBuf = 0;
267 NewBuf->nIncreases = 0;
268 NewBuf->bt[0] = '\0';
269 NewBuf->bt_lastinc[0] = '\0';
271 StrBufBacktrace(NewBuf, 0);
278 * \brief Set an existing buffer from a c-string
279 * \param ptr c-string to put into
280 * \param nChars set to -1 if we should work 0-terminated
281 * \returns the new length of the string
283 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
285 size_t Siz = Buf->BufSize;
289 CopySize = strlen(ptr);
293 while (Siz <= CopySize)
296 if (Siz != Buf->BufSize)
297 IncreaseBuf(Buf, 0, Siz);
298 memcpy(Buf->buf, ptr, CopySize);
299 Buf->buf[CopySize] = '\0';
300 Buf->BufUsed = CopySize;
307 * \brief use strbuf as wrapper for a string constant for easy handling
308 * \param StringConstant a string to wrap
309 * \param SizeOfConstant should be sizeof(StringConstant)-1
311 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
315 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
316 NewBuf->buf = (char*) StringConstant;
317 NewBuf->BufSize = SizeOfStrConstant;
318 NewBuf->BufUsed = SizeOfStrConstant;
319 NewBuf->ConstBuf = 1;
321 NewBuf->nIncreases = 0;
322 NewBuf->bt[0] = '\0';
323 NewBuf->bt_lastinc[0] = '\0';
330 * \brief flush the content of a Buf; keep its struct
331 * \param buf Buffer to flush
333 int FlushStrBuf(StrBuf *buf)
345 * \brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
346 * \param buf Buffer to wipe
348 int FLUSHStrBuf(StrBuf *buf)
354 if (buf->BufUsed > 0) {
355 memset(buf->buf, 0, buf->BufUsed);
362 int hFreeDbglog = -1;
365 * \brief Release a Buffer
366 * Its a double pointer, so it can NULL your pointer
367 * so fancy SIG11 appear instead of random results
368 * \param FreeMe Pointer Pointer to the buffer to free
370 void FreeStrBuf (StrBuf **FreeMe)
375 if (hFreeDbglog == -1){
376 pid_t pid = getpid();
378 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
379 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
381 if ((*FreeMe)->nIncreases > 0)
385 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
386 (*FreeMe)->nIncreases,
390 (*FreeMe)->bt_lastinc);
391 n = write(hFreeDbglog, buf, n);
397 n = snprintf(buf, 128, "_|0|%ld%ld|\n",
400 n = write(hFreeDbglog, buf, n);
403 if (!(*FreeMe)->ConstBuf)
404 free((*FreeMe)->buf);
410 * \brief Release the buffer
411 * If you want put your StrBuf into a Hash, use this as Destructor.
412 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
414 void HFreeStrBuf (void *VFreeMe)
416 StrBuf *FreeMe = (StrBuf*)VFreeMe;
420 if (hFreeDbglog == -1){
421 pid_t pid = getpid();
423 snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
424 hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
426 if (FreeMe->nIncreases > 0)
430 n = snprintf(buf, SIZ * 3, "+|%ld|%ld|%ld|%s|%s|\n",
436 write(hFreeDbglog, buf, n);
442 n = snprintf(buf, 128, "_|%ld|%ld%ld|\n",
448 if (!FreeMe->ConstBuf)
454 * \brief Wrapper around atol
456 long StrTol(const StrBuf *Buf)
461 return atol(Buf->buf);
467 * \brief Wrapper around atoi
469 int StrToi(const StrBuf *Buf)
473 if (Buf->BufUsed > 0)
474 return atoi(Buf->buf);
480 * \brief Checks to see if the string is a pure number
482 int StrBufIsNumber(const StrBuf *Buf) {
487 strtoll(Buf->buf, &pEnd, 10);
488 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
494 * \brief modifies a Single char of the Buf
495 * You can point to it via char* or a zero-based integer
496 * \param ptr char* to zero; use NULL if unused
497 * \param nThChar zero based pointer into the string; use -1 if unused
498 * \param PeekValue The Character to place into the position
500 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
505 nThChar = ptr - Buf->buf;
506 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
508 Buf->buf[nThChar] = PeekValue;
513 * \brief Append a StringBuffer to the buffer
514 * \param Buf Buffer to modify
515 * \param AppendBuf Buffer to copy at the end of our buffer
516 * \param Offset Should we start copying from an offset?
518 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
520 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
523 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
526 AppendBuf->BufUsed + Buf->BufUsed);
528 memcpy(Buf->buf + Buf->BufUsed,
529 AppendBuf->buf + Offset,
530 AppendBuf->BufUsed - Offset);
531 Buf->BufUsed += AppendBuf->BufUsed - Offset;
532 Buf->buf[Buf->BufUsed] = '\0';
537 * \brief Append a C-String to the buffer
538 * \param Buf Buffer to modify
539 * \param AppendBuf Buffer to copy at the end of our buffer
540 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
541 * \param Offset Should we start copying from an offset?
543 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
546 long BufSizeRequired;
548 if ((AppendBuf == NULL) || (Buf == NULL))
552 aps = strlen(AppendBuf + Offset);
554 aps = AppendSize - Offset;
556 BufSizeRequired = Buf->BufUsed + aps + 1;
557 if (Buf->BufSize <= BufSizeRequired)
558 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
560 memcpy(Buf->buf + Buf->BufUsed,
564 Buf->buf[Buf->BufUsed] = '\0';
568 * \brief Callback for cURL to append the webserver reply to a buffer
569 * params pre-defined by the cURL API; see man 3 curl for mre info
571 size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
580 StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
586 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
587 * \param outbuf the output buffer
588 * \param oblen the size of outbuf to sanitize
589 * \param strbuf the input buffer
591 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
593 const char *pch, *pche;
596 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
597 int eclen = sizeof(ec) -1;
599 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
601 if (PlainIn != NULL) {
602 len = strlen(PlainIn);
608 pche = pch + In->BufUsed;
615 pt = OutBuf->buf + OutBuf->BufUsed;
616 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
620 IncreaseBuf(OutBuf, 1, -1);
621 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
622 pt = OutBuf->buf + OutBuf->BufUsed;
626 for (b = 0; b < eclen; ++b) {
633 sprintf(pt,"%%%02X", *pch);
635 OutBuf->BufUsed += 3;
647 * \brief Append a string, escaping characters which have meaning in HTML.
649 * \param Target target buffer
650 * \param Source source buffer; set to NULL if you just have a C-String
651 * \param PlainIn Plain-C string to append; set to NULL if unused
652 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
653 * \param nolinebreaks if set to 1, linebreaks are removed from the string.
654 * if set to 2, linebreaks are replaced by <br/>
656 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
658 const char *aptr, *eiptr;
662 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
665 if (PlainIn != NULL) {
667 len = strlen(PlainIn);
672 eiptr = aptr + Source->BufUsed;
673 len = Source->BufUsed;
679 bptr = Target->buf + Target->BufUsed;
680 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
682 while (aptr < eiptr){
684 IncreaseBuf(Target, 1, -1);
685 eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
686 bptr = Target->buf + Target->BufUsed;
689 memcpy(bptr, "<", 4);
691 Target->BufUsed += 4;
693 else if (*aptr == '>') {
694 memcpy(bptr, ">", 4);
696 Target->BufUsed += 4;
698 else if (*aptr == '&') {
699 memcpy(bptr, "&", 5);
701 Target->BufUsed += 5;
703 else if (*aptr == '"') {
704 memcpy(bptr, """, 6);
706 Target->BufUsed += 6;
708 else if (*aptr == '\'') {
709 memcpy(bptr, "'", 5);
711 Target->BufUsed += 5;
713 else if (*aptr == LB) {
718 else if (*aptr == RB) {
723 else if (*aptr == QU) {
728 else if ((*aptr == 32) && (nbsp == 1)) {
729 memcpy(bptr, " ", 6);
731 Target->BufUsed += 6;
733 else if ((*aptr == '\n') && (nolinebreaks == 1)) {
734 *bptr='\0'; /* nothing */
736 else if ((*aptr == '\n') && (nolinebreaks == 2)) {
737 memcpy(bptr, "<br/>", 11);
739 Target->BufUsed += 11;
743 else if ((*aptr == '\r') && (nolinebreaks != 0)) {
744 *bptr='\0'; /* nothing */
754 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
756 return Target->BufUsed;
760 * \brief Append a string, escaping characters which have meaning in HTML.
761 * Converts linebreaks into blanks; escapes single quotes
762 * \param Target target buffer
763 * \param Source source buffer; set to NULL if you just have a C-String
764 * \param PlainIn Plain-C string to append; set to NULL if unused
766 void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
768 const char *aptr, *eiptr;
772 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
775 if (PlainIn != NULL) {
777 len = strlen(PlainIn);
782 eiptr = aptr + Source->BufUsed;
783 len = Source->BufUsed;
789 eptr = Target->buf + Target->BufSize - 8;
790 tptr = Target->buf + Target->BufUsed;
792 while (aptr < eiptr){
794 IncreaseBuf(Target, 1, -1);
795 eptr = Target->buf + Target->BufSize - 8;
796 tptr = Target->buf + Target->BufUsed;
803 else if (*aptr == '\r') {
807 else if (*aptr == '\'') {
813 Target->BufUsed += 5;
826 * \brief Append a string, escaping characters which have meaning in ICAL.
828 * \param Target target buffer
829 * \param Source source buffer; set to NULL if you just have a C-String
830 * \param PlainIn Plain-C string to append; set to NULL if unused
832 void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
834 const char *aptr, *eiptr;
838 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
841 if (PlainIn != NULL) {
843 len = strlen(PlainIn);
848 eiptr = aptr + Source->BufUsed;
849 len = Source->BufUsed;
855 eptr = Target->buf + Target->BufSize - 8;
856 tptr = Target->buf + Target->BufUsed;
858 while (aptr < eiptr){
859 if(tptr + 3 >= eptr) {
860 IncreaseBuf(Target, 1, -1);
861 eptr = Target->buf + Target->BufSize - 8;
862 tptr = Target->buf + Target->BufUsed;
872 else if (*aptr == '\r') {
879 else if (*aptr == ',') {
895 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
897 * \param Target target buffer
898 * \param Source source buffer; set to NULL if you just have a C-String
899 * \param PlainIn Plain-C string to append; set to NULL if unused
901 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
903 const char *aptr, *eiptr;
907 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
910 if (PlainIn != NULL) {
912 len = strlen(PlainIn);
917 eiptr = aptr + Source->BufUsed;
918 len = Source->BufUsed;
924 bptr = Target->buf + Target->BufUsed;
925 eptr = Target->buf + Target->BufSize - 3; /* our biggest unit to put in... */
927 while (aptr < eiptr){
929 IncreaseBuf(Target, 1, -1);
930 eptr = Target->buf + Target->BufSize - 3;
931 bptr = Target->buf + Target->BufUsed;
933 else if (*aptr == '"') {
938 Target->BufUsed += 2;
939 } else if (*aptr == '\\') {
944 Target->BufUsed += 2;
954 if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
956 return Target->BufUsed;
960 * \brief extracts a substring from Source into dest
961 * \param dest buffer to place substring into
962 * \param Source string to copy substring from
963 * \param Offset chars to skip from start
964 * \param nChars number of chars to copy
965 * \returns the number of chars copied; may be different from nChars due to the size of Source
967 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
970 if (Offset > Source->BufUsed)
975 if (Offset + nChars < Source->BufUsed)
977 if (nChars >= dest->BufSize)
978 IncreaseBuf(dest, 0, nChars + 1);
979 memcpy(dest->buf, Source->buf + Offset, nChars);
980 dest->BufUsed = nChars;
981 dest->buf[dest->BufUsed] = '\0';
984 NCharsRemain = Source->BufUsed - Offset;
985 if (NCharsRemain >= dest->BufSize)
986 IncreaseBuf(dest, 0, NCharsRemain + 1);
987 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
988 dest->BufUsed = NCharsRemain;
989 dest->buf[dest->BufUsed] = '\0';
994 * \brief sprintf like function appending the formated string to the buffer
995 * vsnprintf version to wrap into own calls
996 * \param Buf Buffer to extend by format and params
997 * \param format printf alike format to add
998 * \param ap va_list containing the items for format
1000 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
1003 size_t BufSize = Buf->BufSize;
1004 size_t nWritten = Buf->BufSize + 1;
1005 size_t Offset = Buf->BufUsed;
1006 size_t newused = Offset + nWritten;
1008 while (newused >= BufSize) {
1010 nWritten = vsnprintf(Buf->buf + Offset,
1011 Buf->BufSize - Offset,
1014 newused = Offset + nWritten;
1015 if (newused >= Buf->BufSize) {
1016 IncreaseBuf(Buf, 1, newused);
1017 newused = Buf->BufSize + 1;
1020 Buf->BufUsed = Offset + nWritten;
1021 BufSize = Buf->BufSize;
1028 * \brief sprintf like function appending the formated string to the buffer
1029 * \param Buf Buffer to extend by format and params
1030 * \param format printf alike format to add
1031 * \param ap va_list containing the items for format
1033 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
1035 size_t BufSize = Buf->BufSize;
1036 size_t nWritten = Buf->BufSize + 1;
1037 size_t Offset = Buf->BufUsed;
1038 size_t newused = Offset + nWritten;
1041 while (newused >= BufSize) {
1042 va_start(arg_ptr, format);
1043 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
1044 Buf->BufSize - Buf->BufUsed,
1047 newused = Buf->BufUsed + nWritten;
1048 if (newused >= Buf->BufSize) {
1049 IncreaseBuf(Buf, 1, newused);
1050 newused = Buf->BufSize + 1;
1053 Buf->BufUsed += nWritten;
1054 BufSize = Buf->BufSize;
1061 * \brief sprintf like function putting the formated string into the buffer
1062 * \param Buf Buffer to extend by format and params
1063 * \param format printf alike format to add
1064 * \param ap va_list containing the items for format
1066 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
1068 size_t nWritten = Buf->BufSize + 1;
1071 while (nWritten >= Buf->BufSize) {
1072 va_start(arg_ptr, format);
1073 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
1075 if (nWritten >= Buf->BufSize) {
1076 IncreaseBuf(Buf, 0, 0);
1077 nWritten = Buf->BufSize + 1;
1080 Buf->BufUsed = nWritten ;
1086 * \brief Counts the numbmer of tokens in a buffer
1087 * \param Source String to count tokens in
1088 * \param tok Tokenizer char to count
1089 * \returns numbers of tokenizer chars found
1091 int StrBufNum_tokens(const StrBuf *source, char tok)
1095 return num_tokens(source->buf, tok);
1099 * remove_token() - a tokenizer that kills, maims, and destroys
1102 * \brief a string tokenizer
1103 * \param Source StringBuffer to read into
1104 * \param parmnum n'th parameter to remove
1105 * \param separator tokenizer param
1106 * \returns -1 if not found, else length of token.
1108 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
1111 char *d, *s; /* dest, source */
1114 /* Find desired parameter */
1116 while (count < parmnum) {
1117 /* End of string, bail! */
1122 if (*d == separator) {
1127 if (!d) return 0; /* Parameter not found */
1129 /* Find next parameter */
1131 while (*s && *s != separator) {
1134 if (*s == separator)
1138 /* Hack and slash */
1140 memmove(d, s, Source->BufUsed - (s - Source->buf) + 1);
1141 Source->BufUsed -= (ReducedBy + 1);
1143 else if (d == Source->buf) {
1145 Source->BufUsed = 0;
1149 Source->BufUsed -= (ReducedBy + 1);
1162 * \brief a string tokenizer
1163 * \param dest Destination StringBuffer
1164 * \param Source StringBuffer to read into
1165 * \param parmnum n'th parameter to extract
1166 * \param separator tokenizer param
1167 * \returns -1 if not found, else length of token.
1169 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
1171 const char *s, *e; //* source * /
1172 int len = 0; //* running total length of extracted string * /
1173 int current_token = 0; //* token currently being processed * /
1176 dest->buf[0] = '\0';
1182 if ((Source == NULL) || (Source->BufUsed ==0)) {
1186 e = s + Source->BufUsed;
1189 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1191 while ((s<e) && !IsEmptyStr(s)) {
1192 if (*s == separator) {
1195 if (len >= dest->BufSize) {
1196 dest->BufUsed = len;
1197 if (IncreaseBuf(dest, 1, -1) < 0) {
1202 if ( (current_token == parmnum) &&
1203 (*s != separator)) {
1204 dest->buf[len] = *s;
1207 else if (current_token > parmnum) {
1213 dest->buf[len] = '\0';
1214 dest->BufUsed = len;
1216 if (current_token < parmnum) {
1217 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1220 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1229 * \brief a string tokenizer to fetch an integer
1230 * \param dest Destination StringBuffer
1231 * \param parmnum n'th parameter to extract
1232 * \param separator tokenizer param
1233 * \returns 0 if not found, else integer representation of the token
1235 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
1245 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1252 * \brief a string tokenizer to fetch a long integer
1253 * \param dest Destination StringBuffer
1254 * \param parmnum n'th parameter to extract
1255 * \param separator tokenizer param
1256 * \returns 0 if not found, else long integer representation of the token
1258 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
1268 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
1276 * \brief a string tokenizer to fetch an unsigned long
1277 * \param dest Destination StringBuffer
1278 * \param parmnum n'th parameter to extract
1279 * \param separator tokenizer param
1280 * \returns 0 if not found, else unsigned long representation of the token
1282 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
1293 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1297 return (unsigned long) atol(pnum);
1305 * \brief a string tokenizer
1306 * \param dest Destination StringBuffer
1307 * \param Source StringBuffer to read into
1308 * \param pStart pointer to the end of the last token. Feed with NULL.
1309 * \param separator tokenizer param
1310 * \returns -1 if not found, else length of token.
1312 int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
1314 const char *s, *EndBuffer; //* source * /
1315 int len = 0; //* running total length of extracted string * /
1316 int current_token = 0; //* token currently being processed * /
1319 dest->buf[0] = '\0';
1325 if ((Source == NULL) ||
1326 (Source->BufUsed ==0)) {
1329 if (*pStart == NULL)
1330 *pStart = Source->buf;
1332 EndBuffer = Source->buf + Source->BufUsed;
1334 if ((*pStart < Source->buf) ||
1335 (*pStart > EndBuffer)) {
1343 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1345 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1346 if (*s == separator) {
1349 if (len >= dest->BufSize) {
1350 dest->BufUsed = len;
1352 if (IncreaseBuf(dest, 1, -1) < 0) {
1353 *pStart = EndBuffer + 1;
1358 if ( (current_token == 0) &&
1359 (*s != separator)) {
1360 dest->buf[len] = *s;
1363 else if (current_token > 0) {
1372 dest->buf[len] = '\0';
1373 dest->BufUsed = len;
1374 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
1375 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
1381 * \brief a string tokenizer
1382 * \param dest Destination StringBuffer
1383 * \param Source StringBuffer to read into
1384 * \param pStart pointer to the end of the last token. Feed with NULL.
1385 * \param separator tokenizer param
1386 * \returns -1 if not found, else length of token.
1388 int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
1390 const char *s, *EndBuffer; //* source * /
1391 int len = 0; //* running total length of extracted string * /
1392 int current_token = 0; //* token currently being processed * /
1394 if ((Source == NULL) ||
1395 (Source->BufUsed ==0)) {
1399 return Source->BufUsed;
1401 if (*pStart == NULL)
1402 *pStart = Source->buf;
1404 EndBuffer = Source->buf + Source->BufUsed;
1406 if ((*pStart < Source->buf) ||
1407 (*pStart > EndBuffer)) {
1415 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
1417 while ((s<EndBuffer) && !IsEmptyStr(s)) {
1418 if (*s == separator) {
1421 if (current_token >= nTokens) {
1433 * \brief a string tokenizer to fetch an integer
1434 * \param dest Destination StringBuffer
1435 * \param parmnum n'th parameter to extract
1436 * \param separator tokenizer param
1437 * \returns 0 if not found, else integer representation of the token
1439 int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
1449 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1456 * \brief a string tokenizer to fetch a long integer
1457 * \param dest Destination StringBuffer
1458 * \param parmnum n'th parameter to extract
1459 * \param separator tokenizer param
1460 * \returns 0 if not found, else long integer representation of the token
1462 long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
1472 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
1480 * \brief a string tokenizer to fetch an unsigned long
1481 * \param dest Destination StringBuffer
1482 * \param parmnum n'th parameter to extract
1483 * \param separator tokenizer param
1484 * \returns 0 if not found, else unsigned long representation of the token
1486 unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
1497 if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
1501 return (unsigned long) atol(pnum);
1510 * \brief Read a line from socket
1511 * flushes and closes the FD on error
1512 * \param buf the buffer to get the input to
1513 * \param fd pointer to the filedescriptor to read
1514 * \param append Append to an existing string or replace?
1515 * \param Error strerror() on error
1516 * \returns numbers of chars read
1518 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1520 int len, rlen, slen;
1525 slen = len = buf->BufUsed;
1527 rlen = read(*fd, &buf->buf[len], 1);
1529 *Error = strerror(errno);
1536 if (buf->buf[len] == '\n')
1538 if (buf->buf[len] != '\r')
1540 if (len >= buf->BufSize) {
1542 buf->buf[len+1] = '\0';
1543 IncreaseBuf(buf, 1, -1);
1547 buf->buf[len] = '\0';
1552 * \brief Read a line from socket
1553 * flushes and closes the FD on error
1554 * \param buf the buffer to get the input to
1555 * \param fd pointer to the filedescriptor to read
1556 * \param append Append to an existing string or replace?
1557 * \param Error strerror() on error
1558 * \returns numbers of chars read
1560 int StrBufTCP_read_buffered_line(StrBuf *Line,
1564 int selectresolution,
1568 int nSuccessLess = 0;
1574 if (buf->BufUsed > 0) {
1575 pch = strchr(buf->buf, '\n');
1578 len = pch - buf->buf;
1579 if (len > 0 && (*(pch - 1) == '\r') )
1581 StrBufSub(Line, buf, 0, len - rlen);
1582 StrBufCutLeft(buf, len + 1);
1587 if (buf->BufSize - buf->BufUsed < 10)
1588 IncreaseBuf(buf, 1, -1);
1590 fdflags = fcntl(*fd, F_GETFL);
1591 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1594 while ((nSuccessLess < timeout) && (pch == NULL)) {
1595 tv.tv_sec = selectresolution;
1600 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1601 *Error = strerror(errno);
1606 if (FD_ISSET(*fd, &rfds)) {
1608 &buf->buf[buf->BufUsed],
1609 buf->BufSize - buf->BufUsed - 1);
1611 *Error = strerror(errno);
1616 else if (rlen > 0) {
1618 buf->BufUsed += rlen;
1619 buf->buf[buf->BufUsed] = '\0';
1620 if (buf->BufUsed + 10 > buf->BufSize) {
1621 IncreaseBuf(buf, 1, -1);
1623 pch = strchr(buf->buf, '\n');
1631 len = pch - buf->buf;
1632 if (len > 0 && (*(pch - 1) == '\r') )
1634 StrBufSub(Line, buf, 0, len - rlen);
1635 StrBufCutLeft(buf, len + 1);
1642 static const char *ErrRBLF_WrongFDFlags="StrBufTCP_read_buffered_line_fast: don't work with fdflags & O_NONBLOCK";
1643 static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
1644 static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
1646 * \brief Read a line from socket
1647 * flushes and closes the FD on error
1648 * \param buf the buffer to get the input to
1649 * \param Pos pointer to the current read position, should be NULL initialized!
1650 * \param fd pointer to the filedescriptor to read
1651 * \param append Append to an existing string or replace?
1652 * \param Error strerror() on error
1653 * \returns numbers of chars read
1655 int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
1660 int selectresolution,
1663 const char *pche = NULL;
1664 const char *pos = NULL;
1666 int nSuccessLess = 0;
1668 const char *pch = NULL;
1673 if ((IOBuf->BufUsed > 0) &&
1675 (pos < IOBuf->buf + IOBuf->BufUsed))
1677 pche = IOBuf->buf + IOBuf->BufUsed;
1679 while ((pch < pche) && (*pch != '\n'))
1681 if ((pch >= pche) || (*pch == '\0'))
1683 if ((pch != NULL) &&
1688 if (len > 0 && (*(pch - 1) == '\r') )
1690 StrBufSub(Line, IOBuf, (pos - IOBuf->buf), len - rlen);
1700 StrBufCutLeft(IOBuf, (pos - IOBuf->buf));
1704 if (IOBuf->BufSize - IOBuf->BufUsed < 10) {
1705 IncreaseBuf(IOBuf, 1, -1);
1708 fdflags = fcntl(*fd, F_GETFL);
1709 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1710 *Error = ErrRBLF_WrongFDFlags;
1715 while ((nSuccessLess < timeout) && (pch == NULL)) {
1716 tv.tv_sec = selectresolution;
1721 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1722 *Error = strerror(errno);
1726 *Error = ErrRBLF_SelectFailed;
1729 if (FD_ISSET(*fd, &rfds) != 0) {
1731 &IOBuf->buf[IOBuf->BufUsed],
1732 IOBuf->BufSize - IOBuf->BufUsed - 1);
1734 *Error = strerror(errno);
1739 else if (rlen > 0) {
1741 IOBuf->BufUsed += rlen;
1742 IOBuf->buf[IOBuf->BufUsed] = '\0';
1743 if (IOBuf->BufUsed + 10 > IOBuf->BufSize) {
1744 IncreaseBuf(IOBuf, 1, -1);
1747 pche = IOBuf->buf + IOBuf->BufUsed;
1749 while ((pch < pche) && (*pch != '\n'))
1751 if ((pch >= pche) || (*pch == '\0'))
1762 if (len > 0 && (*(pch - 1) == '\r') )
1764 StrBufSub(Line, IOBuf, 0, len - rlen);
1765 *Pos = pos + len + 1;
1768 *Error = ErrRBLF_NotEnoughSentFromServer;
1774 * \brief Input binary data from socket
1775 * flushes and closes the FD on error
1776 * \param buf the buffer to get the input to
1777 * \param fd pointer to the filedescriptor to read
1778 * \param append Append to an existing string or replace?
1779 * \param nBytes the maximal number of bytes to read
1780 * \param Error strerror() on error
1781 * \returns numbers of chars read
1783 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1787 int len, rlen, slen;
1791 if ((Buf == NULL) || (*fd == -1))
1795 if (Buf->BufUsed + nBytes >= Buf->BufSize)
1796 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1798 ptr = Buf->buf + Buf->BufUsed;
1800 slen = len = Buf->BufUsed;
1802 fdflags = fcntl(*fd, F_GETFL);
1804 while (nRead < nBytes) {
1805 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1808 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1809 *Error = strerror(errno);
1814 if ((rlen = read(*fd,
1816 nBytes - nRead)) == -1) {
1819 *Error = strerror(errno);
1824 Buf->BufUsed += rlen;
1826 Buf->buf[Buf->BufUsed] = '\0';
1830 const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
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 StrBufReadBLOBBuffered(StrBuf *Blob,
1862 if ((Blob == NULL) || (*fd == -1) || (IOBuf == NULL) || (Pos == NULL))
1866 if (Blob->BufUsed + nBytes >= Blob->BufSize)
1867 IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
1872 len = pos - IOBuf->buf;
1873 rlen = IOBuf->BufUsed - len;
1876 if ((IOBuf->BufUsed > 0) &&
1878 (pos < IOBuf->buf + IOBuf->BufUsed))
1880 pche = IOBuf->buf + IOBuf->BufUsed;
1883 if (rlen < nBytes) {
1884 memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
1885 Blob->BufUsed += rlen;
1886 Blob->buf[Blob->BufUsed] = '\0';
1890 if (rlen >= nBytes) {
1891 memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
1892 Blob->BufUsed += nBytes;
1893 Blob->buf[Blob->BufUsed] = '\0';
1894 if (rlen == nBytes) {
1905 if (IOBuf->BufSize < nBytes - nRead)
1906 IncreaseBuf(IOBuf, 0, nBytes - nRead);
1909 slen = len = Blob->BufUsed;
1911 fdflags = fcntl(*fd, F_GETFL);
1916 while (nRead < nBytes) {
1917 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1920 SelRes = select(*fd + 1, NULL, &wset, NULL, NULL);
1923 *Error = strerror(errno);
1934 *Error = strerror(errno);
1940 if ((check == NNN_TERM) &&
1942 (strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
1944 StrBufPlain(Blob, HKEY("\n000\n"));
1945 StrBufCutRight(Blob, 5);
1946 return Blob->BufUsed;
1948 if (nSelects > 10) {
1950 *Error = ErrRBB_too_many_selects;
1957 IOBuf->BufUsed += rlen;
1960 if (nRead > nBytes) {
1961 *Pos = IOBuf->buf + nBytes;
1963 Blob->buf[Blob->BufUsed] = '\0';
1964 StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
1969 * \brief Cut nChars from the start of the string
1970 * \param Buf Buffer to modify
1971 * \param nChars how many chars should be skipped?
1973 void StrBufCutLeft(StrBuf *Buf, int nChars)
1975 if (nChars >= Buf->BufUsed) {
1979 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1980 Buf->BufUsed -= nChars;
1981 Buf->buf[Buf->BufUsed] = '\0';
1985 * \brief Cut the trailing n Chars from the string
1986 * \param Buf Buffer to modify
1987 * \param nChars how many chars should be trunkated?
1989 void StrBufCutRight(StrBuf *Buf, int nChars)
1991 if (nChars >= Buf->BufUsed) {
1995 Buf->BufUsed -= nChars;
1996 Buf->buf[Buf->BufUsed] = '\0';
2000 * \brief Cut the string after n Chars
2001 * \param Buf Buffer to modify
2002 * \param AfternChars after how many chars should we trunkate the string?
2003 * \param At if non-null and points inside of our string, cut it there.
2005 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
2008 AfternChars = At - Buf->buf;
2011 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
2013 Buf->BufUsed = AfternChars;
2014 Buf->buf[Buf->BufUsed] = '\0';
2019 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
2020 * buf - the string to modify
2021 * len - length of the string.
2023 void StrBufTrim(StrBuf *Buf)
2026 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
2028 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
2031 if (delta > 0) StrBufCutLeft(Buf, delta);
2033 if (Buf->BufUsed == 0) return;
2034 while (isspace(Buf->buf[Buf->BufUsed - 1])){
2037 Buf->buf[Buf->BufUsed] = '\0';
2041 void StrBufUpCase(StrBuf *Buf)
2046 pche = pch + Buf->BufUsed;
2047 while (pch < pche) {
2048 *pch = toupper(*pch);
2054 void StrBufLowerCase(StrBuf *Buf)
2059 pche = pch + Buf->BufUsed;
2060 while (pch < pche) {
2061 *pch = tolower(*pch);
2067 * \Brief removes double slashes from pathnames
2068 * \param Dir directory string to filter
2069 * \param RemoveTrailingSlash allows / disallows trailing slashes
2071 void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
2077 while (!IsEmptyStr(a)) {
2089 if ((RemoveTrailingSlash) && (*(b - 1) != '/')){
2094 Dir->BufUsed = b - Dir->buf;
2098 * \brief unhide special chars hidden to the HTML escaper
2099 * \param target buffer to put the unescaped string in
2100 * \param source buffer to unescape
2102 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
2108 FlushStrBuf(target);
2110 if (source == NULL ||target == NULL)
2115 len = source->BufUsed;
2116 for (a = 0; a < len; ++a) {
2117 if (target->BufUsed >= target->BufSize)
2118 IncreaseBuf(target, 1, -1);
2120 if (source->buf[a] == '=') {
2121 hex[0] = source->buf[a + 1];
2122 hex[1] = source->buf[a + 2];
2125 sscanf(hex, "%02x", &b);
2126 target->buf[target->BufUsed] = b;
2127 target->buf[++target->BufUsed] = 0;
2131 target->buf[target->BufUsed] = source->buf[a];
2132 target->buf[++target->BufUsed] = 0;
2139 * \brief hide special chars from the HTML escapers and friends
2140 * \param target buffer to put the escaped string in
2141 * \param source buffer to escape
2143 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
2148 FlushStrBuf(target);
2150 if (source == NULL ||target == NULL)
2155 len = source->BufUsed;
2156 for (i=0; i<len; ++i) {
2157 if (target->BufUsed + 4 >= target->BufSize)
2158 IncreaseBuf(target, 1, -1);
2159 if ( (isalnum(source->buf[i])) ||
2160 (source->buf[i]=='-') ||
2161 (source->buf[i]=='_') ) {
2162 target->buf[target->BufUsed++] = source->buf[i];
2165 sprintf(&target->buf[target->BufUsed],
2167 (0xFF &source->buf[i]));
2168 target->BufUsed += 3;
2171 target->buf[target->BufUsed + 1] = '\0';
2175 * \brief uses the same calling syntax as compress2(), but it
2176 * creates a stream compatible with HTTP "Content-encoding: gzip"
2179 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
2180 #define OS_CODE 0x03 /*< unix */
2181 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
2182 size_t * destLen, /*< length of the compresed data */
2183 const Bytef * source, /*< source to encode */
2184 uLong sourceLen, /*< length of source to encode */
2185 int level) /*< compression level */
2187 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
2189 /* write gzip header */
2190 snprintf((char *) dest, *destLen,
2191 "%c%c%c%c%c%c%c%c%c%c",
2192 gz_magic[0], gz_magic[1], Z_DEFLATED,
2193 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
2196 /* normal deflate */
2199 stream.next_in = (Bytef *) source;
2200 stream.avail_in = (uInt) sourceLen;
2201 stream.next_out = dest + 10L; // after header
2202 stream.avail_out = (uInt) * destLen;
2203 if ((uLong) stream.avail_out != *destLen)
2206 stream.zalloc = (alloc_func) 0;
2207 stream.zfree = (free_func) 0;
2208 stream.opaque = (voidpf) 0;
2210 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
2211 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
2215 err = deflate(&stream, Z_FINISH);
2216 if (err != Z_STREAM_END) {
2217 deflateEnd(&stream);
2218 return err == Z_OK ? Z_BUF_ERROR : err;
2220 *destLen = stream.total_out + 10L;
2222 /* write CRC and Length */
2223 uLong crc = crc32(0L, source, sourceLen);
2225 for (n = 0; n < 4; ++n, ++*destLen) {
2226 dest[*destLen] = (int) (crc & 0xff);
2229 uLong len = stream.total_in;
2230 for (n = 0; n < 4; ++n, ++*destLen) {
2231 dest[*destLen] = (int) (len & 0xff);
2234 err = deflateEnd(&stream);
2241 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
2243 int CompressBuffer(StrBuf *Buf)
2246 char *compressed_data = NULL;
2247 size_t compressed_len, bufsize;
2250 bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
2251 compressed_data = malloc(compressed_len);
2253 if (compressed_data == NULL)
2255 /* Flush some space after the used payload so valgrind shuts up... */
2256 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2257 Buf->buf[Buf->BufUsed + i++] = '\0';
2258 if (compress_gzip((Bytef *) compressed_data,
2261 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
2264 Buf->buf = compressed_data;
2265 Buf->BufUsed = compressed_len;
2266 Buf->BufSize = bufsize;
2267 /* Flush some space after the used payload so valgrind shuts up... */
2269 while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
2270 Buf->buf[Buf->BufUsed + i++] = '\0';
2273 free(compressed_data);
2275 #endif /* HAVE_ZLIB */
2280 * \brief decode a buffer from base 64 encoding; destroys original
2281 * \param Buf Buffor to transform
2283 int StrBufDecodeBase64(StrBuf *Buf)
2287 if (Buf == NULL) return -1;
2289 xferbuf = (char*) malloc(Buf->BufSize);
2290 siz = CtdlDecodeBase64(xferbuf,
2300 * \brief decode a buffer from base 64 encoding; destroys original
2301 * \param Buf Buffor to transform
2303 int StrBufDecodeHex(StrBuf *Buf)
2306 char *pch, *pche, *pchi;
2308 if (Buf == NULL) return -1;
2310 pch = pchi = Buf->buf;
2311 pche = pch + Buf->BufUsed;
2313 while (pchi < pche){
2314 ch = decode_hex(pchi);
2321 Buf->BufUsed = pch - Buf->buf;
2322 return Buf->BufUsed;
2326 * \brief replace all chars >0x20 && < 0x7F with Mute
2327 * \param Mute char to put over invalid chars
2328 * \param Buf Buffor to transform
2330 int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
2334 if (Buf == NULL) return -1;
2335 pch = (unsigned char *)Buf->buf;
2336 while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
2337 if ((*pch < 0x20) || (*pch > 0x7F))
2341 return Buf->BufUsed;
2346 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
2347 * \param Buf Buffer to translate
2348 * \param StripBlanks Reduce several blanks to one?
2350 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
2356 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
2357 Buf->buf[Buf->BufUsed - 1] = '\0';
2362 while (a < Buf->BufUsed) {
2363 if (Buf->buf[a] == '+')
2365 else if (Buf->buf[a] == '%') {
2366 /* don't let % chars through, rather truncate the input. */
2367 if (a + 2 > Buf->BufUsed) {
2372 hex[0] = Buf->buf[a + 1];
2373 hex[1] = Buf->buf[a + 2];
2376 sscanf(hex, "%02x", &b);
2377 Buf->buf[a] = (char) b;
2378 len = Buf->BufUsed - a - 2;
2380 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
2392 * \brief RFC2047-encode a header field if necessary.
2393 * If no non-ASCII characters are found, the string
2394 * will be copied verbatim without encoding.
2396 * \param target Target buffer.
2397 * \param source Source string to be encoded.
2398 * \returns encoded length; -1 if non success.
2400 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
2402 const char headerStr[] = "=?UTF-8?Q?";
2403 int need_to_encode = 0;
2407 if ((source == NULL) ||
2411 while ((i < source->BufUsed) &&
2412 (!IsEmptyStr (&source->buf[i])) &&
2413 (need_to_encode == 0)) {
2414 if (((unsigned char) source->buf[i] < 32) ||
2415 ((unsigned char) source->buf[i] > 126)) {
2421 if (!need_to_encode) {
2422 if (*target == NULL) {
2423 *target = NewStrBufPlain(source->buf, source->BufUsed);
2426 FlushStrBuf(*target);
2427 StrBufAppendBuf(*target, source, 0);
2429 return (*target)->BufUsed;
2431 if (*target == NULL)
2432 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
2433 else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
2434 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
2435 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
2436 (*target)->BufUsed = sizeof(headerStr) - 1;
2437 for (i=0; (i < source->BufUsed); ++i) {
2438 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2439 IncreaseBuf(*target, 1, 0);
2440 ch = (unsigned char) source->buf[i];
2441 if ((ch < 32) || (ch > 126) || (ch == 61)) {
2442 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
2443 (*target)->BufUsed += 3;
2446 (*target)->buf[(*target)->BufUsed] = ch;
2447 (*target)->BufUsed++;
2451 if ((*target)->BufUsed + 4 >= (*target)->BufSize)
2452 IncreaseBuf(*target, 1, 0);
2454 (*target)->buf[(*target)->BufUsed++] = '?';
2455 (*target)->buf[(*target)->BufUsed++] = '=';
2456 (*target)->buf[(*target)->BufUsed] = '\0';
2457 return (*target)->BufUsed;;
2461 * \brief replaces all occurances of 'search' by 'replace'
2462 * \param buf Buffer to modify
2463 * \param search character to search
2464 * \param relpace character to replace search by
2466 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
2471 for (i=0; i<buf->BufUsed; i++)
2472 if (buf->buf[i] == search)
2473 buf->buf[i] = replace;
2480 * Wrapper around iconv_open()
2481 * Our version adds aliases for non-standard Microsoft charsets
2482 * such as 'MS950', aliasing them to names like 'CP950'
2484 * tocode Target encoding
2485 * fromcode Source encoding
2487 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
2490 iconv_t ic = (iconv_t)(-1) ;
2491 ic = iconv_open(tocode, fromcode);
2492 if (ic == (iconv_t)(-1) ) {
2493 char alias_fromcode[64];
2494 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
2495 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
2496 alias_fromcode[0] = 'C';
2497 alias_fromcode[1] = 'P';
2498 ic = iconv_open(tocode, alias_fromcode);
2501 *(iconv_t *)pic = ic;
2507 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
2510 /* Find the next ?Q? */
2511 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
2514 end = strchr(bptr + 2, '?');
2519 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
2520 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
2521 (*(end + 2) == '?')) {
2522 /* skip on to the end of the cluster, the next ?= */
2523 end = strstr(end + 3, "?=");
2526 /* sort of half valid encoding, try to find an end. */
2527 end = strstr(bptr, "?=");
2531 static inline void SwapBuffers(StrBuf *A, StrBuf *B)
2535 memcpy(&C, A, sizeof(*A));
2536 memcpy(A, B, sizeof(*B));
2537 memcpy(B, &C, sizeof(C));
2541 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
2547 char *ibuf; /**< Buffer of characters to be converted */
2548 char *obuf; /**< Buffer for converted characters */
2549 size_t ibuflen; /**< Length of input buffer */
2550 size_t obuflen; /**< Length of output buffer */
2553 /* since we're converting to utf-8, one glyph may take up to 6 bytes */
2554 if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
2555 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
2557 ic = *(iconv_t*)pic;
2558 ibuf = ConvertBuf->buf;
2559 ibuflen = ConvertBuf->BufUsed;
2561 obuflen = TmpBuf->BufSize;
2563 siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
2566 if (errno == E2BIG) {
2568 IncreaseBuf(TmpBuf, 0, 0);
2573 else if (errno == EILSEQ){
2574 /* hm, invalid utf8 sequence... what to do now? */
2575 /* An invalid multibyte sequence has been encountered in the input */
2577 else if (errno == EINVAL) {
2578 /* An incomplete multibyte sequence has been encountered in the input. */
2581 FlushStrBuf(TmpBuf);
2584 TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
2585 TmpBuf->buf[TmpBuf->BufUsed] = '\0';
2587 /* little card game: wheres the red lady? */
2588 SwapBuffers(ConvertBuf, TmpBuf);
2589 FlushStrBuf(TmpBuf);
2597 inline static void DecodeSegment(StrBuf *Target,
2598 const StrBuf *DecodeMe,
2602 StrBuf *ConvertBuf2,
2603 StrBuf *FoundCharset)
2609 iconv_t ic = (iconv_t)(-1);
2611 /* Now we handle foreign character sets properly encoded
2612 * in RFC2047 format.
2614 StaticBuf.buf = SegmentStart;
2615 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
2616 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
2617 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
2618 if (FoundCharset != NULL) {
2619 FlushStrBuf(FoundCharset);
2620 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
2622 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
2623 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
2625 *encoding = toupper(*encoding);
2626 if (*encoding == 'B') { /**< base64 */
2627 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
2629 ConvertBuf->BufUsed);
2631 else if (*encoding == 'Q') { /**< quoted-printable */
2635 while (pos < ConvertBuf->BufUsed)
2637 if (ConvertBuf->buf[pos] == '_')
2638 ConvertBuf->buf[pos] = ' ';
2642 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
2645 ConvertBuf->BufUsed);
2648 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
2651 ctdl_iconv_open("UTF-8", charset, &ic);
2652 if (ic != (iconv_t)(-1) ) {
2654 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
2655 StrBufAppendBuf(Target, ConvertBuf2, 0);
2660 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
2665 * Handle subjects with RFC2047 encoding such as:
2666 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
2668 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
2670 StrBuf *ConvertBuf, *ConvertBuf2;
2671 char *start, *end, *next, *nextend, *ptr = NULL;
2673 iconv_t ic = (iconv_t)(-1) ;
2678 int illegal_non_rfc2047_encoding = 0;
2680 /* Sometimes, badly formed messages contain strings which were simply
2681 * written out directly in some foreign character set instead of
2682 * using RFC2047 encoding. This is illegal but we will attempt to
2683 * handle it anyway by converting from a user-specified default
2684 * charset to UTF-8 if we see any nonprintable characters.
2687 len = StrLength(DecodeMe);
2688 for (i=0; i<DecodeMe->BufUsed; ++i) {
2689 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
2690 illegal_non_rfc2047_encoding = 1;
2695 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
2696 if ((illegal_non_rfc2047_encoding) &&
2697 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
2698 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
2701 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
2702 if (ic != (iconv_t)(-1) ) {
2703 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
2709 /* pre evaluate the first pair */
2710 nextend = end = NULL;
2711 len = StrLength(DecodeMe);
2712 start = strstr(DecodeMe->buf, "=?");
2713 eptr = DecodeMe->buf + DecodeMe->BufUsed;
2715 end = FindNextEnd (DecodeMe, start);
2717 StrBufAppendBuf(Target, DecodeMe, 0);
2718 FreeStrBuf(&ConvertBuf);
2722 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
2724 if (start != DecodeMe->buf) {
2727 nFront = start - DecodeMe->buf;
2728 StrBufAppendBufPlain(Target, DecodeMe->buf, nFront, 0);
2732 * Since spammers will go to all sorts of absurd lengths to get their
2733 * messages through, there are LOTS of corrupt headers out there.
2734 * So, prevent a really badly formed RFC2047 header from throwing
2735 * this function into an infinite loop.
2737 while ((start != NULL) &&
2744 DecodeSegment(Target,
2752 next = strstr(end, "=?");
2754 if ((next != NULL) &&
2756 nextend = FindNextEnd(DecodeMe, next);
2757 if (nextend == NULL)
2760 /* did we find two partitions */
2761 if ((next != NULL) &&
2765 while ((ptr < next) &&
2771 /* did we find a gab just filled with blanks? */
2774 long gap = next - start;
2779 /* now terminate the gab at the end */
2780 delta = (next - end) - 2; ////TODO: const!
2781 ((StrBuf*)DecodeMe)->BufUsed -= delta;
2782 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
2784 /* move next to its new location. */
2789 /* our next-pair is our new first pair now. */
2795 nextend = DecodeMe->buf + DecodeMe->BufUsed;
2796 if ((end != NULL) && (end < nextend)) {
2798 while ( (ptr < nextend) &&
2805 StrBufAppendBufPlain(Target, end, nextend - end, 0);
2807 FreeStrBuf(&ConvertBuf);
2808 FreeStrBuf(&ConvertBuf2);
2812 * \brief evaluate the length of an utf8 special character sequence
2813 * \param Char the character to examine
2814 * \returns width of utf8 chars in bytes
2816 static inline int Ctdl_GetUtf8SequenceLength(char *CharS, char *CharE)
2821 while ((n < 8) && ((test & *CharS) != 0)) {
2825 if ((n > 6) || ((CharE - CharS) > n))
2831 * \brief detect whether this char starts an utf-8 encoded char
2832 * \param Char character to inspect
2833 * \returns yes or no
2835 static inline int Ctdl_IsUtf8SequenceStart(char Char)
2837 /** 11??.???? indicates an UTF8 Sequence. */
2838 return ((Char & 0xC0) != 0);
2842 * \brief measure the number of glyphs in an UTF8 string...
2843 * \param str string to measure
2844 * \returns the length of str
2846 long StrBuf_Utf8StrLen(StrBuf *Buf)
2852 if ((Buf == NULL) || (Buf->BufUsed == 0))
2855 eptr = Buf->buf + Buf->BufUsed;
2856 while ((aptr < eptr) && (*aptr != '\0')) {
2857 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2858 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2859 while ((aptr < eptr) && (m-- > 0) && (*aptr++ != '\0'))
2872 * \brief cuts a string after maxlen glyphs
2873 * \param str string to cut to maxlen glyphs
2874 * \param maxlen how long may the string become?
2875 * \returns pointer to maxlen or the end of the string
2877 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
2883 eptr = Buf->buf + Buf->BufUsed;
2884 while ((aptr < eptr) && (*aptr != '\0')) {
2885 if (Ctdl_IsUtf8SequenceStart(*aptr)){
2886 m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
2887 while ((m-- > 0) && (*aptr++ != '\0'))
2896 Buf->BufUsed = aptr - Buf->buf;
2897 return Buf->BufUsed;
2900 return Buf->BufUsed;
2906 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
2908 const char *aptr, *ptr, *eptr;
2915 ptr = aptr = Buf->buf;
2919 optr = LineBuf->buf;
2920 eptr = Buf->buf + Buf->BufUsed;
2921 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2923 while ((*ptr != '\n') &&
2930 LineBuf->BufUsed = optr - LineBuf->buf;
2931 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
2932 optr = LineBuf->buf + LineBuf->BufUsed;
2933 xptr = LineBuf->buf + LineBuf->BufSize - 1;
2936 LineBuf->BufUsed = optr - LineBuf->buf;
2945 return Buf->BufUsed - (ptr - Buf->buf);