119 lines
2.1 KiB
C
119 lines
2.1 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <skalibs/buffer.h>
|
|
#include <skalibs/skamisc.h>
|
|
#include <skalibs/stralloc.h>
|
|
#include <skalibs/strerr.h>
|
|
#include <skalibs/djbunix.h>
|
|
#include <skalibs/exec.h>
|
|
|
|
#define USAGE "mvwtimg host path filename"
|
|
#define HTTPOK "HTTP/1.1 200 OK"
|
|
|
|
int
|
|
download(int infd, char *path)
|
|
{
|
|
int outfd;
|
|
|
|
outfd = open_trunc(path);
|
|
if (outfd < 0)
|
|
return -1;
|
|
|
|
if (fd_cat(infd, outfd) < 0) {
|
|
fd_close(outfd);
|
|
return -1;
|
|
}
|
|
|
|
fd_sync(outfd);
|
|
fd_close(outfd);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
fdgetln(int fd, stralloc *sa, int sep)
|
|
{
|
|
char s[1];
|
|
ssize_t r;
|
|
|
|
sa->len = 0;
|
|
for (;;) {
|
|
r = fd_read(fd, s, 1);
|
|
if (r < 0)
|
|
return -1;
|
|
if (s[0] == EOF)
|
|
break;
|
|
stralloc_append(sa, s[0]);
|
|
if (s[0] == sep)
|
|
break;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
http_recv_header(int fd)
|
|
{
|
|
stralloc sa = STRALLOC_ZERO;
|
|
|
|
if (fdgetln(fd, &sa, '\n') < 0)
|
|
return -1;
|
|
if (sa.len < sizeof(HTTPOK) || !strncmp(sa.s, HTTPOK, sizeof(HTTPOK)))
|
|
return -1;
|
|
sa.len = 0;
|
|
|
|
for (;;) {
|
|
if (fdgetln(fd, &sa, '\n') < 0)
|
|
return -1;
|
|
if (!strncmp(sa.s, "\r\n", 2)) {
|
|
break;
|
|
}
|
|
sa.len = 0;
|
|
}
|
|
|
|
stralloc_free(&sa);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
http_send(int fd, char *path, char *host)
|
|
{
|
|
char buf[BUFFER_OUTSIZE];
|
|
|
|
buffer b = BUFFER_INIT(&buffer_write, fd, buf, BUFFER_OUTSIZE);
|
|
|
|
buffer_putsnoflush(&b, "GET ");
|
|
buffer_putsnoflush(&b, path);
|
|
buffer_putsnoflush(&b, " HTTP/1.0\r\n");
|
|
buffer_putsnoflush(&b, "Host: ");
|
|
buffer_putsnoflush(&b, host);
|
|
buffer_putsnoflush(&b, "\r\nConnection: close\r\n");
|
|
buffer_putsnoflush(&b, "User-Agent: mvwt\r\n\r\n");
|
|
buffer_flush(&b);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
main(int argc, char *argv[])
|
|
{
|
|
PROG = "mvwtimg";
|
|
|
|
if (argc != 4)
|
|
strerr_dieusage(100, USAGE);
|
|
|
|
if (http_send(7, argv[2], argv[1]) < 0)
|
|
strerr_diefu(111, "send http request");
|
|
if (http_recv_header(6) < 0)
|
|
strerr_diefu(111, "recieve image header");
|
|
if (download(6, argv[3]) < 0)
|
|
strerr_diefu(111, "downloading and saving image");
|
|
fd_shutdown(7, 1);
|
|
fd_close(7);
|
|
fd_shutdown(6, 0);
|
|
fd_close(6);
|
|
|
|
char const *hsetroot_argv[] = { "hsetroot", "-cover", argv[3], 0 };
|
|
xexec(hsetroot_argv);
|
|
return 0;
|
|
}
|