From 95a10c5f9bfa341b0422c4c04e1d5ff55c37ea35 Mon Sep 17 00:00:00 2001 From: voidarc Date: Fri, 13 Nov 2026 11:06:37 +0000 Subject: [PATCH] ENSLAVED opencode to fix the search thingy --- README.md | 4 +- flake.nix | 7 +- src/Config.h | 8 +- src/Scraping/Scraping.c | 956 ++++++++++++++++++++++++++++-------- src/Scraping/Scraping.h | 2 - src/Scraping/ScrapingHttp.c | 82 +--- src/Utility/HttpClient.c | 36 +- src/Utility/HttpClient.h | 3 + 8 files changed, 802 insertions(+), 296 deletions(-) diff --git a/README.md b/README.md index 1813ddb..c5d573d 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,11 @@ Create a config.ini, there is an example included in the root. Or if you install ## Dependencies - libxml2 -- libcurl (may be replaced in the future with curl-impersonate) +- curl-impersonate (or libcurl; build with `-DOMNISEARCH_USE_CURL_IMPERSONATE` and link `-lcurl-impersonate` to enable browser impersonation) - beaker [(source)](https://git.bwaaa.space/beaker/) +The included Nix flake and NixOS module build against curl-impersonate automatically. Set `OMNISEARCH_IMPERSONATE_TARGET` to override the impersonated browser profile (default: `chrome136`). + ## First Setup Depending on your system, you may first need to install libcurl and libxml2. diff --git a/flake.nix b/flake.nix index 85aba5a..e859846 100644 --- a/flake.nix +++ b/flake.nix @@ -40,7 +40,8 @@ buildInputs = [ pkgs.libxml2.dev - pkgs.curl.dev + pkgs.curl-impersonate + pkgs.curl-impersonate.dev pkgs.openssl beaker ]; @@ -48,8 +49,8 @@ preBuild = '' makeFlagsArray+=( "PREFIX=$out" - "CFLAGS=-Wall -Wextra -O2 -Isrc -I${pkgs.libxml2.dev}/include/libxml2" - "LIBS=-lbeaker -lcurl -lxml2 -lpthread -lm -lssl -lcrypto" + "CFLAGS=-Wall -Wextra -O2 -Isrc -I${pkgs.libxml2.dev}/include/libxml2 -I${pkgs.curl-impersonate.dev}/include -DOMNISEARCH_USE_CURL_IMPERSONATE" + "LIBS=-lbeaker -lcurl-impersonate -lxml2 -lpthread -lm -lssl -lcrypto" ) ''; diff --git a/src/Config.h b/src/Config.h index 17ce1d9..8e6571e 100644 --- a/src/Config.h +++ b/src/Config.h @@ -25,9 +25,15 @@ #define INFOBOX_FIELD_COUNT 5 #define MAX_RESULTS_PER_ENGINE 10 -#define CURL_TIMEOUT_SECS 15L +#define CURL_TIMEOUT_SECS 8L +#define CURL_CONNECT_TIMEOUT_SECS 5L #define CURL_DNS_TIMEOUT_SECS 300L +/* Upper bound for a whole search, even if one engine hangs. */ +#define SCRAPE_DEADLINE_MS 8000 + +#define DEFAULT_IMPERSONATE_TARGET "chrome136" + #define BING_IMAGE_URL "https://www.bing.com/images/search" #define IMAGE_RESULTS_PER_PAGE 32 #define IMAGE_RESULT_FIELDS 4 diff --git a/src/Scraping/Scraping.c b/src/Scraping/Scraping.c index a017e55..1287b77 100644 --- a/src/Scraping/Scraping.c +++ b/src/Scraping/Scraping.c @@ -6,7 +6,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -17,90 +20,50 @@ static int response_contains(const char *response, const char *needle) { return response && needle && strstr(response, needle) != NULL; } -static int is_ddg_job(const ScrapeJob *job) { - return job && job->engine && job->engine->id && - strcmp(job->engine->id, "ddg") == 0; -} - static int is_startpage_job(const ScrapeJob *job) { return job && job->engine && job->engine->id && strcmp(job->engine->id, "startpage") == 0; } +static int is_mojeek_job(const ScrapeJob *job) { + return job && job->engine && job->engine->id && + strcmp(job->engine->id, "mojeek") == 0; +} + static char *job_cache_key(const ScrapeJob *job, int page) { - const char *scope = is_ddg_job(job) ? "ddg_pagination_v2" : job->engine->name; - return cache_compute_key(job->query, page, scope); + return cache_compute_key(job->query, page, job->engine->name); } -static char *extract_ddg_vqd(const char *html) { - if (!html) - return NULL; +static int perform_startpage_request(ScrapeJob *job, const char *url, + const struct timespec *deadline_start); +static int perform_mojeek_request(ScrapeJob *job, const char *url, + const struct timespec *deadline_start); - const char *start = strstr(html, "vqd=\""); - if (start) { - start += sizeof("vqd=\"") - 1; - } else { - start = strstr(html, "vqd="); - if (!start) - return NULL; - start += sizeof("vqd=") - 1; - } - - const char *end = start; - while (*end && *end != '"' && *end != '\'' && *end != '&' && *end != ';' && - *end != ' ' && *end != '\n' && *end != '\r') - end++; - - if (end == start) - return NULL; - - size_t length = (size_t)(end - start); - char *vqd = malloc(length + 1); - if (!vqd) - return NULL; - memcpy(vqd, start, length); - vqd[length] = '\0'; - return vqd; +static long scrape_time_remaining_ms(const struct timespec *deadline_start) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + long elapsed = (now.tv_sec - deadline_start->tv_sec) * 1000L + + (now.tv_nsec - deadline_start->tv_nsec) / 1000000L; + long remaining = SCRAPE_DEADLINE_MS - elapsed; + return remaining > 0 ? remaining : 0; } -static char *fetch_ddg_vqd(const char *encoded_query) { - CURL *handle = curl_easy_init(); - if (!handle) - return NULL; - - MemoryBuffer response = {0}; - size_t url_size = - strlen(encoded_query) + sizeof("https://duckduckgo.com/?q=&ia=web"); - char *url = malloc(url_size); - if (!url) { - curl_easy_cleanup(handle); - return NULL; - } - snprintf(url, url_size, "https://duckduckgo.com/?q=%s&ia=web", - encoded_query); - - struct curl_slist *headers = - build_request_headers("duckduckgo.com", "https://duckduckgo.com/"); - configure_curl_handle(handle, url, &response, headers); - curl_easy_setopt(handle, CURLOPT_USERAGENT, get_first_user_agent()); - - char *vqd = NULL; - if (curl_easy_perform(handle) == CURLE_OK) - vqd = extract_ddg_vqd(response.memory); - - free(response.memory); - free(url); - curl_slist_free_all(headers); - curl_easy_cleanup(handle); - return vqd; +static void apply_deadline_timeout(CURL *handle, + const struct timespec *deadline_start) { + long remaining = scrape_time_remaining_ms(deadline_start); + long max_timeout = CURL_TIMEOUT_SECS * 1000L; + if (remaining > max_timeout) + remaining = max_timeout; + if (remaining < 1) + remaining = 1; + curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, remaining); } -static int perform_ddg_request(ScrapeJob *job, const char *url, - const char *encoded_query); -static int perform_startpage_request(ScrapeJob *job, const char *url); - static int configure_job_request(ScrapeJob *job, char *url, - const char *encoded_query) { + const struct timespec *deadline_start) { + if (scrape_time_remaining_ms(deadline_start) <= 0) + return -1; + job->handle = curl_easy_init(); if (!job->handle) return -1; @@ -116,10 +79,11 @@ static int configure_job_request(ScrapeJob *job, char *url, configure_curl_handle(job->handle, url, &job->response, headers); curl_easy_setopt(job->handle, CURLOPT_PRIVATE, headers); - if (is_ddg_job(job)) - return perform_ddg_request(job, url, encoded_query); + apply_deadline_timeout(job->handle, deadline_start); if (is_startpage_job(job)) - return perform_startpage_request(job, url); + return perform_startpage_request(job, url, deadline_start); + if (is_mojeek_job(job)) + return perform_mojeek_request(job, url, deadline_start); return 0; } @@ -132,9 +96,34 @@ static int response_is_startpage_captcha(const ScrapeJob *job, response_contains(response, "Startpage Captcha") || response_contains(response, "/static-pages-assets/page-data/captcha/") || + response_contains(response, "/sp/captcha-block") || response_contains(response, ">Startpage Blocked"); } +static int response_is_mojeek_captcha(const ScrapeJob *job, + const char *response) { + if (!is_mojeek_job(job)) + return 0; + + return response_contains(response, "captcha-wrap") || + response_contains(response, "altcha-widget") || + response_contains(response, "/captcha/challenge") || + response_contains(response, "Captcha"); +} + +static int response_is_block_page(const ScrapeJob *job, + const char *response) { + if (response_is_startpage_captcha(job, response)) + return 1; + if (response_is_mojeek_captcha(job, response)) + return 1; + + return response_contains(response, "id=\"challenge-form\"") || + response_contains(response, "Captcha") || + response_contains(response, "anubis_challenge") || + response_contains(response, "g-recaptcha"); +} + static int response_looks_like_results_page(const ScrapeJob *job, const char *response) { if (!job || !job->engine || !response) @@ -161,8 +150,7 @@ static int response_looks_like_results_page(const ScrapeJob *job, } if (strcmp(job->engine->name, "Mojeek") == 0) { - return response_contains(response, "class=\"results-standard\"") || - response_contains(response, "Mojeek Search"); + return response_contains(response, "class=\"results-standard\""); } if (strcmp(job->engine->name, "Bing") == 0) { @@ -186,8 +174,7 @@ static void classify_job_response(ScrapeJob *job, const char *response, return; } - if (response_is_startpage_captcha(job, response) || - (is_ddg_job(job) && response_contains(response, "id=\"challenge-form\""))) { + if (response_is_block_page(job, response)) { job->status = SCRAPE_STATUS_BLOCKED; return; } @@ -304,96 +291,6 @@ static void cleanup_job_handle(ScrapeJob *job, CURL *handle) { job->response.capacity = 0; } -static int ddg_response_is_challenge(const char *response) { - return response_contains(response, "id=\"challenge-form\"") || - response_contains(response, "challenge-form") || - response_contains(response, "anomaly"); -} - -static char *build_ddg_endpoint_url(const char *base_url, - const char *query_part, - const char *escaped_vqd) { - size_t size = - strlen(base_url) + strlen(query_part) + strlen(escaped_vqd) + 16; - char *final_url = malloc(size); - if (!final_url) - return NULL; - snprintf(final_url, size, "%s%s&vqd=%s", base_url, query_part, escaped_vqd); - return final_url; -} - -static int perform_ddg_request(ScrapeJob *job, const char *url, - const char *encoded_query) { - const int max_attempts = 3; - int completed = 0; - - const char *query_part = strchr(url, '?'); - if (!query_part) - query_part = ""; - - for (int attempt = 0; attempt < max_attempts && !completed; attempt++) { - char *vqd = fetch_ddg_vqd(encoded_query); - if (!vqd) { - if (attempt + 1 < max_attempts) - usleep(1000000); - continue; - } - - char *escaped_vqd = curl_easy_escape(NULL, vqd, 0); - free(vqd); - if (!escaped_vqd) - continue; - - for (int endpoint = 0; endpoint < 2 && !completed; endpoint++) { - char *final_url; - if (endpoint == 0) { - size_t size = strlen(url) + strlen(escaped_vqd) + sizeof("&vqd="); - final_url = malloc(size); - if (final_url) - snprintf(final_url, size, "%s&vqd=%s", url, escaped_vqd); - } else { - final_url = build_ddg_endpoint_url( - "https://duckduckgo.com/html/", query_part, escaped_vqd); - } - - if (!final_url) - continue; - - curl_easy_setopt(job->handle, CURLOPT_URL, final_url); - curl_easy_setopt(job->handle, CURLOPT_USERAGENT, get_first_user_agent()); - free(final_url); - - job->response.size = 0; - if (job->response.memory) - job->response.memory[0] = '\0'; - - CURLcode result = curl_easy_perform(job->handle); - if (result != CURLE_OK) - continue; - - curl_easy_getinfo(job->handle, CURLINFO_RESPONSE_CODE, - &job->http_status); - if (ddg_response_is_challenge(job->response.memory)) - continue; - - parse_and_cache_response(job); - completed = 1; - } - - curl_free(escaped_vqd); - if (!completed && attempt + 1 < max_attempts) - usleep(1000000); - } - - if (!completed) - parse_and_cache_response(job); - - cleanup_job_handle(job, job->handle); - curl_easy_cleanup(job->handle); - job->handle = NULL; - return 1; -} - static const char *json_field_start(const char *json, const char *anchor, const char *field) { if (!json || !field) @@ -477,56 +374,653 @@ static int hash_meets_difficulty(const unsigned char *digest, return 1; } -static char *solve_anubis_challenge(const char *random_data, int difficulty, - char *nonce_out, size_t nonce_size, - long *elapsed_ms) { - struct timespec started, finished; - clock_gettime(CLOCK_MONOTONIC, &started); +#define ANUBIS_MAX_NONCE 50000000ULL +#define ANUBIS_NONCE_CHUNK 1024ULL +#define ANUBIS_MAX_THREADS 8 +#define ANUBIS_SOLVER_TIMEOUT_MS 5000L +#define STARTPAGE_AUTH_COOKIE_TTL 240 - size_t random_length = strlen(random_data); - char *input = malloc(random_length + 32); - if (!input) - return NULL; - memcpy(input, random_data, random_length); +typedef struct { + const char *random_data; + size_t random_length; + int difficulty; + unsigned long long max_nonce; + atomic_ullong next_nonce; + atomic_int found; + pthread_mutex_t result_mutex; + struct timespec started; + long timeout_ms; + char response_hex[SHA256_DIGEST_LENGTH * 2 + 1]; + char nonce[32]; +} AnubisSolver; + +static long timespec_elapsed_ms(const struct timespec *start, + const struct timespec *end) { + return (end->tv_sec - start->tv_sec) * 1000L + + (end->tv_nsec - start->tv_nsec) / 1000000L; +} + +static void *anubis_solver_worker(void *arg) { + AnubisSolver *solver = (AnubisSolver *)arg; + + SHA256_CTX prefix; + SHA256_Init(&prefix); + SHA256_Update(&prefix, (const unsigned char *)solver->random_data, + solver->random_length); unsigned char digest[SHA256_DIGEST_LENGTH]; - for (unsigned long long nonce = 0; nonce < 50000000ULL; nonce++) { - int written = snprintf(input + random_length, 32, "%llu", nonce); - if (written < 0 || written >= 32) { - free(input); + char nonce_buffer[32]; + + while (!atomic_load_explicit(&solver->found, memory_order_relaxed)) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + if (timespec_elapsed_ms(&solver->started, &now) >= solver->timeout_ms) + return NULL; + + unsigned long long first = atomic_fetch_add_explicit( + &solver->next_nonce, ANUBIS_NONCE_CHUNK, memory_order_relaxed); + if (first >= solver->max_nonce) + return NULL; + + unsigned long long last = first + ANUBIS_NONCE_CHUNK; + if (last > solver->max_nonce) + last = solver->max_nonce; + + for (unsigned long long nonce = first; nonce < last; nonce++) { + int written = + snprintf(nonce_buffer, sizeof(nonce_buffer), "%llu", nonce); + if (written < 0 || (size_t)written >= sizeof(nonce_buffer)) + continue; + + SHA256_CTX ctx = prefix; + SHA256_Update(&ctx, (const unsigned char *)nonce_buffer, + (size_t)written); + SHA256_Final(digest, &ctx); + + if (!hash_meets_difficulty(digest, solver->difficulty)) + continue; + + pthread_mutex_lock(&solver->result_mutex); + if (!atomic_load_explicit(&solver->found, memory_order_relaxed)) { + for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) + snprintf(solver->response_hex + i * 2, 3, "%02x", digest[i]); + solver->response_hex[SHA256_DIGEST_LENGTH * 2] = '\0'; + snprintf(solver->nonce, sizeof(solver->nonce), "%llu", nonce); + atomic_store_explicit(&solver->found, 1, memory_order_relaxed); + } + pthread_mutex_unlock(&solver->result_mutex); return NULL; } - - SHA256((const unsigned char *)input, random_length + (size_t)written, - digest); - if (!hash_meets_difficulty(digest, difficulty)) - continue; - - char *hex = malloc(SHA256_DIGEST_LENGTH * 2 + 1); - if (!hex) { - free(input); - return NULL; - } - for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) - snprintf(hex + i * 2, 3, "%02x", digest[i]); - hex[SHA256_DIGEST_LENGTH * 2] = '\0'; - snprintf(nonce_out, nonce_size, "%llu", nonce); - - clock_gettime(CLOCK_MONOTONIC, &finished); - *elapsed_ms = (finished.tv_sec - started.tv_sec) * 1000 + - (finished.tv_nsec - started.tv_nsec) / 1000000; - if (*elapsed_ms < 1) - *elapsed_ms = 1; - - free(input); - return hex; } - free(input); return NULL; } -static int perform_startpage_request(ScrapeJob *job, const char *url) { +static char *solve_anubis_challenge(const char *random_data, int difficulty, + long timeout_ms, char *nonce_out, + size_t nonce_size, long *elapsed_ms) { + AnubisSolver solver = { + .random_data = random_data, + .random_length = strlen(random_data), + .difficulty = difficulty, + .max_nonce = ANUBIS_MAX_NONCE, + .timeout_ms = timeout_ms, + }; + atomic_init(&solver.next_nonce, 0); + atomic_init(&solver.found, 0); + pthread_mutex_init(&solver.result_mutex, NULL); + clock_gettime(CLOCK_MONOTONIC, &solver.started); + + long cpu_count = sysconf(_SC_NPROCESSORS_ONLN); + int thread_count = cpu_count > 0 ? (int)cpu_count : 1; + if (thread_count < 1) + thread_count = 1; + if (thread_count > ANUBIS_MAX_THREADS) + thread_count = ANUBIS_MAX_THREADS; + + pthread_t threads[ANUBIS_MAX_THREADS]; + int started_threads = 0; + for (int i = 0; i < thread_count; i++) { + if (pthread_create(&threads[i], NULL, anubis_solver_worker, &solver) != 0) + break; + started_threads++; + } + + if (started_threads == 0) + anubis_solver_worker(&solver); + + for (int i = 0; i < started_threads; i++) + pthread_join(threads[i], NULL); + + struct timespec finished; + clock_gettime(CLOCK_MONOTONIC, &finished); + *elapsed_ms = timespec_elapsed_ms(&solver.started, &finished); + if (*elapsed_ms < 1) + *elapsed_ms = 1; + + char *response_hash = NULL; + if (atomic_load_explicit(&solver.found, memory_order_relaxed)) { + response_hash = strdup(solver.response_hex); + snprintf(nonce_out, nonce_size, "%s", solver.nonce); + } + + pthread_mutex_destroy(&solver.result_mutex); + return response_hash; +} + +static char *anubis_cookie_cache_key(void) { + return cache_compute_key("startpage", 0, "anubis_cookie_v1"); +} + +static char *load_startpage_cookie(void) { + char *key = anubis_cookie_cache_key(); + if (!key) + return NULL; + + char *cookie = NULL; + size_t cookie_size = 0; + int result = cache_get(key, STARTPAGE_AUTH_COOKIE_TTL, &cookie, &cookie_size); + free(key); + + if (result != 0 || !cookie || cookie_size == 0) { + free(cookie); + return NULL; + } + + return cookie; +} + +static void save_startpage_cookie(const char *cookie) { + if (!cookie || cookie[0] == '\0') + return; + + char *key = anubis_cookie_cache_key(); + if (!key) + return; + + cache_set(key, cookie, strlen(cookie)); + free(key); +} + +static char *cookie_value_from_jar(CURL *handle, const char *name) { + struct curl_slist *cookies = NULL; + if (curl_easy_getinfo(handle, CURLINFO_COOKIELIST, &cookies) != CURLE_OK) + return NULL; + + char *value = NULL; + for (struct curl_slist *item = cookies; item && !value; item = item->next) { + char *copy = strdup(item->data); + if (!copy) + break; + + char *fields[7] = {0}; + int field_count = 0; + char *cursor = copy; + while (field_count < 7) { + fields[field_count++] = cursor; + char *tab = strchr(cursor, '\t'); + if (!tab) + break; + *tab = '\0'; + cursor = tab + 1; + } + + if (field_count == 7 && strcmp(fields[5], name) == 0 && + fields[6][0] != '\0') + value = strdup(fields[6]); + + free(copy); + } + + curl_slist_free_all(cookies); + return value; +} + +#define ALTCHA_MAX_COUNTER 20000U +#define ALTCHA_COUNTER_CHUNK 64U +#define ALTCHA_MAX_THREADS 8 +#define ALTCHA_SOLVER_TIMEOUT_MS 5000L +#define ALTCHA_MAX_NONCE_BYTES 64 +#define MOJEEK_COOKIE_TTL 86400 +#define ALTCHA_MULTIPART_BOUNDARY "omnisearch-altcha-boundary" + +typedef struct { + const unsigned char *nonce; + size_t nonce_length; + const unsigned char *salt; + size_t salt_length; + const unsigned char *prefix; + size_t prefix_length; + int cost; + int key_length; + atomic_uint next_counter; + atomic_int found; + pthread_mutex_t result_mutex; + struct timespec started; + long timeout_ms; + unsigned int counter; + char derived_hex[EVP_MAX_MD_SIZE * 2 + 1]; +} AltchaSolver; + +static int hex_nibble(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; +} + +static int hex_decode(const char *hex, unsigned char *out, size_t out_capacity, + size_t *out_length) { + if (!hex || !out || !out_length) + return 0; + + size_t length = strlen(hex); + if ((length % 2) != 0 || length / 2 > out_capacity) + return 0; + + for (size_t i = 0; i < length / 2; i++) { + int high = hex_nibble(hex[i * 2]); + int low = hex_nibble(hex[i * 2 + 1]); + if (high < 0 || low < 0) + return 0; + out[i] = (unsigned char)((high << 4) | low); + } + + *out_length = length / 2; + return 1; +} + +static void hex_encode(const unsigned char *input, size_t length, char *out) { + static const char digits[] = "0123456789abcdef"; + for (size_t i = 0; i < length; i++) { + out[i * 2] = digits[input[i] >> 4]; + out[i * 2 + 1] = digits[input[i] & 0x0f]; + } + out[length * 2] = '\0'; +} + +static void *altcha_solver_worker(void *arg) { + AltchaSolver *solver = (AltchaSolver *)arg; + unsigned char password[ALTCHA_MAX_NONCE_BYTES + 4]; + unsigned char derived[EVP_MAX_MD_SIZE]; + + memcpy(password, solver->nonce, solver->nonce_length); + + while (!atomic_load_explicit(&solver->found, memory_order_relaxed)) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + if (timespec_elapsed_ms(&solver->started, &now) >= solver->timeout_ms) + return NULL; + + unsigned int first = atomic_fetch_add_explicit( + &solver->next_counter, ALTCHA_COUNTER_CHUNK, memory_order_relaxed); + if (first >= ALTCHA_MAX_COUNTER) + return NULL; + + unsigned int last = first + ALTCHA_COUNTER_CHUNK; + if (last > ALTCHA_MAX_COUNTER) + last = ALTCHA_MAX_COUNTER; + + for (unsigned int counter = first; counter < last; counter++) { + struct timespec check; + clock_gettime(CLOCK_MONOTONIC, &check); + if (timespec_elapsed_ms(&solver->started, &check) >= solver->timeout_ms) + return NULL; + + password[solver->nonce_length] = (unsigned char)(counter >> 24); + password[solver->nonce_length + 1] = (unsigned char)(counter >> 16); + password[solver->nonce_length + 2] = (unsigned char)(counter >> 8); + password[solver->nonce_length + 3] = (unsigned char)counter; + + if (PKCS5_PBKDF2_HMAC((const char *)password, + (int)solver->nonce_length + 4, solver->salt, + (int)solver->salt_length, solver->cost, + EVP_sha256(), solver->key_length, + derived) != 1) + continue; + + if (memcmp(derived, solver->prefix, solver->prefix_length) != 0) + continue; + + pthread_mutex_lock(&solver->result_mutex); + if (!atomic_load_explicit(&solver->found, memory_order_relaxed)) { + solver->counter = counter; + hex_encode(derived, (size_t)solver->key_length, solver->derived_hex); + atomic_store_explicit(&solver->found, 1, memory_order_relaxed); + } + pthread_mutex_unlock(&solver->result_mutex); + return NULL; + } + } + + return NULL; +} + +static int solve_altcha_challenge(const char *challenge, char **encoded_out, + long max_timeout_ms) { + char *algorithm = + json_string_after(challenge, "\"parameters\":", "algorithm"); + char *key_prefix_hex = + json_string_after(challenge, "\"parameters\":", "keyPrefix"); + char *nonce_hex = json_string_after(challenge, "\"parameters\":", "nonce"); + char *salt_hex = json_string_after(challenge, "\"parameters\":", "salt"); + int cost = 0; + int key_length = 0; + int has_cost = + json_int_after(challenge, "\"parameters\":", "cost", &cost); + int has_key_length = + json_int_after(challenge, "\"parameters\":", "keyLength", &key_length); + + unsigned char nonce[ALTCHA_MAX_NONCE_BYTES]; + unsigned char salt[ALTCHA_MAX_NONCE_BYTES]; + unsigned char prefix[EVP_MAX_MD_SIZE]; + size_t nonce_length = 0; + size_t salt_length = 0; + size_t prefix_length = 0; + + int valid = algorithm && strncmp(algorithm, "PBKDF2", 6) == 0 && + has_cost && cost > 0 && cost <= 1000000 && has_key_length && + key_length > 0 && key_length <= EVP_MAX_MD_SIZE && + key_prefix_hex && + hex_decode(key_prefix_hex, prefix, sizeof(prefix), + &prefix_length) && + prefix_length > 0 && prefix_length <= (size_t)key_length && + nonce_hex && + hex_decode(nonce_hex, nonce, sizeof(nonce), &nonce_length) && + nonce_length > 0 && salt_hex && + hex_decode(salt_hex, salt, sizeof(salt), &salt_length) && + salt_length > 0; + + free(algorithm); + free(key_prefix_hex); + free(nonce_hex); + free(salt_hex); + + if (!valid || max_timeout_ms <= 0) + return 0; + + AltchaSolver solver = { + .nonce = nonce, + .nonce_length = nonce_length, + .salt = salt, + .salt_length = salt_length, + .prefix = prefix, + .prefix_length = prefix_length, + .cost = cost, + .key_length = key_length, + .timeout_ms = max_timeout_ms > ALTCHA_SOLVER_TIMEOUT_MS + ? ALTCHA_SOLVER_TIMEOUT_MS + : max_timeout_ms, + }; + atomic_init(&solver.next_counter, 0); + atomic_init(&solver.found, 0); + pthread_mutex_init(&solver.result_mutex, NULL); + clock_gettime(CLOCK_MONOTONIC, &solver.started); + + long cpu_count = sysconf(_SC_NPROCESSORS_ONLN); + int thread_count = cpu_count > 0 ? (int)cpu_count : 1; + if (thread_count < 1) + thread_count = 1; + if (thread_count > ALTCHA_MAX_THREADS) + thread_count = ALTCHA_MAX_THREADS; + + pthread_t threads[ALTCHA_MAX_THREADS]; + int started_threads = 0; + for (int i = 0; i < thread_count; i++) { + if (pthread_create(&threads[i], NULL, altcha_solver_worker, &solver) != 0) + break; + started_threads++; + } + + if (started_threads == 0) + altcha_solver_worker(&solver); + + for (int i = 0; i < started_threads; i++) + pthread_join(threads[i], NULL); + + struct timespec finished; + clock_gettime(CLOCK_MONOTONIC, &finished); + long elapsed_ms = timespec_elapsed_ms(&solver.started, &finished); + if (elapsed_ms < 1) + elapsed_ms = 1; + + pthread_mutex_destroy(&solver.result_mutex); + + if (!atomic_load_explicit(&solver.found, memory_order_relaxed)) + return 0; + + size_t payload_size = + strlen(challenge) + sizeof(solver.derived_hex) + 160; + char *payload = malloc(payload_size); + if (!payload) + return 0; + + snprintf(payload, payload_size, + "{\"challenge\":%s,\"solution\":{\"counter\":%u," + "\"derivedKey\":\"%s\",\"time\":%ld}}", + challenge, solver.counter, solver.derived_hex, elapsed_ms); + + size_t payload_length = strlen(payload); + size_t encoded_size = 4 * ((payload_length + 2) / 3) + 1; + char *encoded = malloc(encoded_size); + if (!encoded) { + free(payload); + return 0; + } + + int written = EVP_EncodeBlock((unsigned char *)encoded, + (const unsigned char *)payload, + (int)payload_length); + free(payload); + if (written <= 0) { + free(encoded); + return 0; + } + + *encoded_out = encoded; + return 1; +} + +static char *mojeek_cookie_cache_key(void) { + return cache_compute_key("mojeek", 0, "altcha_cookie_v1"); +} + +static char *load_mojeek_cookie(void) { + char *key = mojeek_cookie_cache_key(); + if (!key) + return NULL; + + char *cookie = NULL; + size_t cookie_size = 0; + int result = cache_get(key, MOJEEK_COOKIE_TTL, &cookie, &cookie_size); + free(key); + + if (result != 0 || !cookie || cookie_size == 0) { + free(cookie); + return NULL; + } + + return cookie; +} + +static void save_mojeek_cookie(const char *cookie) { + if (!cookie || cookie[0] == '\0') + return; + + char *key = mojeek_cookie_cache_key(); + if (!key) + return; + + cache_set(key, cookie, strlen(cookie)); + free(key); +} + +static int perform_mojeek_request(ScrapeJob *job, const char *url, + const struct timespec *deadline_start) { + char *cached_cookie = load_mojeek_cookie(); + if (cached_cookie) { + size_t header_size = strlen(cached_cookie) + sizeof("chllg="); + char *cookie_header = malloc(header_size); + if (cookie_header) { + snprintf(cookie_header, header_size, "chllg=%s", cached_cookie); + curl_easy_setopt(job->handle, CURLOPT_COOKIE, cookie_header); + free(cookie_header); + } + free(cached_cookie); + } + + apply_deadline_timeout(job->handle, deadline_start); + CURLcode result = curl_easy_perform(job->handle); + if (result != CURLE_OK) { + job->results_count = 0; + job->status = SCRAPE_STATUS_FETCH_ERROR; + cleanup_job_handle(job, job->handle); + curl_easy_cleanup(job->handle); + job->handle = NULL; + return 1; + } + + curl_easy_getinfo(job->handle, CURLINFO_RESPONSE_CODE, &job->http_status); + + if (response_is_mojeek_captcha(job, job->response.memory)) { + /* The cached cookie was stale; do not replay it with the new challenge. */ + curl_easy_setopt(job->handle, CURLOPT_COOKIE, NULL); + + struct curl_slist *original_headers = NULL; + curl_easy_getinfo(job->handle, CURLINFO_PRIVATE, &original_headers); + struct curl_slist *captcha_headers = original_headers; + struct curl_slist *appended = curl_slist_append( + captcha_headers, "Accept: application/json, text/plain, */*"); + if (appended) + captcha_headers = appended; + appended = curl_slist_append(captcha_headers, + "X-Requested-With: XMLHttpRequest"); + if (appended) + captcha_headers = appended; + appended = + curl_slist_append(captcha_headers, "Origin: https://www.mojeek.com"); + if (appended) + captcha_headers = appended; + curl_easy_setopt(job->handle, CURLOPT_HTTPHEADER, captcha_headers); + curl_easy_setopt(job->handle, CURLOPT_PRIVATE, captcha_headers); + + if (scrape_time_remaining_ms(deadline_start) > 0) { + job->response.size = 0; + if (job->response.memory) + job->response.memory[0] = '\0'; + curl_easy_setopt(job->handle, CURLOPT_URL, + "https://www.mojeek.com/captcha/challenge"); + curl_easy_setopt(job->handle, CURLOPT_HTTPGET, 1L); + apply_deadline_timeout(job->handle, deadline_start); + if (curl_easy_perform(job->handle) == CURLE_OK) { + char *encoded = NULL; + long solver_timeout = scrape_time_remaining_ms(deadline_start); + if (solve_altcha_challenge(job->response.memory, &encoded, + solver_timeout)) { + char content_type[128]; + snprintf(content_type, sizeof(content_type), + "Content-Type: multipart/form-data; boundary=%s", + ALTCHA_MULTIPART_BOUNDARY); + struct curl_slist *verify_headers = + curl_slist_append(captcha_headers, content_type); + if (verify_headers) { + captcha_headers = verify_headers; + curl_easy_setopt(job->handle, CURLOPT_HTTPHEADER, captcha_headers); + curl_easy_setopt(job->handle, CURLOPT_PRIVATE, captcha_headers); + } + + size_t body_size = strlen(encoded) + 256; + char *body = malloc(body_size); + if (body) { + int body_length = snprintf( + body, body_size, + "--%s\r\n" + "Content-Disposition: form-data; name=\"altcha\"\r\n" + "\r\n" + "%s\r\n" + "--%s--\r\n", + ALTCHA_MULTIPART_BOUNDARY, encoded, ALTCHA_MULTIPART_BOUNDARY); + if (body_length > 0 && (size_t)body_length < body_size) { + job->response.size = 0; + if (job->response.memory) + job->response.memory[0] = '\0'; + curl_easy_setopt(job->handle, CURLOPT_URL, + "https://www.mojeek.com/captcha/verify"); + curl_easy_setopt(job->handle, CURLOPT_POSTFIELDS, body); + curl_easy_setopt(job->handle, CURLOPT_POSTFIELDSIZE, + (long)body_length); + curl_easy_setopt(job->handle, CURLOPT_POST, 1L); + apply_deadline_timeout(job->handle, deadline_start); + if (curl_easy_perform(job->handle) == CURLE_OK && + response_contains(job->response.memory, "\"ok\":true") && + response_contains(job->response.memory, + "\"verified\":true")) { + char *auth_cookie = + cookie_value_from_jar(job->handle, "chllg"); + if (auth_cookie) { + save_mojeek_cookie(auth_cookie); + free(auth_cookie); + } + } + curl_easy_setopt(job->handle, CURLOPT_POSTFIELDS, NULL); + curl_easy_setopt(job->handle, CURLOPT_POSTFIELDSIZE, -1L); + } + free(body); + } + free(encoded); + } + } + } + + /* Restore the original request headers and fetch the search page again. */ + struct curl_slist *final_headers = build_request_headers( + job->engine->host_header, job->engine->referer); + if (final_headers) { + curl_easy_setopt(job->handle, CURLOPT_HTTPHEADER, final_headers); + curl_easy_setopt(job->handle, CURLOPT_PRIVATE, final_headers); + curl_slist_free_all(captcha_headers); + } + + if (scrape_time_remaining_ms(deadline_start) > 0) { + job->response.size = 0; + if (job->response.memory) + job->response.memory[0] = '\0'; + curl_easy_setopt(job->handle, CURLOPT_URL, url); + curl_easy_setopt(job->handle, CURLOPT_HTTPGET, 1L); + apply_deadline_timeout(job->handle, deadline_start); + if (curl_easy_perform(job->handle) == CURLE_OK) + curl_easy_getinfo(job->handle, CURLINFO_RESPONSE_CODE, + &job->http_status); + else + job->status = SCRAPE_STATUS_FETCH_ERROR; + } + } + + parse_and_cache_response(job); + cleanup_job_handle(job, job->handle); + curl_easy_cleanup(job->handle); + job->handle = NULL; + return 1; +} + +static int perform_startpage_request(ScrapeJob *job, const char *url, + const struct timespec *deadline_start) { + char *cached_cookie = load_startpage_cookie(); + if (cached_cookie) { + size_t header_size = strlen(cached_cookie) + sizeof("spchal-auth="); + char *cookie_header = malloc(header_size); + if (cookie_header) { + snprintf(cookie_header, header_size, "spchal-auth=%s", cached_cookie); + curl_easy_setopt(job->handle, CURLOPT_COOKIE, cookie_header); + free(cookie_header); + } + free(cached_cookie); + } + + apply_deadline_timeout(job->handle, deadline_start); CURLcode result = curl_easy_perform(job->handle); if (result != CURLE_OK) { job->results_count = 0; @@ -535,6 +1029,9 @@ static int perform_startpage_request(ScrapeJob *job, const char *url) { curl_easy_getinfo(job->handle, CURLINFO_RESPONSE_CODE, &job->http_status); if (response_contains(job->response.memory, "anubis_challenge")) { + /* The cached cookie was stale; do not replay it with the new challenge. */ + curl_easy_setopt(job->handle, CURLOPT_COOKIE, NULL); + char *algorithm = json_string_after(job->response.memory, "\"rules\":", "algorithm"); char *random_data = json_string_after(job->response.memory, @@ -545,12 +1042,18 @@ static int perform_startpage_request(ScrapeJob *job, const char *url) { int has_difficulty = json_int_after(job->response.memory, "\"rules\":", "difficulty", &difficulty); + long solver_timeout = scrape_time_remaining_ms(deadline_start); + if (solver_timeout > ANUBIS_SOLVER_TIMEOUT_MS) + solver_timeout = ANUBIS_SOLVER_TIMEOUT_MS; + if (algorithm && strcmp(algorithm, "fast") == 0 && random_data && - challenge_id && has_difficulty && difficulty >= 0) { + challenge_id && has_difficulty && difficulty >= 0 && + solver_timeout > 0) { char nonce[32]; long elapsed_ms = 1; - char *response_hash = solve_anubis_challenge( - random_data, difficulty, nonce, sizeof(nonce), &elapsed_ms); + char *response_hash = + solve_anubis_challenge(random_data, difficulty, solver_timeout, + nonce, sizeof(nonce), &elapsed_ms); if (response_hash) { char *escaped_redir = curl_easy_escape(NULL, url, 0); @@ -572,9 +1075,18 @@ static int perform_startpage_request(ScrapeJob *job, const char *url) { if (job->response.memory) job->response.memory[0] = '\0'; curl_easy_setopt(job->handle, CURLOPT_URL, pass_url); - if (curl_easy_perform(job->handle) == CURLE_OK) + apply_deadline_timeout(job->handle, deadline_start); + if (curl_easy_perform(job->handle) == CURLE_OK) { curl_easy_getinfo(job->handle, CURLINFO_RESPONSE_CODE, &job->http_status); + + char *auth_cookie = + cookie_value_from_jar(job->handle, "spchal-auth"); + if (auth_cookie) { + save_startpage_cookie(auth_cookie); + free(auth_cookie); + } + } free(pass_url); } curl_free(escaped_redir); @@ -611,7 +1123,8 @@ static int process_response(ScrapeJob *job, CURL *handle, CURLcode result) { return 0; } -int setup_job(ScrapeJob *job, CURLM *multi_handle) { +int setup_job(ScrapeJob *job, CURLM *multi_handle, + const struct timespec *deadline_start) { cleanup_job_handle(job, job->handle); if (job->handle) curl_easy_cleanup(job->handle); @@ -649,8 +1162,9 @@ int setup_job(ScrapeJob *job, CURLM *multi_handle) { build_search_url(job->engine->base_url, job->engine->page_param, job->engine->page_multiplier, job->engine->page_base, encoded_query, job->page); - int configured = - full_url ? configure_job_request(job, full_url, encoded_query) : -1; + int configured = full_url + ? configure_job_request(job, full_url, deadline_start) + : -1; free(full_url); curl_free(encoded_query); @@ -732,6 +1246,8 @@ int should_retry(ScrapeJob *jobs, int num_jobs) { int scrape_engines_parallel(ScrapeJob *jobs, int num_jobs) { int retries = 0; + struct timespec deadline_start; + clock_gettime(CLOCK_MONOTONIC, &deadline_start); retry:; CURLM *multi_handle = curl_multi_init(); @@ -739,7 +1255,7 @@ retry:; return -1; for (int i = 0; i < num_jobs; i++) { - setup_job(&jobs[i], multi_handle); + setup_job(&jobs[i], multi_handle, &deadline_start); } http_delay(); @@ -757,8 +1273,13 @@ retry:; if (!active) break; + long remaining = scrape_time_remaining_ms(&deadline_start); + if (remaining <= 0) + break; + + int wait_ms = remaining > 1000 ? 1000 : (int)remaining; int numfds = 0; - mc = curl_multi_wait(multi_handle, NULL, 0, 1000, &numfds); + mc = curl_multi_wait(multi_handle, NULL, 0, wait_ms, &numfds); if (mc != CURLM_OK) break; } @@ -766,7 +1287,8 @@ retry:; cleanup_unfinished_jobs(multi_handle, jobs, num_jobs); curl_multi_cleanup(multi_handle); - if (retries < max_proxy_retries && should_retry(jobs, num_jobs)) { + if (retries < max_proxy_retries && should_retry(jobs, num_jobs) && + scrape_time_remaining_ms(&deadline_start) > 0) { retries++; goto retry; } diff --git a/src/Scraping/Scraping.h b/src/Scraping/Scraping.h index aeff855..378b6a1 100644 --- a/src/Scraping/Scraping.h +++ b/src/Scraping/Scraping.h @@ -66,13 +66,11 @@ void configure_yacy_engine(const char *instance); size_t write_memory_callback(void *contents, size_t size, size_t nmemb, void *userp); const char *get_random_user_agent(void); -const char *get_first_user_agent(void); void configure_curl_handle(CURL *curl, const char *full_url, MemoryBuffer *chunk, struct curl_slist *headers); char *build_search_url(const char *base_url, const char *page_param, int page_multiplier, int page_base, const char *encoded_query, int page); -char *build_ddg_next_page_data(const char *html, size_t size); struct curl_slist *build_request_headers(const char *host_header, const char *referer); void http_delay(void); diff --git a/src/Scraping/ScrapingHttp.c b/src/Scraping/ScrapingHttp.c index fd0e635..41cc5b0 100644 --- a/src/Scraping/ScrapingHttp.c +++ b/src/Scraping/ScrapingHttp.c @@ -1,4 +1,5 @@ #include "../Proxy/Proxy.h" +#include "../Utility/HttpClient.h" #include "Config.h" #include "Scraping.h" #include @@ -53,27 +54,30 @@ 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); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_memory_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk); - curl_easy_setopt(curl, CURLOPT_USERAGENT, get_random_user_agent()); - /* Yahoo currently answers HTTP/2 requests with a 500 error. HTTP/1.1 is - accepted by all of the scraped engines, so use it everywhere. */ - curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, CURL_DNS_TIMEOUT_SECS); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT_SECS); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CURL_CONNECT_TIMEOUT_SECS); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); apply_proxy_settings(curl); + +#ifdef OMNISEARCH_USE_CURL_IMPERSONATE + http_apply_browser_impersonation(curl); +#else + curl_easy_setopt(curl, CURLOPT_USERAGENT, get_random_user_agent()); + /* Yahoo currently answers plain HTTP/2 requests with a 500 error. */ + curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); +#endif } char *build_search_url(const char *base_url, const char *page_param, @@ -89,69 +93,6 @@ char *build_search_url(const char *base_url, const char *page_param, 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; @@ -165,12 +106,15 @@ struct curl_slist *build_request_headers(const char *host_header, snprintf(ref_buf, sizeof(ref_buf), "Referer: %s", referer); headers = curl_slist_append(headers, ref_buf); } + +#ifndef OMNISEARCH_USE_CURL_IMPERSONATE headers = curl_slist_append( headers, "Accept: " "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headers = curl_slist_append(headers, "Accept-Language: en-US,en;q=0.5"); headers = curl_slist_append(headers, "DNT: 1"); +#endif return headers; } diff --git a/src/Utility/HttpClient.c b/src/Utility/HttpClient.c index 0ffb9ff..bfc86c4 100644 --- a/src/Utility/HttpClient.c +++ b/src/Utility/HttpClient.c @@ -2,9 +2,27 @@ #include "../Cache/Cache.h" #include "../Proxy/Proxy.h" #include "Config.h" +#include #include #include +void http_apply_browser_impersonation(CURL *curl) { +#ifdef OMNISEARCH_USE_CURL_IMPERSONATE + const char *target = getenv("OMNISEARCH_IMPERSONATE_TARGET"); + if (!target || target[0] == '\0') + target = DEFAULT_IMPERSONATE_TARGET; + + CURLcode result = curl_easy_impersonate(curl, target, 1); + if (result != CURLE_OK) { + fprintf(stderr, + "[WARN] curl-impersonate target '%s' failed: %s; using defaults\n", + target, curl_easy_strerror(result)); + } +#else + (void)curl; +#endif +} + static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; @@ -32,6 +50,10 @@ static size_t write_callback(void *contents, size_t size, size_t nmemb, } static struct curl_slist *build_http_headers(void) { +#ifdef OMNISEARCH_USE_CURL_IMPERSONATE + /* curl-impersonate supplies a complete, browser-consistent header set. */ + return NULL; +#else struct curl_slist *headers = NULL; headers = curl_slist_append( headers, @@ -40,6 +62,7 @@ static struct curl_slist *build_http_headers(void) { headers = curl_slist_append(headers, "Accept-Language: en-US,en;q=0.5"); headers = curl_slist_append(headers, "DNT: 1"); return headers; +#endif } HttpResponse http_get(const char *url, const char *user_agent) { @@ -68,16 +91,23 @@ HttpResponse http_get(const char *url, const char *user_agent) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp); - curl_easy_setopt(curl, CURLOPT_USERAGENT, - user_agent ? user_agent : "libcurl-agent/1.0"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT_SECS); - curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CURL_CONNECT_TIMEOUT_SECS); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, CURL_DNS_TIMEOUT_SECS); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); apply_proxy_settings(curl); +#ifdef OMNISEARCH_USE_CURL_IMPERSONATE + (void)user_agent; + http_apply_browser_impersonation(curl); +#else + curl_easy_setopt(curl, CURLOPT_USERAGENT, + user_agent ? user_agent : "libcurl-agent/1.0"); + curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); +#endif + CURLcode res = curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); diff --git a/src/Utility/HttpClient.h b/src/Utility/HttpClient.h index 5eceb83..ec45b35 100644 --- a/src/Utility/HttpClient.h +++ b/src/Utility/HttpClient.h @@ -15,6 +15,9 @@ typedef struct { HttpResponse http_get(const char *url, const char *user_agent); void http_response_free(HttpResponse *resp); +/* Apply a browser TLS/HTTP fingerprint when built against curl-impersonate. */ +void http_apply_browser_impersonation(CURL *curl); + typedef xmlDocPtr (*XmlParserFn)(const char *data, size_t size, const char *url);