| 1 | /* |
| 2 | * ws_providers.c - the six search backends and their result normalisation. |
| 3 | * |
| 4 | * Every provider returns the same shape, so the agent and the page never see |
| 5 | * provider-specific field names: |
| 6 | * |
| 7 | * {title, url, snippet, published, site} |
| 8 | * |
| 9 | * The five keyed providers are plain JSON calls (Brave GET, Tavily POST, Exa |
| 10 | * POST, Perplexity POST, SearXNG GET ?format=json). DuckDuckGo has no API, so |
| 11 | * its HTML page is parsed — and that parser is the only place in this plugin |
| 12 | * where markup is trusted to be well-formed: every buffer it fills is bounded |
| 13 | * and every string it copies goes through the JSON escaper on output. |
| 14 | * |
| 15 | * Provider ids are stable strings ("duckduckgo", "searxng", "brave", "tavily", |
| 16 | * "exa", "perplexity") because they are MCP tool arguments and config values. |
| 17 | * |
| 18 | * Two rules the code enforces rather than documents: |
| 19 | * 1. A secret never leaves this file. `ws_provider_has_key()` is the only way |
| 20 | * the rest of the plugin learns about a key, and it answers a boolean. |
| 21 | * 2. An upstream error is reported with the provider's own message and its |
| 22 | * HTTP status. Swallowing a 401 into "no results" makes a wrong key look |
| 23 | * like a working query with nothing to say. |
| 24 | * |
| 25 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 26 | */ |
| 27 | |
| 28 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 29 | # define _WIN32_WINNT 0x0601 |
| 30 | #endif |
| 31 | #if !defined(_WIN32) |
| 32 | # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L |
| 33 | # undef _POSIX_C_SOURCE |
| 34 | # define _POSIX_C_SOURCE 200809L |
| 35 | # endif |
| 36 | # ifndef _DEFAULT_SOURCE |
| 37 | # define _DEFAULT_SOURCE 1 |
| 38 | # endif |
| 39 | #endif |
| 40 | |
| 41 | #include "ws.h" |
| 42 | #include "sx_http_tls.h" |
| 43 | |
| 44 | #include <ctype.h> |
| 45 | #include <stdio.h> |
| 46 | #include <stdlib.h> |
| 47 | #include <string.h> |
| 48 | #include <time.h> |
| 49 | |
| 50 | const ws_provider_info WS_PROVIDERS[WS_PROVIDER_COUNT] = { |
| 51 | { "duckduckgo", "DuckDuckGo", "No key needed", "https://duckduckgo.com/", 0, 0 }, |
| 52 | { "searxng", "SearXNG", "Self-hosted", "https://docs.searxng.org/", 0, 1 }, |
| 53 | { "brave", "Brave", "Structured API", "https://brave.com/search/api/", 1, 0 }, |
| 54 | { "tavily", "Tavily", "Agent-optimised", "https://tavily.com/", 1, 0 }, |
| 55 | { "exa", "Exa", "Neural search", "https://exa.ai/", 1, 0 }, |
| 56 | { "perplexity", "Perplexity", "Answer + sources", "https://perplexity.ai/", 1, 0 } |
| 57 | }; |
| 58 | |
| 59 | int ws_provider_known(const char *id) |
| 60 | { |
| 61 | int i; |
| 62 | if (!id || !*id) return 0; |
| 63 | for (i = 0; i < WS_PROVIDER_COUNT; i++) |
| 64 | if (ws_ieq(id, WS_PROVIDERS[i].id)) return 1; |
| 65 | return 0; |
| 66 | } |
| 67 | |
| 68 | const char *ws_provider_active(const ws_config *cfg) |
| 69 | { |
| 70 | if (cfg && cfg->active[0] && ws_provider_known(cfg->active)) return cfg->active; |
| 71 | return "duckduckgo"; |
| 72 | } |
| 73 | |
| 74 | int ws_provider_has_key(const ws_config *cfg, const char *id) |
| 75 | { |
| 76 | if (!cfg || !id) return 0; |
| 77 | if (ws_ieq(id, "brave")) return cfg->brave_key[0] ? 1 : 0; |
| 78 | if (ws_ieq(id, "tavily")) return cfg->tavily_key[0] ? 1 : 0; |
| 79 | if (ws_ieq(id, "exa")) return cfg->exa_key[0] ? 1 : 0; |
| 80 | if (ws_ieq(id, "perplexity")) return cfg->pplx_key[0] ? 1 : 0; |
| 81 | return 0; |
| 82 | } |
| 83 | |
| 84 | int ws_provider_ready(const ws_config *cfg, const char *id) |
| 85 | { |
| 86 | if (!cfg || !id) return 0; |
| 87 | if (ws_ieq(id, "duckduckgo")) return 1; |
| 88 | if (ws_ieq(id, "searxng")) return cfg->searxng_base[0] ? 1 : 0; |
| 89 | if (ws_ieq(id, "brave")) return cfg->brave_key[0] ? 1 : 0; |
| 90 | if (ws_ieq(id, "tavily")) return cfg->tavily_key[0] ? 1 : 0; |
| 91 | if (ws_ieq(id, "exa")) return cfg->exa_key[0] ? 1 : 0; |
| 92 | if (ws_ieq(id, "perplexity")) return cfg->pplx_key[0] ? 1 : 0; |
| 93 | return 0; |
| 94 | } |
| 95 | |
| 96 | /* ------------------------------------------------------------- results bag */ |
| 97 | |
| 98 | void ws_results_init(ws_results *r) |
| 99 | { |
| 100 | memset(r, 0, sizeof *r); |
| 101 | ws_buf_init(&r->answer); |
| 102 | ws_buf_init(&r->citations); |
| 103 | } |
| 104 | |
| 105 | void ws_results_free(ws_results *r) |
| 106 | { |
| 107 | if (!r) return; |
| 108 | free(r->items); |
| 109 | r->items = NULL; |
| 110 | r->n = r->cap = 0; |
| 111 | ws_buf_free(&r->answer); |
| 112 | ws_buf_free(&r->citations); |
| 113 | } |
| 114 | |
| 115 | ws_result *ws_results_push(ws_results *r) |
| 116 | { |
| 117 | if (r->n >= r->cap) { |
| 118 | int want = r->cap ? r->cap * 2 : 8; |
| 119 | ws_result *np = (ws_result *)realloc(r->items, (size_t)want * sizeof *np); |
| 120 | if (!np) return NULL; |
| 121 | r->items = np; |
| 122 | r->cap = want; |
| 123 | } |
| 124 | memset(&r->items[r->n], 0, sizeof r->items[r->n]); |
| 125 | return &r->items[r->n++]; |
| 126 | } |
| 127 | |
| 128 | /* Host part of a URL, for the "site" field. Never returns a credential. */ |
| 129 | static void site_of(const char *url, char *out, size_t capsz) |
| 130 | { |
| 131 | const char *p = url; |
| 132 | const char *e; |
| 133 | |
| 134 | out[0] = '\0'; |
| 135 | if (!url || !*url) return; |
| 136 | if (ws_iprefix(p, "https://")) p += 8; |
| 137 | else if (ws_iprefix(p, "http://")) p += 7; |
| 138 | e = p; |
| 139 | while (*e && *e != '/' && *e != '?' && *e != '#') e++; |
| 140 | if (e == p) return; |
| 141 | if ((size_t)(e - p) >= capsz) e = p + capsz - 1; |
| 142 | memcpy(out, p, (size_t)(e - p)); |
| 143 | out[e - p] = '\0'; |
| 144 | } |
| 145 | |
| 146 | static void fill_result(ws_result *it, const char *title, const char *url, |
| 147 | const char *snippet, const char *published) |
| 148 | { |
| 149 | char tmp[4096]; |
| 150 | |
| 151 | ws_html_text(tmp, sizeof tmp, title ? title : ""); |
| 152 | ws_copy(it->title, sizeof it->title, tmp); |
| 153 | ws_copy(it->url, sizeof it->url, url ? url : ""); |
| 154 | ws_html_text(tmp, sizeof tmp, snippet ? snippet : ""); |
| 155 | ws_copy(it->snippet, sizeof it->snippet, tmp); |
| 156 | ws_copy(it->published, sizeof it->published, published ? published : ""); |
| 157 | site_of(it->url, it->site, sizeof it->site); |
| 158 | } |
| 159 | |
| 160 | /* ------------------------------------------------------------- helpers */ |
| 161 | |
| 162 | static const char *jstr(yyjson_val *o, const char *key) |
| 163 | { |
| 164 | yyjson_val *v; |
| 165 | if (!o || !yyjson_is_obj(o)) return NULL; |
| 166 | v = yyjson_obj_get(o, key); |
| 167 | return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; |
| 168 | } |
| 169 | |
| 170 | static yyjson_val *jobj(yyjson_val *o, const char *key) |
| 171 | { |
| 172 | yyjson_val *v; |
| 173 | if (!o || !yyjson_is_obj(o)) return NULL; |
| 174 | v = yyjson_obj_get(o, key); |
| 175 | return (v && yyjson_is_obj(v)) ? v : NULL; |
| 176 | } |
| 177 | |
| 178 | static yyjson_val *jarr(yyjson_val *o, const char *key) |
| 179 | { |
| 180 | yyjson_val *v; |
| 181 | if (!o || !yyjson_is_obj(o)) return NULL; |
| 182 | v = yyjson_obj_get(o, key); |
| 183 | return (v && yyjson_is_arr(v)) ? v : NULL; |
| 184 | } |
| 185 | |
| 186 | /* Trim a base URL's trailing slashes so joining a path is predictable. */ |
| 187 | static void base_trim(char *out, size_t capsz, const char *base) |
| 188 | { |
| 189 | size_t n; |
| 190 | ws_copy(out, capsz, base); |
| 191 | n = strlen(out); |
| 192 | while (n > 0 && out[n - 1] == '/') out[--n] = '\0'; |
| 193 | } |
| 194 | |
| 195 | /* Upstream error text: the provider's own `error`/`message`/`detail` field |
| 196 | * when the body parses, the first 300 bytes of the body otherwise. The body is |
| 197 | * never echoed wholesale — a provider error page can be a whole HTML document. */ |
| 198 | static void upstream_error(ws_resp *r, const char *provider, char *err, |
| 199 | size_t errsz) |
| 200 | { |
| 201 | char detail[320]; |
| 202 | yyjson_doc *doc = NULL; |
| 203 | |
| 204 | detail[0] = '\0'; |
| 205 | if (r->body && r->body_len) { |
| 206 | doc = yyjson_read(r->body, r->body_len, 0); |
| 207 | if (doc) { |
| 208 | yyjson_val *root = yyjson_doc_get_root(doc); |
| 209 | const char *m = jstr(root, "message"); |
| 210 | if (!m) m = jstr(root, "error"); |
| 211 | if (!m) m = jstr(root, "detail"); |
| 212 | if (!m) { |
| 213 | yyjson_val *e = yyjson_obj_get(root, "error"); |
| 214 | /* some providers nest {"error":{"message":"..."}} */ |
| 215 | if (e && yyjson_is_obj(e)) m = jstr(e, "message"); |
| 216 | } |
| 217 | if (m) ws_copy(detail, sizeof detail, m); |
| 218 | yyjson_doc_free(doc); |
| 219 | } |
| 220 | } |
| 221 | if (!detail[0] && r->body && r->body_len) { |
| 222 | char tmp[321]; |
| 223 | size_t n = r->body_len < 300 ? r->body_len : 300; |
| 224 | char stripped[321]; |
| 225 | memcpy(tmp, r->body, n); |
| 226 | tmp[n] = '\0'; |
| 227 | ws_html_text(stripped, sizeof stripped, tmp); |
| 228 | ws_copy(detail, sizeof detail, stripped); |
| 229 | } |
| 230 | snprintf(err, errsz, "%s returned HTTP %ld%s%s", provider, r->status, |
| 231 | detail[0] ? ": " : "", detail); |
| 232 | } |
| 233 | |
| 234 | static int parse_json(ws_resp *r, yyjson_doc **out, const char *provider, |
| 235 | char *err, size_t errsz) |
| 236 | { |
| 237 | *out = NULL; |
| 238 | if (!r->body || !r->body_len) { |
| 239 | snprintf(err, errsz, "%s returned an empty response", provider); |
| 240 | return -1; |
| 241 | } |
| 242 | *out = yyjson_read(r->body, r->body_len, 0); |
| 243 | if (!*out) { |
| 244 | snprintf(err, errsz, "%s returned a body that is not JSON", provider); |
| 245 | return -1; |
| 246 | } |
| 247 | return 0; |
| 248 | } |
| 249 | |
| 250 | /* ------------------------------------------------------------- DuckDuckGo */ |
| 251 | |
| 252 | /* Finds the next `<a ... class="...<needle>...">inner</a>` at or after `from`. |
| 253 | * Returns 1 and fills href/inner, or 0. Done by hand rather than with a regex |
| 254 | * because C99 has none and because every offset here is bounded by hlen. */ |
| 255 | static int next_anchor(const char *hay, size_t hlen, size_t from, |
| 256 | const char *needle, |
| 257 | char *href, size_t hrefcap, |
| 258 | const char **inner, size_t *inner_len) |
| 259 | { |
| 260 | size_t i = from; |
| 261 | |
| 262 | while (i + 2 < hlen) { |
| 263 | const char *tag, *close, *attr, *ih; |
| 264 | size_t tag_end, attr_len; |
| 265 | |
| 266 | tag = ws_memmem(hay + i, hlen - i, "<a"); |
| 267 | if (!tag) return 0; |
| 268 | i = (size_t)(tag - hay); |
| 269 | close = memchr(tag, '>', hlen - i); |
| 270 | if (!close) return 0; |
| 271 | tag_end = (size_t)(close - hay); |
| 272 | attr = tag; |
| 273 | attr_len = tag_end - i + 1; |
| 274 | |
| 275 | /* Match `class="…needle…"` inside the tag only. */ |
| 276 | { |
| 277 | const char *cpos = ws_memmem(attr, attr_len, "class="); |
| 278 | int matched = 0; |
| 279 | if (cpos) { |
| 280 | const char *v = cpos + 6; |
| 281 | char quote = '"'; |
| 282 | const char *vend; |
| 283 | if (*v == '"' || *v == '\'') { quote = *v; v++; } |
| 284 | vend = memchr(v, quote, (size_t)(attr + attr_len - v)); |
| 285 | if (!vend) vend = attr + attr_len; |
| 286 | if (ws_memmem(v, (size_t)(vend - v), needle)) |
| 287 | matched = 1; |
| 288 | } |
| 289 | if (!matched) { i = tag_end + 1; continue; } |
| 290 | } |
| 291 | |
| 292 | ih = ws_memmem(attr, attr_len, "href="); |
| 293 | if (href && hrefcap) { |
| 294 | href[0] = '\0'; |
| 295 | if (ih) { |
| 296 | const char *v = ih + 5; |
| 297 | char quote = '"'; |
| 298 | const char *vend; |
| 299 | if (*v == '"' || *v == '\'') { quote = *v; v++; } |
| 300 | vend = memchr(v, quote, (size_t)(attr + attr_len - v)); |
| 301 | if (vend) { |
| 302 | size_t n = (size_t)(vend - v); |
| 303 | if (n >= hrefcap) n = hrefcap - 1; |
| 304 | memcpy(href, v, n); |
| 305 | href[n] = '\0'; |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | { |
| 310 | const char *istart = hay + tag_end + 1; |
| 311 | const char *iend = ws_memmem(istart, hlen - (size_t)(istart - hay), "</a"); |
| 312 | if (!iend) return 0; |
| 313 | if (inner) *inner = istart; |
| 314 | if (inner_len) *inner_len = (size_t)(iend - istart); |
| 315 | } |
| 316 | return 1; |
| 317 | } |
| 318 | return 0; |
| 319 | } |
| 320 | |
| 321 | /* A DuckDuckGo result link is either direct or /l/?uddg=<encoded>. */ |
| 322 | static void ddg_real_url(char *out, size_t capsz, const char *href) |
| 323 | { |
| 324 | const char *u = href; |
| 325 | |
| 326 | out[0] = '\0'; |
| 327 | if (!href) return; |
| 328 | if (href[0] == '/' && href[1] == '/') { |
| 329 | /* "//host/path" — same scheme as the page we fetched it from. */ |
| 330 | char joined[2048]; |
| 331 | snprintf(joined, sizeof joined, "https:%.2030s", href); |
| 332 | ws_copy(out, capsz, joined); |
| 333 | return; |
| 334 | } |
| 335 | if (href[0] == '/') { |
| 336 | const char *uddg = strstr(href, "uddg="); |
| 337 | if (uddg) { |
| 338 | char enc[2048], dec[2048]; |
| 339 | const char *amp = strchr(uddg + 5, '&'); |
| 340 | size_t n = amp ? (size_t)(amp - (uddg + 5)) : strlen(uddg + 5); |
| 341 | if (n >= sizeof enc) n = sizeof enc - 1; |
| 342 | memcpy(enc, uddg + 5, n); |
| 343 | enc[n] = '\0'; |
| 344 | ws_url_decode(dec, sizeof dec, enc); |
| 345 | ws_copy(out, capsz, dec); |
| 346 | return; |
| 347 | } |
| 348 | ws_copy(out, capsz, href); |
| 349 | return; |
| 350 | } |
| 351 | ws_copy(out, capsz, u); |
| 352 | } |
| 353 | |
| 354 | static int search_duckduckgo(const ws_config *cfg, const char *query, int count, |
| 355 | const char *region, const char *safe, |
| 356 | ws_results *res, long *status_out, |
| 357 | char *err, size_t errsz) |
| 358 | { |
| 359 | static const char *const SAFE_PARAM_STRICT = "1"; |
| 360 | static const char *const SAFE_PARAM_MODERATE = "-1"; |
| 361 | static const char *const SAFE_PARAM_OFF = "-2"; |
| 362 | const char *sp = SAFE_PARAM_MODERATE; |
| 363 | char base[WS_URL_MAX], url[1200]; |
| 364 | char body[4096]; |
| 365 | ws_buf form; |
| 366 | ws_resp r; |
| 367 | size_t pos = 0; |
| 368 | int n = 0; |
| 369 | |
| 370 | if (safe && ws_ieq(safe, "strict")) sp = SAFE_PARAM_STRICT; |
| 371 | else if (safe && ws_ieq(safe, "off")) sp = SAFE_PARAM_OFF; |
| 372 | |
| 373 | base_trim(base, sizeof base, cfg->ddg_base[0] ? cfg->ddg_base : "https://html.duckduckgo.com"); |
| 374 | snprintf(url, sizeof url, "%s/html/", base); |
| 375 | |
| 376 | ws_buf_init(&form); |
| 377 | ws_buf_puts(&form, "q="); |
| 378 | ws_url_encode(query, &form); |
| 379 | if (region && *region) { |
| 380 | ws_buf_puts(&form, "&kl="); |
| 381 | ws_url_encode(region, &form); |
| 382 | } |
| 383 | ws_buf_puts(&form, "&kp="); |
| 384 | ws_buf_puts(&form, sp); |
| 385 | snprintf(body, sizeof body, "%s", ws_buf_str(&form)); |
| 386 | ws_buf_free(&form); |
| 387 | |
| 388 | /* POST, not GET: html.duckduckgo.com answers a bare GET with a bot |
| 389 | * challenge and the same query as a form post with a result page. */ |
| 390 | if (ws_http_do("POST", url, |
| 391 | "Content-Type: application/x-www-form-urlencoded\r\n" |
| 392 | "Accept: text/html\r\n" |
| 393 | "User-Agent: SCORPIOXBOT-websearch/" WS_VER |
| 394 | " (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-websearch)\r\n", |
| 395 | body, strlen(body), 25000, &r) != 0) { |
| 396 | ws_copy(err, errsz, r.error); |
| 397 | ws_resp_free(&r); |
| 398 | return -1; |
| 399 | } |
| 400 | if (status_out) *status_out = r.status; |
| 401 | if (!r.ok || r.status >= 400) { |
| 402 | upstream_error(&r, "DuckDuckGo", err, errsz); |
| 403 | ws_resp_free(&r); |
| 404 | return -1; |
| 405 | } |
| 406 | if (!r.body || !r.body_len) { |
| 407 | ws_copy(err, errsz, "DuckDuckGo returned an empty page"); |
| 408 | ws_resp_free(&r); |
| 409 | return -1; |
| 410 | } |
| 411 | |
| 412 | for (;;) { |
| 413 | char href[2048]; |
| 414 | const char *inner = NULL; |
| 415 | size_t inner_len = 0; |
| 416 | char title_html[2048], snippet_html[4096]; |
| 417 | char realurl[1024]; |
| 418 | ws_result *it; |
| 419 | |
| 420 | if (n >= count) break; |
| 421 | if (!next_anchor(r.body, r.body_len, pos, "result__a", href, sizeof href, |
| 422 | &inner, &inner_len)) |
| 423 | break; |
| 424 | /* Where the snippet starts: right after this anchor's </a>. */ |
| 425 | { |
| 426 | const char *after = ws_memmem(inner + inner_len, |
| 427 | r.body_len - (size_t)(inner + inner_len - r.body), |
| 428 | "</a"); |
| 429 | size_t next_from = after ? (size_t)(after - r.body) + 3 : r.body_len; |
| 430 | size_t nlen = inner_len < sizeof title_html - 1 ? inner_len : sizeof title_html - 1; |
| 431 | memcpy(title_html, inner, nlen); |
| 432 | title_html[nlen] = '\0'; |
| 433 | |
| 434 | snippet_html[0] = '\0'; |
| 435 | { |
| 436 | char shref[1024]; |
| 437 | const char *sinner = NULL; |
| 438 | size_t sinner_len = 0; |
| 439 | if (next_anchor(r.body, r.body_len, next_from, "result__snippet", |
| 440 | shref, sizeof shref, &sinner, &sinner_len)) { |
| 441 | size_t sl = sinner_len < sizeof snippet_html - 1 |
| 442 | ? sinner_len : sizeof snippet_html - 1; |
| 443 | memcpy(snippet_html, sinner, sl); |
| 444 | snippet_html[sl] = '\0'; |
| 445 | } |
| 446 | } |
| 447 | pos = next_from; |
| 448 | } |
| 449 | |
| 450 | ddg_real_url(realurl, sizeof realurl, href); |
| 451 | if (!realurl[0] && !title_html[0]) continue; |
| 452 | it = ws_results_push(res); |
| 453 | if (!it) { |
| 454 | ws_copy(err, errsz, "out of memory"); |
| 455 | ws_resp_free(&r); |
| 456 | return -1; |
| 457 | } |
| 458 | fill_result(it, title_html, realurl, snippet_html, ""); |
| 459 | n++; |
| 460 | } |
| 461 | |
| 462 | if (n == 0 && |
| 463 | (strstr(r.body, "anomaly-modal") || strstr(r.body, "challenge-form") || |
| 464 | strstr(r.body, "g-recaptcha"))) { |
| 465 | ws_copy(err, errsz, |
| 466 | "DuckDuckGo returned a bot-detection challenge instead of results. " |
| 467 | "Retry later, or configure a keyed provider (Brave, Tavily, Exa, " |
| 468 | "Perplexity) or your own SearXNG base URL."); |
| 469 | ws_resp_free(&r); |
| 470 | return -1; |
| 471 | } |
| 472 | ws_resp_free(&r); |
| 473 | return 0; |
| 474 | } |
| 475 | |
| 476 | /* ---------------------------------------------------------------- SearXNG */ |
| 477 | |
| 478 | static int search_searxng(const ws_config *cfg, const char *query, int count, |
| 479 | const char *language, const char *safe, |
| 480 | ws_results *res, long *status_out, |
| 481 | char *err, size_t errsz) |
| 482 | { |
| 483 | char base[WS_URL_MAX], url[1600]; |
| 484 | ws_buf q; |
| 485 | ws_resp r; |
| 486 | yyjson_doc *doc = NULL; |
| 487 | yyjson_val *root, *arr, *el; |
| 488 | int n = 0; |
| 489 | |
| 490 | if (!cfg->searxng_base[0]) { |
| 491 | ws_copy(err, errsz, |
| 492 | "SearXNG needs a base URL (a self-hosted instance). Set " |
| 493 | "WEBSEARCH_SEARXNG_BASE, or set it on the plugin page."); |
| 494 | return -1; |
| 495 | } |
| 496 | base_trim(base, sizeof base, cfg->searxng_base); |
| 497 | snprintf(url, sizeof url, "%s/search?q=", base); |
| 498 | ws_buf_init(&q); |
| 499 | ws_buf_puts(&q, url); |
| 500 | ws_url_encode(query, &q); |
| 501 | ws_buf_puts(&q, "&format=json"); |
| 502 | if (cfg->searxng_categories[0]) { |
| 503 | ws_buf_puts(&q, "&categories="); |
| 504 | ws_url_encode(cfg->searxng_categories, &q); |
| 505 | } |
| 506 | if (language && *language) { |
| 507 | ws_buf_puts(&q, "&language="); |
| 508 | ws_url_encode(language, &q); |
| 509 | } |
| 510 | if (safe && *safe) { |
| 511 | ws_buf_puts(&q, "&safesearch="); |
| 512 | if (ws_ieq(safe, "strict")) ws_buf_puts(&q, "2"); |
| 513 | else if (ws_ieq(safe, "off")) ws_buf_puts(&q, "0"); |
| 514 | else ws_buf_puts(&q, "1"); |
| 515 | } |
| 516 | ws_copy(url, sizeof url, ws_buf_str(&q)); |
| 517 | ws_buf_free(&q); |
| 518 | |
| 519 | if (ws_http_do("GET", url, "Accept: application/json\r\n", NULL, 0, 25000, |
| 520 | &r) != 0) { |
| 521 | ws_copy(err, errsz, r.error); |
| 522 | ws_resp_free(&r); |
| 523 | return -1; |
| 524 | } |
| 525 | if (status_out) *status_out = r.status; |
| 526 | if (!r.ok || r.status >= 400) { |
| 527 | upstream_error(&r, "SearXNG", err, errsz); |
| 528 | ws_resp_free(&r); |
| 529 | return -1; |
| 530 | } |
| 531 | if (parse_json(&r, &doc, "SearXNG", err, errsz) != 0) { ws_resp_free(&r); return -1; } |
| 532 | root = yyjson_doc_get_root(doc); |
| 533 | arr = jarr(root, "results"); |
| 534 | if (!arr) { |
| 535 | ws_copy(err, errsz, |
| 536 | "SearXNG answered without a results array - check that this " |
| 537 | "instance allows ?format=json (settings.yml: search.formats)"); |
| 538 | yyjson_doc_free(doc); |
| 539 | ws_resp_free(&r); |
| 540 | return -1; |
| 541 | } |
| 542 | yyjson_arr_iter iter; |
| 543 | yyjson_arr_iter_init(arr, &iter); |
| 544 | while ((el = yyjson_arr_iter_next(&iter)) && n < count) { |
| 545 | const char *title = jstr(el, "title"); |
| 546 | const char *u = jstr(el, "url"); |
| 547 | const char *content = jstr(el, "content"); |
| 548 | const char *pub = jstr(el, "publishedDate"); |
| 549 | ws_result *it; |
| 550 | if (!u || !*u) continue; |
| 551 | it = ws_results_push(res); |
| 552 | if (!it) { |
| 553 | ws_copy(err, errsz, "out of memory"); |
| 554 | yyjson_doc_free(doc); |
| 555 | ws_resp_free(&r); |
| 556 | return -1; |
| 557 | } |
| 558 | fill_result(it, title, u, content, pub); |
| 559 | n++; |
| 560 | } |
| 561 | yyjson_doc_free(doc); |
| 562 | ws_resp_free(&r); |
| 563 | return 0; |
| 564 | } |
| 565 | |
| 566 | /* ------------------------------------------------------------------ Brave */ |
| 567 | |
| 568 | static int search_brave(const ws_config *cfg, const char *query, int count, |
| 569 | const char *country, const char *language, |
| 570 | const char *freshness, ws_results *res, |
| 571 | long *status_out, char *err, size_t errsz) |
| 572 | { |
| 573 | char base[WS_URL_MAX], url[2000]; |
| 574 | char hdr[1200]; |
| 575 | ws_buf q; |
| 576 | ws_resp r; |
| 577 | yyjson_doc *doc = NULL; |
| 578 | yyjson_val *root, *web, *arr, *el; |
| 579 | int n = 0; |
| 580 | |
| 581 | if (!cfg->brave_key[0]) { |
| 582 | ws_copy(err, errsz, |
| 583 | "Brave needs an API key. Set BRAVE_API_KEY, or save one on the " |
| 584 | "plugin page."); |
| 585 | return -1; |
| 586 | } |
| 587 | base_trim(base, sizeof base, cfg->brave_base); |
| 588 | ws_buf_init(&q); |
| 589 | ws_buf_printf(&q, "%s/res/v1/web/search?q=", base); |
| 590 | ws_url_encode(query, &q); |
| 591 | { |
| 592 | char num[16]; |
| 593 | snprintf(num, sizeof num, "%d", count); |
| 594 | ws_buf_puts(&q, "&count="); |
| 595 | ws_buf_puts(&q, num); |
| 596 | } |
| 597 | if (country && *country) { |
| 598 | ws_buf_puts(&q, "&country="); |
| 599 | ws_url_encode(country, &q); |
| 600 | } |
| 601 | if (language && *language) { |
| 602 | ws_buf_puts(&q, "&search_lang="); |
| 603 | ws_url_encode(language, &q); |
| 604 | } |
| 605 | if (freshness && *freshness) { |
| 606 | ws_buf_puts(&q, "&freshness="); |
| 607 | ws_url_encode(freshness, &q); |
| 608 | } |
| 609 | ws_copy(url, sizeof url, ws_buf_str(&q)); |
| 610 | ws_buf_free(&q); |
| 611 | |
| 612 | snprintf(hdr, sizeof hdr, |
| 613 | "Accept: application/json\r\n" |
| 614 | "Accept-Encoding: identity\r\n" |
| 615 | "X-Subscription-Token: %s\r\n", cfg->brave_key); |
| 616 | |
| 617 | if (ws_http_do("GET", url, hdr, NULL, 0, 25000, &r) != 0) { |
| 618 | ws_copy(err, errsz, r.error); |
| 619 | ws_resp_free(&r); |
| 620 | return -1; |
| 621 | } |
| 622 | if (status_out) *status_out = r.status; |
| 623 | if (!r.ok || r.status >= 400) { |
| 624 | upstream_error(&r, "Brave", err, errsz); |
| 625 | ws_resp_free(&r); |
| 626 | return -1; |
| 627 | } |
| 628 | if (parse_json(&r, &doc, "Brave", err, errsz) != 0) { ws_resp_free(&r); return -1; } |
| 629 | root = yyjson_doc_get_root(doc); |
| 630 | web = jobj(root, "web"); |
| 631 | arr = jarr(web, "results"); |
| 632 | if (arr) { |
| 633 | yyjson_arr_iter iter; |
| 634 | yyjson_arr_iter_init(arr, &iter); |
| 635 | while ((el = yyjson_arr_iter_next(&iter)) && n < count) { |
| 636 | const char *title = jstr(el, "title"); |
| 637 | const char *u = jstr(el, "url"); |
| 638 | const char *desc = jstr(el, "description"); |
| 639 | const char *age = jstr(el, "age"); |
| 640 | ws_result *it; |
| 641 | if (!u || !*u) continue; |
| 642 | it = ws_results_push(res); |
| 643 | if (!it) { |
| 644 | ws_copy(err, errsz, "out of memory"); |
| 645 | yyjson_doc_free(doc); |
| 646 | ws_resp_free(&r); |
| 647 | return -1; |
| 648 | } |
| 649 | fill_result(it, title, u, desc, age); |
| 650 | n++; |
| 651 | } |
| 652 | } |
| 653 | yyjson_doc_free(doc); |
| 654 | ws_resp_free(&r); |
| 655 | return 0; |
| 656 | } |
| 657 | |
| 658 | /* ----------------------------------------------------------------- Tavily */ |
| 659 | |
| 660 | /* One POST body shared by the keyed POST providers: build with yyjson so a |
| 661 | * quote in the query cannot break the document. */ |
| 662 | static char *json_body(const char *query, int count, int advanced, int answer) |
| 663 | { |
| 664 | yyjson_mut_doc *md = yyjson_mut_doc_new(NULL); |
| 665 | yyjson_mut_val *root; |
| 666 | char *js; |
| 667 | size_t len; |
| 668 | |
| 669 | if (!md) return NULL; |
| 670 | root = yyjson_mut_obj(md); |
| 671 | yyjson_mut_doc_set_root(md, root); |
| 672 | yyjson_mut_obj_add_strcpy(md, root, "query", query); |
| 673 | yyjson_mut_obj_add_int(md, root, "max_results", count); |
| 674 | if (advanced) yyjson_mut_obj_add_strcpy(md, root, "search_depth", "advanced"); |
| 675 | if (answer) yyjson_mut_obj_add_bool(md, root, "include_answer", 1); |
| 676 | js = yyjson_mut_write(md, 0, &len); |
| 677 | yyjson_mut_doc_free(md); |
| 678 | return js; |
| 679 | } |
| 680 | |
| 681 | static int search_tavily(const ws_config *cfg, const char *query, int count, |
| 682 | ws_results *res, long *status_out, char *err, |
| 683 | size_t errsz) |
| 684 | { |
| 685 | char base[WS_URL_MAX], url[1300], hdr[1200]; |
| 686 | char *body; |
| 687 | ws_resp r; |
| 688 | yyjson_doc *doc = NULL; |
| 689 | yyjson_val *root, *arr, *el; |
| 690 | int n = 0; |
| 691 | |
| 692 | if (!cfg->tavily_key[0]) { |
| 693 | ws_copy(err, errsz, |
| 694 | "Tavily needs an API key. Set TAVILY_API_KEY, or save one on the " |
| 695 | "plugin page."); |
| 696 | return -1; |
| 697 | } |
| 698 | base_trim(base, sizeof base, cfg->tavily_base); |
| 699 | snprintf(url, sizeof url, "%s/search", base); |
| 700 | body = json_body(query, count, cfg->tavily_advanced, cfg->tavily_answer); |
| 701 | if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } |
| 702 | snprintf(hdr, sizeof hdr, |
| 703 | "Content-Type: application/json\r\n" |
| 704 | "Accept: application/json\r\n" |
| 705 | "Authorization: Bearer %s\r\n", cfg->tavily_key); |
| 706 | |
| 707 | if (ws_http_do("POST", url, hdr, body, strlen(body), 30000, &r) != 0) { |
| 708 | ws_copy(err, errsz, r.error); |
| 709 | free(body); |
| 710 | ws_resp_free(&r); |
| 711 | return -1; |
| 712 | } |
| 713 | free(body); |
| 714 | if (status_out) *status_out = r.status; |
| 715 | if (!r.ok || r.status >= 400) { |
| 716 | upstream_error(&r, "Tavily", err, errsz); |
| 717 | ws_resp_free(&r); |
| 718 | return -1; |
| 719 | } |
| 720 | if (parse_json(&r, &doc, "Tavily", err, errsz) != 0) { ws_resp_free(&r); return -1; } |
| 721 | root = yyjson_doc_get_root(doc); |
| 722 | { |
| 723 | const char *ans = jstr(root, "answer"); |
| 724 | if (ans && *ans) ws_buf_puts(&res->answer, ans); |
| 725 | } |
| 726 | arr = jarr(root, "results"); |
| 727 | if (arr) { |
| 728 | yyjson_arr_iter iter; |
| 729 | yyjson_arr_iter_init(arr, &iter); |
| 730 | while ((el = yyjson_arr_iter_next(&iter)) && n < count) { |
| 731 | const char *title = jstr(el, "title"); |
| 732 | const char *u = jstr(el, "url"); |
| 733 | const char *content = jstr(el, "content"); |
| 734 | const char *pub = jstr(el, "published_date"); |
| 735 | ws_result *it; |
| 736 | if (!u || !*u) continue; |
| 737 | it = ws_results_push(res); |
| 738 | if (!it) { |
| 739 | ws_copy(err, errsz, "out of memory"); |
| 740 | yyjson_doc_free(doc); |
| 741 | ws_resp_free(&r); |
| 742 | return -1; |
| 743 | } |
| 744 | fill_result(it, title, u, content, pub); |
| 745 | n++; |
| 746 | } |
| 747 | } |
| 748 | yyjson_doc_free(doc); |
| 749 | ws_resp_free(&r); |
| 750 | return 0; |
| 751 | } |
| 752 | |
| 753 | /* -------------------------------------------------------------------- Exa */ |
| 754 | |
| 755 | static int search_exa(const ws_config *cfg, const char *query, int count, |
| 756 | ws_results *res, long *status_out, char *err, size_t errsz) |
| 757 | { |
| 758 | char base[WS_URL_MAX], url[1300], hdr[1200]; |
| 759 | yyjson_mut_doc *md; |
| 760 | yyjson_mut_val *root, *contents; |
| 761 | char *body; |
| 762 | size_t blen; |
| 763 | ws_resp r; |
| 764 | yyjson_doc *doc = NULL; |
| 765 | yyjson_val *jroot, *arr, *el; |
| 766 | int n = 0; |
| 767 | |
| 768 | if (!cfg->exa_key[0]) { |
| 769 | ws_copy(err, errsz, |
| 770 | "Exa needs an API key. Set EXA_API_KEY, or save one on the " |
| 771 | "plugin page."); |
| 772 | return -1; |
| 773 | } |
| 774 | base_trim(base, sizeof base, cfg->exa_base); |
| 775 | /* Both https://api.exa.ai and a base that already ends in /search work. */ |
| 776 | if (strlen(base) >= 7 && ws_ieq(base + strlen(base) - 7, "/search")) |
| 777 | snprintf(url, sizeof url, "%s", base); |
| 778 | else |
| 779 | snprintf(url, sizeof url, "%s/search", base); |
| 780 | |
| 781 | md = yyjson_mut_doc_new(NULL); |
| 782 | if (!md) { ws_copy(err, errsz, "out of memory"); return -1; } |
| 783 | root = yyjson_mut_obj(md); |
| 784 | yyjson_mut_doc_set_root(md, root); |
| 785 | yyjson_mut_obj_add_strcpy(md, root, "query", query); |
| 786 | yyjson_mut_obj_add_int(md, root, "numResults", count); |
| 787 | contents = yyjson_mut_obj(md); |
| 788 | yyjson_mut_obj_add_bool(md, contents, "highlights", 1); |
| 789 | yyjson_mut_obj_add_val(md, root, "contents", contents); |
| 790 | body = yyjson_mut_write(md, 0, &blen); |
| 791 | yyjson_mut_doc_free(md); |
| 792 | if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } |
| 793 | |
| 794 | snprintf(hdr, sizeof hdr, |
| 795 | "Content-Type: application/json\r\n" |
| 796 | "Accept: application/json\r\n" |
| 797 | "x-api-key: %s\r\n", cfg->exa_key); |
| 798 | |
| 799 | if (ws_http_do("POST", url, hdr, body, blen, 30000, &r) != 0) { |
| 800 | ws_copy(err, errsz, r.error); |
| 801 | free(body); |
| 802 | ws_resp_free(&r); |
| 803 | return -1; |
| 804 | } |
| 805 | free(body); |
| 806 | if (status_out) *status_out = r.status; |
| 807 | if (!r.ok || r.status >= 400) { |
| 808 | upstream_error(&r, "Exa", err, errsz); |
| 809 | ws_resp_free(&r); |
| 810 | return -1; |
| 811 | } |
| 812 | if (parse_json(&r, &doc, "Exa", err, errsz) != 0) { ws_resp_free(&r); return -1; } |
| 813 | jroot = yyjson_doc_get_root(doc); |
| 814 | arr = jarr(jroot, "results"); |
| 815 | if (arr) { |
| 816 | yyjson_arr_iter iter; |
| 817 | yyjson_arr_iter_init(arr, &iter); |
| 818 | while ((el = yyjson_arr_iter_next(&iter)) && n < count) { |
| 819 | const char *title = jstr(el, "title"); |
| 820 | const char *u = jstr(el, "url"); |
| 821 | const char *pub = jstr(el, "publishedDate"); |
| 822 | const char *text = jstr(el, "text"); |
| 823 | const char *first_highlight = NULL; |
| 824 | ws_result *it; |
| 825 | |
| 826 | if (!u || !*u) continue; |
| 827 | /* `highlights` is an array of the most relevant excerpts; the first |
| 828 | * one is the closest thing to a snippet Exa offers. */ |
| 829 | { |
| 830 | yyjson_val *hl = jarr(el, "highlights"); |
| 831 | if (hl && yyjson_arr_size(hl) > 0) { |
| 832 | yyjson_val *h0 = yyjson_arr_get_first(hl); |
| 833 | if (h0 && yyjson_is_str(h0)) first_highlight = yyjson_get_str(h0); |
| 834 | } |
| 835 | } |
| 836 | it = ws_results_push(res); |
| 837 | if (!it) { |
| 838 | ws_copy(err, errsz, "out of memory"); |
| 839 | yyjson_doc_free(doc); |
| 840 | ws_resp_free(&r); |
| 841 | return -1; |
| 842 | } |
| 843 | fill_result(it, title, u, first_highlight ? first_highlight : text, pub); |
| 844 | n++; |
| 845 | } |
| 846 | } |
| 847 | yyjson_doc_free(doc); |
| 848 | ws_resp_free(&r); |
| 849 | return 0; |
| 850 | } |
| 851 | |
| 852 | /* ------------------------------------------------------------ Perplexity */ |
| 853 | |
| 854 | static int search_perplexity(const ws_config *cfg, const char *query, int count, |
| 855 | ws_results *res, long *status_out, char *err, |
| 856 | size_t errsz) |
| 857 | { |
| 858 | char base[WS_URL_MAX], url[1400], hdr[1200]; |
| 859 | char *body; |
| 860 | ws_resp r; |
| 861 | yyjson_doc *doc = NULL; |
| 862 | yyjson_val *root, *arr, *el; |
| 863 | int n = 0; |
| 864 | |
| 865 | if (!cfg->pplx_key[0]) { |
| 866 | ws_copy(err, errsz, |
| 867 | "Perplexity needs an API key. Set PERPLEXITY_API_KEY, or save one " |
| 868 | "on the plugin page."); |
| 869 | return -1; |
| 870 | } |
| 871 | base_trim(base, sizeof base, cfg->pplx_base); |
| 872 | if (strlen(base) >= 7 && ws_ieq(base + strlen(base) - 7, "/search")) |
| 873 | snprintf(url, sizeof url, "%s", base); |
| 874 | else |
| 875 | snprintf(url, sizeof url, "%s/search", base); |
| 876 | |
| 877 | /* The Search API (not chat completions): it returns ranked sources rather |
| 878 | * than prose, which is what a search tool is for. */ |
| 879 | body = json_body(query, count, 0, 0); |
| 880 | if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } |
| 881 | snprintf(hdr, sizeof hdr, |
| 882 | "Content-Type: application/json\r\n" |
| 883 | "Accept: application/json\r\n" |
| 884 | "Authorization: Bearer %s\r\n", cfg->pplx_key); |
| 885 | |
| 886 | if (ws_http_do("POST", url, hdr, body, strlen(body), 30000, &r) != 0) { |
| 887 | ws_copy(err, errsz, r.error); |
| 888 | free(body); |
| 889 | ws_resp_free(&r); |
| 890 | return -1; |
| 891 | } |
| 892 | free(body); |
| 893 | if (status_out) *status_out = r.status; |
| 894 | if (!r.ok || r.status >= 400) { |
| 895 | upstream_error(&r, "Perplexity", err, errsz); |
| 896 | ws_resp_free(&r); |
| 897 | return -1; |
| 898 | } |
| 899 | if (parse_json(&r, &doc, "Perplexity", err, errsz) != 0) { ws_resp_free(&r); return -1; } |
| 900 | root = yyjson_doc_get_root(doc); |
| 901 | arr = jarr(root, "results"); |
| 902 | if (arr) { |
| 903 | yyjson_arr_iter iter; |
| 904 | yyjson_arr_iter_init(arr, &iter); |
| 905 | while ((el = yyjson_arr_iter_next(&iter)) && n < count) { |
| 906 | const char *title = jstr(el, "title"); |
| 907 | const char *u = jstr(el, "url"); |
| 908 | const char *snip = jstr(el, "snippet"); |
| 909 | const char *date = jstr(el, "date"); |
| 910 | ws_result *it; |
| 911 | if (!u || !*u) continue; |
| 912 | it = ws_results_push(res); |
| 913 | if (!it) { |
| 914 | ws_copy(err, errsz, "out of memory"); |
| 915 | yyjson_doc_free(doc); |
| 916 | ws_resp_free(&r); |
| 917 | return -1; |
| 918 | } |
| 919 | fill_result(it, title, u, snip, date); |
| 920 | n++; |
| 921 | } |
| 922 | } |
| 923 | yyjson_doc_free(doc); |
| 924 | ws_resp_free(&r); |
| 925 | return 0; |
| 926 | } |
| 927 | |
| 928 | /* --------------------------------------------------------------- dispatch */ |
| 929 | |
| 930 | int ws_search(const ws_config *cfg, const char *provider, const char *query, |
| 931 | int count, const char *country, const char *language, |
| 932 | const char *freshness, const char *safe_override, |
| 933 | ws_results *r, long *status_out, char *err, size_t errsz) |
| 934 | { |
| 935 | const char *prov = (provider && *provider) ? provider : ws_provider_active(cfg); |
| 936 | const char *safe = (safe_override && *safe_override) ? safe_override : cfg->safe; |
| 937 | const char *lang = (language && *language) ? language : cfg->language; |
| 938 | long long t0; |
| 939 | int rc; |
| 940 | |
| 941 | if (status_out) *status_out = 0; |
| 942 | err[0] = '\0'; |
| 943 | |
| 944 | if (!query || !*query) { |
| 945 | ws_copy(err, errsz, "query is required"); |
| 946 | return -2; |
| 947 | } |
| 948 | if (!ws_provider_known(prov)) { |
| 949 | snprintf(err, errsz, |
| 950 | "unknown provider \"%s\" (choose duckduckgo, searxng, brave, " |
| 951 | "tavily, exa or perplexity)", prov); |
| 952 | return -2; |
| 953 | } |
| 954 | if (count < 1) count = cfg->count > 0 ? cfg->count : WS_DEFAULT_COUNT; |
| 955 | if (count > WS_MAX_COUNT) count = WS_MAX_COUNT; |
| 956 | |
| 957 | ws_copy(r->provider, sizeof r->provider, prov); |
| 958 | ws_copy(r->query, sizeof r->query, query); |
| 959 | r->count = count; |
| 960 | r->n = 0; |
| 961 | t0 = sx_now_ms(); |
| 962 | |
| 963 | if (ws_ieq(prov, "duckduckgo")) |
| 964 | rc = search_duckduckgo(cfg, query, count, cfg->region, safe, r, |
| 965 | status_out, err, errsz); |
| 966 | else if (ws_ieq(prov, "searxng")) |
| 967 | rc = search_searxng(cfg, query, count, lang, safe, r, status_out, |
| 968 | err, errsz); |
| 969 | else if (ws_ieq(prov, "brave")) |
| 970 | rc = search_brave(cfg, query, count, country, lang, freshness, r, |
| 971 | status_out, err, errsz); |
| 972 | else if (ws_ieq(prov, "tavily")) |
| 973 | rc = search_tavily(cfg, query, count, r, status_out, err, errsz); |
| 974 | else if (ws_ieq(prov, "exa")) |
| 975 | rc = search_exa(cfg, query, count, r, status_out, err, errsz); |
| 976 | else |
| 977 | rc = search_perplexity(cfg, query, count, r, status_out, err, errsz); |
| 978 | |
| 979 | r->took_ms = sx_now_ms() - t0; |
| 980 | if (rc != 0) return rc; |
| 981 | if (r->n > 0) r->truncated = 0; |
| 982 | return 0; |
| 983 | } |