BASE64: forcefully terminate it after deciphering it.
[citadel.git] / libcitadel / lib / stringbuf.c
index 6bcbaf1fa3ab725d10c19c1132b2cd2ec4628bbc..436864690bd62d0af5eb9f638053de41ac9fe495 100644 (file)
@@ -32,6 +32,9 @@
 
 #include "libcitadel.h"
 
+#include "b64/cencode.h"
+#include "b64/cdecode.h"
+
 #ifdef HAVE_ICONV
 #include <iconv.h>
 #endif
@@ -2820,9 +2823,81 @@ int StrBufDecodeBase64(StrBuf *Buf)
        free(Buf->buf);
        Buf->buf = xferbuf;
        Buf->BufUsed = siz;
+
+       Buf->buf[Buf->BufUsed] = '\0';
        return siz;
 }
 
+/**
+ * @ingroup StrBuf_DeEnCoder
+ * @brief decode a buffer from base 64 encoding; expects targetbuffer
+ * @param BufIn Buffor to transform
+ * @param BufOut Buffer to put result into
+ */
+int StrBufDecodeBase64To(const StrBuf *BufIn, StrBuf *BufOut)
+{
+       if ((BufIn == NULL) || (BufOut == NULL))
+               return -1;
+
+       if (BufOut->BufSize < BufIn->BufUsed)
+               IncreaseBuf(BufOut, BufIn->BufUsed, 0);
+
+       BufOut->BufUsed = CtdlDecodeBase64(BufOut->buf,
+                                          BufIn->buf,
+                                          BufIn->BufUsed);
+       return BufOut->BufUsed;
+}
+
+void *StrBufNewStreamContext(eStreamType type)
+{
+       base64_decodestate *state;;
+
+       switch (type)
+       {
+       case eBase64Decode:
+               state = (base64_decodestate*) malloc(sizeof(base64_decodestate));
+               base64_init_decodestate(state);
+               return state;
+               break;
+       }
+       return NULL;
+}
+
+void StrBufDestroyStreamContext(eStreamType type, void **Stream)
+{
+       switch (type)
+       {
+       case eBase64Decode:
+               free(*Stream);
+               *Stream = NULL;
+               break;
+       }
+}
+void StrBufStreamDecodeTo(StrBuf *Target, const StrBuf *In, const char* pIn, long pInLen, void *Stream)
+{
+       base64_decodestate *state = Stream;
+       long ExpectLen;
+
+       if (In != NULL)
+       {
+               pIn = In->buf;
+               pInLen = In->BufUsed;
+       }
+       if ((pIn == NULL) || (Stream == NULL))
+               return;
+       
+       ExpectLen = (pInLen / 4) * 3;
+
+       if (Target->BufSize - Target->BufUsed < ExpectLen)
+       {
+               IncreaseBuf(Target, 1, Target->BufUsed + ExpectLen + 1);
+       }
+
+       ExpectLen = base64_decode_block(pIn, pInLen, Target->buf + Target->BufUsed, state);
+       Target->BufUsed += ExpectLen;
+       Target->buf[Target->BufUsed] = '\0';
+}
+
 /**
  * @ingroup StrBuf_DeEnCoder
  * @brief decode a buffer from base 64 encoding; destroys original