def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] running = 1 while running: try: inputready, outputready, exceptready = select.select( inputs, self.outputs, []) except select.error as e: break except socket.error as e: break for s in inputready: if s == self.server: client, address = self.server.accept() print('chatserver: got connection %d from %s' % (client.fileno(), address)) cname = receive(client).split('NAME: ')[1] self.clients = 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname) msg = str('\n(Connected: New client ' + str(self.clients) + ' from ' + str(self.get_name(client))) for o in self.outputs: send(o, msg) self.outputs.append(client) elif s == sys.stdin: junk = sys.stdin.readline() running = 0 else: try: data = receive(s) if data: msg = '\n#[' + self.get_name(s) + ']>>' + data for o in self.outputs: if o != s: send(o, msg) else: print('chatserver: %d hung up' % s.fileno()) self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) msg = '\n(Hung up: Client from %s)' % self.get_name( s) for o in self.outputs: send(o, msg) except socket.error as e: inputs.remove(s) self.outputs.remove(s) self.server.close()
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: data =str(self.obj.textEdit.toPlainText()) print data if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.obj.textEdit_chat.setText("Shutting Down") self.flag = True break else: sys.stdout.write(data + '\n') self.obj.textEdit_chat.setText(str(self.obj.textEdit_chat.toPlainText())+str(data)+'\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def __init__(self, ip=None, port=8888, path=''): # Quit flag self.path = path if ip is None: with open(path + 'ip', 'r') as f: ip = f.read() self.flag = False self.port = int(port) self.x = csr_matrix(0) self.x_ave = csr_matrix(0) self.alpha = csr_matrix(0) self.alpha_ave = csr_matrix(0) self.n = 0 self.n_i = 0 self.algo = None self.i = None # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((ip, self.port)) slave_print('Connected to server@%d' % self.port) # Send slave's name... data = receive(self.sock) # Contains slave address, set it addr = data[0].split('SLAVE: ')[1] self.i = data[1] global PRINT_SUFFIX PRINT_SUFFIX = ' ' + str(self.i) except socket.error as e: slave_print('Could not connect to server @%d' % self.port) sys.exit(1)
def cmdloop(self): Q_flag = True while Q_flag: try: # !! if you notice that the form is always written # It's PROBLEM sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print('Shutting down.') Q_flag = False break else: sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt as error: print('Interrupted.', error) self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: encryptMsg = EncryptAES256(data, self.key) send(self.sock, encryptMsg) elif i == self.sock: data = receive(self.sock) if re.search('>>',data) != None: fromC = data.split('>> ')[0] msg = data.split('>> ')[1] decryptMsg = DecryptAES256(msg, self.key) data = fromC + '>> ' + decryptMsg if not data: print 'Shutting down.' self.flag = True break else: sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for i in inputready: if i == 0: data = str(self.obj.textEdit.toPlainText()) print data if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.obj.textEdit_chat.setText("Shutting Down") self.flag = True break else: sys.stdout.write(data + '\n') self.obj.textEdit_chat.setText( str(self.obj.textEdit_chat.toPlainText()) + str(data) + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: f=open('p.html','a') sys.stdout.write(data + '\n') f.write('\n'+name_chrome+' == '+data+'\n\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' f=open('p.html','a') f.write('</font></div></body></html>') f.close() self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: f = open('p.html', 'a') sys.stdout.write(data + '\n') f.write('\n' + name_chrome + ' == ' + data + '\n\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' f = open('p.html', 'a') f.write('</font></div></body></html>') f.close() self.sock.close() break
def __init__(self, obj, name, host='127.0.0.1', port=5000): self.name = name self.obj = obj print self.name # Quit flag self.flag = False self.port = int(port) print self.port self.host = host print self.host # Initial prompt self.prompt = '[' + '@'.join( (name, socket.gethostname().split('.')[0])) + ']> ' # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port self.obj.textEdit_chat.setText("Connected to server @" + str(self.port)) # Send my name... send(self.sock, 'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port self.obj.textEdit_chat.setText( "Could not connect to chat server @" + str(self.port)) sys.exit(1)
def wait_until_get_data(self): while True: try: inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) except select.error as e: break except socket.error as e: break for i in inputready: data = receive(self.sock) if data is None: slave_print('Something went wrong') self.flag = True break can_read, n_features = data if can_read == True: slave_print('Reading my part of the data with', n_features, 'features...') self.A, self.b = load_svmlight_file(self.path + 'slave' + str(self.i) + '_data', n_features=n_features, zero_based=True) self.b = csr_matrix(self.b).T self.n_i = self.b.shape[0] return
def wait_until_get_parameters(self): parameters_not_known = True while parameters_not_known: try: inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) except select.error as e: break except socket.error as e: break for i in inputready: data = receive(self.sock) if data is None: slave_print('Something went wrong') self.flag = 1 parameters_not_known = False break slave_print('Receiving parameters...') self.x_ave, self.M, self.gamma, self.l2, self.l1, self.n, self.algo, data_name = data slave_print( 'Received parameters: M = %d, l2 = %3f, l1 = %3f, n = %d, algo = %s, dataset is %s' % (self.M, self.l2, self.l1, self.n, self.algo, data_name)) self.x = self.x_ave parameters_not_known = False return
def __init__(self,obj,name, host='127.0.0.1', port=5000): self.name = name self.obj=obj print self.name # Quit flag self.flag = False self.port = int(port) print self.port self.host = host print self.host # Initial prompt self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port self.obj.textEdit_chat.setText("Connected to server @"+str(self.port)) # Send my name... send(self.sock,'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port self.obj.textEdit_chat.setText("Could not connect to chat server @"+str(self.port)) sys.exit(1)
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select([0, self.sock], [], []) for i in inputready: if i == 0: # grab message data = sys.stdin.readline().strip() try: # encrypt data = self.encryptionKey.encrypt(data, 0) data = data[0] # append signature signkey = self.decryptor message_hash = SHA.new() message_hash.update(data) signer = PKCS1_PSS.new(signkey) signature = signer.sign(message_hash) data = '%s#^[[%s' % (data, signature) except ValueError: print 'Too large text, cannot encrypt, not sending.' data = None if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: if 'PLAIN:' in data: data = data.strip('PLAIN:').strip() else: #data = str(data) data = self.decryptor.decrypt(data) sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def cmdloop(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select([0, self.sock], [], []) for i in inputready: if i == 0: # grab message data = sys.stdin.readline().strip() try: # encrypt data = self.encryptionKey.encrypt(data, 0) data = data[0] # append signature signkey = self.decryptor message_hash = SHA512.new() message_hash.update(data) signer = PKCS1_PSS.new(signkey) signature = signer.sign(message_hash) data = '%s#^[[%s' % (data, signature) except ValueError: print 'Too large text, cannot encrypt, not sending.' data = None if data: send(self.ssl_sock, data) elif i == self.sock: data = receive(self.ssl_sock) if not data: print 'Shutting down.' self.flag = True break else: if 'PLAIN:' in data: data = data.strip('PLAIN:').strip() else: #data = str(data) data = self.decryptor.decrypt(data) sys.stdout.write(data + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def setClientData(self,sockets): try: client, address = sockets.accept() print 'MIA server: got connection %d from %s' % (client.fileno(), address) self.dataClient = receive(client) self.client=client self.address=address except socket.error,e: print e
def __init__(self, name, host='127.0.0.1', port=3490, user="******"): self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host self.user = user # Initial prompt self.prompt = '[' + '@'.join( (name, socket.gethostname().split('.')[0])) + ']> ' client_privkey = RSA.generate(4096, os.urandom) client_pubkey = client_privkey.publickey() self.decryptor = client_privkey # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server %s:%d' % (self.host, self.port) # Send my pubkey... send(self.sock, client_pubkey.exportKey()) server_pubkey = receive(self.sock) self.encryptor = RSA.importKey(server_pubkey) # Send my name... send(self.sock, 'NAME: ' + self.name) data = receive(self.sock) #Send block name.. #send(self.sock, 'BlockNAME: ' + self.name) #data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def __init__(self, name, host='127.0.0.1', port=3490, user="******"): self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host self.user = user # Initial prompt self.prompt = '[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' client_privkey = RSA.generate(4096, os.urandom) client_pubkey = client_privkey.publickey() self.decryptor = client_privkey # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server %s:%d' % (self.host, self.port) # Send my pubkey... send(self.sock, client_pubkey.exportKey()) server_pubkey = receive(self.sock) self.encryptor = RSA.importKey(server_pubkey) # Send my name... send(self.sock, 'NAME: ' + self.name) data = receive(self.sock) #Send block name.. #send(self.sock, 'BlockNAME: ' + self.name) #data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def connect(self, args): #It is responsible for make the first contact and connection #with the server. #TODO Improve arguments parser if len(args) < 2: #Verify if there are all parameters for connection print("It is missing arguments") return False elif len(args) == 2: server = args[0][0] nickname = args[1][0] port = PORT_DEFAULT elif len(args) == 3: server = args[0][0] nickname = args[1][0] port = args[2][0] try: self.socket.connect((server, port)) msg = "NICK {0}\n\r".format(nickname) send(self.socket, msg) data = receive(self.socket).strip("\n\r") command, arguments = self.parser_data(data) if command in ERR: command, arguments = self.parser_data(data) msg = self.commands(command, arguments) raise BaseException(msg) self.nickname = nickname self.prompt = "[{0}]>".format(nickname) self.connected = True print("You are connect to {0}.".format(server)) except socket.error as e: self.socket.close() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Could not connect to chat server {0} at port {1}'.format(server, port)) return False except BaseException as e: self.socket.close() self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if msg: sys.stdout.write(str(e) + '\n\r') else: sys.stdout.write('\r') sys.stdout.flush() return False return True
def __init__(self, name, host='127.0.0.1', port=6530): self.name = sys.argv[1] self.flag = False self.port = int(port) self.host = host try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port send(self.sock,'NAME: ' + self.name) data = receive(self.sock) addr = data.split('Client: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def __init__(self, name, host='127.0.0.1', port=6530): self.name = sys.argv[1] self.flag = False self.port = int(port) self.host = host try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port send(self.sock, 'NAME: ' + self.name) data = receive(self.sock) addr = data.split('Client: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def connect(self): """ Checking registration/login data""" is_authenticate = False while not is_authenticate: try: form = userform.create_userform() if form is None: sys.exit('KeyboardInterrupt from user_form') data = {} if form[0] == 0: data = form[1] data['type'] = 'log' elif form[0] == 1: data = form[1] data['type'] = 'reg' self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.server_host, self.server_port)) send(self.sock, data) receive_data = receive(self.sock) if receive_data == 'Error': raise RegisterError(0) elif receive_data == 'Success': is_authenticate = True return data['login'] else: raise RegisterError(1) except socket.error as error: print('Cchat_Client: Could not connect to chat server') print(error) sys.exit(1) except RegisterError as msg: print(msg) print("Try again") self.sock.close() except KeyboardInterrupt as signal: print(signal) if self.sock: self.sock.close() sys.exit(1)
def run_chat_loop(self): is_shutdown = True while is_shutdown: in_fds, out_fds, err_fds = select.select([self.sock], [], []) for sock in in_fds: if sock is self.sock: data = receive(self.sock) if not data: self.print_into_box('Server was shutdown') is_shutdown = False break else: if not data['message']: continue message = data['head'] + data['message'] print(message) self.print_into_box(message)
def __init__(self, name, host='127.0.0.1', port=5153): self.name = name self.flag = False self.port = int(port) self.host = host try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) send(self.sock,'NAME: ' + self.name) data = receive(self.sock) addr = data.split('CLIENT: ')[1] except socket.error, e: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def __init__(self, name, host, port, key): self.name = name self.flag = False self.port = int(port) self.host = host self.key = key try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port # Send my name... send(self.sock,'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '@'.join((self.name, addr)) + '> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def cmdloop(self): if "TEST" in environ: inputs = [self.sock] # For testing on Win else: inputs = [0, self.sock] while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( inputs, [], []) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send_message(self.sock, 'text', data) elif i == self.sock: data = receive(self.sock) if not data: print('Shutting down.') self.flag = True break else: if data.type == 'text': sys.stdout.write(data.text + '\n') sys.stdout.flush() elif data.type == 'kick': print('You were kicked by the server') self.sock.close() self.flag = True break except KeyboardInterrupt: print('Interrupted.') self.sock.close() break
def cmdloop(self): if "TEST" in environ: inputs = [self.sock] # For testing on Win else: inputs = [0, self.sock] while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select(inputs, [], []) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send_message(self.sock, 'text', data) elif i == self.sock: data = receive(self.sock) if not data: print('Shutting down.') self.flag = True break else: if data.type == 'text': sys.stdout.write(data.text + '\n') sys.stdout.flush() elif data.type == 'kick': print('You were kicked by the server') self.sock.close() self.flag = True break except KeyboardInterrupt: print('Interrupted.') self.sock.close() break
def __init__(self, name, host="95.179.184.41", port=8080): self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host # Initial prompt self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print('Connected to chat server@%d' % self.port) # Send my name... send(self.sock,'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error as e: print('Could not connect to chat server @%d' % self.port) sys.exit(1)
def __init__(self, name, host="127.0.0.1", port=3490): self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host # Initial prompt self.prompt = "[" + "@".join((name, socket.gethostname().split(".")[0])) + "]> " # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print "Connected to chat server@%d" % self.port # Send my name... send(self.sock, "NAME: " + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split("CLIENT: ")[1] self.prompt = "[" + "@".join((self.name, addr)) + "]> " except socket.error, e: print "Could not connect to chat server @%d" % self.port sys.exit(1)
def __init__(self, host='localhost', port=3490): """ init client object """ PORT = port HOST = host # Initial prompt self.prompt = '[unknown]> ' log_flag = True while log_flag: try: pswd = getpass('Please enter the password:'******'Connected to chat server') self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((HOST, PORT)) # check password send(self.sock, pswd) data = receive(self.sock) if data == 'Error': raise RegisterError(0) elif data == 'Confirmed': send(self.sock, self.create_usrform()) self.prompt = '[You]> ' log_flag = False else: raise RegisterError(1) except socket.error as error: print('Cchat_Client: Could not connect to chat server') print(error) sys.exit(1) except RegisterError as msg: print(msg) print("Try again") self.sock.close() except KeyboardInterrupt as signal: print(signal) self.sock.close() sys.exit(1)
def __init__(self, name, host='127.0.0.1', port=3490, client_key='client.pem', client_key_passphrase=''): self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host # Initial prompt self.prompt = '[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' server_pubkey = open('server.pub', 'r').read() client_privkey = open(client_key, 'r').read() self.encryptor = RSA.importKey(server_pubkey) self.decryptor = RSA.importKey(client_privkey, passphrase=client_key_passphrase) # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port # Send my name... send(self.sock, 'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] #Create a password and Username Dictionary #passwordDict = {'rew': hashlib.sha1('123456'), 'set': hashlib.sha1('1230'), 'rew1': hashlib.sha1('23456'), 'set1': hashlib.sha1('1231'), 'rew2': hashlib.sha1('13456'), 'set2': hashlib.sha1('1232'), 'rew3': hashlib.sha1('12456'), 'set3': hashlib.sha1('1233'), 'rew4': hashlib.sha1('12356'), 'set4': hashlib.sha1('1234')} FILENAME = 'passwordHex.txt' # Converting data to dict where the key is the user and the value is the hashed password passwordDict = dict([x.split('::') for x in self.read_passwords(FILENAME)]) existingCustomers = {} running = 1 while running: try: inputready, outputready, exceptready = select.select(inputs, self.outputs, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() connstream = self.context.wrap_socket(client, server_side=True) print 'chat_server: got connection %d from %s' % (client.fileno(), address) # Get client public key and send our public key publicKey = RSA.importKey(receive(connstream)) send(connstream, self.server_publicKey.exportKey()) # Read the login name cname = receive(connstream).split('NAME: ')[1] # Read the login password cpassword = receive(connstream).split('PASSWORD: '******'CLIENT: Username and/or Password Does Not Match') continue if cname in existingCustomers.values(): send(connstream, 'CLIENT: Customer with these Credentials is Already LoggedIn: Use Different Credentials') continue # Add customer's name to array existingCustomers[connstream] = cname print existingCustomers.values() send(connstream, 'Users connected: ' + str(existingCustomers.values())) # Compute client name and send back self.numOfClients += 1 send(connstream, 'CLIENT: ' + str(address[0])) inputs.append(connstream) self.clientmap[connstream] = (address, cname, publicKey) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.numOfClients, self.getName(connstream)) for o in self.outputs: try: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: self.outputs.remove(o) inputs.remove(o) self.outputs.append(connstream) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verifySignature(s, data, signature) data = self.server_privateKey.decrypt(data) if data != '\x00': if verified: data = '%s [verified]' % data else: data = '%s [Not verified]' % data # Send as new client's message... dataReceivers = data.split(' ') total = 0 for rec in dataReceivers: total = total + 1 dataReceivers = data.split(' ') try: numDataReceivers = int(dataReceivers[0]) if numDataReceivers > 9: numDataReceivers = 0 #print dataReceivers[0] if numDataReceivers != 0: print "Sending message to: " for k in xrange(1,numDataReceivers+1): print dataReceivers[k] + " " msg = '\n# [' + self.getName(s) + ']>> ' for ltotal in xrange (1,total-numDataReceivers): msg = msg + dataReceivers[numDataReceivers+ltotal] + ' ' for j in xrange(1, numDataReceivers+1): if dataReceivers[j] in existingCustomers.values(): for o in self.outputs: if existingCustomers.get(o) == dataReceivers[j]: self.sendEncryptedMsg(o, msg, self.get_just_name(s)) else: msg = '\n# [' + self.getName(s) + ']>> ' + 'Receiver ' + dataReceivers[j] + ' is NOT Logged In Now' self.sendEncryptedMsg(s, msg, self.get_just_name(s)) else: # Send msg to all except ourselves print 'Sending message to all users' msg = '\nMessage from # [' + self.getName(s) + ']>> ' for ltotal in xrange (1,total-numDataReceivers): msg = msg + dataReceivers[numDataReceivers+ltotal] + ' ' for o in self.outputs: if o != s: self.sendEncryptedMsg(o, msg, self.get_just_name(s)) except ValueError: msg = '\n# [' + self.getName(s) + ']>> ' + 'Message Not in Expected Format' self.sendEncryptedMsg(s, msg, self.get_just_name(s)) continue else: print 'chat_server: Client %d hung up' % s.fileno() self.numOfClients -= 1 s.close() inputs.remove(s) del existingCustomers[s] self.outputs.remove(s) # Send client-leaving information to others msg = '\n(Hung up: Client from %s)' % self.getName(s) for o in self.outputs: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: # Remove the input causing error inputs.remove(s) self.outputs.remove(s) sleep(0.1) self.server.close()
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] running = 1 while running: try: inputready, outputready, exceptready = select.select(inputs, self.outputs, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print ('chatserver: got connection %d from %s' % (client.fileno(), address)) # Get client public key and send our public key pubkey = RSA.importKey(receive(client)) send(client, self.server_pubkey.exportKey()) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname, pubkey) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client)) for o in self.outputs: try: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: self.outputs.remove(o) inputs.remove(o) self.outputs.append(client) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verify_signature(s, data, signature) data = self.server_privkey.decrypt(data) if data != '\x00': if verified: data = '%s [OK]' % data else: data = '%s [Not verified]' % data # Send as new client's message... msg = '\n# [' + self.getname(s) + ']>> ' + data # Send data to all except ourselves for o in self.outputs: if o != s: self.send_encrypted(o, msg, self.get_just_name(s)) else: print ('Chatserver: Client %d hung up' % s.fileno()) self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.getname(s) for o in self.outputs: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: # Remove inputs.remove(s) self.outputs.remove(s) sleep(0.1) self.server.close()
def serve(self): if "TEST" in environ: inputs = [self.server] # for testing on Win else: inputs = [self.server, sys.stdin] self.outputs = [] kick_command = re.compile('^kick.*') while True: try: inputready, outputready, exceptready = select.select(inputs, self.outputs, []) except select.error as e: print(e) break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print('chatserver: got connection %d from %s' % (client.fileno(), address)) # Read the login name client_name = receive_name(client) # Compute client name and send back self.clients += 1 send_message(client, 'address', str(address[0])) inputs.append(client) self.clientmap[client] = (address, client_name) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client)) for o in self.outputs: send_message(o, 'text', msg) self.outputs.append(client) elif s == sys.stdin: # handle standard input line = sys.stdin.readline().strip('\n') # print('got input', line) if line == 'list': for client in self.clientmap: # print('client') print(self.getname(client)) elif kick_command.match(line): name = line.split(' ')[1] # print('here we kick', line.split(' ')[1]) for client in self.clientmap: # print(self.getname(client)) if self.getname(client).split('@')[0] == name: # print('got him') # Send client leaving information to others msg = '\n(Kicked: Client from %s)' % self.getname(client) for o in self.outputs: send_message(o, 'text', msg) send_message(client, 'kick', '') self.clients -= 1 inputs.remove(client) self.outputs.remove(client) del self.clientmap[client] client.close() break else: # handle all other sockets try: data = receive(s) if data: # Send as new client's message... msg = '\n#[' + self.getname(s) + ']>> ' + data.text # print('text: ', data.text) # print('type: ', data.type) # Send data to all except ourselves for o in self.outputs: if o != s: send_message(o, 'text', msg) else: print('chatserver: %d hung up' % s.fileno()) self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.getname(s) for o in self.outputs: send_message(o, 'text', msg) # Removing it later to be able to get name earlier del self.clientmap[s] except socket.error: # Remove inputs.remove(s) self.outputs.remove(s) del self.clientmap[s] self.server.close()
def cmdloop(self): while not self.flag: try: sys.stdout.flush() inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: continue elif i == self.sock: data = receive(self.sock) cleanData = data.replace('\n', '') if not data: print 'SshDaemon Shutting down.' self.flag = True break if cleanData.find('>> ') != -1: if cleanData.split('>> ')[1] == 'Shutdown sshDaemon': print 'SshDaemon Shutting down.' self.flag = True break if cleanData[:1] == '#': if cleanData.find('>> ') != -1: newData = cleanData.split('>> ')[1] splitData = newData.split(' ') if splitData[0] == 'sshDaemon': if splitData[1] == 'shutdown': print 'SshDaemon Shutting down.' self.flag = True break if splitData[1] == 'command': doThread = threading.Thread(target = doStuff, args = (splitData, serverLookup, )) doThread.start() if splitData[1] == 'ping': if len(splitData) == 2: send(clientObj.sock, 'ok') if len(splitData) > 2: send(clientObj.sock, 'ok ' + splitData[2]) sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def serve(self): inputs = [self.server, sys.stdin] self.outputsock = [] running = 1 while running: try: inputready, outputready, exceptready = select.select(inputs, self.outputsock, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print 'Chat Server: got connection %d from %s' % (client.fileno(), address) # Get client public key and send our public key pubkey = RSA.importKey(receive(client)) send(client, self.server_pubkey.exportKey()) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname, pubkey) # Send joining information to other clients msg = '\n(New client (%d) entered the chat room : %s)' % (self.clients, self.getname(client)) for o in self.outputsock: try: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: self.outputsock.remove(o) inputs.remove(o) self.outputsock.append(client) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verify_signature(s, data, signature) data = self.server_privkey.decrypt(data) word = "Check online users" user_list = ["Online Users:"] if word in data: #for item in inputs: for o in self.outputsock: ur = self.get_just_name(o) user_list.append(ur) user_list = str(user_list) print user_list for o in self.outputsock: #self.send_encrypted(o, msg, self.get_just_name(o)) self.send_encrypted(o, user_list, self.get_just_name(o)) if data != '\x00': if verified: data = '%s [Client Signature Verified:OK]' % data else: data = '%s [Not verified]' % data # Send as new client's message... msg = '\n# [' + self.getname(s) + ']>> ' + data # Send data to all except ourselves for o in self.outputsock: if o != s: self.send_encrypted(o, msg, self.get_just_name(s)) else: print 'Chatserver: Client %d disconnected' % s.fileno() self.clients -= 1 s.close() inputs.remove(s) self.outputsock.remove(s) # Send client leaving information to others msg = '\n(Left the Chat Room: Client from %s)' % self.getname(s) for o in self.outputsock: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: # Remove inputs.remove(s) self.outputsock.remove(s) sleep(0.1) self.server.close()
def send_receive(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for i in inputready: if i == 0: # grab message data = sys.stdin.readline().strip() try: #Attach Timestamp timestamp = str(datetime.datetime.now()) data = data + " " + "|Sent: " + timestamp # encrypt data = self.encryptor.encrypt(data, 0) data = data[0] # Generate Hash message_hash = SHA256.new() message_hash.update(data) #Append Signature signkey = self.decryptor signer = PKCS1_PSS.new(signkey) signature = signer.sign(message_hash) data = '%s#^[[%s' % (data, signature) except ValueError: print 'Too large text, cannot encrypt, not sending.' data = None if data: send(self.sock, data) elif i == self.sock: data_time = datetime.datetime.now() elapsed_time = (datetime.datetime.now() - data_time).total_seconds() data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: if 'PLAIN:' in data: data = data.strip('PLAIN:').strip() else: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] key = self.encryptor msg_hash = SHA256.new() msg_hash.update(data) verifier = PKCS1_PSS.new(key) if verifier.verify(msg_hash, signature): data = self.decryptor.decrypt(data) data = data + "[Server Signature Verified:OK]" else: print "The signature is not authentic." timestamp_received = str(datetime.datetime.now()) block_user = self.user #block_time = 50 status = "Online" if (block_user and status in data): #data = re.sub(block_user, "", data) if self.name == block_user: data = re.sub(self.name, "", data) sys.stdout.write(data + '\n') sys.stdout.flush() else: data = re.sub(block_user, "", data) sys.stdout.write(data + '\n') sys.stdout.flush() elif block_user in data: sys.stdout.write('\n') pass else: sys.stdout.write(data + " " + "Received: " + timestamp_received + "|" + '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def receive(self): return communication.receive(self.channel)
def send_receive(self): while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready, exceptrdy = select.select([0, self.sock], [], []) for i in inputready: if i == 0: # grab message data = sys.stdin.readline().strip() try: #Attach Timestamp timestamp = str(datetime.datetime.now()) data = data + " " + "|Sent: "+timestamp # encrypt data = self.encryptor.encrypt(data, 0) data = data[0] # Generate Hash message_hash = SHA256.new() message_hash.update(data) #Append Signature signkey = self.decryptor signer = PKCS1_PSS.new(signkey) signature = signer.sign(message_hash) data = '%s#^[[%s' % (data, signature) except ValueError: print 'Too large text, cannot encrypt, not sending.' data = None if data: send(self.sock, data) elif i == self.sock: data_time = datetime.datetime.now() elapsed_time = (datetime.datetime.now() - data_time).total_seconds() data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: if 'PLAIN:' in data: data = data.strip('PLAIN:').strip() else: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] key = self.encryptor msg_hash = SHA256.new() msg_hash.update(data) verifier = PKCS1_PSS.new(key) if verifier.verify(msg_hash, signature): data = self.decryptor.decrypt(data) data = data + "[Server Signature Verified:OK]" else: print "The signature is not authentic." timestamp_received = str(datetime.datetime.now()) block_user = self.user #block_time = 50 status = "Online" if (block_user and status in data): #data = re.sub(block_user, "", data) if self.name == block_user: data = re.sub(self.name, "", data) sys.stdout.write(data + '\n') sys.stdout.flush() else: data = re.sub(block_user, "", data) sys.stdout.write(data + '\n') sys.stdout.flush() elif block_user in data: sys.stdout.write('\n') pass else: sys.stdout.write(data + " " +"Received: "+ timestamp_received + "|"+ '\n') sys.stdout.flush() except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break
def receive(self, client): return communication.receive(client)
def run_server_loop(self): input_socket_list = [self.server] is_running = True while is_running: try: in_fds, out_fds, err_fds = select.select( input_socket_list, self.user_list, []) except select.error as error: print(error) break except socket.error as error: print(error) break for sock in in_fds: if sock is self.server: user, user_address = self.server.accept() data = receive(user) request = self.authenticate_user(data) if request[0]: message = request[2] self.broadcast_message(message) self.uid_link[user] = request[1] input_socket_list.append(user) self.user_list.append(user) send(user, 'Success') else: send(user, 'Error') continue else: try: data = receive(sock) if data: print(data) if data in self.CmdWorker.command_list: send(sock, self.CmdWorker.execute_commands(data)) else: user = self.DbWorker.get_user( self.uid_link[sock])['login'] head = '%s~%s' % (user, self.MsgWorker.time()) message = data self.broadcast_message( { 'head': head, 'message': message }, sock) else: time = self.CmdWorker.time() self.DbWorker.update_state(self.uid_link[sock], 0, time) sock.close() input_socket_list.remove(sock) self.user_list.remove(sock) message = self.MsgWorker.print_user_left( self.DbWorker.get_user( self.uid_link[sock])['login']) self.broadcast_message(message) except socket.error as error: print(error) input_socket_list.remove(sock) self.user_list.remove(sock) self.server.close()
def loop(self): #Main function responsible for read inputs and accept connections. wait_list = {} self.inputs = [self.socket] while True: remove_wait_list = [] try: inputready, outputready, exceptready = select.select(self.inputs, self.outputs, []) except select.error as e: break except socket.error as e: break for s in inputready: try: if s == self.socket: #Accept connections clientsock, address = self.socket.accept() wait_list[clientsock] = datetime.now() self.outputs.append(clientsock) self.inputs.append(clientsock) else: #Verify other sockets, already accepted. data = receive(s).strip("\n\r")[:BUFFSIZE-2] if data: command, arguments = self.parser_data(data) reply = self.commands(command, arguments, s) for msg, dest in reply: data = msg + "\n\r" if s in wait_list: #If client just connected, he is added on wait list, which is responsible #to keep tracking which users don't set their nick yet. After a while they #are disconnected. if command == "NICK": del wait_list[s] send(dest, data) else: msg = "PRIVMSG SERVER :You must try to use command NICK before\n\r" send(dest, msg) self.outputs.remove(s) self.inputs.remove(s) s.close() del wait_list[s] send(dest, data) else: #If there is no data, it means that client #has closed connection. try: self.disconnect_client(s) except BaseException as e: pass except socket.error as e: break for w in wait_list: #Track wait list if (datetime.now() - wait_list[w]).seconds > WAIT_TIMEOUT: self.outputs.remove(w) self.inputs.remove(w) w.close() remove_wait_list.append(w) for w in remove_wait_list: #Remove_Wait_List is responsible for track which users #set their nick and need to be removed from wait_list. del wait_list[w] del remove_wait_list
class ChatServer(object): """ Simple chat server using select """ def __init__(self, port=5000, backlog=5): self.clients = 0 # Client map self.clientmap = {} # Output socket list self.outputs = [] self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind(('',port)) print 'Listening to port',port,'...' self.server.listen(backlog) print "hostname:- "+socket.gethostname() # Trap keyboard interrupts signal.signal(signal.SIGINT, self.sighandler) def sighandler(self, signum, frame): # Close the server print 'Shutting down server...' # Close existing client sockets for o in self.outputs: o.close() self.server.close() def getname(self, client): # Return the printable name of the # client, given its socket... info = self.clientmap[client] host, name = info[0][0], info[1] return '@'.join((name, host)) def serve(self): inputs = [self.server,sys.stdin] self.outputs = [] running = 1 while running: try: inputready,outputready,exceptready = select.select(inputs, self.outputs, []) except select.error, e: break except socket.error, e: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print 'chatserver: got connection %d from %s' % (client.fileno(), address) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client)) for o in self.outputs: # o.send(msg) send(o, msg) self.outputs.append(client) elif s == sys.stdin: # handle standard input junk = sys.stdin.readline() running = 0 else: # handle all other sockets try: # data = s.recv(BUFSIZ) data = receive(s) if data: # Send as new client's message... msg = '\n#[' + self.getname(s) + ']>> ' + data # Send data to all except ourselves for o in self.outputs: if o != s: # o.send(msg) send(o, msg) else: print 'chatserver: %d hung up' % s.fileno() self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.getname(s) for o in self.outputs: # o.send(msg) send(o, msg) except socket.error, e: # Remove inputs.remove(s) self.outputs.remove(s)
def cmdloop(self, message): sentMessage = False gotResponse = False if not sentMessage: send(self.sock, message) sentMessage = True while not self.flag and not gotResponse: try: sys.stdout.flush() inputready, outputready,exceptrdy = select.select([0, self.sock], [],[]) for i in inputready: if i == 0: data = sys.stdin.readline().strip() if data: send(self.sock, data) elif i == self.sock: data = receive(self.sock) cleanData = data.replace('\n', '') if not data: print 'Shutting down.' self.flag = True break if cleanData[:1] == '#': newData = cleanData.split('>> ') if newData[1][:12] == 'sshProcessor': relevantData = newData[1].split('|') splitMessage = message.split(' ') if relevantData[1] == splitMessage[2]: gotResponse = True break if message == 'sshDaemon ping': if newData[0] == '#[sshDaemon]' and newData[1] == 'ok': gotResponse = True self.sock.close() break except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break return newData[1]
def loop(self): #Main function which read sockets and prompts. while not self.connected: #If not connected, wait until you digit /server try: sys.stdout.write(self.prompt) sys.stdout.flush() data = sys.stdin.readline().strip() if data: if data.startswith("/"): cmd, arguments = self.parser_cmd(data) if cmd == 'server': self.connect(arguments) else: print("You must connect to a server first. Use '/server <server> <nickname> [<port>]'.") except KeyboardInterrupt: sys.exit(1) except BaseException as err: print(err) while not self.flag: try: sys.stdout.write(self.prompt) sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready,exceptrdy = select.select([0, self.socket], [],[]) for i in inputready: if i == 0: #Get data from STDIN. data = sys.stdin.readline().strip() if data and data.startswith("/"): cmd, arguments = self.parser_cmd(data) msg = self.build_msg(cmd, arguments) if msg: send(self.socket, msg) elif i == self.socket: #Verify if socket is enable and receive data data = receive(self.socket).strip("\n\r") if data: command, arguments = self.parser_data(data) msg = self.commands(command, arguments) if msg: sys.stdout.write(msg + '\n\r') else: sys.stdout.write('\r') sys.stdout.flush() else: #If socket is enable, but there is no data, #it means that server closed connection. #TODO After a server disconnects, do not exit, just restart. print('Server disconnected.') self.flag = True break except KeyboardInterrupt: print('Exiting...') self.socket.close() break except socket.error as e: print(e)
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] #Create a password and Username Dictionary #passwordDict = {'rew': hashlib.sha1('123456'), 'set': hashlib.sha1('1230'), 'rew1': hashlib.sha1('23456'), 'set1': hashlib.sha1('1231'), 'rew2': hashlib.sha1('13456'), 'set2': hashlib.sha1('1232'), 'rew3': hashlib.sha1('12456'), 'set3': hashlib.sha1('1233'), 'rew4': hashlib.sha1('12356'), 'set4': hashlib.sha1('1234')} FILENAME = 'passwordHex.txt' # Converting data to dict where the key is the user and the value is the hashed password passwordDict = dict( [x.split('::') for x in self.read_passwords(FILENAME)]) existingCustomers = {} running = 1 while running: try: inputready, outputready, exceptready = select.select( inputs, self.outputs, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() connstream = self.context.wrap_socket(client, server_side=True) print 'chat_server: got connection %d from %s' % ( client.fileno(), address) # Get client public key and send our public key publicKey = RSA.importKey(receive(connstream)) send(connstream, self.server_publicKey.exportKey()) # Read the login name cname = receive(connstream).split('NAME: ')[1] # Read the login password cpassword = receive(connstream).split('PASSWORD: '******'CLIENT: Username and/or Password Does Not Match') continue if cname in existingCustomers.values(): send( connstream, 'CLIENT: Customer with these Credentials is Already LoggedIn: Use Different Credentials' ) continue # Add customer's name to array existingCustomers[connstream] = cname print existingCustomers.values() send(connstream, 'Users connected: ' + str(existingCustomers.values())) # Compute client name and send back self.numOfClients += 1 send(connstream, 'CLIENT: ' + str(address[0])) inputs.append(connstream) self.clientmap[connstream] = (address, cname, publicKey) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % ( self.numOfClients, self.getName(connstream)) for o in self.outputs: try: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: self.outputs.remove(o) inputs.remove(o) self.outputs.append(connstream) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verifySignature(s, data, signature) data = self.server_privateKey.decrypt(data) if data != '\x00': if verified: data = '%s [verified]' % data else: data = '%s [Not verified]' % data # Send as new client's message... dataReceivers = data.split(' ') total = 0 for rec in dataReceivers: total = total + 1 dataReceivers = data.split(' ') try: numDataReceivers = int(dataReceivers[0]) if numDataReceivers > 9: numDataReceivers = 0 #print dataReceivers[0] if numDataReceivers != 0: print "Sending message to: " for k in xrange( 1, numDataReceivers + 1): print dataReceivers[k] + " " msg = '\n# [' + self.getName( s) + ']>> ' for ltotal in xrange( 1, total - numDataReceivers): msg = msg + dataReceivers[ numDataReceivers + ltotal] + ' ' for j in xrange( 1, numDataReceivers + 1): if dataReceivers[ j] in existingCustomers.values( ): for o in self.outputs: if existingCustomers.get( o ) == dataReceivers[j]: self.sendEncryptedMsg( o, msg, self.get_just_name( s)) else: msg = '\n# [' + self.getName( s ) + ']>> ' + 'Receiver ' + dataReceivers[ j] + ' is NOT Logged In Now' self.sendEncryptedMsg( s, msg, self.get_just_name(s)) else: # Send msg to all except ourselves print 'Sending message to all users' msg = '\nMessage from # [' + self.getName( s) + ']>> ' for ltotal in xrange( 1, total - numDataReceivers): msg = msg + dataReceivers[ numDataReceivers + ltotal] + ' ' for o in self.outputs: if o != s: self.sendEncryptedMsg( o, msg, self.get_just_name(s)) except ValueError: msg = '\n# [' + self.getName( s ) + ']>> ' + 'Message Not in Expected Format' self.sendEncryptedMsg( s, msg, self.get_just_name(s)) continue else: print 'chat_server: Client %d hung up' % s.fileno() self.numOfClients -= 1 s.close() inputs.remove(s) del existingCustomers[s] self.outputs.remove(s) # Send client-leaving information to others msg = '\n(Hung up: Client from %s)' % self.getName( s) for o in self.outputs: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: # Remove the input causing error inputs.remove(s) self.outputs.remove(s) sleep(0.1) self.server.close()
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] running = 1 while running: try: inputready, outputready, exceptready = select.select( inputs, self.outputs, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print 'chat_server: got connection %d from %s' % ( client.fileno(), address) # Get client public key and send our public key publicKey = RSA.importKey(receive(client)) send(client, self.server_publicKey.exportKey()) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.numOfClients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname, publicKey) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % ( self.numOfClients, self.getName(client)) for o in self.outputs: try: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: self.outputs.remove(o) inputs.remove(o) self.outputs.append(client) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verifySignature(s, data, signature) data = self.server_privateKey.decrypt(data) if data != '\x00': if verified: data = '%s [verified]' % data else: data = '%s [Not verified]' % data # Send as new client's message... msg = '\n# [' + self.getName(s) + ']>> ' + data # Send msg to all except ourselves for o in self.outputs: if o != s: self.sendEncryptedMsg( o, msg, self.get_just_name(s)) else: print 'chat_server: Client %d hung up' % s.fileno() self.numOfClients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client-leaving information to others msg = '\n(Hung up: Client from %s)' % self.getName( s) for o in self.outputs: self.sendEncryptedMsg(o, msg, self.get_just_name(o)) except socket.error: # Remove the input causing error inputs.remove(s) self.outputs.remove(s) sleep(0.1) self.server.close()
def serve(self): """ main loop server """ inputs = [self.server, sys.stdin] self.outputs = [] running = True while running: try: inputready, outputready, exceptready = select.select( inputs, self.outputs, []) except select.error as error: print(error) break except socket.error as error: print(error) break for sock in inputready: if sock == self.server: client, address = self.server.accept() tmp_msg = "Cchat: got connection from {}".format(address) print(tmp_msg) # here server must get json or any variable data = receive(client) if data != 'qwerty': send(client, 'Error') continue elif data == 'qwerty': send(client, 'Confirmed') else: send(client, 'Unexpected Error') data = receive(client) client_name = data['name'] client_long_name = data['long_name'] inputs.append(client) self.clientmap[client] = (address, client_name, client_long_name) tmp_connect_msg = """\n(Connected: New client from """.format(self.getname(client)) # send message for all users for item in self.outputs: send(item, tmp_connect_msg) # add new client in outputs set self.outputs.append(client) else: try: data = receive(sock) if data: if data in self.commands: send(sock, self.exec_cmds(data)) else: message = "\nUSER[{}]>> {}".format( self.getname(sock), data) for item in self.outputs: if item is not sock: send(item, message) else: tmp_left_msg = "Cchat: {} left".format( {self.getname(client)}) print(tmp_left_msg) sock.close() inputs.remove(sock) self.outputs.remove(sock) msg = "\n(Hung up: Client from {})".format( {self.getname(sock)}) for item in self.outputs: send(item, msg) except socket.error as error: print(error) inputs.remove(sock) self.outputs.remove(sock) self.server.close()
def handleClients(self, s): if s == self.server: # handle the server socket client, address = self.server.accept() print 'chatserver: got connection %d from %s' % (client.fileno(), address) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) self.inputs.append(client) self.clientmap[client] = (address, cname) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client)) if msg.find('sshProcessor') == -1: for o in self.outputs: send(o, msg) self.outputs.append(client) elif s == sys.stdin: # handle standard input pass else: # handle all other sockets try: # data = s.recv(BUFSIZ) data = receive(s) print 'handling stuff ', data if data[:9] == 'conServer': # Isolate conServer commands newData = data.split(' ') if len(newData) > 1: if newData[1] == 'command': if len(newData) > 2: if newData[2] == 'start': if len(newData) > 3: exists = False for o in self.outputs: if (self.getname(o)).find(newData[3]) != -1: exists = True if not exists: print 'Trying to start ' + newData[3] os.system('nohup ./' + newData[3] + '.py &') if newData[2] == 'stop': if len(newData) > 3: print 'Trying to stop ' + newData[3] for o in self.outputs: if (self.getname(o)).find(newData[3]) != -1: send(o, '\n' + '#[[email protected]]>> ' + newData[3] + ' shutdown') self.clients -= 1 o.close() self.inputs.remove(o) self.outputs.remove(o) msg = '\n(Hung up: Client from %s)' % self.getname(o) for z in self.outputs: send(z, msg) if newData[2] == 'clients': clientString = '' for o in self.outputs: clientString += self.getname(o) + ', ' self.broadcast(clientString[:-2]) if newData[1] == 'shutdown': running = 0 if data: name = self.getname(s).split('@') msg = '\n#[' + name[0] + ']>> ' + data for o in self.outputs: if o != s: print 'BROARDCAST fired at ', self.getname(o) send(o, msg) else: print 'Not fired at ', self.getname(o) self.printClients() #time.sleep(0.1) else: print '#### %s hung up' % self.getname(s) self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.getname(s) if msg.find('sshProcessor') == -1: for o in self.outputs: send(o, msg) except socket.error, e: # Remove self.inputs.remove(s) self.outputs.remove(s)
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] running = 1 while running: try: inputready, outputready, exceptready = select.select(inputs, self.outputs, []) except select.error: break except socket.error: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print 'chatserver: got connection %d from %s' % (client.fileno(), address) # Get client public key and send our public key pubkey = RSA.importKey(receive(client)) send(client, self.server_pubkey.exportKey()) # Read the login name cname = receive(client).split('NAME: ')[1] for s, val in self.clientmap.iteritems(): if cname in [str(i) for i in val]: # Have to convert each one to prevent a __getstate__ error continue # Want to abort the connection here! # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname, pubkey) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client)) for o in self.outputs: try: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: self.outputs.remove(o) inputs.remove(o) self.outputs.append(client) elif s == sys.stdin: # handle standard input sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: dataparts = data.split('#^[[') signature = dataparts[1] data = dataparts[0] verified = self.verify_signature(s, data, signature) data = self.server_privkey.decrypt(data) # Server can decide parsing here if data != '\x00': if verified: data = '%s [OK]' % data else: data = '%s [Not verified]' % data self.process(data, s) # parse out server-side commands or send as-is else: print 'Chatserver: Client %d hung up' % s.fileno() self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.getname(s) for o in self.outputs: self.send_encrypted(o, msg, self.get_just_name(o)) except socket.error: # Remove inputs.remove(s) self.outputs.remove(s) sleep(0.1) # Don't kill the main thread! self.server.close()
def __init__(self, name): self.name = name # Quit flag self.flag = False self.port = 3490 self.host = 'localhost' print "Enter your password" #Encrypt the password self.password = hashlib.sha512(getpass.getpass()) #print self.password.hexdigest() #print self.password.digest_size # Initial prompt self.prompt = '[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' #May not need (Maximus) # Generate client certificate #print "Generating client certificate" #self.createClientCert(self.name) #print "Client certificate created" client_privateKey = RSA.generate(4096, os.urandom) client_pubkey = client_privateKey.publickey() self.decryptor = client_privateKey # Connect to server at port try: self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) self.context.verify_mode = ssl.CERT_REQUIRED self.context.check_hostname = True #Get the servers CA certificate file_location = os.getcwd() self.context.load_verify_locations(file_location + "/server.crt") self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Check server certificate self.ssl_sock = self.context.wrap_socket(self.sock, server_hostname=self.host) self.ssl_sock.settimeout(2) except: print "Server certificate invalid, closing chat." exit(0) #Check cipher used, we expect none since we didn't specify any #print self.ssl_sock.cipher() self.ssl_sock.connect((self.host, self.port)) print 'Connected to chat server %s:%d' % (self.host, self.port) # Send my pubkey... send(self.ssl_sock, client_pubkey.exportKey()) server_pubkey = receive(self.ssl_sock) self.encryptionKey = RSA.importKey(server_pubkey) # Send my name... send(self.ssl_sock, 'NAME: ' + self.name) # Send my password... send(self.ssl_sock, 'PASSWORD: '******'PASSWORD: '******'CLIENT: ')[1] if len(addr) > 15:#Means the server is not sending IP address of client print 'Password Verification Failed' print addr exit(0) self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error: print 'Could not connect to chat server @%d' % self.port sys.exit(1)
def serve(self): self.wait_until_get_data() self.wait_until_get_parameters() self.alpha = csr_matrix(np.zeros(self.x.shape[0])).T self.alpha_ave = csr_matrix(np.zeros(self.x.shape[0])).T slave_print('Start optimizing...') it = 0 while not self.flag: it += 1 if it == 1: start = time.time() if self.algo in ['asynch_ave', 'daga']: grad = f_grad(self.x, self.A, self.b, self.l2) delta_grad = (grad - self.alpha) * (self.n_i / self.n) if self.algo == 'asynch_ave': delta_x = -self.gamma * (self.alpha_ave + delta_grad) else: delta_x = -self.gamma * (self.alpha_ave + delta_grad * (self.n / self.n_i)) elif self.algo == 'daga2': z = prox_r(self.x_ave, self.gamma, self.l1) grad = f_grad(z, self.A, self.b, self.l2) delta_grad = (grad - self.alpha) * (self.n_i / self.n) x_new = z - self.gamma * (self.alpha_ave + delta_grad * (self.n / self.n_i)) delta_x = (x_new - self.x_ave) self.x = x_new elif self.algo == 'daga3': x_new = z - self.gamma * grad delta_x = (x_new - self.x ) * self.n_i / self.n - self.gamma * self.alpha_ave self.x = x_new if self.algo in ['asynch_ave', 'daga', 'daga2']: self.alpha = grad data = [delta_x, delta_grad] elif self.algo in ['synch_gd', 'asynch_gd']: delta = csr_matrix(np.zeros(self.A.shape[1])).T p = 1 for i in range(p): z = prox_r(self.x_ave + delta, self.gamma, self.l1) grad = f_grad(z, self.A, self.b, self.l2) x_new = z - self.gamma * grad delta += (self.n_i / self.n) * (x_new - self.x) self.x = x_new data = delta if it == 1: dif = time.time() - start n_passes = p if self.algo == 'asynch_gd' else 1 slave_print('It takes', dif, 'seconds to make', n_passes, 'pass(es) through the data') start = time.time() send(self.sock, data) if it == 1: end = time.time() slave_print('It takes', end - start, 'seconds to send an update') not_updated = True while not_updated: try: inputready, outputready, exceptrdy = select.select( [0, self.sock], [], []) for inp in inputready: if inp == self.sock: data = receive(self.sock) not_updated = False if data is None: slave_print('Shutting down...') self.flag = True break elif type(data ) is str and data == 'Change algorithm': self.wait_until_get_parameters() slave_print('Start optimizing...') continue elif type(data) is str and data == 'Terminate': slave_print('Terminating.') self.flag = True break if self.algo in ['asynch_ave', 'daga', 'daga2']: self.x, self.alpha_ave = data break else: self.x_ave = data break except KeyboardInterrupt: slave_print('Interrupted.') self.sock.close() break # crash = np.random.binomial(1, 0.01) # if crash: # time.sleep(2) self.sock.close()
def serve(self): inputs = [self.server, sys.stdin] self.outputs = [] running = 1 while running: try: inputready, outputready, exceptready = select.select( inputs, self.outputs, []) except select.error as e: break except socket.error as e: break for s in inputready: if s == self.server: # handle the server socket client, address = self.server.accept() print('chatserver: got connection %d from %s' % (client.fileno(), address)) # Read the login name cname = receive(client).split('NAME: ')[1] # Compute client name and send back self.clients += 1 send(client, 'CLIENT: ' + str(address[0])) inputs.append(client) self.clientmap[client] = (address, cname) # Send joining information to other clients msg = '\n(Connected: New client (%d) from %s)' % ( self.clients, self.get_name(client)) for o in self.outputs: # o.send(msg) send(o, msg) self.outputs.append(client) elif s == sys.stdin: # handle standard input junk = sys.stdin.readline() running = 0 else: # handle all other sockets try: data = receive(s) if data: # Send as new client's message... msg = '\n#[' + self.get_name(s) + ']>> ' + data # Send data to all except ourselves for o in self.outputs: if o != s: send(o, msg) else: print('chatserver: %d hung up' % s.fileno()) self.clients -= 1 s.close() inputs.remove(s) self.outputs.remove(s) # Send client leaving information to others msg = '\n(Hung up: Client from %s)' % self.get_name( s) for o in self.outputs: # o.send(msg) send(o, msg) except socket.error as e: # Remove inputs.remove(s) self.outputs.remove(s) self.server.close()
def clntBet(): #輪流指標 global ptr #最大賭金指標 global maxbetptr #賭池賭金 global betpool #紀錄放棄的玩家 global giveup #本迴圈自己下的賭金 selfbet={} for o in self.outputs: selfbet[o]=0 #最大賭金 maxbet=0 flag=0 while flag==0: msg='\n目前最大賭金='+str(maxbet)+'\n現在戶頭還有:'+str(selfmoney[self.outputs[ptr]])+'\n1.跟, 2:加注, 3.放棄退出' send(self.outputs[ptr], msg) reMsg=receive(self.outputs[ptr]) print reMsg if int(reMsg)==1: if (selfmoney[self.outputs[ptr]]>=maxbet): selfmoney[self.outputs[ptr]]=selfmoney[self.outputs[ptr]]-maxbet betpool=betpool+maxbet ptr=(ptr+1)%len(self.outputs) print selfmoney if (ptr==maxbetptr): flag=1 else: msg='錢不夠唷~~~' send(self.outputs[ptr], msg) elif int(reMsg)==2: msg='輸入你加注的金額:' send(self.outputs[ptr], msg) rebet=receive(self.outputs[ptr]) if (selfmoney[self.outputs[ptr]]>=(int(rebet)+maxbet)): maxbet=maxbet+int(rebet) selfmoney[self.outputs[ptr]]=selfmoney[self.outputs[ptr]]-maxbet betpool=betpool+maxbet-selfbet[self.outputs[ptr]] maxbetptr=ptr ptr=(ptr+1)%len(self.outputs) print selfmoney else: msg='錢不夠唷~~~' send(self.outputs[ptr], msg) elif int(reMsg)==3: msg='exit~' send(self.outputs[ptr], msg) giveup=giveup+[ptr] ptr=ptr+1 else: msg='輸入錯誤~~別亂來~~~' send(self.outputs[ptr%len(self.outputs)], msg)