fix: follow DuckDuckGo continuation forms for pagination

This commit is contained in:
frosty
2026-11-03 13:24:54 -05:00
parent b8c920ef0a
commit 186f66619c
3 changed files with 207 additions and 61 deletions

View File

@@ -53,6 +53,8 @@ const char *get_random_user_agent(void) {
return USER_AGENTS[rand() % USER_AGENT_COUNT];
}
const char *get_first_user_agent(void) { return USER_AGENTS[0]; }
void configure_curl_handle(CURL *curl, const char *full_url,
MemoryBuffer *chunk, struct curl_slist *headers) {
curl_easy_setopt(curl, CURLOPT_URL, full_url);
@@ -75,15 +77,79 @@ void configure_curl_handle(CURL *curl, const char *full_url,
char *build_search_url(const char *base_url, const char *page_param,
int page_multiplier, int page_base,
const char *encoded_query, int page) {
int page_value = (page < 1 ? 1 : page - 1) * page_multiplier + page_base;
long long page_value =
(long long)(page > 1 ? page - 1 : 0) * page_multiplier + page_base;
char *url = malloc(BUFFER_SIZE_LARGE);
if (!url)
return NULL;
snprintf(url, BUFFER_SIZE_LARGE, "%s%s&%s=%d", base_url, encoded_query,
snprintf(url, BUFFER_SIZE_LARGE, "%s%s&%s=%lld", base_url, encoded_query,
page_param, page_value);
return url;
}
char *build_ddg_next_page_data(const char *html, size_t size) {
htmlDocPtr doc = htmlReadMemory(html, size, NULL, NULL,
HTML_PARSE_RECOVER | HTML_PARSE_NOERROR |
HTML_PARSE_NOWARNING);
if (!doc)
return NULL;
xmlXPathContextPtr ctx = create_xpath_context(doc);
if (!ctx) {
xmlFreeDoc(doc);
return NULL;
}
xmlXPathObjectPtr inputs = xmlXPathEvalExpression(
(const xmlChar *)"(//form[.//input[@name='s'] and "
".//input[@name='vqd' and string-length(@value)>0] and "
"(.//input[@type='submit' and contains(@value, 'Next')] or "
".//button[contains(., 'Next')])])[1]"
"//input[@name and not(@disabled) and "
"(not(@type) or @type='hidden')]",
ctx);
if (!inputs || !inputs->nodesetval) {
free_xpath_objects(ctx, inputs);
xmlFreeDoc(doc);
return NULL;
}
char *data = NULL;
size_t length = 0;
int failed = 0;
for (int i = 0; i < inputs->nodesetval->nodeNr; i++) {
xmlNodePtr node = inputs->nodesetval->nodeTab[i];
xmlChar *name = xmlGetProp(node, (const xmlChar *)"name");
xmlChar *value = xmlGetProp(node, (const xmlChar *)"value");
char *key = curl_easy_escape(NULL, (const char *)name, 0);
char *val = curl_easy_escape(NULL, value ? (const char *)value : "", 0);
size_t needed = key && val ? strlen(key) + strlen(val) + 2 : 0;
char *expanded = needed ? realloc(data, length + needed + 1) : NULL;
if (expanded) {
data = expanded;
length += snprintf(data + length, needed + 1, "%s%s=%s",
length ? "&" : "", key, val);
} else {
failed = 1;
}
curl_free(key);
curl_free(val);
xmlFree(name);
xmlFree(value);
if (failed)
break;
}
if (failed) {
free(data);
data = NULL;
}
free_xpath_objects(ctx, inputs);
xmlFreeDoc(doc);
return data;
}
struct curl_slist *build_request_headers(const char *host_header,
const char *referer) {
struct curl_slist *headers = NULL;