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)
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);
296 * \brief modifies a Single char of the Buf
297 * You can point to it via char* or a zero-based integer
298 * \param ptr char* to zero; use NULL if unused
299 * \param nThChar zero based pointer into the string; use -1 if unused
300 * \param PeekValue The Character to place into the position
302 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
307 nThChar = ptr - Buf->buf;
308 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
310 Buf->buf[nThChar] = PeekValue;
315 * \brief Append a StringBuffer to the buffer
316 * \param Buf Buffer to modify
317 * \param AppendBuf Buffer to copy at the end of our buffer
318 * \param Offset Should we start copying from an offset?
320 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
322 if ((AppendBuf == NULL) || (Buf == NULL))
325 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
328 AppendBuf->BufUsed + Buf->BufUsed);
330 memcpy(Buf->buf + Buf->BufUsed,
331 AppendBuf->buf + Offset,
332 AppendBuf->BufUsed - Offset);
333 Buf->BufUsed += AppendBuf->BufUsed - Offset;
334 Buf->buf[Buf->BufUsed] = '\0';
339 * \brief Append a C-String to the buffer
340 * \param Buf Buffer to modify
341 * \param AppendBuf Buffer to copy at the end of our buffer
342 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
343 * \param Offset Should we start copying from an offset?
345 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
348 long BufSizeRequired;
350 if ((AppendBuf == NULL) || (Buf == NULL))
354 aps = strlen(AppendBuf + Offset);
356 aps = AppendSize - Offset;
358 BufSizeRequired = Buf->BufUsed + aps + 1;
359 if (Buf->BufSize <= BufSizeRequired)
360 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
362 memcpy(Buf->buf + Buf->BufUsed,
366 Buf->buf[Buf->BufUsed] = '\0';
371 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
372 * \param outbuf the output buffer
373 * \param oblen the size of outbuf to sanitize
374 * \param strbuf the input buffer
376 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
378 const char *pch, *pche;
381 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
382 int eclen = sizeof(ec) -1;
384 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
386 if (PlainIn != NULL) {
387 len = strlen(PlainIn);
393 pche = pch + In->BufUsed;
400 pt = OutBuf->buf + OutBuf->BufUsed;
401 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
405 IncreaseBuf(OutBuf, 1, -1);
406 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
407 pt = OutBuf->buf + OutBuf->BufUsed;
411 for (b = 0; b < eclen; ++b) {
418 sprintf(pt,"%%%02X", *pch);
420 OutBuf->BufUsed += 3;
432 * \brief Append a string, escaping characters which have meaning in HTML.
434 * \param Target target buffer
435 * \param Source source buffer; set to NULL if you just have a C-String
436 * \param PlainIn Plain-C string to append; set to NULL if unused
437 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
438 * \param nolinebreaks if set, linebreaks are removed from the string.
440 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
442 const char *aptr, *eiptr;
446 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
449 if (PlainIn != NULL) {
451 len = strlen(PlainIn);
456 eiptr = aptr + Source->BufUsed;
457 len = Source->BufUsed;
463 bptr = Target->buf + Target->BufUsed;
464 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
466 while (aptr < eiptr){
468 IncreaseBuf(Target, 1, -1);
469 eptr = Target->buf + Target->BufSize - 6;
470 bptr = Target->buf + Target->BufUsed;
473 memcpy(bptr, "<", 4);
475 Target->BufUsed += 4;
477 else if (*aptr == '>') {
478 memcpy(bptr, ">", 4);
480 Target->BufUsed += 4;
482 else if (*aptr == '&') {
483 memcpy(bptr, "&", 5);
485 Target->BufUsed += 5;
487 else if (*aptr == '"') {
488 memcpy(bptr, """, 6);
490 Target->BufUsed += 6;
492 else if (*aptr == '\'') {
493 memcpy(bptr, "'", 5);
495 Target->BufUsed += 5;
497 else if (*aptr == LB) {
502 else if (*aptr == RB) {
507 else if (*aptr == QU) {
512 else if ((*aptr == 32) && (nbsp == 1)) {
513 memcpy(bptr, " ", 6);
515 Target->BufUsed += 6;
517 else if ((*aptr == '\n') && (nolinebreaks)) {
518 *bptr='\0'; /* nothing */
520 else if ((*aptr == '\r') && (nolinebreaks)) {
521 *bptr='\0'; /* nothing */
531 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
533 return Target->BufUsed;
537 * \brief Append a string, escaping characters which have meaning in HTML.
538 * Converts linebreaks into blanks; escapes single quotes
539 * \param Target target buffer
540 * \param Source source buffer; set to NULL if you just have a C-String
541 * \param PlainIn Plain-C string to append; set to NULL if unused
543 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
545 const char *aptr, *eiptr;
549 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
552 if (PlainIn != NULL) {
554 len = strlen(PlainIn);
559 eiptr = aptr + Source->BufUsed;
560 len = Source->BufUsed;
566 eptr = Target->buf + Target->BufSize - 6;
567 tptr = Target->buf + Target->BufUsed;
569 while (aptr < eiptr){
571 IncreaseBuf(Target, 1, -1);
572 eptr = Target->buf + Target->BufSize - 6;
573 tptr = Target->buf + Target->BufUsed;
580 else if (*aptr == '\r') {
584 else if (*aptr == '\'') {
590 Target->BufUsed += 5;
602 * \brief extracts a substring from Source into dest
603 * \param dest buffer to place substring into
604 * \param Source string to copy substring from
605 * \param Offset chars to skip from start
606 * \param nChars number of chars to copy
607 * \returns the number of chars copied; may be different from nChars due to the size of Source
609 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
612 if (Offset > Source->BufUsed)
617 if (Offset + nChars < Source->BufUsed)
619 if (nChars > dest->BufSize)
620 IncreaseBuf(dest, 0, nChars + 1);
621 memcpy(dest->buf, Source->buf + Offset, nChars);
622 dest->BufUsed = nChars;
623 dest->buf[dest->BufUsed] = '\0';
626 NCharsRemain = Source->BufUsed - Offset;
627 if (NCharsRemain > dest->BufSize)
628 IncreaseBuf(dest, 0, NCharsRemain + 1);
629 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
630 dest->BufUsed = NCharsRemain;
631 dest->buf[dest->BufUsed] = '\0';
636 * \brief sprintf like function appending the formated string to the buffer
637 * vsnprintf version to wrap into own calls
638 * \param Buf Buffer to extend by format and params
639 * \param format printf alike format to add
640 * \param ap va_list containing the items for format
642 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
645 size_t BufSize = Buf->BufSize;
646 size_t nWritten = Buf->BufSize + 1;
647 size_t Offset = Buf->BufUsed;
648 size_t newused = Offset + nWritten;
650 while (newused >= BufSize) {
652 nWritten = vsnprintf(Buf->buf + Offset,
653 Buf->BufSize - Offset,
656 newused = Offset + nWritten;
657 if (newused >= Buf->BufSize) {
658 IncreaseBuf(Buf, 1, newused);
661 Buf->BufUsed = Offset + nWritten;
662 BufSize = Buf->BufSize;
669 * \brief sprintf like function appending the formated string to the buffer
670 * \param Buf Buffer to extend by format and params
671 * \param format printf alike format to add
672 * \param ap va_list containing the items for format
674 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
676 size_t BufSize = Buf->BufSize;
677 size_t nWritten = Buf->BufSize + 1;
678 size_t Offset = Buf->BufUsed;
679 size_t newused = Offset + nWritten;
682 while (newused >= BufSize) {
683 va_start(arg_ptr, format);
684 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
685 Buf->BufSize - Buf->BufUsed,
688 newused = Buf->BufUsed + nWritten;
689 if (newused >= Buf->BufSize) {
690 IncreaseBuf(Buf, 1, newused);
693 Buf->BufUsed += nWritten;
694 BufSize = Buf->BufSize;
701 * \brief sprintf like function putting the formated string into the buffer
702 * \param Buf Buffer to extend by format and params
703 * \param format printf alike format to add
704 * \param ap va_list containing the items for format
706 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
708 size_t nWritten = Buf->BufSize + 1;
711 while (nWritten >= Buf->BufSize) {
712 va_start(arg_ptr, format);
713 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
715 Buf->BufUsed = nWritten ;
716 if (nWritten >= Buf->BufSize)
717 IncreaseBuf(Buf, 0, 0);
723 * \brief Counts the numbmer of tokens in a buffer
724 * \param Source String to count tokens in
725 * \param tok Tokenizer char to count
726 * \returns numbers of tokenizer chars found
728 inline int StrBufNum_tokens(const StrBuf *source, char tok)
732 return num_tokens(source->buf, tok);
736 * remove_token() - a tokenizer that kills, maims, and destroys
739 * \brief a string tokenizer
740 * \param Source StringBuffer to read into
741 * \param parmnum n'th parameter to remove
742 * \param separator tokenizer param
743 * \returns -1 if not found, else length of token.
745 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
748 char *d, *s; /* dest, source */
751 /* Find desired parameter */
753 while (count < parmnum) {
754 /* End of string, bail! */
759 if (*d == separator) {
764 if (!d) return 0; /* Parameter not found */
766 /* Find next parameter */
768 while (*s && *s != separator) {
776 memmove(d, s, Source->BufUsed - (s - Source->buf));
777 Source->BufUsed -= (ReducedBy + 1);
779 else if (d == Source->buf) {
785 Source->BufUsed -= (ReducedBy + 1);
798 * \brief a string tokenizer
799 * \param dest Destination StringBuffer
800 * \param Source StringBuffer to read into
801 * \param parmnum n'th parameter to extract
802 * \param separator tokenizer param
803 * \returns -1 if not found, else length of token.
805 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
807 const char *s, *e; //* source * /
808 int len = 0; //* running total length of extracted string * /
809 int current_token = 0; //* token currently being processed * /
811 if ((Source == NULL) || (Source->BufUsed ==0)) {
815 e = s + Source->BufUsed;
821 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
825 while ((s<e) && !IsEmptyStr(s)) {
826 if (*s == separator) {
829 if (len >= dest->BufSize)
830 if (!IncreaseBuf(dest, 1, -1))
832 if ( (current_token == parmnum) &&
837 else if (current_token > parmnum) {
843 dest->buf[len] = '\0';
846 if (current_token < parmnum) {
847 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
850 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
856 * \brief a string tokenizer to fetch an integer
857 * \param dest Destination StringBuffer
858 * \param parmnum n'th parameter to extract
859 * \param separator tokenizer param
860 * \returns 0 if not found, else integer representation of the token
862 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
871 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
878 * \brief a string tokenizer to fetch a long integer
879 * \param dest Destination StringBuffer
880 * \param parmnum n'th parameter to extract
881 * \param separator tokenizer param
882 * \returns 0 if not found, else long integer representation of the token
884 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
893 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
901 * \brief a string tokenizer to fetch an unsigned long
902 * \param dest Destination StringBuffer
903 * \param parmnum n'th parameter to extract
904 * \param separator tokenizer param
905 * \returns 0 if not found, else unsigned long representation of the token
907 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
917 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
921 return (unsigned long) atol(pnum);
930 * \brief Read a line from socket
931 * flushes and closes the FD on error
932 * \param buf the buffer to get the input to
933 * \param fd pointer to the filedescriptor to read
934 * \param append Append to an existing string or replace?
935 * \param Error strerror() on error
936 * \returns numbers of chars read
938 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
945 slen = len = buf->BufUsed;
947 rlen = read(*fd, &buf->buf[len], 1);
949 *Error = strerror(errno);
956 if (buf->buf[len] == '\n')
958 if (buf->buf[len] != '\r')
960 if (!(len < buf->BufSize)) {
962 buf->buf[len+1] = '\0';
963 IncreaseBuf(buf, 1, -1);
967 buf->buf[len] = '\0';
972 * \brief Read a line from socket
973 * flushes and closes the FD on error
974 * \param buf the buffer to get the input to
975 * \param fd pointer to the filedescriptor to read
976 * \param append Append to an existing string or replace?
977 * \param Error strerror() on error
978 * \returns numbers of chars read
980 int StrBufTCP_read_buffered_line(StrBuf *Line,
984 int selectresolution,
988 int nSuccessLess = 0;
994 if (buf->BufUsed > 0) {
995 pch = strchr(buf->buf, '\n');
998 len = pch - buf->buf;
999 if (len > 0 && (*(pch - 1) == '\r') )
1001 StrBufSub(Line, buf, 0, len - rlen);
1002 StrBufCutLeft(buf, len + 1);
1007 if (buf->BufSize - buf->BufUsed < 10)
1008 IncreaseBuf(buf, 1, -1);
1010 fdflags = fcntl(*fd, F_GETFL);
1011 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1014 while ((nSuccessLess < timeout) && (pch == NULL)) {
1015 tv.tv_sec = selectresolution;
1020 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1021 *Error = strerror(errno);
1026 if (FD_ISSET(*fd, &rfds)) {
1028 &buf->buf[buf->BufUsed],
1029 buf->BufSize - buf->BufUsed - 1);
1031 *Error = strerror(errno);
1036 else if (rlen > 0) {
1038 buf->BufUsed += rlen;
1039 buf->buf[buf->BufUsed] = '\0';
1040 if (buf->BufUsed + 10 > buf->BufSize) {
1041 IncreaseBuf(buf, 1, -1);
1043 pch = strchr(buf->buf, '\n');
1051 len = pch - buf->buf;
1052 if (len > 0 && (*(pch - 1) == '\r') )
1054 StrBufSub(Line, buf, 0, len - rlen);
1055 StrBufCutLeft(buf, len + 1);
1063 * \brief Input binary data from socket
1064 * flushes and closes the FD on error
1065 * \param buf the buffer to get the input to
1066 * \param fd pointer to the filedescriptor to read
1067 * \param append Append to an existing string or replace?
1068 * \param nBytes the maximal number of bytes to read
1069 * \param Error strerror() on error
1070 * \returns numbers of chars read
1072 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1076 int len, rlen, slen;
1080 if ((Buf == NULL) || (*fd == -1))
1084 if (Buf->BufUsed + nBytes > Buf->BufSize)
1085 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1087 ptr = Buf->buf + Buf->BufUsed;
1089 slen = len = Buf->BufUsed;
1091 fdflags = fcntl(*fd, F_GETFL);
1093 while (nRead < nBytes) {
1094 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1097 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1098 *Error = strerror(errno);
1103 if ((rlen = read(*fd,
1105 nBytes - nRead)) == -1) {
1108 *Error = strerror(errno);
1113 Buf->BufUsed += rlen;
1115 Buf->buf[Buf->BufUsed] = '\0';
1120 * \brief Cut nChars from the start of the string
1121 * \param Buf Buffer to modify
1122 * \param nChars how many chars should be skipped?
1124 void StrBufCutLeft(StrBuf *Buf, int nChars)
1126 if (nChars >= Buf->BufUsed) {
1130 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1131 Buf->BufUsed -= nChars;
1132 Buf->buf[Buf->BufUsed] = '\0';
1136 * \brief Cut the trailing n Chars from the string
1137 * \param Buf Buffer to modify
1138 * \param nChars how many chars should be trunkated?
1140 void StrBufCutRight(StrBuf *Buf, int nChars)
1142 if (nChars >= Buf->BufUsed) {
1146 Buf->BufUsed -= nChars;
1147 Buf->buf[Buf->BufUsed] = '\0';
1151 * \brief Cut the string after n Chars
1152 * \param Buf Buffer to modify
1153 * \param AfternChars after how many chars should we trunkate the string?
1154 * \param At if non-null and points inside of our string, cut it there.
1156 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1159 AfternChars = At - Buf->buf;
1162 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1164 Buf->BufUsed = AfternChars;
1165 Buf->buf[Buf->BufUsed] = '\0';
1170 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1171 * buf - the string to modify
1172 * len - length of the string.
1174 void StrBufTrim(StrBuf *Buf)
1177 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1179 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1182 if (delta > 0) StrBufCutLeft(Buf, delta);
1184 if (Buf->BufUsed == 0) return;
1185 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1188 Buf->buf[Buf->BufUsed] = '\0';
1192 void StrBufUpCase(StrBuf *Buf)
1197 pche = pch + Buf->BufUsed;
1198 while (pch < pche) {
1199 *pch = toupper(*pch);
1205 void StrBufLowerCase(StrBuf *Buf)
1210 pche = pch + Buf->BufUsed;
1211 while (pch < pche) {
1212 *pch = tolower(*pch);
1219 * \brief unhide special chars hidden to the HTML escaper
1220 * \param target buffer to put the unescaped string in
1221 * \param source buffer to unescape
1223 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1229 FlushStrBuf(target);
1231 if (source == NULL ||target == NULL)
1236 len = source->BufUsed;
1237 for (a = 0; a < len; ++a) {
1238 if (target->BufUsed >= target->BufSize)
1239 IncreaseBuf(target, 1, -1);
1241 if (source->buf[a] == '=') {
1242 hex[0] = source->buf[a + 1];
1243 hex[1] = source->buf[a + 2];
1246 sscanf(hex, "%02x", &b);
1247 target->buf[target->BufUsed] = b;
1248 target->buf[++target->BufUsed] = 0;
1252 target->buf[target->BufUsed] = source->buf[a];
1253 target->buf[++target->BufUsed] = 0;
1260 * \brief hide special chars from the HTML escapers and friends
1261 * \param target buffer to put the escaped string in
1262 * \param source buffer to escape
1264 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1269 FlushStrBuf(target);
1271 if (source == NULL ||target == NULL)
1276 len = source->BufUsed;
1277 for (i=0; i<len; ++i) {
1278 if (target->BufUsed + 4 >= target->BufSize)
1279 IncreaseBuf(target, 1, -1);
1280 if ( (isalnum(source->buf[i])) ||
1281 (source->buf[i]=='-') ||
1282 (source->buf[i]=='_') ) {
1283 target->buf[target->BufUsed++] = source->buf[i];
1286 sprintf(&target->buf[target->BufUsed],
1288 (0xFF &source->buf[i]));
1289 target->BufUsed += 3;
1292 target->buf[target->BufUsed + 1] = '\0';
1296 * \brief uses the same calling syntax as compress2(), but it
1297 * creates a stream compatible with HTTP "Content-encoding: gzip"
1300 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1301 #define OS_CODE 0x03 /*< unix */
1302 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1303 size_t * destLen, /*< length of the compresed data */
1304 const Bytef * source, /*< source to encode */
1305 uLong sourceLen, /*< length of source to encode */
1306 int level) /*< compression level */
1308 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1310 /* write gzip header */
1311 snprintf((char *) dest, *destLen,
1312 "%c%c%c%c%c%c%c%c%c%c",
1313 gz_magic[0], gz_magic[1], Z_DEFLATED,
1314 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1317 /* normal deflate */
1320 stream.next_in = (Bytef *) source;
1321 stream.avail_in = (uInt) sourceLen;
1322 stream.next_out = dest + 10L; // after header
1323 stream.avail_out = (uInt) * destLen;
1324 if ((uLong) stream.avail_out != *destLen)
1327 stream.zalloc = (alloc_func) 0;
1328 stream.zfree = (free_func) 0;
1329 stream.opaque = (voidpf) 0;
1331 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1332 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1336 err = deflate(&stream, Z_FINISH);
1337 if (err != Z_STREAM_END) {
1338 deflateEnd(&stream);
1339 return err == Z_OK ? Z_BUF_ERROR : err;
1341 *destLen = stream.total_out + 10L;
1343 /* write CRC and Length */
1344 uLong crc = crc32(0L, source, sourceLen);
1346 for (n = 0; n < 4; ++n, ++*destLen) {
1347 dest[*destLen] = (int) (crc & 0xff);
1350 uLong len = stream.total_in;
1351 for (n = 0; n < 4; ++n, ++*destLen) {
1352 dest[*destLen] = (int) (len & 0xff);
1355 err = deflateEnd(&stream);
1362 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1364 int CompressBuffer(StrBuf *Buf)
1367 char *compressed_data = NULL;
1368 size_t compressed_len, bufsize;
1370 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1371 compressed_data = malloc(compressed_len);
1373 if (compress_gzip((Bytef *) compressed_data,
1376 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1379 Buf->buf = compressed_data;
1380 Buf->BufUsed = compressed_len;
1381 Buf->BufSize = bufsize;
1384 free(compressed_data);
1386 #endif /* HAVE_ZLIB */
1391 * \brief decode a buffer from base 64 encoding; destroys original
1392 * \param Buf Buffor to transform
1394 int StrBufDecodeBase64(StrBuf *Buf)
1398 if (Buf == NULL) return -1;
1400 xferbuf = (char*) malloc(Buf->BufSize);
1401 siz = CtdlDecodeBase64(xferbuf,
1412 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1413 * \param Buf Buffer to translate
1414 * \param StripBlanks Reduce several blanks to one?
1416 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1422 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1423 Buf->buf[Buf->BufUsed - 1] = '\0';
1428 while (a < Buf->BufUsed) {
1429 if (Buf->buf[a] == '+')
1431 else if (Buf->buf[a] == '%') {
1432 /* don't let % chars through, rather truncate the input. */
1433 if (a + 2 > Buf->BufUsed) {
1438 hex[0] = Buf->buf[a + 1];
1439 hex[1] = Buf->buf[a + 2];
1442 sscanf(hex, "%02x", &b);
1443 Buf->buf[a] = (char) b;
1444 len = Buf->BufUsed - a - 2;
1446 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1458 * \brief RFC2047-encode a header field if necessary.
1459 * If no non-ASCII characters are found, the string
1460 * will be copied verbatim without encoding.
1462 * \param target Target buffer.
1463 * \param source Source string to be encoded.
1464 * \returns encoded length; -1 if non success.
1466 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1468 const char headerStr[] = "=?UTF-8?Q?";
1469 int need_to_encode = 0;
1473 if ((source == NULL) ||
1477 while ((i < source->BufUsed) &&
1478 (!IsEmptyStr (&source->buf[i])) &&
1479 (need_to_encode == 0)) {
1480 if (((unsigned char) source->buf[i] < 32) ||
1481 ((unsigned char) source->buf[i] > 126)) {
1487 if (!need_to_encode) {
1488 if (*target == NULL) {
1489 *target = NewStrBufPlain(source->buf, source->BufUsed);
1492 FlushStrBuf(*target);
1493 StrBufAppendBuf(*target, source, 0);
1495 return (*target)->BufUsed;
1497 if (*target == NULL)
1498 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1499 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1500 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1501 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1502 (*target)->BufUsed = sizeof(headerStr) - 1;
1503 for (i=0; (i < source->BufUsed); ++i) {
1504 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1505 IncreaseBuf(*target, 1, 0);
1506 ch = (unsigned char) source->buf[i];
1507 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1508 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1509 (*target)->BufUsed += 3;
1512 (*target)->buf[(*target)->BufUsed] = ch;
1513 (*target)->BufUsed++;
1517 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1518 IncreaseBuf(*target, 1, 0);
1520 (*target)->buf[(*target)->BufUsed++] = '?';
1521 (*target)->buf[(*target)->BufUsed++] = '=';
1522 (*target)->buf[(*target)->BufUsed] = '\0';
1523 return (*target)->BufUsed;;
1527 * \brief replaces all occurances of 'search' by 'replace'
1528 * \param buf Buffer to modify
1529 * \param search character to search
1530 * \param relpace character to replace search by
1532 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1537 for (i=0; i<buf->BufUsed; i++)
1538 if (buf->buf[i] == search)
1539 buf->buf[i] = replace;
1546 * Wrapper around iconv_open()
1547 * Our version adds aliases for non-standard Microsoft charsets
1548 * such as 'MS950', aliasing them to names like 'CP950'
1550 * tocode Target encoding
1551 * fromcode Source encoding
1553 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1556 iconv_t ic = (iconv_t)(-1) ;
1557 ic = iconv_open(tocode, fromcode);
1558 if (ic == (iconv_t)(-1) ) {
1559 char alias_fromcode[64];
1560 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1561 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1562 alias_fromcode[0] = 'C';
1563 alias_fromcode[1] = 'P';
1564 ic = iconv_open(tocode, alias_fromcode);
1567 *(iconv_t *)pic = ic;
1573 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1576 /* Find the next ?Q? */
1577 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1580 end = strchr(bptr + 2, '?');
1585 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1586 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1587 (*(end + 2) == '?')) {
1588 /* skip on to the end of the cluster, the next ?= */
1589 end = strstr(end + 3, "?=");
1592 /* sort of half valid encoding, try to find an end. */
1593 end = strstr(bptr, "?=");
1598 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1603 char *ibuf; /**< Buffer of characters to be converted */
1604 char *obuf; /**< Buffer for converted characters */
1605 size_t ibuflen; /**< Length of input buffer */
1606 size_t obuflen; /**< Length of output buffer */
1609 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1610 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1612 ic = *(iconv_t*)pic;
1613 ibuf = ConvertBuf->buf;
1614 ibuflen = ConvertBuf->BufUsed;
1616 obuflen = TmpBuf->BufSize;
1618 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1620 /* little card game: wheres the red lady? */
1621 ibuf = ConvertBuf->buf;
1622 BufSize = ConvertBuf->BufSize;
1624 ConvertBuf->buf = TmpBuf->buf;
1625 ConvertBuf->BufSize = TmpBuf->BufSize;
1626 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1627 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1630 TmpBuf->BufSize = BufSize;
1631 TmpBuf->BufUsed = 0;
1632 TmpBuf->buf[0] = '\0';
1639 inline static void DecodeSegment(StrBuf *Target,
1640 const StrBuf *DecodeMe,
1644 StrBuf *ConvertBuf2,
1645 StrBuf *FoundCharset)
1650 iconv_t ic = (iconv_t)(-1);
1652 /* Now we handle foreign character sets properly encoded
1653 * in RFC2047 format.
1655 StaticBuf.buf = SegmentStart;
1656 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1657 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1658 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1659 if (FoundCharset != NULL) {
1660 FlushStrBuf(FoundCharset);
1661 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1663 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1664 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1666 *encoding = toupper(*encoding);
1667 if (*encoding == 'B') { /**< base64 */
1668 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1670 ConvertBuf->BufUsed);
1672 else if (*encoding == 'Q') { /**< quoted-printable */
1676 while (pos < ConvertBuf->BufUsed)
1678 if (ConvertBuf->buf[pos] == '_')
1679 ConvertBuf->buf[pos] = ' ';
1683 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1686 ConvertBuf->BufUsed);
1689 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1692 ctdl_iconv_open("UTF-8", charset, &ic);
1693 if (ic != (iconv_t)(-1) ) {
1694 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1695 StrBufAppendBuf(Target, ConvertBuf2, 0);
1699 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1703 * Handle subjects with RFC2047 encoding such as:
1704 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1706 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1708 StrBuf *ConvertBuf, *ConvertBuf2;
1709 char *start, *end, *next, *nextend, *ptr = NULL;
1710 iconv_t ic = (iconv_t)(-1) ;
1714 int illegal_non_rfc2047_encoding = 0;
1716 /* Sometimes, badly formed messages contain strings which were simply
1717 * written out directly in some foreign character set instead of
1718 * using RFC2047 encoding. This is illegal but we will attempt to
1719 * handle it anyway by converting from a user-specified default
1720 * charset to UTF-8 if we see any nonprintable characters.
1723 len = StrLength(DecodeMe);
1724 for (i=0; i<DecodeMe->BufUsed; ++i) {
1725 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1726 illegal_non_rfc2047_encoding = 1;
1731 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1732 if ((illegal_non_rfc2047_encoding) &&
1733 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1734 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1736 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1737 if (ic != (iconv_t)(-1) ) {
1738 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1743 /* pre evaluate the first pair */
1744 nextend = end = NULL;
1745 len = StrLength(DecodeMe);
1746 start = strstr(DecodeMe->buf, "=?");
1747 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1749 end = FindNextEnd (DecodeMe, start);
1751 StrBufAppendBuf(Target, DecodeMe, 0);
1752 FreeStrBuf(&ConvertBuf);
1756 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1758 if (start != DecodeMe->buf)
1759 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1761 * Since spammers will go to all sorts of absurd lengths to get their
1762 * messages through, there are LOTS of corrupt headers out there.
1763 * So, prevent a really badly formed RFC2047 header from throwing
1764 * this function into an infinite loop.
1766 while ((start != NULL) &&
1773 DecodeSegment(Target,
1781 next = strstr(end, "=?");
1783 if ((next != NULL) &&
1785 nextend = FindNextEnd(DecodeMe, next);
1786 if (nextend == NULL)
1789 /* did we find two partitions */
1790 if ((next != NULL) &&
1794 while ((ptr < next) &&
1800 /* did we find a gab just filled with blanks? */
1805 len - (next - start));
1807 /* now terminate the gab at the end */
1808 delta = (next - end) - 2; ////TODO: const!
1809 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1810 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1812 /* move next to its new location. */
1817 /* our next-pair is our new first pair now. */
1823 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1824 if ((end != NULL) && (end < nextend)) {
1826 while ( (ptr < nextend) &&
1833 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1835 FreeStrBuf(&ConvertBuf);
1836 FreeStrBuf(&ConvertBuf2);
1841 long StrBuf_Utf8StrLen(StrBuf *Buf)
1843 return Ctdl_Utf8StrLen(Buf->buf);
1846 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1850 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1851 if (CutAt != NULL) {
1852 Buf->BufUsed = CutAt - Buf->buf;
1853 Buf->buf[Buf->BufUsed] = '\0';
1855 return Buf->BufUsed;
1860 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1862 const char *aptr, *ptr, *eptr;
1869 ptr = aptr = Buf->buf;
1873 optr = LineBuf->buf;
1874 eptr = Buf->buf + Buf->BufUsed;
1875 xptr = LineBuf->buf + LineBuf->BufSize;
1877 while ((*ptr != '\n') &&
1884 LineBuf->BufUsed = optr - LineBuf->buf;
1885 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1886 optr = LineBuf->buf + LineBuf->BufUsed;
1887 xptr = LineBuf->buf + LineBuf->BufSize;
1890 LineBuf->BufUsed = optr - LineBuf->buf;
1899 return Buf->BufUsed - (ptr - Buf->buf);