Instantly share code, notes, and snippets.
SSL and cookie handling with libcurl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <curl/curl.h> | |
/* Compiling example: | |
* | |
* gcc -o curltest curl_ssl_cookies.c -L./lib/ -I./lib/include -lcurl -Wl,-rpath ./lib | |
* | |
*/ | |
/* Example cookie handling copied from: | |
* http://curl.haxx.se/libcurl/c/cookie_interface.html | |
* Example SSL request adapted from: | |
* http://curl.haxx.se/libcurl/c/https.html | |
*/ | |
static void print_cookies(CURL *curl) | |
{ | |
CURLcode res; | |
struct curl_slist *cookies; | |
struct curl_slist *nc; | |
int i; | |
printf("Cookies, curl knows:\n"); | |
res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies); | |
if (res != CURLE_OK) { | |
fprintf(stderr, "Curl curl_easy_getinfo failed: %s\n", curl_easy_strerror(res)); | |
return; | |
} | |
nc = cookies, i = 1; | |
while (nc) { | |
printf("[%d]: %s\n", i, nc->data); | |
nc = nc->next; | |
i++; | |
} | |
if (i == 1) { | |
printf("(none)\n"); | |
} | |
curl_slist_free_all(cookies); | |
} | |
void download(const char* url, const char* cert) | |
{ | |
CURL *curl; | |
CURLcode res; | |
curl_global_init(CURL_GLOBAL_DEFAULT); | |
curl = curl_easy_init(); | |
if (curl) | |
{ | |
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); | |
// make sure to verify everything | |
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); | |
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); // yes, 2L is the correct value | |
curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, "PEM"); | |
curl_easy_setopt(curl, CURLOPT_CAINFO, cert); | |
// if you are using OpenSSL, this option may be useful to you: | |
//curl_easy_setopt(curl, CURLOPT_CAPATH, "./assets/certs/"); | |
curl_easy_setopt(curl, CURLOPT_URL, url); | |
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); /* just to start the cookie engine */ | |
/* Perform the request, res will get the return code */ | |
res = curl_easy_perform(curl); | |
/* Check for errors */ | |
if (res != CURLE_OK) | |
fprintf(stderr, "curl_easy_perform() failed: %s\n", | |
curl_easy_strerror(res)); | |
print_cookies(curl); | |
printf("Erasing curl's knowledge of cookies!\n"); | |
curl_easy_setopt(curl, CURLOPT_COOKIELIST, "ALL"); | |
print_cookies(curl); | |
/* always cleanup */ | |
curl_easy_cleanup(curl); | |
} | |
curl_global_cleanup(); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
if (argc < 3) | |
{ | |
printf("Usage: %s <url> <pem>\n", argv[0]); | |
return 1; | |
} | |
download(argv[1], argv[2]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment