Skip to content

Commit

Permalink
fix: 调整手动控逻辑,修复伪服务端重复启动
Browse files Browse the repository at this point in the history
  • Loading branch information
HIM049 committed Sep 17, 2024
1 parent 98edbe1 commit 32c4dc5
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 89 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,5 +129,5 @@ dmypy.json
.pyre/

# MCDR Plugins
.mcdr
.pyz
*.mcdr
*.pyz
182 changes: 95 additions & 87 deletions hibernate_r/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def on_load(server: PluginServerInterface, prev_module):
running = False
current_timer = None

server.logger.info("所有参数初始化完成")
server.logger.info("参数初始化完成")
builder = SimpleCommandBuilder()

# declare your commands
Expand All @@ -47,17 +47,13 @@ def hr_sleep():
Server.stop()
time.sleep(10)

running = True
fake_server(Server)

@new_thread
def hr_wakeup():
global running
Server.logger.info("手动唤醒")
running = True
time.sleep(10)

Server.start()
running = False


# 服务器启动完成事件
Expand Down Expand Up @@ -133,16 +129,23 @@ def shutdown_server(server: PluginServerInterface):
global running
server.logger.info("倒计时结束,关闭服务器")
server.stop()
time.sleep(10)#这个逻辑有点问题,如果用了forge那种大服务器关闭要很久(我遇到过),但是没有思路和精力改
time.sleep(10)
# TODO: 这个逻辑有点问题,如果用了forge那种大服务器关闭要很久(我遇到过),但是没有思路和精力改

running = True
fake_server(server)


# FakeServer部分
@spam_proof
def fake_server(server: PluginServerInterface):
global running

if running :
server.logger.warn("伪装服务器正在运行")
return
else:
running = True

check_config_fire(server)
time.sleep(2)
with open("config/HibernateR.json", "r") as file:
Expand All @@ -163,92 +166,97 @@ def fake_server(server: PluginServerInterface):
with open(config["server_icon"], 'rb') as image:
fs_icon = "data:image/png;base64," + base64.b64encode(image.read()).decode()

while True:
while running:
try:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
server_socket.bind((fs_ip, fs_port))
except:
server.logger.error("伪装服务端启动失败")
server_socket.settimeout(10)
except Exception as e:
server.logger.error(f"伪装服务端启动失败: {e}")
server_socket.close()
time.sleep(1)
time.sleep(1) # 延迟后重试
continue
else:
server.logger.info("伪装服务端已启动")
break

server_socket.listen(5)
server.logger.info("开始监听端口")
try:
while running:
# server.logger.info("等待连接")
client_socket, client_address = server_socket.accept()
try:
recv_data = client_socket.recv(1024)
client_ip = client_address[0]
(length, i) = read_varint(recv_data, 0)
(packetID, i) = read_varint(recv_data, i)

if packetID == 0:
(version, i) = read_varint(recv_data, i)
(ip, i) = read_utf(recv_data, i)

ip = ip.replace('\x00', '').replace("\r", "\\r").replace("\t", "\\t").replace("\n", "\\n")
is_using_fml = False
if ip.endswith("FML"):
is_using_fml = True
ip = ip[:-3]
(port, i) = read_ushort(recv_data, i)
(state, i) = read_varint(recv_data, i)
if state == 1:
server.logger.info("伪装服务器收到了一次ping: %s" % (recv_data))
motd = {}
motd["version"] = {}
motd["version"]["name"] = "Sleeping"
motd["version"]["protocol"] = 2
motd["players"] = {}
motd["players"]["max"] = 10
motd["players"]["online"] = 10
motd["players"]["sample"] = []

for sample in fs_samples:
motd["players"]["sample"].append(
{"name": sample, "id": str(uuid.uuid4())})

motd["description"] = {"text": fs_motd}
if fs_icon and len(fs_icon) > 0:
motd["favicon"] = fs_icon
write_response(client_socket, json.dumps(motd))

elif state == 2:
server.logger.info("伪装服务器收到了一次连接请求: %s" % (recv_data))

# TM判断写一大堆,数据发过来一瞅总是少一截,离大谱。
# 找这个原因最起码花了我四五个小时
# 直接全部删掉,不是ping直接返回、
write_response(client_socket, json.dumps({"text": fs_kick_message}))
start_server(server)
running = False

return
elif packetID == 1:
(long, i) = read_long(recv_data, i)
response = bytearray()
write_varint(response, 9)
write_varint(response, 1)
bytearray.append(long)
client_socket.sendall(bytearray)
server.logger.info("Responded with pong packet.")
else:
server.logger.warning("收到了意外的数据包")

except (TypeError, IndexError): # 错误处理(类型错误或索引错误)
server.logger.warning("[%s:%s]收到了无效数据(%s)" % (client_ip, client_address[1], recv_data))
except Exception as e:
server.logger.error(e)
except Exception as ee:
server.logger.error("发生错误%s" % ee)
server.logger.info("关闭套接字")
server_socket.close()


try:
server_socket.listen(5)
server.logger.info("开始监听端口")
while running:
# server.logger.info("等待连接")
# 接受客户端连接
client_socket, client_address = server_socket.accept()
try:
recv_data = client_socket.recv(1024)
client_ip = client_address[0]
(length, i) = read_varint(recv_data, 0)
(packetID, i) = read_varint(recv_data, i)

if packetID == 0:
(version, i) = read_varint(recv_data, i)
(ip, i) = read_utf(recv_data, i)

ip = ip.replace('\x00', '').replace("\r", "\\r").replace("\t", "\\t").replace("\n", "\\n")
is_using_fml = False
if ip.endswith("FML"):
is_using_fml = True
ip = ip[:-3]
(port, i) = read_ushort(recv_data, i)
(state, i) = read_varint(recv_data, i)
if state == 1:
server.logger.info("伪装服务器收到了一次ping: %s" % (recv_data))
motd = {}
motd["version"] = {}
motd["version"]["name"] = "Sleeping"
motd["version"]["protocol"] = 2
motd["players"] = {}
motd["players"]["max"] = 10
motd["players"]["online"] = 10
motd["players"]["sample"] = []

for sample in fs_samples:
motd["players"]["sample"].append(
{"name": sample, "id": str(uuid.uuid4())})

motd["description"] = {"text": fs_motd}
if fs_icon and len(fs_icon) > 0:
motd["favicon"] = fs_icon
write_response(client_socket, json.dumps(motd))

elif state == 2:
server.logger.info("伪装服务器收到了一次连接请求: %s" % (recv_data))
write_response(client_socket, json.dumps({"text": fs_kick_message}))
start_server(server)
running = False

return
elif packetID == 1:
(long, i) = read_long(recv_data, i)
response = bytearray()
write_varint(response, 9)
write_varint(response, 1)
bytearray.append(long)
client_socket.sendall(bytearray)
server.logger.info("Responded with pong packet.")
else:
server.logger.warning("收到了意外的数据包")
except (TypeError, IndexError): # 错误处理(类型错误或索引错误)
server.logger.warning("[%s:%s]收到了无效数据(%s)" % (client_ip, client_address[1], recv_data))
except Exception as e:
server.logger.error(e)
server_socket.close()
except socket.timeout:
server.logger.debug("连接超时")
server_socket.close()
continue
except Exception as ee:
server.logger.error("发生错误%s" % ee)
server.logger.info("关闭套接字")
server_socket.close()
server.logger.info("伪装服务器已退出")
start_server(server)

# 启动服务器
def start_server(server: PluginServerInterface):
Expand Down

0 comments on commit 32c4dc5

Please sign in to comment.