diff options
author | Anderson Toshiyuki Sasaki <ansasaki@redhat.com> | 2019-11-04 15:35:15 +0100 |
---|---|---|
committer | Andreas Schneider <asn@cryptomilk.org> | 2019-12-09 16:08:03 +0100 |
commit | c9ce8fa40b45af7fca2c75fe5f0614d881e35a84 (patch) | |
tree | 0d44bde9d4cf545f5c4ff57d2517357351a6b619 /src | |
parent | 6c79ed980163d4692281c73adf569c0112885f3e (diff) | |
download | libssh-c9ce8fa40b45af7fca2c75fe5f0614d881e35a84.tar.gz libssh-c9ce8fa40b45af7fca2c75fe5f0614d881e35a84.tar.xz libssh-c9ce8fa40b45af7fca2c75fe5f0614d881e35a84.zip |
misc: Add a function to encode newlines
Given a string, the added function encodes existing newline characters
('\n') as the string "\\n" and puts into a given output buffer.
The output buffer must have at least 2 times the length of the input
string plus 1 for the terminating '\0'. In the worst case, each
character can be replaced by 2 characters.
Fixes T189
Signed-off-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>
Reviewed-by: Andreas Schneider <asn@cryptomilk.org>
Reviewed-by: Jakub Jelen <jjelen@redhat.com>
Diffstat (limited to 'src')
-rw-r--r-- | src/misc.c | 43 |
1 files changed, 43 insertions, 0 deletions
@@ -1692,4 +1692,47 @@ error: return SSH_ERROR; } +/** + * @internal + * + * @brief Given a string, encode existing newlines as the string "\\n" + * + * @param[in] string Input string + * @param[out] buf Output buffer. This buffer must be at least (2 * + * strlen(string)) + 1 long. In the worst case, + * each character can be encoded as 2 characters plus the + * terminating '\0'. + * @param[in] buf_len Size of the provided output buffer + * + * @returns SSH_ERROR on error; length of the resulting string not counting the + * terminating '\0' otherwise + */ +int ssh_newline_vis(const char *string, char *buf, size_t buf_len) +{ + const char *in = NULL; + char *out = NULL; + + if (string == NULL || buf == NULL || buf_len == 0) { + return SSH_ERROR; + } + + if ((2 * strlen(string) + 1) > buf_len) { + SSH_LOG(SSH_LOG_WARNING, "Buffer too small"); + return SSH_ERROR; + } + + out = buf; + for (in = string; *in != '\0'; in++) { + if (*in == '\n') { + *out++ = '\\'; + *out++ = 'n'; + } else { + *out++ = *in; + } + } + *out = '\0'; + + return out - buf; +} + /** @} */ |