Index: package_tags/invirt-vnc-server/0.0.4/debian/changelog
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/changelog	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/changelog	(revision 1417)
@@ -0,0 +1,49 @@
+invirt-vnc-server (0.0.4) unstable; urgency=low
+
+  * Deprecate /etc/invirt/secrets in favor of /etc/invirt/vnc
+  * Include the hostname in the generated SSL certs so that the Java
+    keytool will accept them
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 23:59:57 -0400
+
+invirt-vnc-server (0.0.3) unstable; urgency=low
+
+  * Fix a typo in the new init script
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 22:58:59 -0400
+
+invirt-vnc-server (0.0.2) unstable; urgency=low
+
+  * Cleanup the init script to use /lib/init/std-init.sh
+  * Generate the SSL certificates at install-time
+  * File reads are cheap. Especially when the file is short. Don't cache
+    the token key
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 22:48:24 -0400
+
+invirt-vnc-server (0.0.1) unstable; urgency=low
+
+  * sipb-xen-vnc-server -> invirt-vnc-server
+  * Generate the VNC token key at install-time instead of hard-coding
+  * Add a script for generating VNC auth tokens, to be exposed over remctl
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 19:45:35 -0400
+
+sipb-xen-vnc-server (1.2) unstable; urgency=low
+
+  * Move certificate files into /usr/share/sipb-xen-vnc-server
+  * Switch to distutils-based package
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 15:07:33 -0400
+
+sipb-xen-vnc-server (1.1) unstable; urgency=low
+
+  * Update dependencies for Hardy
+
+ -- Evan Broder <broder@mit.edu>  Fri, 03 Oct 2008 22:16:32 -0400
+
+sipb-xen-vnc-server (1) unstable; urgency=low
+
+  * Initial Release.
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Fri, 28 Mar 2008 19:28:22 -0500
+
Index: package_tags/invirt-vnc-server/0.0.4/debian/compat
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/compat	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/compat	(revision 1417)
@@ -0,0 +1,1 @@
+4
Index: package_tags/invirt-vnc-server/0.0.4/debian/control
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/control	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/control	(revision 1417)
@@ -0,0 +1,16 @@
+Source: invirt-vnc-server
+Section: base
+Priority: extra
+Maintainer: Invirt project <invirt@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0),
+ python-all-dev (>=2.3.5-11), python-support (>= 0.5.3),
+ python-setuptools, python-debian, python-apt
+Standards-Version: 3.8.0
+
+Package: invirt-vnc-server
+Architecture: all
+Depends: ${python:Depends}, ${misc:Depends}, daemon,
+ python-twisted-core, python-xen-3.2
+Provides: ${python:Provides}
+XB-Python-Version: ${python:Versions}
+Description: Install and enable the VNC server
Index: package_tags/invirt-vnc-server/0.0.4/debian/copyright
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/copyright	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/copyright	(revision 1417)
@@ -0,0 +1,16 @@
+This software was written as part of the Invirt project <invirt@mit.edu>.
+
+Copyright :
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+On Debian systems, the complete text of the GNU General Public License
+can be found in the file /usr/share/common-licenses/GPL.
Index: package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.init
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.init	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.init	(revision 1417)
@@ -0,0 +1,60 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:          invirt-vnc-server
+# Required-Start:    $local_fs $remote_fs
+# Required-Stop:     $local_fs $remote_fs
+# Default-Start:     2 3 4 5
+# Default-Stop:      0 1 6
+# Short-Description: Invirt VNC Proxy Server
+# Description:       
+### END INIT INFO
+
+# Author: Invirt project <invirt@mit.edu>
+
+# Do NOT "set -e"
+
+# PATH should only include /usr/* if it runs after the mountnfs.sh script
+PACKAGE=invirt-vnc-server
+DESC="The Invirt VNC Proxy Server"
+DAEMON=/usr/sbin/invirt-vnc-server
+DAEMON_ARGS=""
+PIDFILE=/var/run/$PACKAGE.pid
+SCRIPTNAME=/etc/init.d/$PACKAGE
+
+# Exit if the package is not installed
+[ -x "$DAEMON" ] || exit 0
+
+. /lib/init/std-init.sh
+
+#
+# Function that starts the daemon/service
+#
+do_start()
+{
+	# Return
+	#   0 if daemon has been started
+	#   1 if daemon was already running
+	#   2 if daemon could not be started
+	daemon --running -n $PACKAGE && return 1
+	daemon -r -U -O daemon.info -E daemon.err -n $PACKAGE -U $DAEMON $DAEMON_ARGS || return 2
+}
+
+#
+# Function that stops the daemon/service
+#
+do_stop()
+{
+	# Return
+	#   0 if daemon has been stopped
+	#   1 if daemon was already stopped
+	#   2 if daemon could not be stopped
+	#   other if a failure occurred
+	daemon --stop -n $PACKAGE
+	RETVAL="$?"
+	[ "$RETVAL" = 2 ] && return 2
+	# Many daemons don't delete their pidfiles when they exit.
+	rm -f $PIDFILE
+	return "$RETVAL"
+}
+
+std_init "$1"
Index: package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.postinst
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.postinst	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/invirt-vnc-server.postinst	(revision 1417)
@@ -0,0 +1,54 @@
+#!/bin/sh
+# postinst script for #PACKAGE#
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+#        * <postinst> `configure' <most-recently-configured-version>
+#        * <old-postinst> `abort-upgrade' <new version>
+#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
+#          <new-version>
+#        * <postinst> `abort-remove'
+#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
+#          <failed-install-package> <version> `removing'
+#          <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+    configure)
+        mkdir -p /etc/invirt/vnc
+        if ! [ -e /etc/invirt/vnc/server.pem ]; then
+            openssl genrsa -out /etc/invirt/vnc/server.pem 1024 >/dev/null
+        fi
+        
+        if ! [ -e /etc/invirt/vnc/server.crt ]; then
+            openssl req -new -x509 -nodes -sha1 -subj "/CN=$(hostname -f)" -key /etc/invirt/vnc/server.pem \
+                > /etc/invirt/vnc/server.crt
+        fi
+        
+        if ! [ -e /etc/invirt/vnc/token-key ]; then
+            openssl rand -base64 33 >/etc/invirt/vnc/token-key
+        fi
+    ;;
+
+    abort-upgrade|abort-remove|abort-deconfigure)
+    ;;
+
+    *)
+        echo "postinst called with unknown argument \`$1'" >&2
+        exit 1
+    ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
+
+
Index: package_tags/invirt-vnc-server/0.0.4/debian/pycompat
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/pycompat	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/pycompat	(revision 1417)
@@ -0,0 +1,1 @@
+2
Index: package_tags/invirt-vnc-server/0.0.4/debian/rules
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/debian/rules	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/debian/rules	(revision 1417)
@@ -0,0 +1,13 @@
+#!/usr/bin/make -f
+
+DEB_PYTHON_SYSTEM=pysupport
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+include /usr/share/cdbs/1/class/python-distutils.mk
+
+binary-fixup/invirt-vnc-server::
+	mkdir -p $(DEB_DESTDIR)usr/sbin
+	mv $(DEB_DESTDIR)usr/bin/invirt-vnc-server $(DEB_DESTDIR)usr/sbin/invirt-vnc-server
+
+clean::
+	rm -rf invirt.vnc.egg-info
Index: package_tags/invirt-vnc-server/0.0.4/invirt-vnc-authtoken
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/invirt-vnc-authtoken	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/invirt-vnc-authtoken	(revision 1417)
@@ -0,0 +1,34 @@
+#!/usr/bin/python
+
+import os
+import sys
+import hmac
+import cPickle
+import sha
+import time
+import base64
+from invirt.vnc import getTokenKey
+
+def getAuthToken(username, machine, lifetime=5*60):
+    data = {}
+    data['user'] = username
+    data['machine'] = machine
+    data['expires'] = time.time() + lifetime
+    pickled_data = cPickle.dumps(data)
+    m = hmac.new(getTokenKey(), digestmod=sha)
+    m.update(pickled_data)
+    token = {'data': pickled_data, 'digest': m.digest()}
+    token = cPickle.dumps(token)
+    token = base64.urlsafe_b64encode(token)
+    return token
+
+def main():
+    try:
+        username = os.environ['REMOTE_USER']
+    except KeyError:
+        username = None
+    machine = sys.argv[1]
+    print getAuthToken(username, machine)
+
+if __name__ == '__main__':
+    main()
Index: package_tags/invirt-vnc-server/0.0.4/invirt-vnc-getcert
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/invirt-vnc-getcert	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/invirt-vnc-getcert	(revision 1417)
@@ -0,0 +1,8 @@
+#!/usr/bin/python
+
+import sys
+
+try:
+    print open('/etc/invirt/vnc/server.crt').read()
+except IOError, e:
+    sys.exit(e.errno)
Index: package_tags/invirt-vnc-server/0.0.4/invirt-vnc-server
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/invirt-vnc-server	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/invirt-vnc-server	(revision 1417)
@@ -0,0 +1,12 @@
+#! /usr/bin/python
+from twisted.internet import reactor, ssl
+from invirt import vnc
+
+sslContext = ssl.DefaultOpenSSLContextFactory(
+	'/usr/share/invirt-vnc-server/vncproxykey.pem',
+	'/usr/share/invirt-vnc-server/vncproxy.crt',
+)
+
+if '__main__' == __name__:
+    reactor.listenSSL(10003,vnc.VNCAuthFactory("localhost"), contextFactory=sslContext)
+    reactor.run()
Index: package_tags/invirt-vnc-server/0.0.4/python/vnc/__init__.py
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/python/vnc/__init__.py	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/python/vnc/__init__.py	(revision 1417)
@@ -0,0 +1,1 @@
+from extauth import *
Index: package_tags/invirt-vnc-server/0.0.4/python/vnc/extauth.py
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/python/vnc/extauth.py	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/python/vnc/extauth.py	(revision 1417)
@@ -0,0 +1,206 @@
+"""
+Wrapper for Invirt VNC proxying
+"""
+
+# twisted imports
+from twisted.internet import reactor, protocol, defer
+from twisted.python import log
+
+# python imports
+import sys
+import struct
+import string
+import cPickle
+# Python 2.5:
+#import hashlib
+import sha
+import hmac
+import base64
+import socket
+import time
+
+def getTokenKey():
+    return file('/etc/invirt/vnc/token-key').read().strip()
+
+def getPort(name, auth_data):
+    import get_port
+    if (auth_data["machine"] == name):
+        port = get_port.findPort(name)
+        if port is None:
+            return 0
+        return int(port.split(':')[1])
+    else:
+        return None
+    
+class VNCAuthOutgoing(protocol.Protocol):
+    
+    def __init__(self,socks):
+        self.socks=socks
+
+    def connectionMade(self):
+        peer = self.transport.getPeer()
+        self.socks.makeReply(200)
+        self.socks.otherConn=self
+
+    def connectionLost(self, reason):
+        self.socks.transport.loseConnection()
+
+    def dataReceived(self,data):
+        self.socks.write(data)
+
+    def write(self,data):
+        self.transport.write(data)
+
+
+class VNCAuth(protocol.Protocol):
+    
+    def __init__(self,server="localhost"):
+        self.server=server
+        self.auth=None
+    
+    def connectionMade(self):
+        self.buf=""
+        self.otherConn=None
+
+    def validateToken(self, token):
+        self.auth_error = "Invalid token"
+        try:
+            token = base64.urlsafe_b64decode(token)
+            token = cPickle.loads(token)
+            m = hmac.new(getTokenKey(), digestmod=sha)
+            m.update(token['data'])
+            if (m.digest() == token['digest']):
+                data = cPickle.loads(token['data'])
+                expires = data["expires"]
+                if (time.time() < expires):
+                    self.auth = data["user"]
+                    self.auth_error = None
+                    self.auth_machine = data["machine"]
+                    self.auth_data = data
+                else:
+                    self.auth_error = "Token has expired; please try logging in again"
+        except (TypeError, cPickle.UnpicklingError):
+            self.auth = None            
+            print sys.exc_info()
+
+    def dataReceived(self,data):
+        if self.otherConn:
+            self.otherConn.write(data)
+            return
+        self.buf=self.buf+data
+        if ('\r\n\r\n' in self.buf) or ('\n\n' in self.buf) or ('\r\r' in self.buf):
+            lines = self.buf.splitlines()
+            args = lines.pop(0).split()
+            command = args.pop(0)
+            headers = {}
+            for line in lines:
+                try:
+                    (header, data) = line.split(": ", 1)
+                    headers[header] = data
+                except ValueError:
+                    pass
+
+            if command == "AUTHTOKEN":
+                user = args[0]
+                token = headers["Auth-token"]
+                if token == "1": #FIXME
+                    self.auth = user
+                    self.makeReply(200, "Authentication successful")
+                else:
+                    self.makeReply(401)
+            elif command == "CONNECTVNC":
+                vmname = args[0]
+                if ("Auth-token" in headers):
+                    token = headers["Auth-token"]
+                    self.validateToken(token)
+                    if self.auth is not None:
+                        port = getPort(vmname, self.auth_data)
+                        if port is not None: # FIXME
+                            if port != 0:
+                                d = self.connectClass(self.server, port, VNCAuthOutgoing, self)
+                                d.addErrback(lambda result, self=self: self.makeReply(404, result.getErrorMessage()))
+                            else:
+                                self.makeReply(404, "Unable to find VNC for VM "+vmname)
+                        else:
+                            self.makeReply(401, "Unauthorized to connect to VM "+vmname)
+                    else:
+                        if self.auth_error:
+                            self.makeReply(401, self.auth_error)
+                        else:
+                            self.makeReply(401, "Invalid token")
+                else:
+                    self.makeReply(401, "Login first")
+            else:
+                self.makeReply(501, "unknown method "+command)
+            self.buf=''
+        if False and '\000' in self.buf[8:]:
+            head,self.buf=self.buf[:8],self.buf[8:]
+            try:
+                version,code,port=struct.unpack("!BBH",head[:4])
+            except struct.error:
+                raise RuntimeError, "struct error with head='%s' and buf='%s'"%(repr(head),repr(self.buf))
+            user,self.buf=string.split(self.buf,"\000",1)
+            if head[4:7]=="\000\000\000": # domain is after
+                server,self.buf=string.split(self.buf,'\000',1)
+                #server=gethostbyname(server)
+            else:
+                server=socket.inet_ntoa(head[4:8])
+            assert version==4, "Bad version code: %s"%version
+            if not self.authorize(code,server,port,user):
+                self.makeReply(91)
+                return
+            if code==1: # CONNECT
+                d = self.connectClass(server, port, SOCKSv4Outgoing, self)
+                d.addErrback(lambda result, self=self: self.makeReply(91))
+            else:
+                raise RuntimeError, "Bad Connect Code: %s" % code
+            assert self.buf=="","hmm, still stuff in buffer... %s" % repr(self.buf)
+
+    def connectionLost(self, reason):
+        if self.otherConn:
+            self.otherConn.transport.loseConnection()
+
+    def authorize(self,code,server,port,user):
+        log.msg("code %s connection to %s:%s (user %s) authorized" % (code,server,port,user))
+        return 1
+
+    def connectClass(self, host, port, klass, *args):
+        return protocol.ClientCreator(reactor, klass, *args).connectTCP(host,port)
+
+    def makeReply(self,reply,message=""):
+        self.transport.write("VNCProxy/1.0 %d %s\r\n\r\n" % (reply, message))
+        if int(reply / 100)!=2: self.transport.loseConnection()
+
+    def write(self,data):
+        self.transport.write(data)
+
+    def log(self,proto,data):
+        peer = self.transport.getPeer()
+        their_peer = self.otherConn.transport.getPeer()
+        print "%s\t%s:%d %s %s:%d\n"%(time.ctime(),
+                                        peer.host,peer.port,
+                                        ((proto==self and '<') or '>'),
+                                        their_peer.host,their_peer.port),
+        while data:
+            p,data=data[:16],data[16:]
+            print string.join(map(lambda x:'%02X'%ord(x),p),' ')+' ',
+            print ((16-len(p))*3*' '),
+            for c in p:
+                if len(repr(c))>3: print '.',
+                else: print c,
+            print ""
+        print ""
+
+
+class VNCAuthFactory(protocol.Factory):
+    """A factory for a VNC auth proxy.
+    
+    Constructor accepts one argument, a log file name.
+    """
+    
+    def __init__(self, server):
+        self.server = server
+    
+    def buildProtocol(self, addr):
+        return VNCAuth(self.server)
+
Index: package_tags/invirt-vnc-server/0.0.4/python/vnc/get_port.py
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/python/vnc/get_port.py	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/python/vnc/get_port.py	(revision 1417)
@@ -0,0 +1,25 @@
+#!/usr/bin/python
+import sys
+import glob
+sys.path.append('/usr/lib/xen-default/lib/python/')
+import xen.xm
+import xen.xm.XenAPI
+import xen.xend.XendClient
+import time
+import xmlrpclib
+
+prefix = "d_"
+server = xen.xm.XenAPI.Session(xen.xend.XendClient.uri)
+
+def findPort(name):
+    try:
+        state = server.xend.domain(prefix + name, True)
+        for (key,value) in state[1:]:
+            if key == 'device' and value[0] == 'vfb':
+                location=dict(value[1:]).get('location')
+                return location
+    except xmlrpclib.Fault:
+        return None
+
+if __name__ == '__main__':
+    print findPort(sys.argv[1])
Index: package_tags/invirt-vnc-server/0.0.4/setup.py
===================================================================
--- package_tags/invirt-vnc-server/0.0.4/setup.py	(revision 1417)
+++ package_tags/invirt-vnc-server/0.0.4/setup.py	(revision 1417)
@@ -0,0 +1,24 @@
+#!/usr/bin/python
+
+from os import path
+from debian_bundle.changelog import Changelog
+from debian_bundle.deb822 import Deb822
+from email.utils import parseaddr
+from setuptools import setup
+
+version = Changelog(open(path.join(path.dirname(__file__), 'debian/changelog')).read()).\
+    get_version().full_version
+
+maintainer_full = Deb822(open(path.join(path.dirname(__file__), 'debian/control')))['Maintainer']
+maintainer, maintainer_email = parseaddr(maintainer_full)
+
+setup(
+    name='invirt.vnc',
+    version=version,
+    maintainer=maintainer,
+    maintainer_email=maintainer_email,
+    
+    packages = ['invirt.vnc'],
+    package_dir = {'invirt': 'python'},
+    scripts=['invirt-vnc-server', 'invirt-vnc-authtoken', 'invirt-vnc-getcert']
+)
