Running libcurl http request from DllMain() in a DLL file on a separate thread

131 views Asked by At
#pragma once
#include <curl/curl.h>
#include <spdlog/spdlog.h>

#include <string>

#include "json.hpp"

inline std::string GetData() {
  CURL* curl = curl_easy_init();
  std::ofstream file;
  file.open("C:/google_logs/test10.txt");
  file << "t";
  file.close();
  if (curl) {
      std::string all_game_data_url =
          "https://google.com";
      curl_easy_setopt(curl, CURLOPT_URL, all_game_data_url);
      curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
      curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
      curl_easy_setopt(curl, CURLOPT_VERBOSE, TRUE);
      
      FILE* filep = fopen("c:\\google_logs\\dump", "wb");
      curl_easy_setopt(curl, CURLOPT_STDERR, filep);

      std::string response_body;
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_body);

      long response_code;
      curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
      
      spdlog::error("Response code: {:d}", response_code);
      CURLcode response = curl_easy_perform(curl);
      
      std::ofstream file;
      file.open("C:/google_logs/test19.txt");
      file << response;
      file.close();
      

      if (response != CURLE_OK) {
        spdlog::error("curl_easy_perform() failed: {:s}",
                      curl_easy_strerror(response));
        
        std::ofstream file;
        file.open("C:/google_logs/test14.txt");
        file << curl_easy_strerror(response);
        file.close();

      }

      curl_easy_cleanup(curl);

      return response_body;
  }
  return std::string();
}

It keeps hanging when curl_easy_perform is called, then it times out, and nothing is returned.

1

There are 1 answers

2
Andreas Wenzel On

When using the function curl_easy_setopt with the argument CURLOPT_URL, it expects a pointer to a C-style string (array of characters terminated by a null character) as the third argument. However, you are instead passing it a std::string.

Since curl_easy_set_opt is a variadic function, the std::string argument will not automatically be converted to a C-style string.

Therefore, I recommend that you change the line

curl_easy_setopt(curl, CURLOPT_URL, all_game_data_url);

to:

curl_easy_setopt(curl, CURLOPT_URL, all_game_data_url.c_str() );

It is also worth noting that creating a thread in DLLMain is risky. See this link for further information.