8 #include <sys/select.h>
10 #define SHOW_ME_VAPPEND_PRINTF
12 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
30 * Private Structure for the Stringbuffer
33 char *buf; /**< the pointer to the dynamic buffer */
34 long BufSize; /**< how many spcae do we optain */
35 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
36 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 * \Brief Cast operator to Plain String
42 * Note: if the buffer is altered by StrBuf operations, this pointer may become
43 * invalid. So don't lean on it after altering the buffer!
44 * Since this operation is considered cheap, rather call it often than risking
45 * your pointer to become invalid!
46 * \param Str the string we want to get the c-string representation for
47 * \returns the Pointer to the Content. Don't mess with it!
49 inline const char *ChrPtr(const StrBuf *Str)
57 * \brief since we know strlen()'s result, provide it here.
58 * \param Str the string to return the length to
59 * \returns contentlength of the buffer
61 inline int StrLength(const StrBuf *Str)
63 return (Str != NULL) ? Str->BufUsed : 0;
67 * \brief local utility function to resize the buffer
68 * \param Buf the buffer whichs storage we should increase
69 * \param KeepOriginal should we copy the original buffer or just start over with a new one
70 * \param DestSize what should fit in after?
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
75 size_t NewSize = Buf->BufSize * 2;
81 while (NewSize <= DestSize)
84 NewBuf= (char*) malloc(NewSize);
85 if (KeepOriginal && (Buf->BufUsed > 0))
87 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
101 * Allocate a new buffer with default buffer size
102 * \returns the new stringbuffer
104 StrBuf* NewStrBuf(void)
108 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109 NewBuf->buf = (char*) malloc(SIZ);
110 NewBuf->buf[0] = '\0';
111 NewBuf->BufSize = SIZ;
113 NewBuf->ConstBuf = 0;
118 * \brief Copy Constructor; returns a duplicate of CopyMe
119 * \params CopyMe Buffer to faxmilate
120 * \returns the new stringbuffer
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
129 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132 NewBuf->BufUsed = CopyMe->BufUsed;
133 NewBuf->BufSize = CopyMe->BufSize;
134 NewBuf->ConstBuf = 0;
139 * \brief create a new Buffer using an existing c-string
140 * this function should also be used if you want to pre-suggest
141 * the buffer size to allocate in conjunction with ptr == NULL
142 * \param ptr the c-string to copy; may be NULL to create a blank instance
143 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144 * \returns the new stringbuffer
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
152 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
154 CopySize = strlen((ptr != NULL)?ptr:"");
158 while (Siz <= CopySize)
161 NewBuf->buf = (char*) malloc(Siz);
162 NewBuf->BufSize = Siz;
164 memcpy(NewBuf->buf, ptr, CopySize);
165 NewBuf->buf[CopySize] = '\0';
166 NewBuf->BufUsed = CopySize;
169 NewBuf->buf[0] = '\0';
172 NewBuf->ConstBuf = 0;
177 * \brief Set an existing buffer from a c-string
178 * \param ptr c-string to put into
179 * \param nChars set to -1 if we should work 0-terminated
180 * \returns the new length of the string
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
184 size_t Siz = Buf->BufSize;
188 CopySize = strlen(ptr);
192 while (Siz <= CopySize)
195 if (Siz != Buf->BufSize)
196 IncreaseBuf(Buf, 0, Siz);
197 memcpy(Buf->buf, ptr, CopySize);
198 Buf->buf[CopySize] = '\0';
199 Buf->BufUsed = CopySize;
206 * \brief use strbuf as wrapper for a string constant for easy handling
207 * \param StringConstant a string to wrap
208 * \param SizeOfConstant should be sizeof(StringConstant)-1
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) StringConstant;
216 NewBuf->BufSize = SizeOfStrConstant;
217 NewBuf->BufUsed = SizeOfStrConstant;
218 NewBuf->ConstBuf = 1;
224 * \brief flush the content of a Buf; keep its struct
225 * \param buf Buffer to flush
227 int FlushStrBuf(StrBuf *buf)
239 * \brief Release a Buffer
240 * Its a double pointer, so it can NULL your pointer
241 * so fancy SIG11 appear instead of random results
242 * \param FreeMe Pointer Pointer to the buffer to free
244 void FreeStrBuf (StrBuf **FreeMe)
248 if (!(*FreeMe)->ConstBuf)
249 free((*FreeMe)->buf);
255 * \brief Release the buffer
256 * If you want put your StrBuf into a Hash, use this as Destructor.
257 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
259 void HFreeStrBuf (void *VFreeMe)
261 StrBuf *FreeMe = (StrBuf*)VFreeMe;
264 if (!FreeMe->ConstBuf)
270 * \brief Wrapper around atol
272 long StrTol(const StrBuf *Buf)
277 return atol(Buf->buf);
283 * \brief Wrapper around atoi
285 int StrToi(const StrBuf *Buf)
289 if (Buf->BufUsed > 0)
290 return atoi(Buf->buf);
295 * \brief Checks to see if the string is a pure number
297 int StrBufIsNumber(const StrBuf *Buf) {
302 strtoll(Buf->buf, &pEnd, 10);
303 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
309 * \brief modifies a Single char of the Buf
310 * You can point to it via char* or a zero-based integer
311 * \param ptr char* to zero; use NULL if unused
312 * \param nThChar zero based pointer into the string; use -1 if unused
313 * \param PeekValue The Character to place into the position
315 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
320 nThChar = ptr - Buf->buf;
321 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
323 Buf->buf[nThChar] = PeekValue;
328 * \brief Append a StringBuffer to the buffer
329 * \param Buf Buffer to modify
330 * \param AppendBuf Buffer to copy at the end of our buffer
331 * \param Offset Should we start copying from an offset?
333 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
335 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
338 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
341 AppendBuf->BufUsed + Buf->BufUsed);
343 memcpy(Buf->buf + Buf->BufUsed,
344 AppendBuf->buf + Offset,
345 AppendBuf->BufUsed - Offset);
346 Buf->BufUsed += AppendBuf->BufUsed - Offset;
347 Buf->buf[Buf->BufUsed] = '\0';
352 * \brief Append a C-String to the buffer
353 * \param Buf Buffer to modify
354 * \param AppendBuf Buffer to copy at the end of our buffer
355 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
356 * \param Offset Should we start copying from an offset?
358 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
361 long BufSizeRequired;
363 if ((AppendBuf == NULL) || (Buf == NULL))
367 aps = strlen(AppendBuf + Offset);
369 aps = AppendSize - Offset;
371 BufSizeRequired = Buf->BufUsed + aps + 1;
372 if (Buf->BufSize <= BufSizeRequired)
373 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
375 memcpy(Buf->buf + Buf->BufUsed,
379 Buf->buf[Buf->BufUsed] = '\0';
384 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
385 * \param outbuf the output buffer
386 * \param oblen the size of outbuf to sanitize
387 * \param strbuf the input buffer
389 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
391 const char *pch, *pche;
394 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
395 int eclen = sizeof(ec) -1;
397 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
399 if (PlainIn != NULL) {
400 len = strlen(PlainIn);
406 pche = pch + In->BufUsed;
413 pt = OutBuf->buf + OutBuf->BufUsed;
414 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
418 IncreaseBuf(OutBuf, 1, -1);
419 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
420 pt = OutBuf->buf + OutBuf->BufUsed;
424 for (b = 0; b < eclen; ++b) {
431 sprintf(pt,"%%%02X", *pch);
433 OutBuf->BufUsed += 3;
445 * \brief Append a string, escaping characters which have meaning in HTML.
447 * \param Target target buffer
448 * \param Source source buffer; set to NULL if you just have a C-String
449 * \param PlainIn Plain-C string to append; set to NULL if unused
450 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
451 * \param nolinebreaks if set, linebreaks are removed from the string.
453 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
455 const char *aptr, *eiptr;
459 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
462 if (PlainIn != NULL) {
464 len = strlen(PlainIn);
469 eiptr = aptr + Source->BufUsed;
470 len = Source->BufUsed;
476 bptr = Target->buf + Target->BufUsed;
477 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
479 while (aptr < eiptr){
481 IncreaseBuf(Target, 1, -1);
482 eptr = Target->buf + Target->BufSize - 6;
483 bptr = Target->buf + Target->BufUsed;
486 memcpy(bptr, "<", 4);
488 Target->BufUsed += 4;
490 else if (*aptr == '>') {
491 memcpy(bptr, ">", 4);
493 Target->BufUsed += 4;
495 else if (*aptr == '&') {
496 memcpy(bptr, "&", 5);
498 Target->BufUsed += 5;
500 else if (*aptr == '"') {
501 memcpy(bptr, """, 6);
503 Target->BufUsed += 6;
505 else if (*aptr == '\'') {
506 memcpy(bptr, "'", 5);
508 Target->BufUsed += 5;
510 else if (*aptr == LB) {
515 else if (*aptr == RB) {
520 else if (*aptr == QU) {
525 else if ((*aptr == 32) && (nbsp == 1)) {
526 memcpy(bptr, " ", 6);
528 Target->BufUsed += 6;
530 else if ((*aptr == '\n') && (nolinebreaks)) {
531 *bptr='\0'; /* nothing */
533 else if ((*aptr == '\r') && (nolinebreaks)) {
534 *bptr='\0'; /* nothing */
544 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
546 return Target->BufUsed;
550 * \brief Append a string, escaping characters which have meaning in HTML.
551 * Converts linebreaks into blanks; escapes single quotes
552 * \param Target target buffer
553 * \param Source source buffer; set to NULL if you just have a C-String
554 * \param PlainIn Plain-C string to append; set to NULL if unused
556 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
558 const char *aptr, *eiptr;
562 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
565 if (PlainIn != NULL) {
567 len = strlen(PlainIn);
572 eiptr = aptr + Source->BufUsed;
573 len = Source->BufUsed;
579 eptr = Target->buf + Target->BufSize - 6;
580 tptr = Target->buf + Target->BufUsed;
582 while (aptr < eiptr){
584 IncreaseBuf(Target, 1, -1);
585 eptr = Target->buf + Target->BufSize - 6;
586 tptr = Target->buf + Target->BufUsed;
593 else if (*aptr == '\r') {
597 else if (*aptr == '\'') {
603 Target->BufUsed += 5;
614 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
616 * \param Target target buffer
617 * \param Source source buffer; set to NULL if you just have a C-String
618 * \param PlainIn Plain-C string to append; set to NULL if unused
620 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
622 const char *aptr, *eiptr;
626 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
629 if (PlainIn != NULL) {
631 len = strlen(PlainIn);
636 eiptr = aptr + Source->BufUsed;
637 len = Source->BufUsed;
643 bptr = Target->buf + Target->BufUsed;
644 eptr = Target->buf + Target->BufSize - 2; /* our biggest unit to put in... */
646 while (aptr < eiptr){
648 IncreaseBuf(Target, 1, -1);
649 eptr = Target->buf + Target->BufSize - 2;
650 bptr = Target->buf + Target->BufUsed;
652 else if (*aptr == '"') {
653 memcpy(bptr, "\\\"", 2);
655 Target->BufUsed += 2;
657 else if (*aptr == '\'') {
658 memcpy(bptr, "\\\'", 2);
660 Target->BufUsed += 2;
661 } else if (*aptr == '\\') {
662 memcpy(bptr, "\\\\", 2);
664 Target->BufUsed += 2;
674 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
676 return Target->BufUsed;
680 * \brief extracts a substring from Source into dest
681 * \param dest buffer to place substring into
682 * \param Source string to copy substring from
683 * \param Offset chars to skip from start
684 * \param nChars number of chars to copy
685 * \returns the number of chars copied; may be different from nChars due to the size of Source
687 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
690 if (Offset > Source->BufUsed)
695 if (Offset + nChars < Source->BufUsed)
697 if (nChars > dest->BufSize)
698 IncreaseBuf(dest, 0, nChars + 1);
699 memcpy(dest->buf, Source->buf + Offset, nChars);
700 dest->BufUsed = nChars;
701 dest->buf[dest->BufUsed] = '\0';
704 NCharsRemain = Source->BufUsed - Offset;
705 if (NCharsRemain > dest->BufSize)
706 IncreaseBuf(dest, 0, NCharsRemain + 1);
707 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
708 dest->BufUsed = NCharsRemain;
709 dest->buf[dest->BufUsed] = '\0';
714 * \brief sprintf like function appending the formated string to the buffer
715 * vsnprintf version to wrap into own calls
716 * \param Buf Buffer to extend by format and params
717 * \param format printf alike format to add
718 * \param ap va_list containing the items for format
720 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
723 size_t BufSize = Buf->BufSize;
724 size_t nWritten = Buf->BufSize + 1;
725 size_t Offset = Buf->BufUsed;
726 size_t newused = Offset + nWritten;
728 while (newused >= BufSize) {
730 nWritten = vsnprintf(Buf->buf + Offset,
731 Buf->BufSize - Offset,
734 newused = Offset + nWritten;
735 if (newused >= Buf->BufSize) {
736 IncreaseBuf(Buf, 1, newused);
739 Buf->BufUsed = Offset + nWritten;
740 BufSize = Buf->BufSize;
747 * \brief sprintf like function appending the formated string to the buffer
748 * \param Buf Buffer to extend by format and params
749 * \param format printf alike format to add
750 * \param ap va_list containing the items for format
752 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
754 size_t BufSize = Buf->BufSize;
755 size_t nWritten = Buf->BufSize + 1;
756 size_t Offset = Buf->BufUsed;
757 size_t newused = Offset + nWritten;
760 while (newused >= BufSize) {
761 va_start(arg_ptr, format);
762 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
763 Buf->BufSize - Buf->BufUsed,
766 newused = Buf->BufUsed + nWritten;
767 if (newused >= Buf->BufSize) {
768 IncreaseBuf(Buf, 1, newused);
771 Buf->BufUsed += nWritten;
772 BufSize = Buf->BufSize;
779 * \brief sprintf like function putting the formated string into the buffer
780 * \param Buf Buffer to extend by format and params
781 * \param format printf alike format to add
782 * \param ap va_list containing the items for format
784 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
786 size_t nWritten = Buf->BufSize + 1;
789 while (nWritten >= Buf->BufSize) {
790 va_start(arg_ptr, format);
791 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
793 Buf->BufUsed = nWritten ;
794 if (nWritten >= Buf->BufSize)
795 IncreaseBuf(Buf, 0, 0);
801 * \brief Counts the numbmer of tokens in a buffer
802 * \param Source String to count tokens in
803 * \param tok Tokenizer char to count
804 * \returns numbers of tokenizer chars found
806 inline int StrBufNum_tokens(const StrBuf *source, char tok)
810 return num_tokens(source->buf, tok);
814 * remove_token() - a tokenizer that kills, maims, and destroys
817 * \brief a string tokenizer
818 * \param Source StringBuffer to read into
819 * \param parmnum n'th parameter to remove
820 * \param separator tokenizer param
821 * \returns -1 if not found, else length of token.
823 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
826 char *d, *s; /* dest, source */
829 /* Find desired parameter */
831 while (count < parmnum) {
832 /* End of string, bail! */
837 if (*d == separator) {
842 if (!d) return 0; /* Parameter not found */
844 /* Find next parameter */
846 while (*s && *s != separator) {
854 memmove(d, s, Source->BufUsed - (s - Source->buf));
855 Source->BufUsed -= (ReducedBy + 1);
857 else if (d == Source->buf) {
863 Source->BufUsed -= (ReducedBy + 1);
876 * \brief a string tokenizer
877 * \param dest Destination StringBuffer
878 * \param Source StringBuffer to read into
879 * \param parmnum n'th parameter to extract
880 * \param separator tokenizer param
881 * \returns -1 if not found, else length of token.
883 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
885 const char *s, *e; //* source * /
886 int len = 0; //* running total length of extracted string * /
887 int current_token = 0; //* token currently being processed * /
896 if ((Source == NULL) || (Source->BufUsed ==0)) {
900 e = s + Source->BufUsed;
903 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
905 while ((s<e) && !IsEmptyStr(s)) {
906 if (*s == separator) {
909 if (len >= dest->BufSize)
910 if (!IncreaseBuf(dest, 1, -1))
912 if ( (current_token == parmnum) &&
917 else if (current_token > parmnum) {
923 dest->buf[len] = '\0';
926 if (current_token < parmnum) {
927 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
930 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
936 * \brief a string tokenizer to fetch an integer
937 * \param dest Destination StringBuffer
938 * \param parmnum n'th parameter to extract
939 * \param separator tokenizer param
940 * \returns 0 if not found, else integer representation of the token
942 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
951 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
958 * \brief a string tokenizer to fetch a long integer
959 * \param dest Destination StringBuffer
960 * \param parmnum n'th parameter to extract
961 * \param separator tokenizer param
962 * \returns 0 if not found, else long integer representation of the token
964 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
973 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
981 * \brief a string tokenizer to fetch an unsigned long
982 * \param dest Destination StringBuffer
983 * \param parmnum n'th parameter to extract
984 * \param separator tokenizer param
985 * \returns 0 if not found, else unsigned long representation of the token
987 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
997 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
1001 return (unsigned long) atol(pnum);
1010 * \brief Read a line from socket
1011 * flushes and closes the FD on error
1012 * \param buf the buffer to get the input to
1013 * \param fd pointer to the filedescriptor to read
1014 * \param append Append to an existing string or replace?
1015 * \param Error strerror() on error
1016 * \returns numbers of chars read
1018 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1020 int len, rlen, slen;
1025 slen = len = buf->BufUsed;
1027 rlen = read(*fd, &buf->buf[len], 1);
1029 *Error = strerror(errno);
1036 if (buf->buf[len] == '\n')
1038 if (buf->buf[len] != '\r')
1040 if (!(len < buf->BufSize)) {
1042 buf->buf[len+1] = '\0';
1043 IncreaseBuf(buf, 1, -1);
1047 buf->buf[len] = '\0';
1052 * \brief Read a line from socket
1053 * flushes and closes the FD on error
1054 * \param buf the buffer to get the input to
1055 * \param fd pointer to the filedescriptor to read
1056 * \param append Append to an existing string or replace?
1057 * \param Error strerror() on error
1058 * \returns numbers of chars read
1060 int StrBufTCP_read_buffered_line(StrBuf *Line,
1064 int selectresolution,
1068 int nSuccessLess = 0;
1074 if (buf->BufUsed > 0) {
1075 pch = strchr(buf->buf, '\n');
1078 len = pch - buf->buf;
1079 if (len > 0 && (*(pch - 1) == '\r') )
1081 StrBufSub(Line, buf, 0, len - rlen);
1082 StrBufCutLeft(buf, len + 1);
1087 if (buf->BufSize - buf->BufUsed < 10)
1088 IncreaseBuf(buf, 1, -1);
1090 fdflags = fcntl(*fd, F_GETFL);
1091 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1094 while ((nSuccessLess < timeout) && (pch == NULL)) {
1095 tv.tv_sec = selectresolution;
1100 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1101 *Error = strerror(errno);
1106 if (FD_ISSET(*fd, &rfds)) {
1108 &buf->buf[buf->BufUsed],
1109 buf->BufSize - buf->BufUsed - 1);
1111 *Error = strerror(errno);
1116 else if (rlen > 0) {
1118 buf->BufUsed += rlen;
1119 buf->buf[buf->BufUsed] = '\0';
1120 if (buf->BufUsed + 10 > buf->BufSize) {
1121 IncreaseBuf(buf, 1, -1);
1123 pch = strchr(buf->buf, '\n');
1131 len = pch - buf->buf;
1132 if (len > 0 && (*(pch - 1) == '\r') )
1134 StrBufSub(Line, buf, 0, len - rlen);
1135 StrBufCutLeft(buf, len + 1);
1143 * \brief Input binary data from socket
1144 * flushes and closes the FD on error
1145 * \param buf the buffer to get the input to
1146 * \param fd pointer to the filedescriptor to read
1147 * \param append Append to an existing string or replace?
1148 * \param nBytes the maximal number of bytes to read
1149 * \param Error strerror() on error
1150 * \returns numbers of chars read
1152 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1156 int len, rlen, slen;
1160 if ((Buf == NULL) || (*fd == -1))
1164 if (Buf->BufUsed + nBytes > Buf->BufSize)
1165 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1167 ptr = Buf->buf + Buf->BufUsed;
1169 slen = len = Buf->BufUsed;
1171 fdflags = fcntl(*fd, F_GETFL);
1173 while (nRead < nBytes) {
1174 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1177 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1178 *Error = strerror(errno);
1183 if ((rlen = read(*fd,
1185 nBytes - nRead)) == -1) {
1188 *Error = strerror(errno);
1193 Buf->BufUsed += rlen;
1195 Buf->buf[Buf->BufUsed] = '\0';
1200 * \brief Cut nChars from the start of the string
1201 * \param Buf Buffer to modify
1202 * \param nChars how many chars should be skipped?
1204 void StrBufCutLeft(StrBuf *Buf, int nChars)
1206 if (nChars >= Buf->BufUsed) {
1210 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1211 Buf->BufUsed -= nChars;
1212 Buf->buf[Buf->BufUsed] = '\0';
1216 * \brief Cut the trailing n Chars from the string
1217 * \param Buf Buffer to modify
1218 * \param nChars how many chars should be trunkated?
1220 void StrBufCutRight(StrBuf *Buf, int nChars)
1222 if (nChars >= Buf->BufUsed) {
1226 Buf->BufUsed -= nChars;
1227 Buf->buf[Buf->BufUsed] = '\0';
1231 * \brief Cut the string after n Chars
1232 * \param Buf Buffer to modify
1233 * \param AfternChars after how many chars should we trunkate the string?
1234 * \param At if non-null and points inside of our string, cut it there.
1236 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1239 AfternChars = At - Buf->buf;
1242 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1244 Buf->BufUsed = AfternChars;
1245 Buf->buf[Buf->BufUsed] = '\0';
1250 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1251 * buf - the string to modify
1252 * len - length of the string.
1254 void StrBufTrim(StrBuf *Buf)
1257 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1259 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1262 if (delta > 0) StrBufCutLeft(Buf, delta);
1264 if (Buf->BufUsed == 0) return;
1265 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1268 Buf->buf[Buf->BufUsed] = '\0';
1272 void StrBufUpCase(StrBuf *Buf)
1277 pche = pch + Buf->BufUsed;
1278 while (pch < pche) {
1279 *pch = toupper(*pch);
1285 void StrBufLowerCase(StrBuf *Buf)
1290 pche = pch + Buf->BufUsed;
1291 while (pch < pche) {
1292 *pch = tolower(*pch);
1299 * \brief unhide special chars hidden to the HTML escaper
1300 * \param target buffer to put the unescaped string in
1301 * \param source buffer to unescape
1303 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1309 FlushStrBuf(target);
1311 if (source == NULL ||target == NULL)
1316 len = source->BufUsed;
1317 for (a = 0; a < len; ++a) {
1318 if (target->BufUsed >= target->BufSize)
1319 IncreaseBuf(target, 1, -1);
1321 if (source->buf[a] == '=') {
1322 hex[0] = source->buf[a + 1];
1323 hex[1] = source->buf[a + 2];
1326 sscanf(hex, "%02x", &b);
1327 target->buf[target->BufUsed] = b;
1328 target->buf[++target->BufUsed] = 0;
1332 target->buf[target->BufUsed] = source->buf[a];
1333 target->buf[++target->BufUsed] = 0;
1340 * \brief hide special chars from the HTML escapers and friends
1341 * \param target buffer to put the escaped string in
1342 * \param source buffer to escape
1344 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1349 FlushStrBuf(target);
1351 if (source == NULL ||target == NULL)
1356 len = source->BufUsed;
1357 for (i=0; i<len; ++i) {
1358 if (target->BufUsed + 4 >= target->BufSize)
1359 IncreaseBuf(target, 1, -1);
1360 if ( (isalnum(source->buf[i])) ||
1361 (source->buf[i]=='-') ||
1362 (source->buf[i]=='_') ) {
1363 target->buf[target->BufUsed++] = source->buf[i];
1366 sprintf(&target->buf[target->BufUsed],
1368 (0xFF &source->buf[i]));
1369 target->BufUsed += 3;
1372 target->buf[target->BufUsed + 1] = '\0';
1376 * \brief uses the same calling syntax as compress2(), but it
1377 * creates a stream compatible with HTTP "Content-encoding: gzip"
1380 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1381 #define OS_CODE 0x03 /*< unix */
1382 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1383 size_t * destLen, /*< length of the compresed data */
1384 const Bytef * source, /*< source to encode */
1385 uLong sourceLen, /*< length of source to encode */
1386 int level) /*< compression level */
1388 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1390 /* write gzip header */
1391 snprintf((char *) dest, *destLen,
1392 "%c%c%c%c%c%c%c%c%c%c",
1393 gz_magic[0], gz_magic[1], Z_DEFLATED,
1394 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1397 /* normal deflate */
1400 stream.next_in = (Bytef *) source;
1401 stream.avail_in = (uInt) sourceLen;
1402 stream.next_out = dest + 10L; // after header
1403 stream.avail_out = (uInt) * destLen;
1404 if ((uLong) stream.avail_out != *destLen)
1407 stream.zalloc = (alloc_func) 0;
1408 stream.zfree = (free_func) 0;
1409 stream.opaque = (voidpf) 0;
1411 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1412 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1416 err = deflate(&stream, Z_FINISH);
1417 if (err != Z_STREAM_END) {
1418 deflateEnd(&stream);
1419 return err == Z_OK ? Z_BUF_ERROR : err;
1421 *destLen = stream.total_out + 10L;
1423 /* write CRC and Length */
1424 uLong crc = crc32(0L, source, sourceLen);
1426 for (n = 0; n < 4; ++n, ++*destLen) {
1427 dest[*destLen] = (int) (crc & 0xff);
1430 uLong len = stream.total_in;
1431 for (n = 0; n < 4; ++n, ++*destLen) {
1432 dest[*destLen] = (int) (len & 0xff);
1435 err = deflateEnd(&stream);
1442 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1444 int CompressBuffer(StrBuf *Buf)
1447 char *compressed_data = NULL;
1448 size_t compressed_len, bufsize;
1450 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1451 compressed_data = malloc(compressed_len);
1453 if (compress_gzip((Bytef *) compressed_data,
1456 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1459 Buf->buf = compressed_data;
1460 Buf->BufUsed = compressed_len;
1461 Buf->BufSize = bufsize;
1464 free(compressed_data);
1466 #endif /* HAVE_ZLIB */
1471 * \brief decode a buffer from base 64 encoding; destroys original
1472 * \param Buf Buffor to transform
1474 int StrBufDecodeBase64(StrBuf *Buf)
1478 if (Buf == NULL) return -1;
1480 xferbuf = (char*) malloc(Buf->BufSize);
1481 siz = CtdlDecodeBase64(xferbuf,
1492 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1493 * \param Buf Buffer to translate
1494 * \param StripBlanks Reduce several blanks to one?
1496 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1502 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1503 Buf->buf[Buf->BufUsed - 1] = '\0';
1508 while (a < Buf->BufUsed) {
1509 if (Buf->buf[a] == '+')
1511 else if (Buf->buf[a] == '%') {
1512 /* don't let % chars through, rather truncate the input. */
1513 if (a + 2 > Buf->BufUsed) {
1518 hex[0] = Buf->buf[a + 1];
1519 hex[1] = Buf->buf[a + 2];
1522 sscanf(hex, "%02x", &b);
1523 Buf->buf[a] = (char) b;
1524 len = Buf->BufUsed - a - 2;
1526 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1538 * \brief RFC2047-encode a header field if necessary.
1539 * If no non-ASCII characters are found, the string
1540 * will be copied verbatim without encoding.
1542 * \param target Target buffer.
1543 * \param source Source string to be encoded.
1544 * \returns encoded length; -1 if non success.
1546 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1548 const char headerStr[] = "=?UTF-8?Q?";
1549 int need_to_encode = 0;
1553 if ((source == NULL) ||
1557 while ((i < source->BufUsed) &&
1558 (!IsEmptyStr (&source->buf[i])) &&
1559 (need_to_encode == 0)) {
1560 if (((unsigned char) source->buf[i] < 32) ||
1561 ((unsigned char) source->buf[i] > 126)) {
1567 if (!need_to_encode) {
1568 if (*target == NULL) {
1569 *target = NewStrBufPlain(source->buf, source->BufUsed);
1572 FlushStrBuf(*target);
1573 StrBufAppendBuf(*target, source, 0);
1575 return (*target)->BufUsed;
1577 if (*target == NULL)
1578 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1579 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1580 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1581 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1582 (*target)->BufUsed = sizeof(headerStr) - 1;
1583 for (i=0; (i < source->BufUsed); ++i) {
1584 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1585 IncreaseBuf(*target, 1, 0);
1586 ch = (unsigned char) source->buf[i];
1587 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1588 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1589 (*target)->BufUsed += 3;
1592 (*target)->buf[(*target)->BufUsed] = ch;
1593 (*target)->BufUsed++;
1597 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1598 IncreaseBuf(*target, 1, 0);
1600 (*target)->buf[(*target)->BufUsed++] = '?';
1601 (*target)->buf[(*target)->BufUsed++] = '=';
1602 (*target)->buf[(*target)->BufUsed] = '\0';
1603 return (*target)->BufUsed;;
1607 * \brief replaces all occurances of 'search' by 'replace'
1608 * \param buf Buffer to modify
1609 * \param search character to search
1610 * \param relpace character to replace search by
1612 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1617 for (i=0; i<buf->BufUsed; i++)
1618 if (buf->buf[i] == search)
1619 buf->buf[i] = replace;
1626 * Wrapper around iconv_open()
1627 * Our version adds aliases for non-standard Microsoft charsets
1628 * such as 'MS950', aliasing them to names like 'CP950'
1630 * tocode Target encoding
1631 * fromcode Source encoding
1633 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1636 iconv_t ic = (iconv_t)(-1) ;
1637 ic = iconv_open(tocode, fromcode);
1638 if (ic == (iconv_t)(-1) ) {
1639 char alias_fromcode[64];
1640 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1641 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1642 alias_fromcode[0] = 'C';
1643 alias_fromcode[1] = 'P';
1644 ic = iconv_open(tocode, alias_fromcode);
1647 *(iconv_t *)pic = ic;
1653 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1656 /* Find the next ?Q? */
1657 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1660 end = strchr(bptr + 2, '?');
1665 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1666 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1667 (*(end + 2) == '?')) {
1668 /* skip on to the end of the cluster, the next ?= */
1669 end = strstr(end + 3, "?=");
1672 /* sort of half valid encoding, try to find an end. */
1673 end = strstr(bptr, "?=");
1678 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1683 char *ibuf; /**< Buffer of characters to be converted */
1684 char *obuf; /**< Buffer for converted characters */
1685 size_t ibuflen; /**< Length of input buffer */
1686 size_t obuflen; /**< Length of output buffer */
1689 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1690 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1692 ic = *(iconv_t*)pic;
1693 ibuf = ConvertBuf->buf;
1694 ibuflen = ConvertBuf->BufUsed;
1696 obuflen = TmpBuf->BufSize;
1698 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1700 /* little card game: wheres the red lady? */
1701 ibuf = ConvertBuf->buf;
1702 BufSize = ConvertBuf->BufSize;
1704 ConvertBuf->buf = TmpBuf->buf;
1705 ConvertBuf->BufSize = TmpBuf->BufSize;
1706 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1707 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1710 TmpBuf->BufSize = BufSize;
1711 TmpBuf->BufUsed = 0;
1712 TmpBuf->buf[0] = '\0';
1719 inline static void DecodeSegment(StrBuf *Target,
1720 const StrBuf *DecodeMe,
1724 StrBuf *ConvertBuf2,
1725 StrBuf *FoundCharset)
1730 iconv_t ic = (iconv_t)(-1);
1732 /* Now we handle foreign character sets properly encoded
1733 * in RFC2047 format.
1735 StaticBuf.buf = SegmentStart;
1736 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1737 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1738 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1739 if (FoundCharset != NULL) {
1740 FlushStrBuf(FoundCharset);
1741 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1743 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1744 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1746 *encoding = toupper(*encoding);
1747 if (*encoding == 'B') { /**< base64 */
1748 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1750 ConvertBuf->BufUsed);
1752 else if (*encoding == 'Q') { /**< quoted-printable */
1756 while (pos < ConvertBuf->BufUsed)
1758 if (ConvertBuf->buf[pos] == '_')
1759 ConvertBuf->buf[pos] = ' ';
1763 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1766 ConvertBuf->BufUsed);
1769 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1772 ctdl_iconv_open("UTF-8", charset, &ic);
1773 if (ic != (iconv_t)(-1) ) {
1774 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1775 StrBufAppendBuf(Target, ConvertBuf2, 0);
1779 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1783 * Handle subjects with RFC2047 encoding such as:
1784 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1786 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1788 StrBuf *ConvertBuf, *ConvertBuf2;
1789 char *start, *end, *next, *nextend, *ptr = NULL;
1790 iconv_t ic = (iconv_t)(-1) ;
1794 int illegal_non_rfc2047_encoding = 0;
1796 /* Sometimes, badly formed messages contain strings which were simply
1797 * written out directly in some foreign character set instead of
1798 * using RFC2047 encoding. This is illegal but we will attempt to
1799 * handle it anyway by converting from a user-specified default
1800 * charset to UTF-8 if we see any nonprintable characters.
1803 len = StrLength(DecodeMe);
1804 for (i=0; i<DecodeMe->BufUsed; ++i) {
1805 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1806 illegal_non_rfc2047_encoding = 1;
1811 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1812 if ((illegal_non_rfc2047_encoding) &&
1813 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1814 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1816 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1817 if (ic != (iconv_t)(-1) ) {
1818 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1823 /* pre evaluate the first pair */
1824 nextend = end = NULL;
1825 len = StrLength(DecodeMe);
1826 start = strstr(DecodeMe->buf, "=?");
1827 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1829 end = FindNextEnd (DecodeMe, start);
1831 StrBufAppendBuf(Target, DecodeMe, 0);
1832 FreeStrBuf(&ConvertBuf);
1836 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1838 if (start != DecodeMe->buf)
1839 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1841 * Since spammers will go to all sorts of absurd lengths to get their
1842 * messages through, there are LOTS of corrupt headers out there.
1843 * So, prevent a really badly formed RFC2047 header from throwing
1844 * this function into an infinite loop.
1846 while ((start != NULL) &&
1853 DecodeSegment(Target,
1861 next = strstr(end, "=?");
1863 if ((next != NULL) &&
1865 nextend = FindNextEnd(DecodeMe, next);
1866 if (nextend == NULL)
1869 /* did we find two partitions */
1870 if ((next != NULL) &&
1874 while ((ptr < next) &&
1880 /* did we find a gab just filled with blanks? */
1885 len - (next - start));
1887 /* now terminate the gab at the end */
1888 delta = (next - end) - 2; ////TODO: const!
1889 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1890 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1892 /* move next to its new location. */
1897 /* our next-pair is our new first pair now. */
1903 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1904 if ((end != NULL) && (end < nextend)) {
1906 while ( (ptr < nextend) &&
1913 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1915 FreeStrBuf(&ConvertBuf);
1916 FreeStrBuf(&ConvertBuf2);
1921 long StrBuf_Utf8StrLen(StrBuf *Buf)
1923 return Ctdl_Utf8StrLen(Buf->buf);
1926 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1930 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1931 if (CutAt != NULL) {
1932 Buf->BufUsed = CutAt - Buf->buf;
1933 Buf->buf[Buf->BufUsed] = '\0';
1935 return Buf->BufUsed;
1940 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1942 const char *aptr, *ptr, *eptr;
1949 ptr = aptr = Buf->buf;
1953 optr = LineBuf->buf;
1954 eptr = Buf->buf + Buf->BufUsed;
1955 xptr = LineBuf->buf + LineBuf->BufSize;
1957 while ((*ptr != '\n') &&
1964 LineBuf->BufUsed = optr - LineBuf->buf;
1965 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1966 optr = LineBuf->buf + LineBuf->BufUsed;
1967 xptr = LineBuf->buf + LineBuf->BufSize;
1970 LineBuf->BufUsed = optr - LineBuf->buf;
1979 return Buf->BufUsed - (ptr - Buf->buf);