-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
274 lines (220 loc) · 8.6 KB
/
plugin.py
File metadata and controls
274 lines (220 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
###
# Copyright (c) 2026, Barry KW Suridge
# All rights reserved.
#
#
###
from supybot import callbacks, ircmsgs, ircutils, log, world
from supybot.commands import *
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization("LocalControl")
import os
import socket
import threading
import time
import itertools
class LocalControl(callbacks.Plugin):
"""Provides a local-only UNIX socket for issuing bot commands."""
threaded = True
_req_counter = itertools.count(1)
def __init__(self, irc):
self.__parent = super(LocalControl, self)
self.__parent.__init__(irc)
self._dispatch_lock = threading.Lock()
plugin_dir = os.path.dirname(__file__)
self.socket_path = os.path.join(plugin_dir, ".localcontrol.sock")
# Remove stale socket
try:
os.unlink(self.socket_path)
except FileNotFoundError:
pass
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.server.bind(self.socket_path)
self.server.listen(1)
self.server.settimeout(1.0)
threading.Thread(target=self._accept_loop, daemon=True).start()
def die(self):
try:
self.server.close()
except Exception:
pass
try:
os.unlink(self.socket_path)
except OSError:
pass
self.__parent.die()
# -----------------------------------------------------------------------------
def _accept_loop(self):
while True:
try:
conn, _ = self.server.accept()
except socket.timeout:
if world.dying:
return
continue
except OSError:
if world.dying:
return
raise
threading.Thread(
target=self._handle_client, args=(conn,), daemon=True
).start()
# ----------------------------------------------------------------------
def _handle_client(self, conn):
req_id = next(self._req_counter)
started = time.perf_counter()
raw_data = ""
try:
# Read the incoming command (single line)
raw_data = conn.recv(4096).decode("utf-8")
data = raw_data.strip()
if not data:
conn.sendall(b"(no reply)\n")
self._log_socket_request(
req_id, raw_data, "empty", replies=0, started=started
)
return
parts = data.split()
command = parts[0]
args = parts[1:]
# Capture outgoing messages
replies = []
synthetic_nick = f"LocalControl{req_id}"
reply_target = synthetic_nick
# synthetic_prefix = "Barry!Barry@hello.at.bazzas.club"
synthetic_prefix = (
f"LocalControl{req_id}!local{req_id}@localcontrol.invalid"
)
# Monkeypatch sendMsg/queueMsg to capture replies
irc = world.ircs[0]
old_send = irc.sendMsg
old_queue = irc.queueMsg
def capture(msg):
# Tag outgoing messages so Limnoria treats them as owner-authenticated
msg.tag("identified", True)
msg.tag("authenticated", True)
msg.tag("account", "owner")
msg.tag("capability", "owner")
# Capture PRIVMSG/NOTICE replies addressed to our synthetic nick
if msg.command in ("PRIVMSG", "NOTICE") and len(msg.args) >= 2:
if ircutils.strEqual(msg.args[0], reply_target):
replies.append(msg.args[1])
return True
return False
def send_cb(msg):
if not capture(msg):
old_send(msg)
def queue_cb(msg):
if not capture(msg):
old_queue(msg)
irc.sendMsg = send_cb
irc.queueMsg = queue_cb
try:
# Dispatch the command
self._dispatch(irc, command, args, synthetic_prefix)
finally:
# Restore original methods
irc.sendMsg = old_send
irc.queueMsg = old_queue
# Build reply text
if replies:
reply_text = "\n".join(replies) + "\n"
else:
reply_text = "(no reply)\n"
conn.sendall(reply_text.encode("utf-8"))
# Log the request
self._log_socket_request(
req_id, raw_data, reply_text, replies=len(replies), started=started
)
except Exception as e:
err = f"Error: {e}\n"
conn.sendall(err.encode("utf-8"))
self._log_socket_request(req_id, raw_data, err, replies=0, started=started)
finally:
conn.close()
def _log_socket_request(
self, req_id, command, status, replies, started, error=None
):
if not self.registryValue("socketRequestLogging"):
return
duration_ms = (time.perf_counter() - started) * 1000.0
cmd = " ".join(command.split())[:200] if command else ""
line = 'LocalControl: socket req=%s status=%s replies=%s ms=%.1f cmd="%s"' % (
req_id,
status,
replies,
duration_ms,
cmd,
)
if error:
err = " ".join(error.split())[:200]
line += ' error="%s"' % err
log.info(line)
# ----------------------------------------------------------------------
def _getIrc(self):
# In Limnoria, active IRC connections are tracked in world.ircs.
# Prefer a bound irc instance if present, otherwise use the first live one.
if hasattr(self, "irc") and self.irc is not None: # type: ignore[attr-defined]
return self.irc # type: ignore[attr-defined]
if getattr(world, "ircs", None):
return world.ircs[0]
raise RuntimeError("No IRC object is available for LocalControl")
# ----------------------------------------------------------------------
def _dispatch(self, baseIrc, command, args, synthetic_prefix):
# Build the payload exactly as a user would type it
payload = " ".join([command] + args)
# Construct the synthetic PRIVMSG that delivers the command to the bot
msg = ircmsgs.privmsg(baseIrc.nick, payload, prefix=synthetic_prefix)
# Mark the synthetic user as authenticated/owner so Limnoria trusts it
msg.tag("identified", True)
msg.tag("authenticated", True)
msg.tag("account", "owner") # type: ignore[arg-type]
msg.tag("capability", "owner") # type: ignore[arg-type]
# Feed the message into Limnoria's parser
baseIrc.feedMsg(msg)
# ----------------------------------------------------------------------
def sysinfo(self, irc, msg, args):
"""sysinfo
Show basic bot and system information.
"""
import platform
import sys
import supybot.version as v
bot_nick = irc.nick
limnoria_version = v.version
python_version = sys.version.split()[0]
os_name = platform.system()
os_release = platform.release()
kernel = platform.version()
arch = platform.machine()
summary = (
f"Bot: {bot_nick} | "
f"Python: {python_version} | "
f"Limnoria: {limnoria_version} | "
f"OS: {os_name} {os_release} | "
f"Kernel: {kernel} | "
f"Arch: {arch}"
)
irc.reply(summary)
# ----------------------------------------------------------------------
@wrap(["channel", "text"])
def say(self, irc, msg, args, channel, text):
"""say <channel> <text>
Sends a message to a channel.
"""
out = ircmsgs.privmsg(channel, text)
# Tag outgoing message as owner so Limnoria does not rewrite or block it
out.tag("identified", True)
out.tag("authenticated", True)
out.tag("account", "owner") # type: ignore[arg-type]
# Queue the message for actual network send
irc.queueMsg(out)
# Acknowledge the command
irc.replySuccess()
# ----------------------------------------------------------------------
@wrap([])
def info(self, irc, msg, args):
"""Shows information about the LocalControl plugin."""
irc.reply("LocalControl provides a UNIX socket for local command execution.")
Class = LocalControl
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: