apk-tools/src/url.c

113 lines
2.2 KiB
C
Raw Normal View History

2008-11-28 13:03:27 +00:00
/* url.c - Alpine Package Keeper (APK)
*
* Copyright (C) 2005-2008 Natanael Copa <n@tanael.org>
* Copyright (C) 2008 Timo Teräs <timo.teras@iki.fi>
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
2008-11-28 13:03:27 +00:00
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation. See http://www.gnu.org/ for details.
*/
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
2008-11-28 13:03:27 +00:00
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
2008-11-28 13:03:27 +00:00
#include "apk_io.h"
const char *apk_url_local_file(const char *url)
2008-11-28 13:03:27 +00:00
{
if (strncmp(url, "file:", 5) == 0)
return &url[5];
if (strncmp(url, "http:", 5) != 0 &&
strncmp(url, "https:", 6) != 0 &&
strncmp(url, "ftp:", 4) != 0)
return url;
return NULL;
}
static int fork_wget(const char *url)
{
pid_t pid;
int fds[2];
if (pipe(fds) < 0)
return -1;
pid = fork();
if (pid == -1) {
close(fds[0]);
close(fds[1]);
return -1;
}
if (pid == 0) {
setsid();
close(fds[0]);
dup2(open("/dev/null", O_RDONLY), STDIN_FILENO);
dup2(fds[1], STDOUT_FILENO);
2009-01-16 09:58:27 +00:00
execlp("wget", "wget", "-q", "-O", "-", url, NULL);
2008-11-28 13:03:27 +00:00
exit(0);
}
close(fds[1]);
return fds[0];
}
struct apk_istream *apk_istream_from_url(const char *url)
{
if (apk_url_local_file(url) != NULL)
return apk_istream_from_file(AT_FDCWD, apk_url_local_file(url));
2008-11-28 13:03:27 +00:00
return apk_istream_from_fd(fork_wget(url));
}
2009-01-15 10:55:26 +00:00
struct apk_istream *apk_istream_from_url_gz(const char *file)
{
return apk_bstream_gunzip(apk_bstream_from_url(file));
2009-01-15 10:55:26 +00:00
}
2008-11-28 13:03:27 +00:00
struct apk_bstream *apk_bstream_from_url(const char *url)
{
if (apk_url_local_file(url))
return apk_bstream_from_file(AT_FDCWD, url);
2008-11-28 13:03:27 +00:00
return apk_bstream_from_fd(fork_wget(url));
}
2009-01-15 10:55:26 +00:00
int apk_url_download(const char *url, int atfd, const char *file)
{
pid_t pid;
int status, fd;
fd = openat(atfd, file, O_CREAT|O_RDWR|O_TRUNC, 0644);
if (fd < 0)
return -errno;
pid = fork();
if (pid == -1)
return -1;
if (pid == 0) {
setsid();
dup2(open("/dev/null", O_RDONLY), STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
execlp("wget", "wget", "-q", "-O", "-", url, NULL);
exit(0);
}
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
unlinkat(atfd, file, 0);
return -1;
}
return 0;
}