/* * Secure eXtended Message Passing framework * Secure eXtended Transport layer implementation: (libsxt) * - very similar to SSH2/TLS * - using already proven and tested crypto algos * - better than TLS for message passing * * (c) Alexander Vdolainen 2016 * * libsxmp is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 2.1 of the License, or * (at your option) any later version. * * libsxmp is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see ."; * */ #include #include #include #include #include #include #include sxtsafebuffer_t *sxtsafebuffer_new(size_t size) { sxtsafebuffer_t *buf = NULL; if(size > (UINT_MAX - sizeof(sxtsafebuffer_t))) return NULL; if(!(buf = malloc(sizeof(sxtsafebuffer_t) + size))) return NULL; buf->size = htonl(size); buf->data[0] = 0; return buf; } int sxtsafebuffer_setdata(sxtsafebuffer_t *buf, const void *data, size_t size) { /* validate parameters */ if(!buf || !data) return -1; if(!size || size > sxtsafebuffer_length(buf)) return -1; memcpy(buf->data, data, size); return 0; } size_t sxtsafebuffer_length(sxtsafebuffer_t *buf) { size_t size = 0; if(!buf) return size; else size = ntohl(buf->size); if((size > 0) && (size < UINT_MAX)) return size; return 0; } void sxtsafebuffer_destroy(sxtsafebuffer_t *buf) { if(!buf) return; buf->size = 0; memset((void *)buf->data, 0, sxtsafebuffer_length(buf)); free(buf); return; } void *sxtsafebuffer_getdata(sxtsafebuffer_t *buf) { if(!buf) return NULL; return (void *)buf->data; } /* C string ops */ const char *sxtsafebuffer_tocstr(sxtsafebuffer_t *buf) { if(!buf) return NULL; buf->data[sxtsafebuffer_length(buf)] = '\0'; return (const char *)buf->data;; } sxtsafebuffer_t *sxtsafebuffer_new_fromcstr(const char *str) { size_t length; sxtsafebuffer_t *buf = NULL; if(!str) return NULL; else length = strlen(str); if(!(buf = sxtsafebuffer_new(length))) return NULL; else memcpy(buf->data, str, length); return buf; } /* returning value should be freed after use */ char *sxtsafebuffer_getcstr(sxtsafebuffer_t *buf) { size_t length; char *str = NULL; if(!buf) return NULL; length = sxtsafebuffer_length(buf); if(length <= 0) return NULL; if(!(str = malloc(length + 1))) return NULL; else memcpy(str, buf->data, length); str[length] = '\0'; return str; } void sxtsafebuffer_freecstr(char *str) { if(!str) return; memset(str, 0, strlen(str)); free(str); return; }