Skip to content
pi-c Documentation
Login

Documentation

/* The web_fetch tool: a GET of one public URL over pic's own HTTP and TLS, redirects followed
 * (five at most), the body capped (5 MB) and the whole call under a deadline (30 s). HTML becomes
 * markdown-ish text (htmltext.c); text and JSON pass through; binary types are refused. The
 * address check is the transport's web mode (net.c), made on every address actually connected to,
 * so it holds for a name that resolves to a private address and for each redirect. What is
 * returned is cut to max_chars, the whole kept for read as pic:output/N. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <arpa/inet.h>
#include <ctype.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>

#include "htmltext.h"
#include "http.h"
#include "net.h"
#include "toolreg.h"
#include "userdb.h"
#include "webfetch.h"

#define WF_MAX_BODY (5u * 1024u * 1024u)
#define WF_DEADLINE 30
#define WF_REDIRECTS 5
#define WF_URL_MAX 4096
#define WF_DEFAULT_CHARS 20000
#define WF_MAX_CHARS 50000

static const char wf_schema[] =
    "{\"name\":\"web_fetch\",\"description\":\"Fetch a public web page (http or https) and return its text. HTML is "
    "converted to markdown (headings, links, lists and code blocks kept; scripts, styles and navigation dropped); "
    "plain text and JSON are returned as they are; images, PDFs and other binary types are refused. Redirects are "
    "followed (up to 5); pages over 5 MB and requests over 30 seconds fail; addresses on private networks, loopback, "
    "link-local and cloud metadata addresses are refused. The text is cut to max_chars (default 20000, at most "
    "50000); the whole is kept and a notice names where to read the rest with the read tool.\","
    "\"input_schema\":{\"type\":\"object\",\"properties\":{"
    "\"url\":{\"type\":\"string\",\"description\":\"The page's address, beginning http:// or https://\"},"
    "\"max_chars\":{\"type\":\"integer\",\"description\":\"The most characters to return (default 20000, at most "
    "50000)\"}},\"required\":[\"url\"]}}";

/* ---- messages ---------------------------------------------------------------------------- */

static char *wf_fmt(int *is_error, const char *fmt, ...) {
    va_list ap;
    int n;
    char *out;
    va_start(ap, fmt);
    n = vsnprintf(NULL, 0, fmt, ap);
    va_end(ap);
    if (n < 0 || !(out = malloc((size_t)n + 1))) {
        return NULL;
    }
    va_start(ap, fmt);
    (void)vsnprintf(out, (size_t)n + 1, fmt, ap);
    va_end(ap);
    *is_error = 1;
    return out;
}

/* ---- the input --------------------------------------------------------------------------- */

/* The first column of SQL's first row, with ?1 bound to A, as text (malloc'd), or NULL. */
static char *wf_json(const char *sql, const char *a) {
    sqlite3 *db = NULL;
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
        sqlite3_close(db);
        return NULL;
    }
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    sqlite3_close(db);
    return out;
}

/* ---- URLs -------------------------------------------------------------------------------- */

/* A parsed absolute URL: scheme, authority (host[:port], the host bracketed for IPv6) and the
 * path with its query, always beginning with '/'. */
typedef struct {
    char scheme[8];
    char auth[300];
    char path[WF_URL_MAX];
} wf_url;

/* Writes the percent-encoding of the bytes a URL may not carry (controls and non-ASCII). */
static int wf_clean_url(const char *in, char *out, size_t cap) {
    size_t o = 0;
    for (const unsigned char *p = (const unsigned char *)in; *p && *p != '#'; p++) {
        if (*p <= ' ' || *p == 0x7f) {
            return -1; /* a space or a control character */
        }
        if (*p >= 0x80) {
            if (o + 3 >= cap) {
                return -1;
            }
            o += (size_t)snprintf(out + o, cap - o, "%%%02X", *p);
        } else {
            if (o + 1 >= cap) {
                return -1;
            }
            out[o++] = (char)*p;
        }
    }
    out[o] = '\0';
    return 0;
}

/* Parses an absolute http(s) URL; 0, or -1 with WHY. The host is made canonical: lowercase, and an
 * IPv4 written as a number, in octal or hex, or short ("127.1") as its dotted quad, so what is
 * checked is what is connected to. */
static int wf_parse(const char *raw, wf_url *u, const char **why) {
    char clean[WF_URL_MAX], *rest, *at, host[256], *colon;
    const char *port = "";
    if (wf_clean_url(raw, clean, sizeof clean) != 0) {
        *why = "the URL has a space or control character, or is too long";
        return -1;
    }
    if (strncasecmp(clean, "https://", 8) == 0) {
        strcpy(u->scheme, "https");
        rest = clean + 8;
    } else if (strncasecmp(clean, "http://", 7) == 0) {
        strcpy(u->scheme, "http");
        rest = clean + 7;
    } else {
        *why = "only http and https URLs can be fetched";
        return -1;
    }
    {
        size_t alen = (size_t)(strcspn(rest, "/?"));
        char auth[300];
        if (alen == 0 || alen >= sizeof auth) {
            *why = "the URL has no host";
            return -1;
        }
        memcpy(auth, rest, alen);
        auth[alen] = '\0';
        at = strchr(auth, '@');
        if (at) {
            *why = "a URL with a user name or password is not fetched";
            return -1;
        }
        if (auth[0] == '[') {
            char *close = strchr(auth, ']');
            if (!close || (close[1] != '\0' && close[1] != ':') || close - auth < 3 || (size_t)(close - auth) + 1 >= sizeof host) {
                *why = "the URL's host is malformed";
                return -1;
            }
            memcpy(host, auth, (size_t)(close - auth) + 1);
            host[close - auth + 1] = '\0';
            port = close[1] == ':' ? close + 2 : "";
        } else {
            colon = strchr(auth, ':');
            if (colon) {
                *colon = '\0';
                port = colon + 1;
            }
            if (strlen(auth) >= sizeof host) {
                *why = "the URL's host is too long";
                return -1;
            }
            (void)snprintf(host, sizeof host, "%s", auth);
            for (char *p = host; *p; p++) {
                if ((unsigned char)*p >= 0x80 || *p == '%') {
                    *why = "give the host in ASCII (punycode for an international name)";
                    return -1;
                }
                *p = (char)tolower((unsigned char)*p);
            }
            if (host[0] == '\0') {
                *why = "the URL has no host";
                return -1;
            }
            {
                struct in_addr a;
                if (strspn(host, "0123456789.xXabcdefABCDEF") == strlen(host) && inet_aton(host, &a) != 0) {
                    (void)inet_ntop(AF_INET, &a, host, sizeof host);
                }
            }
        }
        if (*port) {
            char *stop;
            long p = strtol(port, &stop, 10);
            if (*stop || p < 1 || p > 65535 || strlen(port) > 5) {
                *why = "the URL's port is not a number from 1 to 65535";
                return -1;
            }
        }
        (void)snprintf(u->auth, sizeof u->auth, "%s%s%s", host, *port ? ":" : "", port);
        (void)snprintf(u->path, sizeof u->path, "%s", rest + alen);
        if (u->path[0] != '/') {
            memmove(u->path + 1, u->path, strlen(u->path) + 1);
            u->path[0] = '/';
        }
    }
    return 0;
}

static void wf_str(const wf_url *u, char *out, size_t cap) {
    (void)snprintf(out, cap, "%s://%s%s", u->scheme, u->auth, u->path);
}

/* Removes "." and ".." segments from PATH (which begins with '/'); a query is kept as it is. */
static void wf_dots(char *path) {
    char *q = strchr(path, '?'), *out = path, *in = path, tail[WF_URL_MAX];
    tail[0] = '\0';
    if (q) {
        (void)snprintf(tail, sizeof tail, "%s", q);
        *q = '\0';
    }
    while (*in) {
        char *end = strchr(in + 1, '/');
        size_t seg = end ? (size_t)(end - in) : strlen(in); /* "/name" */
        if (seg == 2 && in[1] == '.') {
            in += seg;
            if (!*in) {
                *out++ = '/';
            }
        } else if (seg == 3 && in[1] == '.' && in[2] == '.') {
            while (out > path && out[-1] != '/') {
                out--;
            }
            if (out > path) {
                out--;
            }
            in += seg;
            if (!*in) {
                *out++ = '/';
            }
        } else {
            memmove(out, in, seg);
            out += seg;
            in += seg;
        }
    }
    *out = '\0';
    if (out == path) {
        strcpy(path, "/");
    }
    (void)snprintf(path + strlen(path), WF_URL_MAX - strlen(path), "%s", tail);
}

/* REF against BASE, as a URL a browser would follow: absolute, "//host", "/path", "?query",
 * "name". Fills OUT; 0, or -1 when REF is not an http(s) URL. */
static int wf_resolve_ref(const wf_url *base, const char *ref, wf_url *out, const char **why) {
    char tmp[WF_URL_MAX], clean[WF_URL_MAX];
    size_t schemelen;
    if (wf_clean_url(ref, clean, sizeof clean) != 0) {
        *why = "the redirect's address has a space or control character, or is too long";
        return -1;
    }
    ref = clean;
    schemelen = strcspn(ref, ":/?#");
    if (ref[schemelen] == ':' && schemelen > 0) {
        return wf_parse(ref, out, why); /* has a scheme; wf_parse accepts only http and https */
    }
    if (ref[0] == '/' && ref[1] == '/') {
        (void)snprintf(tmp, sizeof tmp, "%s:%s", base->scheme, ref);
        return wf_parse(tmp, out, why);
    }
    *out = *base;
    if (ref[0] == '\0') {
        return 0;
    }
    if (ref[0] == '/') {
        (void)snprintf(out->path, sizeof out->path, "%s", ref);
    } else if (ref[0] == '?') {
        char *q = strchr(out->path, '?');
        if (q) {
            *q = '\0';
        }
        (void)snprintf(out->path + strlen(out->path), sizeof out->path - strlen(out->path), "%s", ref);
    } else {
        char *q = strchr(out->path, '?'), *slash;
        if (q) {
            *q = '\0';
        }
        slash = strrchr(out->path, '/');
        slash[1] = '\0';
        (void)snprintf(out->path + strlen(out->path), sizeof out->path - strlen(out->path), "%s", ref);
    }
    wf_dots(out->path);
    return 0;
}

/* htmltext's resolve: a page's link made absolute against the page's URL. */
static char *wf_link(void *ctx, const char *href) {
    const wf_url *base = ctx;
    wf_url u;
    const char *why;
    char full[WF_URL_MAX + 400];
    if (wf_resolve_ref(base, href, &u, &why) != 0) {
        return NULL; /* some other scheme (ftp:, a data: image): as written */
    }
    wf_str(&u, full, sizeof full);
    return strdup(full);
}

/* ---- the response ------------------------------------------------------------------------ */

enum { K_UNKNOWN, K_HTML, K_TEXT, K_BINARY };

typedef struct {
    char *p;
    size_t len, cap;
    int status, kind, redirect, oom;
    char ctype[128], location[2048];
    unsigned long long clen;
    int has_clen;
    char *stop; /* why the response was stopped (malloc'd), or NULL */
} wf_resp;

static int wf_ends(const char *s, const char *suffix) {
    size_t a = strlen(s), b = strlen(suffix);
    return a >= b && strcasecmp(s + a - b, suffix) == 0;
}

/* What kind of content a Content-Type names. */
static int wf_kind(const char *ctype) {
    char t[128];
    size_t n = strcspn(ctype, "; \t");
    if (n == 0) {
        return K_UNKNOWN;
    }
    (void)snprintf(t, sizeof t, "%.*s", (int)n, ctype);
    if (strcasecmp(t, "text/html") == 0 || strcasecmp(t, "application/xhtml+xml") == 0) {
        return K_HTML;
    }
    if (strncasecmp(t, "text/", 5) == 0 || strcasecmp(t, "application/json") == 0 || strcasecmp(t, "application/xml") == 0 ||
        strcasecmp(t, "application/javascript") == 0 || strcasecmp(t, "application/x-javascript") == 0 ||
        strcasecmp(t, "application/ecmascript") == 0 || strcasecmp(t, "application/yaml") == 0 ||
        strcasecmp(t, "application/x-yaml") == 0 || strcasecmp(t, "application/toml") == 0 ||
        strcasecmp(t, "application/x-ndjson") == 0 || strcasecmp(t, "application/x-www-form-urlencoded") == 0 ||
        wf_ends(t, "+json") || wf_ends(t, "+xml")) {
        return K_TEXT;
    }
    return K_BINARY;
}

static char *wf_stop(const char *fmt, ...) {
    va_list ap;
    char tmp[600];
    va_start(ap, fmt);
    (void)vsnprintf(tmp, sizeof tmp, fmt, ap);
    va_end(ap);
    return strdup(tmp);
}

static char *wf_binary_msg(const wf_resp *r, int sized, unsigned long long size) {
    char sz[48];
    if (sized) {
        (void)snprintf(sz, sizeof sz, "%llu bytes", size);
    } else {
        (void)snprintf(sz, sizeof sz, "unknown size");
    }
    return wf_stop("it is binary content (%s, %s); only text, HTML and JSON are fetched",
                   r->ctype[0] ? r->ctype : "no content type", sz);
}

static int wf_on_head(void *ctx, const pic_http_resp *h) {
    wf_resp *r = ctx;
    r->status = h->status;
    (void)snprintf(r->ctype, sizeof r->ctype, "%s", h->content_type);
    r->has_clen = h->has_length;
    r->clen = h->has_length ? h->remaining : 0;
    if (h->status == 301 || h->status == 302 || h->status == 303 || h->status == 307 || h->status == 308) {
        if (h->wanted[0]) {
            r->redirect = 1;
            (void)snprintf(r->location, sizeof r->location, "%s", h->wanted);
            return 1;
        }
    }
    r->kind = wf_kind(h->content_type);
    if (r->kind == K_BINARY && h->status < 400) {
        r->stop = wf_binary_msg(r, r->has_clen, r->clen);
        return 1;
    }
    if (r->has_clen && r->clen > WF_MAX_BODY) {
        r->stop = wf_stop("the page is %llu bytes, over the 5 MB limit", r->clen);
        return 1;
    }
    return 0;
}

static int wf_on_body(void *ctx, const char *bytes, size_t n) {
    wf_resp *r = ctx;
    if (r->len + n > WF_MAX_BODY) {
        r->stop = wf_stop("the page is over the 5 MB limit");
        return 1;
    }
    if (r->len + n + 1 > r->cap) {
        size_t cap = r->cap ? r->cap : 16384;
        char *q;
        while (cap < r->len + n + 1) {
            cap *= 2;
        }
        if (!(q = realloc(r->p, cap))) {
            r->oom = 1;
            return 1;
        }
        r->p = q;
        r->cap = cap;
    }
    memcpy(r->p + r->len, bytes, n);
    r->len += n;
    r->p[r->len] = '\0';
    return 0;
}

/* ---- text -------------------------------------------------------------------------------- */

/* Windows-1252 for the bytes 0x80-0x9f (ISO-8859-1 has controls there; every page that says it is
 * Latin-1 means this): the code point, or 0 for the five it leaves undefined. */
static const unsigned short wf_cp1252[32] = {
    0x20ac, 0, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0, 0x017d, 0,
    0,      0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0, 0x017e, 0x0178};

/* IN as valid UTF-8 without NULs or bare CRs (malloc'd, *LEN set); LATIN1: its bytes are
 * ISO-8859-1. */
static char *wf_utf8(const char *in, size_t n, int latin1, size_t *len) {
    char *out = malloc(n * 3 + 1);
    size_t o = 0;
    if (!out) {
        return NULL;
    }
    for (size_t i = 0; i < n;) {
        unsigned char c = (unsigned char)in[i];
        size_t need = c < 0x80 ? 1 : (c >= 0xc2 && c <= 0xdf) ? 2 : (c >= 0xe0 && c <= 0xef) ? 3 : (c >= 0xf0 && c <= 0xf4) ? 4 : 0;
        int ok = need > 0 && i + need <= n;
        if (latin1 && c >= 0x80) {
            unsigned cp = c >= 0xa0 ? c : wf_cp1252[c - 0x80];
            if (cp >= 0x800) {
                out[o++] = (char)(0xe0 | (cp >> 12));
                out[o++] = (char)(0x80 | ((cp >> 6) & 0x3f));
                out[o++] = (char)(0x80 | (cp & 0x3f));
            } else if (cp != 0) {
                out[o++] = (char)(0xc0 | (cp >> 6));
                out[o++] = (char)(0x80 | (cp & 0x3f));
            }
            i++;
            continue;
        }
        for (size_t k = 1; ok && k < need; k++) {
            ok = ((unsigned char)in[i + k] & 0xc0) == 0x80;
        }
        if (ok && need == 3) {
            unsigned char c1 = (unsigned char)in[i + 1];
            ok = !(c == 0xe0 && c1 < 0xa0) && !(c == 0xed && c1 >= 0xa0);
        } else if (ok && need == 4) {
            unsigned char c1 = (unsigned char)in[i + 1];
            ok = !(c == 0xf0 && c1 < 0x90) && !(c == 0xf4 && c1 >= 0x90);
        }
        if (!ok) {
            memcpy(out + o, "\xef\xbf\xbd", 3);
            o += 3;
            i++;
            continue;
        }
        if (c == 0 || (c < 0x20 && c != '\n' && c != '\t' && c != '\r') || c == 0x7f) {
            i++;
            continue;
        }
        if (c == 0xc2 && (unsigned char)in[i + 1] >= 0x80 && (unsigned char)in[i + 1] <= 0x9f) {
            i += 2; /* a C1 control: U+0080 to U+009F */
            continue;
        }
        if (c == '\r') {
            out[o++] = '\n';
            i += i + 1 < n && in[i + 1] == '\n' ? 2 : 1;
            continue;
        }
        memcpy(out + o, in + i, need);
        o += need;
        i += need;
    }
    out[o] = '\0';
    *len = o;
    return out;
}

/* The byte offset after the first MAX characters of S, and the number of characters in all. */
static size_t wf_cut(const char *s, size_t n, size_t max, size_t *chars) {
    size_t seen = 0, at = n;
    for (size_t i = 0; i < n; i++) {
        if (((unsigned char)s[i] & 0xc0) != 0x80) {
            if (seen == max) {
                at = i;
            }
            seen++;
        }
    }
    *chars = seen;
    return at;
}

/* ---- the call ---------------------------------------------------------------------------- */

static unsigned long long wf_now_ms(void) {
    struct timespec t;
    (void)clock_gettime(CLOCK_MONOTONIC, &t);
    return (unsigned long long)t.tv_sec * 1000u + (unsigned long long)t.tv_nsec / 1000000u;
}

static char *wf_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
                    const pic_tool_hooks *h, int *is_error) {
    const char *input = h->input && *h->input ? h->input : "{}", *why = NULL;
    char *urlv = NULL, *maxv = NULL, *type = NULL, *result = NULL, neterr[256] = "", shown[WF_URL_MAX + 400];
    char err[300];
    wf_url cur;
    wf_resp r;
    pic_net *net = NULL;
    long max_chars = WF_DEFAULT_CHARS;
    int deadline_s = WF_DEADLINE, loopback = 0, hops = 0, redirected = 0;
    unsigned long long t0, elapsed;
    (void)state;
    (void)workspace;
    (void)tool;
    *is_error = 0;
    memset(&r, 0, sizeof r);
    if (h->started == NULL || h->started(h->ctx, NULL, 0) != 0) {
        return NULL;
    }
    if (args->bad_input) {
        return wf_fmt(is_error, "web_fetch: %s", args->bad_input);
    }
    if (pic_offline()) {
        return wf_fmt(is_error, "web_fetch: offline is on, so nothing was fetched (turn it off with pic settings --unset offline)");
    }
    type = wf_json("SELECT json_valid(?1) || json_type(?1)", input);
    if (!type || strcmp(type, "1object") != 0) {
        free(type);
        return wf_fmt(is_error, "web_fetch: the input is not a JSON object");
    }
    free(type);
    type = wf_json("SELECT json_type(?1, '$.url')", input);
    urlv = type && strcmp(type, "text") == 0 ? wf_json("SELECT json_extract(?1, '$.url')", input) : NULL;
    free(type);
    if (!urlv || !*urlv) {
        free(urlv);
        return wf_fmt(is_error, "web_fetch: url is required, a string beginning http:// or https://");
    }
    type = wf_json("SELECT json_type(?1, '$.max_chars')", input);
    if (type) {
        if (strcmp(type, "integer") == 0 || strcmp(type, "real") == 0) {
            maxv = wf_json("SELECT cast(json_extract(?1, '$.max_chars') as integer)", input);
            max_chars = maxv ? strtol(maxv, NULL, 10) : 0;
        } else {
            max_chars = 0;
        }
        free(type);
        free(maxv);
        if (max_chars < 1) {
            free(urlv);
            return wf_fmt(is_error, "web_fetch: max_chars must be a whole number from 1 to %d", WF_MAX_CHARS);
        }
        if (max_chars > WF_MAX_CHARS) {
            max_chars = WF_MAX_CHARS;
        }
    }
    if (wf_parse(urlv, &cur, &why) != 0) {
        result = wf_fmt(is_error, "web_fetch: %s", why);
        free(urlv);
        return result;
    }
    free(urlv);
#ifdef PIC_FAULTS
    {
        const char *lp = getenv("PIC_TEST_WEB_LOOPBACK"), *dl = getenv("PIC_TEST_WEB_DEADLINE");
        loopback = lp ? atoi(lp) : 0;
        deadline_s = dl && atoi(dl) > 0 ? atoi(dl) : WF_DEADLINE;
    }
#endif
    net = pic_net_new(neterr, sizeof neterr);
    if (!net) {
        return wf_fmt(is_error, "web_fetch: cannot start the network: %s", neterr);
    }
    pic_net_web(net, 1, loopback);
    t0 = wf_now_ms();
    for (;;) {
        pic_http_resp hr;
        const char *const hdrs[] = {"User-Agent: pic", "Accept: text/html,text/markdown,text/plain,application/json;q=0.9,*/*;q=0.1"};
        int left, rc;
        wf_str(&cur, shown, sizeof shown);
        elapsed = wf_now_ms() - t0;
        if (elapsed >= (unsigned long long)deadline_s * 1000u) {
            result = wf_fmt(is_error, "web_fetch: %s took longer than the %d second deadline", shown, deadline_s);
            goto out;
        }
        left = (int)(((unsigned long long)deadline_s * 1000u - elapsed + 999u) / 1000u);
        free(r.p);
        free(r.stop);
        memset(&r, 0, sizeof r);
        pic_http_resp_init(&hr, wf_on_body, &r);
        hr.on_head = wf_on_head;
        hr.want = "Location";
        err[0] = '\0';
        rc = pic_http_get(net, shown, hdrs, 2, &hr, left, left, err, sizeof err);
        if (r.oom) {
            result = wf_fmt(is_error, "web_fetch: out of memory");
            goto out;
        }
        if (r.redirect) {
            wf_url next;
            if (hops >= WF_REDIRECTS) {
                result = wf_fmt(is_error, "web_fetch: too many redirects (more than %d) from %s", WF_REDIRECTS, shown);
                goto out;
            }
            if (wf_resolve_ref(&cur, r.location, &next, &why) != 0) {
                result = wf_fmt(is_error, "web_fetch: %s redirected somewhere that is not fetched: %s", shown,
                                strstr(why, "only http") ? "only http and https URLs can be fetched" : why);
                goto out;
            }
            cur = next;
            hops++;
            redirected = 1;
            continue;
        }
        if (r.stop) {
            result = wf_fmt(is_error, "web_fetch: refused %s: %s", shown, r.stop);
            goto out;
        }
        if (rc != 0) {
            if (pic_net_refused(net)) {
                result = wf_fmt(is_error, "web_fetch: refused %s: %s", shown, err);
            } else {
                result = wf_fmt(is_error, "web_fetch: could not fetch %s: %s", shown, err);
            }
            goto out;
        }
        break;
    }
    {
        char *clean, *text = NULL, *note = NULL;
        size_t clen_, tlen, chars, at;
        int kind = r.kind, latin1 = 0;
        const char *cs = r.ctype;
        while (*cs && strncasecmp(cs, "charset=", 8) != 0) {
            cs++;
        }
        if (*cs) {
            cs += 8;
            latin1 = strncasecmp(cs, "iso-8859-1", 10) == 0 || strncasecmp(cs, "latin1", 6) == 0 ||
                     strncasecmp(cs, "windows-1252", 12) == 0;
        }
        if (kind == K_BINARY) { /* an error page of a binary type: only its status is of use */
            result = wf_fmt(is_error, "web_fetch: %s answered HTTP %d", shown, r.status);
            goto out;
        }
        if (kind == K_UNKNOWN) {
            size_t probe = r.len < 1024 ? r.len : 1024;
            kind = r.p && memchr(r.p, '\0', probe) ? K_BINARY : K_TEXT;
            if (kind == K_TEXT && r.p) {
                const char *p = r.p;
                while (*p && isspace((unsigned char)*p)) {
                    p++;
                }
                if (strncasecmp(p, "<!doctype html", 14) == 0 || strncasecmp(p, "<html", 5) == 0) {
                    kind = K_HTML;
                }
            }
        }
        if (kind == K_BINARY) {
            char *m = wf_binary_msg(&r, 1, r.len);
            result = wf_fmt(is_error, "web_fetch: refused %s: %s", shown, m);
            free(m);
            goto out;
        }
        clean = wf_utf8(r.p ? r.p : "", r.len, latin1, &clen_);
        if (!clean) {
            result = wf_fmt(is_error, "web_fetch: out of memory");
            goto out;
        }
        if (kind == K_HTML) {
            text = pic_html_to_text(clean, clen_, wf_link, &cur);
            free(clean);
        } else {
            text = clean;
        }
        if (!text) {
            result = wf_fmt(is_error, "web_fetch: out of memory");
            goto out;
        }
        tlen = strlen(text);
        if (r.status >= 400) {
            size_t c2, ex = wf_cut(text, tlen, 1000, &c2);
            result = wf_fmt(is_error, "web_fetch: %s answered HTTP %d%s%.*s", shown, r.status, tlen ? "\n\n" : "", (int)ex, text);
            free(text);
            goto out;
        }
        at = wf_cut(text, tlen, (size_t)max_chars, &chars);
        if (at < tlen) {
            char where[160];
            if (h->output && h->output_name && (h->output->data = strdup(text))) {
                h->output->len = tlen;
                (void)snprintf(where, sizeof where, "Full output: %s (read it with the read tool, with offset and limit)",
                               h->output_name);
            } else {
                (void)snprintf(where, sizeof where, "Ask again with a larger max_chars (at most %d) for more", WF_MAX_CHARS);
            }
            note = wf_fmt(is_error, "\n\n[Showing the first %ld of %zu characters. %s]", max_chars, chars, where);
            *is_error = 0;
        }
        {
            size_t cap = at + (note ? strlen(note) : 0) + strlen(shown) + 64;
            char *res = malloc(cap);
            if (res) {
                int w = 0;
                if (redirected) {
                    w = snprintf(res, cap, "Redirected to: %s\n\n", shown);
                }
                memcpy(res + w, text, at);
                res[w + (int)at] = '\0';
                if (note) {
                    strcat(res, note);
                }
                if (w == 0 && at == 0 && !note) {
                    (void)snprintf(res, cap, "(the page is empty)");
                }
            }
            result = res;
        }
        free(text);
        free(note);
    }
out:
    free(r.p);
    free(r.stop);
    if (net) {
        pic_net_free(net);
    }
    return result;
}

static int wf_on(void) { return 1; }

/* A GET: the same call run again has the same effect, so a replay after a crash is safe. */
const pic_tool_def pic_webfetch_tool = {"web_fetch", wf_schema, 1, 0, PIC_TIER_BUNDLED, 1, wf_on, wf_run, NULL};