1 18824b58 2008-08-03 rsc #include "a.h"
3 18824b58 2008-08-03 rsc typedef struct DEntry DEntry;
7 18824b58 2008-08-03 rsc HTTPHeader hdr;
8 18824b58 2008-08-03 rsc char *tmpfile;
13 18824b58 2008-08-03 rsc dfree(CEntry *ce)
17 18824b58 2008-08-03 rsc d = (DEntry*)ce;
18 18824b58 2008-08-03 rsc if(d->tmpfile){
19 18824b58 2008-08-03 rsc remove(d->tmpfile);
20 18824b58 2008-08-03 rsc free(d->tmpfile);
21 18824b58 2008-08-03 rsc close(d->fd);
25 18824b58 2008-08-03 rsc static Cache *downloadcache;
28 18824b58 2008-08-03 rsc parseurl(char *url, char **path)
30 18824b58 2008-08-03 rsc char *host, *p;
33 18824b58 2008-08-03 rsc if(memcmp(url, "http://", 7) != 0)
35 18824b58 2008-08-03 rsc p = strchr(url+7, '/');
37 18824b58 2008-08-03 rsc p = url+strlen(url);
38 18824b58 2008-08-03 rsc len = p - (url+7);
39 18824b58 2008-08-03 rsc host = emalloc(len+1);
40 18824b58 2008-08-03 rsc memmove(host, url+7, len);
41 18824b58 2008-08-03 rsc host[len] = 0;
49 18824b58 2008-08-03 rsc download(char *url, HTTPHeader *hdr)
52 18824b58 2008-08-03 rsc char *host, *path;
53 18824b58 2008-08-03 rsc char buf[] = "/var/tmp/smugfs.XXXXXX";
58 18824b58 2008-08-03 rsc if(downloadcache == nil)
59 18824b58 2008-08-03 rsc downloadcache = newcache(sizeof(DEntry), 128, dfree);
61 18824b58 2008-08-03 rsc host = parseurl(url, &path);
62 18824b58 2008-08-03 rsc if(host == nil)
65 18824b58 2008-08-03 rsc d = (DEntry*)cachelookup(downloadcache, url, 1);
66 18824b58 2008-08-03 rsc if(d->tmpfile){
68 18824b58 2008-08-03 rsc *hdr = d->hdr;
69 18824b58 2008-08-03 rsc return dup(d->fd, -1);
71 18824b58 2008-08-03 rsc d->fd = -1; // paranoia
73 18824b58 2008-08-03 rsc if((fd = opentemp(buf, ORDWR|ORCLOSE)) < 0){
78 18824b58 2008-08-03 rsc fmtstrinit(&fmt);
79 18824b58 2008-08-03 rsc fmtprint(&fmt, "GET %s HTTP/1.0\r\n", path);
80 18824b58 2008-08-03 rsc fmtprint(&fmt, "Host: %s\r\n", host);
81 18824b58 2008-08-03 rsc fmtprint(&fmt, "User-Agent: " USER_AGENT "\r\n");
82 18824b58 2008-08-03 rsc fmtprint(&fmt, "\r\n");
83 18824b58 2008-08-03 rsc req = fmtstrflush(&fmt);
85 18824b58 2008-08-03 rsc fprint(2, "Get %s\n", url);
87 18824b58 2008-08-03 rsc if(httptofile(&http, host, req, hdr, fd) < 0){
94 18824b58 2008-08-03 rsc d->tmpfile = estrdup(buf);
95 18824b58 2008-08-03 rsc d->fd = dup(fd, -1);
96 18824b58 2008-08-03 rsc d->hdr = *hdr;
101 18824b58 2008-08-03 rsc downloadflush(char *substr)
103 18824b58 2008-08-03 rsc if(downloadcache)
104 18824b58 2008-08-03 rsc cacheflush(downloadcache, substr);