Index: package_tags/sipb-xen-vnc-server/1/code/get_port.py
===================================================================
--- package_tags/sipb-xen-vnc-server/1/code/get_port.py	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/code/get_port.py	(revision 331)
@@ -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/sipb-xen-vnc-server/1/code/vncexternalauth.py
===================================================================
--- package_tags/sipb-xen-vnc-server/1/code/vncexternalauth.py	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/code/vncexternalauth.py	(revision 331)
@@ -0,0 +1,206 @@
+"""
+Wrapper for sipb-xen 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
+import get_port
+
+TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN"
+
+def getPort(name, auth_data):
+    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):
+        global TOKEN_KEY
+        self.auth_error = "Invalid token"
+        try:
+            token = base64.urlsafe_b64decode(token)
+            token = cPickle.loads(token)
+            m = hmac.new(TOKEN_KEY, 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/sipb-xen-vnc-server/1/code/vncproxy.py
===================================================================
--- package_tags/sipb-xen-vnc-server/1/code/vncproxy.py	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/code/vncproxy.py	(revision 331)
@@ -0,0 +1,12 @@
+#! /usr/bin/python
+from twisted.internet import reactor, ssl
+import vncexternalauth
+
+sslContext = ssl.DefaultOpenSSLContextFactory(
+	'vncproxykey.pem',
+	'vncproxy.crt',
+)
+
+if '__main__' == __name__:
+    reactor.listenSSL(10003,vncexternalauth.VNCAuthFactory("localhost"), contextFactory=sslContext)
+    reactor.run()
Index: package_tags/sipb-xen-vnc-server/1/debian/changelog
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/changelog	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/changelog	(revision 331)
@@ -0,0 +1,5 @@
+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/sipb-xen-vnc-server/1/debian/compat
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/compat	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/compat	(revision 331)
@@ -0,0 +1,1 @@
+4
Index: package_tags/sipb-xen-vnc-server/1/debian/control
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/control	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/control	(revision 331)
@@ -0,0 +1,11 @@
+Source: sipb-xen-vnc-server
+Section: base
+Priority: extra
+Maintainer: SIPB Xen Project <sipb-xen@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0), subversion
+Standards-Version: 3.7.2
+
+Package: sipb-xen-vnc-server
+Architecture: all
+Depends: ${misc:Depends}, daemon, python-twisted-core, xen-utils-3.1-1
+Description: Install and enable the VNC server
Index: package_tags/sipb-xen-vnc-server/1/debian/copyright
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/copyright	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/copyright	(revision 331)
@@ -0,0 +1,3 @@
+This package was created for internal use of the SIPB Xen Project of
+the MIT Student Information Processing Board.  Ask sipb-xen@mit.edu if
+you have questions about redistribution.
Index: package_tags/sipb-xen-vnc-server/1/debian/rules
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/rules	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/rules	(revision 331)
@@ -0,0 +1,6 @@
+#!/usr/bin/make -f
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+
+binary-fixup/sipb-xen-vnc-server::
+	svn co https://sipb-xen-dev.mit.edu:1111/trunk/packages/sipb-xen-vnc-server/code/ $(DEB_DESTDIR)/usr/local/lib/sipb-xen-vnc-server
Index: package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.init
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.init	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.init	(revision 331)
@@ -0,0 +1,124 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:          sipb-xen-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: sipb-xen VNC Proxy Server
+# Description:       
+### END INIT INFO
+
+# Author: SIPB Xen Project <sipb-xen@mit.edu>
+
+# Do NOT "set -e"
+
+# PATH should only include /usr/* if it runs after the mountnfs.sh script
+PATH=/sbin:/usr/sbin:/bin:/usr/bin
+DESC="The sipb-xen VNC Proxy Server"
+NAME=sipb-xen-vnc-server
+DAEMON=/usr/local/lib/sipb-xen-vnc-server/vncproxy.py
+DAEMON_ARGS=""
+PIDFILE=/var/run/$NAME.pid
+SCRIPTNAME=/etc/init.d/$NAME
+
+# Exit if the package is not installed
+[ -x "$DAEMON" ] || exit 0
+
+# Read configuration variable file if it is present
+[ -r /etc/default/$NAME ] && . /etc/default/$NAME
+
+# Load the VERBOSE setting and other rcS variables
+. /lib/init/vars.sh
+
+# Define LSB log_* functions.
+# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
+. /lib/lsb/init-functions
+
+#
+# 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 $NAME && return 1
+	daemon -r -U -D "$(dirname $DAEMON)" -O daemon.info -E daemon.err -n $NAME -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 $NAME
+	RETVAL="$?"
+	[ "$RETVAL" = 2 ] && return 2
+	# Many daemons don't delete their pidfiles when they exit.
+	rm -f $PIDFILE
+	return "$RETVAL"
+}
+
+case "$1" in
+  start)
+	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
+	do_start
+	case "$?" in
+		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
+		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
+	esac
+	;;
+  stop)
+	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
+	do_stop
+	case "$?" in
+		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
+		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
+	esac
+	;;
+  #reload|force-reload)
+	#
+	# If do_reload() is not implemented then leave this commented out
+	# and leave 'force-reload' as an alias for 'restart'.
+	#
+	#log_daemon_msg "Reloading $DESC" "$NAME"
+	#do_reload
+	#log_end_msg $?
+	#;;
+  restart|force-reload)
+	#
+	# If the "reload" option is implemented then remove the
+	# 'force-reload' alias
+	#
+	log_daemon_msg "Restarting $DESC" "$NAME"
+	do_stop
+	case "$?" in
+	  0|1)
+		do_start
+		case "$?" in
+			0) log_end_msg 0 ;;
+			1) log_end_msg 1 ;; # Old process is still running
+			*) log_end_msg 1 ;; # Failed to start
+		esac
+		;;
+	  *)
+	  	# Failed to stop
+		log_end_msg 1
+		;;
+	esac
+	;;
+  *)
+	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
+	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
+	exit 3
+	;;
+esac
+
+:
Index: package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.install
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.install	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.install	(revision 331)
@@ -0,0 +1,1 @@
+files/* .
Index: package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.postinst
===================================================================
--- package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.postinst	(revision 331)
+++ package_tags/sipb-xen-vnc-server/1/debian/sipb-xen-vnc-server.postinst	(revision 331)
@@ -0,0 +1,44 @@
+#!/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)
+	if [ -z "$2" ]; then
+	    echo "Please be sure to copy vncproxy.crt and vncproxykey.pem into /usr/local/lib/sipb-xen-vnc-server/"
+	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
+
+
