8 #include <sys/select.h>
10 #define SHOW_ME_VAPPEND_PRINTF
12 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
30 * Private Structure for the Stringbuffer
33 char *buf; /**< the pointer to the dynamic buffer */
34 long BufSize; /**< how many spcae do we optain */
35 long BufUsed; /**< Number of Chars used excluding the trailing \0 */
36 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 * \Brief Cast operator to Plain String
42 * Note: if the buffer is altered by StrBuf operations, this pointer may become
43 * invalid. So don't lean on it after altering the buffer!
44 * Since this operation is considered cheap, rather call it often than risking
45 * your pointer to become invalid!
46 * \param Str the string we want to get the c-string representation for
47 * \returns the Pointer to the Content. Don't mess with it!
49 inline const char *ChrPtr(const StrBuf *Str)
57 * \brief since we know strlen()'s result, provide it here.
58 * \param Str the string to return the length to
59 * \returns contentlength of the buffer
61 inline int StrLength(const StrBuf *Str)
63 return (Str != NULL) ? Str->BufUsed : 0;
67 * \brief local utility function to resize the buffer
68 * \param Buf the buffer whichs storage we should increase
69 * \param KeepOriginal should we copy the original buffer or just start over with a new one
70 * \param DestSize what should fit in after?
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
75 size_t NewSize = Buf->BufSize * 2;
81 while (NewSize <= DestSize)
84 NewBuf= (char*) malloc(NewSize);
85 if (KeepOriginal && (Buf->BufUsed > 0))
87 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
101 * Allocate a new buffer with default buffer size
102 * \returns the new stringbuffer
104 StrBuf* NewStrBuf(void)
108 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109 NewBuf->buf = (char*) malloc(SIZ);
110 NewBuf->buf[0] = '\0';
111 NewBuf->BufSize = SIZ;
113 NewBuf->ConstBuf = 0;
118 * \brief Copy Constructor; returns a duplicate of CopyMe
119 * \params CopyMe Buffer to faxmilate
120 * \returns the new stringbuffer
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
129 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132 NewBuf->BufUsed = CopyMe->BufUsed;
133 NewBuf->BufSize = CopyMe->BufSize;
134 NewBuf->ConstBuf = 0;
139 * \brief create a new Buffer using an existing c-string
140 * this function should also be used if you want to pre-suggest
141 * the buffer size to allocate in conjunction with ptr == NULL
142 * \param ptr the c-string to copy; may be NULL to create a blank instance
143 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144 * \returns the new stringbuffer
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
152 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
154 CopySize = strlen((ptr != NULL)?ptr:"");
158 while (Siz <= CopySize)
161 NewBuf->buf = (char*) malloc(Siz);
162 NewBuf->BufSize = Siz;
164 memcpy(NewBuf->buf, ptr, CopySize);
165 NewBuf->buf[CopySize] = '\0';
166 NewBuf->BufUsed = CopySize;
169 NewBuf->buf[0] = '\0';
172 NewBuf->ConstBuf = 0;
177 * \brief Set an existing buffer from a c-string
178 * \param ptr c-string to put into
179 * \param nChars set to -1 if we should work 0-terminated
180 * \returns the new length of the string
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
184 size_t Siz = Buf->BufSize;
188 CopySize = strlen(ptr);
192 while (Siz <= CopySize)
195 if (Siz != Buf->BufSize)
196 IncreaseBuf(Buf, 0, Siz);
197 memcpy(Buf->buf, ptr, CopySize);
198 Buf->buf[CopySize] = '\0';
199 Buf->BufUsed = CopySize;
206 * \brief use strbuf as wrapper for a string constant for easy handling
207 * \param StringConstant a string to wrap
208 * \param SizeOfConstant should be sizeof(StringConstant)-1
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) StringConstant;
216 NewBuf->BufSize = SizeOfStrConstant;
217 NewBuf->BufUsed = SizeOfStrConstant;
218 NewBuf->ConstBuf = 1;
224 * \brief flush the content of a Buf; keep its struct
225 * \param buf Buffer to flush
227 int FlushStrBuf(StrBuf *buf)
239 * \brief Release a Buffer
240 * Its a double pointer, so it can NULL your pointer
241 * so fancy SIG11 appear instead of random results
242 * \param FreeMe Pointer Pointer to the buffer to free
244 void FreeStrBuf (StrBuf **FreeMe)
248 if (!(*FreeMe)->ConstBuf)
249 free((*FreeMe)->buf);
255 * \brief Release the buffer
256 * If you want put your StrBuf into a Hash, use this as Destructor.
257 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
259 void HFreeStrBuf (void *VFreeMe)
261 StrBuf *FreeMe = (StrBuf*)VFreeMe;
264 if (!FreeMe->ConstBuf)
270 * \brief Wrapper around atol
272 long StrTol(const StrBuf *Buf)
277 return atol(Buf->buf);
283 * \brief Wrapper around atoi
285 int StrToi(const StrBuf *Buf)
289 if (Buf->BufUsed > 0)
290 return atoi(Buf->buf);
295 * \brief Checks to see if the string is a pure number
297 int StrBufIsNumber(const StrBuf *Buf) {
299 strtoll(Buf->buf, &pEnd, 10);
300 return (strlen(pEnd) > 0) ? 0 : 1;
303 * \brief modifies a Single char of the Buf
304 * You can point to it via char* or a zero-based integer
305 * \param ptr char* to zero; use NULL if unused
306 * \param nThChar zero based pointer into the string; use -1 if unused
307 * \param PeekValue The Character to place into the position
309 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
314 nThChar = ptr - Buf->buf;
315 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
317 Buf->buf[nThChar] = PeekValue;
322 * \brief Append a StringBuffer to the buffer
323 * \param Buf Buffer to modify
324 * \param AppendBuf Buffer to copy at the end of our buffer
325 * \param Offset Should we start copying from an offset?
327 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
329 if ((AppendBuf == NULL) || (Buf == NULL))
332 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
335 AppendBuf->BufUsed + Buf->BufUsed);
337 memcpy(Buf->buf + Buf->BufUsed,
338 AppendBuf->buf + Offset,
339 AppendBuf->BufUsed - Offset);
340 Buf->BufUsed += AppendBuf->BufUsed - Offset;
341 Buf->buf[Buf->BufUsed] = '\0';
346 * \brief Append a C-String to the buffer
347 * \param Buf Buffer to modify
348 * \param AppendBuf Buffer to copy at the end of our buffer
349 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
350 * \param Offset Should we start copying from an offset?
352 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
355 long BufSizeRequired;
357 if ((AppendBuf == NULL) || (Buf == NULL))
361 aps = strlen(AppendBuf + Offset);
363 aps = AppendSize - Offset;
365 BufSizeRequired = Buf->BufUsed + aps + 1;
366 if (Buf->BufSize <= BufSizeRequired)
367 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
369 memcpy(Buf->buf + Buf->BufUsed,
373 Buf->buf[Buf->BufUsed] = '\0';
378 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
379 * \param outbuf the output buffer
380 * \param oblen the size of outbuf to sanitize
381 * \param strbuf the input buffer
383 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
385 const char *pch, *pche;
388 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
389 int eclen = sizeof(ec) -1;
391 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
393 if (PlainIn != NULL) {
394 len = strlen(PlainIn);
400 pche = pch + In->BufUsed;
407 pt = OutBuf->buf + OutBuf->BufUsed;
408 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
412 IncreaseBuf(OutBuf, 1, -1);
413 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
414 pt = OutBuf->buf + OutBuf->BufUsed;
418 for (b = 0; b < eclen; ++b) {
425 sprintf(pt,"%%%02X", *pch);
427 OutBuf->BufUsed += 3;
439 * \brief Append a string, escaping characters which have meaning in HTML.
441 * \param Target target buffer
442 * \param Source source buffer; set to NULL if you just have a C-String
443 * \param PlainIn Plain-C string to append; set to NULL if unused
444 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
445 * \param nolinebreaks if set, linebreaks are removed from the string.
447 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
449 const char *aptr, *eiptr;
453 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
456 if (PlainIn != NULL) {
458 len = strlen(PlainIn);
463 eiptr = aptr + Source->BufUsed;
464 len = Source->BufUsed;
470 bptr = Target->buf + Target->BufUsed;
471 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
473 while (aptr < eiptr){
475 IncreaseBuf(Target, 1, -1);
476 eptr = Target->buf + Target->BufSize - 6;
477 bptr = Target->buf + Target->BufUsed;
480 memcpy(bptr, "<", 4);
482 Target->BufUsed += 4;
484 else if (*aptr == '>') {
485 memcpy(bptr, ">", 4);
487 Target->BufUsed += 4;
489 else if (*aptr == '&') {
490 memcpy(bptr, "&", 5);
492 Target->BufUsed += 5;
494 else if (*aptr == '"') {
495 memcpy(bptr, """, 6);
497 Target->BufUsed += 6;
499 else if (*aptr == '\'') {
500 memcpy(bptr, "'", 5);
502 Target->BufUsed += 5;
504 else if (*aptr == LB) {
509 else if (*aptr == RB) {
514 else if (*aptr == QU) {
519 else if ((*aptr == 32) && (nbsp == 1)) {
520 memcpy(bptr, " ", 6);
522 Target->BufUsed += 6;
524 else if ((*aptr == '\n') && (nolinebreaks)) {
525 *bptr='\0'; /* nothing */
527 else if ((*aptr == '\r') && (nolinebreaks)) {
528 *bptr='\0'; /* nothing */
538 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
540 return Target->BufUsed;
544 * \brief Append a string, escaping characters which have meaning in HTML.
545 * Converts linebreaks into blanks; escapes single quotes
546 * \param Target target buffer
547 * \param Source source buffer; set to NULL if you just have a C-String
548 * \param PlainIn Plain-C string to append; set to NULL if unused
550 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
552 const char *aptr, *eiptr;
556 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
559 if (PlainIn != NULL) {
561 len = strlen(PlainIn);
566 eiptr = aptr + Source->BufUsed;
567 len = Source->BufUsed;
573 eptr = Target->buf + Target->BufSize - 6;
574 tptr = Target->buf + Target->BufUsed;
576 while (aptr < eiptr){
578 IncreaseBuf(Target, 1, -1);
579 eptr = Target->buf + Target->BufSize - 6;
580 tptr = Target->buf + Target->BufUsed;
587 else if (*aptr == '\r') {
591 else if (*aptr == '\'') {
597 Target->BufUsed += 5;
609 * \brief extracts a substring from Source into dest
610 * \param dest buffer to place substring into
611 * \param Source string to copy substring from
612 * \param Offset chars to skip from start
613 * \param nChars number of chars to copy
614 * \returns the number of chars copied; may be different from nChars due to the size of Source
616 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
619 if (Offset > Source->BufUsed)
624 if (Offset + nChars < Source->BufUsed)
626 if (nChars > dest->BufSize)
627 IncreaseBuf(dest, 0, nChars + 1);
628 memcpy(dest->buf, Source->buf + Offset, nChars);
629 dest->BufUsed = nChars;
630 dest->buf[dest->BufUsed] = '\0';
633 NCharsRemain = Source->BufUsed - Offset;
634 if (NCharsRemain > dest->BufSize)
635 IncreaseBuf(dest, 0, NCharsRemain + 1);
636 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
637 dest->BufUsed = NCharsRemain;
638 dest->buf[dest->BufUsed] = '\0';
643 * \brief sprintf like function appending the formated string to the buffer
644 * vsnprintf version to wrap into own calls
645 * \param Buf Buffer to extend by format and params
646 * \param format printf alike format to add
647 * \param ap va_list containing the items for format
649 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
652 size_t BufSize = Buf->BufSize;
653 size_t nWritten = Buf->BufSize + 1;
654 size_t Offset = Buf->BufUsed;
655 size_t newused = Offset + nWritten;
657 while (newused >= BufSize) {
659 nWritten = vsnprintf(Buf->buf + Offset,
660 Buf->BufSize - Offset,
663 newused = Offset + nWritten;
664 if (newused >= Buf->BufSize) {
665 IncreaseBuf(Buf, 1, newused);
668 Buf->BufUsed = Offset + nWritten;
669 BufSize = Buf->BufSize;
676 * \brief sprintf like function appending the formated string to the buffer
677 * \param Buf Buffer to extend by format and params
678 * \param format printf alike format to add
679 * \param ap va_list containing the items for format
681 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
683 size_t BufSize = Buf->BufSize;
684 size_t nWritten = Buf->BufSize + 1;
685 size_t Offset = Buf->BufUsed;
686 size_t newused = Offset + nWritten;
689 while (newused >= BufSize) {
690 va_start(arg_ptr, format);
691 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
692 Buf->BufSize - Buf->BufUsed,
695 newused = Buf->BufUsed + nWritten;
696 if (newused >= Buf->BufSize) {
697 IncreaseBuf(Buf, 1, newused);
700 Buf->BufUsed += nWritten;
701 BufSize = Buf->BufSize;
708 * \brief sprintf like function putting the formated string into the buffer
709 * \param Buf Buffer to extend by format and params
710 * \param format printf alike format to add
711 * \param ap va_list containing the items for format
713 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
715 size_t nWritten = Buf->BufSize + 1;
718 while (nWritten >= Buf->BufSize) {
719 va_start(arg_ptr, format);
720 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
722 Buf->BufUsed = nWritten ;
723 if (nWritten >= Buf->BufSize)
724 IncreaseBuf(Buf, 0, 0);
730 * \brief Counts the numbmer of tokens in a buffer
731 * \param Source String to count tokens in
732 * \param tok Tokenizer char to count
733 * \returns numbers of tokenizer chars found
735 inline int StrBufNum_tokens(const StrBuf *source, char tok)
739 return num_tokens(source->buf, tok);
743 * remove_token() - a tokenizer that kills, maims, and destroys
746 * \brief a string tokenizer
747 * \param Source StringBuffer to read into
748 * \param parmnum n'th parameter to remove
749 * \param separator tokenizer param
750 * \returns -1 if not found, else length of token.
752 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
755 char *d, *s; /* dest, source */
758 /* Find desired parameter */
760 while (count < parmnum) {
761 /* End of string, bail! */
766 if (*d == separator) {
771 if (!d) return 0; /* Parameter not found */
773 /* Find next parameter */
775 while (*s && *s != separator) {
783 memmove(d, s, Source->BufUsed - (s - Source->buf));
784 Source->BufUsed -= (ReducedBy + 1);
786 else if (d == Source->buf) {
792 Source->BufUsed -= (ReducedBy + 1);
805 * \brief a string tokenizer
806 * \param dest Destination StringBuffer
807 * \param Source StringBuffer to read into
808 * \param parmnum n'th parameter to extract
809 * \param separator tokenizer param
810 * \returns -1 if not found, else length of token.
812 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
814 const char *s, *e; //* source * /
815 int len = 0; //* running total length of extracted string * /
816 int current_token = 0; //* token currently being processed * /
825 if ((Source == NULL) || (Source->BufUsed ==0)) {
829 e = s + Source->BufUsed;
832 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
834 while ((s<e) && !IsEmptyStr(s)) {
835 if (*s == separator) {
838 if (len >= dest->BufSize)
839 if (!IncreaseBuf(dest, 1, -1))
841 if ( (current_token == parmnum) &&
846 else if (current_token > parmnum) {
852 dest->buf[len] = '\0';
855 if (current_token < parmnum) {
856 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
859 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
865 * \brief a string tokenizer to fetch an integer
866 * \param dest Destination StringBuffer
867 * \param parmnum n'th parameter to extract
868 * \param separator tokenizer param
869 * \returns 0 if not found, else integer representation of the token
871 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
880 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
887 * \brief a string tokenizer to fetch a long integer
888 * \param dest Destination StringBuffer
889 * \param parmnum n'th parameter to extract
890 * \param separator tokenizer param
891 * \returns 0 if not found, else long integer representation of the token
893 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
902 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
910 * \brief a string tokenizer to fetch an unsigned long
911 * \param dest Destination StringBuffer
912 * \param parmnum n'th parameter to extract
913 * \param separator tokenizer param
914 * \returns 0 if not found, else unsigned long representation of the token
916 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
926 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
930 return (unsigned long) atol(pnum);
939 * \brief Read a line from socket
940 * flushes and closes the FD on error
941 * \param buf the buffer to get the input to
942 * \param fd pointer to the filedescriptor to read
943 * \param append Append to an existing string or replace?
944 * \param Error strerror() on error
945 * \returns numbers of chars read
947 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
954 slen = len = buf->BufUsed;
956 rlen = read(*fd, &buf->buf[len], 1);
958 *Error = strerror(errno);
965 if (buf->buf[len] == '\n')
967 if (buf->buf[len] != '\r')
969 if (!(len < buf->BufSize)) {
971 buf->buf[len+1] = '\0';
972 IncreaseBuf(buf, 1, -1);
976 buf->buf[len] = '\0';
981 * \brief Read a line from socket
982 * flushes and closes the FD on error
983 * \param buf the buffer to get the input to
984 * \param fd pointer to the filedescriptor to read
985 * \param append Append to an existing string or replace?
986 * \param Error strerror() on error
987 * \returns numbers of chars read
989 int StrBufTCP_read_buffered_line(StrBuf *Line,
993 int selectresolution,
997 int nSuccessLess = 0;
1003 if (buf->BufUsed > 0) {
1004 pch = strchr(buf->buf, '\n');
1007 len = pch - buf->buf;
1008 if (len > 0 && (*(pch - 1) == '\r') )
1010 StrBufSub(Line, buf, 0, len - rlen);
1011 StrBufCutLeft(buf, len + 1);
1016 if (buf->BufSize - buf->BufUsed < 10)
1017 IncreaseBuf(buf, 1, -1);
1019 fdflags = fcntl(*fd, F_GETFL);
1020 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1023 while ((nSuccessLess < timeout) && (pch == NULL)) {
1024 tv.tv_sec = selectresolution;
1029 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1030 *Error = strerror(errno);
1035 if (FD_ISSET(*fd, &rfds)) {
1037 &buf->buf[buf->BufUsed],
1038 buf->BufSize - buf->BufUsed - 1);
1040 *Error = strerror(errno);
1045 else if (rlen > 0) {
1047 buf->BufUsed += rlen;
1048 buf->buf[buf->BufUsed] = '\0';
1049 if (buf->BufUsed + 10 > buf->BufSize) {
1050 IncreaseBuf(buf, 1, -1);
1052 pch = strchr(buf->buf, '\n');
1060 len = pch - buf->buf;
1061 if (len > 0 && (*(pch - 1) == '\r') )
1063 StrBufSub(Line, buf, 0, len - rlen);
1064 StrBufCutLeft(buf, len + 1);
1072 * \brief Input binary data from socket
1073 * flushes and closes the FD on error
1074 * \param buf the buffer to get the input to
1075 * \param fd pointer to the filedescriptor to read
1076 * \param append Append to an existing string or replace?
1077 * \param nBytes the maximal number of bytes to read
1078 * \param Error strerror() on error
1079 * \returns numbers of chars read
1081 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1085 int len, rlen, slen;
1089 if ((Buf == NULL) || (*fd == -1))
1093 if (Buf->BufUsed + nBytes > Buf->BufSize)
1094 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1096 ptr = Buf->buf + Buf->BufUsed;
1098 slen = len = Buf->BufUsed;
1100 fdflags = fcntl(*fd, F_GETFL);
1102 while (nRead < nBytes) {
1103 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1106 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1107 *Error = strerror(errno);
1112 if ((rlen = read(*fd,
1114 nBytes - nRead)) == -1) {
1117 *Error = strerror(errno);
1122 Buf->BufUsed += rlen;
1124 Buf->buf[Buf->BufUsed] = '\0';
1129 * \brief Cut nChars from the start of the string
1130 * \param Buf Buffer to modify
1131 * \param nChars how many chars should be skipped?
1133 void StrBufCutLeft(StrBuf *Buf, int nChars)
1135 if (nChars >= Buf->BufUsed) {
1139 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1140 Buf->BufUsed -= nChars;
1141 Buf->buf[Buf->BufUsed] = '\0';
1145 * \brief Cut the trailing n Chars from the string
1146 * \param Buf Buffer to modify
1147 * \param nChars how many chars should be trunkated?
1149 void StrBufCutRight(StrBuf *Buf, int nChars)
1151 if (nChars >= Buf->BufUsed) {
1155 Buf->BufUsed -= nChars;
1156 Buf->buf[Buf->BufUsed] = '\0';
1160 * \brief Cut the string after n Chars
1161 * \param Buf Buffer to modify
1162 * \param AfternChars after how many chars should we trunkate the string?
1163 * \param At if non-null and points inside of our string, cut it there.
1165 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1168 AfternChars = At - Buf->buf;
1171 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1173 Buf->BufUsed = AfternChars;
1174 Buf->buf[Buf->BufUsed] = '\0';
1179 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1180 * buf - the string to modify
1181 * len - length of the string.
1183 void StrBufTrim(StrBuf *Buf)
1186 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1188 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1191 if (delta > 0) StrBufCutLeft(Buf, delta);
1193 if (Buf->BufUsed == 0) return;
1194 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1197 Buf->buf[Buf->BufUsed] = '\0';
1201 void StrBufUpCase(StrBuf *Buf)
1206 pche = pch + Buf->BufUsed;
1207 while (pch < pche) {
1208 *pch = toupper(*pch);
1214 void StrBufLowerCase(StrBuf *Buf)
1219 pche = pch + Buf->BufUsed;
1220 while (pch < pche) {
1221 *pch = tolower(*pch);
1228 * \brief unhide special chars hidden to the HTML escaper
1229 * \param target buffer to put the unescaped string in
1230 * \param source buffer to unescape
1232 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1238 FlushStrBuf(target);
1240 if (source == NULL ||target == NULL)
1245 len = source->BufUsed;
1246 for (a = 0; a < len; ++a) {
1247 if (target->BufUsed >= target->BufSize)
1248 IncreaseBuf(target, 1, -1);
1250 if (source->buf[a] == '=') {
1251 hex[0] = source->buf[a + 1];
1252 hex[1] = source->buf[a + 2];
1255 sscanf(hex, "%02x", &b);
1256 target->buf[target->BufUsed] = b;
1257 target->buf[++target->BufUsed] = 0;
1261 target->buf[target->BufUsed] = source->buf[a];
1262 target->buf[++target->BufUsed] = 0;
1269 * \brief hide special chars from the HTML escapers and friends
1270 * \param target buffer to put the escaped string in
1271 * \param source buffer to escape
1273 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1278 FlushStrBuf(target);
1280 if (source == NULL ||target == NULL)
1285 len = source->BufUsed;
1286 for (i=0; i<len; ++i) {
1287 if (target->BufUsed + 4 >= target->BufSize)
1288 IncreaseBuf(target, 1, -1);
1289 if ( (isalnum(source->buf[i])) ||
1290 (source->buf[i]=='-') ||
1291 (source->buf[i]=='_') ) {
1292 target->buf[target->BufUsed++] = source->buf[i];
1295 sprintf(&target->buf[target->BufUsed],
1297 (0xFF &source->buf[i]));
1298 target->BufUsed += 3;
1301 target->buf[target->BufUsed + 1] = '\0';
1305 * \brief uses the same calling syntax as compress2(), but it
1306 * creates a stream compatible with HTTP "Content-encoding: gzip"
1309 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1310 #define OS_CODE 0x03 /*< unix */
1311 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1312 size_t * destLen, /*< length of the compresed data */
1313 const Bytef * source, /*< source to encode */
1314 uLong sourceLen, /*< length of source to encode */
1315 int level) /*< compression level */
1317 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1319 /* write gzip header */
1320 snprintf((char *) dest, *destLen,
1321 "%c%c%c%c%c%c%c%c%c%c",
1322 gz_magic[0], gz_magic[1], Z_DEFLATED,
1323 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1326 /* normal deflate */
1329 stream.next_in = (Bytef *) source;
1330 stream.avail_in = (uInt) sourceLen;
1331 stream.next_out = dest + 10L; // after header
1332 stream.avail_out = (uInt) * destLen;
1333 if ((uLong) stream.avail_out != *destLen)
1336 stream.zalloc = (alloc_func) 0;
1337 stream.zfree = (free_func) 0;
1338 stream.opaque = (voidpf) 0;
1340 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1341 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1345 err = deflate(&stream, Z_FINISH);
1346 if (err != Z_STREAM_END) {
1347 deflateEnd(&stream);
1348 return err == Z_OK ? Z_BUF_ERROR : err;
1350 *destLen = stream.total_out + 10L;
1352 /* write CRC and Length */
1353 uLong crc = crc32(0L, source, sourceLen);
1355 for (n = 0; n < 4; ++n, ++*destLen) {
1356 dest[*destLen] = (int) (crc & 0xff);
1359 uLong len = stream.total_in;
1360 for (n = 0; n < 4; ++n, ++*destLen) {
1361 dest[*destLen] = (int) (len & 0xff);
1364 err = deflateEnd(&stream);
1371 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1373 int CompressBuffer(StrBuf *Buf)
1376 char *compressed_data = NULL;
1377 size_t compressed_len, bufsize;
1379 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1380 compressed_data = malloc(compressed_len);
1382 if (compress_gzip((Bytef *) compressed_data,
1385 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1388 Buf->buf = compressed_data;
1389 Buf->BufUsed = compressed_len;
1390 Buf->BufSize = bufsize;
1393 free(compressed_data);
1395 #endif /* HAVE_ZLIB */
1400 * \brief decode a buffer from base 64 encoding; destroys original
1401 * \param Buf Buffor to transform
1403 int StrBufDecodeBase64(StrBuf *Buf)
1407 if (Buf == NULL) return -1;
1409 xferbuf = (char*) malloc(Buf->BufSize);
1410 siz = CtdlDecodeBase64(xferbuf,
1421 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1422 * \param Buf Buffer to translate
1423 * \param StripBlanks Reduce several blanks to one?
1425 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1431 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1432 Buf->buf[Buf->BufUsed - 1] = '\0';
1437 while (a < Buf->BufUsed) {
1438 if (Buf->buf[a] == '+')
1440 else if (Buf->buf[a] == '%') {
1441 /* don't let % chars through, rather truncate the input. */
1442 if (a + 2 > Buf->BufUsed) {
1447 hex[0] = Buf->buf[a + 1];
1448 hex[1] = Buf->buf[a + 2];
1451 sscanf(hex, "%02x", &b);
1452 Buf->buf[a] = (char) b;
1453 len = Buf->BufUsed - a - 2;
1455 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1467 * \brief RFC2047-encode a header field if necessary.
1468 * If no non-ASCII characters are found, the string
1469 * will be copied verbatim without encoding.
1471 * \param target Target buffer.
1472 * \param source Source string to be encoded.
1473 * \returns encoded length; -1 if non success.
1475 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1477 const char headerStr[] = "=?UTF-8?Q?";
1478 int need_to_encode = 0;
1482 if ((source == NULL) ||
1486 while ((i < source->BufUsed) &&
1487 (!IsEmptyStr (&source->buf[i])) &&
1488 (need_to_encode == 0)) {
1489 if (((unsigned char) source->buf[i] < 32) ||
1490 ((unsigned char) source->buf[i] > 126)) {
1496 if (!need_to_encode) {
1497 if (*target == NULL) {
1498 *target = NewStrBufPlain(source->buf, source->BufUsed);
1501 FlushStrBuf(*target);
1502 StrBufAppendBuf(*target, source, 0);
1504 return (*target)->BufUsed;
1506 if (*target == NULL)
1507 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1508 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1509 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1510 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1511 (*target)->BufUsed = sizeof(headerStr) - 1;
1512 for (i=0; (i < source->BufUsed); ++i) {
1513 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1514 IncreaseBuf(*target, 1, 0);
1515 ch = (unsigned char) source->buf[i];
1516 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1517 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1518 (*target)->BufUsed += 3;
1521 (*target)->buf[(*target)->BufUsed] = ch;
1522 (*target)->BufUsed++;
1526 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1527 IncreaseBuf(*target, 1, 0);
1529 (*target)->buf[(*target)->BufUsed++] = '?';
1530 (*target)->buf[(*target)->BufUsed++] = '=';
1531 (*target)->buf[(*target)->BufUsed] = '\0';
1532 return (*target)->BufUsed;;
1536 * \brief replaces all occurances of 'search' by 'replace'
1537 * \param buf Buffer to modify
1538 * \param search character to search
1539 * \param relpace character to replace search by
1541 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1546 for (i=0; i<buf->BufUsed; i++)
1547 if (buf->buf[i] == search)
1548 buf->buf[i] = replace;
1555 * Wrapper around iconv_open()
1556 * Our version adds aliases for non-standard Microsoft charsets
1557 * such as 'MS950', aliasing them to names like 'CP950'
1559 * tocode Target encoding
1560 * fromcode Source encoding
1562 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1565 iconv_t ic = (iconv_t)(-1) ;
1566 ic = iconv_open(tocode, fromcode);
1567 if (ic == (iconv_t)(-1) ) {
1568 char alias_fromcode[64];
1569 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1570 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1571 alias_fromcode[0] = 'C';
1572 alias_fromcode[1] = 'P';
1573 ic = iconv_open(tocode, alias_fromcode);
1576 *(iconv_t *)pic = ic;
1582 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1585 /* Find the next ?Q? */
1586 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1589 end = strchr(bptr + 2, '?');
1594 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1595 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1596 (*(end + 2) == '?')) {
1597 /* skip on to the end of the cluster, the next ?= */
1598 end = strstr(end + 3, "?=");
1601 /* sort of half valid encoding, try to find an end. */
1602 end = strstr(bptr, "?=");
1607 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1612 char *ibuf; /**< Buffer of characters to be converted */
1613 char *obuf; /**< Buffer for converted characters */
1614 size_t ibuflen; /**< Length of input buffer */
1615 size_t obuflen; /**< Length of output buffer */
1618 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1619 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1621 ic = *(iconv_t*)pic;
1622 ibuf = ConvertBuf->buf;
1623 ibuflen = ConvertBuf->BufUsed;
1625 obuflen = TmpBuf->BufSize;
1627 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1629 /* little card game: wheres the red lady? */
1630 ibuf = ConvertBuf->buf;
1631 BufSize = ConvertBuf->BufSize;
1633 ConvertBuf->buf = TmpBuf->buf;
1634 ConvertBuf->BufSize = TmpBuf->BufSize;
1635 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1636 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1639 TmpBuf->BufSize = BufSize;
1640 TmpBuf->BufUsed = 0;
1641 TmpBuf->buf[0] = '\0';
1648 inline static void DecodeSegment(StrBuf *Target,
1649 const StrBuf *DecodeMe,
1653 StrBuf *ConvertBuf2,
1654 StrBuf *FoundCharset)
1659 iconv_t ic = (iconv_t)(-1);
1661 /* Now we handle foreign character sets properly encoded
1662 * in RFC2047 format.
1664 StaticBuf.buf = SegmentStart;
1665 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1666 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1667 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1668 if (FoundCharset != NULL) {
1669 FlushStrBuf(FoundCharset);
1670 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1672 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1673 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1675 *encoding = toupper(*encoding);
1676 if (*encoding == 'B') { /**< base64 */
1677 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1679 ConvertBuf->BufUsed);
1681 else if (*encoding == 'Q') { /**< quoted-printable */
1685 while (pos < ConvertBuf->BufUsed)
1687 if (ConvertBuf->buf[pos] == '_')
1688 ConvertBuf->buf[pos] = ' ';
1692 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1695 ConvertBuf->BufUsed);
1698 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1701 ctdl_iconv_open("UTF-8", charset, &ic);
1702 if (ic != (iconv_t)(-1) ) {
1703 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1704 StrBufAppendBuf(Target, ConvertBuf2, 0);
1708 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1712 * Handle subjects with RFC2047 encoding such as:
1713 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1715 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1717 StrBuf *ConvertBuf, *ConvertBuf2;
1718 char *start, *end, *next, *nextend, *ptr = NULL;
1719 iconv_t ic = (iconv_t)(-1) ;
1723 int illegal_non_rfc2047_encoding = 0;
1725 /* Sometimes, badly formed messages contain strings which were simply
1726 * written out directly in some foreign character set instead of
1727 * using RFC2047 encoding. This is illegal but we will attempt to
1728 * handle it anyway by converting from a user-specified default
1729 * charset to UTF-8 if we see any nonprintable characters.
1732 len = StrLength(DecodeMe);
1733 for (i=0; i<DecodeMe->BufUsed; ++i) {
1734 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1735 illegal_non_rfc2047_encoding = 1;
1740 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1741 if ((illegal_non_rfc2047_encoding) &&
1742 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1743 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1745 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1746 if (ic != (iconv_t)(-1) ) {
1747 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1752 /* pre evaluate the first pair */
1753 nextend = end = NULL;
1754 len = StrLength(DecodeMe);
1755 start = strstr(DecodeMe->buf, "=?");
1756 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1758 end = FindNextEnd (DecodeMe, start);
1760 StrBufAppendBuf(Target, DecodeMe, 0);
1761 FreeStrBuf(&ConvertBuf);
1765 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1767 if (start != DecodeMe->buf)
1768 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1770 * Since spammers will go to all sorts of absurd lengths to get their
1771 * messages through, there are LOTS of corrupt headers out there.
1772 * So, prevent a really badly formed RFC2047 header from throwing
1773 * this function into an infinite loop.
1775 while ((start != NULL) &&
1782 DecodeSegment(Target,
1790 next = strstr(end, "=?");
1792 if ((next != NULL) &&
1794 nextend = FindNextEnd(DecodeMe, next);
1795 if (nextend == NULL)
1798 /* did we find two partitions */
1799 if ((next != NULL) &&
1803 while ((ptr < next) &&
1809 /* did we find a gab just filled with blanks? */
1814 len - (next - start));
1816 /* now terminate the gab at the end */
1817 delta = (next - end) - 2; ////TODO: const!
1818 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1819 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1821 /* move next to its new location. */
1826 /* our next-pair is our new first pair now. */
1832 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1833 if ((end != NULL) && (end < nextend)) {
1835 while ( (ptr < nextend) &&
1842 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1844 FreeStrBuf(&ConvertBuf);
1845 FreeStrBuf(&ConvertBuf2);
1850 long StrBuf_Utf8StrLen(StrBuf *Buf)
1852 return Ctdl_Utf8StrLen(Buf->buf);
1855 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1859 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1860 if (CutAt != NULL) {
1861 Buf->BufUsed = CutAt - Buf->buf;
1862 Buf->buf[Buf->BufUsed] = '\0';
1864 return Buf->BufUsed;
1869 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1871 const char *aptr, *ptr, *eptr;
1878 ptr = aptr = Buf->buf;
1882 optr = LineBuf->buf;
1883 eptr = Buf->buf + Buf->BufUsed;
1884 xptr = LineBuf->buf + LineBuf->BufSize;
1886 while ((*ptr != '\n') &&
1893 LineBuf->BufUsed = optr - LineBuf->buf;
1894 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1895 optr = LineBuf->buf + LineBuf->BufUsed;
1896 xptr = LineBuf->buf + LineBuf->BufSize;
1899 LineBuf->BufUsed = optr - LineBuf->buf;
1908 return Buf->BufUsed - (ptr - Buf->buf);