/** ** abac_m64.c **/ #include #include #include #include #include #include #include "zlib.h" #define CHUNK 1024 /* 16384 */ static int debug=0; static int zip=1; /* to choose to compress/decompress */ /* using strongswan's m64 utility so we can stay within the buf len size that strongwan set in using its certifiate generation code (512) chunk_t b64 = chunk_to_base64(chunk, NULL); chunk_t chk = chunk_from_base64(base64, NULL); */ static int _compress(char *string, int slen, char*ostring) { unsigned long olen=CHUNK; unsigned long ilen=(unsigned long) slen; int rc=compress(ostring,&olen,string,ilen); if(rc==Z_OK) { if(debug) fprintf(stderr,"compress from %ld to %ld\n", ilen, olen); return (int)olen; } return 0; } /* all of these are deep copy of a string */ char* abac_encode_string(char *string) { assert(string); char *ret=NULL; char *ptr=string;; int len=strlen(ptr); char ostring[CHUNK]; if(zip) { int olen=_compress(ptr, len, ostring); if(olen==0) { /* can not do the compress */ if(debug) fprintf(stderr,"ERROR, can not compress the string!!\n"); errx(1, "ERROR, compress failed!!"); } else { ptr=ostring; len=olen; } } chunk_t orig = { ptr, len }; chunk_t b64 = chunk_to_base64(orig, NULL); if(debug) fprintf(stderr,"abac_encode_string: (%s)\n",b64.ptr); ret=strndup(b64.ptr,b64.len); chunk_free(&b64); return ret; } static int _uncompress(char *string, int slen, char *ostring) { unsigned long olen=CHUNK; unsigned long ilen=(unsigned long) slen; int rc=uncompress(ostring,&olen,string,ilen); if(rc==Z_OK) { if(debug) fprintf(stderr,"uncompress from %ld to %ld\n", ilen, olen); return (int)olen; } return 0; } char* abac_decode_string(char *string) { assert(string); char *ret=NULL; int len=strlen(string); chunk_t b64 = { string, len }; chunk_t chk= chunk_from_base64(b64, NULL); if(debug) fprintf(stderr,"abac_decode_string: (%s)\n",chk.ptr); if(zip) { char ostring[CHUNK]; int olen=_uncompress(chk.ptr, chk.len, ostring); if(olen==0) { /* unable to uncompress the string!! */ if(debug) fprintf(stderr,"ERROR, can not uncompress the string!!\n"); errx(1, "ERROR, uncompress failed!!"); } else ret=strndup(ostring,olen); } else { ret=strndup(chk.ptr, chk.len); } chunk_free(&chk); return ret; }