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
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
 def send(self, port):
     """ Convert thruster force values from percent to PWM values and send them.
     """
     communication.send(port, 'T', bytes(int(self.force[0] // 100)),
                        bytes(int(self.force[0] % 100)),
                        bytes(int(self.force[1] // 100)),
                        bytes(int(self.force[1] % 100)))
Ejemplo n.º 6
0
 def communication_set(self, DT):
     self.res_b.setText('')
     work_mode_text = '16' + '%02X' % self.C_work_mode_l.currentIndex()
     online_mode_text = '16' + '%02X' % self.C_online_mode_l.currentIndex()
     connect_mode_text = '16' + '%02X' % self.C_connect_mode_l.currentIndex(
     )
     connect_app_mode_text = '16' + '%02X' % self.C_connect_app_mode_l.currentIndex(
     )
     listen_port_text = '0100'  # 暂时不可设置
     APN_text = param.format_visible_string(self.C_APN_box.text())
     usr_text = param.format_visible_string(self.C_usr_box.text())
     pw_text = param.format_visible_string(self.C_pw_box.text())
     proxy_addr_text = param.format_octet(self.C_proxy_addr_box.text())
     proxy_port_text = param.format_long_unsigned(
         self.C_proxy_prot_box.text())
     overtm_retry_num_text = '11' + '%02X' % (
         (int(self.C_retry_box.text()) << 6)
         | int(self.C_over_tm_box.text()))
     heart_tm_text = param.format_long_unsigned(self.C_heart_tm_box.text())
     apdu_text = '06010D45000200 020C' + work_mode_text + online_mode_text + \
                 connect_mode_text + connect_app_mode_text + listen_port_text + APN_text + \
                 usr_text + pw_text + proxy_addr_text + proxy_port_text +\
                 overtm_retry_num_text + heart_tm_text + '00'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.read_res)
     communication.send(link_layer.add_link_layer(apdu_text))
 def runRestart(self,filename, host, port, passw):
     self.filename =filename
     self.port = int(port)
     self.host=host
     self.passw=passw
     que=Queue()
     # Quit flag
     self.data=''
     self.flag=False
     self.hsl=[]
     
     # Initial prompt
     # Connect to server at port
     try:
         #self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.s=self.getClientSocket()
         self.s.connect((self.host, self.port))
         #print 'Connected to chat server@%d' % self.port
         # Send my name...
         if self.filename[:1] == 'R' :
             tempToSend=self.dataSend(self.passw,self.filename)
             self.hsl.append('REBOOT')
         elif self.filename[:1] == 'S':
             tempToSend=self.dataSend(self.passw,self.filename)
             self.hsl.append('SHUTDOWN')
         else:
             pass
         send(self.s,tempToSend)
         addr=socket.gethostbyname(socket.gethostname())
         self.hsl.append(addr)
         return self.hsl
     except socket.error, e:
         print 'Could not connect to server @%d' % self.port
         sys.exit(1)
Ejemplo n.º 8
0
def require_game_start():
    '''
        4号消息
        自己设备号,0,消息号,0,''
    '''
    game_mode = gv.game_mode

    if game_mode == 0:

        # 一些图形操作
        print('你不能开始游戏,请先起个昵称,并找个座位坐下')

    elif game_mode == 1:
        site_num = gv.my_site_num

        if site_num == -1:

            # 一些图形操作
            print('你不能开始游戏,请找个座位坐下')

        elif site_num != 0:

            # 一些图形操作
            print('你不能开始游戏,只有0号位玩家可以宣布开始游戏')

        else:

            m = com.GAMEMSG(gv.dev_num, 0, 4, 0, bytes([]))
            com.send(m)

    else:

        # 一些图形操作
        print('不能重复开始游戏')
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
def sending(text, show_detail):
    en_file = 'bin\\en.bin'
    key_file = 'bin\\keys_here.json'
    server_file = 'bin\\server_ip.json'
    with open(key_file) as f:
        keys = json.load(f)

    recipient_pub = keys['SERVER_PUB']

    rsa_encrypto.encryption(text, recipient_pub, en_file)

    with open(en_file, 'rb') as f:
        data = f.read()

    with open(server_file) as f:
        server = json.load(f)

    server_address = (server['server_ip'], server['server_port'])

    sock = communication.sock()

    communication.connect(sock, server_address)

    communication.send(sock, b'SEND', show_detail)
    response = communication.check_response(sock, b'OK', b'READY?', 128)
    if response == 1:
        communication.send(sock, data, show_detail)
        communication.close(sock)
        return None
    if response == 2:
        data = communication.receiving_data(sock, 1024)
        communication.close(sock)
        return data
Ejemplo n.º 11
0
 def evt_set(self, DT):
     self.res_b.setText('')
     bit_string_text = ''
     for byte_index in range(11):
         for bit_index in range(8):
             evt_no = byte_index * 8 + bit_index + 1
             bit_val = 0
             if evt_no <= 85:
                 if eval('self.valid_c_' + str(evt_no) +
                         '.isChecked()') is True:
                     bit_val = 1
             bit_string_text += str(bit_val)
     bit_string_text = hex(int(bit_string_text,
                               2)).split('x')[1].rjust(22, '0')
     valid_text = '0455' + bit_string_text
     bit_string_text = ''
     for byte_index in range(11):
         for bit_index in range(8):
             evt_no = byte_index * 8 + bit_index + 1
             bit_val = 0
             if evt_no <= 85:
                 if eval('self.rpt_c_' + str(evt_no) +
                         '.isChecked()') is True:
                     bit_val = 1
             bit_string_text += str(bit_val)
     bit_string_text = hex(int(bit_string_text,
                               2)).split('x')[1].rjust(22, '0')
     rpt_text = '0455' + bit_string_text
     apdu_text = '060101 3FFF0200 0202' + valid_text + rpt_text + '00'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.read_res)
     communication.send(link_layer.add_link_layer(apdu_text))
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
 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)
Ejemplo n.º 14
0
 def kill(self, command, arguments, socket):
     msgs = []
     nickname = self.clients_socket[socket].nickname
     
     if not arguments:
         #ERR_NEEDMOREPARAMS
         dest = socket
         msg = "401 {0} :Not enough parameters".format(command)
         msgs.append([msg, dest])
     else:
         kill_nick = arguments[0][0]
         if socket.getpeername()[0] != "127.0.0.1":
             #ERR_NOPERMISSION
             dest = socket
             msg = "402 :No permission"
             msgs.append([msg, dest])
         else:
             if kill_nick in self.clients_nick:
                 dest = self.clients_nick[kill_nick].socket
                 for c in self.channels:
                     self.quit_chan(dest, c)
                 if len(arguments) > 1:
                     msg = "You were kicked because '{0}'.".format(arguments[1][0])
                 else:
                     msg = "You were kicked because 'No reason'."
                 send(dest, msg)
                 self.disconnect_client(self.clients_nick[kill_nick].socket)
             else:
                 #ERR_NOSUCHNICK
                 msg = "405 :No such nick"
                 dest = socket
                 msgs.append([msg, dest])
     
     return msgs
def broadcast_message(message, sender, channelMap):
    sender_name = return_user_name(sender, channelMap)
    affected_sockets = return_channel_sockets('Global', channelMap)
    connbroadcast = '\n[' + sender_name + ']>> ' + message
    for o in affected_sockets:
        if o != sender:
            send(o, connbroadcast)
Ejemplo n.º 16
0
def send():
    c.send('connect',outPipe)
    while 1:
                try:
                        msg=raw_input()#listen for user input
                        c.send(msg,outPipe)
                except: pass
Ejemplo n.º 17
0
def removePlayer(player):
 	global all, wolves, witch
	isTownsperson=1
   
	newAll={}
	for p in all.keys():
		if player!=p: newAll[p]=all[p]
	newWolves={}
	for p in wolves.keys():
		if player!=p: newWolves[p]=wolves[p]
		c.log('%s-wolf killed.'%p,1,0,1)
		isTownsperson=0
	if player in witch.keys():
		c.log('%s-witch killed'%player,1,0,1)
		witch={}
		isTownsperson=0
	if isTownsperson:
		c.log('%s-townsperson killed'%player,1,0,1)
	c.setLogChat(1)
	if giveDeathSpeech:
		c.broadcast('These are %ss last words.'%player, all)
		c.send("Share your parting words.", all[player][1])
		c.spawnDeathSpeech(player,deathspeechtime)
	c.setLogChat(0)

	c.send('close',all[player][1])
	all=newAll
	wolves=newWolves
	if len(wolves)<=1: wolftalktime=0
Ejemplo n.º 18
0
    def __init__(self, name, host='192.168.1.14', port=5000):
        self.name = name
        self.flag = False
        self.port = int(port)
        self.host = host
        # Initial prompt
        self.prompt = '[%s]' % self.name
        # 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, self.name)

            #data = receive(self.sock)
            data = self.sock.recv(BUFSIZ)

            # Contains client address, set it
            #addr = data.split('CLIENT: ')[1]
            #self.prompt = '[' + '@'.join((self.name, addr)) + ']> '

            self.prompt = '[%s]>' % self.name

        except socket.error, e:
            print e
            print 'Could not connect to chat server @%d' % self.port
            sys.exit(1)
Ejemplo n.º 19
0
def broadcast_message(message, sender, channelMap):
    sender_name = return_user_name(sender, channelMap)
    affected_sockets = return_channel_sockets('Global', channelMap)
    connbroadcast = '\n[' + sender_name + ']>> ' + message
    for o in affected_sockets:
        if o != sender:
            send(o, connbroadcast)
Ejemplo n.º 20
0
def doStuff(splitList, serverLookup):

    if len(splitList) >= 4:

        if splitList[1] == 'command':

            serverObj = serverLookup.get(splitList[2])
            newList = []
            for i in splitList[3:]:
                temp = i.replace('%20', ' ')
                temp = temp.replace("'\\'", "'")
                newList.append(temp)

            print newList

            response = serverObj.run(newList).output
            singleLine = response.replace('\n', '|')

            if singleLine[-1:] == '|':
                singleLine = singleLine[:-1]

            if singleLine[:1] != '|':
                singleLine = '|' + singleLine

            singleLine = 'sshProcessor|' + splitList[2] + singleLine

            print 'Trying to return to ' + splitList[2]
            send(clientObj.sock, singleLine.strip())
Ejemplo n.º 21
0
 def evt_read(self):
     self.res_b.setText('')
     self.clr_all_cb()
     apdu_text = '0501003FFF020000'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.re_evt)
     communication.send(link_layer.add_link_layer(apdu_text))
Ejemplo n.º 22
0
def removePlayer(player):
    global all, wolves, witch
    isTownsperson = 1

    newAll = {}
    for p in all.keys():
        if player != p: newAll[p] = all[p]
    newWolves = {}
    for p in wolves.keys():
        if player != p: newWolves[p] = wolves[p]
        c.log('%s-wolf killed.' % p, 1, 0, 1)
        isTownsperson = 0
    if player in witch.keys():
        c.log('%s-witch killed' % player, 1, 0, 1)
        witch = {}
        isTownsperson = 0
    if isTownsperson:
        c.log('%s-townsperson killed' % player, 1, 0, 1)
    c.setLogChat(1)
    if giveDeathSpeech:
        c.broadcast('These are %ss last words.' % player, all)
        c.send("Share your parting words.", all[player][1])
        c.spawnDeathSpeech(player, deathspeechtime)
    c.setLogChat(0)

    c.send('close', all[player][1])
    all = newAll
    wolves = newWolves
    if len(wolves) <= 1: wolftalktime = 0
Ejemplo n.º 23
0
    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
Ejemplo n.º 24
0
    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
Ejemplo n.º 25
0
 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)
Ejemplo n.º 26
0
def require_site_set(site_num):
    '''
        2号消息
        自己设备号,0,2,座位号
    '''

    if gv.game_page == 1:

        if gv.name == '':

            # 一些图形操作
            print('起名后才能选座')

        else:

            m = com.GAMEMSG(gv.dev_num, 0, 2, bytes([site_num]))
            com.send(m)

            if gv.site_num == -1:

                # 一些图形操作
                print('锁定座位中')

            else:

                # 一些图形操作
                print('尝试换位中')
    def sendEncryptedMsg(self, to_who, message, name):
        try:
            encryptionKey = self.clientmap[to_who][2]
            msg = encryptionKey.encrypt(message, 0)
            send(to_who, msg)

        except IOError:
            send(to_who, 'PLAIN: cannot find public key for: %s' % name)
Ejemplo n.º 28
0
 def send_message(self):
     """ Send message into socket"""
     # Warning error send message if unbound magic
     data = self.ui.inputLine.text()
     time = str(datetime.datetime.now().time())[:16]
     self.print_into_box(self.head + time + ':' + data)
     self.ui.inputLine.clear()
     send(self.sock, data)
Ejemplo n.º 29
0
    def send_encrypted(self, to_who, message, name):
        try:
            encryptor = self.clientmap[to_who][2]
            msg = encryptor.encrypt(message, 0)
            send(to_who, msg)

        except IOError:
            send(to_who, 'PLAIN: cannot find public key for: %s' % name)
Ejemplo n.º 30
0
    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
Ejemplo n.º 31
0
    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
Ejemplo n.º 32
0
 def broadcast_message(self, message, sockt=None):
     """ Broadcast messages for all users"""
     if sockt is None:
         for sock in self.user_list:
             send(sock, message)
     else:
         for sock in self.user_list:
             if sock is not sockt:
                 send(sock, message)
Ejemplo n.º 33
0
 def rpt_read(self):
     self.clear_res()
     apdu_text = '0502 0104 43000700 43000800 43000900 43000A00 00'
     self.rpt_follow_cb.setCurrentIndex(-1)
     self.rpt_cb.setCurrentIndex(-1)
     self.conn_sever_cb.setCurrentIndex(-1)
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.re_rpt)
     communication.send(link_layer.add_link_layer(apdu_text))
def private_message(message, send_from, send_to, channelMap):
    sender = return_user_name(send_from, channelMap)
    receiver = return_user_socket(send_to, channelMap)
    if receiver:
        new_message = '\nPRIVATE[' + sender + ']>> ' + message
        send(receiver, new_message)
    else:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'User Does not Exist'
        send(send_from,new_message)
Ejemplo n.º 35
0
 def esam_certi_read(self):
     self.res_b.setText('')
     if self.esam_certi_l.currentIndex() == 0:
         apdu_text = '0502 0102 F1000900 F1000A00 00'
     else:
         apdu_text = '0502 0102 F1000B00 F1000C00 00'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.re_esam_certi)
     communication.send(link_layer.add_link_layer(apdu_text))
Ejemplo n.º 36
0
def private_message(message, send_from, send_to, channelMap):
    sender = return_user_name(send_from, channelMap)
    receiver = return_user_socket(send_to, channelMap)
    if receiver:
        new_message = '\nPRIVATE[' + sender + ']>> ' + message
        send(receiver, new_message)
    else:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'User Does not Exist'
        send(send_from, new_message)
Ejemplo n.º 37
0
def answer_game_start(msg):
    '''
        4号消息
        客户端设备号,0,消息号,0,''

        -4号消息
        0,客户端设备号,消息号,1,答复
                                0 可以开始
                                1 人数不足
                                2 没有权限

        -5号消息
        0,0,消息号,0,''
    '''
    dev_num = msg.send

    m_ok = com.GAMEMSG(0, dev_num, -4, 1, bytes([0]))
    m_not_enough = com.GAMEMSG(0, dev_num, -4, 1, bytes([1]))
    m_no_power = com.GAMEMSG(0, dev_num, -4, 1, bytes([2]))

    m_all = com.GAMEMSG(0, 0, -5, 0, bytes([]))

    site_dict = gv.site_dict

    if 0 in site_dict.keys():

        if site_dict[0] == dev_num:

            player_num = site_dict.__len__()

            if player_num >= 4:

                com.send(m_ok)
                com.send(m_all)

                # 游戏开始
                gv.game_mode = 2

                # 生成有序座位表
                site_order_list = []
                for k in site_dict.keys():
                    site_order_list.append(k)
                site_order_list.sort()
                gv.site_order_list = site_order_list

                # 生成牌库,洗牌,发牌
                build_deck()

                # 查找第一发现人

            else:
                com.send(m_not_enough)
        else:
            com.send(m_no_power)
    else:
        com.send(m_no_power)
def disconnect(socket, channelMap):
    name = return_user_name(socket, channelMap)
    for key,values in channelMap.items():
        channelMap[key].remove([name,socket])
    socket.close()
    message = '%s just left the IRC'
    affected_sockets = return_channel_sockets('Global', channelMap)
    connbroadcast = '\n[' + 'SERVER@6510' + ']>> ' + message
    for o in affected_sockets:
        if o != socket:
            send(o, connbroadcast)
Ejemplo n.º 39
0
def disconnect(socket, channelMap):
    name = return_user_name(socket, channelMap)
    for key, values in channelMap.items():
        channelMap[key].remove([name, socket])
    socket.close()
    message = '%s just left the IRC'
    affected_sockets = return_channel_sockets('Global', channelMap)
    connbroadcast = '\n[' + 'SERVER@6510' + ']>> ' + message
    for o in affected_sockets:
        if o != socket:
            send(o, connbroadcast)
Ejemplo n.º 40
0
def play_dead():
	communication.send(b'7')
	set_mode('BACKWARDS')
	sleep(1)
	set_mode('FORWARDS')
	sleep(0.25)
	set_mode('STOP')
	communication.send(b'8')
	
	send_room_message('blegh')
	return statement('blegh')
def list_rooms(socket, channelMap):
    sample = []
    for key,values in channelMap.items():
        if key != 'Global':
            sample.append(key)
    if sample:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'Currently available rooms are: \n' + '\n'.join(sample)
        send(socket,new_message)
    elif not sample:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'There are no rooms'
        send(socket,new_message)
Ejemplo n.º 42
0
 def set_DT(self, DT):
     # self.DT_box.setDateTime(DT)
     DT_list = DT.toString('yyyy.MM.dd.hh.mm.ss').split('.')
     DT_text = '1C%04X' % int(DT_list[0])
     for DT in DT_list[1:]:
         DT_text += '%02X' % int(DT)
     print(DT_text)
     apdu_text = '06010D40000200' + DT_text + '00'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.read_res)
     communication.send(link_layer.add_link_layer(apdu_text))
Ejemplo n.º 43
0
def check_user_inchannel(clientname, socket, channelname, channelMap):
    if check_channel_exist(channelname, channelMap) == True:
        if [clientname, socket] in channelMap[channelname]:
            return True
        else:
            return False
    else:
        #send to requesting socket, if i implement this, but this is mainly for other functions
        msg = "Checking for user in room that doesn't exist"
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
        send(socket, new_message)
def check_user_inchannel(clientname, socket, channelname, channelMap):
    if check_channel_exist(channelname, channelMap) == True:
        if [clientname,socket] in channelMap[channelname]:
            return True
        else:
            return False
    else:
        #send to requesting socket, if i implement this, but this is mainly for other functions
        msg = "Checking for user in room that doesn't exist"
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
        send(socket, new_message)
Ejemplo n.º 45
0
def set_game_page(page):

    if (page == 2):
        # 游戏开始
        gv.game_page = 2

        # 重新生成紧密排列的座位表
        new_site_list = [0, 0, 0, 0, 0, 0, 0, 0]
        cnt = 0
        for s in gv.site_list:
            if s != 0:
                new_site_list[cnt] = s
                cnt = cnt + 1

        gv.site_list = new_site_list

        # 生成牌库,洗牌,发牌
        '''
            普通人 0
            不在场证明 1
            第一发现人 2
            共犯 3
            目击者 4
            谣言 5
            情报交换 6
            交易 7
            犯人 8
            侦探 9
            神犬 10
        '''
        card_deck = []
        player_num = gv.player_num
        card_num = player_num * 4
        for i in range(card_num):
            card_deck.append(0)

        # 洗牌

        # 发牌
        for i in range(player_num):
            gv.player_card_list[i] = []

        cnt = 0
        for c in card_deck:
            gv.player_card_list[cnt].append(c)
            cnt = cnt + 1
            if cnt >= player_num:
                cnt = 0

        for i in range(player_num):
            dev_num = new_site_list[i]
            bs = bytes([dev_num] + gv.player_card_list[i])
            m = com.GAMEMSG(0, dev_num, -3, bs)
            com.send(m)
Ejemplo n.º 46
0
 def SA_set(self, DT):
     self.res_b.setText('')
     SA_text = self.SA_box.text().replace(' ', '')
     if len(SA_text) % 2 == 1:
         SA_text += 'F'
     self.SA_box.setText(SA_text)
     print('SA_text', SA_text)
     SA_len = len(SA_text) // 2
     apdu_text = '06010D4001020009' + '%02X' % (SA_len) + SA_text + '00'
     config.serial_window._receive_signal.disconnect()
     config.serial_window._receive_signal.connect(self.read_res_SA)
     communication.send(link_layer.add_link_layer(apdu_text))
def create_channel(channelname, client, socket, channelMap):
    if check_channel_exist(channelname, channelMap) == False:
        channelMap[channelname] = [[client,socket]]
        msg = "Room %s Created" % (channelname)
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
        send(socket,new_message)
        return channelMap
    else:
        msg = "Room is Existing....Joining Room"
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
        send(socket, new_message)
        join_channel(channelname, client, socket, channelMap)
Ejemplo n.º 48
0
def list_rooms(socket, channelMap):
    sample = []
    for key, values in channelMap.items():
        if key != 'Global':
            sample.append(key)
    if sample:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'Currently available rooms are: \n' + '\n'.join(
            sample)
        send(socket, new_message)
    elif not sample:
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + 'There are no rooms'
        send(socket, new_message)
Ejemplo n.º 49
0
    def send_encrypted(self, to_who, message, name):

        try:

            client_pubkey = open('%s.pub' % name, 'r').read()

            encryptor = RSA.importKey(client_pubkey)
            msg = encryptor.encrypt(message, 0)
            send(to_who, msg)

        except IOError:

            send(to_who, 'PLAIN: cannot find public key for: %s' % name)
Ejemplo n.º 50
0
def get_hum(port):
    """ Requests and returns temperature

    Arguments:
    ser -- serial port object to which Master is connected

    Returns:
    Relative humidity readings from sensor on Slave in percent
    """

    communication.send(port, 'S', 'h')

    hum = communication.read(port)
    return hum
Ejemplo n.º 51
0
def get_temp(port):
    """ Requests and returns temperature

    Arguments:
    ser -- serial port object to which Master is connected

    Returns:
    Temperature readings from sensor on Slave in Celsius
    """

    communication.send(port, 'S', 't')

    temp = communication.read(port)
    return temp
def join_channel(channelname, client, socket, channelMap):    #two steps, check if the room exists and add the client if it des
    if check_channel_exist(channelname, channelMap) == True:
        if check_user_inchannel(client, socket, channelname, channelMap) == True:
            #Send to requesting socket
            msg = "User already in channel"
            new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
            send(socket,new_message)
            return channelMap
        else:
            channelMap[channelname].append([client,socket])
            # send first message to requesting socket and second to other sockets in group
            msg = "Joined Room !"
            new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
            send(socket, new_message)
            msg2= "%s just joined Room - %s" % (client, channelname)
            new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg2
            affected_sockets = return_channel_sockets(channelname, channelMap)
            for o in affected_sockets:
                if o != socket:
                    send(o, new_message)
            return channelMap
    else:
        # Send message to Requesting socket
        msg = "Room Does Not Exist !"
        new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
        send(socket,new_message)
        return channelMap
    def runClient(self,filename, host, port, passw):
        self.filename =filename
        self.port = int(port)
        self.host=host
        self.passw=passw
        que=Queue()
        q1=Queue()
        self.data=''
        self.flag=False
        
        try:
            
            self.s=self.getClientSocket()
            self.s.connect((self.host, self.port))
            if self.filename[:1] == '~' :
                tempToSend=self.dataSend(self.passw,self.filename)
            else:
                self.file=open(self.filename, 'rb')
                while True:
                    self.data = self.file.read(1024)
                    if not self.data:break
                    tempToSend=self.dataSend(self.passw,self.data)
            send(self.s,tempToSend)
            q=Process(target=self.getData,args=(que,))
            p=Process(target=self.pendingData,args=(q1,))
            q.start()
            p.start()
            self.data=que.get()
            self.pid=q1.get()
            #q.terminate()
            if self.data:
                self.flag = False
            print 'sudah terima'
            if self.flag == False:
                
                os.kill(self.pid, signal.SIGTERM)
                p.terminate()
                #p.join()

            # Contains client address, set it
            addr = self.data
            print self.data

            return addr
            messg='repo updated..>!!!!'
            print messg
        except socket.error, e:
            print 'Could not connect to server @%d' % self.port
            sys.exit(1)
Ejemplo n.º 54
0
    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
Ejemplo n.º 55
0
 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 help_message(socket):
    msg = """
            WELCOME TO THE IRC HELP\n
            CREATE A ROOM OR JOIN A ROOM TO START A CONVERSATION
            TO LIST ALL ROOMS. USE: 'LIST' \n
            TO LIST ALL MEMEBERS OF A ROOM. USE: 'MEMBERS roomname' \n
            TO CREATE A ROOM. USE: 'CREATE roomname' NOTE: IF ROOM ALREADY EXISTS YOU'LL JOIN IT. \n
            TO JOIN A ROOM. USE: 'JOIN roomname' \n
            TO JOIN MULTIPLE ROOMS. USE: 'JOIN roomname roomname roomname' \n
            TO LEAVE A ROOM. USE: 'LEAVE roomname' \n
            TO DISCONNECT FROM THE IRC. USE: 'DISCONNECT' \n
            TO SEND A PRIVATE MESSAGE TO ANOTHER CLIENT. USE: 'PRIVATE-MSG username message' \n
            TO SEND A MESSAGE TO A CHANNEL. USE: 'CHANNEL-MSG channelname message.' \n
            TO SEND DISTINCT MESSAGE TO MULTIPLE CHANNELS. USE: 'CHANNEL-MSG channelname message channelname message.' \n
        """
    new_message = '\n[' + 'SERVER@6510' + ']>> ' + msg
    send(socket, new_message)
    def send_encrypted(self, to_who, message, name):
        try:
            encryptor = self.clientmap[to_who][2]
            msg = encryptor.encrypt(message, 0)
            msg = msg[0]
            
            message_hash = SHA256.new()
            message_hash.update(msg)
            signkey = self.sign
            #Append Signature
            signer = PKCS1_PSS.new(signkey)
            signature = signer.sign(message_hash)
            msg = '%s#^[[%s' % (msg, signature)
            #print msg
            send(to_who, msg)

        except IOError:
            send(to_who, 'PLAIN: cannot find public key for: %s' % name)
Ejemplo n.º 58
0
    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)
Ejemplo n.º 59
0
 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 __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)