/* ssl/ssl_task.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* VMS */ /* * DECnet object for servicing SSL. We accept the inbound and speak a * simple protocol for multiplexing the 2 data streams (application and * ssl data) over this logical link. * * Logical names: * SSL_CIPHER Defines a list of cipher specifications the server * will support in order of preference. * SSL_SERVER_CERTIFICATE * Points to PEM (privacy enhanced mail) file that * contains the server certificate and private password. * SYS$NET Logical created by netserver.exe as hook for completing * DECnet logical link. * * Each NSP message sent over the DECnet link has the following structure: * struct rpc_msg { * char channel; * char function; * short length; * char data[MAX_DATA]; * } msg; * * The channel field designates the virtual data stream this message applies * to and is one of: * A - Application data (payload). * R - Remote client connection that initiated the SSL connection. Encrypted * data is sent over this connection. * G - General data, reserved for future use. * * The data streams are half-duplex read/write and have following functions: * G - Get, requests that up to msg.length bytes of data be returned. The * data is returned in the next 'C' function response that matches the * requesting channel. * P - Put, requests that the first msg.length bytes of msg.data be appended * to the designated stream. * C - Confirms a get or put. Every get and put will get a confirm response, * you cannot initiate another function on a channel until the previous * operation has been confirmed. * * The 2 channels may interleave their operations, for example: * Server msg Client msg * A, Get, 4092 ----> * <---- R, get, 4092 * R, Confirm, {hello} ----> * <---- R, put, {srv hello} * R, Confirm, 0 ----> * . (SSL handshake completed) * . (read first app data). * <---- A, confirm, {http data} * A, Put, {http data} ----> * <---- A, confirm, 0 * * The length field is not permitted to be larger that 4092 bytes. * * Author: Dave Jones * Date: 22-JUL-1996 */ #include #include #include /* VMS IO$_ definitions */ #include /* VMS string descriptors */ extern int SYS$QIOW(), SYS$ASSIGN(); int LIB$INIT_TIMER(), LIB$SHOW_TIMER(); #include /* from ssltest.c */ #include #include "e_os.h" #include #include #include #include int MS_CALLBACK verify_callback(int ok, X509 *xs, X509 *xi, int depth, int error); BIO *bio_err=NULL; BIO *bio_stdout=NULL; BIO_METHOD *BIO_s_rtcp(); static char *cipher=NULL; int verbose=1; #ifdef FIONBIO static int s_nbio=0; #endif #define TEST_SERVER_CERT "SSL_SERVER_CERTIFICATE" /*************************************************************************/ struct rpc_msg { /* Should have member alignment inhibited */ char channel; /* 'A'-app data. 'R'-remote client 'G'-global */ char function; /* 'G'-get, 'P'-put, 'C'-confirm, 'X'-close */ unsigned short int length; /* Amount of data returned or max to return */ char data[4092]; /* variable data */ }; #define RPC_HDR_SIZE (sizeof(struct rpc_msg) - 4092) static $DESCRIPTOR(sysnet, "SYS$NET"); typedef unsigned short io_channel; struct io_status { unsigned short status; unsigned short count; unsigned long stsval; }; int doit(io_channel chan, SSL_CTX *s_ctx ); /*****************************************************************************/ /* Decnet I/O routines. */ static int get ( io_channel chan, char *buffer, int maxlen, int *length ) { int status; struct io_status iosb; status = SYS$QIOW ( 0, chan, IO$_READVBLK, &iosb, 0, 0, buffer, maxlen, 0, 0, 0, 0 ); if ( (status&1) == 1 ) status = iosb.status; if ( (status&1) == 1 ) *length = iosb.count; return status; } static int put ( io_channel chan, char *buffer, int length ) { int status; struct io_status iosb; status = SYS$QIOW ( 0, chan, IO$_WRITEVBLK, &iosb, 0, 0, buffer, length, 0, 0, 0, 0 ); if ( (status&1) == 1 ) status = iosb.status; return status; } /***************************************************************************/ /* Handle operations on the 'G' channel. */ static int general_request ( io_channel chan, struct rpc_msg *msg, int length ) { return 48; } /***************************************************************************/ int main ( int argc, char **argv ) { int status, length; io_channel chan; struct rpc_msg msg; char *CApath=NULL,*CAfile=NULL; int badop=0; int ret=1; int client_auth=0; int server_auth=0; SSL_CTX *s_ctx=NULL; /* * Confirm logical link with initiating client. */ LIB$INIT_TIMER(); status = SYS$ASSIGN ( &sysnet, &chan, 0, 0, 0 ); printf("status of assign to SYS$NET: %d\n", status ); /* * Initialize standard out and error files. */ if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE); if (bio_stdout == NULL) if ((bio_stdout=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_stdout,stdout,BIO_NOCLOSE); /* * get the preferred cipher list and other initialization */ if (cipher == NULL) cipher=getenv("SSL_CIPHER"); printf("cipher list: %s\n", cipher ? cipher : "{undefined}" ); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); /* DRM, this was the original, but there is no such thing as SSLv2() s_ctx=SSL_CTX_new(SSLv2()); */ s_ctx=SSL_CTX_new(SSLv2_server_method()); if (s_ctx == NULL) goto end; SSL_CTX_use_certificate_file(s_ctx,TEST_SERVER_CERT,SSL_FILETYPE_PEM); SSL_CTX_use_RSAPrivateKey_file(s_ctx,TEST_SERVER_CERT,SSL_FILETYPE_PEM); printf("Loaded server certificate: '%s'\n", TEST_SERVER_CERT ); /* * Take commands from client until bad status. */ LIB$SHOW_TIMER(); status = doit ( chan, s_ctx ); LIB$SHOW_TIMER(); /* * do final cleanup and exit. */ end: if (s_ctx != NULL) SSL_CTX_free(s_ctx); LIB$SHOW_TIMER(); return 1; } int doit(io_channel chan, SSL_CTX *s_ctx ) { int status, length, link_state; struct rpc_msg msg; SSL *s_ssl=NULL; BIO *c_to_s=NULL; BIO *s_to_c=NULL; BIO *c_bio=NULL; BIO *s_bio=NULL; int i; int done=0; s_ssl=SSL_new(s_ctx); if (s_ssl == NULL) goto err; c_to_s=BIO_new(BIO_s_rtcp()); s_to_c=BIO_new(BIO_s_rtcp()); if ((s_to_c == NULL) || (c_to_s == NULL)) goto err; /* original, DRM 24-SEP-1997 BIO_set_fd ( c_to_s, "", chan ); BIO_set_fd ( s_to_c, "", chan ); */ BIO_set_fd ( c_to_s, 0, chan ); BIO_set_fd ( s_to_c, 0, chan ); c_bio=BIO_new(BIO_f_ssl()); s_bio=BIO_new(BIO_f_ssl()); if ((c_bio == NULL) || (s_bio == NULL)) goto err; SSL_set_accept_state(s_ssl); SSL_set_bio(s_ssl,c_to_s,s_to_c); BIO_set_ssl(s_bio,s_ssl,BIO_CLOSE); /* We can always do writes */ printf("Begin doit main loop\n"); /* * Link states: 0-idle, 1-read pending, 2-write pending, 3-closed. */ for (link_state = 0; link_state < 3; ) { /* * Wait for remote end to request data action on A channel. */ while ( link_state == 0 ) { status = get ( chan, (char *) &msg, sizeof(msg), &length ); if ( (status&1) == 0 ) { printf("Error in main loop get: %d\n", status ); li
"""
Testbed for figuring out how to write asynchronous HTTPS code.

$Id$

Copyright (C) 2009  Internet Systems Consortium ("ISC")

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""

# Command that may be useful for testing server side of this:
#
#    lynx -post_data -mime_header -source http://127.0.0.1:8000/


import sys, os, time, socket, fcntl, asyncore, asynchat, getopt, email, traceback

class http_message(object):

  software_name = "WombatWare test HTTP code"

  @classmethod
  def parse_from_wire(cls, headers):
    self = cls()
    headers = headers.split("\r\n")
    self.parse_first_line(*headers.pop(0).split(None, 2))
    for i in xrange(len(headers) - 2, -1, -1):
      if headers[i + 1][0].isspace():
        headers[i] += headers[i + 1]
        del headers[i + 1]
    self.headers = {}
    for h in headers:
      k,v = h.split(":", 1)
      k = "-".join(s.capitalize() for s in k.split("-"))
      if k in self.headers:
        self.headers[k] += ", " + v
      else:
        self.headers[k] = v
    return self

  def format(self):
    s = self.format_first_line()
    if self.body is not None:
      assert isinstance(self.body, str)
      self.headers["Content-Length"] = len(self.body)
    for kv in self.headers.iteritems():
      s += "%s: %s\r\n" % kv
    s += "\r\n"
    if self.body is not None:
      s += self.body
    return s

  def __str__(self):
    return self.format()

  def parse_version(self, version):
    if version[:5] != "HTTP/":
      raise RuntimeError, "Couldn't parse version %s" % version
    self.version = tuple(int(i) for i in version[5:].split("."))

class http_request(http_message):

  def __init__(self, cmd = None, path = None, version = (1,0), body = None, headers = None):
    if cmd is not None and cmd != "POST" and body is not None:
      raise RuntimeError
    self.cmd = cmd
    self.path = path
    self.version = version
    self.body = body
    self.headers = {} if headers is None else headers

  def parse_first_line(self, cmd, path, version):
    self.parse_version(version)
    self.cmd = cmd
    self.path = path

  def format_first_line(self):
    self.headers.setdefault("User-Agent", self.software_name)
    return "%s %s HTTP/%d.%d\r\n" % (self.cmd, self.path, self.version[0], self.version[1])

class http_response(http_message):

  def __init__(self, code = None, msg = None, version = (1,0), body = None, headers = None):
    self.code = code
    self.msg = msg
    self.version = version
    self.body = body
    self.headers = {} if headers is None else headers

  def parse_first_line(self, version, code, msg):
    self.parse_version(version)
    self.code = int(code)
    self.msg = msg

  def format_first_line(self):
    self.headers.setdefault("Date", time.strftime("%a, %d %b %Y %T GMT"))
    self.headers.setdefault("Server", self.software_name)
    return "HTTP/%d.%d %s %s\r\n" % (self.version[0], self.version[1], self.code, self.msg)

class http_stream(asynchat.async_chat):

  def __init__(self, conn = None):
    asynchat.async_chat.__init__(self, conn = conn)
    self.buffer = []
    self.restart()

  def restart(self):
    assert not self.buffer
    self.set_terminator("\r\n\r\n")

  def reading_headers(self):
    return isinstance(self.get_terminator(), str)

  def reading_body(self):
    return isinstance(self.get_terminator(), int)

  def collect_incoming_data(self, data):
    """Buffer the data"""
    self.buffer.append(data)

  def get_buffer(self):
    val = "".join(self.buffer)
    self.buffer = []
    return val

  def found_terminator(self):
    if self.reading_headers():
      return self.handle_headers()
    if self.reading_body():
      return self.handle_body()
    raise RuntimeError

  def handle_body(self):
    self.msg.body = self.get_buffer()
    assert len(self.msg.body) == int(self.msg.headers["Content-Length"])
    self.handle_message()

  def handle_error(self):
    print traceback.format_exc()
    asyncore.close_all()

class http_server(http_stream):

  def handle_headers(self):
    self.msg = http_request.parse_from_wire(self.get_buffer())
    if self.msg.cmd == "POST":
      self.set_terminator(int(self.msg.headers["Content-Length"]))
    else:
      self.handle_message()

  def handle_message(self):
    print self.msg
    self.push(http_response(code = 200, msg = "OK", body = self.msg.format(), headers = { "Content-Type" : "text/plain" }).format())
    if False:
      self.close_when_done()
    else:
      self.restart()

  def handle_close(self):
    asyncore.close_all()

class http_client(http_stream):

  def handle_headers(self):
    self.msg = http_response.parse_from_wire(self.get_buffer())
    self.set_terminator(int(self.msg.headers["Content-Length"]))

  def handle_message(self):
    print self.msg
    self.next_msg()

  def handle_connect(self):
    self.next_msg()

  @classmethod
  def queue_messages(cls, msgs):
    self = cls()
    self.msgs = msgs
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.connect(("", 8000))
    
  def next_msg(self):
    if self.msgs:
      self.push(self.msgs.pop(0).format())
      self.restart()
    else:
      self.close_when_done()

class http_listener(asyncore.dispatcher):

  def __init__(self):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    self.bind(("", 8000))
    self.listen(5)

  def handle_accept(self):
    server = http_server(self.accept()[0])

  def handle_error(self):
    print traceback.format_exc()
    asyncore.close_all()

assert len(sys.argv) in (1, 2)

if len(sys.argv) == 1:

  listener = http_listener()

else:

  # This doesn't comply with HTTP, we're not signalling reusable
  # connections properly.  For the moment this is just a test to see
  # whether the parser can survive multiple mssages.

  client = http_client.queue_messages([
    http_request(cmd = sys.argv[1].upper(), path = "/", body = "Hi, Mom!\r\n", headers = { "Content-Type" : "text/plain" }),
    http_request(cmd = sys.argv[1].upper(), path = "/", body = "Hi, Dad!\r\n", headers = { "Content-Type" : "text/plain" }),
    http_request(cmd = sys.argv[1].upper(), path = "/", body = "Hi, Bro!\r\n", headers = { "Content-Type" : "text/plain" }),
    http_request(cmd = sys.argv[1].upper(), path = "/", body = "Hi, Sis!\r\n", headers = { "Content-Type" : "text/plain" }),
    ])

asyncore.loop()