[Openlanhouse-development] SF.net SVN: openlanhouse:[289] trunk/openlh-core
Status: Pre-Alpha
Brought to you by:
n3rd3x
|
From: <n3...@us...> - 2008-10-11 17:27:50
|
Revision: 289
http://openlanhouse.svn.sourceforge.net/openlanhouse/?rev=289&view=rev
Author: n3rd3x
Date: 2008-10-11 17:27:44 +0000 (Sat, 11 Oct 2008)
Log Message:
-----------
initial state of migration of network to openlh-core
Modified Paths:
--------------
trunk/openlh-core/Makefile.am
trunk/openlh-core/configure.ac
Added Paths:
-----------
trunk/openlh-core/src/Makefile.am
trunk/openlh-core/src/OpenlhCore/__init__.py
trunk/openlh-core/src/OpenlhCore/net/
trunk/openlh-core/src/OpenlhCore/net/__init__.py
trunk/openlh-core/src/OpenlhCore/net/client.py
trunk/openlh-core/src/OpenlhCore/net/constants.py
trunk/openlh-core/src/OpenlhCore/net/request_handler.py
trunk/openlh-core/src/OpenlhCore/net/response.py
trunk/openlh-core/src/OpenlhCore/net/server.py
Modified: trunk/openlh-core/Makefile.am
===================================================================
--- trunk/openlh-core/Makefile.am 2008-10-11 16:54:09 UTC (rev 288)
+++ trunk/openlh-core/Makefile.am 2008-10-11 17:27:44 UTC (rev 289)
@@ -1,20 +1,10 @@
## Process this file with automake to produce Makefile.in
-SUBDIRS = data src po
+SUBDIRS = src
-#DISTCLEANFILES = \
-# intltool-extract \
-# intltool-merge \
-# intltool-update
-
-#EXTRA_DIST = \
-# intltool-extract.in \
-# intltool-merge.in \
-# intltool-update.in
-
CLEANFILES = \
- src/OpenlhServer/*.pyc \
- src/OpenlhServer/*.pyo \
- src/OpenlhServer/ui/*.pyc \
- src/OpenlhServer/ui/*.pyo
+ src/OpenlhCore/*.pyc \
+ src/OpenlhCore/*.pyo \
+ src/OpenlhCore/net/*.pyc \
+ src/OpenlhCore/net/*.pyo
Modified: trunk/openlh-core/configure.ac
===================================================================
--- trunk/openlh-core/configure.ac 2008-10-11 16:54:09 UTC (rev 288)
+++ trunk/openlh-core/configure.ac 2008-10-11 17:27:44 UTC (rev 289)
@@ -13,33 +13,13 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-AC_INIT([OpenLanhouse Server],[0.1],[http://openlanhouse.sf.net],[openlh-server])
+AC_INIT([OpenLanhouse Core],[0.2],[http://trac.openlanhouse.org],[openlh-core])
AM_INIT_AUTOMAKE([1.7])
AM_MAINTAINER_MODE
-GETTEXT_PACKAGE=openlh-server
-AC_SUBST([GETTEXT_PACKAGE])
-AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE],["$GETTEXT_PACKAGE"],[Gettext package])
-AC_PROG_INTLTOOL([0.35.0])
-AM_GLIB_GNU_GETTEXT
-AM_GCONF_SOURCE_2
-AM_PROG_LIBTOOL
-
-AC_PATH_PROG(GCONFTOOL, gconftool-2, no)
-
-if test x"$GCONFTOOL" = xno; then
- AC_MSG_ERROR([gconftool-2 executable not found in your path - should be installed with GConf])
- fi
-
dnl python checks
AM_PATH_PYTHON(2.5)
-dnl gtk dependencie
-PYGTK_REQUIRED=2.12.0
-PKG_CHECK_MODULES([DEPENDENCIES], [
- pygtk-2.0 >= $PYGTK_REQUIRED
-])
-
#python-gnutls
dnl Checking python-gnutls
AC_MSG_CHECKING([for the python-gnutls package])
@@ -59,84 +39,19 @@
$ac_pgnutls_result])
fi
-#python-gconf
-dnl Checking python-gconf
-AC_MSG_CHECKING([for the python-gconf package])
-ac_pgconf_result=`$PYTHON -c 'try:
- import gconf
-except Exception, e:
- print str(e)' 2> /dev/null`
-
-if test -z "$ac_pgconf_result"; then
- AC_MSG_RESULT([yes])
-else
- AC_MSG_RESULT([no])
- AC_MSG_ERROR([cannot import Python module "gconf".
- Please check if you have python-gconf installed. The error was:
- $ac_pgconf_result])
-fi
-
-#python-certtool
-dnl Checking python-certtool
-AC_MSG_CHECKING([for the python-certtool package])
-ac_pgconf_result=`$PYTHON -c 'try:
- import certtool
-except Exception, e:
- print str(e)' 2> /dev/null`
-
-if test -z "$ac_pgconf_result"; then
- AC_MSG_RESULT([yes])
-else
- AC_MSG_RESULT([no])
- AC_MSG_ERROR([cannot import Python module "certtool".
- Please check if you have python-certtool installed. The error was:
- $ac_pgconf_result])
-fi
-
-#python-sqlalchemy
-dnl Checking python-sqlalchemy
-AC_MSG_CHECKING([for the python-sqlalchemy package])
-ac_psqlalchemy_result=`$PYTHON -c 'try:
- import sys
- import sqlalchemy
- from sqlalchemy import __version__
- if not __version__ >= "0.4":
- print "python-sqlalchemy must be 0.4 version or later"
- sys.exit(2)
-except:
- print str(e)' 2> /dev/null`
-exit_code=$?
-
-if (("$exit_code"==0)); then
- AC_MSG_RESULT([yes])
-else
- AC_MSG_RESULT([no])
- AC_MSG_ERROR([cannot import Python module "sqlalchemy".
- Please check if you have python-sqlalchemy installed. The error was:
- $ac_psqlalchemy_result])
-fi
-
dnl output files
AC_CONFIG_FILES([
Makefile
-data/Makefile
-data/openlh-server.desktop.in
-data/glade/Makefile
-data/ui/Makefile
-data/db/Makefile
-data/icons/Makefile
-data/icons/status/Makefile
src/Makefile
-src/OpenlhServer/Makefile
-src/OpenlhServer/ui/Makefile
-src/OpenlhServer/config.py
-po/Makefile.in
+src/OpenlhCore/Makefile
+src/OpenlhCore/ui/Makefile
+src/OpenlhCore/config.py
])
AC_OUTPUT
echo "
-openlh-server-$VERSION:
+openlh-core-$VERSION:
prefix: ${prefix}
Added: trunk/openlh-core/src/Makefile.am
===================================================================
--- trunk/openlh-core/src/Makefile.am (rev 0)
+++ trunk/openlh-core/src/Makefile.am 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1 @@
+SUBDIRS = OpenlhCore
Added: trunk/openlh-core/src/OpenlhCore/net/__init__.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/__init__.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/__init__.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto J\xFAnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+__all__ = ('server', 'client', 'response', 'request_handler',
+ 'constants', 'backends', 'certgen')
\ No newline at end of file
Added: trunk/openlh-core/src/OpenlhCore/net/client.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/client.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/client.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto J\xFAnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
\ No newline at end of file
Added: trunk/openlh-core/src/OpenlhCore/net/constants.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/constants.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/constants.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto Júnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+XMLRESPONSE_TYPE, XMLREQUEST_TYPE, SENDFILE_TYPE = range(1, 4)
+
+BEGIN_XMLRESPONSE_HEADER = '-----BEGIN XMLRESPONSE ID=%d SIZE=%d-----'
+END_XMLRESPONSE_HEADER = '-----END XMLRESPONSE-----'
+
+BEGIN_XMLREQUEST_HEADER = "-----BEGIN XMLREQUEST ID=%d SIZE=%d-----"
+END_XMLREQUEST_HEADER = "-----END XMLREQUEST-----"
+
+BEGIN_SENDFILE_HEADER = "-----BEGIN SENDFILE ID=%d METHOD=%s SIZE=%d-----"
+END_SENDFILE_HEADER = "-----END SENDFILE-----"
\ No newline at end of file
Added: trunk/openlh-core/src/OpenlhCore/net/request_handler.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/request_handler.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/request_handler.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,471 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto Júnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import sys
+import re
+import gobject
+
+import traceback
+import logging
+
+from os import path as ospath
+from threading import RLock
+from OpenlhServer.utils import DictLimited
+
+from xmlrpclib import loads as xmlpickler_loads
+from xmlrpclib import dumps as xmlpickler_dumps
+
+from OpenlhServer.net.response import Response
+from OpenlhServer.net.constants import *
+
+HashIDRegex = re.compile(r'-----HASH_ID=(?P<hash_id>\w+)-----(?P<data>(.*))')
+
+XMLResponseRegex = re.compile(r'-----BEGIN XMLRESPONSE ID=(?P<id>\d+)'
+ r' SIZE=(?P<size>\d+)-----(?P<data>(.*))')
+
+XMLRequestRegex = re.compile(r'-----BEGIN XMLREQUEST'
+ r' ID=(?P<id>\d+) SIZE=(?P<size>\d+)-----(?P<data>(.*))')
+
+SendFileRegex = re.compile(r'-----BEGIN SENDFILE METHOD=(?P<method>[\w.]+) '
+ r'SIZE=(?P<size>\d+)-----(?P<data>(.*))')
+
+class RequestHandler(gobject.GObject):
+
+ rbufsize = -1
+ wbufsize = 0
+ checking = False
+ currid = 1
+
+ closed = False
+ disconnected = False
+ hash_id = None
+ io_session_handler_id = 0
+
+ current_id = None
+ current_size = None
+ current_type = None
+ current_size_remaining = None
+ current_data = None
+ current_method = None
+
+ def __init__(self, session, client_address, server):
+
+ self.__gobject_init__()
+
+ self.session = session
+ self.client_address = client_address
+ self.server = server
+
+ self.send_lock = RLock()
+ self.open_responses = DictLimited(limit=5)
+
+ self.logger = logging.getLogger('%s:%s' % client_address)
+
+ try:
+ self.setup()
+ self.handshake()
+ gobject.timeout_add(5000, self.check_hash_id)
+ self.io_session_handler_id = gobject.io_add_watch(self.session,
+ gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP,
+ self.handler_io)
+
+ except:
+ traceback.print_exc()
+ self.close()
+
+ finally:
+ sys.exc_traceback = None
+
+ def setup(self):
+ self.rfile = self.session.makefile('rb', self.rbufsize)
+ self.wfile = self.session.makefile('wb', self.wbufsize)
+
+ def handshake(self):
+ self.session.handshake()
+
+ def close(self):
+ """
+ Close Connection
+ """
+ self.listen = False
+
+ if self.io_session_handler_id:
+ gobject.source_remove(self.io_session_handler_id)
+
+ try:
+ self.session.send('CLOSE')
+ except:
+ pass
+
+ try:
+ self.session.shutdown()
+ except:
+ pass
+
+ try:
+ self.session.close()
+ except:
+ pass
+
+ try:
+ if not self.wfile.closed:
+ self.wfile.flush()
+
+ self.wfile.close()
+ self.rfile.close()
+
+ except:
+ pass
+
+ self.closed = True
+ self.logger.info('connection closed')
+
+ def send_response(self, id, response):
+ """
+ Send reponse to peer
+ """
+
+ try:
+ output = xmlpickler_dumps((response,), methodresponse=1)
+ head = BEGIN_XMLRESPONSE_HEADER % (id, len(output))
+
+ self.send_lock.acquire() #acquire thread lock
+
+ self.session.send(head)
+ self.session.send(output)
+ self.session.send(END_XMLRESPONSE_HEADER)
+
+ except Exception, error:
+ traceback.print_exc()
+ self.logger.error(error)
+
+ self.send_lock.release() #release thread lock
+
+ def request(self, method, params=()):
+ """
+ Request from peer
+ @method:
+ name of method requested
+ @params:
+ tuple params passed to method
+ """
+
+ if not isinstance(params, tuple):
+ params = (params,)
+
+ xmlout = xmlpickler_dumps(params, method)
+ size = len(xmlout)
+ head = BEGIN_XMLREQUEST_HEADER % (self.currid, size)
+
+ self.send_lock.acquire() #acquire thread lock
+
+ try:
+ self.session.send(head)
+ self.session.send(xmlout)
+ self.session.send(END_XMLREQUEST_HEADER)
+ has_error = False
+ except Exception, error:
+ has_error = True
+ self.logger.error(error)
+ traceback.print_exc()
+
+ self.send_lock.release() #release thread lock
+
+ if has_error:
+ return
+
+ response = Response(self.currid)
+ self.open_responses[self.currid] = response
+ self.currid += 1
+
+ return response
+
+ def send_file(self, method, filepath):
+ """
+ Send file to peer
+ @method:
+ name of method to receive file
+ @filepath:
+ path of file to be send
+ """
+
+ self.logger.info('Sending %s file' % filepath)
+
+ assert ospath.exists(filepath), 'File not Found'
+
+ f = open(filepath)
+ size = ospath.getsize(filepath)
+
+ head = BEGIN_SENDFILE_HEADER % (self.currid, method, size)
+
+ self.currid += 1
+
+ self.send_lock.acquire() #acquire thread lock
+
+ try:
+ self.session.send(head)
+
+ while True:
+ data = f.read(1024)
+ if data != "":
+ self.session.send(data)
+ else:
+ break
+
+ self.session.send(END_SENDFILE_HEADER)
+ self.logger.info('Done: File sent %s' % filepath)
+
+ except Exception, error:
+ self.logger.error(error)
+
+ self.send_lock.release()
+
+ def handle_headers(self, data):
+ """
+ Handler header and return missing data
+ """
+
+ #Response Header
+ if data.startswith('-----BEGIN XMLRESPONSE'):
+ try:
+ out = XMLResponseRegex.match(data)
+
+ if out:
+ self.current_id = int(out.group('id'))
+ self.current_size = int(out.group('size'))
+ self.current_type = XMLRESPONSE_TYPE
+ self.current_size_remaining = self.current_size
+ self.current_data = []
+ data = out.group('data')
+ else:
+ data = ""
+
+ except:
+ traceback.print_exc()
+ data = ""
+
+ return data
+
+ #Response End
+ elif (self.current_type == XMLRESPONSE_TYPE and
+ data.startswith(END_XMLRESPONSE_HEADER)):
+
+ self.check_and_alert_size_remaining()
+
+ outdata = ''.join(self.current_data)
+
+ self.current_type = None
+ self.current_data = []
+ id = self.current_id
+
+ try:
+ response = xmlpickler_loads(outdata)[0][0]
+
+ if self.open_responses.has_key(id):
+ self.open_responses[id].set_value(response)
+ self.open_responses.pop(id)
+
+ except Exception, error:
+ self.logger.error(error)
+ traceback.print_exc()
+
+ data = data[len(END_XMLRESPONSE_HEADER):]
+
+ return data
+
+ #Request Header
+ elif data.startswith('-----BEGIN XMLREQUEST'):
+
+ try:
+ out = XMLRequestRegex.match(data)
+
+ if out:
+ self.current_id = int(out.group('id'))
+ self.current_size = int(out.group('size'))
+ self.current_type = XMLREQUEST_TYPE
+ self.current_size_remaining = self.current_size
+ self.current_data = []
+
+ data = out.group('data')
+ else:
+ data = ""
+
+ except Exception, error:
+ self.logger.error(error)
+ traceback.print_exc()
+ data = ""
+
+ return data
+
+ #End Request
+ elif (self.current_type == XMLREQUEST_TYPE and
+ data.startswith(END_XMLREQUEST_HEADER)):
+
+ self.check_and_alert_size_remaining()
+
+ outdata = ''.join(self.current_data)
+ self.current_type = None
+ self.current_data = []
+ id = self.current_id
+
+ params, method = xmlpickler_loads(outdata)
+
+ if self.server.dispatch_func:
+ response = self.server.dispatch_func(self.hash_id,
+ method, params)
+
+ else:
+ response = None
+
+ self.send_response(id, response)
+ data = data[len(END_XMLREQUEST_HEADER):]
+
+ return data
+
+ #SendFile Begin
+ elif data.startswith('-----BEGIN SENDFILE'):
+
+ try:
+ out = SendFileRegex.match(data)
+
+ if out:
+ self.current_method = out.group('method')
+ self.current_size = int(out.group('size'))
+ self.current_type = SENDFILE_TYPE
+ self.current_size_remaining = self.current_size
+ self.current_data = []
+ data = out.group('data')
+ else:
+ data = ""
+
+ except Exception, error:
+ self.logger.error(error)
+ traceback.print_exc()
+ data = ""
+
+ return data
+
+ #SendFile End
+ elif (self.current_type == SENDFILE_TYPE and
+ data.startswith(END_SENDFILE_HEADER)):
+
+ data = ''.join(self.current_data)
+ method = self.current_method
+ self.current_data = []
+ self.current_type = None
+
+ self.logger.debug('done sent file, method:%s, size:%d' %
+ (self.current_method, self.current_size))
+
+ self.check_and_alert_size_remaining()
+
+ if (self.server.recvfile_func and
+ callable(self.server.recvfile_func)):
+
+ self.server.recvfile_func(method, data)
+
+ data = data[len(END_SENDFILE_HEADER):]
+
+ return data
+
+ def handle_data(self, data, client_address):
+ """
+ Handle data received
+ """
+
+ if not self.current_type:
+ self.logger.debug('error no type defined')
+ return
+
+ self.current_data.append(data[:self.current_size_remaining])
+ self.current_size_remaining -= len(data[:self.current_size_remaining])
+
+ def handler_io(self, session, flags):
+ """
+ Handler all data received
+ """
+
+ if flags & gobject.IO_ERR:
+ print "Flags IO_ERR"
+ self.close_session()
+ return False
+
+ if flags & gobject.IO_HUP:
+ print "Flags IO_HUP"
+ self.close_session()
+ return False
+
+ try:
+ data = session.recv(1024)
+
+ if data == 0 or data == '' or data == 'CLOSE':
+ raise IOError('Disconnected from client')
+
+ # Identification packet
+ if data.startswith('-----HASH_ID'):
+ m = HashIDRegex.match(data)
+
+ if m:
+ hash_id = m.group('hash_id')
+ data = m.group('data')
+ else:
+ hash_id = None
+ data = ""
+
+ if hash_id and not self.hash_id:
+ self.hash_id = hash_id
+ self.server.emit('connected', self.client_address,
+ self, self.hash_id)
+
+ #headers
+ if data.startswith('-----'):
+ try:
+ data = self.handle_headers(data)
+ except:
+ traceback.print_exc()
+ data = ""
+
+ #finally data
+ if data:
+ self.handle_data(data, self.client_address)
+
+ return True
+
+ except Exception, error:
+ self.logger.error(str(error))
+ self.close_session()
+ return False
+
+ def check_hash_id(self):
+ """
+ Check hash id after 5 seconds after connection up
+ """
+ if not self.hash_id:
+ self.logger.error('Close Connection: Because no sent hash_id')
+ self.close_session()
+
+ def close_session(self):
+ """
+ Close Socket Session
+ """
+ self.server.disconnect_session(self)
+
+ def check_and_alert_size_remaining(self):
+ if self.current_size_remaining != 0:
+ self.logger.warning('size_remaining != 0, size_remaing = %d' % self.current_size_remaining)
+
\ No newline at end of file
Added: trunk/openlh-core/src/OpenlhCore/net/response.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/response.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/response.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto Júnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import gobject
+
+class Response(gobject.GObject):
+ waiting = True
+ done = False
+
+ __gsignals__ = {'done': (gobject.SIGNAL_RUN_FIRST,
+ gobject.TYPE_NONE,
+ (gobject.TYPE_PYOBJECT,)),
+ }
+
+ def __init__(self, id):
+ self.__gobject_init__()
+ self.id = id
+
+ def get_value(self):
+ if hasattr(self, 'value'):
+ return self.value
+ else:
+ raise ResponseError('Response is not done')
+
+ def set_value(self, value):
+ self.value = value
+ self.done = True
+ self.waiting = False
+ self.emit('done', self.value)
\ No newline at end of file
Added: trunk/openlh-core/src/OpenlhCore/net/server.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/server.py (rev 0)
+++ trunk/openlh-core/src/OpenlhCore/net/server.py 2008-10-11 17:27:44 UTC (rev 289)
@@ -0,0 +1,188 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2008 Wilson Pinto Júnior <wi...@op...>
+#
+# 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 3 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import gobject
+import socket
+import logging
+import traceback
+
+try:
+ from OpenlhServer.net.backends import gnutls_backend as gnutls
+except Exception, error:
+ print error
+ gnutls = None
+
+try:
+ from OpenlhServer.net.backends import openssl_backend as openssl #this backend is not working now
+except Exception, error:
+ print error
+ openssl = None
+
+class NetServer(gobject.GObject):
+ """
+ Network Server Class
+ """
+
+ __gsignals__ = {'connected':(gobject.SIGNAL_RUN_FIRST,
+ gobject.TYPE_NONE,
+ (gobject.TYPE_PYOBJECT,
+ gobject.TYPE_PYOBJECT,
+ gobject.TYPE_PYOBJECT
+ )),
+
+ 'disconnected':(gobject.SIGNAL_RUN_FIRST,
+ gobject.TYPE_NONE,
+ (gobject.TYPE_PYOBJECT,
+ gobject.TYPE_PYOBJECT
+ )),
+
+ }
+
+ request_queue_size = 100
+ allow_reuse_address = True
+ connected_clients = []
+ connected_clients_by_addr = {}
+ handshake = True
+ dispatch_func = None
+ recvfile_func = None
+
+ def __init__(self, server_address, RequestHandlerClass, privkey_path, selfsigned_path):
+
+ self.__gobject_init__()
+
+ self.logger = logging.getLogger('net:Server')
+
+ self.server_address = server_address
+ self.RequestHandlerClass = RequestHandlerClass
+
+ self.session = gnutls.ServerSessionFactory(privkey_path, selfsigned_path)
+
+ self.server_bind()
+ self.server_activate()
+
+ def server_bind(self):
+
+ if self.allow_reuse_address:
+ self.session.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+ self.session.bind(self.server_address)
+ self.server_address = self.session.getsockname()
+
+ def server_activate(self):
+ """
+ Activate the server
+ """
+
+ self.session.listen(self.request_queue_size)
+
+ def server_close(self):
+
+ self.session.shutdown()
+ self.session.close()
+
+ def fileno(self):
+ return self.session.fileno()
+
+ def disconnect_session(self, session):
+
+ session.close()
+
+ if session in self.connected_clients:
+ self.connected_clients.remove(session)
+
+ address = session.client_address
+
+ if self.connected_clients_by_addr.has_key(address[0]):
+ if session in self.connected_clients_by_addr[address[0]]:
+ self.connected_clients_by_addr[address[0]].remove(session)
+
+ if not session.disconnected:
+ self.emit('disconnected', address, session.hash_id)
+
+ session.disconnected = True
+
+ def process_connection(self, request, client_address):
+ try:
+ self.finish_request(request, client_address)
+ self.close_connection(request)
+
+ except:
+ self.handle_error(request, client_address)
+ self.close_connection(request)
+
+ def finish_request(self, request, client_address):
+
+ session = self.RequestHandlerClass(request, client_address, self)
+ self.connected_clients.append(session)
+
+ if not self.connected_clients_by_addr.has_key(client_address[0]):
+ self.connected_clients_by_addr[client_address[0]] = []
+
+ self.connected_clients_by_addr[client_address[0]].append(session)
+
+ def handle_connection(self, server_session, flags):
+
+ if flags & gobject.IO_ERR:
+ print "Flags IO_ERR"
+ return False
+
+ if flags & gobject.IO_HUP:
+ print "Flags IO_HUP"
+ return False
+
+ try:
+ session, client_address = server_session.accept()
+ except socket.error:
+ return True
+
+ try:
+ self.process_connection(session, client_address)
+ except:
+ traceback.print_exc()
+ self.handle_error(session, client_address)
+ self.close_connection(session)
+
+ return True
+
+ def close_connection(self, request):
+ """Called to clean up an individual request."""
+ request.close()
+
+ def handle_error(self, request, client_address):
+ print '-' * 40
+ print 'Exception happened during processing of request from',
+ print client_address
+ traceback.print_exc() # XXX But this goes to stderr!
+ print '-' * 40
+
+ def serve_forever(self):
+ self.io_watch_tag = gobject.io_add_watch(self.session,
+ gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP,
+ self.handle_connection)
+
+ def serve_stop(self):
+ self.closeall_connections()
+
+ if self.io_watch_tag:
+ gobject.source_remove(self.io_watch_tag)
+
+ self.close_connection(self.session)
+
+ def closeall_connections(self):
+ for con in self.connected_clients:
+ con.close()
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|