connection.ss
#lang scheme

(require (prefix-in dest: "destination.ss"))

(require openssl)

(define-struct connection (input output dest))

(define *context* 'sslv2-or-v3)
(define (set-context ctx)
  (set! *context* ctx))

(define (closed? connection)
  (ormap port-closed? (list (connection-input connection) (connection-output connection))))

(define (new dest)
  (let-values ([(input output) 
                  (if (dest:ssl? dest)
                      (ssl-connect (dest:host dest) (dest:port dest) *context*)
                      (tcp-connect (dest:host dest) (dest:port dest)))])
    (make-connection input output dest)))
      
(define (reconnect connection)
  (new (connection-dest connection)))

(define (close connection)
  (close-input-port (connection-input connection))
  (close-output-port (connection-output connection)))

(define input connection-input)
(define output connection-output)
(define dest connection-dest)

(provide/contract
 [closed? (-> connection? boolean?)]
 [new (-> dest:dest? connection?)]
 [reconnect (-> connection? connection?)]
 [close (-> connection? void?)]
 [input (-> connection? input-port?)]
 [output (-> connection? output-port?)]
 [dest (-> connection? dest:dest?)]
 [connection? (-> any/c boolean?)])