const failable setup()

in modules/http/http.hpp [269:340]


const failable<CURL*> setup(const string& url, const CURLSession& cs) {

    // Init CURL session
    if (cs.h.h != NULL)
        cleanup(cs);
    cs.h.h = curl_easy_init();
    debug(cs.h.h, "http::setup::init::h");
    CURL* const ch = cs.h.h;
    curl_easy_setopt(ch, CURLOPT_USERAGENT, "libcurl/1.0");
#ifdef WANT_MAINTAINER_CURL_VERBOSE
    curl_easy_setopt(ch, CURLOPT_VERBOSE, true);
#endif

    // Setup protocol options
    curl_easy_setopt(ch, CURLOPT_TCP_NODELAY, true);
    curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, true);
    curl_easy_setopt(ch, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
    curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
    curl_easy_setopt(ch, CURLOPT_TIMEOUT, cs.timeout);

    // Setup SSL options
    if (cs.ca != emptyString) {
        debug(cs.ca, "http::setup::ca");
        curl_easy_setopt(ch, CURLOPT_CAINFO, c_str(cs.ca));
        curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 2);
    } else
        curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, false);
    if (cs.cert != emptyString) {
        debug(cs.cert, "http::setup::cert");
        curl_easy_setopt(ch, CURLOPT_SSLCERT, c_str(cs.cert));
        curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM");
    }
    if (cs.key != emptyString) {
        debug(cs.key, "http::setup::key");
        curl_easy_setopt(ch, CURLOPT_SSLKEY, c_str(cs.key));
        curl_easy_setopt(ch, CURLOPT_SSLKEYTYPE, "PEM");
    }
    if (cs.cookie != emptyString) {
        debug(cs.cookie, "http::setup::cookie");
        curl_easy_setopt(ch, CURLOPT_COOKIE, c_str(cs.cookie));
    }

    // Set up HTTP basic auth if requested
    apr_uri_t u;
    apr_pool_t* const p = gc_current_pool();
    const apr_status_t prc = apr_uri_parse(p, c_str(url), &u);
    if (prc == APR_SUCCESS) {
        if (u.user != NULL) {
            debug(u.user, "http::setup::user");
            curl_easy_setopt(ch, CURLOPT_USERNAME, u.user);
        }
        if (u.password != NULL) {
            debug(u.password, "http::setup::pass");
            curl_easy_setopt(ch, CURLOPT_PASSWORD, u.password);
        }
        if (u.user != NULL || u.password != NULL) {
            curl_easy_setopt(ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            
            // Set target URL, omitting the user:password part
            curl_easy_setopt(ch, CURLOPT_URL, c_str(escapeURI(apr_uri_unparse(p, &u, APR_URI_UNP_OMITUSERINFO))));

            return ch;
        }
    }

    // Set target URL
    curl_easy_setopt(ch, CURLOPT_URL, c_str(escapeURI(url)));

    return ch;
}