aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndreas Schneider <asn@cryptomilk.org>2019-12-10 18:28:03 +0100
committerAndreas Schneider <asn@cryptomilk.org>2019-12-20 14:35:04 +0100
commit5317ebf0fcf927e45a4c7a8c322357179dd87f2f (patch)
tree4f6ee597c28e276f89a669c93d91125529964947
parent08f4469e21981185eaf9da5d6f84eec9e845b124 (diff)
downloadlibssh-5317ebf0fcf927e45a4c7a8c322357179dd87f2f.tar.gz
libssh-5317ebf0fcf927e45a4c7a8c322357179dd87f2f.tar.xz
libssh-5317ebf0fcf927e45a4c7a8c322357179dd87f2f.zip
misc: Add ssh_tmpname()
Signed-Off-By: Andreas Schneider <asn@cryptomilk.org> Reviewed-by: Jakub Jelen <jjelen@redhat.com>
-rw-r--r--include/libssh/misc.h1
-rw-r--r--src/misc.c51
2 files changed, 52 insertions, 0 deletions
diff --git a/include/libssh/misc.h b/include/libssh/misc.h
index 3cc3b113..4c25a54a 100644
--- a/include/libssh/misc.h
+++ b/include/libssh/misc.h
@@ -96,5 +96,6 @@ int ssh_mkdirs(const char *pathname, mode_t mode);
int ssh_quote_file_name(const char *file_name, char *buf, size_t buf_len);
int ssh_newline_vis(const char *string, char *buf, size_t buf_len);
+int ssh_tmpname(char *template);
#endif /* MISC_H_ */
diff --git a/src/misc.c b/src/misc.c
index 0f1a7d49..bedf18e8 100644
--- a/src/misc.c
+++ b/src/misc.c
@@ -1735,4 +1735,55 @@ int ssh_newline_vis(const char *string, char *buf, size_t buf_len)
return out - buf;
}
+/**
+ * @internal
+ *
+ * @brief Replaces the last 6 characters of a string from 'X' to 6 random hexdigits.
+ *
+ * @param[in] template Any input string with last 6 characters as 'X'.
+ * @returns -1 as error when the last 6 characters of the input to be replaced are not 'X'
+ * 0 otherwise.
+ */
+int ssh_tmpname(char *template)
+{
+ char *tmp = NULL;
+ size_t i = 0;
+
+ if (template == NULL) {
+ goto err;
+ }
+
+ tmp = template + strlen(template) - 6;
+ if (tmp < template) {
+ goto err;
+ }
+
+ for (i = 0; i < 6; i++) {
+ if (tmp[i] != 'X') {
+ SSH_LOG(SSH_LOG_WARNING,
+ "Invalid input. Last six characters of the input must be \'X\'");
+ goto err;
+ }
+ }
+
+ srand(time(NULL));
+
+ for (i = 0; i < 6; ++i) {
+#ifdef _WIN32
+ /* in win32 MAX_RAND is 32767, thus we can not shift that far,
+ * otherwise the last three chars are 0 */
+ int hexdigit = (rand() >> (i * 2)) & 0x1f;
+#else
+ int hexdigit = (rand() >> (i * 5)) & 0x1f;
+#endif
+ tmp[i] = hexdigit > 9 ? hexdigit + 'a' - 10 : hexdigit + '0';
+ }
+
+ return 0;
+
+err:
+ errno = EINVAL;
+ return -1;
+}
+
/** @} */