[Openlanhouse-development] SF.net SVN: openlanhouse:[294] trunk
Status: Pre-Alpha
Brought to you by:
n3rd3x
|
From: <n3...@us...> - 2008-10-11 19:21:26
|
Revision: 294
http://openlanhouse.svn.sourceforge.net/openlanhouse/?rev=294&view=rev
Author: n3rd3x
Date: 2008-10-11 19:21:16 +0000 (Sat, 11 Oct 2008)
Log Message:
-----------
* Client network moved to OpenlhCore Module
Modified Paths:
--------------
trunk/openlh-client/src/OpenlhClient/main.py
trunk/openlh-core/src/OpenlhCore/net/backends/gnutls_backend.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-server/src/OpenlhServer/__init__.py
Modified: trunk/openlh-client/src/OpenlhClient/main.py
===================================================================
--- trunk/openlh-client/src/OpenlhClient/main.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-client/src/OpenlhClient/main.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -23,14 +23,17 @@
import gconf
import gobject
+from OpenlhCore.net.client import NetClient
+
from OpenlhClient.ui import icons
from OpenlhClient.ui import tray
from OpenlhClient.globals import *
-from OpenlhClient import login, network
+from OpenlhClient import login
from OpenlhClient.utils import get_os, md5_cripto, humanize_time
from OpenlhClient.ui import dialogs
from OpenlhClient.ui.utils import get_gtk_builder
from OpenlhClient.dbus_manager import Server
+
from os import remove
from os import path as ospath
_ = gettext.gettext
@@ -92,13 +95,13 @@
if not self.port: #FIXED BUG: Cannot connect if gconf value is None
self.port = 4558
- self.network = network.Client(self.server, self.port,
+ self.netclient = NetClient(self.server, self.port,
CLIENT_TLS_CERT, CLIENT_TLS_KEY, self.hash_id)
- self.network.connect('connected', self.connected)
- self.network.connect('disconnected', self.disconnected)
- self.network.dispatch_func = self.dispatch
- self.network.recvfile_func = self.recvfile_func
+ self.netclient.connect('connected', self.connected)
+ self.netclient.connect('disconnected', self.disconnected)
+ self.netclient.dispatch_func = self.dispatch
+ self.netclient.recvfile_func = self.recvfile_func
#icons
self.icons = icons.Icons()
@@ -143,7 +146,7 @@
self.login_window = login.Login(self)
self.login_window.run()
- if not self.network.start():
+ if not self.netclient.start():
self.login_window.set_connected(False)
def on_window_delete_event(self, *args):
@@ -296,13 +299,13 @@
if 'background_md5' in data:
if (data['background_md5'] != self.background_md5
or not(self.background_md5)):
- self.network.request('get_background')
+ self.netclient.request('get_background')
background_requested = True
logo_requested = False
if 'logo_md5' in data:
if (data['logo_md5'] != self.logo_md5 or not(self.logo_md5)):
- self.network.request('get_logo')
+ self.netclient.request('get_logo')
logo_requested = True
if 'use_background' in data:
@@ -418,13 +421,13 @@
self.set_logo(data)
def reload_network(self):
- self.network = network.Client(self.server, self.port,
+ self.netclient = NetClient(self.server, self.port,
CLIENT_TLS_CERT, CLIENT_TLS_KEY, self.hash_id)
- self.network.connect('connected', self.connected)
- self.network.connect('disconnected', self.disconnected)
- self.network.dispatch_func = self.dispatch
- self.network.recvfile_func = self.recvfile_func
+ self.netclient.connect('connected', self.connected)
+ self.netclient.connect('disconnected', self.disconnected)
+ self.netclient.dispatch_func = self.dispatch
+ self.netclient.recvfile_func = self.recvfile_func
def update_time_status(self):
if not self.update_time:
@@ -458,7 +461,7 @@
self.update_time_status)
def monitory_status(self):
- request = self.network.request('get_status')
+ request = self.netclient.request('get_status')
request.connect("done", self.on_get_status_request_done)
self.monitory_handler_id = gobject.timeout_add(120000,
self.monitory_status)
@@ -599,7 +602,7 @@
def on_login(self, username, password):
self.login_window.set_lock_all(True)
- request = self.network.request('login', (username, password))
+ request = self.netclient.request('login', (username, password))
request.connect("done", self.on_login_response)
def on_logout_menuitem_activate(self, obj):
@@ -614,5 +617,5 @@
dlg.destroy()
if response == gtk.RESPONSE_YES:
- self.network.request('logout')
+ self.netclient.request('logout')
\ No newline at end of file
Modified: trunk/openlh-core/src/OpenlhCore/net/backends/gnutls_backend.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/backends/gnutls_backend.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-core/src/OpenlhCore/net/backends/gnutls_backend.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -56,4 +56,25 @@
def accept(self):
new_session, address = self.session.accept()
session = ServerSession(new_session)
- return (session, address)
\ No newline at end of file
+ return (session, address)
+
+class ClientSession:
+ address_family = socket.AF_INET
+ socket_type = socket.SOCK_STREAM
+
+ def __init__(self, privkey_path, selfsigned_path):
+
+ self.cert = gnutls.crypto.X509Certificate(open(selfsigned_path).read())
+ self.key = gnutls.crypto.X509PrivateKey(open(privkey_path).read())
+
+ self.cred = gnutls.connection.X509Credentials(self.cert, self.key)
+
+ self.socket = socket.socket(self.address_family, self.socket_type)
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+ self.session = gnutls.connection.ClientSession(self.socket, self.cred)
+
+ def __getattr__(self, name):
+ ## Generic wrapper for the underlying socket methods and attributes
+ return getattr(self.session, name)
+
\ No newline at end of file
Modified: trunk/openlh-core/src/OpenlhCore/net/client.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/client.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-core/src/OpenlhCore/net/client.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
-# Copyright (C) 2008 Wilson Pinto J\xFAnior <wi...@op...>
+# 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
@@ -14,4 +14,435 @@
# 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
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import sys
+import re
+import gobject
+import socket
+import logging
+import traceback
+
+try:
+ from OpenlhCore.net.backends import gnutls_backend as gnutls
+except Exception, error:
+ print error
+ gnutls = None
+
+try:
+ from OpenlhCore.net.backends import openssl_backend as openssl #this backend is not working now
+except Exception, error:
+ print error
+ openssl = None
+
+from xmlrpclib import loads as xmlpickler_loads
+from xmlrpclib import dumps as xmlpickler_dumps
+
+from OpenlhCore.net.response import Response
+from OpenlhCore.net.constants import *
+
+from os import path as ospath
+from threading import RLock
+
+class NetClient(gobject.GObject):
+ """
+ Network Client Class
+ """
+ __gsignals__ = {'connected':(gobject.SIGNAL_RUN_FIRST,
+ gobject.TYPE_NONE,
+ (gobject.TYPE_STRING,)),
+
+ 'disconnected':(gobject.SIGNAL_RUN_FIRST,
+ gobject.TYPE_NONE,
+ ()),
+
+ }
+
+ rbufsize = -1
+ wbufsize = 0
+ receive = False
+ handshake = True
+
+ current_id = None
+ current_size = None
+ current_type = None
+ current_size_remaining = None
+ current_data = None
+ current_method = None
+
+ currid = 1
+
+ dispatch_func = None
+ recvfile_func = None
+
+ open_responses = {}
+ io_session_handler_id = 0
+
+ def __init__(self, server, port, cert_path, key_path, hash_id):
+
+ self.__gobject_init__()
+
+ self._server = server
+ self._port = port
+ self.hash_id = hash_id
+
+ self.send_lock = RLock()
+ self.logger = logging.getLogger('net:Client')
+
+ self.session = gnutls.ClientSession(key_path, cert_path)
+
+ def handle_headers(self, data):
+ """
+ Handler header and return missing data
+ """
+
+ #Begin XMLRESPONSE
+ 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
+
+ #End XMLRESPONSE
+ 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 = []
+
+ response = xmlpickler_loads(outdata)[0][0]
+
+ if self.open_responses.has_key(self.current_id):
+ self.open_responses[self.current_id].set_value(response)
+ self.open_responses.pop(self.current_id)
+
+ data = data[len(END_XMLRESPONSE_HEADER):]
+
+ return data
+
+ #Begin XMLREQUEST
+ 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:
+ traceback.print_exc()
+ data = ""
+
+ return data
+
+ #End XMLREQUEST
+ 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.dispatch_func:
+ response = self.dispatch_func(method, params)
+
+ else:
+ response = None
+
+ self.send_response(id, response)
+
+ data = data[len(END_XMLREQUEST_HEADER):]
+
+ return data
+
+ #Begin SENDFILE
+ elif data.startswith('-----BEGIN SENDFILE'):
+
+ try:
+ out = SendFileRegex.match(data)
+
+ if out:
+ self.current_id = int(out.group('id'))
+ 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:
+ traceback.print_exc()
+ data = ""
+
+ return data
+
+ #End SENDFILE
+ 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.check_and_alert_size_remaining()
+
+ if self.recvfile_func and callable(self.recvfile_func):
+ self.recvfile_func(method, data)
+
+ data = data[len(END_SENDFILE_HEADER):]
+
+ return data
+
+ def handle_data(self, data):
+ """
+ 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 -= len(self.current_data[-1])
+
+ def handle_io(self, session, flags):
+ """
+ Handler all data received
+ """
+
+ if flags & gobject.IO_ERR:
+ print "Flags IO_ERR"
+ return False
+
+ if flags & gobject.IO_HUP:
+ print "Flags IO_HUP"
+ return False
+
+ try:
+ data = self.session.recv(1024)
+
+ if data == 0 or data == '' or data == 'CLOSE':
+ raise IOError('Disconnected from server')
+
+ #headers
+ if data.startswith('-----'):
+
+ try:
+ data = self.handle_headers(data)
+ except Exception, error:
+ traceback.print_exc()
+ data = ""
+
+ #finally data
+ if data:
+ self.handle_data(data)
+
+ return True
+
+ except Exception, error:
+ self.logger.error(error)
+ self.stop()
+
+ return False
+
+ def start(self):
+ """
+ Start Connection in server
+ """
+ try:
+ self.session.connect((self._server, self._port))
+
+ if self.handshake:
+ self.session.handshake()
+
+ self.emit('connected', (self._server, self._port))
+
+ self.rfile = self.session.makefile('rb', self.rbufsize)
+ self.wfile = self.session.makefile('wb', self.wbufsize)
+
+ self.send_hash_id() #Send packet identification to server
+ self.io_session_handler_id = gobject.io_add_watch(self.session,
+ gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP,
+ self.handle_io)
+
+ return True
+
+ except Exception, error:
+ try:
+ (code, msg) = error
+ except ValueError:
+ msg = str(error)
+
+ traceback.print_exc()
+ self.logger.error(msg)
+ return False
+
+ def stop(self):
+ """
+ Close Connection in Server
+ """
+ self.logger.info('connection closed')
+ self.receive = 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.emit('disconnected')
+
+ def send_hash_id(self):
+ """
+ Send hash_id packet information to server
+ """
+ self.session.send(HASH_ID_HEADER % self.hash_id)
+
+ 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 ID=%d SIZE=%d-----" % (self.currid, size)
+ self.send_lock.acquire()
+ self.session.send(head)
+ self.session.send(xmlout)
+ self.session.send("-----END XMLREQUEST-----")
+
+ self.send_lock.release()
+
+ response = Response(self.currid)
+ self.open_responses[self.currid] = response
+ self.currid += 1
+
+ return response
+
+ def send_response(self, id, response):
+ """
+ Send Response to peer
+ """
+
+ self.logger.info('sending response number %d' % id)
+
+ try:
+ output = xmlpickler_dumps((response,), methodresponse=1)
+ head = '-----BEGIN XMLRESPONSE ID=%d SIZE=%d-----' % (id, len(output))
+ self.send_lock.acquire()
+ self.session.send(head)
+ self.session.send(output)
+ self.session.send("-----END XMLRESPONSE-----")
+
+ except Exception, error:
+ self.logger.error(error)
+
+ self.send_lock.release()
+
+ 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 to server' % filepath)
+
+ assert ospath.exists(filepath), 'File not Found'
+
+ f = open(filepath)
+ size = ospath.getsize(filepath)
+
+ head = "-----BEGIN SENDFILE ID=%d METHOD=%s SIZE=%d-----" % (self.currid,
+ method, size)
+
+ self.currid += 1
+ self.send_lock.acquire()
+
+ try:
+ self.session.send(head)
+
+ while True:
+ data = f.read(1024)
+ if data != "":
+ self.session.send(data)
+ else:
+ break
+
+ self.session.send("-----END SENDFILE-----")
+
+ self.logger.info('Done: File sent %s to server' % filepath)
+
+ except Exception, error:
+ self.logger.error(error)
+
+ self.send_lock.release()
+
+ 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
Modified: trunk/openlh-core/src/OpenlhCore/net/constants.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/constants.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-core/src/OpenlhCore/net/constants.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -16,6 +16,8 @@
# 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 re
+
XMLRESPONSE_TYPE, XMLREQUEST_TYPE, SENDFILE_TYPE = range(1, 4)
BEGIN_XMLRESPONSE_HEADER = '-----BEGIN XMLRESPONSE ID=%d SIZE=%d-----'
@@ -25,4 +27,17 @@
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
+END_SENDFILE_HEADER = "-----END SENDFILE-----"
+
+HASH_ID_HEADER = '-----HASH_ID=%s-----'
+
+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>(.*))')
\ No newline at end of file
Modified: trunk/openlh-core/src/OpenlhCore/net/request_handler.py
===================================================================
--- trunk/openlh-core/src/OpenlhCore/net/request_handler.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-core/src/OpenlhCore/net/request_handler.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -33,17 +33,6 @@
from OpenlhCore.net.response import Response
from OpenlhCore.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
Modified: trunk/openlh-server/src/OpenlhServer/__init__.py
===================================================================
--- trunk/openlh-server/src/OpenlhServer/__init__.py 2008-10-11 17:59:13 UTC (rev 293)
+++ trunk/openlh-server/src/OpenlhServer/__init__.py 2008-10-11 19:21:16 UTC (rev 294)
@@ -16,5 +16,5 @@
# 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__ = ('net', 'daemon', 'globals', 'ui', 'db', 'g_timer',
+__all__ = ('daemon', 'globals', 'ui', 'db', 'g_timer',
'utils', 'certgen', 'config')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|