8 #include <sys/select.h>
10 #define SHOW_ME_VAPPEND_PRINTF
12 #include "libcitadel.h"
25 int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
26 const Bytef * source, uLong sourceLen, int level);
30 * Private Structure for the Stringbuffer
33 char *buf; /**< the pointer to the dynamic buffer */
34 long BufSize; /**< how many spcae do we optain */
35 long BufUsed; /**< Number of Chars used excluding the trailing \0 */
36 int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
41 * \Brief Cast operator to Plain String
42 * Note: if the buffer is altered by StrBuf operations, this pointer may become
43 * invalid. So don't lean on it after altering the buffer!
44 * Since this operation is considered cheap, rather call it often than risking
45 * your pointer to become invalid!
46 * \param Str the string we want to get the c-string representation for
47 * \returns the Pointer to the Content. Don't mess with it!
49 inline const char *ChrPtr(const StrBuf *Str)
57 * \brief since we know strlen()'s result, provide it here.
58 * \param Str the string to return the length to
59 * \returns contentlength of the buffer
61 inline int StrLength(const StrBuf *Str)
63 return (Str != NULL) ? Str->BufUsed : 0;
67 * \brief local utility function to resize the buffer
68 * \param Buf the buffer whichs storage we should increase
69 * \param KeepOriginal should we copy the original buffer or just start over with a new one
70 * \param DestSize what should fit in after?
72 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
75 size_t NewSize = Buf->BufSize * 2;
81 while (NewSize <= DestSize)
84 NewBuf= (char*) malloc(NewSize);
85 if (KeepOriginal && (Buf->BufUsed > 0))
87 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
101 * Allocate a new buffer with default buffer size
102 * \returns the new stringbuffer
104 StrBuf* NewStrBuf(void)
108 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
109 NewBuf->buf = (char*) malloc(SIZ);
110 NewBuf->buf[0] = '\0';
111 NewBuf->BufSize = SIZ;
113 NewBuf->ConstBuf = 0;
118 * \brief Copy Constructor; returns a duplicate of CopyMe
119 * \params CopyMe Buffer to faxmilate
120 * \returns the new stringbuffer
122 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
129 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
130 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
131 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
132 NewBuf->BufUsed = CopyMe->BufUsed;
133 NewBuf->BufSize = CopyMe->BufSize;
134 NewBuf->ConstBuf = 0;
139 * \brief create a new Buffer using an existing c-string
140 * this function should also be used if you want to pre-suggest
141 * the buffer size to allocate in conjunction with ptr == NULL
142 * \param ptr the c-string to copy; may be NULL to create a blank instance
143 * \param nChars How many chars should we copy; -1 if we should measure the length ourselves
144 * \returns the new stringbuffer
146 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
152 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
154 CopySize = strlen((ptr != NULL)?ptr:"");
158 while (Siz <= CopySize)
161 NewBuf->buf = (char*) malloc(Siz);
162 NewBuf->BufSize = Siz;
164 memcpy(NewBuf->buf, ptr, CopySize);
165 NewBuf->buf[CopySize] = '\0';
166 NewBuf->BufUsed = CopySize;
169 NewBuf->buf[0] = '\0';
172 NewBuf->ConstBuf = 0;
177 * \brief Set an existing buffer from a c-string
178 * \param ptr c-string to put into
179 * \param nChars set to -1 if we should work 0-terminated
180 * \returns the new length of the string
182 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
184 size_t Siz = Buf->BufSize;
188 CopySize = strlen(ptr);
192 while (Siz <= CopySize)
195 if (Siz != Buf->BufSize)
196 IncreaseBuf(Buf, 0, Siz);
197 memcpy(Buf->buf, ptr, CopySize);
198 Buf->buf[CopySize] = '\0';
199 Buf->BufUsed = CopySize;
206 * \brief use strbuf as wrapper for a string constant for easy handling
207 * \param StringConstant a string to wrap
208 * \param SizeOfConstant should be sizeof(StringConstant)-1
210 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
214 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
215 NewBuf->buf = (char*) StringConstant;
216 NewBuf->BufSize = SizeOfStrConstant;
217 NewBuf->BufUsed = SizeOfStrConstant;
218 NewBuf->ConstBuf = 1;
224 * \brief flush the content of a Buf; keep its struct
225 * \param buf Buffer to flush
227 int FlushStrBuf(StrBuf *buf)
239 * \brief Release a Buffer
240 * Its a double pointer, so it can NULL your pointer
241 * so fancy SIG11 appear instead of random results
242 * \param FreeMe Pointer Pointer to the buffer to free
244 void FreeStrBuf (StrBuf **FreeMe)
248 if (!(*FreeMe)->ConstBuf)
249 free((*FreeMe)->buf);
255 * \brief Release the buffer
256 * If you want put your StrBuf into a Hash, use this as Destructor.
257 * \param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
259 void HFreeStrBuf (void *VFreeMe)
261 StrBuf *FreeMe = (StrBuf*)VFreeMe;
264 if (!FreeMe->ConstBuf)
270 * \brief Wrapper around atol
272 long StrTol(const StrBuf *Buf)
277 return atol(Buf->buf);
283 * \brief Wrapper around atoi
285 int StrToi(const StrBuf *Buf)
289 if (Buf->BufUsed > 0)
290 return atoi(Buf->buf);
296 * \brief modifies a Single char of the Buf
297 * You can point to it via char* or a zero-based integer
298 * \param ptr char* to zero; use NULL if unused
299 * \param nThChar zero based pointer into the string; use -1 if unused
300 * \param PeekValue The Character to place into the position
302 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
307 nThChar = ptr - Buf->buf;
308 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
310 Buf->buf[nThChar] = PeekValue;
315 * \brief Append a StringBuffer to the buffer
316 * \param Buf Buffer to modify
317 * \param AppendBuf Buffer to copy at the end of our buffer
318 * \param Offset Should we start copying from an offset?
320 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
322 if ((AppendBuf == NULL) || (Buf == NULL))
325 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
328 AppendBuf->BufUsed + Buf->BufUsed);
330 memcpy(Buf->buf + Buf->BufUsed,
331 AppendBuf->buf + Offset,
332 AppendBuf->BufUsed - Offset);
333 Buf->BufUsed += AppendBuf->BufUsed - Offset;
334 Buf->buf[Buf->BufUsed] = '\0';
339 * \brief Append a C-String to the buffer
340 * \param Buf Buffer to modify
341 * \param AppendBuf Buffer to copy at the end of our buffer
342 * \param AppendSize number of bytes to copy; set to -1 if we should count it in advance
343 * \param Offset Should we start copying from an offset?
345 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
348 long BufSizeRequired;
350 if ((AppendBuf == NULL) || (Buf == NULL))
354 aps = strlen(AppendBuf + Offset);
356 aps = AppendSize - Offset;
358 BufSizeRequired = Buf->BufUsed + aps + 1;
359 if (Buf->BufSize <= BufSizeRequired)
360 IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
362 memcpy(Buf->buf + Buf->BufUsed,
366 Buf->buf[Buf->BufUsed] = '\0';
371 * \brief Escape a string for feeding out as a URL while appending it to a Buffer
372 * \param outbuf the output buffer
373 * \param oblen the size of outbuf to sanitize
374 * \param strbuf the input buffer
376 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
378 const char *pch, *pche;
381 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
382 int eclen = sizeof(ec) -1;
384 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
386 if (PlainIn != NULL) {
387 len = strlen(PlainIn);
393 pche = pch + In->BufUsed;
400 pt = OutBuf->buf + OutBuf->BufUsed;
401 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
405 IncreaseBuf(OutBuf, 1, -1);
406 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
407 pt = OutBuf->buf + OutBuf->BufUsed;
411 for (b = 0; b < eclen; ++b) {
418 sprintf(pt,"%%%02X", *pch);
420 OutBuf->BufUsed += 3;
432 * \brief Append a string, escaping characters which have meaning in HTML.
434 * \param Target target buffer
435 * \param Source source buffer; set to NULL if you just have a C-String
436 * \param PlainIn Plain-C string to append; set to NULL if unused
437 * \param nbsp If nonzero, spaces are converted to non-breaking spaces.
438 * \param nolinebreaks if set, linebreaks are removed from the string.
440 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
442 const char *aptr, *eiptr;
446 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
449 if (PlainIn != NULL) {
451 len = strlen(PlainIn);
456 eiptr = aptr + Source->BufUsed;
457 len = Source->BufUsed;
463 bptr = Target->buf + Target->BufUsed;
464 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
466 while (aptr < eiptr){
468 IncreaseBuf(Target, 1, -1);
469 eptr = Target->buf + Target->BufSize - 6;
470 bptr = Target->buf + Target->BufUsed;
473 memcpy(bptr, "<", 4);
475 Target->BufUsed += 4;
477 else if (*aptr == '>') {
478 memcpy(bptr, ">", 4);
480 Target->BufUsed += 4;
482 else if (*aptr == '&') {
483 memcpy(bptr, "&", 5);
485 Target->BufUsed += 5;
487 else if (*aptr == '"') {
488 memcpy(bptr, """, 6);
490 Target->BufUsed += 6;
492 else if (*aptr == '\'') {
493 memcpy(bptr, "'", 5);
495 Target->BufUsed += 5;
497 else if (*aptr == LB) {
502 else if (*aptr == RB) {
507 else if (*aptr == QU) {
512 else if ((*aptr == 32) && (nbsp == 1)) {
513 memcpy(bptr, " ", 6);
515 Target->BufUsed += 6;
517 else if ((*aptr == '\n') && (nolinebreaks)) {
518 *bptr='\0'; /* nothing */
520 else if ((*aptr == '\r') && (nolinebreaks)) {
521 *bptr='\0'; /* nothing */
531 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
533 return Target->BufUsed;
537 * \brief Append a string, escaping characters which have meaning in HTML.
538 * Converts linebreaks into blanks; escapes single quotes
539 * \param Target target buffer
540 * \param Source source buffer; set to NULL if you just have a C-String
541 * \param PlainIn Plain-C string to append; set to NULL if unused
543 void StrMsgEscAppend(StrBuf *Target, StrBuf *Source, const char *PlainIn)
545 const char *aptr, *eiptr;
549 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
552 if (PlainIn != NULL) {
554 len = strlen(PlainIn);
559 eiptr = aptr + Source->BufUsed;
560 len = Source->BufUsed;
566 eptr = Target->buf + Target->BufSize - 6;
567 tptr = Target->buf + Target->BufUsed;
569 while (aptr < eiptr){
571 IncreaseBuf(Target, 1, -1);
572 eptr = Target->buf + Target->BufSize - 6;
573 tptr = Target->buf + Target->BufUsed;
580 else if (*aptr == '\r') {
584 else if (*aptr == '\'') {
590 Target->BufUsed += 5;
602 * \brief extracts a substring from Source into dest
603 * \param dest buffer to place substring into
604 * \param Source string to copy substring from
605 * \param Offset chars to skip from start
606 * \param nChars number of chars to copy
607 * \returns the number of chars copied; may be different from nChars due to the size of Source
609 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
612 if (Offset > Source->BufUsed)
617 if (Offset + nChars < Source->BufUsed)
619 if (nChars > dest->BufSize)
620 IncreaseBuf(dest, 0, nChars + 1);
621 memcpy(dest->buf, Source->buf + Offset, nChars);
622 dest->BufUsed = nChars;
623 dest->buf[dest->BufUsed] = '\0';
626 NCharsRemain = Source->BufUsed - Offset;
627 if (NCharsRemain > dest->BufSize)
628 IncreaseBuf(dest, 0, NCharsRemain + 1);
629 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
630 dest->BufUsed = NCharsRemain;
631 dest->buf[dest->BufUsed] = '\0';
636 * \brief sprintf like function appending the formated string to the buffer
637 * vsnprintf version to wrap into own calls
638 * \param Buf Buffer to extend by format and params
639 * \param format printf alike format to add
640 * \param ap va_list containing the items for format
642 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
645 size_t BufSize = Buf->BufSize;
646 size_t nWritten = Buf->BufSize + 1;
647 size_t Offset = Buf->BufUsed;
648 size_t newused = Offset + nWritten;
650 while (newused >= BufSize) {
652 nWritten = vsnprintf(Buf->buf + Offset,
653 Buf->BufSize - Offset,
656 newused = Offset + nWritten;
657 if (newused >= Buf->BufSize) {
658 IncreaseBuf(Buf, 1, newused);
661 Buf->BufUsed = Offset + nWritten;
662 BufSize = Buf->BufSize;
669 * \brief sprintf like function appending the formated string to the buffer
670 * \param Buf Buffer to extend by format and params
671 * \param format printf alike format to add
672 * \param ap va_list containing the items for format
674 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
676 size_t BufSize = Buf->BufSize;
677 size_t nWritten = Buf->BufSize + 1;
678 size_t Offset = Buf->BufUsed;
679 size_t newused = Offset + nWritten;
682 while (newused >= BufSize) {
683 va_start(arg_ptr, format);
684 nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
685 Buf->BufSize - Buf->BufUsed,
688 newused = Buf->BufUsed + nWritten;
689 if (newused >= Buf->BufSize) {
690 IncreaseBuf(Buf, 1, newused);
693 Buf->BufUsed += nWritten;
694 BufSize = Buf->BufSize;
701 * \brief sprintf like function putting the formated string into the buffer
702 * \param Buf Buffer to extend by format and params
703 * \param format printf alike format to add
704 * \param ap va_list containing the items for format
706 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
708 size_t nWritten = Buf->BufSize + 1;
711 while (nWritten >= Buf->BufSize) {
712 va_start(arg_ptr, format);
713 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
715 Buf->BufUsed = nWritten ;
716 if (nWritten >= Buf->BufSize)
717 IncreaseBuf(Buf, 0, 0);
723 * \brief Counts the numbmer of tokens in a buffer
724 * \param Source String to count tokens in
725 * \param tok Tokenizer char to count
726 * \returns numbers of tokenizer chars found
728 inline int StrBufNum_tokens(const StrBuf *source, char tok)
732 return num_tokens(source->buf, tok);
736 * remove_token() - a tokenizer that kills, maims, and destroys
739 * \brief a string tokenizer
740 * \param Source StringBuffer to read into
741 * \param parmnum n'th parameter to remove
742 * \param separator tokenizer param
743 * \returns -1 if not found, else length of token.
745 int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
748 char *d, *s; /* dest, source */
751 /* Find desired parameter */
753 while (count < parmnum) {
754 /* End of string, bail! */
759 if (*d == separator) {
764 if (!d) return 0; /* Parameter not found */
766 /* Find next parameter */
768 while (*s && *s != separator) {
776 memmove(d, s, Source->BufUsed - (s - Source->buf));
777 Source->BufUsed -= (ReducedBy + 1);
779 else if (d == Source->buf) {
785 Source->BufUsed -= (ReducedBy + 1);
798 * \brief a string tokenizer
799 * \param dest Destination StringBuffer
800 * \param Source StringBuffer to read into
801 * \param parmnum n'th parameter to extract
802 * \param separator tokenizer param
803 * \returns -1 if not found, else length of token.
805 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
807 const char *s, *e; //* source * /
808 int len = 0; //* running total length of extracted string * /
809 int current_token = 0; //* token currently being processed * /
818 if ((Source == NULL) || (Source->BufUsed ==0)) {
822 e = s + Source->BufUsed;
825 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
827 while ((s<e) && !IsEmptyStr(s)) {
828 if (*s == separator) {
831 if (len >= dest->BufSize)
832 if (!IncreaseBuf(dest, 1, -1))
834 if ( (current_token == parmnum) &&
839 else if (current_token > parmnum) {
845 dest->buf[len] = '\0';
848 if (current_token < parmnum) {
849 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
852 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
858 * \brief a string tokenizer to fetch an integer
859 * \param dest Destination StringBuffer
860 * \param parmnum n'th parameter to extract
861 * \param separator tokenizer param
862 * \returns 0 if not found, else integer representation of the token
864 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
873 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
880 * \brief a string tokenizer to fetch a long integer
881 * \param dest Destination StringBuffer
882 * \param parmnum n'th parameter to extract
883 * \param separator tokenizer param
884 * \returns 0 if not found, else long integer representation of the token
886 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
895 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
903 * \brief a string tokenizer to fetch an unsigned long
904 * \param dest Destination StringBuffer
905 * \param parmnum n'th parameter to extract
906 * \param separator tokenizer param
907 * \returns 0 if not found, else unsigned long representation of the token
909 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
919 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
923 return (unsigned long) atol(pnum);
932 * \brief Read a line from socket
933 * flushes and closes the FD on error
934 * \param buf the buffer to get the input to
935 * \param fd pointer to the filedescriptor to read
936 * \param append Append to an existing string or replace?
937 * \param Error strerror() on error
938 * \returns numbers of chars read
940 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
947 slen = len = buf->BufUsed;
949 rlen = read(*fd, &buf->buf[len], 1);
951 *Error = strerror(errno);
958 if (buf->buf[len] == '\n')
960 if (buf->buf[len] != '\r')
962 if (!(len < buf->BufSize)) {
964 buf->buf[len+1] = '\0';
965 IncreaseBuf(buf, 1, -1);
969 buf->buf[len] = '\0';
974 * \brief Read a line from socket
975 * flushes and closes the FD on error
976 * \param buf the buffer to get the input to
977 * \param fd pointer to the filedescriptor to read
978 * \param append Append to an existing string or replace?
979 * \param Error strerror() on error
980 * \returns numbers of chars read
982 int StrBufTCP_read_buffered_line(StrBuf *Line,
986 int selectresolution,
990 int nSuccessLess = 0;
996 if (buf->BufUsed > 0) {
997 pch = strchr(buf->buf, '\n');
1000 len = pch - buf->buf;
1001 if (len > 0 && (*(pch - 1) == '\r') )
1003 StrBufSub(Line, buf, 0, len - rlen);
1004 StrBufCutLeft(buf, len + 1);
1009 if (buf->BufSize - buf->BufUsed < 10)
1010 IncreaseBuf(buf, 1, -1);
1012 fdflags = fcntl(*fd, F_GETFL);
1013 if ((fdflags & O_NONBLOCK) == O_NONBLOCK)
1016 while ((nSuccessLess < timeout) && (pch == NULL)) {
1017 tv.tv_sec = selectresolution;
1022 if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
1023 *Error = strerror(errno);
1028 if (FD_ISSET(*fd, &rfds)) {
1030 &buf->buf[buf->BufUsed],
1031 buf->BufSize - buf->BufUsed - 1);
1033 *Error = strerror(errno);
1038 else if (rlen > 0) {
1040 buf->BufUsed += rlen;
1041 buf->buf[buf->BufUsed] = '\0';
1042 if (buf->BufUsed + 10 > buf->BufSize) {
1043 IncreaseBuf(buf, 1, -1);
1045 pch = strchr(buf->buf, '\n');
1053 len = pch - buf->buf;
1054 if (len > 0 && (*(pch - 1) == '\r') )
1056 StrBufSub(Line, buf, 0, len - rlen);
1057 StrBufCutLeft(buf, len + 1);
1065 * \brief Input binary data from socket
1066 * flushes and closes the FD on error
1067 * \param buf the buffer to get the input to
1068 * \param fd pointer to the filedescriptor to read
1069 * \param append Append to an existing string or replace?
1070 * \param nBytes the maximal number of bytes to read
1071 * \param Error strerror() on error
1072 * \returns numbers of chars read
1074 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
1078 int len, rlen, slen;
1082 if ((Buf == NULL) || (*fd == -1))
1086 if (Buf->BufUsed + nBytes > Buf->BufSize)
1087 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
1089 ptr = Buf->buf + Buf->BufUsed;
1091 slen = len = Buf->BufUsed;
1093 fdflags = fcntl(*fd, F_GETFL);
1095 while (nRead < nBytes) {
1096 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
1099 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
1100 *Error = strerror(errno);
1105 if ((rlen = read(*fd,
1107 nBytes - nRead)) == -1) {
1110 *Error = strerror(errno);
1115 Buf->BufUsed += rlen;
1117 Buf->buf[Buf->BufUsed] = '\0';
1122 * \brief Cut nChars from the start of the string
1123 * \param Buf Buffer to modify
1124 * \param nChars how many chars should be skipped?
1126 void StrBufCutLeft(StrBuf *Buf, int nChars)
1128 if (nChars >= Buf->BufUsed) {
1132 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
1133 Buf->BufUsed -= nChars;
1134 Buf->buf[Buf->BufUsed] = '\0';
1138 * \brief Cut the trailing n Chars from the string
1139 * \param Buf Buffer to modify
1140 * \param nChars how many chars should be trunkated?
1142 void StrBufCutRight(StrBuf *Buf, int nChars)
1144 if (nChars >= Buf->BufUsed) {
1148 Buf->BufUsed -= nChars;
1149 Buf->buf[Buf->BufUsed] = '\0';
1153 * \brief Cut the string after n Chars
1154 * \param Buf Buffer to modify
1155 * \param AfternChars after how many chars should we trunkate the string?
1156 * \param At if non-null and points inside of our string, cut it there.
1158 void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
1161 AfternChars = At - Buf->buf;
1164 if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
1166 Buf->BufUsed = AfternChars;
1167 Buf->buf[Buf->BufUsed] = '\0';
1172 * Strip leading and trailing spaces from a string; with premeasured and adjusted length.
1173 * buf - the string to modify
1174 * len - length of the string.
1176 void StrBufTrim(StrBuf *Buf)
1179 if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
1181 while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
1184 if (delta > 0) StrBufCutLeft(Buf, delta);
1186 if (Buf->BufUsed == 0) return;
1187 while (isspace(Buf->buf[Buf->BufUsed - 1])){
1190 Buf->buf[Buf->BufUsed] = '\0';
1194 void StrBufUpCase(StrBuf *Buf)
1199 pche = pch + Buf->BufUsed;
1200 while (pch < pche) {
1201 *pch = toupper(*pch);
1207 void StrBufLowerCase(StrBuf *Buf)
1212 pche = pch + Buf->BufUsed;
1213 while (pch < pche) {
1214 *pch = tolower(*pch);
1221 * \brief unhide special chars hidden to the HTML escaper
1222 * \param target buffer to put the unescaped string in
1223 * \param source buffer to unescape
1225 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
1231 FlushStrBuf(target);
1233 if (source == NULL ||target == NULL)
1238 len = source->BufUsed;
1239 for (a = 0; a < len; ++a) {
1240 if (target->BufUsed >= target->BufSize)
1241 IncreaseBuf(target, 1, -1);
1243 if (source->buf[a] == '=') {
1244 hex[0] = source->buf[a + 1];
1245 hex[1] = source->buf[a + 2];
1248 sscanf(hex, "%02x", &b);
1249 target->buf[target->BufUsed] = b;
1250 target->buf[++target->BufUsed] = 0;
1254 target->buf[target->BufUsed] = source->buf[a];
1255 target->buf[++target->BufUsed] = 0;
1262 * \brief hide special chars from the HTML escapers and friends
1263 * \param target buffer to put the escaped string in
1264 * \param source buffer to escape
1266 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
1271 FlushStrBuf(target);
1273 if (source == NULL ||target == NULL)
1278 len = source->BufUsed;
1279 for (i=0; i<len; ++i) {
1280 if (target->BufUsed + 4 >= target->BufSize)
1281 IncreaseBuf(target, 1, -1);
1282 if ( (isalnum(source->buf[i])) ||
1283 (source->buf[i]=='-') ||
1284 (source->buf[i]=='_') ) {
1285 target->buf[target->BufUsed++] = source->buf[i];
1288 sprintf(&target->buf[target->BufUsed],
1290 (0xFF &source->buf[i]));
1291 target->BufUsed += 3;
1294 target->buf[target->BufUsed + 1] = '\0';
1298 * \brief uses the same calling syntax as compress2(), but it
1299 * creates a stream compatible with HTTP "Content-encoding: gzip"
1302 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
1303 #define OS_CODE 0x03 /*< unix */
1304 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
1305 size_t * destLen, /*< length of the compresed data */
1306 const Bytef * source, /*< source to encode */
1307 uLong sourceLen, /*< length of source to encode */
1308 int level) /*< compression level */
1310 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
1312 /* write gzip header */
1313 snprintf((char *) dest, *destLen,
1314 "%c%c%c%c%c%c%c%c%c%c",
1315 gz_magic[0], gz_magic[1], Z_DEFLATED,
1316 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
1319 /* normal deflate */
1322 stream.next_in = (Bytef *) source;
1323 stream.avail_in = (uInt) sourceLen;
1324 stream.next_out = dest + 10L; // after header
1325 stream.avail_out = (uInt) * destLen;
1326 if ((uLong) stream.avail_out != *destLen)
1329 stream.zalloc = (alloc_func) 0;
1330 stream.zfree = (free_func) 0;
1331 stream.opaque = (voidpf) 0;
1333 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
1334 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
1338 err = deflate(&stream, Z_FINISH);
1339 if (err != Z_STREAM_END) {
1340 deflateEnd(&stream);
1341 return err == Z_OK ? Z_BUF_ERROR : err;
1343 *destLen = stream.total_out + 10L;
1345 /* write CRC and Length */
1346 uLong crc = crc32(0L, source, sourceLen);
1348 for (n = 0; n < 4; ++n, ++*destLen) {
1349 dest[*destLen] = (int) (crc & 0xff);
1352 uLong len = stream.total_in;
1353 for (n = 0; n < 4; ++n, ++*destLen) {
1354 dest[*destLen] = (int) (len & 0xff);
1357 err = deflateEnd(&stream);
1364 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
1366 int CompressBuffer(StrBuf *Buf)
1369 char *compressed_data = NULL;
1370 size_t compressed_len, bufsize;
1372 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
1373 compressed_data = malloc(compressed_len);
1375 if (compress_gzip((Bytef *) compressed_data,
1378 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
1381 Buf->buf = compressed_data;
1382 Buf->BufUsed = compressed_len;
1383 Buf->BufSize = bufsize;
1386 free(compressed_data);
1388 #endif /* HAVE_ZLIB */
1393 * \brief decode a buffer from base 64 encoding; destroys original
1394 * \param Buf Buffor to transform
1396 int StrBufDecodeBase64(StrBuf *Buf)
1400 if (Buf == NULL) return -1;
1402 xferbuf = (char*) malloc(Buf->BufSize);
1403 siz = CtdlDecodeBase64(xferbuf,
1414 * \brief remove escaped strings from i.e. the url string (like %20 for blanks)
1415 * \param Buf Buffer to translate
1416 * \param StripBlanks Reduce several blanks to one?
1418 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
1424 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
1425 Buf->buf[Buf->BufUsed - 1] = '\0';
1430 while (a < Buf->BufUsed) {
1431 if (Buf->buf[a] == '+')
1433 else if (Buf->buf[a] == '%') {
1434 /* don't let % chars through, rather truncate the input. */
1435 if (a + 2 > Buf->BufUsed) {
1440 hex[0] = Buf->buf[a + 1];
1441 hex[1] = Buf->buf[a + 2];
1444 sscanf(hex, "%02x", &b);
1445 Buf->buf[a] = (char) b;
1446 len = Buf->BufUsed - a - 2;
1448 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
1460 * \brief RFC2047-encode a header field if necessary.
1461 * If no non-ASCII characters are found, the string
1462 * will be copied verbatim without encoding.
1464 * \param target Target buffer.
1465 * \param source Source string to be encoded.
1466 * \returns encoded length; -1 if non success.
1468 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
1470 const char headerStr[] = "=?UTF-8?Q?";
1471 int need_to_encode = 0;
1475 if ((source == NULL) ||
1479 while ((i < source->BufUsed) &&
1480 (!IsEmptyStr (&source->buf[i])) &&
1481 (need_to_encode == 0)) {
1482 if (((unsigned char) source->buf[i] < 32) ||
1483 ((unsigned char) source->buf[i] > 126)) {
1489 if (!need_to_encode) {
1490 if (*target == NULL) {
1491 *target = NewStrBufPlain(source->buf, source->BufUsed);
1494 FlushStrBuf(*target);
1495 StrBufAppendBuf(*target, source, 0);
1497 return (*target)->BufUsed;
1499 if (*target == NULL)
1500 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
1501 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
1502 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1503 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1504 (*target)->BufUsed = sizeof(headerStr) - 1;
1505 for (i=0; (i < source->BufUsed); ++i) {
1506 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1507 IncreaseBuf(*target, 1, 0);
1508 ch = (unsigned char) source->buf[i];
1509 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1510 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1511 (*target)->BufUsed += 3;
1514 (*target)->buf[(*target)->BufUsed] = ch;
1515 (*target)->BufUsed++;
1519 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1520 IncreaseBuf(*target, 1, 0);
1522 (*target)->buf[(*target)->BufUsed++] = '?';
1523 (*target)->buf[(*target)->BufUsed++] = '=';
1524 (*target)->buf[(*target)->BufUsed] = '\0';
1525 return (*target)->BufUsed;;
1529 * \brief replaces all occurances of 'search' by 'replace'
1530 * \param buf Buffer to modify
1531 * \param search character to search
1532 * \param relpace character to replace search by
1534 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1539 for (i=0; i<buf->BufUsed; i++)
1540 if (buf->buf[i] == search)
1541 buf->buf[i] = replace;
1548 * Wrapper around iconv_open()
1549 * Our version adds aliases for non-standard Microsoft charsets
1550 * such as 'MS950', aliasing them to names like 'CP950'
1552 * tocode Target encoding
1553 * fromcode Source encoding
1555 void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
1558 iconv_t ic = (iconv_t)(-1) ;
1559 ic = iconv_open(tocode, fromcode);
1560 if (ic == (iconv_t)(-1) ) {
1561 char alias_fromcode[64];
1562 if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
1563 safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
1564 alias_fromcode[0] = 'C';
1565 alias_fromcode[1] = 'P';
1566 ic = iconv_open(tocode, alias_fromcode);
1569 *(iconv_t *)pic = ic;
1575 static inline char *FindNextEnd (const StrBuf *Buf, char *bptr)
1578 /* Find the next ?Q? */
1579 if (Buf->BufUsed - (bptr - Buf->buf) < 6)
1582 end = strchr(bptr + 2, '?');
1587 if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
1588 ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) &&
1589 (*(end + 2) == '?')) {
1590 /* skip on to the end of the cluster, the next ?= */
1591 end = strstr(end + 3, "?=");
1594 /* sort of half valid encoding, try to find an end. */
1595 end = strstr(bptr, "?=");
1600 void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
1605 char *ibuf; /**< Buffer of characters to be converted */
1606 char *obuf; /**< Buffer for converted characters */
1607 size_t ibuflen; /**< Length of input buffer */
1608 size_t obuflen; /**< Length of output buffer */
1611 if (ConvertBuf->BufUsed > TmpBuf->BufSize)
1612 IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed);
1614 ic = *(iconv_t*)pic;
1615 ibuf = ConvertBuf->buf;
1616 ibuflen = ConvertBuf->BufUsed;
1618 obuflen = TmpBuf->BufSize;
1620 iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
1622 /* little card game: wheres the red lady? */
1623 ibuf = ConvertBuf->buf;
1624 BufSize = ConvertBuf->BufSize;
1626 ConvertBuf->buf = TmpBuf->buf;
1627 ConvertBuf->BufSize = TmpBuf->BufSize;
1628 ConvertBuf->BufUsed = TmpBuf->BufSize - obuflen;
1629 ConvertBuf->buf[ConvertBuf->BufUsed] = '\0';
1632 TmpBuf->BufSize = BufSize;
1633 TmpBuf->BufUsed = 0;
1634 TmpBuf->buf[0] = '\0';
1641 inline static void DecodeSegment(StrBuf *Target,
1642 const StrBuf *DecodeMe,
1646 StrBuf *ConvertBuf2,
1647 StrBuf *FoundCharset)
1652 iconv_t ic = (iconv_t)(-1);
1654 /* Now we handle foreign character sets properly encoded
1655 * in RFC2047 format.
1657 StaticBuf.buf = SegmentStart;
1658 StaticBuf.BufUsed = SegmentEnd - SegmentStart;
1659 StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
1660 extract_token(charset, SegmentStart, 1, '?', sizeof charset);
1661 if (FoundCharset != NULL) {
1662 FlushStrBuf(FoundCharset);
1663 StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
1665 extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
1666 StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
1668 *encoding = toupper(*encoding);
1669 if (*encoding == 'B') { /**< base64 */
1670 ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
1672 ConvertBuf->BufUsed);
1674 else if (*encoding == 'Q') { /**< quoted-printable */
1678 while (pos < ConvertBuf->BufUsed)
1680 if (ConvertBuf->buf[pos] == '_')
1681 ConvertBuf->buf[pos] = ' ';
1685 ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
1688 ConvertBuf->BufUsed);
1691 StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
1694 ctdl_iconv_open("UTF-8", charset, &ic);
1695 if (ic != (iconv_t)(-1) ) {
1696 StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
1697 StrBufAppendBuf(Target, ConvertBuf2, 0);
1701 StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
1705 * Handle subjects with RFC2047 encoding such as:
1706 * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
1708 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
1710 StrBuf *ConvertBuf, *ConvertBuf2;
1711 char *start, *end, *next, *nextend, *ptr = NULL;
1712 iconv_t ic = (iconv_t)(-1) ;
1716 int illegal_non_rfc2047_encoding = 0;
1718 /* Sometimes, badly formed messages contain strings which were simply
1719 * written out directly in some foreign character set instead of
1720 * using RFC2047 encoding. This is illegal but we will attempt to
1721 * handle it anyway by converting from a user-specified default
1722 * charset to UTF-8 if we see any nonprintable characters.
1725 len = StrLength(DecodeMe);
1726 for (i=0; i<DecodeMe->BufUsed; ++i) {
1727 if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
1728 illegal_non_rfc2047_encoding = 1;
1733 ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
1734 if ((illegal_non_rfc2047_encoding) &&
1735 (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
1736 (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
1738 ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
1739 if (ic != (iconv_t)(-1) ) {
1740 StrBufConvert((StrBuf*)DecodeMe, ConvertBuf, &ic);///TODO: don't void const?
1745 /* pre evaluate the first pair */
1746 nextend = end = NULL;
1747 len = StrLength(DecodeMe);
1748 start = strstr(DecodeMe->buf, "=?");
1749 eptr = DecodeMe->buf + DecodeMe->BufUsed;
1751 end = FindNextEnd (DecodeMe, start);
1753 StrBufAppendBuf(Target, DecodeMe, 0);
1754 FreeStrBuf(&ConvertBuf);
1758 ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
1760 if (start != DecodeMe->buf)
1761 StrBufAppendBufPlain(Target, DecodeMe->buf, start - DecodeMe->buf, 0);
1763 * Since spammers will go to all sorts of absurd lengths to get their
1764 * messages through, there are LOTS of corrupt headers out there.
1765 * So, prevent a really badly formed RFC2047 header from throwing
1766 * this function into an infinite loop.
1768 while ((start != NULL) &&
1775 DecodeSegment(Target,
1783 next = strstr(end, "=?");
1785 if ((next != NULL) &&
1787 nextend = FindNextEnd(DecodeMe, next);
1788 if (nextend == NULL)
1791 /* did we find two partitions */
1792 if ((next != NULL) &&
1796 while ((ptr < next) &&
1802 /* did we find a gab just filled with blanks? */
1807 len - (next - start));
1809 /* now terminate the gab at the end */
1810 delta = (next - end) - 2; ////TODO: const!
1811 ((StrBuf*)DecodeMe)->BufUsed -= delta;
1812 ((StrBuf*)DecodeMe)->buf[DecodeMe->BufUsed] = '\0';
1814 /* move next to its new location. */
1819 /* our next-pair is our new first pair now. */
1825 nextend = DecodeMe->buf + DecodeMe->BufUsed;
1826 if ((end != NULL) && (end < nextend)) {
1828 while ( (ptr < nextend) &&
1835 StrBufAppendBufPlain(Target, end, nextend - end, 0);
1837 FreeStrBuf(&ConvertBuf);
1838 FreeStrBuf(&ConvertBuf2);
1843 long StrBuf_Utf8StrLen(StrBuf *Buf)
1845 return Ctdl_Utf8StrLen(Buf->buf);
1848 long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
1852 CutAt = Ctdl_Utf8StrCut(Buf->buf, maxlen);
1853 if (CutAt != NULL) {
1854 Buf->BufUsed = CutAt - Buf->buf;
1855 Buf->buf[Buf->BufUsed] = '\0';
1857 return Buf->BufUsed;
1862 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
1864 const char *aptr, *ptr, *eptr;
1871 ptr = aptr = Buf->buf;
1875 optr = LineBuf->buf;
1876 eptr = Buf->buf + Buf->BufUsed;
1877 xptr = LineBuf->buf + LineBuf->BufSize;
1879 while ((*ptr != '\n') &&
1886 LineBuf->BufUsed = optr - LineBuf->buf;
1887 IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
1888 optr = LineBuf->buf + LineBuf->BufUsed;
1889 xptr = LineBuf->buf + LineBuf->BufSize;
1892 LineBuf->BufUsed = optr - LineBuf->buf;
1901 return Buf->BufUsed - (ptr - Buf->buf);