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)
237 * \brief Release a Buffer
238 * Its a double pointer, so it can NULL your pointer
239 * so fancy SIG11 appear instead of random results
240 * \param FreeMe Pointer Pointer to the buffer to free
242 void FreeStrBuf (StrBuf **FreeMe)
246 if (!(*FreeMe)->ConstBuf)
247 free((*FreeMe)->buf);
253 * \brief Release the buffer
254 * If you want put your StrBuf into a Hash, use this as Destructor.
255 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
257 void HFreeStrBuf (void *VFreeMe)
259 StrBuf *FreeMe = (StrBuf*)VFreeMe;
262 if (!FreeMe->ConstBuf)
268 * \brief Wrapper around atol
270 long StrTol(const StrBuf *Buf)
273 return atol(Buf->buf);
279 * \brief Wrapper around atoi
281 int StrToi(const StrBuf *Buf)
284 return atoi(Buf->buf);
290 * \brief modifies a Single char of the Buf
291 * You can point to it via char* or a zero-based integer
292 * \param ptr char* to zero; use NULL if unused
293 * \param nThChar zero based pointer into the string; use -1 if unused
294 * \param PeekValue The Character to place into the position
296 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
301 nThChar = ptr - Buf->buf;
302 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
304 Buf->buf[nThChar] = PeekValue;
309 * \brief Append a StringBuffer to the buffer
310 * \param Buf Buffer to modify
311 * \param AppendBuf Buffer to copy at the end of our buffer
312 * \param Offset Should we start copying from an offset?
314 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
316 if ((AppendBuf == NULL) || (Buf == NULL))
319 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
322 AppendBuf->BufUsed + Buf->BufUsed);
324 memcpy(Buf->buf + Buf->BufUsed,
325 AppendBuf->buf + Offset,
326 AppendBuf->BufUsed - Offset);
327 Buf->BufUsed += AppendBuf->BufUsed - Offset;
328 Buf->buf[Buf->BufUsed] = '\0';
333 * \brief Append a C-String to the buffer
334 * \param Buf Buffer to modify
335 * \param AppendBuf Buffer to copy at the end of our buffer
336 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
337 * \param Offset Should we start copying from an offset?
339 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
343 if ((AppendBuf == NULL) || (Buf == NULL))
347 aps = strlen(AppendBuf + Offset);
349 aps = AppendSize - Offset;
351 if (Buf->BufSize < Buf->BufUsed + aps)
352 IncreaseBuf(Buf, (Buf->BufUsed > 0), Buf->BufUsed + aps);
354 memcpy(Buf->buf + Buf->BufUsed,
358 Buf->buf[Buf->BufUsed] = '\0';
363 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
364 * \param outbuf the output buffer
365 * \param oblen the size of outbuf to sanitize
366 * \param strbuf the input buffer
368 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
370 const char *pch, *pche;
373 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
374 int eclen = sizeof(ec) -1;
376 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
378 if (PlainIn != NULL) {
379 len = strlen(PlainIn);
385 pche = pch + In->BufUsed;
392 pt = OutBuf->buf + OutBuf->BufUsed;
393 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
397 IncreaseBuf(OutBuf, 1, -1);
398 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
399 pt = OutBuf->buf + OutBuf->BufUsed;
403 for (b = 0; b < eclen; ++b) {
410 sprintf(pt,"%%%02X", *pch);
412 OutBuf->BufUsed += 3;
424 * \brief Append a string, escaping characters which have meaning in HTML.
426 * \param Target target buffer
427 * \param Source source buffer; set to NULL if you just have a C-String
428 * \param PlainIn Plain-C string to append; set to NULL if unused
429 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
430 * \param nolinebreaks if set, linebreaks are removed from the string.
432 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
434 const char *aptr, *eiptr;
438 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
441 if (PlainIn != NULL) {
443 len = strlen(PlainIn);
448 eiptr = aptr + Source->BufUsed;
449 len = Source->BufUsed;
455 bptr = Target->buf + Target->BufUsed;
456 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
458 while (aptr < eiptr){
460 IncreaseBuf(Target, 1, -1);
461 eptr = Target->buf + Target->BufSize - 6;
462 bptr = Target->buf + Target->BufUsed;
465 memcpy(bptr, "<", 4);
467 Target->BufUsed += 4;
469 else if (*aptr == '>') {
470 memcpy(bptr, ">", 4);
472 Target->BufUsed += 4;
474 else if (*aptr == '&') {
475 memcpy(bptr, "&", 5);
477 Target->BufUsed += 5;
479 else if (*aptr == '\"') {
480 memcpy(bptr, """, 6);
482 Target->BufUsed += 6;
484 else if (*aptr == '\'') {
485 memcpy(bptr, "'", 5);
487 Target->BufUsed += 5;
489 else if (*aptr == LB) {
494 else if (*aptr == RB) {
499 else if (*aptr == QU) {
504 else if ((*aptr == 32) && (nbsp == 1)) {
505 memcpy(bptr, " ", 6);
507 Target->BufUsed += 6;
509 else if ((*aptr == '\n') && (nolinebreaks)) {
510 *bptr='\0'; /* nothing */
512 else if ((*aptr == '\r') && (nolinebreaks)) {
513 *bptr='\0'; /* nothing */
523 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
525 return Target->BufUsed;
529 * \brief Append a string, escaping characters which have meaning in HTML.
530 * Converts linebreaks into blanks; escapes single quotes
531 * \param Target target buffer
532 * \param Source source buffer; set to NULL if you just have a C-String
533 * \param PlainIn Plain-C string to append; set to NULL if unused
535 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
537 const char *aptr, *eiptr;
541 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
544 if (PlainIn != NULL) {
546 len = strlen(PlainIn);
551 eiptr = aptr + Source->BufUsed;
552 len = Source->BufUsed;
558 eptr = Target->buf + Target->BufSize - 6;
559 tptr = Target->buf + Target->BufUsed;
561 while (aptr < eiptr){
563 IncreaseBuf(Target, 1, -1);
564 eptr = Target->buf + Target->BufSize - 6;
565 tptr = Target->buf + Target->BufUsed;
572 else if (*aptr == '\r') {
576 else if (*aptr == '\'') {
582 Target->BufUsed += 5;
594 * \brief extracts a substring from Source into dest
595 * \param dest buffer to place substring into
596 * \param Source string to copy substring from
597 * \param Offset chars to skip from start
598 * \param nChars number of chars to copy
599 * \returns the number of chars copied; may be different from nChars due to the size of Source
601 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
604 if (Offset > Source->BufUsed)
609 if (Offset + nChars < Source->BufUsed)
611 if (nChars > dest->BufSize)
612 IncreaseBuf(dest, 0, nChars + 1);
613 memcpy(dest->buf, Source->buf + Offset, nChars);
614 dest->BufUsed = nChars;
615 dest->buf[dest->BufUsed] = '\0';
618 NCharsRemain = Source->BufUsed - Offset;
619 if (NCharsRemain > dest->BufSize)
620 IncreaseBuf(dest, 0, NCharsRemain + 1);
621 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
622 dest->BufUsed = NCharsRemain;
623 dest->buf[dest->BufUsed] = '\0';
628 * \brief sprintf like function appending the formated string to the buffer
629 * vsnprintf version to wrap into own calls
630 * \param Buf Buffer to extend by format and params
631 * \param format printf alike format to add
632 * \param ap va_list containing the items for format
634 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
637 size_t BufSize = Buf->BufSize;
638 size_t nWritten = Buf->BufSize + 1;
639 size_t Offset = Buf->BufUsed;
640 size_t newused = Offset + nWritten;
642 while (newused >= BufSize) {
644 nWritten = vsnprintf(Buf->buf + Offset,
645 Buf->BufSize - Offset,
648 newused = Offset + nWritten;
649 if (newused >= Buf->BufSize) {
650 IncreaseBuf(Buf, 1, newused);
653 Buf->BufUsed = Offset + nWritten;
654 BufSize = Buf->BufSize;
661 * \brief sprintf like function appending the formated string to the buffer
662 * \param Buf Buffer to extend by format and params
663 * \param format printf alike format to add
664 * \param ap va_list containing the items for format
666 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
668 size_t BufSize = Buf->BufSize;
669 size_t nWritten = Buf->BufSize + 1;
670 size_t Offset = Buf->BufUsed;
671 size_t newused = Offset + nWritten;
674 while (newused >= BufSize) {
675 va_start(arg_ptr, format);
676 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
677 Buf->BufSize - Buf->BufUsed,
680 newused = Buf->BufUsed + nWritten;
681 if (newused >= Buf->BufSize) {
682 IncreaseBuf(Buf, 1, newused);
685 Buf->BufUsed += nWritten;
686 BufSize = Buf->BufSize;
693 * \brief sprintf like function putting the formated string into the buffer
694 * \param Buf Buffer to extend by format and params
695 * \param format printf alike format to add
696 * \param ap va_list containing the items for format
698 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
700 size_t nWritten = Buf->BufSize + 1;
703 while (nWritten >= Buf->BufSize) {
704 va_start(arg_ptr, format);
705 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
707 Buf->BufUsed = nWritten ;
708 if (nWritten >= Buf->BufSize)
709 IncreaseBuf(Buf, 0, 0);
715 * \brief Counts the numbmer of tokens in a buffer
716 * \param Source String to count tokens in
717 * \param tok Tokenizer char to count
718 * \returns numbers of tokenizer chars found
720 inline int StrBufNum_tokens(const StrBuf *source, char tok)
724 return num_tokens(source->buf, tok);
728 * remove_token() - a tokenizer that kills, maims, and destroys
731 * \brief a string tokenizer
732 * \param Source StringBuffer to read into
733 * \param parmnum n'th parameter to remove
734 * \param separator tokenizer param
735 * \returns -1 if not found, else length of token.
737 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
740 char *d, *s; /* dest, source */
743 /* Find desired parameter */
745 while (count < parmnum) {
746 /* End of string, bail! */
751 if (*d == separator) {
756 if (!d) return 0; /* Parameter not found */
758 /* Find next parameter */
760 while (*s && *s != separator) {
768 memmove(d, s, Source->BufUsed - (s - Source->buf));
769 Source->BufUsed -= (ReducedBy + 1);
771 else if (d == Source->buf) {
777 Source->BufUsed -= (ReducedBy + 1);
790 * \brief a string tokenizer
791 * \param dest Destination StringBuffer
792 * \param Source StringBuffer to read into
793 * \param parmnum n'th parameter to extract
794 * \param separator tokenizer param
795 * \returns -1 if not found, else length of token.
797 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
799 const char *s, *e; //* source * /
800 int len = 0; //* running total length of extracted string * /
801 int current_token = 0; //* token currently being processed * /
803 if ((Source == NULL) || (Source->BufUsed ==0)) {
807 e = s + Source->BufUsed;
813 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
817 while ((s<e) && !IsEmptyStr(s)) {
818 if (*s == separator) {
821 if (len >= dest->BufSize)
822 if (!IncreaseBuf(dest, 1, -1))
824 if ( (current_token == parmnum) &&
829 else if (current_token > parmnum) {
835 dest->buf[len] = '\0';
838 if (current_token < parmnum) {
839 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
842 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
848 * \brief a string tokenizer to fetch an integer
849 * \param dest Destination StringBuffer
850 * \param parmnum n'th parameter to extract
851 * \param separator tokenizer param
852 * \returns 0 if not found, else integer representation of the token
854 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
863 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
870 * \brief a string tokenizer to fetch a long integer
871 * \param dest Destination StringBuffer
872 * \param parmnum n'th parameter to extract
873 * \param separator tokenizer param
874 * \returns 0 if not found, else long integer representation of the token
876 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
885 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
893 * \brief a string tokenizer to fetch an unsigned long
894 * \param dest Destination StringBuffer
895 * \param parmnum n'th parameter to extract
896 * \param separator tokenizer param
897 * \returns 0 if not found, else unsigned long representation of the token
899 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
909 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
913 return (unsigned long) atol(pnum);
922 * \brief Read a line from socket
923 * flushes and closes the FD on error
924 * \param buf the buffer to get the input to
925 * \param fd pointer to the filedescriptor to read
926 * \param append Append to an existing string or replace?
927 * \param Error strerror() on error
928 * \returns numbers of chars read
930 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
937 slen = len = buf->BufUsed;
939 rlen = read(*fd, &buf->buf[len], 1);
941 *Error = strerror(errno);
948 if (buf->buf[len] == '\n')
950 if (buf->buf[len] != '\r')
952 if (!(len < buf->BufSize)) {
954 buf->buf[len+1] = '\0';
955 IncreaseBuf(buf, 1, -1);
959 buf->buf[len] = '\0';
964 * \brief Read a line from socket
965 * flushes and closes the FD on error
966 * \param buf the buffer to get the input to
967 * \param fd pointer to the filedescriptor to read
968 * \param append Append to an existing string or replace?
969 * \param Error strerror() on error
970 * \returns numbers of chars read
972 int StrBufTCP_read_buffered_line(StrBuf *Line,
976 int selectresolution,
980 int nSuccessLess = 0;
986 if (buf->BufUsed > 0) {
987 pch = strchr(buf->buf, '\n');
990 len = pch - buf->buf;
991 if (len > 0 && (*(pch - 1) == '\r') )
993 StrBufSub(Line, buf, 0, len - rlen);
994 StrBufCutLeft(buf, len + 1);
999 if (buf->BufSize - buf->BufUsed < 10)
1000 IncreaseBuf(buf, 1, -1);
1002 fdflags = fcntl(*fd, F_GETFL);
1003 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1006 while ((nSuccessLess < timeout) && (pch == NULL)) {
1007 tv.tv_sec = selectresolution;
1012 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1013 *Error = strerror(errno);
1018 if (FD_ISSET(*fd, &rfds)) {
1020 &buf->buf[buf->BufUsed],
1021 buf->BufSize - buf->BufUsed - 1);
1023 *Error = strerror(errno);
1028 else if (rlen > 0) {
1030 buf->BufUsed += rlen;
1031 buf->buf[buf->BufUsed] = '\0';
1032 if (buf->BufUsed + 10 > buf->BufSize) {
1033 IncreaseBuf(buf, 1, -1);
1035 pch = strchr(buf->buf, '\n');
1043 len = pch - buf->buf;
1044 if (len > 0 && (*(pch - 1) == '\r') )
1046 StrBufSub(Line, buf, 0, len - rlen);
1047 StrBufCutLeft(buf, len + 1);
1055 * \brief Input binary data from socket
1056 * flushes and closes the FD on error
1057 * \param buf the buffer to get the input to
1058 * \param fd pointer to the filedescriptor to read
1059 * \param append Append to an existing string or replace?
1060 * \param nBytes the maximal number of bytes to read
1061 * \param Error strerror() on error
1062 * \returns numbers of chars read
1064 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1068 int len, rlen, slen;
1072 if ((Buf == NULL) || (*fd == -1))
1076 if (Buf->BufUsed + nBytes > Buf->BufSize)
1077 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1079 ptr = Buf->buf + Buf->BufUsed;
1081 slen = len = Buf->BufUsed;
1083 fdflags = fcntl(*fd, F_GETFL);
1085 while (nRead < nBytes) {
1086 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1089 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1090 *Error = strerror(errno);
1095 if ((rlen = read(*fd,
1097 nBytes - nRead)) == -1) {
1100 *Error = strerror(errno);
1105 Buf->BufUsed += rlen;
1107 Buf->buf[Buf->BufUsed] = '\0';
1112 * \brief Cut nChars from the start of the string
1113 * \param Buf Buffer to modify
1114 * \param nChars how many chars should be skipped?
1116 void StrBufCutLeft(StrBuf *Buf, int nChars)
1118 if (nChars >= Buf->BufUsed) {
1122 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1123 Buf->BufUsed -= nChars;
1124 Buf->buf[Buf->BufUsed] = '\0';
1128 * \brief Cut the trailing n Chars from the string
1129 * \param Buf Buffer to modify
1130 * \param nChars how many chars should be trunkated?
1132 void StrBufCutRight(StrBuf *Buf, int nChars)
1134 if (nChars >= Buf->BufUsed) {
1138 Buf->BufUsed -= nChars;
1139 Buf->buf[Buf->BufUsed] = '\0';
1144 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1145 * buf - the string to modify
1146 * len - length of the string.
1148 void StrBufTrim(StrBuf *Buf)
1151 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1153 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1156 if (delta > 0) StrBufCutLeft(Buf, delta);
1158 if (Buf->BufUsed == 0) return;
1159 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1162 Buf->buf[Buf->BufUsed] = '\0';
1166 void StrBufUpCase(StrBuf *Buf)
1171 pche = pch + Buf->BufUsed;
1172 while (pch < pche) {
1173 *pch = toupper(*pch);
1180 * \brief unhide special chars hidden to the HTML escaper
1181 * \param target buffer to put the unescaped string in
1182 * \param source buffer to unescape
1184 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1190 FlushStrBuf(target);
1192 if (source == NULL ||target == NULL)
1197 len = source->BufUsed;
1198 for (a = 0; a < len; ++a) {
1199 if (target->BufUsed >= target->BufSize)
1200 IncreaseBuf(target, 1, -1);
1202 if (source->buf[a] == '=') {
1203 hex[0] = source->buf[a + 1];
1204 hex[1] = source->buf[a + 2];
1207 sscanf(hex, "%02x", &b);
1208 target->buf[target->BufUsed] = b;
1209 target->buf[++target->BufUsed] = 0;
1213 target->buf[target->BufUsed] = source->buf[a];
1214 target->buf[++target->BufUsed] = 0;
1221 * \brief hide special chars from the HTML escapers and friends
1222 * \param target buffer to put the escaped string in
1223 * \param source buffer to escape
1225 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1230 FlushStrBuf(target);
1232 if (source == NULL ||target == NULL)
1237 len = source->BufUsed;
1238 for (i=0; i<len; ++i) {
1239 if (target->BufUsed + 4 >= target->BufSize)
1240 IncreaseBuf(target, 1, -1);
1241 if ( (isalnum(source->buf[i])) ||
1242 (source->buf[i]=='-') ||
1243 (source->buf[i]=='_') ) {
1244 target->buf[target->BufUsed++] = source->buf[i];
1247 sprintf(&target->buf[target->BufUsed],
1249 (0xFF &source->buf[i]));
1250 target->BufUsed += 3;
1253 target->buf[target->BufUsed + 1] = '\0';
1257 * \brief uses the same calling syntax as compress2(), but it
1258 * creates a stream compatible with HTTP "Content-encoding: gzip"
1261 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1262 #define OS_CODE 0x03 /*< unix */
1263 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1264 size_t * destLen, /*< length of the compresed data */
1265 const Bytef * source, /*< source to encode */
1266 uLong sourceLen, /*< length of source to encode */
1267 int level) /*< compression level */
1269 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1271 /* write gzip header */
1272 snprintf((char *) dest, *destLen,
1273 "%c%c%c%c%c%c%c%c%c%c",
1274 gz_magic[0], gz_magic[1], Z_DEFLATED,
1275 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1278 /* normal deflate */
1281 stream.next_in = (Bytef *) source;
1282 stream.avail_in = (uInt) sourceLen;
1283 stream.next_out = dest + 10L; // after header
1284 stream.avail_out = (uInt) * destLen;
1285 if ((uLong) stream.avail_out != *destLen)
1288 stream.zalloc = (alloc_func) 0;
1289 stream.zfree = (free_func) 0;
1290 stream.opaque = (voidpf) 0;
1292 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1293 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1297 err = deflate(&stream, Z_FINISH);
1298 if (err != Z_STREAM_END) {
1299 deflateEnd(&stream);
1300 return err == Z_OK ? Z_BUF_ERROR : err;
1302 *destLen = stream.total_out + 10L;
1304 /* write CRC and Length */
1305 uLong crc = crc32(0L, source, sourceLen);
1307 for (n = 0; n < 4; ++n, ++*destLen) {
1308 dest[*destLen] = (int) (crc & 0xff);
1311 uLong len = stream.total_in;
1312 for (n = 0; n < 4; ++n, ++*destLen) {
1313 dest[*destLen] = (int) (len & 0xff);
1316 err = deflateEnd(&stream);
1323 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1325 int CompressBuffer(StrBuf *Buf)
1328 char *compressed_data = NULL;
1329 size_t compressed_len, bufsize;
1331 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1332 compressed_data = malloc(compressed_len);
1334 if (compress_gzip((Bytef *) compressed_data,
1337 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1340 Buf->buf = compressed_data;
1341 Buf->BufUsed = compressed_len;
1342 Buf->BufSize = bufsize;
1345 free(compressed_data);
1347 #endif /* HAVE_ZLIB */
1352 * \brief decode a buffer from base 64 encoding; destroys original
1353 * \param Buf Buffor to transform
1355 int StrBufDecodeBase64(StrBuf *Buf)
1359 if (Buf == NULL) return -1;
1361 xferbuf = (char*) malloc(Buf->BufSize);
1362 siz = CtdlDecodeBase64(xferbuf,
1373 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1374 * \param Buf Buffer to translate
1375 * \param StripBlanks Reduce several blanks to one?
1377 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1383 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1384 Buf->buf[Buf->BufUsed - 1] = '\0';
1389 while (a < Buf->BufUsed) {
1390 if (Buf->buf[a] == '+')
1392 else if (Buf->buf[a] == '%') {
1393 /* don't let % chars through, rather truncate the input. */
1394 if (a + 2 > Buf->BufUsed) {
1399 hex[0] = Buf->buf[a + 1];
1400 hex[1] = Buf->buf[a + 2];
1403 sscanf(hex, "%02x", &b);
1404 Buf->buf[a] = (char) b;
1405 len = Buf->BufUsed - a - 2;
1407 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1419 * \brief RFC2047-encode a header field if necessary.
1420 * If no non-ASCII characters are found, the string
1421 * will be copied verbatim without encoding.
1423 * \param target Target buffer.
1424 * \param source Source string to be encoded.
1425 * \returns encoded length; -1 if non success.
1427 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1429 const char headerStr[] = "=?UTF-8?Q?";
1430 int need_to_encode = 0;
1434 if ((source == NULL) ||
1438 while ((i < source->BufUsed) &&
1439 (!IsEmptyStr (&source->buf[i])) &&
1440 (need_to_encode == 0)) {
1441 if (((unsigned char) source->buf[i] < 32) ||
1442 ((unsigned char) source->buf[i] > 126)) {
1448 if (!need_to_encode) {
1449 if (*target == NULL) {
1450 *target = NewStrBufPlain(source->buf, source->BufUsed);
1453 FlushStrBuf(*target);
1454 StrBufAppendBuf(*target, source, 0);
1456 return (*target)->BufUsed;
1458 if (*target == NULL)
1459 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1460 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1461 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1462 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1463 (*target)->BufUsed = sizeof(headerStr) - 1;
1464 for (i=0; (i < source->BufUsed); ++i) {
1465 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1466 IncreaseBuf(*target, 1, 0);
1467 ch = (unsigned char) source->buf[i];
1468 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1469 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1470 (*target)->BufUsed += 3;
1473 (*target)->buf[(*target)->BufUsed] = ch;
1474 (*target)->BufUsed++;
1478 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1479 IncreaseBuf(*target, 1, 0);
1481 (*target)->buf[(*target)->BufUsed++] = '?';
1482 (*target)->buf[(*target)->BufUsed++] = '=';
1483 (*target)->buf[(*target)->BufUsed] = '\0';
1484 return (*target)->BufUsed;;
1488 * \brief replaces all occurances of 'search' by 'replace'
1489 * \param buf Buffer to modify
1490 * \param search character to search
1491 * \param relpace character to replace search by
1493 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1498 for (i=0; i<buf->BufUsed; i++)
1499 if (buf->buf[i] == search)
1500 buf->buf[i] = replace;
1507 * Wrapper around iconv_open()
1508 * Our version adds aliases for non-standard Microsoft charsets
1509 * such as 'MS950', aliasing them to names like 'CP950'
1511 * tocode Target encoding
1512 * fromcode Source encoding
1514 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1517 iconv_t ic = (iconv_t)(-1) ;
1518 ic = iconv_open(tocode, fromcode);
1519 if (ic == (iconv_t)(-1) ) {
1520 char alias_fromcode[64];
1521 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1522 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1523 alias_fromcode[0] = 'C';
1524 alias_fromcode[1] = 'P';
1525 ic = iconv_open(tocode, alias_fromcode);
1528 *(iconv_t *)pic = ic;
1534 static inline char *FindNextEnd (StrBuf *Buf, char *bptr)
1537 /* Find the next ?Q? */
1538 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1541 end = strchr(bptr + 2, '?');
1546 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1547 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1548 (*(end + 2) == '?')) {
1549 /* skip on to the end of the cluster, the next ?= */
1550 end = strstr(end + 3, "?=");
1553 /* sort of half valid encoding, try to find an end. */
1554 end = strstr(bptr, "?=");
1559 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1564 char *ibuf; /**< Buffer of characters to be converted */
1565 char *obuf; /**< Buffer for converted characters */
1566 size_t ibuflen; /**< Length of input buffer */
1567 size_t obuflen; /**< Length of output buffer */
1570 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1571 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1573 ic = *(iconv_t*)pic;
1574 ibuf = ConvertBuf->buf;
1575 ibuflen = ConvertBuf->BufUsed;
1577 obuflen = TmpBuf->BufSize;
1579 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1581 /* little card game: wheres the red lady? */
1582 ibuf = ConvertBuf->buf;
1583 BufSize = ConvertBuf->BufSize;
1585 ConvertBuf->buf = TmpBuf->buf;
1586 ConvertBuf->BufSize = TmpBuf->BufSize;
1587 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1588 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1591 TmpBuf->BufSize = BufSize;
1592 TmpBuf->BufUsed = 0;
1593 TmpBuf->buf[0] = '\0';
1600 inline static void DecodeSegment(StrBuf *Target,
1605 StrBuf *ConvertBuf2)
1610 iconv_t ic = (iconv_t)(-1);
1612 /* Now we handle foreign character sets properly encoded
1613 * in RFC2047 format.
1615 StaticBuf.buf = SegmentStart;
1616 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1617 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1618 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1619 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1620 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1622 if (*encoding == 'B') { /**< base64 */
1623 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1625 ConvertBuf->BufUsed);
1627 else if (*encoding == 'Q') { /**< quoted-printable */
1631 while (pos < ConvertBuf->BufUsed)
1633 if (ConvertBuf->buf[pos] == '_')
1634 ConvertBuf->buf[pos] = ' ';
1638 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1641 ConvertBuf->BufUsed);
1644 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1647 ctdl_iconv_open("UTF-8", charset, &ic);
1648 if (ic != (iconv_t)(-1) ) {
1649 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1650 StrBufAppendBuf(Target, ConvertBuf2, 0);
1654 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1658 * Handle subjects with RFC2047 encoding such as:
1659 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1661 void StrBuf_RFC822_to_Utf8(StrBuf *Target, StrBuf *DecodeMe, const StrBuf* DefaultCharset)
1663 StrBuf *ConvertBuf, *ConvertBuf2;
1664 char *start, *end, *next, *nextend, *ptr;
1665 iconv_t ic = (iconv_t)(-1) ;
1666 char *ibuf; /**< Buffer of characters to be converted */
1667 char *obuf; /**< Buffer for converted characters */
1668 size_t ibuflen; /**< Length of input buffer */
1669 size_t obuflen; /**< Length of output buffer */
1674 int illegal_non_rfc2047_encoding = 0;
1676 /* Sometimes, badly formed messages contain strings which were simply
1677 * written out directly in some foreign character set instead of
1678 * using RFC2047 encoding. This is illegal but we will attempt to
1679 * handle it anyway by converting from a user-specified default
1680 * charset to UTF-8 if we see any nonprintable characters.
1683 len = StrLength(DecodeMe);
1684 for (i=0; i<DecodeMe->BufUsed; ++i) {
1685 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1686 illegal_non_rfc2047_encoding = 1;
1691 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1692 if (illegal_non_rfc2047_encoding) {
1693 if ( (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1694 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) ) {
1695 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1696 if (ic != (iconv_t)(-1) ) {
1698 ibuf = DecodeMe->buf;
1699 obuf = ConvertBuf->buf;
1700 ibuflen = DecodeMe->BufUsed;
1701 obuflen = ConvertBuf->BufSize;
1703 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1704 /* little card game: wheres the red lady? */
1705 ibuf = DecodeMe->buf;
1706 BufSize = DecodeMe->BufSize;
1707 DecodeMe->buf = ConvertBuf->buf;
1708 DecodeMe->BufSize = ConvertBuf->BufSize;
1709 DecodeMe->BufUsed = ConvertBuf->BufSize - obuflen;
1710 DecodeMe->buf[DecodeMe->BufUsed] = '\0';
1712 ConvertBuf->buf = ibuf;
1713 ConvertBuf->BufSize = BufSize;
1714 ConvertBuf->BufUsed = 0;
1715 ConvertBuf->buf[0] = '\0';
1722 /* pre evaluate the first pair */
1723 nextend = end = NULL;
1724 len = StrLength(DecodeMe);
1725 start = strstr(DecodeMe->buf, "=?");
1726 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1728 end = FindNextEnd (DecodeMe, start);
1730 StrBufAppendBuf(Target, DecodeMe, 0);
1731 FreeStrBuf(&ConvertBuf);
1735 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1738 * Since spammers will go to all sorts of absurd lengths to get their
1739 * messages through, there are LOTS of corrupt headers out there.
1740 * So, prevent a really badly formed RFC2047 header from throwing
1741 * this function into an infinite loop.
1743 while ((start != NULL) &&
1750 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. */
1797 FreeStrBuf(&ConvertBuf);
1798 FreeStrBuf(&ConvertBuf2);
1803 long StrBuf_Utf8StrLen(StrBuf *Buf)
1805 return Ctdl_Utf8StrLen(Buf->buf);
1808 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1812 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1813 if (CutAt != NULL) {
1814 Buf->BufUsed = CutAt - Buf->buf;
1815 Buf->buf[Buf->BufUsed] = '\0';
1817 return Buf->BufUsed;
1822 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1824 const char *aptr, *ptr, *eptr;
1831 ptr = aptr = Buf->buf;
1835 optr = LineBuf->buf;
1836 eptr = Buf->buf + Buf->BufUsed;
1837 xptr = LineBuf->buf + LineBuf->BufSize;
1839 while ((*ptr != '\n') &&
1846 LineBuf->BufUsed = optr - LineBuf->buf;
1847 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1848 optr = LineBuf->buf + LineBuf->BufUsed;
1849 xptr = LineBuf->buf + LineBuf->BufSize;
1852 LineBuf->BufUsed = optr - LineBuf->buf;
1861 return Buf->BufUsed - (ptr - Buf->buf);