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))
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;
615 * \brief extracts a substring from Source into dest
616 * \param dest buffer to place substring into
617 * \param Source string to copy substring from
618 * \param Offset chars to skip from start
619 * \param nChars number of chars to copy
620 * \returns the number of chars copied; may be different from nChars due to the size of Source
622 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
625 if (Offset > Source->BufUsed)
630 if (Offset + nChars < Source->BufUsed)
632 if (nChars > dest->BufSize)
633 IncreaseBuf(dest, 0, nChars + 1);
634 memcpy(dest->buf, Source->buf + Offset, nChars);
635 dest->BufUsed = nChars;
636 dest->buf[dest->BufUsed] = '\0';
639 NCharsRemain = Source->BufUsed - Offset;
640 if (NCharsRemain > dest->BufSize)
641 IncreaseBuf(dest, 0, NCharsRemain + 1);
642 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
643 dest->BufUsed = NCharsRemain;
644 dest->buf[dest->BufUsed] = '\0';
649 * \brief sprintf like function appending the formated string to the buffer
650 * vsnprintf version to wrap into own calls
651 * \param Buf Buffer to extend by format and params
652 * \param format printf alike format to add
653 * \param ap va_list containing the items for format
655 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
658 size_t BufSize = Buf->BufSize;
659 size_t nWritten = Buf->BufSize + 1;
660 size_t Offset = Buf->BufUsed;
661 size_t newused = Offset + nWritten;
663 while (newused >= BufSize) {
665 nWritten = vsnprintf(Buf->buf + Offset,
666 Buf->BufSize - Offset,
669 newused = Offset + nWritten;
670 if (newused >= Buf->BufSize) {
671 IncreaseBuf(Buf, 1, newused);
674 Buf->BufUsed = Offset + nWritten;
675 BufSize = Buf->BufSize;
682 * \brief sprintf like function appending the formated string to the buffer
683 * \param Buf Buffer to extend by format and params
684 * \param format printf alike format to add
685 * \param ap va_list containing the items for format
687 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
689 size_t BufSize = Buf->BufSize;
690 size_t nWritten = Buf->BufSize + 1;
691 size_t Offset = Buf->BufUsed;
692 size_t newused = Offset + nWritten;
695 while (newused >= BufSize) {
696 va_start(arg_ptr, format);
697 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
698 Buf->BufSize - Buf->BufUsed,
701 newused = Buf->BufUsed + nWritten;
702 if (newused >= Buf->BufSize) {
703 IncreaseBuf(Buf, 1, newused);
706 Buf->BufUsed += nWritten;
707 BufSize = Buf->BufSize;
714 * \brief sprintf like function putting the formated string into the buffer
715 * \param Buf Buffer to extend by format and params
716 * \param format printf alike format to add
717 * \param ap va_list containing the items for format
719 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
721 size_t nWritten = Buf->BufSize + 1;
724 while (nWritten >= Buf->BufSize) {
725 va_start(arg_ptr, format);
726 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
728 Buf->BufUsed = nWritten ;
729 if (nWritten >= Buf->BufSize)
730 IncreaseBuf(Buf, 0, 0);
736 * \brief Counts the numbmer of tokens in a buffer
737 * \param Source String to count tokens in
738 * \param tok Tokenizer char to count
739 * \returns numbers of tokenizer chars found
741 inline int StrBufNum_tokens(const StrBuf *source, char tok)
745 return num_tokens(source->buf, tok);
749 * remove_token() - a tokenizer that kills, maims, and destroys
752 * \brief a string tokenizer
753 * \param Source StringBuffer to read into
754 * \param parmnum n'th parameter to remove
755 * \param separator tokenizer param
756 * \returns -1 if not found, else length of token.
758 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
761 char *d, *s; /* dest, source */
764 /* Find desired parameter */
766 while (count < parmnum) {
767 /* End of string, bail! */
772 if (*d == separator) {
777 if (!d) return 0; /* Parameter not found */
779 /* Find next parameter */
781 while (*s && *s != separator) {
789 memmove(d, s, Source->BufUsed - (s - Source->buf));
790 Source->BufUsed -= (ReducedBy + 1);
792 else if (d == Source->buf) {
798 Source->BufUsed -= (ReducedBy + 1);
811 * \brief a string tokenizer
812 * \param dest Destination StringBuffer
813 * \param Source StringBuffer to read into
814 * \param parmnum n'th parameter to extract
815 * \param separator tokenizer param
816 * \returns -1 if not found, else length of token.
818 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
820 const char *s, *e; //* source * /
821 int len = 0; //* running total length of extracted string * /
822 int current_token = 0; //* token currently being processed * /
831 if ((Source == NULL) || (Source->BufUsed ==0)) {
835 e = s + Source->BufUsed;
838 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
840 while ((s<e) && !IsEmptyStr(s)) {
841 if (*s == separator) {
844 if (len >= dest->BufSize)
845 if (!IncreaseBuf(dest, 1, -1))
847 if ( (current_token == parmnum) &&
852 else if (current_token > parmnum) {
858 dest->buf[len] = '\0';
861 if (current_token < parmnum) {
862 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
865 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
871 * \brief a string tokenizer to fetch an integer
872 * \param dest Destination StringBuffer
873 * \param parmnum n'th parameter to extract
874 * \param separator tokenizer param
875 * \returns 0 if not found, else integer representation of the token
877 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
886 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
893 * \brief a string tokenizer to fetch a long integer
894 * \param dest Destination StringBuffer
895 * \param parmnum n'th parameter to extract
896 * \param separator tokenizer param
897 * \returns 0 if not found, else long integer representation of the token
899 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
908 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
916 * \brief a string tokenizer to fetch an unsigned long
917 * \param dest Destination StringBuffer
918 * \param parmnum n'th parameter to extract
919 * \param separator tokenizer param
920 * \returns 0 if not found, else unsigned long representation of the token
922 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
932 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
936 return (unsigned long) atol(pnum);
945 * \brief Read a line from socket
946 * flushes and closes the FD on error
947 * \param buf the buffer to get the input to
948 * \param fd pointer to the filedescriptor to read
949 * \param append Append to an existing string or replace?
950 * \param Error strerror() on error
951 * \returns numbers of chars read
953 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
960 slen = len = buf->BufUsed;
962 rlen = read(*fd, &buf->buf[len], 1);
964 *Error = strerror(errno);
971 if (buf->buf[len] == '\n')
973 if (buf->buf[len] != '\r')
975 if (!(len < buf->BufSize)) {
977 buf->buf[len+1] = '\0';
978 IncreaseBuf(buf, 1, -1);
982 buf->buf[len] = '\0';
987 * \brief Read a line from socket
988 * flushes and closes the FD on error
989 * \param buf the buffer to get the input to
990 * \param fd pointer to the filedescriptor to read
991 * \param append Append to an existing string or replace?
992 * \param Error strerror() on error
993 * \returns numbers of chars read
995 int StrBufTCP_read_buffered_line(StrBuf *Line,
999 int selectresolution,
1003 int nSuccessLess = 0;
1009 if (buf->BufUsed > 0) {
1010 pch = strchr(buf->buf, '\n');
1013 len = pch - buf->buf;
1014 if (len > 0 && (*(pch - 1) == '\r') )
1016 StrBufSub(Line, buf, 0, len - rlen);
1017 StrBufCutLeft(buf, len + 1);
1022 if (buf->BufSize - buf->BufUsed < 10)
1023 IncreaseBuf(buf, 1, -1);
1025 fdflags = fcntl(*fd, F_GETFL);
1026 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1029 while ((nSuccessLess < timeout) && (pch == NULL)) {
1030 tv.tv_sec = selectresolution;
1035 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1036 *Error = strerror(errno);
1041 if (FD_ISSET(*fd, &rfds)) {
1043 &buf->buf[buf->BufUsed],
1044 buf->BufSize - buf->BufUsed - 1);
1046 *Error = strerror(errno);
1051 else if (rlen > 0) {
1053 buf->BufUsed += rlen;
1054 buf->buf[buf->BufUsed] = '\0';
1055 if (buf->BufUsed + 10 > buf->BufSize) {
1056 IncreaseBuf(buf, 1, -1);
1058 pch = strchr(buf->buf, '\n');
1066 len = pch - buf->buf;
1067 if (len > 0 && (*(pch - 1) == '\r') )
1069 StrBufSub(Line, buf, 0, len - rlen);
1070 StrBufCutLeft(buf, len + 1);
1078 * \brief Input binary data from socket
1079 * flushes and closes the FD on error
1080 * \param buf the buffer to get the input to
1081 * \param fd pointer to the filedescriptor to read
1082 * \param append Append to an existing string or replace?
1083 * \param nBytes the maximal number of bytes to read
1084 * \param Error strerror() on error
1085 * \returns numbers of chars read
1087 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1091 int len, rlen, slen;
1095 if ((Buf == NULL) || (*fd == -1))
1099 if (Buf->BufUsed + nBytes > Buf->BufSize)
1100 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1102 ptr = Buf->buf + Buf->BufUsed;
1104 slen = len = Buf->BufUsed;
1106 fdflags = fcntl(*fd, F_GETFL);
1108 while (nRead < nBytes) {
1109 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1112 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1113 *Error = strerror(errno);
1118 if ((rlen = read(*fd,
1120 nBytes - nRead)) == -1) {
1123 *Error = strerror(errno);
1128 Buf->BufUsed += rlen;
1130 Buf->buf[Buf->BufUsed] = '\0';
1135 * \brief Cut nChars from the start of the string
1136 * \param Buf Buffer to modify
1137 * \param nChars how many chars should be skipped?
1139 void StrBufCutLeft(StrBuf *Buf, int nChars)
1141 if (nChars >= Buf->BufUsed) {
1145 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1146 Buf->BufUsed -= nChars;
1147 Buf->buf[Buf->BufUsed] = '\0';
1151 * \brief Cut the trailing n Chars from the string
1152 * \param Buf Buffer to modify
1153 * \param nChars how many chars should be trunkated?
1155 void StrBufCutRight(StrBuf *Buf, int nChars)
1157 if (nChars >= Buf->BufUsed) {
1161 Buf->BufUsed -= nChars;
1162 Buf->buf[Buf->BufUsed] = '\0';
1166 * \brief Cut the string after n Chars
1167 * \param Buf Buffer to modify
1168 * \param AfternChars after how many chars should we trunkate the string?
1169 * \param At if non-null and points inside of our string, cut it there.
1171 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1174 AfternChars = At - Buf->buf;
1177 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1179 Buf->BufUsed = AfternChars;
1180 Buf->buf[Buf->BufUsed] = '\0';
1185 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1186 * buf - the string to modify
1187 * len - length of the string.
1189 void StrBufTrim(StrBuf *Buf)
1192 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1194 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1197 if (delta > 0) StrBufCutLeft(Buf, delta);
1199 if (Buf->BufUsed == 0) return;
1200 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1203 Buf->buf[Buf->BufUsed] = '\0';
1207 void StrBufUpCase(StrBuf *Buf)
1212 pche = pch + Buf->BufUsed;
1213 while (pch < pche) {
1214 *pch = toupper(*pch);
1220 void StrBufLowerCase(StrBuf *Buf)
1225 pche = pch + Buf->BufUsed;
1226 while (pch < pche) {
1227 *pch = tolower(*pch);
1234 * \brief unhide special chars hidden to the HTML escaper
1235 * \param target buffer to put the unescaped string in
1236 * \param source buffer to unescape
1238 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1244 FlushStrBuf(target);
1246 if (source == NULL ||target == NULL)
1251 len = source->BufUsed;
1252 for (a = 0; a < len; ++a) {
1253 if (target->BufUsed >= target->BufSize)
1254 IncreaseBuf(target, 1, -1);
1256 if (source->buf[a] == '=') {
1257 hex[0] = source->buf[a + 1];
1258 hex[1] = source->buf[a + 2];
1261 sscanf(hex, "%02x", &b);
1262 target->buf[target->BufUsed] = b;
1263 target->buf[++target->BufUsed] = 0;
1267 target->buf[target->BufUsed] = source->buf[a];
1268 target->buf[++target->BufUsed] = 0;
1275 * \brief hide special chars from the HTML escapers and friends
1276 * \param target buffer to put the escaped string in
1277 * \param source buffer to escape
1279 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1284 FlushStrBuf(target);
1286 if (source == NULL ||target == NULL)
1291 len = source->BufUsed;
1292 for (i=0; i<len; ++i) {
1293 if (target->BufUsed + 4 >= target->BufSize)
1294 IncreaseBuf(target, 1, -1);
1295 if ( (isalnum(source->buf[i])) ||
1296 (source->buf[i]=='-') ||
1297 (source->buf[i]=='_') ) {
1298 target->buf[target->BufUsed++] = source->buf[i];
1301 sprintf(&target->buf[target->BufUsed],
1303 (0xFF &source->buf[i]));
1304 target->BufUsed += 3;
1307 target->buf[target->BufUsed + 1] = '\0';
1311 * \brief uses the same calling syntax as compress2(), but it
1312 * creates a stream compatible with HTTP "Content-encoding: gzip"
1315 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1316 #define OS_CODE 0x03 /*< unix */
1317 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1318 size_t * destLen, /*< length of the compresed data */
1319 const Bytef * source, /*< source to encode */
1320 uLong sourceLen, /*< length of source to encode */
1321 int level) /*< compression level */
1323 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1325 /* write gzip header */
1326 snprintf((char *) dest, *destLen,
1327 "%c%c%c%c%c%c%c%c%c%c",
1328 gz_magic[0], gz_magic[1], Z_DEFLATED,
1329 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1332 /* normal deflate */
1335 stream.next_in = (Bytef *) source;
1336 stream.avail_in = (uInt) sourceLen;
1337 stream.next_out = dest + 10L; // after header
1338 stream.avail_out = (uInt) * destLen;
1339 if ((uLong) stream.avail_out != *destLen)
1342 stream.zalloc = (alloc_func) 0;
1343 stream.zfree = (free_func) 0;
1344 stream.opaque = (voidpf) 0;
1346 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1347 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1351 err = deflate(&stream, Z_FINISH);
1352 if (err != Z_STREAM_END) {
1353 deflateEnd(&stream);
1354 return err == Z_OK ? Z_BUF_ERROR : err;
1356 *destLen = stream.total_out + 10L;
1358 /* write CRC and Length */
1359 uLong crc = crc32(0L, source, sourceLen);
1361 for (n = 0; n < 4; ++n, ++*destLen) {
1362 dest[*destLen] = (int) (crc & 0xff);
1365 uLong len = stream.total_in;
1366 for (n = 0; n < 4; ++n, ++*destLen) {
1367 dest[*destLen] = (int) (len & 0xff);
1370 err = deflateEnd(&stream);
1377 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1379 int CompressBuffer(StrBuf *Buf)
1382 char *compressed_data = NULL;
1383 size_t compressed_len, bufsize;
1385 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1386 compressed_data = malloc(compressed_len);
1388 if (compress_gzip((Bytef *) compressed_data,
1391 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1394 Buf->buf = compressed_data;
1395 Buf->BufUsed = compressed_len;
1396 Buf->BufSize = bufsize;
1399 free(compressed_data);
1401 #endif /* HAVE_ZLIB */
1406 * \brief decode a buffer from base 64 encoding; destroys original
1407 * \param Buf Buffor to transform
1409 int StrBufDecodeBase64(StrBuf *Buf)
1413 if (Buf == NULL) return -1;
1415 xferbuf = (char*) malloc(Buf->BufSize);
1416 siz = CtdlDecodeBase64(xferbuf,
1427 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1428 * \param Buf Buffer to translate
1429 * \param StripBlanks Reduce several blanks to one?
1431 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1437 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1438 Buf->buf[Buf->BufUsed - 1] = '\0';
1443 while (a < Buf->BufUsed) {
1444 if (Buf->buf[a] == '+')
1446 else if (Buf->buf[a] == '%') {
1447 /* don't let % chars through, rather truncate the input. */
1448 if (a + 2 > Buf->BufUsed) {
1453 hex[0] = Buf->buf[a + 1];
1454 hex[1] = Buf->buf[a + 2];
1457 sscanf(hex, "%02x", &b);
1458 Buf->buf[a] = (char) b;
1459 len = Buf->BufUsed - a - 2;
1461 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1473 * \brief RFC2047-encode a header field if necessary.
1474 * If no non-ASCII characters are found, the string
1475 * will be copied verbatim without encoding.
1477 * \param target Target buffer.
1478 * \param source Source string to be encoded.
1479 * \returns encoded length; -1 if non success.
1481 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1483 const char headerStr[] = "=?UTF-8?Q?";
1484 int need_to_encode = 0;
1488 if ((source == NULL) ||
1492 while ((i < source->BufUsed) &&
1493 (!IsEmptyStr (&source->buf[i])) &&
1494 (need_to_encode == 0)) {
1495 if (((unsigned char) source->buf[i] < 32) ||
1496 ((unsigned char) source->buf[i] > 126)) {
1502 if (!need_to_encode) {
1503 if (*target == NULL) {
1504 *target = NewStrBufPlain(source->buf, source->BufUsed);
1507 FlushStrBuf(*target);
1508 StrBufAppendBuf(*target, source, 0);
1510 return (*target)->BufUsed;
1512 if (*target == NULL)
1513 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1514 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1515 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1516 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1517 (*target)->BufUsed = sizeof(headerStr) - 1;
1518 for (i=0; (i < source->BufUsed); ++i) {
1519 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1520 IncreaseBuf(*target, 1, 0);
1521 ch = (unsigned char) source->buf[i];
1522 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1523 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1524 (*target)->BufUsed += 3;
1527 (*target)->buf[(*target)->BufUsed] = ch;
1528 (*target)->BufUsed++;
1532 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1533 IncreaseBuf(*target, 1, 0);
1535 (*target)->buf[(*target)->BufUsed++] = '?';
1536 (*target)->buf[(*target)->BufUsed++] = '=';
1537 (*target)->buf[(*target)->BufUsed] = '\0';
1538 return (*target)->BufUsed;;
1542 * \brief replaces all occurances of 'search' by 'replace'
1543 * \param buf Buffer to modify
1544 * \param search character to search
1545 * \param relpace character to replace search by
1547 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1552 for (i=0; i<buf->BufUsed; i++)
1553 if (buf->buf[i] == search)
1554 buf->buf[i] = replace;
1561 * Wrapper around iconv_open()
1562 * Our version adds aliases for non-standard Microsoft charsets
1563 * such as 'MS950', aliasing them to names like 'CP950'
1565 * tocode Target encoding
1566 * fromcode Source encoding
1568 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1571 iconv_t ic = (iconv_t)(-1) ;
1572 ic = iconv_open(tocode, fromcode);
1573 if (ic == (iconv_t)(-1) ) {
1574 char alias_fromcode[64];
1575 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1576 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1577 alias_fromcode[0] = 'C';
1578 alias_fromcode[1] = 'P';
1579 ic = iconv_open(tocode, alias_fromcode);
1582 *(iconv_t *)pic = ic;
1588 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1591 /* Find the next ?Q? */
1592 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1595 end = strchr(bptr + 2, '?');
1600 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1601 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1602 (*(end + 2) == '?')) {
1603 /* skip on to the end of the cluster, the next ?= */
1604 end = strstr(end + 3, "?=");
1607 /* sort of half valid encoding, try to find an end. */
1608 end = strstr(bptr, "?=");
1613 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1618 char *ibuf; /**< Buffer of characters to be converted */
1619 char *obuf; /**< Buffer for converted characters */
1620 size_t ibuflen; /**< Length of input buffer */
1621 size_t obuflen; /**< Length of output buffer */
1624 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1625 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1627 ic = *(iconv_t*)pic;
1628 ibuf = ConvertBuf->buf;
1629 ibuflen = ConvertBuf->BufUsed;
1631 obuflen = TmpBuf->BufSize;
1633 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1635 /* little card game: wheres the red lady? */
1636 ibuf = ConvertBuf->buf;
1637 BufSize = ConvertBuf->BufSize;
1639 ConvertBuf->buf = TmpBuf->buf;
1640 ConvertBuf->BufSize = TmpBuf->BufSize;
1641 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1642 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1645 TmpBuf->BufSize = BufSize;
1646 TmpBuf->BufUsed = 0;
1647 TmpBuf->buf[0] = '\0';
1654 inline static void DecodeSegment(StrBuf *Target,
1655 const StrBuf *DecodeMe,
1659 StrBuf *ConvertBuf2,
1660 StrBuf *FoundCharset)
1665 iconv_t ic = (iconv_t)(-1);
1667 /* Now we handle foreign character sets properly encoded
1668 * in RFC2047 format.
1670 StaticBuf.buf = SegmentStart;
1671 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1672 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1673 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1674 if (FoundCharset != NULL) {
1675 FlushStrBuf(FoundCharset);
1676 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1678 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1679 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1681 *encoding = toupper(*encoding);
1682 if (*encoding == 'B') { /**< base64 */
1683 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1685 ConvertBuf->BufUsed);
1687 else if (*encoding == 'Q') { /**< quoted-printable */
1691 while (pos < ConvertBuf->BufUsed)
1693 if (ConvertBuf->buf[pos] == '_')
1694 ConvertBuf->buf[pos] = ' ';
1698 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1701 ConvertBuf->BufUsed);
1704 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1707 ctdl_iconv_open("UTF-8", charset, &ic);
1708 if (ic != (iconv_t)(-1) ) {
1709 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1710 StrBufAppendBuf(Target, ConvertBuf2, 0);
1714 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1718 * Handle subjects with RFC2047 encoding such as:
1719 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1721 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1723 StrBuf *ConvertBuf, *ConvertBuf2;
1724 char *start, *end, *next, *nextend, *ptr = NULL;
1725 iconv_t ic = (iconv_t)(-1) ;
1729 int illegal_non_rfc2047_encoding = 0;
1731 /* Sometimes, badly formed messages contain strings which were simply
1732 * written out directly in some foreign character set instead of
1733 * using RFC2047 encoding. This is illegal but we will attempt to
1734 * handle it anyway by converting from a user-specified default
1735 * charset to UTF-8 if we see any nonprintable characters.
1738 len = StrLength(DecodeMe);
1739 for (i=0; i<DecodeMe->BufUsed; ++i) {
1740 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1741 illegal_non_rfc2047_encoding = 1;
1746 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1747 if ((illegal_non_rfc2047_encoding) &&
1748 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1749 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1751 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1752 if (ic != (iconv_t)(-1) ) {
1753 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1758 /* pre evaluate the first pair */
1759 nextend = end = NULL;
1760 len = StrLength(DecodeMe);
1761 start = strstr(DecodeMe->buf, "=?");
1762 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1764 end = FindNextEnd (DecodeMe, start);
1766 StrBufAppendBuf(Target, DecodeMe, 0);
1767 FreeStrBuf(&ConvertBuf);
1771 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1773 if (start != DecodeMe->buf)
1774 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1776 * Since spammers will go to all sorts of absurd lengths to get their
1777 * messages through, there are LOTS of corrupt headers out there.
1778 * So, prevent a really badly formed RFC2047 header from throwing
1779 * this function into an infinite loop.
1781 while ((start != NULL) &&
1788 DecodeSegment(Target,
1796 next = strstr(end, "=?");
1798 if ((next != NULL) &&
1800 nextend = FindNextEnd(DecodeMe, next);
1801 if (nextend == NULL)
1804 /* did we find two partitions */
1805 if ((next != NULL) &&
1809 while ((ptr < next) &&
1815 /* did we find a gab just filled with blanks? */
1820 len - (next - start));
1822 /* now terminate the gab at the end */
1823 delta = (next - end) - 2; ////TODO: const!
1824 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1825 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1827 /* move next to its new location. */
1832 /* our next-pair is our new first pair now. */
1838 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1839 if ((end != NULL) && (end < nextend)) {
1841 while ( (ptr < nextend) &&
1848 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1850 FreeStrBuf(&ConvertBuf);
1851 FreeStrBuf(&ConvertBuf2);
1856 long StrBuf_Utf8StrLen(StrBuf *Buf)
1858 return Ctdl_Utf8StrLen(Buf->buf);
1861 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1865 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1866 if (CutAt != NULL) {
1867 Buf->BufUsed = CutAt - Buf->buf;
1868 Buf->buf[Buf->BufUsed] = '\0';
1870 return Buf->BufUsed;
1875 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1877 const char *aptr, *ptr, *eptr;
1884 ptr = aptr = Buf->buf;
1888 optr = LineBuf->buf;
1889 eptr = Buf->buf + Buf->BufUsed;
1890 xptr = LineBuf->buf + LineBuf->BufSize;
1892 while ((*ptr != '\n') &&
1899 LineBuf->BufUsed = optr - LineBuf->buf;
1900 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1901 optr = LineBuf->buf + LineBuf->BufUsed;
1902 xptr = LineBuf->buf + LineBuf->BufSize;
1905 LineBuf->BufUsed = optr - LineBuf->buf;
1914 return Buf->BufUsed - (ptr - Buf->buf);