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; /**< Number 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)
275 return atol(Buf->buf);
281 * \brief Wrapper around atoi
283 int StrToi(const StrBuf *Buf)
286 return atoi(Buf->buf);
292 * \brief modifies a Single char of the Buf
293 * You can point to it via char* or a zero-based integer
294 * \param ptr char* to zero; use NULL if unused
295 * \param nThChar zero based pointer into the string; use -1 if unused
296 * \param PeekValue The Character to place into the position
298 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
303 nThChar = ptr - Buf->buf;
304 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
306 Buf->buf[nThChar] = PeekValue;
311 * \brief Append a StringBuffer to the buffer
312 * \param Buf Buffer to modify
313 * \param AppendBuf Buffer to copy at the end of our buffer
314 * \param Offset Should we start copying from an offset?
316 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
318 if ((AppendBuf == NULL) || (Buf == NULL))
321 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
324 AppendBuf->BufUsed + Buf->BufUsed);
326 memcpy(Buf->buf + Buf->BufUsed,
327 AppendBuf->buf + Offset,
328 AppendBuf->BufUsed - Offset);
329 Buf->BufUsed += AppendBuf->BufUsed - Offset;
330 Buf->buf[Buf->BufUsed] = '\0';
335 * \brief Append a C-String to the buffer
336 * \param Buf Buffer to modify
337 * \param AppendBuf Buffer to copy at the end of our buffer
338 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
339 * \param Offset Should we start copying from an offset?
341 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
344 long BufSizeRequired;
346 if ((AppendBuf == NULL) || (Buf == NULL))
350 aps = strlen(AppendBuf + Offset);
352 aps = AppendSize - Offset;
354 BufSizeRequired = Buf->BufUsed + aps + 1;
355 if (Buf->BufSize <= BufSizeRequired)
356 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
358 memcpy(Buf->buf + Buf->BufUsed,
362 Buf->buf[Buf->BufUsed] = '\0';
367 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
368 * \param outbuf the output buffer
369 * \param oblen the size of outbuf to sanitize
370 * \param strbuf the input buffer
372 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
374 const char *pch, *pche;
377 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
378 int eclen = sizeof(ec) -1;
380 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
382 if (PlainIn != NULL) {
383 len = strlen(PlainIn);
389 pche = pch + In->BufUsed;
396 pt = OutBuf->buf + OutBuf->BufUsed;
397 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
401 IncreaseBuf(OutBuf, 1, -1);
402 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
403 pt = OutBuf->buf + OutBuf->BufUsed;
407 for (b = 0; b < eclen; ++b) {
414 sprintf(pt,"%%%02X", *pch);
416 OutBuf->BufUsed += 3;
428 * \brief Append a string, escaping characters which have meaning in HTML.
430 * \param Target target buffer
431 * \param Source source buffer; set to NULL if you just have a C-String
432 * \param PlainIn Plain-C string to append; set to NULL if unused
433 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
434 * \param nolinebreaks if set, linebreaks are removed from the string.
436 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
438 const char *aptr, *eiptr;
442 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
445 if (PlainIn != NULL) {
447 len = strlen(PlainIn);
452 eiptr = aptr + Source->BufUsed;
453 len = Source->BufUsed;
459 bptr = Target->buf + Target->BufUsed;
460 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
462 while (aptr < eiptr){
464 IncreaseBuf(Target, 1, -1);
465 eptr = Target->buf + Target->BufSize - 6;
466 bptr = Target->buf + Target->BufUsed;
469 memcpy(bptr, "<", 4);
471 Target->BufUsed += 4;
473 else if (*aptr == '>') {
474 memcpy(bptr, ">", 4);
476 Target->BufUsed += 4;
478 else if (*aptr == '&') {
479 memcpy(bptr, "&", 5);
481 Target->BufUsed += 5;
483 else if (*aptr == '"') {
484 memcpy(bptr, """, 6);
486 Target->BufUsed += 6;
488 else if (*aptr == '\'') {
489 memcpy(bptr, "'", 5);
491 Target->BufUsed += 5;
493 else if (*aptr == LB) {
498 else if (*aptr == RB) {
503 else if (*aptr == QU) {
508 else if ((*aptr == 32) && (nbsp == 1)) {
509 memcpy(bptr, " ", 6);
511 Target->BufUsed += 6;
513 else if ((*aptr == '\n') && (nolinebreaks)) {
514 *bptr='\0'; /* nothing */
516 else if ((*aptr == '\r') && (nolinebreaks)) {
517 *bptr='\0'; /* nothing */
527 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
529 return Target->BufUsed;
533 * \brief Append a string, escaping characters which have meaning in HTML.
534 * Converts linebreaks into blanks; escapes single quotes
535 * \param Target target buffer
536 * \param Source source buffer; set to NULL if you just have a C-String
537 * \param PlainIn Plain-C string to append; set to NULL if unused
539 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
541 const char *aptr, *eiptr;
545 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
548 if (PlainIn != NULL) {
550 len = strlen(PlainIn);
555 eiptr = aptr + Source->BufUsed;
556 len = Source->BufUsed;
562 eptr = Target->buf + Target->BufSize - 6;
563 tptr = Target->buf + Target->BufUsed;
565 while (aptr < eiptr){
567 IncreaseBuf(Target, 1, -1);
568 eptr = Target->buf + Target->BufSize - 6;
569 tptr = Target->buf + Target->BufUsed;
576 else if (*aptr == '\r') {
580 else if (*aptr == '\'') {
586 Target->BufUsed += 5;
598 * \brief extracts a substring from Source into dest
599 * \param dest buffer to place substring into
600 * \param Source string to copy substring from
601 * \param Offset chars to skip from start
602 * \param nChars number of chars to copy
603 * \returns the number of chars copied; may be different from nChars due to the size of Source
605 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
608 if (Offset > Source->BufUsed)
613 if (Offset + nChars < Source->BufUsed)
615 if (nChars > dest->BufSize)
616 IncreaseBuf(dest, 0, nChars + 1);
617 memcpy(dest->buf, Source->buf + Offset, nChars);
618 dest->BufUsed = nChars;
619 dest->buf[dest->BufUsed] = '\0';
622 NCharsRemain = Source->BufUsed - Offset;
623 if (NCharsRemain > dest->BufSize)
624 IncreaseBuf(dest, 0, NCharsRemain + 1);
625 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
626 dest->BufUsed = NCharsRemain;
627 dest->buf[dest->BufUsed] = '\0';
632 * \brief sprintf like function appending the formated string to the buffer
633 * vsnprintf version to wrap into own calls
634 * \param Buf Buffer to extend by format and params
635 * \param format printf alike format to add
636 * \param ap va_list containing the items for format
638 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
641 size_t BufSize = Buf->BufSize;
642 size_t nWritten = Buf->BufSize + 1;
643 size_t Offset = Buf->BufUsed;
644 size_t newused = Offset + nWritten;
646 while (newused >= BufSize) {
648 nWritten = vsnprintf(Buf->buf + Offset,
649 Buf->BufSize - Offset,
652 newused = Offset + nWritten;
653 if (newused >= Buf->BufSize) {
654 IncreaseBuf(Buf, 1, newused);
657 Buf->BufUsed = Offset + nWritten;
658 BufSize = Buf->BufSize;
665 * \brief sprintf like function appending the formated string to the buffer
666 * \param Buf Buffer to extend by format and params
667 * \param format printf alike format to add
668 * \param ap va_list containing the items for format
670 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
672 size_t BufSize = Buf->BufSize;
673 size_t nWritten = Buf->BufSize + 1;
674 size_t Offset = Buf->BufUsed;
675 size_t newused = Offset + nWritten;
678 while (newused >= BufSize) {
679 va_start(arg_ptr, format);
680 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
681 Buf->BufSize - Buf->BufUsed,
684 newused = Buf->BufUsed + nWritten;
685 if (newused >= Buf->BufSize) {
686 IncreaseBuf(Buf, 1, newused);
689 Buf->BufUsed += nWritten;
690 BufSize = Buf->BufSize;
697 * \brief sprintf like function putting the formated string into the buffer
698 * \param Buf Buffer to extend by format and params
699 * \param format printf alike format to add
700 * \param ap va_list containing the items for format
702 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
704 size_t nWritten = Buf->BufSize + 1;
707 while (nWritten >= Buf->BufSize) {
708 va_start(arg_ptr, format);
709 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
711 Buf->BufUsed = nWritten ;
712 if (nWritten >= Buf->BufSize)
713 IncreaseBuf(Buf, 0, 0);
719 * \brief Counts the numbmer of tokens in a buffer
720 * \param Source String to count tokens in
721 * \param tok Tokenizer char to count
722 * \returns numbers of tokenizer chars found
724 inline int StrBufNum_tokens(const StrBuf *source, char tok)
728 return num_tokens(source->buf, tok);
732 * remove_token() - a tokenizer that kills, maims, and destroys
735 * \brief a string tokenizer
736 * \param Source StringBuffer to read into
737 * \param parmnum n'th parameter to remove
738 * \param separator tokenizer param
739 * \returns -1 if not found, else length of token.
741 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
744 char *d, *s; /* dest, source */
747 /* Find desired parameter */
749 while (count < parmnum) {
750 /* End of string, bail! */
755 if (*d == separator) {
760 if (!d) return 0; /* Parameter not found */
762 /* Find next parameter */
764 while (*s && *s != separator) {
772 memmove(d, s, Source->BufUsed - (s - Source->buf));
773 Source->BufUsed -= (ReducedBy + 1);
775 else if (d == Source->buf) {
781 Source->BufUsed -= (ReducedBy + 1);
794 * \brief a string tokenizer
795 * \param dest Destination StringBuffer
796 * \param Source StringBuffer to read into
797 * \param parmnum n'th parameter to extract
798 * \param separator tokenizer param
799 * \returns -1 if not found, else length of token.
801 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
803 const char *s, *e; //* source * /
804 int len = 0; //* running total length of extracted string * /
805 int current_token = 0; //* token currently being processed * /
807 if ((Source == NULL) || (Source->BufUsed ==0)) {
811 e = s + Source->BufUsed;
817 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
821 while ((s<e) && !IsEmptyStr(s)) {
822 if (*s == separator) {
825 if (len >= dest->BufSize)
826 if (!IncreaseBuf(dest, 1, -1))
828 if ( (current_token == parmnum) &&
833 else if (current_token > parmnum) {
839 dest->buf[len] = '\0';
842 if (current_token < parmnum) {
843 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
846 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
852 * \brief a string tokenizer to fetch an integer
853 * \param dest Destination StringBuffer
854 * \param parmnum n'th parameter to extract
855 * \param separator tokenizer param
856 * \returns 0 if not found, else integer representation of the token
858 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
867 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
874 * \brief a string tokenizer to fetch a long integer
875 * \param dest Destination StringBuffer
876 * \param parmnum n'th parameter to extract
877 * \param separator tokenizer param
878 * \returns 0 if not found, else long integer representation of the token
880 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
889 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
897 * \brief a string tokenizer to fetch an unsigned long
898 * \param dest Destination StringBuffer
899 * \param parmnum n'th parameter to extract
900 * \param separator tokenizer param
901 * \returns 0 if not found, else unsigned long representation of the token
903 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
913 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
917 return (unsigned long) atol(pnum);
926 * \brief Read a line from socket
927 * flushes and closes the FD on error
928 * \param buf the buffer to get the input to
929 * \param fd pointer to the filedescriptor to read
930 * \param append Append to an existing string or replace?
931 * \param Error strerror() on error
932 * \returns numbers of chars read
934 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
941 slen = len = buf->BufUsed;
943 rlen = read(*fd, &buf->buf[len], 1);
945 *Error = strerror(errno);
952 if (buf->buf[len] == '\n')
954 if (buf->buf[len] != '\r')
956 if (!(len < buf->BufSize)) {
958 buf->buf[len+1] = '\0';
959 IncreaseBuf(buf, 1, -1);
963 buf->buf[len] = '\0';
968 * \brief Read a line from socket
969 * flushes and closes the FD on error
970 * \param buf the buffer to get the input to
971 * \param fd pointer to the filedescriptor to read
972 * \param append Append to an existing string or replace?
973 * \param Error strerror() on error
974 * \returns numbers of chars read
976 int StrBufTCP_read_buffered_line(StrBuf *Line,
980 int selectresolution,
984 int nSuccessLess = 0;
990 if (buf->BufUsed > 0) {
991 pch = strchr(buf->buf, '\n');
994 len = pch - buf->buf;
995 if (len > 0 && (*(pch - 1) == '\r') )
997 StrBufSub(Line, buf, 0, len - rlen);
998 StrBufCutLeft(buf, len + 1);
1003 if (buf->BufSize - buf->BufUsed < 10)
1004 IncreaseBuf(buf, 1, -1);
1006 fdflags = fcntl(*fd, F_GETFL);
1007 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1010 while ((nSuccessLess < timeout) && (pch == NULL)) {
1011 tv.tv_sec = selectresolution;
1016 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1017 *Error = strerror(errno);
1022 if (FD_ISSET(*fd, &rfds)) {
1024 &buf->buf[buf->BufUsed],
1025 buf->BufSize - buf->BufUsed - 1);
1027 *Error = strerror(errno);
1032 else if (rlen > 0) {
1034 buf->BufUsed += rlen;
1035 buf->buf[buf->BufUsed] = '\0';
1036 if (buf->BufUsed + 10 > buf->BufSize) {
1037 IncreaseBuf(buf, 1, -1);
1039 pch = strchr(buf->buf, '\n');
1047 len = pch - buf->buf;
1048 if (len > 0 && (*(pch - 1) == '\r') )
1050 StrBufSub(Line, buf, 0, len - rlen);
1051 StrBufCutLeft(buf, len + 1);
1059 * \brief Input binary data from socket
1060 * flushes and closes the FD on error
1061 * \param buf the buffer to get the input to
1062 * \param fd pointer to the filedescriptor to read
1063 * \param append Append to an existing string or replace?
1064 * \param nBytes the maximal number of bytes to read
1065 * \param Error strerror() on error
1066 * \returns numbers of chars read
1068 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1072 int len, rlen, slen;
1076 if ((Buf == NULL) || (*fd == -1))
1080 if (Buf->BufUsed + nBytes > Buf->BufSize)
1081 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1083 ptr = Buf->buf + Buf->BufUsed;
1085 slen = len = Buf->BufUsed;
1087 fdflags = fcntl(*fd, F_GETFL);
1089 while (nRead < nBytes) {
1090 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1093 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1094 *Error = strerror(errno);
1099 if ((rlen = read(*fd,
1101 nBytes - nRead)) == -1) {
1104 *Error = strerror(errno);
1109 Buf->BufUsed += rlen;
1111 Buf->buf[Buf->BufUsed] = '\0';
1116 * \brief Cut nChars from the start of the string
1117 * \param Buf Buffer to modify
1118 * \param nChars how many chars should be skipped?
1120 void StrBufCutLeft(StrBuf *Buf, int nChars)
1122 if (nChars >= Buf->BufUsed) {
1126 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1127 Buf->BufUsed -= nChars;
1128 Buf->buf[Buf->BufUsed] = '\0';
1132 * \brief Cut the trailing n Chars from the string
1133 * \param Buf Buffer to modify
1134 * \param nChars how many chars should be trunkated?
1136 void StrBufCutRight(StrBuf *Buf, int nChars)
1138 if (nChars >= Buf->BufUsed) {
1142 Buf->BufUsed -= nChars;
1143 Buf->buf[Buf->BufUsed] = '\0';
1147 * \brief Cut the string after n Chars
1148 * \param Buf Buffer to modify
1149 * \param AfternChars after how many chars should we trunkate the string?
1150 * \param At if non-null and points inside of our string, cut it there.
1152 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1155 AfternChars = At - Buf->buf;
1158 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1160 Buf->BufUsed = AfternChars;
1161 Buf->buf[Buf->BufUsed] = '\0';
1166 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1167 * buf - the string to modify
1168 * len - length of the string.
1170 void StrBufTrim(StrBuf *Buf)
1173 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1175 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1178 if (delta > 0) StrBufCutLeft(Buf, delta);
1180 if (Buf->BufUsed == 0) return;
1181 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1184 Buf->buf[Buf->BufUsed] = '\0';
1188 void StrBufUpCase(StrBuf *Buf)
1193 pche = pch + Buf->BufUsed;
1194 while (pch < pche) {
1195 *pch = toupper(*pch);
1201 void StrBufLowerCase(StrBuf *Buf)
1206 pche = pch + Buf->BufUsed;
1207 while (pch < pche) {
1208 *pch = tolower(*pch);
1215 * \brief unhide special chars hidden to the HTML escaper
1216 * \param target buffer to put the unescaped string in
1217 * \param source buffer to unescape
1219 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1225 FlushStrBuf(target);
1227 if (source == NULL ||target == NULL)
1232 len = source->BufUsed;
1233 for (a = 0; a < len; ++a) {
1234 if (target->BufUsed >= target->BufSize)
1235 IncreaseBuf(target, 1, -1);
1237 if (source->buf[a] == '=') {
1238 hex[0] = source->buf[a + 1];
1239 hex[1] = source->buf[a + 2];
1242 sscanf(hex, "%02x", &b);
1243 target->buf[target->BufUsed] = b;
1244 target->buf[++target->BufUsed] = 0;
1248 target->buf[target->BufUsed] = source->buf[a];
1249 target->buf[++target->BufUsed] = 0;
1256 * \brief hide special chars from the HTML escapers and friends
1257 * \param target buffer to put the escaped string in
1258 * \param source buffer to escape
1260 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1265 FlushStrBuf(target);
1267 if (source == NULL ||target == NULL)
1272 len = source->BufUsed;
1273 for (i=0; i<len; ++i) {
1274 if (target->BufUsed + 4 >= target->BufSize)
1275 IncreaseBuf(target, 1, -1);
1276 if ( (isalnum(source->buf[i])) ||
1277 (source->buf[i]=='-') ||
1278 (source->buf[i]=='_') ) {
1279 target->buf[target->BufUsed++] = source->buf[i];
1282 sprintf(&target->buf[target->BufUsed],
1284 (0xFF &source->buf[i]));
1285 target->BufUsed += 3;
1288 target->buf[target->BufUsed + 1] = '\0';
1292 * \brief uses the same calling syntax as compress2(), but it
1293 * creates a stream compatible with HTTP "Content-encoding: gzip"
1296 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1297 #define OS_CODE 0x03 /*< unix */
1298 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1299 size_t * destLen, /*< length of the compresed data */
1300 const Bytef * source, /*< source to encode */
1301 uLong sourceLen, /*< length of source to encode */
1302 int level) /*< compression level */
1304 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1306 /* write gzip header */
1307 snprintf((char *) dest, *destLen,
1308 "%c%c%c%c%c%c%c%c%c%c",
1309 gz_magic[0], gz_magic[1], Z_DEFLATED,
1310 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1313 /* normal deflate */
1316 stream.next_in = (Bytef *) source;
1317 stream.avail_in = (uInt) sourceLen;
1318 stream.next_out = dest + 10L; // after header
1319 stream.avail_out = (uInt) * destLen;
1320 if ((uLong) stream.avail_out != *destLen)
1323 stream.zalloc = (alloc_func) 0;
1324 stream.zfree = (free_func) 0;
1325 stream.opaque = (voidpf) 0;
1327 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1328 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1332 err = deflate(&stream, Z_FINISH);
1333 if (err != Z_STREAM_END) {
1334 deflateEnd(&stream);
1335 return err == Z_OK ? Z_BUF_ERROR : err;
1337 *destLen = stream.total_out + 10L;
1339 /* write CRC and Length */
1340 uLong crc = crc32(0L, source, sourceLen);
1342 for (n = 0; n < 4; ++n, ++*destLen) {
1343 dest[*destLen] = (int) (crc & 0xff);
1346 uLong len = stream.total_in;
1347 for (n = 0; n < 4; ++n, ++*destLen) {
1348 dest[*destLen] = (int) (len & 0xff);
1351 err = deflateEnd(&stream);
1358 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1360 int CompressBuffer(StrBuf *Buf)
1363 char *compressed_data = NULL;
1364 size_t compressed_len, bufsize;
1366 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1367 compressed_data = malloc(compressed_len);
1369 if (compress_gzip((Bytef *) compressed_data,
1372 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1375 Buf->buf = compressed_data;
1376 Buf->BufUsed = compressed_len;
1377 Buf->BufSize = bufsize;
1380 free(compressed_data);
1382 #endif /* HAVE_ZLIB */
1387 * \brief decode a buffer from base 64 encoding; destroys original
1388 * \param Buf Buffor to transform
1390 int StrBufDecodeBase64(StrBuf *Buf)
1394 if (Buf == NULL) return -1;
1396 xferbuf = (char*) malloc(Buf->BufSize);
1397 siz = CtdlDecodeBase64(xferbuf,
1408 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1409 * \param Buf Buffer to translate
1410 * \param StripBlanks Reduce several blanks to one?
1412 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1418 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1419 Buf->buf[Buf->BufUsed - 1] = '\0';
1424 while (a < Buf->BufUsed) {
1425 if (Buf->buf[a] == '+')
1427 else if (Buf->buf[a] == '%') {
1428 /* don't let % chars through, rather truncate the input. */
1429 if (a + 2 > Buf->BufUsed) {
1434 hex[0] = Buf->buf[a + 1];
1435 hex[1] = Buf->buf[a + 2];
1438 sscanf(hex, "%02x", &b);
1439 Buf->buf[a] = (char) b;
1440 len = Buf->BufUsed - a - 2;
1442 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1454 * \brief RFC2047-encode a header field if necessary.
1455 * If no non-ASCII characters are found, the string
1456 * will be copied verbatim without encoding.
1458 * \param target Target buffer.
1459 * \param source Source string to be encoded.
1460 * \returns encoded length; -1 if non success.
1462 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1464 const char headerStr[] = "=?UTF-8?Q?";
1465 int need_to_encode = 0;
1469 if ((source == NULL) ||
1473 while ((i < source->BufUsed) &&
1474 (!IsEmptyStr (&source->buf[i])) &&
1475 (need_to_encode == 0)) {
1476 if (((unsigned char) source->buf[i] < 32) ||
1477 ((unsigned char) source->buf[i] > 126)) {
1483 if (!need_to_encode) {
1484 if (*target == NULL) {
1485 *target = NewStrBufPlain(source->buf, source->BufUsed);
1488 FlushStrBuf(*target);
1489 StrBufAppendBuf(*target, source, 0);
1491 return (*target)->BufUsed;
1493 if (*target == NULL)
1494 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1495 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1496 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1497 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1498 (*target)->BufUsed = sizeof(headerStr) - 1;
1499 for (i=0; (i < source->BufUsed); ++i) {
1500 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1501 IncreaseBuf(*target, 1, 0);
1502 ch = (unsigned char) source->buf[i];
1503 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1504 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1505 (*target)->BufUsed += 3;
1508 (*target)->buf[(*target)->BufUsed] = ch;
1509 (*target)->BufUsed++;
1513 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1514 IncreaseBuf(*target, 1, 0);
1516 (*target)->buf[(*target)->BufUsed++] = '?';
1517 (*target)->buf[(*target)->BufUsed++] = '=';
1518 (*target)->buf[(*target)->BufUsed] = '\0';
1519 return (*target)->BufUsed;;
1523 * \brief replaces all occurances of 'search' by 'replace'
1524 * \param buf Buffer to modify
1525 * \param search character to search
1526 * \param relpace character to replace search by
1528 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1533 for (i=0; i<buf->BufUsed; i++)
1534 if (buf->buf[i] == search)
1535 buf->buf[i] = replace;
1542 * Wrapper around iconv_open()
1543 * Our version adds aliases for non-standard Microsoft charsets
1544 * such as 'MS950', aliasing them to names like 'CP950'
1546 * tocode Target encoding
1547 * fromcode Source encoding
1549 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1552 iconv_t ic = (iconv_t)(-1) ;
1553 ic = iconv_open(tocode, fromcode);
1554 if (ic == (iconv_t)(-1) ) {
1555 char alias_fromcode[64];
1556 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1557 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1558 alias_fromcode[0] = 'C';
1559 alias_fromcode[1] = 'P';
1560 ic = iconv_open(tocode, alias_fromcode);
1563 *(iconv_t *)pic = ic;
1569 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1572 /* Find the next ?Q? */
1573 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1576 end = strchr(bptr + 2, '?');
1581 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1582 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1583 (*(end + 2) == '?')) {
1584 /* skip on to the end of the cluster, the next ?= */
1585 end = strstr(end + 3, "?=");
1588 /* sort of half valid encoding, try to find an end. */
1589 end = strstr(bptr, "?=");
1594 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1599 char *ibuf; /**< Buffer of characters to be converted */
1600 char *obuf; /**< Buffer for converted characters */
1601 size_t ibuflen; /**< Length of input buffer */
1602 size_t obuflen; /**< Length of output buffer */
1605 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1606 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1608 ic = *(iconv_t*)pic;
1609 ibuf = ConvertBuf->buf;
1610 ibuflen = ConvertBuf->BufUsed;
1612 obuflen = TmpBuf->BufSize;
1614 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1616 /* little card game: wheres the red lady? */
1617 ibuf = ConvertBuf->buf;
1618 BufSize = ConvertBuf->BufSize;
1620 ConvertBuf->buf = TmpBuf->buf;
1621 ConvertBuf->BufSize = TmpBuf->BufSize;
1622 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1623 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1626 TmpBuf->BufSize = BufSize;
1627 TmpBuf->BufUsed = 0;
1628 TmpBuf->buf[0] = '\0';
1635 inline static void DecodeSegment(StrBuf *Target,
1636 const StrBuf *DecodeMe,
1640 StrBuf *ConvertBuf2,
1641 StrBuf *FoundCharset)
1646 iconv_t ic = (iconv_t)(-1);
1648 /* Now we handle foreign character sets properly encoded
1649 * in RFC2047 format.
1651 StaticBuf.buf = SegmentStart;
1652 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1653 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1654 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1655 if (FoundCharset != NULL) {
1656 FlushStrBuf(FoundCharset);
1657 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1659 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1660 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1662 *encoding = toupper(*encoding);
1663 if (*encoding == 'B') { /**< base64 */
1664 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1666 ConvertBuf->BufUsed);
1668 else if (*encoding == 'Q') { /**< quoted-printable */
1672 while (pos < ConvertBuf->BufUsed)
1674 if (ConvertBuf->buf[pos] == '_')
1675 ConvertBuf->buf[pos] = ' ';
1679 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1682 ConvertBuf->BufUsed);
1685 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1688 ctdl_iconv_open("UTF-8", charset, &ic);
1689 if (ic != (iconv_t)(-1) ) {
1690 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1691 StrBufAppendBuf(Target, ConvertBuf2, 0);
1695 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1699 * Handle subjects with RFC2047 encoding such as:
1700 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1702 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1704 StrBuf *ConvertBuf, *ConvertBuf2;
1705 char *start, *end, *next, *nextend, *ptr = NULL;
1706 iconv_t ic = (iconv_t)(-1) ;
1710 int illegal_non_rfc2047_encoding = 0;
1712 /* Sometimes, badly formed messages contain strings which were simply
1713 * written out directly in some foreign character set instead of
1714 * using RFC2047 encoding. This is illegal but we will attempt to
1715 * handle it anyway by converting from a user-specified default
1716 * charset to UTF-8 if we see any nonprintable characters.
1719 len = StrLength(DecodeMe);
1720 for (i=0; i<DecodeMe->BufUsed; ++i) {
1721 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1722 illegal_non_rfc2047_encoding = 1;
1727 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1728 if ((illegal_non_rfc2047_encoding) &&
1729 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1730 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1732 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1733 if (ic != (iconv_t)(-1) ) {
1734 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1739 /* pre evaluate the first pair */
1740 nextend = end = NULL;
1741 len = StrLength(DecodeMe);
1742 start = strstr(DecodeMe->buf, "=?");
1743 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1745 end = FindNextEnd (DecodeMe, start);
1747 StrBufAppendBuf(Target, DecodeMe, 0);
1748 FreeStrBuf(&ConvertBuf);
1752 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1754 if (start != DecodeMe->buf)
1755 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1757 * Since spammers will go to all sorts of absurd lengths to get their
1758 * messages through, there are LOTS of corrupt headers out there.
1759 * So, prevent a really badly formed RFC2047 header from throwing
1760 * this function into an infinite loop.
1762 while ((start != NULL) &&
1769 DecodeSegment(Target,
1777 next = strstr(end, "=?");
1779 if ((next != NULL) &&
1781 nextend = FindNextEnd(DecodeMe, next);
1782 if (nextend == NULL)
1785 /* did we find two partitions */
1786 if ((next != NULL) &&
1790 while ((ptr < next) &&
1796 /* did we find a gab just filled with blanks? */
1801 len - (next - start));
1803 /* now terminate the gab at the end */
1804 delta = (next - end) - 2; ////TODO: const!
1805 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1806 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1808 /* move next to its new location. */
1813 /* our next-pair is our new first pair now. */
1819 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1820 if ((end != NULL) && (end < nextend)) {
1822 while ( (ptr < nextend) &&
1829 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1831 FreeStrBuf(&ConvertBuf);
1832 FreeStrBuf(&ConvertBuf2);
1837 long StrBuf_Utf8StrLen(StrBuf *Buf)
1839 return Ctdl_Utf8StrLen(Buf->buf);
1842 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1846 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1847 if (CutAt != NULL) {
1848 Buf->BufUsed = CutAt - Buf->buf;
1849 Buf->buf[Buf->BufUsed] = '\0';
1851 return Buf->BufUsed;
1856 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1858 const char *aptr, *ptr, *eptr;
1865 ptr = aptr = Buf->buf;
1869 optr = LineBuf->buf;
1870 eptr = Buf->buf + Buf->BufUsed;
1871 xptr = LineBuf->buf + LineBuf->BufSize;
1873 while ((*ptr != '\n') &&
1880 LineBuf->BufUsed = optr - LineBuf->buf;
1881 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1882 optr = LineBuf->buf + LineBuf->BufUsed;
1883 xptr = LineBuf->buf + LineBuf->BufSize;
1886 LineBuf->BufUsed = optr - LineBuf->buf;
1895 return Buf->BufUsed - (ptr - Buf->buf);