8 #include <sys/select.h>
10 #define SHOW_ME_VAPPEND_PRINTF
12 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
30 * Private Structure for the Stringbuffer
33 char *buf; /**< the pointer to the dynamic buffer */
34 long BufSize; /**< how many spcae do we optain */
35 long BufUsed; /**< StNumber of Chars used excluding the trailing \0 */
36 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 * \Brief Cast operator to Plain String
42 * Note: if the buffer is altered by StrBuf operations, this pointer may become
43 * invalid. So don't lean on it after altering the buffer!
44 * Since this operation is considered cheap, rather call it often than risking
45 * your pointer to become invalid!
46 * \param Str the string we want to get the c-string representation for
47 * \returns the Pointer to the Content. Don't mess with it!
49 inline const char *ChrPtr(const StrBuf *Str)
57 * \brief since we know strlen()'s result, provide it here.
58 * \param Str the string to return the length to
59 * \returns contentlength of the buffer
61 inline int StrLength(const StrBuf *Str)
63 return (Str != NULL) ? Str->BufUsed : 0;
67 * \brief local utility function to resize the buffer
68 * \param Buf the buffer whichs storage we should increase
69 * \param KeepOriginal should we copy the original buffer or just start over with a new one
70 * \param DestSize what should fit in after?
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
75 size_t NewSize = Buf->BufSize * 2;
81 while (NewSize <= DestSize)
84 NewBuf= (char*) malloc(NewSize);
85 if (KeepOriginal && (Buf->BufUsed > 0))
87 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
101 * Allocate a new buffer with default buffer size
102 * \returns the new stringbuffer
104 StrBuf* NewStrBuf(void)
108 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109 NewBuf->buf = (char*) malloc(SIZ);
110 NewBuf->buf[0] = '\0';
111 NewBuf->BufSize = SIZ;
113 NewBuf->ConstBuf = 0;
118 * \brief Copy Constructor; returns a duplicate of CopyMe
119 * \params CopyMe Buffer to faxmilate
120 * \returns the new stringbuffer
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
129 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132 NewBuf->BufUsed = CopyMe->BufUsed;
133 NewBuf->BufSize = CopyMe->BufSize;
134 NewBuf->ConstBuf = 0;
139 * \brief create a new Buffer using an existing c-string
140 * this function should also be used if you want to pre-suggest
141 * the buffer size to allocate in conjunction with ptr == NULL
142 * \param ptr the c-string to copy; may be NULL to create a blank instance
143 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144 * \returns the new stringbuffer
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
152 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
154 CopySize = strlen((ptr != NULL)?ptr:"");
158 while (Siz <= CopySize)
161 NewBuf->buf = (char*) malloc(Siz);
162 NewBuf->BufSize = Siz;
164 memcpy(NewBuf->buf, ptr, CopySize);
165 NewBuf->buf[CopySize] = '\0';
166 NewBuf->BufUsed = CopySize;
169 NewBuf->buf[0] = '\0';
172 NewBuf->ConstBuf = 0;
177 * \brief Set an existing buffer from a c-string
178 * \param ptr c-string to put into
179 * \param nChars set to -1 if we should work 0-terminated
180 * \returns the new length of the string
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
184 size_t Siz = Buf->BufSize;
188 CopySize = strlen(ptr);
192 while (Siz <= CopySize)
195 if (Siz != Buf->BufSize)
196 IncreaseBuf(Buf, 0, Siz);
197 memcpy(Buf->buf, ptr, CopySize);
198 Buf->buf[CopySize] = '\0';
199 Buf->BufUsed = CopySize;
206 * \brief use strbuf as wrapper for a string constant for easy handling
207 * \param StringConstant a string to wrap
208 * \param SizeOfConstant should be sizeof(StringConstant)-1
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) StringConstant;
216 NewBuf->BufSize = SizeOfStrConstant;
217 NewBuf->BufUsed = SizeOfStrConstant;
218 NewBuf->ConstBuf = 1;
224 * \brief flush the content of a Buf; keep its struct
225 * \param buf Buffer to flush
227 int FlushStrBuf(StrBuf *buf)
239 * \brief Release a Buffer
240 * Its a double pointer, so it can NULL your pointer
241 * so fancy SIG11 appear instead of random results
242 * \param FreeMe Pointer Pointer to the buffer to free
244 void FreeStrBuf (StrBuf **FreeMe)
248 if (!(*FreeMe)->ConstBuf)
249 free((*FreeMe)->buf);
255 * \brief Release the buffer
256 * If you want put your StrBuf into a Hash, use this as Destructor.
257 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
259 void HFreeStrBuf (void *VFreeMe)
261 StrBuf *FreeMe = (StrBuf*)VFreeMe;
264 if (!FreeMe->ConstBuf)
270 * \brief Wrapper around atol
272 long StrTol(const StrBuf *Buf)
277 return atol(Buf->buf);
283 * \brief Wrapper around atoi
285 int StrToi(const StrBuf *Buf)
289 if (Buf->BufUsed > 0)
290 return atoi(Buf->buf);
295 * \brief Checks to see if the string is a pure number
297 int StrBufIsNumber(const StrBuf *Buf) {
302 strtoll(Buf->buf, &pEnd, 10);
303 if (pEnd == NULL && ((Buf->buf)-pEnd) != 0) {
309 * \brief modifies a Single char of the Buf
310 * You can point to it via char* or a zero-based integer
311 * \param ptr char* to zero; use NULL if unused
312 * \param nThChar zero based pointer into the string; use -1 if unused
313 * \param PeekValue The Character to place into the position
315 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
320 nThChar = ptr - Buf->buf;
321 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
323 Buf->buf[nThChar] = PeekValue;
328 * \brief Append a StringBuffer to the buffer
329 * \param Buf Buffer to modify
330 * \param AppendBuf Buffer to copy at the end of our buffer
331 * \param Offset Should we start copying from an offset?
333 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
335 if ((AppendBuf == NULL) || (Buf == NULL) || (AppendBuf->buf == NULL))
338 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
341 AppendBuf->BufUsed + Buf->BufUsed);
343 memcpy(Buf->buf + Buf->BufUsed,
344 AppendBuf->buf + Offset,
345 AppendBuf->BufUsed - Offset);
346 Buf->BufUsed += AppendBuf->BufUsed - Offset;
347 Buf->buf[Buf->BufUsed] = '\0';
352 * \brief Append a C-String to the buffer
353 * \param Buf Buffer to modify
354 * \param AppendBuf Buffer to copy at the end of our buffer
355 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
356 * \param Offset Should we start copying from an offset?
358 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
361 long BufSizeRequired;
363 if ((AppendBuf == NULL) || (Buf == NULL))
367 aps = strlen(AppendBuf + Offset);
369 aps = AppendSize - Offset;
371 BufSizeRequired = Buf->BufUsed + aps + 1;
372 if (Buf->BufSize <= BufSizeRequired)
373 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
375 memcpy(Buf->buf + Buf->BufUsed,
379 Buf->buf[Buf->BufUsed] = '\0';
384 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
385 * \param outbuf the output buffer
386 * \param oblen the size of outbuf to sanitize
387 * \param strbuf the input buffer
389 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
391 const char *pch, *pche;
394 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
395 int eclen = sizeof(ec) -1;
397 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
399 if (PlainIn != NULL) {
400 len = strlen(PlainIn);
406 pche = pch + In->BufUsed;
413 pt = OutBuf->buf + OutBuf->BufUsed;
414 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
418 IncreaseBuf(OutBuf, 1, -1);
419 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
420 pt = OutBuf->buf + OutBuf->BufUsed;
424 for (b = 0; b < eclen; ++b) {
431 sprintf(pt,"%%%02X", *pch);
433 OutBuf->BufUsed += 3;
445 * \brief Append a string, escaping characters which have meaning in HTML.
447 * \param Target target buffer
448 * \param Source source buffer; set to NULL if you just have a C-String
449 * \param PlainIn Plain-C string to append; set to NULL if unused
450 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
451 * \param nolinebreaks if set, linebreaks are removed from the string.
453 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
455 const char *aptr, *eiptr;
459 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
462 if (PlainIn != NULL) {
464 len = strlen(PlainIn);
469 eiptr = aptr + Source->BufUsed;
470 len = Source->BufUsed;
476 bptr = Target->buf + Target->BufUsed;
477 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
479 while (aptr < eiptr){
481 IncreaseBuf(Target, 1, -1);
482 eptr = Target->buf + Target->BufSize - 6;
483 bptr = Target->buf + Target->BufUsed;
486 memcpy(bptr, "<", 4);
488 Target->BufUsed += 4;
490 else if (*aptr == '>') {
491 memcpy(bptr, ">", 4);
493 Target->BufUsed += 4;
495 else if (*aptr == '&') {
496 memcpy(bptr, "&", 5);
498 Target->BufUsed += 5;
500 else if (*aptr == '"') {
501 memcpy(bptr, """, 6);
503 Target->BufUsed += 6;
505 else if (*aptr == '\'') {
506 memcpy(bptr, "'", 5);
508 Target->BufUsed += 5;
510 else if (*aptr == LB) {
515 else if (*aptr == RB) {
520 else if (*aptr == QU) {
525 else if ((*aptr == 32) && (nbsp == 1)) {
526 memcpy(bptr, " ", 6);
528 Target->BufUsed += 6;
530 else if ((*aptr == '\n') && (nolinebreaks)) {
531 *bptr='\0'; /* nothing */
533 else if ((*aptr == '\r') && (nolinebreaks)) {
534 *bptr='\0'; /* nothing */
544 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
546 return Target->BufUsed;
550 * \brief Append a string, escaping characters which have meaning in HTML.
551 * Converts linebreaks into blanks; escapes single quotes
552 * \param Target target buffer
553 * \param Source source buffer; set to NULL if you just have a C-String
554 * \param PlainIn Plain-C string to append; set to NULL if unused
556 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
558 const char *aptr, *eiptr;
562 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
565 if (PlainIn != NULL) {
567 len = strlen(PlainIn);
572 eiptr = aptr + Source->BufUsed;
573 len = Source->BufUsed;
579 eptr = Target->buf + Target->BufSize - 6;
580 tptr = Target->buf + Target->BufUsed;
582 while (aptr < eiptr){
584 IncreaseBuf(Target, 1, -1);
585 eptr = Target->buf + Target->BufSize - 6;
586 tptr = Target->buf + Target->BufUsed;
593 else if (*aptr == '\r') {
597 else if (*aptr == '\'') {
603 Target->BufUsed += 5;
614 * \brief Append a string, escaping characters which have meaning in JavaScript strings .
616 * \param Target target buffer
617 * \param Source source buffer; set to NULL if you just have a C-String
618 * \param PlainIn Plain-C string to append; set to NULL if unused
620 long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
622 const char *aptr, *eiptr;
626 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
629 if (PlainIn != NULL) {
631 len = strlen(PlainIn);
636 eiptr = aptr + Source->BufUsed;
637 len = Source->BufUsed;
643 bptr = Target->buf + Target->BufUsed;
644 eptr = Target->buf + Target->BufSize - 2; /* our biggest unit to put in... */
646 while (aptr < eiptr){
648 IncreaseBuf(Target, 1, -1);
649 eptr = Target->buf + Target->BufSize - 2;
650 bptr = Target->buf + Target->BufUsed;
652 else if (*aptr == '"') {
653 memcpy(bptr, "\\\"", 2);
655 Target->BufUsed += 2;
656 } else if (*aptr == '\\') {
657 memcpy(bptr, "\\\\", 2);
659 Target->BufUsed += 2;
669 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
671 return Target->BufUsed;
675 * \brief extracts a substring from Source into dest
676 * \param dest buffer to place substring into
677 * \param Source string to copy substring from
678 * \param Offset chars to skip from start
679 * \param nChars number of chars to copy
680 * \returns the number of chars copied; may be different from nChars due to the size of Source
682 int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
685 if (Offset > Source->BufUsed)
690 if (Offset + nChars < Source->BufUsed)
692 if (nChars > dest->BufSize)
693 IncreaseBuf(dest, 0, nChars + 1);
694 memcpy(dest->buf, Source->buf + Offset, nChars);
695 dest->BufUsed = nChars;
696 dest->buf[dest->BufUsed] = '\0';
699 NCharsRemain = Source->BufUsed - Offset;
700 if (NCharsRemain > dest->BufSize)
701 IncreaseBuf(dest, 0, NCharsRemain + 1);
702 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
703 dest->BufUsed = NCharsRemain;
704 dest->buf[dest->BufUsed] = '\0';
709 * \brief sprintf like function appending the formated string to the buffer
710 * vsnprintf version to wrap into own calls
711 * \param Buf Buffer to extend by format and params
712 * \param format printf alike format to add
713 * \param ap va_list containing the items for format
715 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
718 size_t BufSize = Buf->BufSize;
719 size_t nWritten = Buf->BufSize + 1;
720 size_t Offset = Buf->BufUsed;
721 size_t newused = Offset + nWritten;
723 while (newused >= BufSize) {
725 nWritten = vsnprintf(Buf->buf + Offset,
726 Buf->BufSize - Offset,
729 newused = Offset + nWritten;
730 if (newused >= Buf->BufSize) {
731 IncreaseBuf(Buf, 1, newused);
734 Buf->BufUsed = Offset + nWritten;
735 BufSize = Buf->BufSize;
742 * \brief sprintf like function appending the formated string to the buffer
743 * \param Buf Buffer to extend by format and params
744 * \param format printf alike format to add
745 * \param ap va_list containing the items for format
747 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
749 size_t BufSize = Buf->BufSize;
750 size_t nWritten = Buf->BufSize + 1;
751 size_t Offset = Buf->BufUsed;
752 size_t newused = Offset + nWritten;
755 while (newused >= BufSize) {
756 va_start(arg_ptr, format);
757 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
758 Buf->BufSize - Buf->BufUsed,
761 newused = Buf->BufUsed + nWritten;
762 if (newused >= Buf->BufSize) {
763 IncreaseBuf(Buf, 1, newused);
766 Buf->BufUsed += nWritten;
767 BufSize = Buf->BufSize;
774 * \brief sprintf like function putting the formated string into the buffer
775 * \param Buf Buffer to extend by format and params
776 * \param format printf alike format to add
777 * \param ap va_list containing the items for format
779 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
781 size_t nWritten = Buf->BufSize + 1;
784 while (nWritten >= Buf->BufSize) {
785 va_start(arg_ptr, format);
786 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
788 Buf->BufUsed = nWritten ;
789 if (nWritten >= Buf->BufSize)
790 IncreaseBuf(Buf, 0, 0);
796 * \brief Counts the numbmer of tokens in a buffer
797 * \param Source String to count tokens in
798 * \param tok Tokenizer char to count
799 * \returns numbers of tokenizer chars found
801 inline int StrBufNum_tokens(const StrBuf *source, char tok)
805 return num_tokens(source->buf, tok);
809 * remove_token() - a tokenizer that kills, maims, and destroys
812 * \brief a string tokenizer
813 * \param Source StringBuffer to read into
814 * \param parmnum n'th parameter to remove
815 * \param separator tokenizer param
816 * \returns -1 if not found, else length of token.
818 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
821 char *d, *s; /* dest, source */
824 /* Find desired parameter */
826 while (count < parmnum) {
827 /* End of string, bail! */
832 if (*d == separator) {
837 if (!d) return 0; /* Parameter not found */
839 /* Find next parameter */
841 while (*s && *s != separator) {
849 memmove(d, s, Source->BufUsed - (s - Source->buf));
850 Source->BufUsed -= (ReducedBy + 1);
852 else if (d == Source->buf) {
858 Source->BufUsed -= (ReducedBy + 1);
871 * \brief a string tokenizer
872 * \param dest Destination StringBuffer
873 * \param Source StringBuffer to read into
874 * \param parmnum n'th parameter to extract
875 * \param separator tokenizer param
876 * \returns -1 if not found, else length of token.
878 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
880 const char *s, *e; //* source * /
881 int len = 0; //* running total length of extracted string * /
882 int current_token = 0; //* token currently being processed * /
891 if ((Source == NULL) || (Source->BufUsed ==0)) {
895 e = s + Source->BufUsed;
898 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
900 while ((s<e) && !IsEmptyStr(s)) {
901 if (*s == separator) {
904 if (len >= dest->BufSize)
905 if (!IncreaseBuf(dest, 1, -1))
907 if ( (current_token == parmnum) &&
912 else if (current_token > parmnum) {
918 dest->buf[len] = '\0';
921 if (current_token < parmnum) {
922 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
925 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
931 * \brief a string tokenizer to fetch an integer
932 * \param dest Destination StringBuffer
933 * \param parmnum n'th parameter to extract
934 * \param separator tokenizer param
935 * \returns 0 if not found, else integer representation of the token
937 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
946 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
953 * \brief a string tokenizer to fetch a long integer
954 * \param dest Destination StringBuffer
955 * \param parmnum n'th parameter to extract
956 * \param separator tokenizer param
957 * \returns 0 if not found, else long integer representation of the token
959 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
968 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
976 * \brief a string tokenizer to fetch an unsigned long
977 * \param dest Destination StringBuffer
978 * \param parmnum n'th parameter to extract
979 * \param separator tokenizer param
980 * \returns 0 if not found, else unsigned long representation of the token
982 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
992 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
996 return (unsigned long) atol(pnum);
1005 * \brief Read a line from socket
1006 * flushes and closes the FD on error
1007 * \param buf the buffer to get the input to
1008 * \param fd pointer to the filedescriptor to read
1009 * \param append Append to an existing string or replace?
1010 * \param Error strerror() on error
1011 * \returns numbers of chars read
1013 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
1015 int len, rlen, slen;
1020 slen = len = buf->BufUsed;
1022 rlen = read(*fd, &buf->buf[len], 1);
1024 *Error = strerror(errno);
1031 if (buf->buf[len] == '\n')
1033 if (buf->buf[len] != '\r')
1035 if (!(len < buf->BufSize)) {
1037 buf->buf[len+1] = '\0';
1038 IncreaseBuf(buf, 1, -1);
1042 buf->buf[len] = '\0';
1047 * \brief Read a line from socket
1048 * flushes and closes the FD on error
1049 * \param buf the buffer to get the input to
1050 * \param fd pointer to the filedescriptor to read
1051 * \param append Append to an existing string or replace?
1052 * \param Error strerror() on error
1053 * \returns numbers of chars read
1055 int StrBufTCP_read_buffered_line(StrBuf *Line,
1059 int selectresolution,
1063 int nSuccessLess = 0;
1069 if (buf->BufUsed > 0) {
1070 pch = strchr(buf->buf, '\n');
1073 len = pch - buf->buf;
1074 if (len > 0 && (*(pch - 1) == '\r') )
1076 StrBufSub(Line, buf, 0, len - rlen);
1077 StrBufCutLeft(buf, len + 1);
1082 if (buf->BufSize - buf->BufUsed < 10)
1083 IncreaseBuf(buf, 1, -1);
1085 fdflags = fcntl(*fd, F_GETFL);
1086 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1089 while ((nSuccessLess < timeout) && (pch == NULL)) {
1090 tv.tv_sec = selectresolution;
1095 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1096 *Error = strerror(errno);
1101 if (FD_ISSET(*fd, &rfds)) {
1103 &buf->buf[buf->BufUsed],
1104 buf->BufSize - buf->BufUsed - 1);
1106 *Error = strerror(errno);
1111 else if (rlen > 0) {
1113 buf->BufUsed += rlen;
1114 buf->buf[buf->BufUsed] = '\0';
1115 if (buf->BufUsed + 10 > buf->BufSize) {
1116 IncreaseBuf(buf, 1, -1);
1118 pch = strchr(buf->buf, '\n');
1126 len = pch - buf->buf;
1127 if (len > 0 && (*(pch - 1) == '\r') )
1129 StrBufSub(Line, buf, 0, len - rlen);
1130 StrBufCutLeft(buf, len + 1);
1138 * \brief Input binary data from socket
1139 * flushes and closes the FD on error
1140 * \param buf the buffer to get the input to
1141 * \param fd pointer to the filedescriptor to read
1142 * \param append Append to an existing string or replace?
1143 * \param nBytes the maximal number of bytes to read
1144 * \param Error strerror() on error
1145 * \returns numbers of chars read
1147 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1151 int len, rlen, slen;
1155 if ((Buf == NULL) || (*fd == -1))
1159 if (Buf->BufUsed + nBytes > Buf->BufSize)
1160 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1162 ptr = Buf->buf + Buf->BufUsed;
1164 slen = len = Buf->BufUsed;
1166 fdflags = fcntl(*fd, F_GETFL);
1168 while (nRead < nBytes) {
1169 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1172 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1173 *Error = strerror(errno);
1178 if ((rlen = read(*fd,
1180 nBytes - nRead)) == -1) {
1183 *Error = strerror(errno);
1188 Buf->BufUsed += rlen;
1190 Buf->buf[Buf->BufUsed] = '\0';
1195 * \brief Cut nChars from the start of the string
1196 * \param Buf Buffer to modify
1197 * \param nChars how many chars should be skipped?
1199 void StrBufCutLeft(StrBuf *Buf, int nChars)
1201 if (nChars >= Buf->BufUsed) {
1205 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1206 Buf->BufUsed -= nChars;
1207 Buf->buf[Buf->BufUsed] = '\0';
1211 * \brief Cut the trailing n Chars from the string
1212 * \param Buf Buffer to modify
1213 * \param nChars how many chars should be trunkated?
1215 void StrBufCutRight(StrBuf *Buf, int nChars)
1217 if (nChars >= Buf->BufUsed) {
1221 Buf->BufUsed -= nChars;
1222 Buf->buf[Buf->BufUsed] = '\0';
1226 * \brief Cut the string after n Chars
1227 * \param Buf Buffer to modify
1228 * \param AfternChars after how many chars should we trunkate the string?
1229 * \param At if non-null and points inside of our string, cut it there.
1231 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1234 AfternChars = At - Buf->buf;
1237 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1239 Buf->BufUsed = AfternChars;
1240 Buf->buf[Buf->BufUsed] = '\0';
1245 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1246 * buf - the string to modify
1247 * len - length of the string.
1249 void StrBufTrim(StrBuf *Buf)
1252 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1254 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1257 if (delta > 0) StrBufCutLeft(Buf, delta);
1259 if (Buf->BufUsed == 0) return;
1260 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1263 Buf->buf[Buf->BufUsed] = '\0';
1267 void StrBufUpCase(StrBuf *Buf)
1272 pche = pch + Buf->BufUsed;
1273 while (pch < pche) {
1274 *pch = toupper(*pch);
1280 void StrBufLowerCase(StrBuf *Buf)
1285 pche = pch + Buf->BufUsed;
1286 while (pch < pche) {
1287 *pch = tolower(*pch);
1294 * \brief unhide special chars hidden to the HTML escaper
1295 * \param target buffer to put the unescaped string in
1296 * \param source buffer to unescape
1298 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1304 FlushStrBuf(target);
1306 if (source == NULL ||target == NULL)
1311 len = source->BufUsed;
1312 for (a = 0; a < len; ++a) {
1313 if (target->BufUsed >= target->BufSize)
1314 IncreaseBuf(target, 1, -1);
1316 if (source->buf[a] == '=') {
1317 hex[0] = source->buf[a + 1];
1318 hex[1] = source->buf[a + 2];
1321 sscanf(hex, "%02x", &b);
1322 target->buf[target->BufUsed] = b;
1323 target->buf[++target->BufUsed] = 0;
1327 target->buf[target->BufUsed] = source->buf[a];
1328 target->buf[++target->BufUsed] = 0;
1335 * \brief hide special chars from the HTML escapers and friends
1336 * \param target buffer to put the escaped string in
1337 * \param source buffer to escape
1339 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1344 FlushStrBuf(target);
1346 if (source == NULL ||target == NULL)
1351 len = source->BufUsed;
1352 for (i=0; i<len; ++i) {
1353 if (target->BufUsed + 4 >= target->BufSize)
1354 IncreaseBuf(target, 1, -1);
1355 if ( (isalnum(source->buf[i])) ||
1356 (source->buf[i]=='-') ||
1357 (source->buf[i]=='_') ) {
1358 target->buf[target->BufUsed++] = source->buf[i];
1361 sprintf(&target->buf[target->BufUsed],
1363 (0xFF &source->buf[i]));
1364 target->BufUsed += 3;
1367 target->buf[target->BufUsed + 1] = '\0';
1371 * \brief uses the same calling syntax as compress2(), but it
1372 * creates a stream compatible with HTTP "Content-encoding: gzip"
1375 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1376 #define OS_CODE 0x03 /*< unix */
1377 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1378 size_t * destLen, /*< length of the compresed data */
1379 const Bytef * source, /*< source to encode */
1380 uLong sourceLen, /*< length of source to encode */
1381 int level) /*< compression level */
1383 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1385 /* write gzip header */
1386 snprintf((char *) dest, *destLen,
1387 "%c%c%c%c%c%c%c%c%c%c",
1388 gz_magic[0], gz_magic[1], Z_DEFLATED,
1389 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1392 /* normal deflate */
1395 stream.next_in = (Bytef *) source;
1396 stream.avail_in = (uInt) sourceLen;
1397 stream.next_out = dest + 10L; // after header
1398 stream.avail_out = (uInt) * destLen;
1399 if ((uLong) stream.avail_out != *destLen)
1402 stream.zalloc = (alloc_func) 0;
1403 stream.zfree = (free_func) 0;
1404 stream.opaque = (voidpf) 0;
1406 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1407 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1411 err = deflate(&stream, Z_FINISH);
1412 if (err != Z_STREAM_END) {
1413 deflateEnd(&stream);
1414 return err == Z_OK ? Z_BUF_ERROR : err;
1416 *destLen = stream.total_out + 10L;
1418 /* write CRC and Length */
1419 uLong crc = crc32(0L, source, sourceLen);
1421 for (n = 0; n < 4; ++n, ++*destLen) {
1422 dest[*destLen] = (int) (crc & 0xff);
1425 uLong len = stream.total_in;
1426 for (n = 0; n < 4; ++n, ++*destLen) {
1427 dest[*destLen] = (int) (len & 0xff);
1430 err = deflateEnd(&stream);
1437 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1439 int CompressBuffer(StrBuf *Buf)
1442 char *compressed_data = NULL;
1443 size_t compressed_len, bufsize;
1445 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1446 compressed_data = malloc(compressed_len);
1448 if (compress_gzip((Bytef *) compressed_data,
1451 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1454 Buf->buf = compressed_data;
1455 Buf->BufUsed = compressed_len;
1456 Buf->BufSize = bufsize;
1459 free(compressed_data);
1461 #endif /* HAVE_ZLIB */
1466 * \brief decode a buffer from base 64 encoding; destroys original
1467 * \param Buf Buffor to transform
1469 int StrBufDecodeBase64(StrBuf *Buf)
1473 if (Buf == NULL) return -1;
1475 xferbuf = (char*) malloc(Buf->BufSize);
1476 siz = CtdlDecodeBase64(xferbuf,
1487 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1488 * \param Buf Buffer to translate
1489 * \param StripBlanks Reduce several blanks to one?
1491 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1497 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1498 Buf->buf[Buf->BufUsed - 1] = '\0';
1503 while (a < Buf->BufUsed) {
1504 if (Buf->buf[a] == '+')
1506 else if (Buf->buf[a] == '%') {
1507 /* don't let % chars through, rather truncate the input. */
1508 if (a + 2 > Buf->BufUsed) {
1513 hex[0] = Buf->buf[a + 1];
1514 hex[1] = Buf->buf[a + 2];
1517 sscanf(hex, "%02x", &b);
1518 Buf->buf[a] = (char) b;
1519 len = Buf->BufUsed - a - 2;
1521 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1533 * \brief RFC2047-encode a header field if necessary.
1534 * If no non-ASCII characters are found, the string
1535 * will be copied verbatim without encoding.
1537 * \param target Target buffer.
1538 * \param source Source string to be encoded.
1539 * \returns encoded length; -1 if non success.
1541 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1543 const char headerStr[] = "=?UTF-8?Q?";
1544 int need_to_encode = 0;
1548 if ((source == NULL) ||
1552 while ((i < source->BufUsed) &&
1553 (!IsEmptyStr (&source->buf[i])) &&
1554 (need_to_encode == 0)) {
1555 if (((unsigned char) source->buf[i] < 32) ||
1556 ((unsigned char) source->buf[i] > 126)) {
1562 if (!need_to_encode) {
1563 if (*target == NULL) {
1564 *target = NewStrBufPlain(source->buf, source->BufUsed);
1567 FlushStrBuf(*target);
1568 StrBufAppendBuf(*target, source, 0);
1570 return (*target)->BufUsed;
1572 if (*target == NULL)
1573 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1574 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1575 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1576 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1577 (*target)->BufUsed = sizeof(headerStr) - 1;
1578 for (i=0; (i < source->BufUsed); ++i) {
1579 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1580 IncreaseBuf(*target, 1, 0);
1581 ch = (unsigned char) source->buf[i];
1582 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1583 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1584 (*target)->BufUsed += 3;
1587 (*target)->buf[(*target)->BufUsed] = ch;
1588 (*target)->BufUsed++;
1592 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1593 IncreaseBuf(*target, 1, 0);
1595 (*target)->buf[(*target)->BufUsed++] = '?';
1596 (*target)->buf[(*target)->BufUsed++] = '=';
1597 (*target)->buf[(*target)->BufUsed] = '\0';
1598 return (*target)->BufUsed;;
1602 * \brief replaces all occurances of 'search' by 'replace'
1603 * \param buf Buffer to modify
1604 * \param search character to search
1605 * \param relpace character to replace search by
1607 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1612 for (i=0; i<buf->BufUsed; i++)
1613 if (buf->buf[i] == search)
1614 buf->buf[i] = replace;
1621 * Wrapper around iconv_open()
1622 * Our version adds aliases for non-standard Microsoft charsets
1623 * such as 'MS950', aliasing them to names like 'CP950'
1625 * tocode Target encoding
1626 * fromcode Source encoding
1628 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1631 iconv_t ic = (iconv_t)(-1) ;
1632 ic = iconv_open(tocode, fromcode);
1633 if (ic == (iconv_t)(-1) ) {
1634 char alias_fromcode[64];
1635 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1636 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1637 alias_fromcode[0] = 'C';
1638 alias_fromcode[1] = 'P';
1639 ic = iconv_open(tocode, alias_fromcode);
1642 *(iconv_t *)pic = ic;
1648 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1651 /* Find the next ?Q? */
1652 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1655 end = strchr(bptr + 2, '?');
1660 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1661 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1662 (*(end + 2) == '?')) {
1663 /* skip on to the end of the cluster, the next ?= */
1664 end = strstr(end + 3, "?=");
1667 /* sort of half valid encoding, try to find an end. */
1668 end = strstr(bptr, "?=");
1673 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1678 char *ibuf; /**< Buffer of characters to be converted */
1679 char *obuf; /**< Buffer for converted characters */
1680 size_t ibuflen; /**< Length of input buffer */
1681 size_t obuflen; /**< Length of output buffer */
1684 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1685 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1687 ic = *(iconv_t*)pic;
1688 ibuf = ConvertBuf->buf;
1689 ibuflen = ConvertBuf->BufUsed;
1691 obuflen = TmpBuf->BufSize;
1693 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1695 /* little card game: wheres the red lady? */
1696 ibuf = ConvertBuf->buf;
1697 BufSize = ConvertBuf->BufSize;
1699 ConvertBuf->buf = TmpBuf->buf;
1700 ConvertBuf->BufSize = TmpBuf->BufSize;
1701 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1702 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1705 TmpBuf->BufSize = BufSize;
1706 TmpBuf->BufUsed = 0;
1707 TmpBuf->buf[0] = '\0';
1714 inline static void DecodeSegment(StrBuf *Target,
1715 const StrBuf *DecodeMe,
1719 StrBuf *ConvertBuf2,
1720 StrBuf *FoundCharset)
1725 iconv_t ic = (iconv_t)(-1);
1727 /* Now we handle foreign character sets properly encoded
1728 * in RFC2047 format.
1730 StaticBuf.buf = SegmentStart;
1731 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1732 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1733 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1734 if (FoundCharset != NULL) {
1735 FlushStrBuf(FoundCharset);
1736 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1738 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1739 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1741 *encoding = toupper(*encoding);
1742 if (*encoding == 'B') { /**< base64 */
1743 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1745 ConvertBuf->BufUsed);
1747 else if (*encoding == 'Q') { /**< quoted-printable */
1751 while (pos < ConvertBuf->BufUsed)
1753 if (ConvertBuf->buf[pos] == '_')
1754 ConvertBuf->buf[pos] = ' ';
1758 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1761 ConvertBuf->BufUsed);
1764 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1767 ctdl_iconv_open("UTF-8", charset, &ic);
1768 if (ic != (iconv_t)(-1) ) {
1769 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1770 StrBufAppendBuf(Target, ConvertBuf2, 0);
1774 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1778 * Handle subjects with RFC2047 encoding such as:
1779 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1781 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1783 StrBuf *ConvertBuf, *ConvertBuf2;
1784 char *start, *end, *next, *nextend, *ptr = NULL;
1785 iconv_t ic = (iconv_t)(-1) ;
1789 int illegal_non_rfc2047_encoding = 0;
1791 /* Sometimes, badly formed messages contain strings which were simply
1792 * written out directly in some foreign character set instead of
1793 * using RFC2047 encoding. This is illegal but we will attempt to
1794 * handle it anyway by converting from a user-specified default
1795 * charset to UTF-8 if we see any nonprintable characters.
1798 len = StrLength(DecodeMe);
1799 for (i=0; i<DecodeMe->BufUsed; ++i) {
1800 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1801 illegal_non_rfc2047_encoding = 1;
1806 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1807 if ((illegal_non_rfc2047_encoding) &&
1808 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1809 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1811 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1812 if (ic != (iconv_t)(-1) ) {
1813 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1818 /* pre evaluate the first pair */
1819 nextend = end = NULL;
1820 len = StrLength(DecodeMe);
1821 start = strstr(DecodeMe->buf, "=?");
1822 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1824 end = FindNextEnd (DecodeMe, start);
1826 StrBufAppendBuf(Target, DecodeMe, 0);
1827 FreeStrBuf(&ConvertBuf);
1831 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1833 if (start != DecodeMe->buf)
1834 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1836 * Since spammers will go to all sorts of absurd lengths to get their
1837 * messages through, there are LOTS of corrupt headers out there.
1838 * So, prevent a really badly formed RFC2047 header from throwing
1839 * this function into an infinite loop.
1841 while ((start != NULL) &&
1848 DecodeSegment(Target,
1856 next = strstr(end, "=?");
1858 if ((next != NULL) &&
1860 nextend = FindNextEnd(DecodeMe, next);
1861 if (nextend == NULL)
1864 /* did we find two partitions */
1865 if ((next != NULL) &&
1869 while ((ptr < next) &&
1875 /* did we find a gab just filled with blanks? */
1880 len - (next - start));
1882 /* now terminate the gab at the end */
1883 delta = (next - end) - 2; ////TODO: const!
1884 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1885 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1887 /* move next to its new location. */
1892 /* our next-pair is our new first pair now. */
1898 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1899 if ((end != NULL) && (end < nextend)) {
1901 while ( (ptr < nextend) &&
1908 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1910 FreeStrBuf(&ConvertBuf);
1911 FreeStrBuf(&ConvertBuf2);
1916 long StrBuf_Utf8StrLen(StrBuf *Buf)
1918 return Ctdl_Utf8StrLen(Buf->buf);
1921 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1925 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1926 if (CutAt != NULL) {
1927 Buf->BufUsed = CutAt - Buf->buf;
1928 Buf->buf[Buf->BufUsed] = '\0';
1930 return Buf->BufUsed;
1935 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1937 const char *aptr, *ptr, *eptr;
1944 ptr = aptr = Buf->buf;
1948 optr = LineBuf->buf;
1949 eptr = Buf->buf + Buf->BufUsed;
1950 xptr = LineBuf->buf + LineBuf->BufSize;
1952 while ((*ptr != '\n') &&
1959 LineBuf->BufUsed = optr - LineBuf->buf;
1960 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1961 optr = LineBuf->buf + LineBuf->BufUsed;
1962 xptr = LineBuf->buf + LineBuf->BufSize;
1965 LineBuf->BufUsed = optr - LineBuf->buf;
1974 return Buf->BufUsed - (ptr - Buf->buf);