forked from Firepup650/python-talk
Compare commits
29 commits
Author | SHA1 | Date | |
---|---|---|---|
565dc27a30 | |||
21bbba74c0 | |||
6376818b85 | |||
e71b256a3e | |||
f5e4726c8e | |||
8714a1bec8 | |||
d39f8224d4 | |||
5805d5efcc | |||
9ff812a7b3 | |||
f90c4f40c8 | |||
426fa341ce | |||
a44e7c29fd | |||
aaeb313181 | |||
6d1ff52b02 | |||
8bc876d7af | |||
a245acc770 | |||
a6a9ba0754 | |||
a6ecd9a129 | |||
d84aab7feb | |||
95e1c3f38d | |||
85f4b289e8 | |||
6ab9c030ba | |||
284c3932dd | |||
0994f92669 | |||
16b74ece80 | |||
7c0c4b0875 | |||
1714010182 | |||
60098ddfd4 | |||
53e57b9dc6 |
8 changed files with 571 additions and 273 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -2,3 +2,4 @@ __pycache__/**
|
|||
.env
|
||||
cache.py
|
||||
*.swp
|
||||
bugs.txt
|
||||
|
|
37
IRC-spec.txt
Normal file
37
IRC-spec.txt
Normal file
|
@ -0,0 +1,37 @@
|
|||
# On-connect
|
||||
:<servername> CAP * LS :
|
||||
:<servername> 001 <client> :Welcome to the python-talk Network, <client>
|
||||
:<servername> 002 <client> :Your host is <servername>, running version 0.1
|
||||
:<servername> 003 <client> :This server was created 0
|
||||
:<servername> 004 <client> python-talk 0.1 r t
|
||||
:<servername> 005 <client> AWAYLEN=200,CASEMAPPING=ascii,CHANTYPES=#,ELIST=U,HOSTLEN=16 :are supported by this server
|
||||
:<servername> 005 <client> CHANLIMIT=#:1,CHANMODES=b,k,l,t,CHANNELLEN=4,KICKLEN=1,MAXLIST=b:1 :are supported by this server
|
||||
:<servername> 005 <client> MODES=4,NETWORK=talknet,NICKLEN=20,TOPICLEN=30,USERLEN=1 :are supported by this server
|
||||
:<servername> 251 <client> :There are <u> users and 0 invisible on <s> servers
|
||||
:<servername> 252 <client> 0 :operator(s) online
|
||||
:<servername> 253 <client> 0 :unknown connection(s)
|
||||
:<servername> 254 <client> 1 :channel formed
|
||||
:<servername> 255 <client> :I have <c> clients and <s> servers
|
||||
:<servername> 265 <client> [<u> <m>] :Current local users <u>, max <m>
|
||||
:<servername> 266 <client> [<u> <m>] :Current global users <u>, max <m>
|
||||
:<servername> 422 <client> :This server does not support MOTDs
|
||||
:<client> JOIN #main
|
||||
:<servername> 324 <client> #main t
|
||||
:<servername> 332 <client> #main :Welcome to the main channel!
|
||||
:<servername> 353 <client> = #main :<client>, ...other clients here...
|
||||
:<servername> 366 <client> #main :End of /NAMES list
|
||||
|
||||
# On Attempting to join/part a channel, or anything else I don't want to deal with
|
||||
:<servername> 421 <client> <command> :Unknown command
|
||||
|
||||
# I should probably return the "NOSUCHCHANNEL" thing for joins
|
||||
|
||||
#PING PONG
|
||||
:<servername> PONG <servername> :<data>
|
||||
|
||||
# If the user tries to kill us or another server, respond with an easter egg
|
||||
:<servername> 483 <client> :You can't kill me, I'm Skynet!
|
||||
# Otherwise, if the user exists:
|
||||
:<servername> 481 <client> :Permission Denied- There are no IRC operators here.
|
||||
# Otherwise:
|
||||
:<servername> 401 <client> <nickname> :No such nick/channel
|
13
init-scripts/freebsd-rc
Normal file
13
init-scripts/freebsd-rc
Normal file
|
@ -0,0 +1,13 @@
|
|||
#!/bin/sh
|
||||
. /etc/rc.subr
|
||||
name="python_talk"
|
||||
start_cmd="${name}_start"
|
||||
stop_cmd=":"
|
||||
rcvar=python_talk_enable
|
||||
load_rc_config $name
|
||||
: ${python_talk_enable:=no}
|
||||
python_talk_start() {
|
||||
cd /usr/src/python-talk
|
||||
(while true; do python3 server.py --link=37.27.51.34:65048 --no-log --no-cache --cwlgd 2>&1 >> /var/log/python-talk.log; done) &
|
||||
}
|
||||
run_rc_command "$1"
|
38
init-scripts/systemd-system.service
Normal file
38
init-scripts/systemd-system.service
Normal file
|
@ -0,0 +1,38 @@
|
|||
[Unit]
|
||||
Description=firepup's python-talk
|
||||
|
||||
[Service]
|
||||
DynamicUser=yes
|
||||
WorkingDirectory=/opt/python-talk
|
||||
ExecStart=/usr/bin/python3 server.py --link=37.27.51.34:65048 --no-logs --no-cache --cwlgd
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
RestrictSUIDSGID=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ProtectProc=ptraceable
|
||||
ProcSubset=pid
|
||||
PrivateTmp=true
|
||||
CapabilityBoundingSet=
|
||||
PrivateDevices=true
|
||||
ProtectClock=true
|
||||
ProtectKernelLogs=true
|
||||
ProtectControlGroups=true
|
||||
ProtectKernelModules=true
|
||||
SystemCallArchitectures=native
|
||||
# python.
|
||||
MemoryDenyWriteExecute=false
|
||||
RestrictNamespaces=true
|
||||
ProtectHostname=true
|
||||
LockPersonality=true
|
||||
ProtectKernelTunables=true
|
||||
RestrictAddressFamilies=AF_INET
|
||||
RestrictRealtime=true
|
||||
PrivateUsers=true
|
||||
SystemCallFilter=@system-service
|
||||
SystemCallFilter=~@privileged @resources
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
38
init-scripts/systemd-user.service
Normal file
38
init-scripts/systemd-user.service
Normal file
|
@ -0,0 +1,38 @@
|
|||
[Unit]
|
||||
Description=firepup's python-talk
|
||||
|
||||
[Service]
|
||||
WorkingDirectory=%h/python-talk
|
||||
ExecStart=/usr/bin/python3 server.py --link=37.27.51.34:65048 --no-logs --no-cache --cwlgd
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
RestrictSUIDSGID=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=tmpfs
|
||||
BindReadOnlyPaths=%h/python-talk
|
||||
ProtectProc=ptraceable
|
||||
ProcSubset=pid
|
||||
PrivateTmp=true
|
||||
CapabilityBoundingSet=
|
||||
PrivateDevices=true
|
||||
ProtectClock=true
|
||||
ProtectKernelLogs=true
|
||||
ProtectControlGroups=true
|
||||
ProtectKernelModules=true
|
||||
SystemCallArchitectures=native
|
||||
# python.
|
||||
MemoryDenyWriteExecute=false
|
||||
RestrictNamespaces=true
|
||||
ProtectHostname=true
|
||||
LockPersonality=true
|
||||
ProtectKernelTunables=true
|
||||
RestrictAddressFamilies=AF_INET
|
||||
RestrictRealtime=true
|
||||
PrivateUsers=true
|
||||
SystemCallFilter=@system-service
|
||||
SystemCallFilter=~@privileged @resources
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
10
logs.py
10
logs.py
|
@ -7,7 +7,7 @@ from typing import Union
|
|||
def log(
|
||||
message: str,
|
||||
level: str = "LOG",
|
||||
origin: str = None,
|
||||
origin: str = None, # pyright: ignore[reportArgumentType]
|
||||
time: Union[dt, str] = "now",
|
||||
) -> bytes:
|
||||
if level in ["EXIT", "CRASH", "FATAL", "ERROR"]:
|
||||
|
@ -30,12 +30,16 @@ def log(
|
|||
print(
|
||||
f"[{level}]{'['+origin+']' if origin else ''}[{time}] {message}",
|
||||
file=stream,
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
for line in message.split("\n"):
|
||||
log = log + f"\n[{level}]{'['+origin+']' if origin else ''}[{time}] {line}"
|
||||
log = (
|
||||
log + f"\r\n[{level}]{'['+origin+']' if origin else ''}[{time}] {line}"
|
||||
)
|
||||
print(
|
||||
f"[{level}]{'['+origin+']' if origin else ''}[{time}] {line}",
|
||||
file=stream,
|
||||
flush=True,
|
||||
)
|
||||
return (log[5:] + "\n").encode("utf8")
|
||||
return (log[5:] + "\r\n").encode("utf8")
|
||||
|
|
15
poetry.lock
generated
15
poetry.lock
generated
|
@ -1,15 +1,14 @@
|
|||
# This file is automatically @generated by Poetry and should not be changed by hand.
|
||||
# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.
|
||||
|
||||
[[package]]
|
||||
name = "firepup650"
|
||||
version = "1.0.40"
|
||||
version = "1.0.43"
|
||||
description = "Package containing various shorthand things I use, and a few imports I almost always use"
|
||||
category = "main"
|
||||
optional = false
|
||||
python-versions = "<4.0,>=3.8"
|
||||
files = [
|
||||
{file = "firepup650-1.0.40-py3-none-any.whl", hash = "sha256:f8c02fd35667fe38a34e1e26f132d00eb3c1ca4fe0585b8bf8e2c3b2feafa659"},
|
||||
{file = "firepup650-1.0.40.tar.gz", hash = "sha256:d1043a8e9deec63a5f057a279528ecddff95b9e53299d2a0b799378bf97294e9"},
|
||||
{file = "firepup650-1.0.43-py3-none-any.whl", hash = "sha256:685a3e00586bfa483108675de52bd05ef1ddbf50864fc4071c735bf36a726b23"},
|
||||
{file = "firepup650-1.0.43.tar.gz", hash = "sha256:985d679370d61490e4a7efa2022d0c1971c63223b5a455b374bfd1fe1b910612"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
|
@ -20,7 +19,6 @@ fpsql = ">=1,<1.0.26 || >1.0.26,<2"
|
|||
name = "fkeycapture"
|
||||
version = "1.2.7"
|
||||
description = "A way to capture keystrokes"
|
||||
category = "main"
|
||||
optional = false
|
||||
python-versions = ">=3.8,<4.0"
|
||||
files = [
|
||||
|
@ -32,7 +30,6 @@ files = [
|
|||
name = "fpsql"
|
||||
version = "1.0.5"
|
||||
description = "An easy to use SQLite package"
|
||||
category = "main"
|
||||
optional = false
|
||||
python-versions = ">=3.8,<4.0"
|
||||
files = [
|
||||
|
@ -42,5 +39,5 @@ files = [
|
|||
|
||||
[metadata]
|
||||
lock-version = "2.0"
|
||||
python-versions = "^3.11"
|
||||
content-hash = "a5fdf74d67707a0d1acbce90d478d8405e7bdc6826f33c0769eb1eb9650649c0"
|
||||
python-versions = "^3.10"
|
||||
content-hash = "883fa6484539c99f51b0004d7241922c884911ba7aaacf6517a3bae6b7a6c3e7"
|
||||
|
|
692
server.py
692
server.py
|
@ -1,35 +1,51 @@
|
|||
#! /usr/bin/python3
|
||||
import os, sys, asyncio, re, signal
|
||||
#!/usr/bin/python3
|
||||
import os, sys, asyncio, re, signal, socket, random
|
||||
from platform import uname
|
||||
from traceback import format_exc
|
||||
from logs import log
|
||||
from datetime import datetime as dt, timezone as tz
|
||||
|
||||
|
||||
class LinksDownException(Exception): ...
|
||||
class LinkDownError(Exception): ...
|
||||
|
||||
|
||||
class Globals: ...
|
||||
class FailedLinkError(Exception): ...
|
||||
|
||||
|
||||
# The two below lines are a hacky fix for python 3.10 asyncio
|
||||
TimoutError = TimeoutError
|
||||
TimeoutError = (TimoutError, asyncio.exceptions.TimeoutError)
|
||||
class Globals:
|
||||
def __init__(G):
|
||||
G.uniqueClients = 0
|
||||
G.servers = {}
|
||||
G.clientsConnected = {}
|
||||
G.msgs = []
|
||||
G.remoteID = uname().node
|
||||
G.event = asyncio.Event()
|
||||
G.loop = asyncio.get_event_loop()
|
||||
G.interruptCount = 0
|
||||
G.killList = {}
|
||||
G.outboundLinks = []
|
||||
G.S2SLogs = []
|
||||
G.cwlgd = False
|
||||
G.NUL = "\x1e"
|
||||
dtime = dt.now(tz.utc)
|
||||
dtime.replace(tzinfo=tz.utc)
|
||||
time = dtime.strftime("%d-%m-%Y at %H:%M:%S UTC")
|
||||
G.IRCStats = {"users": {"localMax": 0, "localCurrent": 0, "globalMax": 0, "globalCurrent": 0}, "servers": 0, "bootTime": time}
|
||||
G.queue = []
|
||||
|
||||
|
||||
TimeoutErrors = (TimeoutError, asyncio.exceptions.TimeoutError)
|
||||
DisconnectErrors = (
|
||||
ConnectionResetError,
|
||||
BrokenPipeError,
|
||||
IndexError,
|
||||
UnicodeDecodeError,
|
||||
*TimeoutErrors,
|
||||
)
|
||||
G = Globals()
|
||||
G.uniqueClients = 0
|
||||
G.servers = {}
|
||||
G.clientsConnected = {}
|
||||
port = 65048
|
||||
G.msgs = []
|
||||
G.remoteID = uname().node
|
||||
G.event = asyncio.Event()
|
||||
G.loop = asyncio.get_event_loop()
|
||||
G.interruptCount = 0
|
||||
G.killList = {}
|
||||
G.outboundLinks = []
|
||||
G.S2SLogs = []
|
||||
G.cwlgd = False
|
||||
saveLogs = True
|
||||
address = "0.0.0.0"
|
||||
port = 65048
|
||||
address = "::"
|
||||
# Try to load a message log, if one exists
|
||||
try:
|
||||
G.msgs = __import__("cache").msgs
|
||||
|
@ -50,7 +66,7 @@ try:
|
|||
log("Explicitly erasing cached messages")
|
||||
G.msgs = []
|
||||
elif arg in ["-?", "-h", "--help"]:
|
||||
filename = filename if filename.startswith("./") else "python3 "+filename
|
||||
filename = filename if filename.startswith("./") else "python3 " + filename
|
||||
print(
|
||||
f"""{filename} <args>
|
||||
All arguments are optional!
|
||||
|
@ -65,6 +81,7 @@ Accepted arguments:
|
|||
--hostname=<string> - Sets the hostname for this server to use when talking to other servers. Defaults to the current system's hostname (limit of 16 chars)
|
||||
--address=<IP> - Sets the IP to listen on, defaults to all addresses (0.0.0.0)
|
||||
--cwlgd - Crashes the server when outbound links go down
|
||||
-r, --random-port - Randomizes the port to listen on
|
||||
|
||||
Examples:
|
||||
{filename} --hostname=Fun-chat --link=chat.example.com:65048 --port=92628
|
||||
|
@ -75,17 +92,20 @@ Examples:
|
|||
elif arg in ["-l", "--no-logs"]:
|
||||
log("Explicitly disabling saving of logs!")
|
||||
saveLogs = False
|
||||
elif arg.startswith("--link"):
|
||||
elif arg.startswith("--link="):
|
||||
G.outboundLinks.append((arg[7:].split(":")[0], int(arg.split(":")[1])))
|
||||
elif arg.startswith("--hostname"):
|
||||
elif arg.startswith("--hostname="):
|
||||
G.remoteID = arg[11:]
|
||||
if not G.remoteID or len(G.remoteID) > 16:
|
||||
raise ValueError
|
||||
elif arg.startswith("--address"):
|
||||
address = arg[9:]
|
||||
elif arg.startswith("--cwlgd"):
|
||||
elif arg.startswith("--address="):
|
||||
address = arg[10:]
|
||||
elif arg in ["--cwlgd"]:
|
||||
G.cwlgd = True
|
||||
log("Server will crasg when outbound links go down!", "WARN")
|
||||
log("Server will crash when outbound links go down!", "WARN")
|
||||
elif arg in ["-r", "--random-port"]:
|
||||
random.seed()
|
||||
port = random.randint(10000, 60000)
|
||||
else:
|
||||
log(f"Unrecognized argument {arg}!", "WARN")
|
||||
except Exception:
|
||||
|
@ -94,12 +114,31 @@ except Exception:
|
|||
|
||||
if not saveLogs:
|
||||
G.msgs.append(
|
||||
b"[00-00-0000 00:00:00] Notice: Logging is disabled on this server instance!\n"
|
||||
b"[00-00-0000 00:00:00] Notice: Logging is disabled on this server instance!\r\n"
|
||||
)
|
||||
if len(G.remoteID) > 16:
|
||||
G.remoteID = G.remoteID[:15]
|
||||
|
||||
|
||||
async def getMessage(reader, localQueue: list, size: int = 0, timeout: float = 0, sanitize: bool = False) -> tuple[str, list[str]]:
|
||||
if not localQueue:
|
||||
data = b""
|
||||
if timeout and timeout > 0:
|
||||
data = await asyncio.wait_for(reader.read(size), timeout)
|
||||
else:
|
||||
data = await reader.read(size)
|
||||
localQueue = data.decode("utf8").strip().split("\r\n")
|
||||
tmp = localQueue.pop(0)
|
||||
if sanitize:
|
||||
tmp = raw(tmp)
|
||||
if size and size > 0:
|
||||
other = tmp[size:]
|
||||
tmp = tmp[:size]
|
||||
if other:
|
||||
localQueue.insert(0, other)
|
||||
return tmp, localQueue
|
||||
|
||||
|
||||
def raw(string: str) -> str:
|
||||
s = string.strip()
|
||||
s = f"{s!r}"[1:-1].replace("\\\\", "\\")
|
||||
|
@ -118,33 +157,124 @@ def fmt(msg: str, name: str = "", action: bool = False) -> str:
|
|||
|
||||
async def handleClient(reader, writer):
|
||||
try:
|
||||
name = ""
|
||||
global G
|
||||
writer.write(b"Please identify yourself. Nick limit is 20 chars.\n")
|
||||
writer.write(b"Please identify yourself. Nick limit is 20 chars.\r\n")
|
||||
await writer.drain()
|
||||
name = raw((await reader.read(20)).decode("utf8"))
|
||||
name, localQueue = await getMessage(reader, [], 20, 0, True)
|
||||
#log(f"{localQueue}", "DEBUG")
|
||||
if len(name) > 20:
|
||||
name = name[
|
||||
:19
|
||||
] # Really this is only possible if someone passes raw unicode as a nick, but let's clean it up anyways.
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
reader.read(), 0.01
|
||||
) # Silently consume the excess username data
|
||||
except TimeoutError:
|
||||
pass
|
||||
if not name:
|
||||
writer.write(b"Nice try. Actually set a nick.\n")
|
||||
writer.write(b"Nice try. Actually set a nick.\r\n")
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
if name.lower() in G.clientsConnected:
|
||||
writer.write(f"Nick ({name}) in use\n".encode("utf8"))
|
||||
writer.write(f"Nick ({name}) in use\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
if not name.startswith("S2S-"):
|
||||
if name == "CAP LS 302":
|
||||
name = "Unknown IRC Client"
|
||||
writer.write(f":{G.remoteID} CAP * LS\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
nameFrag = ""
|
||||
if localQueue:
|
||||
nameFrag = localQueue[0]
|
||||
iname, localQueue = await getMessage(reader, [], 50, 0, True)
|
||||
iname = (nameFrag + iname).split(" ", 1)[1].lower()
|
||||
G.uniqueClients += 1
|
||||
G.clientsConnected[iname] = G.remoteID
|
||||
name = iname
|
||||
G.msgs.extend([log(f"{iname} has connected to the server.")])
|
||||
G.S2SLogs.append(("+", iname, G.remoteID))
|
||||
localQueue = [] # Discard "USER" data
|
||||
clientList = iname + ",".join(G.clientsConnected.keys())
|
||||
writer.write(f""":{G.remoteID} 001 {iname} :Welcome to the python-talk Network, {iname}\r
|
||||
:{G.remoteID} 002 {iname} :Your host is {G.remoteID}, running version 0.1\r
|
||||
:{G.remoteID} 003 {iname} :This server was created on {G.IRCStats["bootTime"]}\r
|
||||
:{G.remoteID} 004 {iname} python-talk 0.1 r t\r
|
||||
:{G.remoteID} 005 {iname} AWAYLEN=200,CASEMAPPING=ascii,CHANTYPES=#,ELIST=U,HOSTLEN=16 :are supported by this server\r
|
||||
:{G.remoteID} 005 {iname} CHANLIMIT=#:1,CHANMODES=b,k,l,t,CHANNELLEN=4,KICKLEN=1,MAXLIST=b:1 :are supported by this server\r
|
||||
:{G.remoteID} 005 {iname} MODES=4,NETWORK=talknet,NICKLEN=20,TOPICLEN=30,USERLEN=1 :are supported by this server\r
|
||||
:{G.remoteID} 251 {iname} :There are {G.IRCStats["users"]["globalCurrent"]} users and 0 invisible on {G.IRCStats["servers"]} servers\r
|
||||
:{G.remoteID} 252 {iname} 0 :operator(s) online\r
|
||||
:{G.remoteID} 253 {iname} 0 :unknown connection(s)\r
|
||||
:{G.remoteID} 254 {iname} 1 :channel formed\r
|
||||
:{G.remoteID} 255 {iname} :I have {G.IRCStats["users"]["globalCurrent"]} clients and {G.IRCStats["servers"]} servers\r
|
||||
:{G.remoteID} 265 {iname} [{G.IRCStats["users"]["localCurrent"]} {G.IRCStats["users"]["localMax"]}] :Current local users {G.IRCStats["users"]["localCurrent"]}, max {G.IRCStats["users"]["localMax"]}\r
|
||||
:{G.remoteID} 266 {iname} [{G.IRCStats["users"]["globalCurrent"]} {G.IRCStats["users"]["globalMax"]}] :Current global users {G.IRCStats["users"]["globalCurrent"]}, max {G.IRCStats["users"]["globalMax"]}\r
|
||||
:{G.remoteID} 422 {iname} :This server does not support MOTDs\r
|
||||
:{iname} JOIN #main\r
|
||||
:{G.remoteID} 324 {iname} #main t\r
|
||||
:{G.remoteID} 332 {iname} #main :Welcome to the main channel!\r
|
||||
:{G.remoteID} 353 {iname} = #main :{clientList}\r
|
||||
:{G.remoteID} 366 {iname} #main :End of /NAMES list\r\n""".encode("utf8"))
|
||||
await writer.drain()
|
||||
msgIndex = len(G.msgs)
|
||||
while 1:
|
||||
try:
|
||||
request, localQueue = await getMessage(reader, localQueue, 967, 0.1, False)
|
||||
request = request.replace(G.NUL, "\\x1e")
|
||||
response = None
|
||||
log(request, "DEBUG")
|
||||
cmd = request.split(" ")[0].lower()
|
||||
args = request.split(" ")[1:]
|
||||
if len(args) == 0:
|
||||
args = ["you-gave-me-an-invalid-command-why-would-you-do-this-to-me"]
|
||||
match cmd:
|
||||
case "ping":
|
||||
writer.write(f":{G.remoteID} PONG {G.remoteID} :{' '.join(args)}\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
case "join":
|
||||
if args[0].lower() == "#main":
|
||||
writer.write(f":{G.remoteID} 443 {iname} {iname} #main :You're already in #main, and you cannot leave\r\n".encode("utf-8"))
|
||||
else:
|
||||
writer.write(f":{G.remoteID} 405 {iname} {args[0]} :Only #main exists.\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
case "privmsg":
|
||||
if args[0].lower() == "#main":
|
||||
msg = " ".join(args[1:])
|
||||
if msg.startswith(":"):
|
||||
msg = msg[1:]
|
||||
if msg.startswith("\x01") and not msg.startswith("\x01ACTION"):
|
||||
writer.write(f":{G.remoteID} 404 {iname} {args[0]} :Unsupported CTCP\r\n".encode("utf-8"))
|
||||
else:
|
||||
writer.write(f":{G.remoteID} 404 {iname} {args[0]} :Channel does not exist\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
case "kill":
|
||||
users = G.clientsConnected.keys()
|
||||
if args[0] in users:
|
||||
writer.write(f":{G.remoteID} 481 {iname} :Permission Denied- There are no IRC operators here.\r\n".encode("utf-8"))
|
||||
elif args[0] == G.remoteID:
|
||||
writer.write(f":{G.remoteID} 483 {iname} :You can't kill me, I'm Skynet!\r\n".encode("utf-8"))
|
||||
else:
|
||||
writer.write(f":{G.remoteID} 401 {iname} :{args[0]}\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
case "part":
|
||||
if args[0].lower() == "#main":
|
||||
clientList = iname + ",".join(G.clientsConnected.keys())
|
||||
writer.write(f""":{iname} PART #main\r
|
||||
:{iname} JOIN #main\r
|
||||
:{G.remoteID} 324 {iname} #main t\r
|
||||
:{G.remoteID} 332 {iname} #main :Welcome to the main channel!\r
|
||||
:{G.remoteID} 353 {iname} = #main :{clientList}\r
|
||||
:{G.remoteID} 366 {iname} #main :End of /NAMES list\r\n""".encode("utf8"))
|
||||
else:
|
||||
writer.write(f":{G.remoteID} 404 {iname} {args[0]} :Channel does not exist\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
case _:
|
||||
writer.write(f":{G.remoteID} 421 {iname} {cmd} :That isn't supported here.\r\n".encode("utf-8"))
|
||||
await writer.drain()
|
||||
except TimeoutErrors:
|
||||
pass
|
||||
elif not name.startswith("S2S-"): # Normal Client logic
|
||||
localQueue = []
|
||||
G.clientsConnected[name.lower()] = G.remoteID
|
||||
msgIndex = 0
|
||||
G.uniqueClients += 1
|
||||
|
@ -152,8 +282,7 @@ async def handleClient(reader, writer):
|
|||
G.S2SLogs.append(("+", name, G.remoteID))
|
||||
while 1:
|
||||
try:
|
||||
buffer = await asyncio.wait_for(reader.read(967), 0.1)
|
||||
request = raw(buffer.decode("utf8"))
|
||||
request, localQueue = await getMessage(reader, localQueue, 967, 0.1, True)
|
||||
response = None
|
||||
if request.startswith("/mes "):
|
||||
response = log(f"* {name}'s {request[5:]}")
|
||||
|
@ -163,25 +292,25 @@ async def handleClient(reader, writer):
|
|||
G.S2SLogs.append(("A", (name, request[4:]), G.remoteID))
|
||||
elif request.startswith("/h"):
|
||||
writer.write(
|
||||
b"""Command List:
|
||||
/me <action> - Sends a special message so it looks like you did <action>
|
||||
/mes <action> - Same as /me, but adds a 's onto your nick
|
||||
/afk [reason] - Optional reason, short hand for `/me is afk [to [reason]]`
|
||||
/h, /help - Triggers this command listing
|
||||
/back - Shorthand for `/me is back`
|
||||
/stats - Sends you some server stats
|
||||
/quit - Disconnects you from the server\n"""
|
||||
b"""Command List:\r
|
||||
/me <action> - Sends a special message so it looks like you did <action>\r
|
||||
/mes <action> - Same as /me, but adds a 's onto your nick\r
|
||||
/afk [reason] - Optional reason, short hand for `/me is afk [to [reason]]`\r
|
||||
/h, /help - Triggers this command listing\r
|
||||
/back - Shorthand for `/me is back`\r
|
||||
/stat - Sends you some server stats\r
|
||||
/quit - Disconnects you from the server\r\n"""
|
||||
)
|
||||
await writer.drain()
|
||||
elif request.startswith("/stats"):
|
||||
elif request.startswith("/stat"):
|
||||
writer.write(
|
||||
f"""Server stats:
|
||||
Linked servers: {len(G.servers)}
|
||||
Connected clients: {G.uniqueClients}
|
||||
Total Clients: {len(G.clientsConnected)}
|
||||
Messages sent: {len(G.msgs)}
|
||||
|
||||
Please note that this is not network level statistics.\n""".encode(
|
||||
f"""Server stats:\r
|
||||
Linked servers: {len(G.servers)}\r
|
||||
Connected clients: {G.uniqueClients}\r
|
||||
Total Clients: {len(G.clientsConnected)}\r
|
||||
Messages sent: {len(G.msgs)}\r
|
||||
\r
|
||||
Please note that this is not network level statistics.\r\n""".encode(
|
||||
"utf8"
|
||||
)
|
||||
)
|
||||
|
@ -205,14 +334,14 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
G.S2SLogs.append(("M", (name, request), G.remoteID))
|
||||
if response:
|
||||
G.msgs.append(response)
|
||||
except TimeoutError:
|
||||
except TimeoutErrors:
|
||||
pass
|
||||
if msgIndex < len(G.msgs):
|
||||
writer.writelines(G.msgs[msgIndex:])
|
||||
await writer.drain()
|
||||
msgIndex = len(G.msgs)
|
||||
if name.lower() in G.killList and G.killList[name.lower()]:
|
||||
writer.write(b"Your client has been killed by the server\n")
|
||||
writer.write(b"Your client has been killed by the server\r\n")
|
||||
G.killList[name.lower()] = False
|
||||
break
|
||||
await writer.drain()
|
||||
|
@ -223,6 +352,7 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
del G.clientsConnected[name.lower()]
|
||||
G.S2SLogs.append(("-", name, G.remoteID))
|
||||
else: # This is... probably a server?
|
||||
localQueue = []
|
||||
sName = name[4:] # Trim off the S2S label
|
||||
if (
|
||||
G.servers.get(sName, False) != False
|
||||
|
@ -230,58 +360,57 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return # Server is already "linked", drop the connection
|
||||
if G.remoteID == sName: # Hey! you can't *also* be ***me***!
|
||||
if G.remoteID == sName or not sName: # Hey! you can't *also* be ***me***!
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return # drop "us"
|
||||
G.msgs.append(log(f"{sName} has linked to the network"))
|
||||
G.servers[sName] = {}
|
||||
msgIndex = 0
|
||||
writer.write(b"I am awaiting your client listing.\n")
|
||||
writer.write(b"I am awaiting your client listing.\r\n")
|
||||
while 1:
|
||||
client = raw((await reader.read(1024)).decode("utf8"))
|
||||
client, localQueue = await getMessage(reader, localQueue, 1024, 0, True)
|
||||
if client == f"END OF CLIENT LISTING FROM {sName}":
|
||||
break
|
||||
if (
|
||||
client.lower() in G.servers[sName]
|
||||
or client.lower() in G.clientsConnected
|
||||
):
|
||||
writer.write(b"K Client rejected: Already exists\n")
|
||||
writer.write(b"K Client rejected: Already exists\r\n")
|
||||
await writer.drain()
|
||||
continue
|
||||
writer.write(b"I added that client.\n")
|
||||
writer.write(b"I added that client.\r\n")
|
||||
await writer.drain()
|
||||
G.msgs.append(log(f"{client} has connected from {sName}"))
|
||||
G.servers[sName][client.lower()] = False
|
||||
G.S2SLogs.append(("+", client, sName))
|
||||
writer.write(f"{G.remoteID}\n".encode("utf8"))
|
||||
writer.write(f"{G.remoteID}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
await reader.read(1024)
|
||||
for client in G.clientsConnected:
|
||||
writer.write(f"{client}\n".encode("utf8"))
|
||||
writer.write(f"{client}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
resp = raw((await reader.read(1024)).decode("utf8"))
|
||||
resp, localQueue = await getMessage(reader, localQueue, 1024, 0, True)
|
||||
if resp.startswith("K"):
|
||||
if G.clientsConnected[client] == G.remoteID:
|
||||
G.killList[client] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[client]][client] = True
|
||||
writer.write(f"END OF CLIENT LISTING FROM {G.remoteID}\n".encode("utf8"))
|
||||
writer.write(f"END OF CLIENT LISTING FROM {G.remoteID}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
for client in G.servers[sName]:
|
||||
G.clientsConnected[client] = sName
|
||||
msgInd = len(G.S2SLogs)
|
||||
while 1:
|
||||
try:
|
||||
rawMsg = await asyncio.wait_for(reader.read(967), 0.1)
|
||||
buffer = raw(rawMsg.decode("utf8"))
|
||||
buffer, localQueue = await getMessage(reader, localQueue, 1024, 0.1, False)
|
||||
match buffer[0]:
|
||||
case "S": # Server notice
|
||||
G.msgs.extend([log(buffer[2:])])
|
||||
writer.write(b"I Mmm... Blueberries\n")
|
||||
case "I":
|
||||
writer.write(b"I Mmm... Blueberries\r\n")
|
||||
case "I": # Ignore lines, ususally responses to everything else
|
||||
pass
|
||||
case "+":
|
||||
case "+": # Add client lines
|
||||
cName = buffer[2:]
|
||||
if cName.lower() not in G.clientsConnected:
|
||||
G.msgs.append(
|
||||
|
@ -290,10 +419,10 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
G.servers[sName][cName.lower()] = False
|
||||
G.clientsConnected[cName.lower()] = sName
|
||||
G.S2SLogs.append(("+", cName, sName))
|
||||
writer.write(b"I Mmm... Pineapples\n")
|
||||
writer.write(b"I Mmm... Pineapples\r\n")
|
||||
else:
|
||||
writer.write(f"K {cName}\n".encode("utf8"))
|
||||
case "-":
|
||||
writer.write(f"K {cName}\r\n".encode("utf8"))
|
||||
case "-": # Remove client lines
|
||||
cName = buffer[2:]
|
||||
if G.clientsConnected.get(cName.lower(), None) == sName:
|
||||
G.msgs.append(
|
||||
|
@ -302,41 +431,43 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
del G.servers[sName][cName.lower()]
|
||||
del G.clientsConnected[cName.lower()]
|
||||
G.S2SLogs.append(("-", cName, sName))
|
||||
writer.write(b"I Mmm... Bananas\n")
|
||||
writer.write(b"I Mmm... Bananas\r\n")
|
||||
else:
|
||||
writer.write(
|
||||
f"S Your server is LYING about who is connected to it. - {G.remoteID}, a fellow server\n".encode(
|
||||
f"S Your server is LYING about who is connected to it. - {G.remoteID}, a fellow server\r\n".encode(
|
||||
"utf8"
|
||||
)
|
||||
)
|
||||
case "M":
|
||||
cName = buffer[2:].split("|", 1)[0]
|
||||
message = buffer[2:].split("|", 1)[1]
|
||||
) # Prevents servers from removing users they don't have, propogates in a fun way IIRC
|
||||
case "M": # Message lines, standard client stuff
|
||||
cName = buffer[2:].split(G.NUL, 1)[0]
|
||||
message = buffer[2:].split(G.NUL, 1)[1]
|
||||
G.msgs.append(log(f" {cName}: {message}"))
|
||||
G.S2SLogs.append(("M", (cName, message), sName))
|
||||
writer.write(
|
||||
b"I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace.\n"
|
||||
b"I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace.\r\n"
|
||||
)
|
||||
case "A":
|
||||
cName = buffer[2:].split("|", 1)[0]
|
||||
message = buffer[2:].split("|", 1)[1]
|
||||
case "A": # Action lines, standard client stuff
|
||||
cName = buffer[2:].split(G.NUL, 1)[0]
|
||||
message = buffer[2:].split(G.NUL, 1)[1]
|
||||
G.msgs.append(log(f"* {cName} {message}"))
|
||||
G.S2SLogs.append(("A", (cName, message), sName))
|
||||
writer.write(b"I Mmm... Strawberries\n")
|
||||
case "Q":
|
||||
writer.write(b"I Mmm... Strawberries\r\n")
|
||||
case "Q": # Quit lines
|
||||
break
|
||||
case "K":
|
||||
case "K": # Kill lines
|
||||
cName = buffer[2:]
|
||||
if G.clientsConnected[cName.lower()] == G.remoteID:
|
||||
if not G.clientsConnected.get(cName.lower(), False):
|
||||
pass # They don't exist, safe to ignore
|
||||
elif G.clientsConnected[cName.lower()] == G.remoteID:
|
||||
G.killList[cName.lower()] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[cName.lower()]][
|
||||
cName.lower()
|
||||
] = True
|
||||
writer.write(b"I Mmm... Blood\n")
|
||||
case _:
|
||||
writer.write(b"I Mmm... Blood\r\n")
|
||||
case _: # Everything we *don't* know how to handle
|
||||
writer.write(
|
||||
f"S Your server is doing drugs over here, sending me bullshit messages man - {G.remoteID}, A fellow server\n".encode(
|
||||
f"S Your server is doing drugs over here, sending me bullshit messages - {G.remoteID}, A fellow server\r\n".encode(
|
||||
"utf8"
|
||||
)
|
||||
)
|
||||
|
@ -345,12 +476,12 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
"WARN",
|
||||
)
|
||||
await writer.drain()
|
||||
except TimeoutError:
|
||||
except TimeoutErrors:
|
||||
pass
|
||||
if any(G.servers[sName].values()):
|
||||
for name in G.servers[sName]:
|
||||
if G.servers[sName][name]:
|
||||
writer.write(f"K {name}\n".encode("utf8"))
|
||||
writer.write(f"K {name}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
G.servers[sName][name] = False
|
||||
while msgInd < len(G.S2SLogs):
|
||||
|
@ -360,14 +491,14 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
match type:
|
||||
case "A":
|
||||
nick, msg = data
|
||||
writer.write(f"A {nick}|{msg}\n".encode("utf8"))
|
||||
writer.write(f"A {nick}{G.NUL}{msg}\r\n".encode("utf8"))
|
||||
case "M":
|
||||
nick, msg = data
|
||||
writer.write(f"M {nick}|{msg}\n".encode("utf8"))
|
||||
writer.write(f"M {nick}{G.NUL}{msg}\r\n".encode("utf8"))
|
||||
case "+":
|
||||
writer.write(f"+ {data}\n".encode("utf8"))
|
||||
writer.write(f"+ {data}\r\n".encode("utf8"))
|
||||
case "-":
|
||||
writer.write(f"- {data}\n".encode("utf8"))
|
||||
writer.write(f"- {data}\r\n".encode("utf8"))
|
||||
case _:
|
||||
pass
|
||||
await writer.drain()
|
||||
|
@ -381,11 +512,9 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
del G.clientsConnected[cName.lower()]
|
||||
del G.servers[sName]
|
||||
G.msgs.append(log(f"{sName} has de-linked from the network"))
|
||||
except (
|
||||
ConnectionResetError,
|
||||
BrokenPipeError,
|
||||
IndexError,
|
||||
): # Don't ask. IndexError needs to be caught here too.
|
||||
except DisconnectErrors:
|
||||
if not name: # pyright: ignore [reportPossiblyUnboundVariable]
|
||||
return
|
||||
if not name.startswith("S2S-"):
|
||||
G.uniqueClients -= 1
|
||||
G.msgs.append(log(f"{name} has disconnected from the server."))
|
||||
|
@ -401,178 +530,213 @@ Please note that this is not network level statistics.\n""".encode(
|
|||
pass
|
||||
del G.servers[name[4:]]
|
||||
G.msgs.append(log(f"{name[4:]} has de-linked from the network"))
|
||||
except Exception:
|
||||
Err = format_exc()
|
||||
for line in Err.split("\r\n"):
|
||||
log(line, "ERROR")
|
||||
|
||||
|
||||
async def connectServer(hostname: str, port: int):
|
||||
global G
|
||||
reader, writer = await asyncio.open_connection(hostname, port)
|
||||
await reader.read(1024)
|
||||
writer.write(f"S2S-{G.remoteID}\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
await reader.read(1024)
|
||||
for client in G.clientsConnected:
|
||||
writer.write(f"{client}\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
resp = raw((await reader.read(1024)).decode("utf8"))
|
||||
if resp.startswith("K"):
|
||||
if G.clientsConnected[client] == G.remoteID:
|
||||
G.killList[client] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[client]][client] = True
|
||||
writer.write(f"END OF CLIENT LISTING FROM {G.remoteID}\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
rID = raw((await reader.read(16)).decode("utf8"))
|
||||
try:
|
||||
await asyncio.wait_for(reader.read(1024), 0.1)
|
||||
except TimeoutError:
|
||||
pass
|
||||
if G.servers.get(rID, False) != False:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
if G.remoteID == rID:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
G.msgs.append(log(f"{rID} has linked to the network"))
|
||||
G.servers[rID] = {}
|
||||
writer.write(b"I recieved your remote ID, now awaiting client listing\n")
|
||||
await writer.drain()
|
||||
# recieve client list from the other server
|
||||
while 1:
|
||||
client = raw((await reader.read(1024)).decode("utf8"))
|
||||
if client == f"END OF CLIENT LISTING FROM {rID}":
|
||||
break
|
||||
if client.lower() in G.servers[rID] or client.lower() in G.clientsConnected:
|
||||
writer.write(b"K Client rejected: Already exists\n")
|
||||
reader, writer = await asyncio.open_connection(hostname, port)
|
||||
ext, localQueue = await getMessage(reader, [], 1024)
|
||||
writer.write(f"S2S-{G.remoteID}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
ext, localQueue = await getMessage(reader, [], 1024)
|
||||
for client in G.clientsConnected:
|
||||
writer.write(f"{client}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
continue
|
||||
writer.write(b"I added that client.\n")
|
||||
resp, localQueue = await getMessage(reader, localQueue, 1024, 0, True)
|
||||
if resp.startswith("K"):
|
||||
if G.clientsConnected[client] == G.remoteID:
|
||||
G.killList[client] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[client]][client] = True
|
||||
writer.write(f"END OF CLIENT LISTING FROM {G.remoteID}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
G.msgs.append(log(f"{client} has connected from {rID}"))
|
||||
G.servers[rID][client.lower()] = False
|
||||
for client in G.servers[rID]:
|
||||
G.clientsConnected[client] = rID
|
||||
msgInd = len(G.S2SLogs)
|
||||
try:
|
||||
rID = raw((await reader.read(16)).decode("utf8"))
|
||||
try:
|
||||
await asyncio.wait_for(reader.read(1024), 0.1)
|
||||
except TimeoutErrors:
|
||||
pass
|
||||
if G.servers.get(rID, False) != False:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
if G.remoteID == rID or not rID:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return
|
||||
G.msgs.append(log(f"{rID} has linked to the network"))
|
||||
G.servers[rID] = {}
|
||||
writer.write(b"I recieved your remote ID, now awaiting client listing\r\n")
|
||||
await writer.drain()
|
||||
# recieve client list from the other server
|
||||
while 1:
|
||||
try:
|
||||
rawMsg = await asyncio.wait_for(reader.read(967), 0.1)
|
||||
buffer = raw(rawMsg.decode("utf8"))
|
||||
match buffer[0]:
|
||||
case "S":
|
||||
G.msgs.extend([log(buffer[2:])])
|
||||
writer.write(b"I Mmm... Blueberries\n")
|
||||
case "I":
|
||||
pass
|
||||
case "+":
|
||||
cName = buffer[2:]
|
||||
if cName.lower() not in G.clientsConnected:
|
||||
G.msgs.append(log(f"{cName} has connected from {rID}"))
|
||||
G.S2SLogs.append(("+", cName, rID))
|
||||
G.servers[rID][cName.lower()] = False
|
||||
G.clientsConnected[cName.lower()] = rID
|
||||
writer.write(b"I Mmm... Pineapples\n")
|
||||
else:
|
||||
writer.write(f"K {cName}\n".encode("utf8"))
|
||||
case "-":
|
||||
cName = buffer[2:]
|
||||
if G.clientsConnected.get(cName.lower(), None) == rID:
|
||||
G.msgs.append(log(f"{cName} has disconnected from {rID}"))
|
||||
del G.servers[rID][cName.lower()]
|
||||
del G.clientsConnected[cName.lower()]
|
||||
G.S2SLogs.append(("-", cName, rID))
|
||||
else:
|
||||
client, localQueue = await getMessage(reader, localQueue, 1024, 0, True)
|
||||
if client == f"END OF CLIENT LISTING FROM {rID}":
|
||||
break
|
||||
if client.lower() in G.servers[rID] or client.lower() in G.clientsConnected:
|
||||
writer.write(b"K Client rejected: Already exists\r\n")
|
||||
await writer.drain()
|
||||
continue
|
||||
writer.write(b"I added that client.\r\n")
|
||||
await writer.drain()
|
||||
G.msgs.append(log(f"{client} has connected from {rID}"))
|
||||
G.servers[rID][client.lower()] = False
|
||||
for client in G.servers[rID]:
|
||||
G.clientsConnected[client] = rID
|
||||
msgInd = len(G.S2SLogs)
|
||||
try:
|
||||
while 1:
|
||||
try:
|
||||
buffer, localQueue = await getMessage(reader, localQueue, 1024, 0.1, False)
|
||||
match buffer[0]:
|
||||
case "S":
|
||||
G.msgs.extend([log(buffer[2:])])
|
||||
writer.write(b"I Mmm... Blueberries\r\n")
|
||||
case "I":
|
||||
pass
|
||||
case "+":
|
||||
cName = buffer[2:]
|
||||
if cName.lower() not in G.clientsConnected:
|
||||
G.msgs.append(log(f"{cName} has connected from {rID}"))
|
||||
G.S2SLogs.append(("+", cName, rID))
|
||||
G.servers[rID][cName.lower()] = False
|
||||
G.clientsConnected[cName.lower()] = rID
|
||||
writer.write(b"I Mmm... Pineapples\r\n")
|
||||
else:
|
||||
writer.write(f"K {cName}\r\n".encode("utf8"))
|
||||
case "-":
|
||||
cName = buffer[2:]
|
||||
if G.clientsConnected.get(cName.lower(), None) == rID:
|
||||
G.msgs.append(
|
||||
log(f"{cName} has disconnected from {rID}")
|
||||
)
|
||||
del G.servers[rID][cName.lower()]
|
||||
del G.clientsConnected[cName.lower()]
|
||||
G.S2SLogs.append(("-", cName, rID))
|
||||
else:
|
||||
writer.write(
|
||||
f"S Your server is LYING about who is connected to it. - {G.remoteID}, a fellow server\r\n".encode(
|
||||
"utf8"
|
||||
)
|
||||
)
|
||||
case "M":
|
||||
cName = buffer[2:].split(G.NUL, 1)[0]
|
||||
message = buffer[2:].split(G.NUL, 1)[1]
|
||||
G.msgs.append(log(f" {cName}: {message}"))
|
||||
G.S2SLogs.append(("M", (cName, message), rID))
|
||||
writer.write(
|
||||
f"S Your server is LYING about who is connected to it. - {G.remoteID}, a fellow server\n".encode(
|
||||
b"I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace.\r\n"
|
||||
)
|
||||
case "A":
|
||||
cName = buffer[2:].split(G.NUL, 1)[0]
|
||||
message = buffer[2:].split(G.NUL, 1)[1]
|
||||
G.S2SLogs.append(("A", (cName, message), rID))
|
||||
G.msgs.append(log(f"* {cName} {message}"))
|
||||
writer.write(b"I Mmm... Strawberries\r\n")
|
||||
case "Q":
|
||||
break
|
||||
case "K":
|
||||
cName = buffer[2:]
|
||||
if not G.clientsConnected.get(cName.lower(), False):
|
||||
pass # They don't exist, safe to ignore
|
||||
elif G.clientsConnected[cName.lower()] == G.remoteID:
|
||||
G.killList[cName.lower()] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[cName.lower()]][
|
||||
cName.lower()
|
||||
] = True
|
||||
writer.write(b"I Mmm... Blood\r\n")
|
||||
case _:
|
||||
writer.write(
|
||||
f"S Your server is doing drugs over here, sending me bullshit messages man - {G.remoteID}, A fellow server\r\n".encode(
|
||||
"utf8"
|
||||
)
|
||||
)
|
||||
case "M":
|
||||
cName = buffer[2:].split("|", 1)[0]
|
||||
message = buffer[2:].split("|", 1)[1]
|
||||
G.msgs.append(log(f" {cName}: {message}"))
|
||||
G.S2SLogs.append(("M", (cName, message), rID))
|
||||
writer.write(
|
||||
b"I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace.\n"
|
||||
)
|
||||
case "A":
|
||||
cName = buffer[2:].split("|", 1)[0]
|
||||
message = buffer[2:].split("|", 1)[1]
|
||||
G.S2SLogs.append(("A", (cName, message), rID))
|
||||
G.msgs.append(log(f"* {cName} {message}"))
|
||||
writer.write(b"I Mmm... Strawberries\n")
|
||||
case "Q":
|
||||
break
|
||||
case "K":
|
||||
cName = buffer[2:]
|
||||
if G.clientsConnected[cName.lower()] == G.remoteID:
|
||||
G.killList[cName.lower()] = True
|
||||
else:
|
||||
G.servers[G.clientsConnected[cName.lower()]][
|
||||
cName.lower()
|
||||
] = True
|
||||
writer.write(b"I Mmm... Blood\n")
|
||||
case _:
|
||||
writer.write(
|
||||
f"S Your server is doing drugs over here, sending me bullshit messages man - {G.remoteID}, A fellow server\n".encode(
|
||||
"utf8"
|
||||
log(
|
||||
f"Recieved invalid message ({buffer}) from {rID}",
|
||||
"WARN",
|
||||
)
|
||||
)
|
||||
log(f"Recieved invalid message ({buffer}) from {sName}", "WARN")
|
||||
await writer.drain()
|
||||
except TimeoutError:
|
||||
pass
|
||||
if any(G.servers[rID].values()):
|
||||
for name in G.servers[rID]:
|
||||
if G.servers[rID][name]:
|
||||
writer.write(f"K {name}\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
G.servers[rID][name] = False
|
||||
while msgInd < len(G.S2SLogs):
|
||||
type, data, server = G.S2SLogs[msgInd]
|
||||
if server != rID:
|
||||
match type:
|
||||
case "A":
|
||||
nick, msg = data
|
||||
writer.write(f"A {nick}|{msg}\n".encode("utf8"))
|
||||
case "M":
|
||||
nick, msg = data
|
||||
writer.write(f"M {nick}|{msg}\n".encode("utf8"))
|
||||
case "+":
|
||||
writer.write(f"+ {data}\n".encode("utf8"))
|
||||
case "-":
|
||||
writer.write(f"- {data}\n".encode("utf8"))
|
||||
case _:
|
||||
pass
|
||||
await writer.drain()
|
||||
msgInd += 1
|
||||
if G.cwlgd:
|
||||
raise LinksDownException
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
for cName in G.servers[rID]:
|
||||
G.msgs.append(log(f"{cName}'s server is going down"))
|
||||
del G.clientsConnected[cName.lower()]
|
||||
del G.servers[rID]
|
||||
G.msgs.append(log(f"{rID} has de-linked from the network"))
|
||||
except (ConnectionResetError, BrokenPipeError, IndexError):
|
||||
if G.cwlgd:
|
||||
raise LinksDownException
|
||||
for cName in G.servers[rID]:
|
||||
G.msgs.append(log(f"{cName}'s server is going down"))
|
||||
try:
|
||||
await writer.drain()
|
||||
except TimeoutErrors:
|
||||
pass
|
||||
if any(G.servers[rID].values()):
|
||||
for name in G.servers[rID]:
|
||||
if G.servers[rID][name]:
|
||||
writer.write(f"K {name}\r\n".encode("utf8"))
|
||||
await writer.drain()
|
||||
G.servers[rID][name] = False
|
||||
while msgInd < len(G.S2SLogs):
|
||||
type, data, server = G.S2SLogs[msgInd]
|
||||
if server != rID:
|
||||
match type:
|
||||
case "A":
|
||||
nick, msg = data
|
||||
writer.write(f"A {nick}{G.NUL}{msg}\r\n".encode("utf8"))
|
||||
case "M":
|
||||
nick, msg = data
|
||||
writer.write(f"M {nick}{G.NUL}{msg}\r\n".encode("utf8"))
|
||||
case "+":
|
||||
writer.write(f"+ {data}\r\n".encode("utf8"))
|
||||
case "-":
|
||||
writer.write(f"- {data}\r\n".encode("utf8"))
|
||||
case _:
|
||||
pass
|
||||
await writer.drain()
|
||||
msgInd += 1
|
||||
if G.cwlgd:
|
||||
raise LinkDownError
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
for cName in G.servers[rID]:
|
||||
G.msgs.append(log(f"{cName}'s server is going down"))
|
||||
del G.clientsConnected[cName.lower()]
|
||||
except Exception:
|
||||
pass
|
||||
del G.servers[rID]
|
||||
G.msgs.append(log(f"{rID} has de-linked from the network"))
|
||||
del G.servers[rID]
|
||||
G.msgs.append(log(f"{rID} has de-linked from the network"))
|
||||
except DisconnectErrors:
|
||||
if G.cwlgd:
|
||||
raise LinkDownError
|
||||
for cName in G.servers[rID]:
|
||||
G.msgs.append(log(f"{cName}'s server is going down"))
|
||||
try:
|
||||
del G.clientsConnected[cName.lower()]
|
||||
except Exception:
|
||||
pass
|
||||
del G.servers[rID]
|
||||
G.msgs.append(log(f"{rID} has de-linked from the network"))
|
||||
except OSError as E:
|
||||
log("OSError: " + str(E), "ERROR")
|
||||
if G.cwlgd:
|
||||
raise FailedLinkError
|
||||
except Exception:
|
||||
Err = format_exc()
|
||||
for line in Err.split("\r\n"):
|
||||
log(line, "ERROR")
|
||||
raise FailedLinkError
|
||||
|
||||
|
||||
async def runServer(address: str, port: int):
|
||||
global G
|
||||
server = await asyncio.start_server(handleClient, address, port)
|
||||
sock = None
|
||||
try:
|
||||
if ":" in address:
|
||||
INET = socket.AF_INET6
|
||||
else:
|
||||
INET = socket.AF_INET
|
||||
sock = socket.socket(INET, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Reuse socket
|
||||
sock.bind((address, port))
|
||||
except OSError as E:
|
||||
if E.errno != 97 or address != '::':
|
||||
raise E
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Reuse socket
|
||||
sock.bind(('0.0.0.0', port))
|
||||
server = await asyncio.start_server(handleClient, sock=sock)
|
||||
log(f"Listening on port {port}...")
|
||||
G.msgs.append(log("Server startup"))
|
||||
links = []
|
||||
|
@ -582,12 +746,17 @@ async def runServer(address: str, port: int):
|
|||
try:
|
||||
links.append(G.event.wait())
|
||||
await asyncio.gather(*links)
|
||||
except LinkDownError:
|
||||
G.msgs.append(log("Lost a server link, going down", "FATAL")[1:])
|
||||
crash = True
|
||||
except FailedLinkError:
|
||||
G.msgs.append(log("Failed to establish a server link, going down", "FATAL")[1:])
|
||||
except Exception:
|
||||
crash = True
|
||||
G.msgs.append(log("Server crash", "FATAL")[1:])
|
||||
log("Shutting down from Exception", "FATAL")
|
||||
Err = format_exc()
|
||||
for line in Err.split("\n"):
|
||||
for line in Err.split("\r\n"):
|
||||
log(line, "ERROR")
|
||||
finally:
|
||||
if not crash:
|
||||
|
@ -597,10 +766,11 @@ async def runServer(address: str, port: int):
|
|||
# server.abort_clients()
|
||||
if saveLogs:
|
||||
with open("cache.py", "w") as cache:
|
||||
cache.write(f"msgs = {G.msgs}\n")
|
||||
cache.write(f"msgs = {G.msgs}\r\n")
|
||||
log("Saved logs, exiting now.")
|
||||
else:
|
||||
log("Not saving logs, exiting now.")
|
||||
sock.close()
|
||||
|
||||
|
||||
class ServerInterruptException(KeyboardInterrupt): ...
|
||||
|
|
Loading…
Reference in a new issue