From bc2b876ae20675d2673f5b57db10ddc99c063e63 Mon Sep 17 00:00:00 2001 From: Nathan Wagner Date: Sat, 16 Feb 2019 09:27:20 +0000 Subject: [PATCH] add option to determine name from url --- src/fetchurl.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/fetchurl.c b/src/fetchurl.c index 3a9436b..9d52696 100644 --- a/src/fetchurl.c +++ b/src/fetchurl.c @@ -508,6 +508,37 @@ static void fake_header(struct io *io, int fd) { tls_buffer_append(hdr, "\r\n", 2); } +char *pathlast(char *path) { + char *last = 0; + size_t len = 0; + + if (path == 0) { + return 0; + } + + while (*path == '/') { + path++; + } + + do { + last = path; + len = 0; + while (*path && *path != '/') { + path++; + len++; + } + while (*path == '/') { + path++; + } + } while (*path); + + if (len == 0) { + return 0; + } + + return strndup(last, len); +} + int main(int ac, char *av[]) { int sockfd, port = -1, rv; ssize_t ret; @@ -536,13 +567,14 @@ int main(int ac, char *av[]) { size_t header_len; char *url = 0; int redirs = 0, redirlimit = 50, printstatus = 0; - int verifypolicy = 1; + int verifypolicy = 1, calcoutfile = 0; ltc_mp = tfm_desc; - while ((option = getopt(ac, av, "o:rIfz:#R:SkK")) != -1) { + while ((option = getopt(ac, av, "o:OrIfz:#R:SkK")) != -1) { switch (option) { case 'o': outfile = optarg; break; + case 'O': calcoutfile = 1; break; case 'S': printstatus = 1; head = 1; break; case 'k': verifypolicy = 0; break; case 'K': verifypolicy = 2; break; @@ -586,6 +618,19 @@ int main(int ac, char *av[]) { exit(EXIT_FAILURE); } + if (calcoutfile && !outfile) { + tls_parse_uri(url, &uri); + outfile = pathlast(uri.path); + /* outfile leaks memory here, so if this + * were turned into a library function, + * we'd need to track it + */ + if (!outfile) { + fprintf(stderr, "unable to determine outfile\n"); + exit(EXIT_FAILURE); + } + } + if (outfile) { out = open(outfile, O_WRONLY|O_CREAT, 0600); if (out == -1) { @@ -609,6 +654,7 @@ int main(int ac, char *av[]) { port = atoi(uri.port); req_file = uri.path; + /* construct request */ if (head) { tls_buffer_append(&request, "HEAD ", 5); -- 2.40.0