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)
345 if ((AppendBuf == NULL) || (Buf == NULL))
349 aps = strlen(AppendBuf + Offset);
351 aps = AppendSize - Offset;
353 if (Buf->BufSize < Buf->BufUsed + aps + 1)
354 IncreaseBuf(Buf, (Buf->BufUsed > 0), Buf->BufUsed + aps + 1);
356 memcpy(Buf->buf + Buf->BufUsed,
360 Buf->buf[Buf->BufUsed] = '\0';
365 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
366 * \param outbuf the output buffer
367 * \param oblen the size of outbuf to sanitize
368 * \param strbuf the input buffer
370 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
372 const char *pch, *pche;
375 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
376 int eclen = sizeof(ec) -1;
378 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
380 if (PlainIn != NULL) {
381 len = strlen(PlainIn);
387 pche = pch + In->BufUsed;
394 pt = OutBuf->buf + OutBuf->BufUsed;
395 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
399 IncreaseBuf(OutBuf, 1, -1);
400 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
401 pt = OutBuf->buf + OutBuf->BufUsed;
405 for (b = 0; b < eclen; ++b) {
412 sprintf(pt,"%%%02X", *pch);
414 OutBuf->BufUsed += 3;
426 * \brief Append a string, escaping characters which have meaning in HTML.
428 * \param Target target buffer
429 * \param Source source buffer; set to NULL if you just have a C-String
430 * \param PlainIn Plain-C string to append; set to NULL if unused
431 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
432 * \param nolinebreaks if set, linebreaks are removed from the string.
434 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
436 const char *aptr, *eiptr;
440 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
443 if (PlainIn != NULL) {
445 len = strlen(PlainIn);
450 eiptr = aptr + Source->BufUsed;
451 len = Source->BufUsed;
457 bptr = Target->buf + Target->BufUsed;
458 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
460 while (aptr < eiptr){
462 IncreaseBuf(Target, 1, -1);
463 eptr = Target->buf + Target->BufSize - 6;
464 bptr = Target->buf + Target->BufUsed;
467 memcpy(bptr, "<", 4);
469 Target->BufUsed += 4;
471 else if (*aptr == '>') {
472 memcpy(bptr, ">", 4);
474 Target->BufUsed += 4;
476 else if (*aptr == '&') {
477 memcpy(bptr, "&", 5);
479 Target->BufUsed += 5;
481 else if (*aptr == '\"') {
482 memcpy(bptr, """, 6);
484 Target->BufUsed += 6;
486 else if (*aptr == '\'') {
487 memcpy(bptr, "'", 5);
489 Target->BufUsed += 5;
491 else if (*aptr == LB) {
496 else if (*aptr == RB) {
501 else if (*aptr == QU) {
506 else if ((*aptr == 32) && (nbsp == 1)) {
507 memcpy(bptr, " ", 6);
509 Target->BufUsed += 6;
511 else if ((*aptr == '\n') && (nolinebreaks)) {
512 *bptr='\0'; /* nothing */
514 else if ((*aptr == '\r') && (nolinebreaks)) {
515 *bptr='\0'; /* nothing */
525 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
527 return Target->BufUsed;
531 * \brief Append a string, escaping characters which have meaning in HTML.
532 * Converts linebreaks into blanks; escapes single quotes
533 * \param Target target buffer
534 * \param Source source buffer; set to NULL if you just have a C-String
535 * \param PlainIn Plain-C string to append; set to NULL if unused
537 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
539 const char *aptr, *eiptr;
543 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
546 if (PlainIn != NULL) {
548 len = strlen(PlainIn);
553 eiptr = aptr + Source->BufUsed;
554 len = Source->BufUsed;
560 eptr = Target->buf + Target->BufSize - 6;
561 tptr = Target->buf + Target->BufUsed;
563 while (aptr < eiptr){
565 IncreaseBuf(Target, 1, -1);
566 eptr = Target->buf + Target->BufSize - 6;
567 tptr = Target->buf + Target->BufUsed;
574 else if (*aptr == '\r') {
578 else if (*aptr == '\'') {
584 Target->BufUsed += 5;
596 * \brief extracts a substring from Source into dest
597 * \param dest buffer to place substring into
598 * \param Source string to copy substring from
599 * \param Offset chars to skip from start
600 * \param nChars number of chars to copy
601 * \returns the number of chars copied; may be different from nChars due to the size of Source
603 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
606 if (Offset > Source->BufUsed)
611 if (Offset + nChars < Source->BufUsed)
613 if (nChars > dest->BufSize)
614 IncreaseBuf(dest, 0, nChars + 1);
615 memcpy(dest->buf, Source->buf + Offset, nChars);
616 dest->BufUsed = nChars;
617 dest->buf[dest->BufUsed] = '\0';
620 NCharsRemain = Source->BufUsed - Offset;
621 if (NCharsRemain > dest->BufSize)
622 IncreaseBuf(dest, 0, NCharsRemain + 1);
623 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
624 dest->BufUsed = NCharsRemain;
625 dest->buf[dest->BufUsed] = '\0';
630 * \brief sprintf like function appending the formated string to the buffer
631 * vsnprintf version to wrap into own calls
632 * \param Buf Buffer to extend by format and params
633 * \param format printf alike format to add
634 * \param ap va_list containing the items for format
636 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
639 size_t BufSize = Buf->BufSize;
640 size_t nWritten = Buf->BufSize + 1;
641 size_t Offset = Buf->BufUsed;
642 size_t newused = Offset + nWritten;
644 while (newused >= BufSize) {
646 nWritten = vsnprintf(Buf->buf + Offset,
647 Buf->BufSize - Offset,
650 newused = Offset + nWritten;
651 if (newused >= Buf->BufSize) {
652 IncreaseBuf(Buf, 1, newused);
655 Buf->BufUsed = Offset + nWritten;
656 BufSize = Buf->BufSize;
663 * \brief sprintf like function appending the formated string to the buffer
664 * \param Buf Buffer to extend by format and params
665 * \param format printf alike format to add
666 * \param ap va_list containing the items for format
668 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
670 size_t BufSize = Buf->BufSize;
671 size_t nWritten = Buf->BufSize + 1;
672 size_t Offset = Buf->BufUsed;
673 size_t newused = Offset + nWritten;
676 while (newused >= BufSize) {
677 va_start(arg_ptr, format);
678 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
679 Buf->BufSize - Buf->BufUsed,
682 newused = Buf->BufUsed + nWritten;
683 if (newused >= Buf->BufSize) {
684 IncreaseBuf(Buf, 1, newused);
687 Buf->BufUsed += nWritten;
688 BufSize = Buf->BufSize;
695 * \brief sprintf like function putting the formated string into the buffer
696 * \param Buf Buffer to extend by format and params
697 * \param format printf alike format to add
698 * \param ap va_list containing the items for format
700 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
702 size_t nWritten = Buf->BufSize + 1;
705 while (nWritten >= Buf->BufSize) {
706 va_start(arg_ptr, format);
707 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
709 Buf->BufUsed = nWritten ;
710 if (nWritten >= Buf->BufSize)
711 IncreaseBuf(Buf, 0, 0);
717 * \brief Counts the numbmer of tokens in a buffer
718 * \param Source String to count tokens in
719 * \param tok Tokenizer char to count
720 * \returns numbers of tokenizer chars found
722 inline int StrBufNum_tokens(const StrBuf *source, char tok)
726 return num_tokens(source->buf, tok);
730 * remove_token() - a tokenizer that kills, maims, and destroys
733 * \brief a string tokenizer
734 * \param Source StringBuffer to read into
735 * \param parmnum n'th parameter to remove
736 * \param separator tokenizer param
737 * \returns -1 if not found, else length of token.
739 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
742 char *d, *s; /* dest, source */
745 /* Find desired parameter */
747 while (count < parmnum) {
748 /* End of string, bail! */
753 if (*d == separator) {
758 if (!d) return 0; /* Parameter not found */
760 /* Find next parameter */
762 while (*s && *s != separator) {
770 memmove(d, s, Source->BufUsed - (s - Source->buf));
771 Source->BufUsed -= (ReducedBy + 1);
773 else if (d == Source->buf) {
779 Source->BufUsed -= (ReducedBy + 1);
792 * \brief a string tokenizer
793 * \param dest Destination StringBuffer
794 * \param Source StringBuffer to read into
795 * \param parmnum n'th parameter to extract
796 * \param separator tokenizer param
797 * \returns -1 if not found, else length of token.
799 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
801 const char *s, *e; //* source * /
802 int len = 0; //* running total length of extracted string * /
803 int current_token = 0; //* token currently being processed * /
805 if ((Source == NULL) || (Source->BufUsed ==0)) {
809 e = s + Source->BufUsed;
815 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
819 while ((s<e) && !IsEmptyStr(s)) {
820 if (*s == separator) {
823 if (len >= dest->BufSize)
824 if (!IncreaseBuf(dest, 1, -1))
826 if ( (current_token == parmnum) &&
831 else if (current_token > parmnum) {
837 dest->buf[len] = '\0';
840 if (current_token < parmnum) {
841 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
844 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
850 * \brief a string tokenizer to fetch an integer
851 * \param dest Destination StringBuffer
852 * \param parmnum n'th parameter to extract
853 * \param separator tokenizer param
854 * \returns 0 if not found, else integer representation of the token
856 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
865 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
872 * \brief a string tokenizer to fetch a long integer
873 * \param dest Destination StringBuffer
874 * \param parmnum n'th parameter to extract
875 * \param separator tokenizer param
876 * \returns 0 if not found, else long integer representation of the token
878 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
887 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
895 * \brief a string tokenizer to fetch an unsigned long
896 * \param dest Destination StringBuffer
897 * \param parmnum n'th parameter to extract
898 * \param separator tokenizer param
899 * \returns 0 if not found, else unsigned long representation of the token
901 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
911 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
915 return (unsigned long) atol(pnum);
924 * \brief Read a line from socket
925 * flushes and closes the FD on error
926 * \param buf the buffer to get the input to
927 * \param fd pointer to the filedescriptor to read
928 * \param append Append to an existing string or replace?
929 * \param Error strerror() on error
930 * \returns numbers of chars read
932 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
939 slen = len = buf->BufUsed;
941 rlen = read(*fd, &buf->buf[len], 1);
943 *Error = strerror(errno);
950 if (buf->buf[len] == '\n')
952 if (buf->buf[len] != '\r')
954 if (!(len < buf->BufSize)) {
956 buf->buf[len+1] = '\0';
957 IncreaseBuf(buf, 1, -1);
961 buf->buf[len] = '\0';
966 * \brief Read a line from socket
967 * flushes and closes the FD on error
968 * \param buf the buffer to get the input to
969 * \param fd pointer to the filedescriptor to read
970 * \param append Append to an existing string or replace?
971 * \param Error strerror() on error
972 * \returns numbers of chars read
974 int StrBufTCP_read_buffered_line(StrBuf *Line,
978 int selectresolution,
982 int nSuccessLess = 0;
988 if (buf->BufUsed > 0) {
989 pch = strchr(buf->buf, '\n');
992 len = pch - buf->buf;
993 if (len > 0 && (*(pch - 1) == '\r') )
995 StrBufSub(Line, buf, 0, len - rlen);
996 StrBufCutLeft(buf, len + 1);
1001 if (buf->BufSize - buf->BufUsed < 10)
1002 IncreaseBuf(buf, 1, -1);
1004 fdflags = fcntl(*fd, F_GETFL);
1005 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1008 while ((nSuccessLess < timeout) && (pch == NULL)) {
1009 tv.tv_sec = selectresolution;
1014 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1015 *Error = strerror(errno);
1020 if (FD_ISSET(*fd, &rfds)) {
1022 &buf->buf[buf->BufUsed],
1023 buf->BufSize - buf->BufUsed - 1);
1025 *Error = strerror(errno);
1030 else if (rlen > 0) {
1032 buf->BufUsed += rlen;
1033 buf->buf[buf->BufUsed] = '\0';
1034 if (buf->BufUsed + 10 > buf->BufSize) {
1035 IncreaseBuf(buf, 1, -1);
1037 pch = strchr(buf->buf, '\n');
1045 len = pch - buf->buf;
1046 if (len > 0 && (*(pch - 1) == '\r') )
1048 StrBufSub(Line, buf, 0, len - rlen);
1049 StrBufCutLeft(buf, len + 1);
1057 * \brief Input binary data from socket
1058 * flushes and closes the FD on error
1059 * \param buf the buffer to get the input to
1060 * \param fd pointer to the filedescriptor to read
1061 * \param append Append to an existing string or replace?
1062 * \param nBytes the maximal number of bytes to read
1063 * \param Error strerror() on error
1064 * \returns numbers of chars read
1066 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1070 int len, rlen, slen;
1074 if ((Buf == NULL) || (*fd == -1))
1078 if (Buf->BufUsed + nBytes > Buf->BufSize)
1079 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1081 ptr = Buf->buf + Buf->BufUsed;
1083 slen = len = Buf->BufUsed;
1085 fdflags = fcntl(*fd, F_GETFL);
1087 while (nRead < nBytes) {
1088 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1091 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1092 *Error = strerror(errno);
1097 if ((rlen = read(*fd,
1099 nBytes - nRead)) == -1) {
1102 *Error = strerror(errno);
1107 Buf->BufUsed += rlen;
1109 Buf->buf[Buf->BufUsed] = '\0';
1114 * \brief Cut nChars from the start of the string
1115 * \param Buf Buffer to modify
1116 * \param nChars how many chars should be skipped?
1118 void StrBufCutLeft(StrBuf *Buf, int nChars)
1120 if (nChars >= Buf->BufUsed) {
1124 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1125 Buf->BufUsed -= nChars;
1126 Buf->buf[Buf->BufUsed] = '\0';
1130 * \brief Cut the trailing n Chars from the string
1131 * \param Buf Buffer to modify
1132 * \param nChars how many chars should be trunkated?
1134 void StrBufCutRight(StrBuf *Buf, int nChars)
1136 if (nChars >= Buf->BufUsed) {
1140 Buf->BufUsed -= nChars;
1141 Buf->buf[Buf->BufUsed] = '\0';
1146 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1147 * buf - the string to modify
1148 * len - length of the string.
1150 void StrBufTrim(StrBuf *Buf)
1153 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1155 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1158 if (delta > 0) StrBufCutLeft(Buf, delta);
1160 if (Buf->BufUsed == 0) return;
1161 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1164 Buf->buf[Buf->BufUsed] = '\0';
1168 void StrBufUpCase(StrBuf *Buf)
1173 pche = pch + Buf->BufUsed;
1174 while (pch < pche) {
1175 *pch = toupper(*pch);
1181 void StrBufLowerCase(StrBuf *Buf)
1186 pche = pch + Buf->BufUsed;
1187 while (pch < pche) {
1188 *pch = tolower(*pch);
1195 * \brief unhide special chars hidden to the HTML escaper
1196 * \param target buffer to put the unescaped string in
1197 * \param source buffer to unescape
1199 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1205 FlushStrBuf(target);
1207 if (source == NULL ||target == NULL)
1212 len = source->BufUsed;
1213 for (a = 0; a < len; ++a) {
1214 if (target->BufUsed >= target->BufSize)
1215 IncreaseBuf(target, 1, -1);
1217 if (source->buf[a] == '=') {
1218 hex[0] = source->buf[a + 1];
1219 hex[1] = source->buf[a + 2];
1222 sscanf(hex, "%02x", &b);
1223 target->buf[target->BufUsed] = b;
1224 target->buf[++target->BufUsed] = 0;
1228 target->buf[target->BufUsed] = source->buf[a];
1229 target->buf[++target->BufUsed] = 0;
1236 * \brief hide special chars from the HTML escapers and friends
1237 * \param target buffer to put the escaped string in
1238 * \param source buffer to escape
1240 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1245 FlushStrBuf(target);
1247 if (source == NULL ||target == NULL)
1252 len = source->BufUsed;
1253 for (i=0; i<len; ++i) {
1254 if (target->BufUsed + 4 >= target->BufSize)
1255 IncreaseBuf(target, 1, -1);
1256 if ( (isalnum(source->buf[i])) ||
1257 (source->buf[i]=='-') ||
1258 (source->buf[i]=='_') ) {
1259 target->buf[target->BufUsed++] = source->buf[i];
1262 sprintf(&target->buf[target->BufUsed],
1264 (0xFF &source->buf[i]));
1265 target->BufUsed += 3;
1268 target->buf[target->BufUsed + 1] = '\0';
1272 * \brief uses the same calling syntax as compress2(), but it
1273 * creates a stream compatible with HTTP "Content-encoding: gzip"
1276 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1277 #define OS_CODE 0x03 /*< unix */
1278 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1279 size_t * destLen, /*< length of the compresed data */
1280 const Bytef * source, /*< source to encode */
1281 uLong sourceLen, /*< length of source to encode */
1282 int level) /*< compression level */
1284 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1286 /* write gzip header */
1287 snprintf((char *) dest, *destLen,
1288 "%c%c%c%c%c%c%c%c%c%c",
1289 gz_magic[0], gz_magic[1], Z_DEFLATED,
1290 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1293 /* normal deflate */
1296 stream.next_in = (Bytef *) source;
1297 stream.avail_in = (uInt) sourceLen;
1298 stream.next_out = dest + 10L; // after header
1299 stream.avail_out = (uInt) * destLen;
1300 if ((uLong) stream.avail_out != *destLen)
1303 stream.zalloc = (alloc_func) 0;
1304 stream.zfree = (free_func) 0;
1305 stream.opaque = (voidpf) 0;
1307 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1308 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1312 err = deflate(&stream, Z_FINISH);
1313 if (err != Z_STREAM_END) {
1314 deflateEnd(&stream);
1315 return err == Z_OK ? Z_BUF_ERROR : err;
1317 *destLen = stream.total_out + 10L;
1319 /* write CRC and Length */
1320 uLong crc = crc32(0L, source, sourceLen);
1322 for (n = 0; n < 4; ++n, ++*destLen) {
1323 dest[*destLen] = (int) (crc & 0xff);
1326 uLong len = stream.total_in;
1327 for (n = 0; n < 4; ++n, ++*destLen) {
1328 dest[*destLen] = (int) (len & 0xff);
1331 err = deflateEnd(&stream);
1338 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1340 int CompressBuffer(StrBuf *Buf)
1343 char *compressed_data = NULL;
1344 size_t compressed_len, bufsize;
1346 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1347 compressed_data = malloc(compressed_len);
1349 if (compress_gzip((Bytef *) compressed_data,
1352 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1355 Buf->buf = compressed_data;
1356 Buf->BufUsed = compressed_len;
1357 Buf->BufSize = bufsize;
1360 free(compressed_data);
1362 #endif /* HAVE_ZLIB */
1367 * \brief decode a buffer from base 64 encoding; destroys original
1368 * \param Buf Buffor to transform
1370 int StrBufDecodeBase64(StrBuf *Buf)
1374 if (Buf == NULL) return -1;
1376 xferbuf = (char*) malloc(Buf->BufSize);
1377 siz = CtdlDecodeBase64(xferbuf,
1388 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1389 * \param Buf Buffer to translate
1390 * \param StripBlanks Reduce several blanks to one?
1392 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1398 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1399 Buf->buf[Buf->BufUsed - 1] = '\0';
1404 while (a < Buf->BufUsed) {
1405 if (Buf->buf[a] == '+')
1407 else if (Buf->buf[a] == '%') {
1408 /* don't let % chars through, rather truncate the input. */
1409 if (a + 2 > Buf->BufUsed) {
1414 hex[0] = Buf->buf[a + 1];
1415 hex[1] = Buf->buf[a + 2];
1418 sscanf(hex, "%02x", &b);
1419 Buf->buf[a] = (char) b;
1420 len = Buf->BufUsed - a - 2;
1422 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1434 * \brief RFC2047-encode a header field if necessary.
1435 * If no non-ASCII characters are found, the string
1436 * will be copied verbatim without encoding.
1438 * \param target Target buffer.
1439 * \param source Source string to be encoded.
1440 * \returns encoded length; -1 if non success.
1442 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1444 const char headerStr[] = "=?UTF-8?Q?";
1445 int need_to_encode = 0;
1449 if ((source == NULL) ||
1453 while ((i < source->BufUsed) &&
1454 (!IsEmptyStr (&source->buf[i])) &&
1455 (need_to_encode == 0)) {
1456 if (((unsigned char) source->buf[i] < 32) ||
1457 ((unsigned char) source->buf[i] > 126)) {
1463 if (!need_to_encode) {
1464 if (*target == NULL) {
1465 *target = NewStrBufPlain(source->buf, source->BufUsed);
1468 FlushStrBuf(*target);
1469 StrBufAppendBuf(*target, source, 0);
1471 return (*target)->BufUsed;
1473 if (*target == NULL)
1474 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1475 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1476 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1477 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1478 (*target)->BufUsed = sizeof(headerStr) - 1;
1479 for (i=0; (i < source->BufUsed); ++i) {
1480 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1481 IncreaseBuf(*target, 1, 0);
1482 ch = (unsigned char) source->buf[i];
1483 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1484 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1485 (*target)->BufUsed += 3;
1488 (*target)->buf[(*target)->BufUsed] = ch;
1489 (*target)->BufUsed++;
1493 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1494 IncreaseBuf(*target, 1, 0);
1496 (*target)->buf[(*target)->BufUsed++] = '?';
1497 (*target)->buf[(*target)->BufUsed++] = '=';
1498 (*target)->buf[(*target)->BufUsed] = '\0';
1499 return (*target)->BufUsed;;
1503 * \brief replaces all occurances of 'search' by 'replace'
1504 * \param buf Buffer to modify
1505 * \param search character to search
1506 * \param relpace character to replace search by
1508 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1513 for (i=0; i<buf->BufUsed; i++)
1514 if (buf->buf[i] == search)
1515 buf->buf[i] = replace;
1522 * Wrapper around iconv_open()
1523 * Our version adds aliases for non-standard Microsoft charsets
1524 * such as 'MS950', aliasing them to names like 'CP950'
1526 * tocode Target encoding
1527 * fromcode Source encoding
1529 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1532 iconv_t ic = (iconv_t)(-1) ;
1533 ic = iconv_open(tocode, fromcode);
1534 if (ic == (iconv_t)(-1) ) {
1535 char alias_fromcode[64];
1536 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1537 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1538 alias_fromcode[0] = 'C';
1539 alias_fromcode[1] = 'P';
1540 ic = iconv_open(tocode, alias_fromcode);
1543 *(iconv_t *)pic = ic;
1549 static inline char *FindNextEnd (StrBuf *Buf, char *bptr)
1552 /* Find the next ?Q? */
1553 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1556 end = strchr(bptr + 2, '?');
1561 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1562 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1563 (*(end + 2) == '?')) {
1564 /* skip on to the end of the cluster, the next ?= */
1565 end = strstr(end + 3, "?=");
1568 /* sort of half valid encoding, try to find an end. */
1569 end = strstr(bptr, "?=");
1574 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1579 char *ibuf; /**< Buffer of characters to be converted */
1580 char *obuf; /**< Buffer for converted characters */
1581 size_t ibuflen; /**< Length of input buffer */
1582 size_t obuflen; /**< Length of output buffer */
1585 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1586 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1588 ic = *(iconv_t*)pic;
1589 ibuf = ConvertBuf->buf;
1590 ibuflen = ConvertBuf->BufUsed;
1592 obuflen = TmpBuf->BufSize;
1594 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1596 /* little card game: wheres the red lady? */
1597 ibuf = ConvertBuf->buf;
1598 BufSize = ConvertBuf->BufSize;
1600 ConvertBuf->buf = TmpBuf->buf;
1601 ConvertBuf->BufSize = TmpBuf->BufSize;
1602 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1603 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1606 TmpBuf->BufSize = BufSize;
1607 TmpBuf->BufUsed = 0;
1608 TmpBuf->buf[0] = '\0';
1615 inline static void DecodeSegment(StrBuf *Target,
1620 StrBuf *ConvertBuf2,
1621 StrBuf *FoundCharset)
1626 iconv_t ic = (iconv_t)(-1);
1628 /* Now we handle foreign character sets properly encoded
1629 * in RFC2047 format.
1631 StaticBuf.buf = SegmentStart;
1632 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1633 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1634 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1635 if (FoundCharset != NULL) {
1636 FlushStrBuf(FoundCharset);
1637 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1639 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1640 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1642 *encoding = toupper(*encoding);
1643 if (*encoding == 'B') { /**< base64 */
1644 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1646 ConvertBuf->BufUsed);
1648 else if (*encoding == 'Q') { /**< quoted-printable */
1652 while (pos < ConvertBuf->BufUsed)
1654 if (ConvertBuf->buf[pos] == '_')
1655 ConvertBuf->buf[pos] = ' ';
1659 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1662 ConvertBuf->BufUsed);
1665 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1668 ctdl_iconv_open("UTF-8", charset, &ic);
1669 if (ic != (iconv_t)(-1) ) {
1670 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1671 StrBufAppendBuf(Target, ConvertBuf2, 0);
1675 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1679 * Handle subjects with RFC2047 encoding such as:
1680 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1682 void StrBuf_RFC822_to_Utf8(StrBuf *Target, StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1684 StrBuf *ConvertBuf, *ConvertBuf2;
1685 char *start, *end, *next, *nextend, *ptr = NULL;
1686 iconv_t ic = (iconv_t)(-1) ;
1690 int illegal_non_rfc2047_encoding = 0;
1692 /* Sometimes, badly formed messages contain strings which were simply
1693 * written out directly in some foreign character set instead of
1694 * using RFC2047 encoding. This is illegal but we will attempt to
1695 * handle it anyway by converting from a user-specified default
1696 * charset to UTF-8 if we see any nonprintable characters.
1699 len = StrLength(DecodeMe);
1700 for (i=0; i<DecodeMe->BufUsed; ++i) {
1701 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1702 illegal_non_rfc2047_encoding = 1;
1707 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1708 if ((illegal_non_rfc2047_encoding) &&
1709 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1710 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1712 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1713 if (ic != (iconv_t)(-1) ) {
1714 StrBufConvert(DecodeMe, ConvertBuf, &ic);
1719 /* pre evaluate the first pair */
1720 nextend = end = NULL;
1721 len = StrLength(DecodeMe);
1722 start = strstr(DecodeMe->buf, "=?");
1723 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1725 end = FindNextEnd (DecodeMe, start);
1727 StrBufAppendBuf(Target, DecodeMe, 0);
1728 FreeStrBuf(&ConvertBuf);
1732 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1734 if (start != DecodeMe->buf)
1735 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1737 * Since spammers will go to all sorts of absurd lengths to get their
1738 * messages through, there are LOTS of corrupt headers out there.
1739 * So, prevent a really badly formed RFC2047 header from throwing
1740 * this function into an infinite loop.
1742 while ((start != NULL) &&
1749 DecodeSegment(Target,
1757 next = strstr(end, "=?");
1759 if ((next != NULL) &&
1761 nextend = FindNextEnd(DecodeMe, next);
1762 if (nextend == NULL)
1765 /* did we find two partitions */
1766 if ((next != NULL) &&
1770 while ((ptr < next) &&
1776 /* did we find a gab just filled with blanks? */
1781 len - (next - start));
1783 /* now terminate the gab at the end */
1784 delta = (next - end) - 2;
1785 DecodeMe->BufUsed -= delta;
1786 DecodeMe->buf[DecodeMe->BufUsed] = '\0';
1788 /* move next to its new location. */
1793 /* our next-pair is our new first pair now. */
1799 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1800 if ((end != NULL) && (end < nextend)) {
1802 while ( (ptr < nextend) &&
1809 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1811 FreeStrBuf(&ConvertBuf);
1812 FreeStrBuf(&ConvertBuf2);
1817 long StrBuf_Utf8StrLen(StrBuf *Buf)
1819 return Ctdl_Utf8StrLen(Buf->buf);
1822 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1826 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1827 if (CutAt != NULL) {
1828 Buf->BufUsed = CutAt - Buf->buf;
1829 Buf->buf[Buf->BufUsed] = '\0';
1831 return Buf->BufUsed;
1836 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1838 const char *aptr, *ptr, *eptr;
1845 ptr = aptr = Buf->buf;
1849 optr = LineBuf->buf;
1850 eptr = Buf->buf + Buf->BufUsed;
1851 xptr = LineBuf->buf + LineBuf->BufSize;
1853 while ((*ptr != '\n') &&
1860 LineBuf->BufUsed = optr - LineBuf->buf;
1861 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1862 optr = LineBuf->buf + LineBuf->BufUsed;
1863 xptr = LineBuf->buf + LineBuf->BufSize;
1866 LineBuf->BufUsed = optr - LineBuf->buf;
1875 return Buf->BufUsed - (ptr - Buf->buf);