aboutsummaryrefslogtreecommitdiffstats
path: root/usr/wget.c
blob: aafbae0c6d4a92cfe50c64ad895d4289916ee8f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "resolve.h"
/* wget HOST|IP - fetch http://HOST/ over the kernel TCP socket layer and print
   it. Resolves a hostname via DNS first (resolve.h), then connect()/send()/
   recv() over TCP - all the SLIP/IP/UDP/TCP lives in the kernel. */

static unsigned char buf[220];        /* first + large so namebuf/dst land arg-safe */
static unsigned char namebuf[64];
static unsigned char dst[4];

void main(void) {
    char *arg, *r;
    unsigned char s, n, i;
    arg = getargs();
    if (!arg || !*arg) { puts("usage: wget HOST|IP"); nl(); sexit(1); }
    for (i = 0; arg[i] && i < 63; i++) namebuf[i] = (unsigned char)arg[i];
    namebuf[i] = 0;

    if (!resolve((char *)namebuf, dst)) {
        puts("wget: cannot resolve "); puts((char *)namebuf); nl(); sexit(1);
    }
    puts("connecting "); for (i = 0; i < 4; i++) { putu(dst[i]); if (i < 3) putc('.'); } nl();

    s = net_socket(SOCK_TCP);
    if (s == 0xFF) { puts("wget: no socket"); nl(); sexit(1); }
    net_bind(s, 40001);
    if (net_connect(s, dst, 80) == 0xFF) { puts("wget: connect failed"); nl(); net_close(s); sexit(1); }

    /* GET / HTTP/1.0 with the requested host as the Host header */
    r = "GET / HTTP/1.0\r\nHost: ";
    n = 0;
    while (r[n]) { buf[n] = (unsigned char)r[n]; n++; }
    for (i = 0; namebuf[i]; i++) buf[n++] = namebuf[i];
    buf[n++] = '\r'; buf[n++] = '\n'; buf[n++] = '\r'; buf[n++] = '\n';
    net_send(s, buf, n);

    for (;;) {
        n = net_recv(s, buf, (unsigned char)sizeof(buf));
        if (n == 0xFF) { nl(); puts("[timeout]"); nl(); break; }
        if (n == 0)    { nl(); puts("[eof]");     nl(); break; }
        for (i = 0; i < n; i++) putc((char)buf[i]);
    }
    net_close(s);
}