From 74d1bf51b5464d42f3be3f38ccbe0803b98fedc6 Mon Sep 17 00:00:00 2001 From: Praneeth Sarode Date: Mon, 6 Oct 2025 12:37:43 +0530 Subject: [PATCH] feat(string): add ssh_string_from_data function to create ssh_string from data buffer Signed-off-by: Praneeth Sarode Reviewed-by: Jakub Jelen --- include/libssh/libssh.h | 1 + src/libssh.map | 1 + src/string.c | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/include/libssh/libssh.h b/include/libssh/libssh.h index 452c1e2e..71cf20c3 100644 --- a/include/libssh/libssh.h +++ b/include/libssh/libssh.h @@ -844,6 +844,7 @@ LIBSSH_API int ssh_string_fill(ssh_string str, const void *data, size_t len); do { if ((x) != NULL) { ssh_string_free(x); x = NULL; } } while(0) LIBSSH_API void ssh_string_free(ssh_string str); LIBSSH_API ssh_string ssh_string_from_char(const char *what); +LIBSSH_API ssh_string ssh_string_from_data(const void *data, size_t len); LIBSSH_API size_t ssh_string_len(ssh_string str); LIBSSH_API ssh_string ssh_string_new(size_t size); LIBSSH_API const char *ssh_string_get_char(ssh_string str); diff --git a/src/libssh.map b/src/libssh.map index 7876ad9a..b31cf692 100644 --- a/src/libssh.map +++ b/src/libssh.map @@ -492,5 +492,6 @@ LIBSSH_AFTER_4_10_0 sshsig_sign; sshsig_verify; ssh_string_cmp; + ssh_string_from_data; } LIBSSH_4_10_0; diff --git a/src/string.c b/src/string.c index fdcce7cc..da9cf46b 100644 --- a/src/string.c +++ b/src/string.c @@ -128,6 +128,45 @@ struct ssh_string_struct *ssh_string_from_char(const char *what) return ptr; } +/** + * @brief Create a ssh string from an arbitrary data buffer. + * + * Allocates a new SSH string of length `len` and copies the provided data + * into it. If len is 0, returns an empty SSH string. When len > 0, data + * must not be NULL. + * + * @param[in] data Pointer to the data buffer to copy from. May be NULL + * only when len == 0. + * @param[in] len Length of the data buffer to copy. + * + * @return The newly allocated string, NULL on error. + */ +struct ssh_string_struct *ssh_string_from_data(const void *data, size_t len) +{ + struct ssh_string_struct *s = NULL; + int rc; + + if (len > 0 && data == NULL) { + errno = EINVAL; + return NULL; + } + + s = ssh_string_new(len); + if (s == NULL) { + return NULL; + } + + if (len > 0) { + rc = ssh_string_fill(s, data, len); + if (rc != 0) { + ssh_string_free(s); + return NULL; + } + } + + return s; +} + /** * @brief Return the size of a SSH string. *