00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027 #include <PVLE/Network/HTTP/Utility.h>
00028
00029 #ifdef PVLE_URL
00030
00031 #include <PVLE/Util/Log.h>
00032
00033 #include <boost/algorithm/string/case_conv.hpp>
00034
00035 namespace Net {
00036
00037 void URLOptions::setProxyType(std::string strType) {
00038 boost::algorithm::to_lower(strType);
00039 if (strType == "http") proxyType = PROXY_HTTP;
00040 else if (strType == "socks4") proxyType = PROXY_SOCKS4;
00041 else if (strType == "socks5") proxyType = PROXY_SOCKS5;
00042 else if (strType == "socks4a") proxyType = PROXY_SOCKS4A;
00043 else if (strType == "socks5h" || strType == "socks5hostname") proxyType = PROXY_SOCKS5_HOSTNAME;
00044 else LOG_WARN << "Could not interpret proxy type: " << strType;
00045 }
00046
00047
00048 CURLHolder::CURLHolder() {
00049 handle = curl_easy_init();
00050 #ifdef WIN32
00051 curl_global_init(CURL_GLOBAL_WIN32);
00052 #else
00053 curl_global_init(CURL_GLOBAL_NOTHING);
00054 #endif
00055 }
00056
00057 CURLHolder::~CURLHolder() {
00058 curl_easy_cleanup(handle);
00059 }
00060
00061
00062 void applyOptions(const URLOptions & options) {
00063 CURL * curlHandle = CURLHolder::instance();
00064
00065 curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1);
00066 curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, "PVLE C++ library (uses libcurl)");
00067 curl_easy_setopt(curlHandle, CURLOPT_FAILONERROR, 1);
00068 #ifdef _DEBUG
00069
00070 #endif
00071
00072 if (options.usesProxy()) {
00073 curl_easy_setopt(curlHandle, CURLOPT_PROXYPORT, options.getProxyPort());
00074 curl_easy_setopt(curlHandle, CURLOPT_PROXY, options.getProxyAddress().c_str());
00075 curl_easy_setopt(curlHandle, CURLOPT_PROXYTYPE, options.getProxyType());
00076 } else {
00077 curl_easy_setopt(curlHandle, CURLOPT_PROXY, "");
00078 }
00079 curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, options.getTimeout());
00080
00081
00082 }
00083
00084
00085 std::size_t readURLAsStringCBf(void *ptr, std::size_t size, std::size_t nmemb, void *stream) {
00086 *reinterpret_cast<std::string *>(stream) += static_cast<const char *>(ptr);
00087 return nmemb;
00088 }
00089
00090
00091 std::string readURLAsString(const std::string & url, const URLOptions & options) {
00092
00093 CURL * curlHandle = CURLHolder::instance();
00094
00095 std::string result;
00096 curl_easy_setopt(curlHandle, CURLOPT_URL, url.c_str());
00097
00098 curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, &readURLAsStringCBf);
00099 curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &result);
00100
00101
00102 applyOptions(options);
00103
00104 curl_easy_perform(curlHandle);
00105
00106
00107 long response = 0;
00108 curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &response);
00109 return response>=400 ? "" : result;
00110 }
00111
00112
00113 }
00114
00115 #endif // PVLE_URL