diff --git a/include/base64.h b/include/base64.h
index 0ff7116..381ef5d 100644
--- a/include/base64.h
+++ b/include/base64.h
@@ -36,7 +36,6 @@
#include <assert.h>
#include "types.h"
-#define B64_BUF 16384
#define FAIL -1
#define SKIP -2
diff --git a/src/base64.c b/src/base64.c
index fd01bac..1b0f301 100644
--- a/src/base64.c
+++ b/src/base64.c
@@ -85,11 +85,9 @@ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL
};
/* Returns NULL on error */
-/* FIXME Possible buffer overflow on outputs larger than B64_BUF */
char* encode_base64(byte* src,size_t ssize)
{
char* outbuf;
- char* retbuf;
int pos;
int i, l, left;
unsigned long triple;
@@ -101,7 +99,10 @@ char* encode_base64(byte* src,size_t ssize)
error(240,"\n");
return NULL;
}
- outbuf = (char *)malloc(sizeof(char)*B64_BUF);
+
+ /* length of encoded base64 string (padded) */
+ size_t length = sizeof(char)* ((ssize + 2) / 3) * 4;
+ outbuf = (char *)malloc(length + 1);
/* Initialize working pointers */
inb = src;
@@ -162,20 +163,14 @@ char* encode_base64(byte* src,size_t ssize)
inb++;
}
- /* outbuf is not completely used so we use retbuf */
- retbuf=(char*)malloc(sizeof(char)*(pos+1));
- memcpy(retbuf,outbuf,pos);
- retbuf[pos]='\0';
- free(outbuf);
+ outbuf[pos]='\0';
- return retbuf;
+ return outbuf;
}
-/* FIXME Possible buffer overflow on outputs larger than B64_BUF */
byte* decode_base64(char* src,size_t ssize, size_t *ret_len)
{
byte* outbuf;
- byte* retbuf;
char* inb;
int i;
int l;
@@ -188,10 +183,18 @@ byte* decode_base64(char* src,size_t ssize, size_t *ret_len)
if (!ssize||src==NULL)
return NULL;
+ /* exit on unpadded input */
+ if (ssize % 4) {
+ error(3, "decode_base64: '%s' has invalid length (missing padding characters?)", src);
+ return NULL;
+ }
+
+ /* calculate length of decoded string, substract padding chars if any (ssize is >= 4) */
+ size_t length = sizeof(byte) * ((ssize / 4) * 3)- (src[ssize-1] == '=') - (src[ssize-2] == '=');
/* Initialize working pointers */
inb = src;
- outbuf = (byte *)malloc(sizeof(byte)*B64_BUF);
+ outbuf = (byte *)malloc(length + 1);
l = 0;
triple = 0;
@@ -243,15 +246,11 @@ byte* decode_base64(char* src,size_t ssize, size_t *ret_len)
inb++;
}
- retbuf=(byte*)malloc(sizeof(byte)*(pos+1));
- memcpy(retbuf,outbuf,pos);
- retbuf[pos]='\0';
-
- free(outbuf);
+ outbuf[pos]='\0';
if (ret_len) *ret_len = pos;
- return retbuf;
+ return outbuf;
}
size_t length_base64(char* src,size_t ssize)
diff --git a/src/db.c b/src/db.c
index 858240d..62c4faa 100644
--- a/src/db.c
+++ b/src/db.c
@@ -664,13 +664,15 @@ db_line* db_char2line(char** ss,int db){
time_t base64totime_t(char* s){
+ if(strcmp(s,"0")==0){
+ return 0;
+ }
byte* b=decode_base64(s,strlen(s),NULL);
char* endp;
- if (b==NULL||strcmp(s,"0")==0) {
+ if (b==NULL) {
/* Should we print error here? */
- free(b);
return 0;
} else {