Add ability to hex encode binary strings
[citadel.git] / libcitadel / lib / stringbuf.c
index 98acba78284590723c04fbe738fb1be0e51a984a..9318ba66ca3a77fbd2fe91e0d80eb0eccb65977f 100644 (file)
@@ -276,9 +276,12 @@ static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
                return -1;
                
        if (DestSize > 0)
-               while (NewSize <= DestSize)
+               while ((NewSize <= DestSize) && (NewSize != 0))
                        NewSize *= 2;
 
+       if (NewSize == 0)
+               return -1;
+
        NewBuf= (char*) malloc(NewSize);
        if (NewBuf == NULL)
                return -1;
@@ -479,9 +482,14 @@ StrBuf* NewStrBufPlain(const char* ptr, int nChars)
        else
                CopySize = nChars;
 
-       while (Siz <= CopySize)
+       while ((Siz <= CopySize) && (Siz != 0))
                Siz *= 2;
 
+       if (Siz == 0)
+       {
+               return NULL;
+       }
+
        NewBuf->buf = (char*) malloc(Siz);
        if (NewBuf->buf == NULL)
        {
@@ -532,9 +540,14 @@ int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
        else
                CopySize = nChars;
 
-       while (Siz <= CopySize)
+       while ((Siz <= CopySize) && (Siz != 0))
                Siz *= 2;
 
+       if (Siz == 0) {
+               FlushStrBuf(Buf);
+               return -1;
+       }
+
        if (Siz != Buf->BufSize)
                IncreaseBuf(Buf, 0, Siz);
        memcpy(Buf->buf, ptr, CopySize);
@@ -858,7 +871,8 @@ void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
                va_end(apl);
                newused = Offset + nWritten;
                if (newused >= Buf->BufSize) {
-                       IncreaseBuf(Buf, 1, newused);
+                       if (IncreaseBuf(Buf, 1, newused) == -1)
+                               return; /* TODO: error handling? */
                        newused = Buf->BufSize + 1;
                }
                else {
@@ -899,7 +913,8 @@ void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
                va_end(arg_ptr);
                newused = Buf->BufUsed + nWritten;
                if (newused >= Buf->BufSize) {
-                       IncreaseBuf(Buf, 1, newused);
+                       if (IncreaseBuf(Buf, 1, newused) == -1)
+                               return; /* TODO: error handling? */
                        newused = Buf->BufSize + 1;
                }
                else {
@@ -930,7 +945,8 @@ void StrBufPrintf(StrBuf *Buf, const char *format, ...)
                nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
                va_end(arg_ptr);
                if (nWritten >= Buf->BufSize) {
-                       IncreaseBuf(Buf, 0, 0);
+                       if (IncreaseBuf(Buf, 0, 0) == -1)
+                               return; /* TODO: error handling? */
                        nWritten = Buf->BufSize + 1;
                        continue;
                }
@@ -1333,7 +1349,7 @@ int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char se
        //cit_backtrace();
        //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
 
-       while ((s<e) && !IsEmptyStr(s)) {
+       while ((s < e) && !IsEmptyStr(s)) {
                if (*s == separator) {
                        ++current_token;
                }
@@ -1502,6 +1518,8 @@ int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pSt
            (Source->BufUsed == 0)      ) 
        {
                *pStart = StrBufNOTNULL;
+               if (dest != NULL)
+                       FlushStrBuf(dest);
                return -1;
        }
         
@@ -1618,7 +1636,7 @@ int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator
        //cit_backtrace();
        //lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
 
-       while ((s<EndBuffer) && !IsEmptyStr(s)) {
+       while ((s < EndBuffer) && !IsEmptyStr(s)) {
                if (*s == separator) {
                        ++current_token;
                }
@@ -1785,22 +1803,26 @@ void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
  * @param OutBuf the output buffer
  * @param In Buffer to encode
  * @param PlainIn way in from plain old c strings
+ * @param PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
  */
-void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
+void StrBufHexEscAppend(StrBuf *OutBuf, const StrBuf *In, const unsigned char *PlainIn, long PlainInLen)
 {
-       const char *pch, *pche;
+       const unsigned char *pch, *pche;
        char *pt, *pte;
        int len;
        
        if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
                return;
        if (PlainIn != NULL) {
-               len = strlen(PlainIn);
+               if (PlainInLen < 0)
+                       len = strlen((const char*)PlainIn);
+               else
+                       len = PlainInLen;
                pch = PlainIn;
                pche = pch + len;
        }
        else {
-               pch = In->buf;
+               pch = (const unsigned char*)In->buf;
                pche = pch + In->BufUsed;
                len = In->BufUsed;
        }
@@ -1818,14 +1840,26 @@ void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
                        pt = OutBuf->buf + OutBuf->BufUsed;
                }
 
-               *pt = HexList[(unsigned char)*pch][0];
+               *pt = HexList[*pch][0];
                pt ++;
-               *pt = HexList[(unsigned char)*pch][1];
+               *pt = HexList[*pch][1];
                pt ++; pch ++; OutBuf->BufUsed += 2;
        }
        *pt = '\0';
 }
 
+/** 
+ * @ingroup StrBuf_DeEnCoder
+ * @brief append a string in hex encoding to the buffer
+ * @param OutBuf the output buffer
+ * @param In Buffer to encode
+ * @param PlainIn way in from plain old c strings
+ */
+void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
+{
+       StrBufHexEscAppend(OutBuf, In, (const unsigned char*) PlainIn, -1);
+}
+
 /**
  * @ingroup StrBuf_DeEnCoder
  * @brief Append a string, escaping characters which have meaning in HTML.  
@@ -2828,7 +2862,8 @@ static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
                return NULL;
 
        if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
-           ((*(end + 1) == 'B') || (*(end + 1) == 'Q')) && 
+           (((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
+            ((*(end + 1) == 'b') || (*(end + 1) == 'q'))) && 
            (*(end + 2) == '?')) {
                /* skip on to the end of the cluster, the next ?= */
                end = strstr(end + 3, "?=");
@@ -2945,6 +2980,8 @@ inline static void DecodeSegment(StrBuf *Target,
        
        *encoding = toupper(*encoding);
        if (*encoding == 'B') { /**< base64 */
+               if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
+                       IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
                ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf, 
                                                        ConvertBuf->buf, 
                                                        ConvertBuf->BufUsed);
@@ -2960,6 +2997,9 @@ inline static void DecodeSegment(StrBuf *Target,
                        pos++;
                }
                
+               if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
+                       IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
+
                ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
                        ConvertBuf2->buf, 
                        ConvertBuf->buf,
@@ -2985,7 +3025,7 @@ inline static void DecodeSegment(StrBuf *Target,
 
 /**
  * @ingroup StrBuf_DeEnCoder
- * @brief Handle subjects with RFC2047 encoding such as:
+ * @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
  * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
  * @param Target where to put the decoded string to 
  * @param DecodeMe buffer with encoded string
@@ -2994,9 +3034,42 @@ inline static void DecodeSegment(StrBuf *Target,
  *        put it here for later use where no string might be known.
  */
 void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
+{
+       StrBuf *ConvertBuf;
+       StrBuf *ConvertBuf2;
+       ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
+       ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
+       
+       StrBuf_RFC822_2_Utf8(Target, 
+                            DecodeMe, 
+                            DefaultCharset, 
+                            FoundCharset, 
+                            ConvertBuf, 
+                            ConvertBuf2);
+       FreeStrBuf(&ConvertBuf);
+       FreeStrBuf(&ConvertBuf2);
+}
+
+/**
+ * @ingroup StrBuf_DeEnCoder
+ * @brief Handle subjects with RFC2047 encoding such as:
+ * =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
+ * @param Target where to put the decoded string to 
+ * @param DecodeMe buffer with encoded string
+ * @param DefaultCharset if we don't find one, which should we use?
+ * @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string, 
+ *        put it here for later use where no string might be known.
+ * @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
+ * @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
+ */
+void StrBuf_RFC822_2_Utf8(StrBuf *Target, 
+                         const StrBuf *DecodeMe, 
+                         const StrBuf* DefaultCharset, 
+                         StrBuf *FoundCharset, 
+                         StrBuf *ConvertBuf, 
+                         StrBuf *ConvertBuf2)
 {
        StrBuf *DecodedInvalidBuf = NULL;
-       StrBuf *ConvertBuf, *ConvertBuf2;
        const StrBuf *DecodeMee = DecodeMe;
        const char *start, *end, *next, *nextend, *ptr = NULL;
 #ifdef HAVE_ICONV
@@ -3022,7 +3095,6 @@ void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf*
                }
        }
 
-       ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
        if ((illegal_non_rfc2047_encoding) &&
            (strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) && 
            (strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
@@ -3044,15 +3116,13 @@ void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf*
        start = strstr(DecodeMee->buf, "=?");
        eptr = DecodeMee->buf + DecodeMee->BufUsed;
        if (start != NULL) 
-               end = FindNextEnd (DecodeMee, start);
+               end = FindNextEnd (DecodeMee, start + 2);
        else {
                StrBufAppendBuf(Target, DecodeMee, 0);
-               FreeStrBuf(&ConvertBuf);
                FreeStrBuf(&DecodedInvalidBuf);
                return;
        }
 
-       ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMee));
 
        if (start != DecodeMee->buf) {
                long nFront;
@@ -3131,8 +3201,6 @@ void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf*
                if (ptr < nextend)
                        StrBufAppendBufPlain(Target, end, nextend - end, 0);
        }
-       FreeStrBuf(&ConvertBuf);
-       FreeStrBuf(&ConvertBuf2);
        FreeStrBuf(&DecodedInvalidBuf);
 }
 
@@ -3359,7 +3427,216 @@ int CompressBuffer(StrBuf *Buf)
        return 0;
 }
 
+/*******************************************************************************
+ *           File I/O; Callbacks to libevent                                   *
+ *******************************************************************************/
+
+long StrBuf_read_one_chunk_callback (int fd, short event, IOBuffer *FB)
+{
+       long bufremain = 0;
+       int n;
+       
+       if ((FB == NULL) || (FB->Buf == NULL))
+               return -1;
+
+       /*
+        * check whether the read pointer is somewhere in a range 
+        * where a cut left is inexpensive
+        */
+
+       if (FB->ReadWritePointer != NULL)
+       {
+               long already_read;
+               
+               already_read = FB->ReadWritePointer - FB->Buf->buf;
+               bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
+
+               if (already_read != 0) {
+                       long unread;
+                       
+                       unread = FB->Buf->BufUsed - already_read;
+
+                       /* else nothing to compact... */
+                       if (unread == 0) {
+                               FB->ReadWritePointer = FB->Buf->buf;
+                               bufremain = FB->Buf->BufSize;                   
+                       }
+                       else if ((unread < 64) || 
+                                (bufremain < already_read))
+                       {
+                               /* 
+                                * if its just a tiny bit remaining, or we run out of space... 
+                                * lets tidy up.
+                                */
+                               FB->Buf->BufUsed = unread;
+                               if (unread < already_read)
+                                       memcpy(FB->Buf->buf, FB->ReadWritePointer, unread);
+                               else
+                                       memmove(FB->Buf->buf, FB->ReadWritePointer, unread);
+                               FB->ReadWritePointer = FB->Buf->buf;
+                               bufremain = FB->Buf->BufSize - unread - 1;
+                       }
+                       else if (bufremain < (FB->Buf->BufSize / 10))
+                       {
+                               /* get a bigger buffer */ 
+
+                               IncreaseBuf(FB->Buf, 0, FB->Buf->BufUsed + 1);
+
+                               FB->ReadWritePointer = FB->Buf->buf + unread;
+
+                               bufremain = FB->Buf->BufSize - unread - 1;
+/*TODO: special increase function that won't copy the already read! */
+                       }
+               }
+               else if (bufremain < 10) {
+                       IncreaseBuf(FB->Buf, 1, FB->Buf->BufUsed + 10);
+                       
+                       FB->ReadWritePointer = FB->Buf->buf;
+                       
+                       bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
+               }
+               
+       }
+       else {
+               FB->ReadWritePointer = FB->Buf->buf;
+               bufremain = FB->Buf->BufSize - 1;
+       }
+
+       n = read(fd, FB->Buf->buf + FB->Buf->BufUsed, bufremain);
+
+       if (n > 0) {
+               FB->Buf->BufUsed += n;
+               FB->Buf->buf[FB->Buf->BufUsed] = '\0';
+       }
+       return n;
+}
+
+int StrBuf_write_one_chunk_callback(int fd, short event, IOBuffer *FB)
+{
+       long WriteRemain;
+       int n;
+
+       if ((FB == NULL) || (FB->Buf == NULL))
+               return -1;
+
+       if (FB->ReadWritePointer != NULL)
+       {
+               WriteRemain = FB->Buf->BufUsed - 
+                       (FB->ReadWritePointer - 
+                        FB->Buf->buf);
+       }
+       else {
+               FB->ReadWritePointer = FB->Buf->buf;
+               WriteRemain = FB->Buf->BufUsed;
+       }
+
+       n = write(fd, FB->ReadWritePointer, WriteRemain);
+       if (n > 0) {
+               FB->ReadWritePointer += n;
+
+               if (FB->ReadWritePointer == 
+                   FB->Buf->buf + FB->Buf->BufUsed)
+               {
+                       FlushStrBuf(FB->Buf);
+                       FB->ReadWritePointer = NULL;
+                       return 0;
+               }
+       // check whether we've got something to write
+       // get the maximum chunk plus the pointer we can send
+       // write whats there
+       // if not all was sent, remember the send pointer for the next time
+               return FB->ReadWritePointer - FB->Buf->buf + FB->Buf->BufUsed;
+       }
+       return n;
+}
+
+/**
+ * @ingroup StrBuf_IO
+ * @brief extract a "next line" from Buf; Ptr to persist across several iterations
+ * @param LineBuf your line will be copied here.
+ * @param FB BLOB with lines of text...
+ * @param Ptr moved arround to keep the next-line across several iterations
+ *        has to be &NULL on start; will be &NotNULL on end of buffer
+ * @returns size of copied buffer
+ */
+eReadState StrBufChunkSipLine(StrBuf *LineBuf, IOBuffer *FB)
+{
+       const char *aptr, *ptr, *eptr;
+       char *optr, *xptr;
+
+       if ((FB->Buf == NULL) || (FB->ReadWritePointer == StrBufNOTNULL)) {
+               FB->ReadWritePointer = StrBufNOTNULL;
+               return eReadFail;
+       }
+
+       FlushStrBuf(LineBuf);
+       if (FB->ReadWritePointer == NULL)
+               ptr = aptr = FB->Buf->buf;
+       else
+               ptr = aptr = FB->ReadWritePointer;
+
+       optr = LineBuf->buf;
+       eptr = FB->Buf->buf + FB->Buf->BufUsed;
+       xptr = LineBuf->buf + LineBuf->BufSize - 1;
+
+       while ((ptr <= eptr) && 
+              (*ptr != '\n') &&
+              (*ptr != '\r') )
+       {
+               *optr = *ptr;
+               optr++; ptr++;
+               if (optr == xptr) {
+                       LineBuf->BufUsed = optr - LineBuf->buf;
+                       IncreaseBuf(LineBuf,  1, LineBuf->BufUsed + 1);
+                       optr = LineBuf->buf + LineBuf->BufUsed;
+                       xptr = LineBuf->buf + LineBuf->BufSize - 1;
+               }
+       }
+
+       if (ptr >= eptr) {
+               if (optr > LineBuf->buf)
+                       optr --;
+               if ((*(ptr - 1) != '\r') && (*(ptr - 1) != '\n')) {
+                       LineBuf->BufUsed = optr - LineBuf->buf;
+                       *optr = '\0';       
+                       return eMustReadMore;
+               }
+       }
+       LineBuf->BufUsed = optr - LineBuf->buf;
+       *optr = '\0';       
+       if ((ptr <= eptr) && (*ptr == '\r'))
+               ptr ++;
+       if ((ptr <= eptr) && (*ptr == '\n'))
+               ptr ++;
+       
+       if (ptr < eptr) {
+               FB->ReadWritePointer = ptr;
+       }
+       else {
+               FlushStrBuf(FB->Buf);
+               FB->ReadWritePointer = NULL;
+       }
+
+       return eReadSuccess;
+}
 
+/**
+ * @ingroup StrBuf_CHUNKED_IO
+ * @brief check whether the chunk-buffer has more data waiting or not.
+ * @param FB Chunk-Buffer to inspect
+ */
+eReadState StrBufCheckBuffer(IOBuffer *FB)
+{
+       if (FB == NULL)
+               return eReadFail;
+       if (FB->Buf->BufUsed == 0)
+               return eReadSuccess;
+       if (FB->ReadWritePointer == NULL)
+               return eBufferNotEmpty;
+       if (FB->Buf->buf + FB->Buf->BufUsed > FB->ReadWritePointer)
+               return eBufferNotEmpty;
+       return eReadSuccess;
+}
 
 /*******************************************************************************
  *           File I/O; Prefer buffered read since its faster!                  *
@@ -3964,7 +4241,7 @@ int StrBufReadBLOBBuffered(StrBuf *Blob,
  * @param Buf BLOB with lines of text...
  * @param Ptr moved arround to keep the next-line across several iterations
  *        has to be &NULL on start; will be &NotNULL on end of buffer
- * @returns size of copied buffer
+ * @returns size of remaining buffer
  */
 int StrBufSipLine(StrBuf *LineBuf, StrBuf *Buf, const char **Ptr)
 {