class TCPServer(QObject): def __init__(self, port): QObject.__init__(self) # logging instance self.log = logging.getLogger('SMIGOL.TCPServer.{0}'.format(port)) # TCP server to listen for control commands self.tcp_server = QTcpServer() # TCP server listenning port self.tcp_port = port # TCP socket connection self.tcp_connection = None def start(self): self.log.info("Starting TCP server...") if self.tcp_server.listen(port=self.tcp_port): txt = "Listening at http://localhost:{0} for a connection" self.log.info(txt.format(self.tcp_server.serverPort())) self.tcp_server.newConnection.connect(self._accept_connection) else: self.log.critical("Unable to start: {0}".format( self.tcp_server.errorString())) def disconnect(self): if self.tcp_connection and self.tcp_connection.state( ) == QTcpSocket.ConnectedState: loop = QEventLoop() self.tcp_connection.disconnected.connect(loop.quit) self.tcp_connection.disconnectFromHost() self.log.debug("Entering disconnect state...") if self.tcp_connection.state() == QTcpSocket.ConnectedState: loop.exec_() self.log.debug("Done waiting, closing server...") if self.tcp_server.isListening(): self.tcp_server.close() self.log.info("Server closed") def _accept_connection(self): if not self.tcp_connection: self.tcp_connection = self.tcp_server.nextPendingConnection() self.tcp_connection.error.connect(self._error_occurred) txt = "Accepted connection" self.log.debug(txt.format(self.tcp_server.serverPort())) else: self.log.warning("Received a second connection, ignoring it...") self.tcp_server.nextPendingConnection() def _error_occurred(self, socket_error): if socket_error == QTcpSocket.RemoteHostClosedError: self.log.info(self.tcp_connection.errorString()) else: self.log.error(self.tcp_connection.errorString())
class TunnelServer(object): """A server for tunnel instances.""" def __init__(self, cookie): """Initialize this tunnel instance.""" self.tunnels = [] self.cookie = cookie self.server = QTcpServer(QCoreApplication.instance()) self.server.newConnection.connect(self.new_connection) self.server.listen(QHostAddress.LocalHost, 0) logger.info("Starting tunnel server at port %d", self.port) def new_connection(self): """On a new connection create a new tunnel instance.""" logger.info("New connection made") local_socket = self.server.nextPendingConnection() tunnel = Tunnel(local_socket, self.cookie) self.tunnels.append(tunnel) def shutdown(self): """Terminate every connection.""" # TODO: handle this gracefully in an upcoming branch @property def port(self): """The port where this server listens.""" return self.server.serverPort()
class ServerApp(FreeseerApp): STATUS = ["Offline", "Online"] status = STATUS[0] clients = [] passPhrase = '' ipAddress = None def __init__(self): FreeseerApp.__init__(self) self.resize(400, 300) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/freeseer/logo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) configdir = os.path.abspath(os.path.expanduser('~/.freeseer/')) self.logger = Logger(configdir) logging.info("Logger initialized") self.server = QTcpServer(self) logging.info("Starting Freeseer Server") # Setup Widget self.mainWidget = ControllerServerWidget() self.setCentralWidget(self.mainWidget) self.mainWidget.hostCombo.addItem(QtCore.QString("0.0.0.0")) #Connections self.connect(self.server, QtCore.SIGNAL('newConnection()'), self.acceptConnection) self.connect(self.mainWidget.startButton, QtCore.SIGNAL('pressed()'), self.startServer) self.connect(self.mainWidget.hostCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.ipComboBoxHandler) self.connect(self.mainWidget.passEdit, QtCore.SIGNAL('textChanged(QString)'), self.onPassChanged) # Initialize Passphrase Field self.mainWidget.passEdit.setPlaceholderText("Passphrase required to start server") self.mainWidget.startButton.setEnabled(False) # Client Control self.connect(self.mainWidget.clientStartButton, QtCore.SIGNAL('pressed()'), self.sendRecordCommand) self.connect(self.mainWidget.clientStopButton, QtCore.SIGNAL('pressed()'), self.sendStopCommand) self.connect(self.mainWidget.clientDisconnectButton, QtCore.SIGNAL('pressed()'), self.disconnectClients) self.connect(self.mainWidget.clientList, QtCore.SIGNAL('itemSelectionChanged()'), self.updateClientButtons) self.load_settings() self.updateStatus(self.status) ### ### Translation Related ### def retranslate(self): self.setWindowTitle(self.uiTranslator.translate("ControllerServerApp", "Controller Server")) # # Reusuable Strings # self.serverStatusString = self.uiTranslator.translate("ControllerServerApp", "Server status") self.startServerString = self.uiTranslator.translate("ControllerServerApp", "Start Server") self.stopServerString = self.uiTranslator.translate("ControllerServerApp", "Stop Server") self.startRecordingString = self.uiTranslator.translate("ControllerServerApp", "Start Recording") self.stopRecordingString = self.uiTranslator.translate("ControllerServerApp", "Stop Recording") self.pauseRecordingString = self.uiTranslator.translate("ControllerServerApp", "Pause Recording") self.resumeRecordingString = self.uiTranslator.translate("ControllerServerApp", "Resume Recording") # --- End Reusable Strings # # Server Settings # self.mainWidget.toolBox.setItemText(0, self.uiTranslator.translate("ControllerServerApp", "Server Settings")) self.mainWidget.hostLabel.setText(self.uiTranslator.translate("ControllerServerApp", "IP Address")) self.mainWidget.portLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Port")) self.mainWidget.passLabel.setText(self.uiTranslator.translate("ControllerServerApp", "Passphrase")) # Button if self.status == self.STATUS[0]: self.mainWidget.startButton.setText(self.startServerString) else: self.mainWidget.startButton.setText(self.stopServerString) # --- End Server Settings # # Control Clients # self.mainWidget.toolBox.setItemText(1, self.uiTranslator.translate("ControllerServerApp", "Control Clients")) self.updateClientButtons() self.mainWidget.clientDisconnectButton.setText(self.uiTranslator.translate("ControllerServerApp", "Disconnect")) # --- End Control Clients ### ### Server Methods ### def load_settings(self): logging.info('Loading settings...') configdir = os.path.abspath(os.path.expanduser('~/.freeseer/')) self.config = Config(configdir) # Load default language. actions = self.menuLanguage.actions() for action in actions: if action.data().toString() == self.config.default_language: action.setChecked(True) self.translate(action) break def startServer(self): if self.status == self.STATUS[0]: # Check if status is Offline if self.ipAddress is None: self.ipAddress = QHostAddress(self.mainWidget.hostCombo.currentText()) self.server.listen(self.ipAddress, PORT) self.status = self.STATUS[1] # Set Running self.mainWidget.hostCombo.setEnabled(False) logging.info("Started server %s: %s", self.server.serverAddress().toString(), str(self.server.serverPort())) elif self.status == self.STATUS[1]: # Check if status is Online self.server.close() self.status = self.STATUS[0] # Set status Offline self.disconnectAllClients() self.mainWidget.hostCombo.setEnabled(True) self.ipAddress = None self.updateStatus(self.status) self.setPassPhrase() self.setConnectionLabel() self.retranslate() def updateStatus(self, status): self.mainWidget.statusLabel.setText("%s: %s" % (self.serverStatusString, status)) def setConnectionLabel(self): text = "%s:%s" % (self.mainWidget.hostCombo.currentText(), self.mainWidget.portEdit.text()) self.mainWidget.settingsEdit.setText(text) if self.mainWidget.passEdit.text(): self.mainWidget.settingsEdit.setText("%s@%s" % (self.mainWidget.passEdit.text(), text)) ''' This function is for changing the passphrase. It saves the new passphrase in the self.passPhrase after encoding it. ''' def setPassPhrase(self): self.passphrase = self.mainWidget.passEdit.text() logging.info ("Passphrase set to %s", self.passphrase) #self.passPhrase = base64.b64encode(self.passPhrase) self.passphrase = str(self.passphrase) self.passphrase = pwd_context.encrypt(self.passphrase) ''' This function reads the passphrase sent from the client. It decodes the saved passphrase and the one that client sent and compares. Client is accepted if the passphrases match. Otherwise client is rejected ''' def readPassPhrase(self): client = QtCore.QObject.sender(self) message = client.read(client.bytesAvailable()) logging.info("Client said: %s", message) if pwd_context.verify(message, self.passphrase) is False: client.disconnectFromHost() logging.info("Client rejected") else: self.clients.append(client) self.updateList() logging.info("Client accepted") self.disconnect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase) self.connect(client, QtCore.SIGNAL('readyRead()'), self.startRead) def onPassChanged(self): """Disable 'Start' button only when the passphrase field is empty.""" if self.mainWidget.passEdit.text(): self.mainWidget.startButton.setEnabled(True) else: self.mainWidget.startButton.setEnabled(False) def ipComboBoxHandler(self): self.ipAddress = QHostAddress(self.ipComboBox.itemText(self.ipComboBox.currentIndex())) logging.info("Server IP changed to: %s", self.ipAddress.toString()) ### ### Messaging ### def startRead(self): client = QtCore.QObject.sender(self) message = client.read(client.bytesAvailable()) logging.info("Client said: %s", message) return message def sendMessage(self, client, message): block = QtCore.QByteArray() block.append(message) client.write(block) ### ### Client List Methods ### ''' This is the function to handle a new connection. ''' def acceptConnection(self): client = self.server.nextPendingConnection() self.connect(client, QtCore.SIGNAL("disconnected()"), self.clientDisconnected) self.connect(client, QtCore.SIGNAL('readyRead()'), self.readPassPhrase) def clientDisconnected(self): client = QtCore.QObject.sender(self) logging.info("Client disconnected") self.clients.remove(client) self.updateList() self.updateClientButtons() ''' This method is to update the list ''' def updateList(self): self.mainWidget.clientList.clear() for i in range(0, len(self.clients)): client = self.clients[i] listItem = ClientListItem(client) self.mainWidget.clientList.addItem(listItem) clientLabel = QtGui.QLabel('F1', self) clientLabel.move(5 + (i * 20), 150) def addClientToList(self, client): self.clients.append(object) listItem = ClientListItem(client) self.mainWidget.clientList.addItem(listItem) def removeClientFromTheList(self, client): self.clients.remove(client) self.updateList() ''' Sends a record command to the selected clients ''' def sendRecordCommand (self): buttonText = self.mainWidget.clientStartButton.text() # Find out what command to send if buttonText == self.startRecordingString or buttonText == self.resumeRecordingString: command = COMMANDS[1] # Set Record elif buttonText == self.pauseRecordingString: command = COMMANDS[2] # Set Pause # Send command for i in range(0, len(self.mainWidget.clientList.selectedItems())): c_item = self.mainWidget.clientList.selectedItems()[i] client = c_item.client self.sendMessage(client, command) if command == COMMANDS[1]: # Check if command is Record c_item.changeStatus(CLIENT_STATUS[1]) # Set Recording elif command == COMMANDS[2]: # Check if command is Pause c_item.changeStatus(CLIENT_STATUS[2]) # Set Paused logging.info("Sent %s command to %s" % (command, c_item.address)) self.updateClientButtons() ''' Sends a stop command to selected clients ''' def sendStopCommand (self): command = COMMANDS[0] # Set Stop command for i in range(0, len(self.mainWidget.clientList.selectedItems())): c_item = self.mainWidget.clientList.selectedItems()[i] client = c_item.client self.sendMessage(client, command) c_item.changeStatus(CLIENT_STATUS[3]) # Set Idle logging.info("Sent %s command to %s" % (command, c_item.address)) self.updateClientButtons() ''' Method to disconnect all clients selected from the list ''' def disconnectClients(self): for i in range(0, len(self.mainWidget.clientList.selectedItems())): client = self.mainWidget.clientList.selectedItems()[i].client client.disconnectFromHost() ''' Method to disconnect all clients that are connected ''' def disconnectAllClients(self): for i in range(0, self.mainWidget.clientList.count()): client = self.mainWidget.clientList.item(i).client client.disconnectFromHost() def updateClientButtons(self): if len(self.mainWidget.clientList.selectedItems()) > 0: self.mainWidget.clientDisconnectButton.setEnabled(True) self.mainWidget.clientStartButton.setEnabled(True) for i in range(0, len(self.mainWidget.clientList.selectedItems())): clientStatus = self.mainWidget.clientList.selectedItems()[i].status logging.debug("Client status: %s", clientStatus) if clientStatus == CLIENT_STATUS[1]: # Client is Recording self.mainWidget.clientStartButton.setText(self.pauseRecordingString) self.mainWidget.clientStopButton.setEnabled(True) elif clientStatus == CLIENT_STATUS[3]: # Client is Idle self.mainWidget.clientStartButton.setText(self.startRecordingString) self.mainWidget.clientStopButton.setEnabled(False) elif clientStatus == CLIENT_STATUS[2]: # Client is Paused self.mainWidget.clientStartButton.setText(self.resumeRecordingString) self.mainWidget.clientStopButton.setEnabled(True) else: self.mainWidget.clientDisconnectButton.setEnabled(False) self.mainWidget.clientStartButton.setEnabled(False) self.mainWidget.clientStartButton.setText(self.startRecordingString) self.mainWidget.clientStopButton.setEnabled(False) self.mainWidget.clientStopButton.setText(self.stopRecordingString)
class HTTPProxy(QObject): debug = True log = sys.stderr username = '******' password = '******' stopServing = pyqtSlot() def __init__(self, parent=None): super(HTTPProxy, self).__init__(parent) self.proxy_server = QTcpServer(self) self.proxy_server.listen(QHostAddress.Any, 8000) self.proxy_server.newConnection.connect(self.manage_request) if self.debug: self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' % self.port()) def port(self): return self.proxy_server.serverPort() def addr(self): return self.proxy_server.serverAddress().toString() def stopServing(self): if self.debug: self.log.write('Service is stopping...\n\n') # does not "close" the server, just stop listening... self.proxy_server.close() if self.proxy_server.hasPendingConnections(): socket = self.proxy_server.nextPendingConnection() while socket: socket.abort() socket = self.proxy_server.nextPendingConnection() def manage_request(self): proxy_server = self.sender() # Qt docs says that the caller of nextPendingConnection() # is the parent of the socket socket = proxy_server.nextPendingConnection() socket.readyRead.connect(self.process_request) socket.disconnected.connect(socket.deleteLater) def authorize_request(self, request_data): return True header = QHttpRequestHeader(QString(request_data)) if self.debug: self.log.write(header.toString()) auth = header.value('Proxy-Authorization') if not auth: return False challenge = base64.b64encode(self.username + ':' + self.password) return challenge == str(auth).split()[1] def process_request(self): socket = self.sender() request_data = socket.readAll() if not self.authorize_request(request_data): socket.write('HTTP/1.1 407 Proxy Authentication Required\r\n') if self.debug: self.log.write('407 Proxy Authentication Required\n\n') socket.write('Proxy-Authenticate: Basic realm="test"\r\n') socket.write('\r\n') socket.disconnectFromHost() return else: # remove Proxy-Authorization header start = request_data.indexOf('Proxy-Authorization:') end = request_data.lastIndexOf('\r\n') request_data.remove(start, end) request_data.append('\r\n') pos = request_data.indexOf('\r\n') request_line = request_data.left(pos) request_data.remove(0, pos + 2) entries = request_line.split(' ') method = entries[0] address = entries[1] version = entries[2] port = '80' if address.count(':') > 1: protocol, host, port = address.split(':') else: protocol, host = address.split(':') print 'address', address #url = QUrl( protocol + host ) url = QUrl.fromEncoded(address) #url.setHost( host ) #url.setPort( int(port) ) if not url.isValid(): if self.debug: self.log.write('Invalid URL: %s\n\n', url) socket.disconnectFromHost() return host = url.host() port = 80 if (url.port() < 0) else url.port() req = url.encodedPath() if url.hasQuery(): req.append('?').append(url.encodedQuery()) request_line = method + ' ' + req + ' ' + version + '\r\n' request_data.prepend(request_line) if self.debug: self.log.write(method + ' ' + address + ' ' + version + '\n\n') key = host + ':' + QString.number(port) proxy_socket = socket.findChild(QTcpSocket, key) if proxy_socket: proxy_socket.setObjectName(key) proxy_socket.setProperty('url', url) proxy_socket.setProperty('request_data', request_data) proxy_socket.write(request_data) else: proxy_socket = QTcpSocket(socket) proxy_socket.setObjectName(key) proxy_socket.setProperty('url', url) proxy_socket.setProperty('request_data', request_data) proxy_socket.connected.connect(self.send_request) proxy_socket.readyRead.connect(self.transfer_data) proxy_socket.disconnected.connect(self.close_connection) proxy_socket.error.connect(self.close_connection) proxy_socket.connectToHost(host, port) def send_request(self): proxy_socket = self.sender() request_data = proxy_socket.property('request_data').toByteArray() proxy_socket.write(request_data) def transfer_data(self): proxy_socket = self.sender() socket = proxy_socket.parent() socket.write(proxy_socket.readAll()) def close_connection(self): proxy_socket = self.sender() if proxy_socket: socket = proxy_socket.parent() if isinstance(socket, QTcpSocket) and socket: socket.disconnectFromHost() if proxy_socket.error() != QTcpSocket.RemoteHostClosedError: url = proxy_socket.property('url').toUrl() error_string = proxy_socket.errorString() if self.debug: self.log.write('Error for %s %s\n\n' % (url, error_string)) proxy_socket.deleteLater()
class RunManager( QObject ): " Manages the external running processes " def __init__( self, mainWindow ): QObject.__init__( self ) self.__mainWindow = mainWindow self.__processes = [] self.__tcpServer = QTcpServer() self.connect( self.__tcpServer, SIGNAL( "newConnection()" ), self.__newConnection ) self.__tcpServer.listen( QHostAddress.LocalHost ) self.__waitTimer = QTimer( self ) self.__waitTimer.setSingleShot( True ) self.connect( self.__waitTimer, SIGNAL( 'timeout()' ), self.__onWaitImer ) return def __newConnection( self ): " Handles new incoming connections " clientSocket = self.__tcpServer.nextPendingConnection() clientSocket.setSocketOption( QAbstractSocket.KeepAliveOption, 1 ) clientSocket.setSocketOption( QAbstractSocket.LowDelayOption, 1 ) QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) ) self.__waitForHandshake( clientSocket ) QApplication.restoreOverrideCursor() return def __waitForHandshake( self, clientSocket ): " Waits for the message with the proc ID " if clientSocket.waitForReadyRead( 1000 ): qs = clientSocket.readAll() us = str( CODEC.fromUnicode( str( qs ) ) ) if not us.endswith( EOT ): return line = us[ 0 : -len( EOT ) ] if not line.startswith( '>' ): return cmdIndex = line.find( '<' ) if cmdIndex == -1: return cmd = line[ 0 : cmdIndex + 1 ] content = line[ cmdIndex + 1 : ] if cmd != ResponseProcID: return # It could only be a redirected process procID = int( content ) procIndex = self.__getProcessIndex( procID ) if procIndex is not None: self.__onProcessStarted( procID ) self.__processes[ procIndex ].procWrapper.setSocket( clientSocket ) return def run( self, path, needDialog ): " Runs the given script with redirected IO " if needDialog: params = GlobalData().getRunParameters( path ) termType = Settings().terminalType profilerParams = Settings().getProfilerSettings() debuggerParams = Settings().getDebuggerSettings() dlg = RunDialog( path, params, termType, profilerParams, debuggerParams, "Run" ) if dlg.exec_() != QDialog.Accepted: return GlobalData().addRunParams( path, dlg.runParams ) if dlg.termType != termType: Settings().terminalType = dlg.termType # The parameters for the run are ready. # Start the run business. remoteProc = RemoteProcess() remoteProc.isProfiling = False remoteProc.procWrapper = RemoteProcessWrapper( path, self.__tcpServer.serverPort() ) if Settings().terminalType == TERM_REDIRECT: remoteProc.widget = RunConsoleTabWidget( remoteProc.procWrapper.procID() ) self.connect( remoteProc.procWrapper, SIGNAL( 'ClientStdout' ), remoteProc.widget.appendStdoutMessage ) self.connect( remoteProc.procWrapper, SIGNAL( 'ClientStderr' ), remoteProc.widget.appendStderrMessage ) self.connect( remoteProc.procWrapper, SIGNAL( 'ClientRawInput' ), remoteProc.widget.rawInput ) self.connect( remoteProc.widget, SIGNAL( 'UserInput' ), self.__onUserInput ) else: remoteProc.widget = None self.connect( remoteProc.procWrapper, SIGNAL( 'Finished' ), self.__onProcessFinished ) self.__processes.append( remoteProc ) if remoteProc.procWrapper.start() == False: # Failed to start - the fact is logged, just remove from the list procIndex = self.__getProcessIndex( remoteProc.procWrapper.procID() ) if procIndex is not None: del self.__processes[ procIndex ] else: if Settings().terminalType != TERM_REDIRECT: if not self.__waitTimer.isActive(): self.__waitTimer.start( 1000 ) return def profile( self, path ): " Profiles the given script with redirected IO " return def killAll( self ): " Kills all the processes if needed " index = len( self.__processes ) - 1 while index >= 0: item = self.__processes[ index ] if item.procWrapper.needRedirection(): item.procWrapper.stop() index -= 1 # Wait till all the processes stopped count = self.__getDetachedCount() while count > 0: time.sleep( 0.01 ) QApplication.processEvents() count = self.__getDetachedCount() return def __getDetachedCount( self ): " Return the number of detached processes still running " count = 0 index = len( self.__processes ) - 1 while index >= 0: if self.__processes[ index ].procWrapper.needRedirection(): count += 1 index -= 1 return count def kill( self, procID ): " Kills a single process " index = self.__getProcessIndex( procID ) if index is None: return item = self.__processes[ index ] if not item.procWrapper.needRedirection(): return item.procWrapper.stop() return def __getProcessIndex( self, procID ): " Returns a process index in the list " for index, item in enumerate( self.__processes ): if item.procWrapper.procID() == procID: return index return None def __onProcessFinished( self, procID, retCode ): " Triggered when a process has finished " index = self.__getProcessIndex( procID ) if index is not None: item = self.__processes[ index ] if item.procWrapper.needRedirection(): if item.widget: item.widget.scriptFinished() if retCode == KILLED: msg = "Script killed" tooltip = "killed" elif retCode == DISCONNECTED: msg = "Connection lost to the script process" tooltip = "connection lost" else: msg = "Script finished with exit code " + str( retCode ) tooltip = "finished, exit code " + str( retCode ) item.procWrapper.wait() item.widget.appendIDEMessage( msg ) self.__mainWindow.updateIOConsoleTooltip( procID, tooltip ) del self.__processes[ index ] return def __onProcessStarted( self, procID ): " Triggered when a process has started " index = self.__getProcessIndex( procID ) if index is not None: item = self.__processes[ index ] if item.widget: self.__mainWindow.installIOConsole( item.widget ) item.widget.appendIDEMessage( "Script " + item.procWrapper.path() + " started" ) return def __onUserInput( self, procID, userInput ): " Triggered when the user input is collected " index = self.__getProcessIndex( procID ) if index is not None: item = self.__processes[ index ] if item.procWrapper.needRedirection(): item.procWrapper.userInput( userInput ) return def __onWaitImer( self ): " Triggered when the timer fired " needNewTimer = False index = len( self.__processes ) - 1 while index >= 0: item = self.__processes[ index ] if item.procWrapper.needRedirection() == False: if item.procWrapper.waitDetached() == True: del self.__processes[ index ] else: needNewTimer = True index -= 1 if needNewTimer: self.__waitTimer.start( 1000 ) return
class RunManager(QObject): " Manages the external running processes " def __init__(self, mainWindow): QObject.__init__(self) self.__mainWindow = mainWindow self.__processes = [] self.__tcpServer = QTcpServer() self.connect(self.__tcpServer, SIGNAL("newConnection()"), self.__newConnection) self.__tcpServer.listen(QHostAddress.LocalHost) self.__waitTimer = QTimer(self) self.__waitTimer.setSingleShot(True) self.connect(self.__waitTimer, SIGNAL('timeout()'), self.__onWaitImer) return def __newConnection(self): " Handles new incoming connections " clientSocket = self.__tcpServer.nextPendingConnection() clientSocket.setSocketOption(QAbstractSocket.KeepAliveOption, 1) clientSocket.setSocketOption(QAbstractSocket.LowDelayOption, 1) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.__waitForHandshake(clientSocket) QApplication.restoreOverrideCursor() return def __waitForHandshake(self, clientSocket): " Waits for the message with the proc ID " if clientSocket.waitForReadyRead(1000): qs = clientSocket.readAll() us = str(CODEC.fromUnicode(str(qs))) if not us.endswith(EOT): return line = us[0:-len(EOT)] if not line.startswith('>'): return cmdIndex = line.find('<') if cmdIndex == -1: return cmd = line[0:cmdIndex + 1] content = line[cmdIndex + 1:] if cmd != ResponseProcID: return # It could only be a redirected process procID = int(content) procIndex = self.__getProcessIndex(procID) if procIndex is not None: self.__onProcessStarted(procID) self.__processes[procIndex].procWrapper.setSocket(clientSocket) return def run(self, path, needDialog): " Runs the given script with redirected IO " if needDialog: params = GlobalData().getRunParameters(path) termType = Settings().terminalType profilerParams = Settings().getProfilerSettings() debuggerParams = Settings().getDebuggerSettings() dlg = RunDialog(path, params, termType, profilerParams, debuggerParams, "Run", self.__mainWindow) if dlg.exec_() != QDialog.Accepted: return GlobalData().addRunParams(path, dlg.runParams) if dlg.termType != termType: Settings().terminalType = dlg.termType # The parameters for the run are ready. # Start the run business. remoteProc = RemoteProcess() remoteProc.isProfiling = False remoteProc.procWrapper = RemoteProcessWrapper( path, self.__tcpServer.serverPort()) if Settings().terminalType == TERM_REDIRECT: remoteProc.widget = RunConsoleTabWidget( remoteProc.procWrapper.procID()) self.connect(remoteProc.procWrapper, SIGNAL('ClientStdout'), remoteProc.widget.appendStdoutMessage) self.connect(remoteProc.procWrapper, SIGNAL('ClientStderr'), remoteProc.widget.appendStderrMessage) self.connect(remoteProc.procWrapper, SIGNAL('ClientRawInput'), remoteProc.widget.rawInput) self.connect(remoteProc.widget, SIGNAL('UserInput'), self.__onUserInput) else: remoteProc.widget = None self.connect(remoteProc.procWrapper, SIGNAL('Finished'), self.__onProcessFinished) self.__processes.append(remoteProc) if remoteProc.procWrapper.start() == False: # Failed to start - the fact is logged, just remove from the list procIndex = self.__getProcessIndex(remoteProc.procWrapper.procID()) if procIndex is not None: del self.__processes[procIndex] else: if Settings().terminalType != TERM_REDIRECT: if not self.__waitTimer.isActive(): self.__waitTimer.start(1000) return def profile(self, path): " Profiles the given script with redirected IO " return def killAll(self): " Kills all the processes if needed " index = len(self.__processes) - 1 while index >= 0: item = self.__processes[index] if item.procWrapper.needRedirection(): item.procWrapper.stop() index -= 1 # Wait till all the processes stopped count = self.__getDetachedCount() while count > 0: time.sleep(0.01) QApplication.processEvents() count = self.__getDetachedCount() return def __getDetachedCount(self): " Return the number of detached processes still running " count = 0 index = len(self.__processes) - 1 while index >= 0: if self.__processes[index].procWrapper.needRedirection(): count += 1 index -= 1 return count def kill(self, procID): " Kills a single process " index = self.__getProcessIndex(procID) if index is None: return item = self.__processes[index] if not item.procWrapper.needRedirection(): return item.procWrapper.stop() return def __getProcessIndex(self, procID): " Returns a process index in the list " for index, item in enumerate(self.__processes): if item.procWrapper.procID() == procID: return index return None def __onProcessFinished(self, procID, retCode): " Triggered when a process has finished " index = self.__getProcessIndex(procID) if index is not None: item = self.__processes[index] if item.procWrapper.needRedirection(): if item.widget: item.widget.scriptFinished() if retCode == KILLED: msg = "Script killed" tooltip = "killed" elif retCode == DISCONNECTED: msg = "Connection lost to the script process" tooltip = "connection lost" else: msg = "Script finished with exit code " + str(retCode) tooltip = "finished, exit code " + str(retCode) item.procWrapper.wait() item.widget.appendIDEMessage(msg) self.__mainWindow.updateIOConsoleTooltip(procID, tooltip) del self.__processes[index] return def __onProcessStarted(self, procID): " Triggered when a process has started " index = self.__getProcessIndex(procID) if index is not None: item = self.__processes[index] if item.widget: self.__mainWindow.installIOConsole(item.widget) item.widget.appendIDEMessage("Script " + item.procWrapper.path() + " started") return def __onUserInput(self, procID, userInput): " Triggered when the user input is collected " index = self.__getProcessIndex(procID) if index is not None: item = self.__processes[index] if item.procWrapper.needRedirection(): item.procWrapper.userInput(userInput) return def __onWaitImer(self): " Triggered when the timer fired " needNewTimer = False index = len(self.__processes) - 1 while index >= 0: item = self.__processes[index] if item.procWrapper.needRedirection() == False: if item.procWrapper.waitDetached() == True: del self.__processes[index] else: needNewTimer = True index -= 1 if needNewTimer: self.__waitTimer.start(1000) return
class GameSession(QObject): ready = pyqtSignal() def __init__(self, client, connectivity): QObject.__init__(self) self._state = GameSessionState.OFF # Subscribe to messages targeted at 'game' from the server client.subscribe_to('game', self) # Connectivity helper self.connectivity = connectivity self.connectivity.ready.connect(self.ready.emit) self.connectivity.peer_bound.connect(self._peer_bound) # Keep a parent pointer so we can use it to send # relay messages about the game state self._client = client # type: Client self.me = client.me self.game_port = client.gamePort self.player = client.me # Use the normal lobby by default self.init_mode = 0 self._joins, self._connects = [], [] # 'GPGNet' TCP listener self._game_listener = QTcpServer(self) self._game_listener.newConnection.connect(self._new_game_connection) self._game_listener.listen(QHostAddress.LocalHost) # We only allow one game connection at a time self._game_connection = None self._process = game_process_instance # type: GameProcess self._process.started.connect(self._launched) self._process.finished.connect(self._exited) @property def relay_port(self): return self._game_listener.serverPort() @property def state(self): return self._state @state.setter def state(self, val): self._state = val def listen(self): """ Start listening for remote commands Call this in good time before hosting a game, e.g. when the host game dialog is being shown. """ assert self.state == GameSessionState.OFF self.state = GameSessionState.LISTENING if self.connectivity.is_ready: self.ready.emit() else: self.connectivity.prepare() def handle_message(self, message): command, args = message.get('command'), message.get('args', []) if command == 'SendNatPacket': addr_and_port, message = args host, port = addr_and_port.split(':') self.connectivity.send(message, (host, port)) elif command == 'CreatePermission': addr_and_port = args[0] host, port = addr_and_port.split(':') self.connectivity.permit((host, port)) elif command == 'JoinGame': addr, login, peer_id = args self._joins.append(peer_id) self.connectivity.bind(addr, login, peer_id) elif command == 'ConnectToPeer': addr, login, peer_id = args self._connects.append(peer_id) self.connectivity.bind(addr, login, peer_id) else: self._game_connection.send(command, *args) def send(self, command_id, args): self._logger.info("Outgoing relay message {} {}".format(command_id, args)) self._client.send({ 'command': command_id, 'target': 'game', 'args': args or [] }) def _peer_bound(self, login, peer_id, port): self._logger.info("Bound peer {}/{} to {}".format(login, peer_id, port)) if peer_id in self._connects: self._game_connection.send('ConnectToPeer', '127.0.0.1:{}'.format(port), login, peer_id) self._connects.remove(peer_id) elif peer_id in self._joins: self._game_connection.send('JoinGame', '127.0.0.1:{}'.format(port), login, peer_id) self._joins.remove(peer_id) def _new_game_connection(self): self._logger.info("Game connected through GPGNet") assert not self._game_connection self._game_connection = GPGNetConnection(self._game_listener.nextPendingConnection()) self._game_connection.messageReceived.connect(self._on_game_message) self.state = GameSessionState.RUNNING def _on_game_message(self, command, args): self._logger.info("Incoming GPGNet: {} {}".format(command, args)) if command == "GameState": if args[0] == 'Idle': # autolobby, port, nickname, uid, hasSupcom self._game_connection.send("CreateLobby", self.init_mode, self.game_port + 1, self.me.login, self.me.id, 1) elif args[0] == 'Lobby': # TODO: Eagerly initialize the game by hosting/joining early pass self.send(command, args) def _turn_state_changed(self, val): if val == TURNState.BOUND: self.ready.emit() def _launched(self): self._logger.info("Game has started") def _exited(self, status): self._game_connection = None self.state = GameSessionState.OFF self._logger.info("Game has exited with status code: {}".format(status)) self.send('GameState', ['Ended'])
class GameSession(QObject): ready = pyqtSignal() def __init__(self, client, connectivity): QObject.__init__(self) self._state = GameSessionState.OFF # Subscribe to messages targeted at 'game' from the server client.subscribe_to('game', self) # Connectivity helper self.connectivity = connectivity self.connectivity.ready.connect(self.ready.emit) self.connectivity.peer_bound.connect(self._peer_bound) # Keep a parent pointer so we can use it to send # relay messages about the game state self._client = client # type: Client self.me = client.me self.game_port = client.gamePort self.player = client.me # Use the normal lobby by default self.init_mode = 0 self._joins, self._connects = [], [] # 'GPGNet' TCP listener self._game_listener = QTcpServer(self) self._game_listener.newConnection.connect(self._new_game_connection) self._game_listener.listen(QHostAddress.LocalHost) # We only allow one game connection at a time self._game_connection = None self._process = game_process_instance # type: GameProcess self._process.started.connect(self._launched) self._process.finished.connect(self._exited) @property def relay_port(self): return self._game_listener.serverPort() @property def state(self): return self._state @state.setter def state(self, val): self._state = val def listen(self): """ Start listening for remote commands Call this in good time before hosting a game, e.g. when the host game dialog is being shown. """ assert self.state == GameSessionState.OFF self.state = GameSessionState.LISTENING if self.connectivity.is_ready: self.ready.emit() else: self.connectivity.prepare() def handle_message(self, message): command, args = message.get('command'), message.get('args', []) if command == 'SendNatPacket': addr_and_port, message = args host, port = addr_and_port.split(':') self.connectivity.send(message, (host, port)) elif command == 'CreatePermission': addr_and_port = args[0] host, port = addr_and_port.split(':') self.connectivity.permit((host, port)) elif command == 'JoinGame': addr, login, peer_id = args self._joins.append(peer_id) self.connectivity.bind(addr, login, peer_id) elif command == 'ConnectToPeer': addr, login, peer_id = args self._connects.append(peer_id) self.connectivity.bind(addr, login, peer_id) else: self._game_connection.send(command, *args) def send(self, command_id, args): self._logger.info("Outgoing relay message {} {}".format( command_id, args)) self._client.send({ 'command': command_id, 'target': 'game', 'args': args or [] }) def _peer_bound(self, login, peer_id, port): self._logger.info("Bound peer {}/{} to {}".format( login, peer_id, port)) if peer_id in self._connects: self._game_connection.send('ConnectToPeer', '127.0.0.1:{}'.format(port), login, peer_id) self._connects.remove(peer_id) elif peer_id in self._joins: self._game_connection.send('JoinGame', '127.0.0.1:{}'.format(port), login, peer_id) self._joins.remove(peer_id) def _new_game_connection(self): self._logger.info("Game connected through GPGNet") assert not self._game_connection self._game_connection = GPGNetConnection( self._game_listener.nextPendingConnection()) self._game_connection.messageReceived.connect(self._on_game_message) self.state = GameSessionState.RUNNING def _on_game_message(self, command, args): self._logger.info("Incoming GPGNet: {} {}".format(command, args)) if command == "GameState": if args[0] == 'Idle': # autolobby, port, nickname, uid, hasSupcom self._game_connection.send("CreateLobby", self.init_mode, self.game_port + 1, self.me.login, self.me.id, 1) elif args[0] == 'Lobby': # TODO: Eagerly initialize the game by hosting/joining early pass self.send(command, args) def _turn_state_changed(self, val): if val == TURNState.BOUND: self.ready.emit() def _launched(self): self._logger.info("Game has started") def _exited(self, status): self._game_connection = None self.state = GameSessionState.OFF self._logger.info( "Game has exited with status code: {}".format(status)) self.send('GameState', ['Ended'])
class HTTPProxy(QObject): debug = True log = sys.stderr username = '******' password = '******' stopServing = pyqtSlot() def __init__(self, parent=None): super(HTTPProxy, self).__init__(parent) self.proxy_server = QTcpServer(self) self.proxy_server.listen(QHostAddress.Any, 8000) self.proxy_server.newConnection.connect(self.manage_request) if self.debug: self.log.write('Proxy server running on 0.0.0.0 port %s\n\n' % self.port()) def port(self): return self.proxy_server.serverPort() def addr(self): return self.proxy_server.serverAddress().toString() def stopServing(self): if self.debug: self.log.write('Service is stopping...\n\n') # does not "close" the server, just stop listening... self.proxy_server.close() if self.proxy_server.hasPendingConnections(): socket = self.proxy_server.nextPendingConnection() while socket: socket.abort() socket = self.proxy_server.nextPendingConnection() def manage_request(self): proxy_server = self.sender() # Qt docs says that the caller of nextPendingConnection() # is the parent of the socket socket = proxy_server.nextPendingConnection() socket.readyRead.connect(self.process_request) socket.disconnected.connect(socket.deleteLater) def authorize_request(self, request_data): return True header = QHttpRequestHeader(QString(request_data)) if self.debug: self.log.write(header.toString()) auth = header.value('Proxy-Authorization') if not auth: return False challenge = base64.b64encode(self.username+':'+self.password) return challenge == str(auth).split()[1] def process_request(self): socket = self.sender() request_data = socket.readAll() if not self.authorize_request(request_data): socket.write('HTTP/1.1 407 Proxy Authentication Required\r\n') if self.debug: self.log.write('407 Proxy Authentication Required\n\n') socket.write('Proxy-Authenticate: Basic realm="test"\r\n') socket.write('\r\n') socket.disconnectFromHost() return else: # remove Proxy-Authorization header start = request_data.indexOf('Proxy-Authorization:') end = request_data.lastIndexOf('\r\n') request_data.remove(start, end) request_data.append('\r\n') pos = request_data.indexOf('\r\n') request_line = request_data.left(pos) request_data.remove(0, pos + 2) entries = request_line.split(' ') method = entries[0] address = entries[1] version = entries[2] port = '80' if address.count(':') > 1: protocol, host, port = address.split(':') else: protocol, host = address.split(':') print 'address', address #url = QUrl( protocol + host ) url = QUrl.fromEncoded(address) #url.setHost( host ) #url.setPort( int(port) ) if not url.isValid(): if self.debug: self.log.write('Invalid URL: %s\n\n', url) socket.disconnectFromHost() return host = url.host() port = 80 if (url.port() < 0) else url.port() req = url.encodedPath() if url.hasQuery(): req.append('?').append(url.encodedQuery()) request_line = method + ' ' + req + ' ' + version + '\r\n' request_data.prepend(request_line) if self.debug: self.log.write(method + ' ' + address + ' ' + version + '\n\n') key = host + ':' + QString.number(port) proxy_socket = socket.findChild(QTcpSocket, key) if proxy_socket: proxy_socket.setObjectName(key) proxy_socket.setProperty('url', url) proxy_socket.setProperty('request_data', request_data) proxy_socket.write(request_data) else: proxy_socket = QTcpSocket(socket) proxy_socket.setObjectName(key) proxy_socket.setProperty('url', url) proxy_socket.setProperty('request_data', request_data) proxy_socket.connected.connect(self.send_request) proxy_socket.readyRead.connect(self.transfer_data) proxy_socket.disconnected.connect(self.close_connection) proxy_socket.error.connect(self.close_connection) proxy_socket.connectToHost(host, port) def send_request(self): proxy_socket = self.sender() request_data = proxy_socket.property('request_data').toByteArray() proxy_socket.write(request_data) def transfer_data(self): proxy_socket = self.sender() socket = proxy_socket.parent() socket.write(proxy_socket.readAll()) def close_connection(self): proxy_socket = self.sender() if proxy_socket: socket = proxy_socket.parent() if isinstance(socket, QTcpSocket) and socket: socket.disconnectFromHost() if proxy_socket.error() != QTcpSocket.RemoteHostClosedError: url = proxy_socket.property('url').toUrl() error_string = proxy_socket.errorString() if self.debug: self.log.write('Error for %s %s\n\n' % (url, error_string)) proxy_socket.deleteLater()
class ControlServer(QObject): # Signal to inform that the set logging level command has been received logging_command_received = pyqtSignal(int) # Signal to inform that the quit command has been received and the system should exit quit_command_received = pyqtSignal() def __init__(self): QObject.__init__(self) # logging instance self.log = logging.getLogger('GDAIS.ControlServer') # TCP server to listen for control commands self.tcp_server = QTcpServer() # regexp to check if command is 'set_log_level' self.valid_loglevel = re.compile(r"^set_log_level (\d?0)$") def start(self): self.log.info("Starting TCP server...") if self.tcp_server.listen(port=12345): txt = "Listening at http://localhost:{0} for commands" self.log.info(txt.format(self.tcp_server.serverPort())) self.tcp_server.newConnection.connect(self._accept_connection) else: self.log.warn("Unable to start: {0}".format( self.tcp_server.errorString())) # define a timer to auto-quit the app after 10 sec timeout = 10 # seconds self.log.warn( "GDAIS will run for {0} seconds and then die".format(timeout)) self.timer = QTimer() self.timer.timeout.connect(self.quit) self.timer.start(timeout * 1000) # msec def quit(self): if self.tcp_connection and self.tcp_connection.state( ) == QTcpSocket.ConnectedState: loop = QEventLoop() self.tcp_connection.disconnected.connect(loop.quit) self.tcp_connection.disconnectFromHost() self.log.debug("Entering disconnect state...") if self.tcp_connection.state() == QTcpSocket.ConnectedState: loop.exec_() self.log.debug("Done waiting, closing server...") if self.tcp_server.isListening(): self.tcp_server.close() self.quit_command_received.emit() def _accept_connection(self): self.tcp_connection = self.tcp_server.nextPendingConnection() self.tcp_connection.readyRead.connect(self._read_data) self.tcp_connection.error.connect(self._error_ocurred) self.log.debug("Accepted connection") def _read_data(self): tcp_data = self.tcp_connection.readAll() if tcp_data == 'quit': self.log.info("Received 'quit' command") self.quit() elif self.valid_loglevel.match(tcp_data): self.log.info("Received 'set_log_level' command") try: new_level = int(self.valid_loglevel.match(tcp_data).group(1)) except ValueError: self.log.exception("Level has to be an integer value") else: self.logging_command_received.emit(new_level) else: self.log.error("Received unknown command: {0}".format(tcp_data)) def _error_ocurred(self, socket_error): if socket_error == QTcpSocket.RemoteHostClosedError: self.log.info(self.tcp_connection.errorString()) else: self.log.error(self.tcp_connection.errorString())