Skip to content

Instantly share code, notes, and snippets.

@pprince

pprince/curl.pl Secret

Last active March 29, 2016 07:06
Show Gist options
  • Save pprince/208f3218852e9ee59876 to your computer and use it in GitHub Desktop.
Save pprince/208f3218852e9ee59876 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
use Net::Curl::NativeCall;
use NativeCall;
#my sub memcpy(Pointer $dest, Pointer $src, size_t $size)
# returns Pointer is native() { * };
constant EmailPassword = 'FIXME';
constant FROM = 'perl6bug@gmail.com';
constant TO = 'madcap.russo@gmail.com';
constant CC = 'jake.russo@zoho.com';
constant MESG = "Hello!\n";
# my Str $MESG = "Hello!\n";
with curl_easy_init() {
curl_easy_setopt($_, CURLOPT_USERNAME, FROM);
curl_easy_setopt($_, CURLOPT_PASSWORD, EmailPassword);
curl_easy_setopt($_, CURLOPT_URL, 'smtp://smtp.gmail.com:587');
curl_easy_setopt($_, CURLOPT_USE_SSL, CURLUSESSL_ALL);
curl_easy_setopt($_, CURLOPT_CAINFO, 'vendor/smtp-gmail.pem');
curl_easy_setopt($_, CURLOPT_MAIL_FROM, FROM);
my $recipients = curl_slist_append(curl_slist, TO);
$recipients = curl_slist_append($recipients, CC);
curl_easy_setopt($_, CURLOPT_MAIL_RCPT, $recipients);
# ... might have to handle context like this ...
# (I am not sure whether the callback function can be a closure.)
#
# class ReadCallbackContext is repr('CStruct') {
# has size_t $.position;
# has CArray[uint8] $.src-buf;
# }
# my Pointer[ReadCallbackContext] $context = ReadCallbackContext.new(:position=0, :src-buf=$src-buf);
my size_t $context = 0;
curl_easy_setopt($_, CURLOPT_READDATA, $context);
my utf8 $src-buf = MESG.encode('UTF-8');
#or perhaps: my $src-buf = CArray[uint8].new($msgstr.encode.('UTF-8').list);
# size_t read_callback(char *buffer, size_t size, size_t nitems, void *ptr)
sub read_callback(
CArray[uint8] $dst-buf, # This function will copy date into $dst-buf,
size_t $itemsize, # up to $itemsize * #numitems bytes on each
size_t $numitems, # invovation.
size_t $pos is rw) # Can be used to track state between calls.
returns size_t is native() # Returns number of bytes copied (this invocation.)
{
my $bytes-wanted = $itemsize * $numitems;
my $bytes-remain = $src-buf.elems - $pos;
my $bytes-to-copy = min $bytes-wanted, $bytes-remain;
return 0 unless $bytes-to-copy > 0;
$dst-buf[$_] = $src-buf[$_] for $pos..^($pos + $bytes-to-copy);
$pos += $bytes-to-copy;
return $bytes-to-copy;
}
curl_easy_setopt($_, CURLOPT_READFUNCTION, &read_callback);
} else { warn "curl failed to initialize" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment