aboutsummaryrefslogtreecommitdiffstats
path: root/c/wget.c
blob: 9d99eb0b75ad290c4827b80497917d98522cf557 (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
44
45
46
#include "sock.h"
/* wget [A.B.C.D] - fetch http://TARGET/ over the kernel TCP socket layer and
   print it. No SLIP/IP/TCP here: connect() handshakes in the kernel, send()/
   recv() drive the stream. Default target 10.0.0.1:80 (the SLIP peer/host). */

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

static unsigned char parse_ip(char *s, unsigned char *out) {
    unsigned char i, v;
    for (i = 0; i < 4; i++) {
        if (*s < '0' || *s > '9') return 0;
        v = 0;
        while (*s >= '0' && *s <= '9') { v = (unsigned char)(v * 10 + (*s - '0')); s++; }
        out[i] = v;
        if (i < 3) { if (*s != '.') return 0; s++; }
    }
    return 1;
}

void main(void) {
    char *arg, *r;
    unsigned char s, n, i;
    arg = getargs();
    if (!arg || !*arg) { dst[0] = 10; dst[1] = 0; dst[2] = 0; dst[3] = 1; }
    else if (!parse_ip(arg, dst)) { puts("wget: bad address"); nl(); sexit(1); }

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

    r = "GET / HTTP/1.0\r\nHost: gbos\r\n\r\n";
    n = 0;
    while (r[n]) { buf[n] = r[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);
}