7 #include <sys/select.h>
9 #define SHOW_ME_VAPPEND_PRINTF
11 #include "libcitadel.h"
22 inline const char *ChrPtr(const StrBuf *Str)
29 inline int StrLength(const StrBuf *Str)
31 return (Str != NULL) ? Str->BufUsed : 0;
34 StrBuf* NewStrBuf(void)
38 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
39 NewBuf->buf = (char*) malloc(SIZ);
40 NewBuf->buf[0] = '\0';
41 NewBuf->BufSize = SIZ;
47 StrBuf* NewStrBufDup(const StrBuf *CopyMe)
54 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
55 NewBuf->buf = (char*) malloc(CopyMe->BufSize);
56 memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
57 NewBuf->BufUsed = CopyMe->BufUsed;
58 NewBuf->BufSize = CopyMe->BufSize;
63 StrBuf* NewStrBufPlain(const char* ptr, int nChars)
69 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
71 CopySize = strlen((ptr != NULL)?ptr:"");
75 while (Siz <= CopySize)
78 NewBuf->buf = (char*) malloc(Siz);
79 NewBuf->BufSize = Siz;
81 memcpy(NewBuf->buf, ptr, CopySize);
82 NewBuf->buf[CopySize] = '\0';
83 NewBuf->BufUsed = CopySize;
86 NewBuf->buf[0] = '\0';
94 StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
98 NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
99 NewBuf->buf = (char*) StringConstant;
100 NewBuf->BufSize = SizeOfStrConstant;
101 NewBuf->BufUsed = SizeOfStrConstant;
102 NewBuf->ConstBuf = 1;
107 static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
110 size_t NewSize = Buf->BufSize * 2;
116 while (NewSize < DestSize)
119 NewBuf= (char*) malloc(NewSize);
122 memcpy(NewBuf, Buf->buf, Buf->BufUsed);
135 int FlushStrBuf(StrBuf *buf)
144 void FreeStrBuf (StrBuf **FreeMe)
148 if (!(*FreeMe)->ConstBuf)
149 free((*FreeMe)->buf);
154 void HFreeStrBuf (void *VFreeMe)
156 StrBuf *FreeMe = (StrBuf*)VFreeMe;
159 if (!FreeMe->ConstBuf)
164 long StrTol(const StrBuf *Buf)
167 return atol(Buf->buf);
172 int StrToi(const StrBuf *Buf)
175 return atoi(Buf->buf);
180 long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
185 nThChar = ptr - Buf->buf;
186 if ((nThChar < 0) || (nThChar > Buf->BufUsed))
188 Buf->buf[nThChar] = PeekValue;
193 int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
195 size_t Siz = Buf->BufSize;
199 CopySize = strlen(ptr);
203 while (Siz <= CopySize)
206 if (Siz != Buf->BufSize)
207 IncreaseBuf(Buf, 0, Siz);
208 memcpy(Buf->buf, ptr, CopySize);
209 Buf->buf[CopySize] = '\0';
210 Buf->BufUsed = CopySize;
215 void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, size_t Offset)
217 if ((AppendBuf == NULL) || (Buf == NULL))
220 if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed)
223 AppendBuf->BufUsed + Buf->BufUsed);
225 memcpy(Buf->buf + Buf->BufUsed,
226 AppendBuf->buf + Offset,
227 AppendBuf->BufUsed - Offset);
228 Buf->BufUsed += AppendBuf->BufUsed - Offset;
229 Buf->buf[Buf->BufUsed] = '\0';
233 void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, size_t Offset)
237 if ((AppendBuf == NULL) || (Buf == NULL))
241 aps = strlen(AppendBuf + Offset);
243 aps = AppendSize - Offset;
245 if (Buf->BufSize < Buf->BufUsed + aps)
246 IncreaseBuf(Buf, (Buf->BufUsed > 0), Buf->BufUsed + aps);
248 memcpy(Buf->buf + Buf->BufUsed,
252 Buf->buf[Buf->BufUsed] = '\0';
257 * \brief Escape a string for feeding out as a URL.
258 * \param outbuf the output buffer
259 * \param oblen the size of outbuf to sanitize
260 * \param strbuf the input buffer
262 void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
264 const char *pch, *pche;
267 const char ec[] = " +#&;`'|*?-~<>^()[]{}/$\"\\";
268 int eclen = sizeof(ec) -1;
270 if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
272 if (PlainIn != NULL) {
273 len = strlen(PlainIn);
279 pche = pch + In->BufUsed;
283 pt = OutBuf->buf + OutBuf->BufUsed;
284 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
288 IncreaseBuf(OutBuf, 1, -1);
289 pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
293 for (b = 0; b < eclen; ++b) {
300 snprintf(pt, pt - pte, "%%%02x", *pch);
302 OutBuf->BufUsed += 3;
313 * Copy a string, escaping characters which have meaning in HTML.
315 * target target buffer
316 * strbuf source buffer
317 * nbsp If nonzero, spaces are converted to non-breaking spaces.
318 * nolinebreaks if set, linebreaks are removed from the string.
320 long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
322 const char *aptr, *eiptr;
326 if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
329 if (PlainIn != NULL) {
331 len = strlen(PlainIn);
336 eiptr = aptr + Source->BufUsed;
337 len = Source->BufUsed;
340 bptr = Target->buf + Target->BufUsed;
341 eptr = Target->buf + Target->BufSize - 6; /* our biggest unit to put in... */
343 while (aptr < eiptr){
345 IncreaseBuf(Target, 1, -1);
346 eptr = Target->buf + Target->BufSize - 6;
349 memcpy(bptr, "<", 4);
351 Target->BufUsed += 4;
353 else if (*aptr == '>') {
354 memcpy(bptr, ">", 4);
356 Target->BufUsed += 4;
358 else if (*aptr == '&') {
359 memcpy(bptr, "&", 5);
361 Target->BufUsed += 5;
363 else if (*aptr == '\"') {
364 memcpy(bptr, """, 6);
366 Target->BufUsed += 6;
368 else if (*aptr == '\'') {
369 memcpy(bptr, "'", 5);
371 Target->BufUsed += 5;
373 else if (*aptr == LB) {
378 else if (*aptr == RB) {
383 else if (*aptr == QU) {
388 else if ((*aptr == 32) && (nbsp == 1)) {
389 memcpy(bptr, " ", 6);
391 Target->BufUsed += 6;
393 else if ((*aptr == '\n') && (nolinebreaks)) {
394 *bptr='\0'; /* nothing */
396 else if ((*aptr == '\r') && (nolinebreaks)) {
397 *bptr='\0'; /* nothing */
407 if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
409 return Target->BufUsed;
412 inline int StrBufNum_tokens(const StrBuf *source, char tok)
414 return num_tokens(source->buf, tok);
418 int StrBufSub(StrBuf *dest, const StrBuf *Source, size_t Offset, size_t nChars)
421 if (Offset > Source->BufUsed)
426 if (Offset + nChars < Source->BufUsed)
428 if (nChars > dest->BufSize)
429 IncreaseBuf(dest, 0, nChars + 1);
430 memcpy(dest->buf, Source->buf + Offset, nChars);
431 dest->BufUsed = nChars;
432 dest->buf[dest->BufUsed] = '\0';
435 NCharsRemain = Source->BufUsed - Offset;
436 if (NCharsRemain > dest->BufSize)
437 IncreaseBuf(dest, 0, NCharsRemain + 1);
438 memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
439 dest->BufUsed = NCharsRemain;
440 dest->buf[dest->BufUsed] = '\0';
445 void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
447 size_t nWritten = Buf->BufSize + 1;
448 size_t Offset = Buf->BufUsed;
449 size_t newused = Offset + nWritten;
451 while (newused >= Buf->BufSize) {
452 nWritten = vsnprintf(Buf->buf + Offset,
453 Buf->BufSize - Offset,
455 newused = Offset + nWritten;
456 if (newused >= Buf->BufSize)
457 IncreaseBuf(Buf, 1, 0);
459 Buf->BufUsed = Offset + nWritten ;
464 void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
466 size_t nWritten = Buf->BufSize + 1;
467 size_t Offset = Buf->BufUsed;
468 size_t newused = Offset + nWritten;
471 while (newused >= Buf->BufSize) {
472 va_start(arg_ptr, format);
473 nWritten = vsnprintf(Buf->buf + Offset,
474 Buf->BufSize - Offset,
477 newused = Offset + nWritten;
478 if (newused >= Buf->BufSize)
479 IncreaseBuf(Buf, 1, 0);
481 Buf->BufUsed = Offset + nWritten ;
486 void StrBufPrintf(StrBuf *Buf, const char *format, ...)
488 size_t nWritten = Buf->BufSize + 1;
491 while (nWritten >= Buf->BufSize) {
492 va_start(arg_ptr, format);
493 nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
495 Buf->BufUsed = nWritten ;
496 if (nWritten >= Buf->BufSize)
497 IncreaseBuf(Buf, 0, 0);
503 * \brief a string tokenizer
504 * \param dest Destination StringBuffer
505 * \param Source StringBuffer to read into
506 * \param separator tokenizer param
507 * \returns -1 if not found, else length of token.
509 int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
511 const char *s, *e; //* source * /
512 int len = 0; //* running total length of extracted string * /
513 int current_token = 0; //* token currently being processed * /
515 if ((Source == NULL) || (Source->BufUsed ==0)) {
519 e = s + Source->BufUsed;
525 //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
529 while ((s<e) && !IsEmptyStr(s)) {
530 if (*s == separator) {
533 if (len >= dest->BufSize)
534 if (!IncreaseBuf(dest, 1, -1))
536 if ( (current_token == parmnum) &&
541 else if (current_token > parmnum) {
547 dest->buf[len] = '\0';
550 if (current_token < parmnum) {
551 //lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
554 //lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
560 * extract_int() - extract an int parm w/o supplying a buffer
562 int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
571 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
578 * extract_long() - extract an long parm w/o supplying a buffer
580 long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
589 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
597 * extract_unsigned_long() - extract an unsigned long parm
599 unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
608 if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
617 * \brief Input binary data from socket
618 * \param buf the buffer to get the input to
619 * \param bytes the maximal number of bytes to read
621 int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
628 slen = len = buf->BufUsed;
630 rlen = read(*fd, &buf->buf[len], 1);
632 *Error = strerror(errno);
639 if (buf->buf[len] == '\n')
641 if (buf->buf[len] != '\r')
643 if (!(len < buf->BufSize)) {
645 buf->buf[len+1] = '\0';
646 IncreaseBuf(buf, 1, -1);
650 buf->buf[len] = '\0';
655 * \brief Input binary data from socket
656 * \param buf the buffer to get the input to
657 * \param bytes the maximal number of bytes to read
659 int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
667 if ((Buf == NULL) || (*fd == -1))
671 if (Buf->BufUsed + nBytes > Buf->BufSize)
672 IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
674 ptr = Buf->buf + Buf->BufUsed;
676 slen = len = Buf->BufUsed;
678 fdflags = fcntl(*fd, F_GETFL);
680 while (nRead < nBytes) {
681 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
684 if (select(*fd + 1, NULL, &wset, NULL, NULL) == -1) {
685 *Error = strerror(errno);
690 if ((rlen = read(*fd,
692 nBytes - nRead)) == -1) {
695 *Error = strerror(errno);
699 Buf->BufUsed += rlen;
701 Buf->buf[Buf->BufUsed] = '\0';
705 void StrBufCutLeft(StrBuf *Buf, int nChars)
707 if (nChars >= Buf->BufUsed) {
711 memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
712 Buf->BufUsed -= nChars;
713 Buf->buf[Buf->BufUsed] = '\0';
716 void StrBufCutRight(StrBuf *Buf, int nChars)
718 if (nChars >= Buf->BufUsed) {
722 Buf->BufUsed -= nChars;
723 Buf->buf[Buf->BufUsed] = '\0';
728 * string conversion function
730 void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
738 if (source == NULL ||target == NULL)
743 len = source->BufUsed;
744 for (a = 0; a < len; ++a) {
745 if (target->BufUsed >= target->BufSize)
746 IncreaseBuf(target, 1, -1);
748 if (source->buf[a] == '=') {
749 hex[0] = source->buf[a + 1];
750 hex[1] = source->buf[a + 2];
753 sscanf(hex, "%02x", &b);
754 target->buf[target->BufUsed] = b;
755 target->buf[++target->BufUsed] = 0;
759 target->buf[target->BufUsed] = source->buf[a];
760 target->buf[++target->BufUsed] = 0;
767 * string conversion function
769 void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
776 if (source == NULL ||target == NULL)
781 len = source->BufUsed;
782 for (i=0; i<len; ++i) {
783 if (target->BufUsed + 4 >= target->BufSize)
784 IncreaseBuf(target, 1, -1);
785 if ( (isalnum(source->buf[i])) ||
786 (source->buf[i]=='-') ||
787 (source->buf[i]=='_') ) {
788 target->buf[target->BufUsed++] = source->buf[i];
791 sprintf(&target->buf[target->BufUsed],
793 (0xFF &source->buf[i]));
794 target->BufUsed += 3;
797 target->buf[target->BufUsed + 1] = '\0';
801 * \brief uses the same calling syntax as compress2(), but it
802 * creates a stream compatible with HTTP "Content-encoding: gzip"
805 #define DEF_MEM_LEVEL 8 /*< memlevel??? */
806 #define OS_CODE 0x03 /*< unix */
807 int ZEXPORT compress_gzip(Bytef * dest, /*< compressed buffer*/
808 size_t * destLen, /*< length of the compresed data */
809 const Bytef * source, /*< source to encode */
810 uLong sourceLen, /*< length of source to encode */
811 int level) /*< compression level */
813 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
815 /* write gzip header */
816 snprintf((char *) dest, *destLen,
817 "%c%c%c%c%c%c%c%c%c%c",
818 gz_magic[0], gz_magic[1], Z_DEFLATED,
819 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
825 stream.next_in = (Bytef *) source;
826 stream.avail_in = (uInt) sourceLen;
827 stream.next_out = dest + 10L; // after header
828 stream.avail_out = (uInt) * destLen;
829 if ((uLong) stream.avail_out != *destLen)
832 stream.zalloc = (alloc_func) 0;
833 stream.zfree = (free_func) 0;
834 stream.opaque = (voidpf) 0;
836 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
837 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
841 err = deflate(&stream, Z_FINISH);
842 if (err != Z_STREAM_END) {
844 return err == Z_OK ? Z_BUF_ERROR : err;
846 *destLen = stream.total_out + 10L;
848 /* write CRC and Length */
849 uLong crc = crc32(0L, source, sourceLen);
851 for (n = 0; n < 4; ++n, ++*destLen) {
852 dest[*destLen] = (int) (crc & 0xff);
855 uLong len = stream.total_in;
856 for (n = 0; n < 4; ++n, ++*destLen) {
857 dest[*destLen] = (int) (len & 0xff);
860 err = deflateEnd(&stream);
867 * Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
869 int CompressBuffer(StrBuf *Buf)
872 char *compressed_data = NULL;
873 size_t compressed_len, bufsize;
875 bufsize = compressed_len = ((Buf->BufUsed * 101) / 100) + 100;
876 compressed_data = malloc(compressed_len);
878 if (compress_gzip((Bytef *) compressed_data,
881 (uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
884 Buf->buf = compressed_data;
885 Buf->BufUsed = compressed_len;
886 Buf->BufSize = bufsize;
889 free(compressed_data);
891 #endif /* HAVE_ZLIB */
895 int StrBufDecodeBase64(StrBuf *Buf)
899 if (Buf == NULL) return -1;
901 xferbuf = (char*) malloc(Buf->BufSize);
902 siz = CtdlDecodeBase64(xferbuf,
913 * remove escaped strings from i.e. the url string (like %20 for blanks)
915 long StrBufUnescape(StrBuf *Buf, int StripBlanks)
921 while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
922 Buf->buf[Buf->BufUsed - 1] = '\0';
927 while (a < Buf->BufUsed) {
928 if (Buf->buf[a] == '+')
930 else if (Buf->buf[a] == '%') {
931 /* don't let % chars through, rather truncate the input. */
932 if (a + 2 > Buf->BufUsed) {
937 hex[0] = Buf->buf[a + 1];
938 hex[1] = Buf->buf[a + 2];
941 sscanf(hex, "%02x", &b);
942 Buf->buf[a] = (char) b;
943 len = Buf->BufUsed - a - 2;
945 memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
957 * \brief RFC2047-encode a header field if necessary.
958 * If no non-ASCII characters are found, the string
959 * will be copied verbatim without encoding.
961 * \param target Target buffer.
962 * \param source Source string to be encoded.
963 * \returns encoded length; -1 if non success.
965 int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
967 const char headerStr[] = "=?UTF-8?Q?";
968 int need_to_encode = 0;
972 if ((source == NULL) ||
976 while ((i < source->BufUsed) &&
977 (!IsEmptyStr (&source->buf[i])) &&
978 (need_to_encode == 0)) {
979 if (((unsigned char) source->buf[i] < 32) ||
980 ((unsigned char) source->buf[i] > 126)) {
986 if (!need_to_encode) {
987 if (*target == NULL) {
988 *target = NewStrBufPlain(source->buf, source->BufUsed);
991 FlushStrBuf(*target);
992 StrBufAppendBuf(*target, source, 0);
994 return (*target)->BufUsed;
997 *target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
998 else if (sizeof(headerStr) + source->BufUsed > (*target)->BufSize)
999 IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
1000 memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
1001 (*target)->BufUsed = sizeof(headerStr) - 1;
1002 for (i=0; (i < source->BufUsed); ++i) {
1003 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1004 IncreaseBuf(*target, 1, 0);
1005 ch = (unsigned char) source->buf[i];
1006 if ((ch < 32) || (ch > 126) || (ch == 61)) {
1007 sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
1008 (*target)->BufUsed += 3;
1011 (*target)->buf[(*target)->BufUsed] = ch;
1012 (*target)->BufUsed++;
1016 if ((*target)->BufUsed + 4 > (*target)->BufSize)
1017 IncreaseBuf(*target, 1, 0);
1019 (*target)->buf[(*target)->BufUsed++] = '?';
1020 (*target)->buf[(*target)->BufUsed++] = '=';
1021 (*target)->buf[(*target)->BufUsed] = '\0';
1022 return (*target)->BufUsed;;
1025 void StrBufReplaceChars(StrBuf *buf, char search, char replace)
1030 for (i=0; i<buf->BufUsed; i++)
1031 if (buf->buf[i] == search)
1032 buf->buf[i] = replace;