From 7999c662e8ed67250e03a3d47c821b13a64d1177 Mon Sep 17 00:00:00 2001 From: Edward Thomson Date: Tue, 31 Mar 2020 22:38:34 +0100 Subject: net: provide function to parse ssh paths SSH paths come in a variety of formats, either URLs (ssh://user@host/path) or SCP style (user@host:path). Provide a mechanism to parse them. --- src/util/net.c | 34 ++++++++++++++++++++++++++++++++++ src/util/net.h | 6 ++++++ 2 files changed, 40 insertions(+) diff --git a/src/util/net.c b/src/util/net.c index 2b85ea2d5..230903b7b 100644 --- a/src/util/net.c +++ b/src/util/net.c @@ -408,3 +408,37 @@ void git_net_url_dispose(git_net_url *url) git__free(url->username); url->username = NULL; git__free(url->password); url->password = NULL; } + +int git_net_url_parse_ssh(git_net_url *url, const char *given) +{ + const char *at, *colon; + size_t i; + + static const char *ssh_prefixes[] = { + "ssh://", "ssh+git://", "git+ssh://" + }; + + for (i = 0; i < ARRAY_SIZE(ssh_prefixes); i++) { + if (!git__prefixcmp(given, ssh_prefixes[i])) + return git_net_url_parse(url, given); + } + + if ((at = strchr(given, '@')) != NULL) { + url->username = git__substrdup(given, at - given); + GIT_ERROR_CHECK_ALLOC(url->username); + + given = at + 1; + } + + if ((colon = strchr(given, ':')) != NULL) { + url->host = git__substrdup(given, colon - given); + GIT_ERROR_CHECK_ALLOC(url->host); + + given = colon + 1; + } + + url->path = git__strdup(given); + GIT_ERROR_CHECK_ALLOC(url->path); + + return 0; +} diff --git a/src/util/net.h b/src/util/net.h index 5422a0a44..23ebb1e79 100644 --- a/src/util/net.h +++ b/src/util/net.h @@ -54,4 +54,10 @@ extern int git_net_url_fmt_path(git_buf *buf, git_net_url *url); /** Disposes the contents of the structure. */ extern void git_net_url_dispose(git_net_url *url); +/** + * Parses an SSH path string in user@host:path or ssh://host/path + * format and returns the results as a URL structure. + */ +extern int git_net_url_parse_ssh(git_net_url *url, const char *str); + #endif -- cgit v1.2.1