Re: Using the SSL module.
Chris Angelico <[email protected]>
| Newsgroups | gmane.comp.lang.pike.user |
|---|---|
| Message-ID | <CAPTjJmroKv=UgWyXtsXJ1cU_192TSdA+-5s-tNK2fkoHOznJiA@mail.gmail.com> |
On Mon, Jun 22, 2015 at 4:34 PM, Trilok Tourani <[email protected]> wrote: > Thanks Chris. Any example would be great. Okay. Got around to dusting off some old code and making sure it actually, yaknow, works. This is written for Pike 8.1, so you may need to make some changes for 7.8. void http_query(Protocols.HTTP.Server.Request r) { write("Request for %s\n",r->not_query); r->response_and_finish((["data":"You requested: "+r->not_query,"type":"text/plain"])); } void sockread(object sock,string data) { write("[%d] Data received: %O\n",hash_value(sock),data); if (String.trim_all_whites(data)=="quit") {sock->write("Bye!\n"); sock->close();} else sock->write("Uh huh.\n"); } void sockgone(object sock) { write("[%d] Disconnected.\n",hash_value(sock)); } object mainsock; void accept(object sock) { mainsock->accept(); //Will return sock, same as the argument. Dunno why we get it both ways. write("[%d] New connection from %s\n",hash_value(sock),sock->query_address()); sock->set_read_callback(sockread); sock->set_close_callback(sockgone); sock->set_id(sock); sock->write("Hello, world!\n"); } int main() { //Load up three files... //1) Certificate chain from the CSA sscanf(Stdio.read_file("gd_bundle.crt"),"%{%*s-----BEGIN CERTIFICATE-----%s-----END CERTIFICATE-----%}",array certs); certs=MIME.decode_base64(certs[*][0][*]); //2) Our certificate sscanf(Stdio.read_file("demo.crt"),"%*s-----BEGIN CERTIFICATE-----%s-----END CERTIFICATE-----",string crt); certs=({MIME.decode_base64(crt)})+certs; //Ours first, chain following it //3) Our private key sscanf(Stdio.read_file("demo.key"),"%*s-----BEGIN RSA PRIVATE KEY-----%s-----END RSA PRIVATE KEY-----",string key); key=MIME.decode_base64(key); write("Keys loaded successfully.\n"); Protocols.HTTP.Server.SSLPort(http_query,443,"::",key,certs); object ctx=SSL.Context(); ctx->add_cert(Standards.PKCS.RSA.parse_private_key(key),certs,({"*"})); mainsock=SSL.Port(ctx); mainsock->bind(1234,accept,"::"); write("Listening on ports 443 and 1234.\n"); return -1; } This is a dual server - HTTPS and a TLS-enabled telnet-like connection. For this, I used a certificate that I bought from GoDaddy, so the authority chain comes from the GoDaddy certificate bundle (gd_bundle.crt). Using a self-signed cert would also work, and as Grubba pointed out, Pike is quite capable of generating those. It's pretty simple, and might even be simpler than I've shown here. Note the one liner to set up HTTPS hosting... a simple reactive function to handle requests, and you can completely ignore SSL and just work with the requests themselves. ChrisA