The skeleton of a man in the middle

Intermediation

Placing yourself in the middle comes in handy in all sorts of situations. The following skeleton of Tcl code is fully functional and easily extended. I've used it in one form or another for many years now:

socket -server accept listeningPort

proc accept {client addr port} {
    if {[catch {socket -async destHost destPort} server]} then {
        shutdown $client
    } else {
        fconfigure $client -blocking 0 -buffering none -translation binary
        fconfigure $server -blocking 0 -buffering none -translation binary
        fileevent  $client readable [list glue $client $server]
        fileevent  $server readable [list glue $server $client]
    }
}

proc glue {src dst} {
    if {[catch {puts -nonewline $dst [read $src]}] ||
        [eof $src] || [eof $dst]} then {
        shutdown $src $dst
    }
}

proc shutdown {args} {
    foreach sock $args {catch {close $sock}}
}

vwait forever

It's possible to get even more mileage out of it. With just another couple of lines you can bridge SSL coming and/or going.

I love Tcl's event-driven I/O.


—Michael A. Cleverly

Permanent URL for this post: http://blog.cleverly.com/permalinks/285.html