def on_message(self, message): try: if message[1] == 0x00: # 0x00代表登陆(0x00是自己定义,可以随意修改成自己的标头) login = MessageLogin() #初始化 登陆的protobuf login.ParseFromString(bytes( message[4:])) #去掉前四位标头 去后面的protobuf数据 并反序列序列化 self.__name = login.account MainHandler.__client_manager.add_client( self.__name, self) #将新登陆玩家 加入到 玩家列表中 Debug.log('All Clienk ' + str(MainHandler.__client_manager.get_client_list())) resp = MessageGenerateExistedClients() # 初始化 已注册的protobuf resp.clients.extend( MainHandler.__client_manager.get_client_list( )) # 将已登陆的玩家列表 转成protobuf 数据 self.write_message( b'\x00\x22\x00\x00' + resp.SerializeToString(), binary=True) #将protobuf数据序列化 传给 新登陆的玩家(前端用词数据生成其玩家的模型) Debug.log('get login req from ' + self.__name) MainHandler.__client_manager.send_message_to_all_except_one( self.__name, message) #将自己的登陆信息 传给除自己以外的其他人 except Exception as e: traceback.print_exc()
def get_colorboard(self): colorboard = self.colors[self.board] colorboard[self.exit.y][self.exit.x] = self.colors[ PacmanObjectType.EXIT] for food in self.current_state.foods: colorboard[food.y][food.x] = self.colors[PacmanObjectType.FOOD] for agent in self.current_state.agents: Debug.print(agent) colorboard[agent.pos.y][agent.pos.x] = self.colors[agent.type] return colorboard
def next(self): self.current_state, _ = self.act(self.current_state) if self.is_winning_state(self.current_state): Console.print("-1 -1") Debug.print("Player won.") return False elif self.is_losing_state(self.current_state): Console.print("-1 -1") Debug.print("Player lost.") return False return True
def on_close(self): #玩家退出时执行的回调 rep = MessageLogout() rep.account = self.__name MainHandler.__client_manager.send_message_to_all_except_one( self.__name, b'\x00\x01\x00\x00' + rep.SerializeToString()) MainHandler.__client_manager.remove_client(self.__name) Debug.log('removed: ' + self.__name) Debug.log('remain clients: ' + str(MainHandler.__client_manager.get_client_list())) self.close()
def res_to_ctl(data, conn, conn_box): if Constants.remote_ssl: # 对称解密 data = asymmetric.decrypt(data, conn_box.random_key) Debug.log('对称解密响应3:', data) if Constants.local_ssl: # 对称加密 data = asymmetric.encrypt(data, conn_box.clt_random_key) Debug.log('对称加密返还客户端响应3:', data) conn.send(data) if Constants.local_ssl: # 发送结束标记 conn.send(conn_box.clt_end_flag)
def forward_data(conn, target_host, target_port, conn_box): # 创建连接对象 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10) conn_box.clt_conn_flag = True conn_box.forward_recv_flag = True end_flag = conn_box.clt_end_flag retain_data = b'' while True: if Constants.local_ssl: buffer = 2048 else: buffer = 1024 try: tmp_data = conn.recv(buffer) except ConnectionAbortedError: break except OSError: break if not tmp_data: break else: Debug.log('接收3:', tmp_data) if Constants.local_ssl: tmp_data = retain_data + tmp_data retain_data = b'' if tmp_data.find(end_flag) == -1: while True: # 接收结束标记 tmp_data += conn.recv(buffer) if tmp_data.find(end_flag) != -1: break tmp_data_s = tmp_data.split(end_flag) for n in range(len(tmp_data_s)): if n == len(tmp_data_s) - 1: retain_data = tmp_data_s[n] break # 发送至下一节点 send_next_node(tmp_data_s[n], s, conn, conn_box, target_host, target_port) else: # 发送至下一节点 send_next_node(tmp_data, s, conn, conn_box, target_host, target_port) Debug.log("----------------------第三次交互完毕------------------------------")
def Sol2(S, P, Q): D = {'A':1, 'C':2, 'G':3, 'T':4} N = len(S) M = len(P) Debug(S) result = [0]*M for i in range(M): partical = S[P[i]:Q[i]+1] if Q[i] < N-1 else S[P[i]:] Debug('partical {}'.format(partical)) s = set(partical) m = min([D[k] for k in s]) result[i] = m return result
def S(X, A): N = len(A) if N < X: return -1 S = set([x for x in range(1, X+1)]) s = set() Debug(S) for i in range(N): s.add(A[i]); if s == S: Debug(s) return i return -1
def S(A): N = len(A) B = [] adding = 0 for i in range(N): adding += A[i] B.append(adding) # B[A0, (A0+A1), .. (A0+..An-1)] Total = B[N - 1] Debug(B) Debug("total: %i" % Total) #Gap = [Total-B(i)-B[i] for i in range(len(B))] #m = min([abs(Total-B[i]*2) for i in range[N-1]]) diff = [abs(Total - x * 2) for x in B[:(N - 1)]] Debug(diff) m = min(diff) return m
def send_next_node(tmp_data, s, conn, conn_box, target_host, target_port): if Constants.local_ssl: # 对称解密 tmp_data = asymmetric.decrypt(tmp_data, conn_box.clt_random_key) Debug.log('对称解密接收3:', tmp_data) if conn_box.clt_conn_flag: conn_box.clt_conn_flag = False # 是否需要前置代理 if Constants.proxy: # 与前置代理建立连接 ss5clt.ss5conn(s, conn_box) else: # 与目标建立连接 s.connect((target_host, target_port)) # 转发数据 Debug.log('转发数据:', tmp_data) if Constants.remote_ssl: # 对称加密 tmp_data = asymmetric.encrypt(tmp_data, conn_box.random_key) Debug.log('对称加密:', tmp_data) s.send(tmp_data) if Constants.remote_ssl: # 发送结束标记 s.send(conn_box.end_flag) if conn_box.forward_recv_flag: conn_box.forward_recv_flag = False # 接收数据并返还客户端 tr = threading.Thread(target=forward_recv, args=(s, conn, conn_box)) tr.start()
def S1(A): N = len(A) if N <= 1: return 0 # count '1's (go backwards) count_of_one = [0] * N counter = 0 for i in range(N - 1): if A[N - i - 1] == 1: counter += 1 count_of_one[N - i - 1 - 1] = counter Debug("count_of_one: {}".format(count_of_one)) total = 0 for i in range(N - 1): if A[i] == 0: pairs = count_of_one[i] total += pairs return total
def act(self, state, action=None): nstate = state.copy() for idx, agent in enumerate(state.agents): if agent.type is PacmanAgentType.PLAYER: nstate.agents[idx], action = agent.move(state, action) newpos = nstate.agents[idx].pos if not self.is_valid_state(nstate): Debug.print("Agent [", agent.name, "] Forbidden move!") raise RuntimeError if newpos in nstate.foods: nstate.foods.remove(newpos) else: # hack. enemies see what move we're going to make. nstate.agents[idx], _ = agent.move(nstate) if not self.is_valid_state(nstate): Debug.print(agent.pos, nstate.agents[idx].pos) Debug.print("Agent [", agent.name, "] Forbidden move!") raise RuntimeError return nstate, self.reward(state.get_player_agent(), state, action, nstate)
def open(self): Debug.log('get a new connection') self.set_nodelay(True) self.__name = ''
def ss5forward(data, conn, conn_box): # 初始化 auth = Constants.auth METHODS_D1 = b'' REP_D2 = b'\x00' VER_C1 = data[0:1] Debug.log("版本:", VER_C1) NMETHODS_C1 = data[1:2] Debug.log("客户端支持的方法数量:", NMETHODS_C1) METHODS_C1 = data[2:] Debug.log("客户端支持的方法:", METHODS_C1) if auth: if METHODS_C1.find(b'\x02') != -1: METHODS_D1 = b'\x02' else: if METHODS_C1.find(b'\x00') != -1: METHODS_D1 = b'\x00' elif METHODS_C1.find(b'\x02') != -1: METHODS_D1 = b'\x02' # 响应 Debug.log("准备响应") if len(METHODS_D1) > 0: Debug.log("服务端选择的方法:", METHODS_D1) else: Debug.log('server没有支持的方法') METHODS_D1 = '\xff' res1 = VER_C1 + METHODS_D1 Debug.log("响应1: %s" % res1) if Constants.local_ssl: # 非对称加密 # res1 = asymmetric.encrypt(res1, conn_box.clt_random_key) res1 = symmetric.encrypt(res1, conn_box.client_public_key) Debug.log('非对称加密res1:', res1) conn.send(res1) Debug.log("----------------------第一次交互完毕------------------------------") # 如果需要用户认证 if METHODS_D1 == b'\x02': if not auth: res_auth = b'\x01\x00' else: Debug.log('----------需要认证------------') data = conn.recv(512) if Constants.local_ssl: # 非对称解密 # data = asymmetric.decrypt(data, conn_box.clt_random_key) data = symmetric.decrypt(data, Constants.privateKey) Debug.log('对称解密认证信息:', data) auth_version = data[0:1] ulen = int(data[1:2].hex(), 16) uname = data[2:2 + ulen].decode() plen = int(data[2 + ulen:3 + ulen].hex(), 16) passwd = data[3 + ulen:4 + ulen + plen].decode() Debug.log('--认证信息--') Debug.log("认证版本", auth_version) Debug.log("用户名长度", ulen) Debug.log("用户名", uname) Debug.log("密码长度", plen) Debug.log("密码", passwd) auth_success = False if auth_version == b'\x01': u_list = Constants.auth_usr_lst for user in u_list: if user.get('usr') == uname: if user.get('pwd') == passwd: Debug.log('认证通过') auth_success = True else: Debug.log('密码不正确') break else: Debug.log('不支持的认证版本') if auth_success: res_auth = b'\x01\x00' else: res_auth = b'\x01\x01' Debug.log('响应认证', res_auth) if Constants.local_ssl: # 非对称加密 # res_auth = asymmetric.encrypt(res_auth, conn_box.clt_random_key) res_auth = symmetric.encrypt(res_auth, conn_box.client_public_key) Debug.log('非对称加密res_auth:', res_auth) conn.send(res_auth) Debug.log('----------认证结束------------') # 接收客户端向服务端发送请求 data = conn.recv(512) Debug.log("接收2: %s" % data) if Constants.local_ssl: # 非对称解密 # data = asymmetric.decrypt(data, conn_box.clt_random_key) data = symmetric.decrypt(data, Constants.privateKey) Debug.log('非对称解密接收2:', data) VER_C2 = data[0:1] CMD_C2 = data[1:2] RSV_C2 = data[2:3] ATYP_C2 = data[3:4] Debug.log("版本:", VER_C2) Debug.log("CMD:", CMD_C2) Debug.log("RSV:", RSV_C2) Debug.log("地址类型:", ATYP_C2) if ATYP_C2 == b'\x01': DST_ADDR_C2 = data[4:8] DST_PORT_C2 = data[8:10] target_host = socket.inet_ntoa( struct.pack('!L', int(DST_ADDR_C2.hex(), 16))) # target_host = utils.ip_int2str(int(DST_ADDR_C2.hex(), 16)) elif ATYP_C2 == b'\x03': conn_box.DST_ADDR_LEN_C2 = data[4:5] DST_ADDR_LEN_C2 = data[4] Debug.log("目标地址长度:", DST_ADDR_LEN_C2) DST_ADDR_C2 = data[5:5 + DST_ADDR_LEN_C2] DST_PORT_C2 = data[5 + DST_ADDR_LEN_C2:7 + DST_ADDR_LEN_C2] target_host = DST_ADDR_C2.decode() else: Debug.log('使用ipv6') DST_ADDR_C2 = data[4:20] DST_PORT_C2 = data[20:22] # target_host = socket.inet_ntoa(struct.pack('!L', int(DST_ADDR_C2.hex(), 16))) target_host = utils.ip_int2str(int(DST_ADDR_C2.hex(), 16)) # 如果需要前置代理,记录此信息 if Constants.proxy: Debug.log('使用前置代理先保留客户端交互信息') conn_box.VER_C2 = VER_C2 conn_box.CMD_C2 = CMD_C2 conn_box.RSV_C2 = RSV_C2 conn_box.ATYP_C2 = ATYP_C2 conn_box.DST_ADDR_C2 = DST_ADDR_C2 conn_box.DST_PORT_C2 = DST_PORT_C2 Debug.log("目标地址:", DST_ADDR_C2) # Debug.log("目标端口:", DST_PORT_C2) Debug.log("目标端口:", int(DST_PORT_C2.hex(), 16)) Debug.log("准备响应") ATYP_D2 = b'\x01' BND_ADDR_D2 = b'\x00\x00\x00\x00' BND_PORT_D2 = b'\x00\x00' res2 = VER_C2 + REP_D2 + RSV_C2 + ATYP_D2 + BND_ADDR_D2 + BND_PORT_D2 Debug.log("响应2: %s" % res2) if Constants.local_ssl: # 对称加密 # res2 = asymmetric.encrypt(res2, conn_box.clt_random_key) res2 = symmetric.encrypt(res2, conn_box.client_public_key) Debug.log('对称加密res1:', res2) conn.send(res2) Debug.log("----------------------第二次交互完毕------------------------------") # 开始转发数据 target_port = int(DST_PORT_C2.hex(), 16) protocmsd.forward_data(conn, target_host, target_port, conn_box)
def ss5conn(s, conn_box): proxy = Constants.proxy proxy_address = proxy.get('proxy_address') proxy_port = proxy.get('proxy_port') usr = proxy.get('usr') pwd = proxy.get('pwd') Debug.log('使用socks5前置代理>>>>> %s:%d' % (proxy_address, proxy_port)) s.connect((proxy_address, proxy_port)) if Constants.remote_ssl: # 发送公钥 tmp_pub_key = Constants.publicKey[31:-30] Debug.log("发送公钥:", tmp_pub_key) s.send(tmp_pub_key) data = b'' while True: # 接收加密公钥 data += s.recv(1024) if not data or len(data) >= 256: break Debug.log('接收公钥:', data) # 解密公钥 tmp_ser_pub_key_1 = symmetric.decrypt(data[:128], Constants.privateKey) tmp_ser_pub_key_2 = symmetric.decrypt(data[128:], Constants.privateKey) conn_box.server_public_key = b'-----BEGIN RSA PUBLIC KEY-----\n' \ + tmp_ser_pub_key_1 \ + tmp_ser_pub_key_2 \ + b'\n-----END RSA PUBLIC KEY-----\n' # # 生成随机密钥 # random_key = asymmetric.generate_key() # 获取随机密钥 random_key = Constants.random_key conn_box.random_key = random_key Debug.log('生成随机密钥:', random_key) # 加密随机密钥 random_key = symmetric.encrypt(conn_box.random_key, conn_box.server_public_key) Debug.log("加密随机密钥:", random_key) # 发送随机密钥 s.send(random_key) # 设置结束标记 conn_box.end_flag = random_key # 建立socks5连接 Debug.log('建立socks5连接') if usr: req1 = b'\x05\x02\x00\x02' else: req1 = b'\x05\x01\x00' Debug.log('req1:', req1) if Constants.remote_ssl: # 非对称加密 req1 = symmetric.encrypt(req1, conn_box.server_public_key) # req1 = asymmetric.encrypt(req1, conn_box.random_key) Debug.log('非对称加密req1:', req1) s.send(req1) # res1 = s.recv(512) res1 = b'' while True: res1 += s.recv(512) if not res1 or len(res1) >= 128: break Debug.log('res1:', res1) if Constants.remote_ssl: # 非对称解密 # res1 = asymmetric.decrypt(res1, conn_box.random_key) res1 = symmetric.decrypt(res1, Constants.privateKey) Debug.log('非对称解密res1:', res1) if res1 == b'\x05\x00': proxy_continue = True elif res1 == b'\x05\x02': auth_info_req = b'\x01' + len(usr).to_bytes( 1, 'big') + usr.encode('utf-8') + len(pwd).to_bytes( 1, 'big') + pwd.encode('utf-8') Debug.log("发送认证信息:", auth_info_req) if Constants.remote_ssl: # 非对称加密 # auth_info_req = asymmetric.encrypt(auth_info_req, conn_box.random_key) auth_info_req = symmetric.encrypt(auth_info_req, conn_box.server_public_key) Debug.log('非对称加密auth_info_req:', auth_info_req) s.send(auth_info_req) auth_info_res = b'' while True: auth_info_res += s.recv(512) if not auth_info_res or len(auth_info_res) >= 128: break # auth_info_res = s.recv(512) Debug.log('接收认证响应:', auth_info_res) if Constants.remote_ssl: # 非对称解密 auth_info_res = symmetric.decrypt(auth_info_res, Constants.privateKey) # auth_info_res = asymmetric.decrypt(auth_info_res, conn_box.random_key) Debug.log('非对称解密接收认证响应:', auth_info_res) if auth_info_res == b'\x01\x00': proxy_continue = True else: print('前置代理用户认证失败') proxy_continue = False else: proxy_continue = False if proxy_continue: if conn_box.ATYP_C2 == b'\x03': req2 = b'\x05' + b'\x01' + b'\x00' + conn_box.ATYP_C2 + conn_box.DST_ADDR_LEN_C2 + conn_box.DST_ADDR_C2 + conn_box.DST_PORT_C2 else: req2 = b'\x05' + b'\x01' + b'\x00' + conn_box.ATYP_C2 + conn_box.DST_ADDR_C2 + conn_box.DST_PORT_C2 Debug.log('发送连接信息至前置代理req:', req2) if Constants.remote_ssl: # 非对称加密 req2 = symmetric.encrypt(req2, conn_box.server_public_key) # req2 = asymmetric.encrypt(req2, conn_box.random_key) Debug.log('对称加密req2:', req2) s.send(req2) res2 = b'' while True: res2 += s.recv(512) if not res2 or len(res2) >= 128: break # res2 = s.recv(512) Debug.log('前置代理返回res2:', res2) if Constants.remote_ssl: # 非对称解密 # res2 = asymmetric.decrypt(res2, conn_box.random_key) res2 = symmetric.decrypt(res2, Constants.privateKey) Debug.log('非对称解密res2:', res2) if res2.startswith(b'\x05\x00'): # ss5连接握手成功 Debug.log('ss5连接握手成功') else: print("前置代理连接过程阶段二发生错误!停止访问!") else: print("前置代理连接过程发生错误!停止访问!")
def ss4forward(data, conn, conn_box): VN_C = data[0:1] CD_C = data[1:2] DSTPORT_C = data[2:4] DSTIP_C = data[4:8] USERID_C = data[8:-1] NULL_C = data[-1:] dst_port = int(DSTPORT_C.hex(), 16) if DSTIP_C == b'\x00\x00\x00\x01': dspip = USERID_C[1:].decode() conn_box.ATYP_C2 = b'\x03' conn_box.DST_ADDR_LEN_C2 = len(USERID_C[1:]).to_bytes(1, 'big') conn_box.DST_ADDR_C2 = USERID_C[1:] else: dspip = socket.inet_ntoa(struct.pack('!L', int(DSTIP_C.hex(), 16))) conn_box.ATYP_C2 = b'\x01' conn_box.DST_ADDR_C2 = DSTIP_C conn_box.DST_PORT_C2 = DSTPORT_C Debug.log('VN', VN_C) Debug.log('CD', CD_C) Debug.log('DSTPORT', dst_port) Debug.log('DSTIP', DSTIP_C) Debug.log('USERID', USERID_C) Debug.log('Null', NULL_C) Debug.log('dspip', dspip) # 响应 VN_C = b'\x00' CD_D = b'\x5A' DSTPORT_D = DSTPORT_C DSTIP_D = DSTIP_C r_send = VN_C + CD_D + DSTPORT_D + DSTIP_D Debug.log("响应1:", r_send) ''' 保留功能 if Constants.local_ssl: # 对称加密 r_send = asymmetric.encrypt(r_send, conn_box.clt_random_key) Debug.log('对称加密res1:', r_send) ''' conn.send(r_send) Debug.log('------------认证过程结束-----------') # 开始转发数据 target_host = dspip target_port = dst_port protocmsd.forward_data(conn, target_host, target_port, conn_box)
def execute(conn): conn_box = ConnVariable(conn) # 判断是否需要和客户端进行加密传输 if Constants.local_ssl: # 接收公钥 data = conn.recv(1024) Debug.log('接收公钥:', data) conn_box.client_public_key = b'-----BEGIN RSA PUBLIC KEY-----\n' + data + b'\n-----END RSA PUBLIC KEY-----\n' # 发送加密公钥 tmp_pub_key = Constants.publicKey[31:-30] tmp_pub_key_1 = symmetric.encrypt(tmp_pub_key[:100], conn_box.client_public_key) tmp_pub_key_2 = symmetric.encrypt(tmp_pub_key[100:], conn_box.client_public_key) conn.send(tmp_pub_key_1 + tmp_pub_key_2) # 接收随机密钥 clt_random_key = conn.recv(1024) Debug.log("接收随机密钥:", clt_random_key) # 设置客户端结束标记 conn_box.clt_end_flag = clt_random_key # 解密随机密钥 clt_random_key = symmetric.decrypt(clt_random_key, Constants.privateKey) Debug.log("解密随机密钥:", clt_random_key) conn_box.clt_random_key = clt_random_key # 接收 data = conn.recv(512) Debug.log("接收1: %s" % data) if Constants.local_ssl: # 非对称解密 # data = asymmetric.decrypt(data, conn_box.clt_random_key) data = symmetric.decrypt(data, Constants.privateKey) Debug.log('非对称解密接收1:', data) version = 5 # 检查协议 if data.startswith(b'\x04') and data.endswith(b'\x00'): Debug.log('使用socks4协议') version = 4 if version == 5: # 使用socks5协议 ss5.ss5forward(data, conn, conn_box) elif version == 4: # 使用socks4协议 ss4.ss4forward(data, conn, conn_box)
def forward_recv(s, conn, conn_box): end_flag = conn_box.end_flag retain_data = b'' while True: if Constants.remote_ssl: buffer = 4096 else: buffer = 2048 Debug.log("设置接收缓冲区大小", buffer) try: # 接收数据 tmp_data = s.recv(buffer) if not tmp_data: break else: if Constants.remote_ssl: tmp_data = retain_data + tmp_data retain_data = b'' if tmp_data.find(end_flag) == -1: while True: # 接收结束标记 tmp_data += s.recv(buffer) if tmp_data.find(end_flag) != -1: break tmp_data_s = tmp_data.split(end_flag) for n in range(len(tmp_data_s)): if n == len(tmp_data_s) - 1: retain_data = tmp_data_s[n] break Debug.log('响应3:', tmp_data) res_to_ctl(tmp_data_s[n], conn, conn_box) else: Debug.log('响应3:', tmp_data) res_to_ctl(tmp_data, conn, conn_box) except ConnectionAbortedError: Debug.log('ConnectionAbortedError') break except OSError: break except socket.timeout: Debug.log('timeout') break Debug.log('关闭连接', s, conn) try: s.close() except Exception as e: print(e) finally: conn.close()