-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinit
executable file
·254 lines (217 loc) · 7.3 KB
/
init
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
#!/usr/bin/env python3
import configparser
import html
import logging
import os
import path
import re
import shlex
import subprocess
import sys
import glob
import getpass
import asyncio
from nio import AsyncClient, ClientConfig, InviteEvent, RoomMessageText, SyncError
from slack import RTMClient
from slack.errors import SlackApiError
def is_ignored(username):
try:
with open('etc/ignore', 'r') as f:
for line in f:
if line.rstrip() == username:
return True
except OSError:
pass
return False
def sanitize_path(path):
return path.replace('/', '')
def commands(tokens):
argv = []
for token in tokens:
if token.literal() == '|':
yield argv
argv = []
else:
argv.append(token)
if argv:
yield argv
def run(commandline, env):
try:
tokens = shlex.split(commandline)
except ValueError as e:
return (255, '', str(e))
processes = []
for i, argv in enumerate(commands(tokens)):
log.info('argv:{}'.format(argv))
if i > MAXPIPES:
return (255, '', 'exceeded maximum number of pipes ({})'.format(MAXPIPES))
if i == 0:
stdin = subprocess.DEVNULL
else:
stdin = processes[i - 1].stdout
redir_at = None
for i, token in enumerate(reversed(argv)):
if token.literal() == '>>':
redir_at = i
break
if redir_at != None:
j = len(argv) - redir_at - 1
argv.pop(j)
try:
chan_path = path.chan_path(env['CHAN'], argv.pop(j))
stdout = open(chan_path, 'a+')
except IndexError:
return (255, '', 'bad redirect')
except OSError as e:
return (e.errno, '', str(e))
else:
stdout = subprocess.PIPE
if len(argv) > 0:
bin_path = os.path.join('bin', sanitize_path(argv[0]))
else:
bin_path = ''
if os.path.isfile(bin_path):
argv[0] = bin_path
else:
argv.insert(0, 'bin/rand')
try:
processes.append(subprocess.Popen(argv,
stdin=stdin,
stdout=stdout,
stderr=subprocess.PIPE,
env=env))
except PermissionError:
pass
except FileNotFoundError as e:
return (e.errno, '', str(e))
if stdout != subprocess.PIPE:
stdout.close()
try:
(stdout, stderr) = processes[-1].communicate(timeout=TIMEOUT)
# The pipeline status is the && of every process, i.e. pipefail is
# always enabled. Don't bother preserving the exact status when there
# is no second process.
status = 0
for process in processes:
if process.wait():
status = 1
except subprocess.TimeoutExpired:
processes[-1].kill()
_ = processes[-1].communicate()
return (255, '', 'timed out after {} seconds'.format(TIMEOUT))
if stdout:
stdout = stdout.decode('utf-8')
else:
stdout = ''
return (status, stdout, stderr.decode('utf-8'))
def ensure_dir(d):
try:
os.mkdir(d)
except OSError:
pass
def handle_message(nick, channel, msg):
if is_ignored(nick):
return
env = { 'NICK': nick, 'CHAN': channel, 'PATH': os.environ['PATH'] , 'PYTHONPATH': '.', 'HOME': '/root' }
ensure_dir(path.chan_path(channel, ''))
for f in glob.glob('lib/filter/*'):
argv = [f, msg]
try:
subprocess.Popen(argv, env=env).communicate()
except PermissionError:
pass
if msg.startswith(LEADER):
commandline = msg[len(LEADER):]
status, stdout, stderr = run(commandline, env)
with open('var/status', 'w') as f:
f.write('{}\n'.format(status))
log.info('command:{} status:{} stdout:{} stderr:{}'.format(repr(commandline), status, repr(stdout), repr(stderr)))
stdout = stdout.rstrip()
stderr = stderr.rstrip()
response = stdout
if stdout and stderr:
response += "\n"
response += stderr
return response
return None
# Matrix callbacks
async def room_message_text_callback(room, event):
log.info("message:{}".format(event))
nick = event.sender
if is_ignored(nick):
return
channel = room.room_id
msg = event.body
response = handle_message(nick, channel, msg)
if response:
fmt = '<pre><code>{}</code></pre>' if '\n' in response else '<code>{}</code>'
content = {
"body": response,
"msgtype": "m.text",
"format": "org.matrix.custom.html",
"formatted_body": fmt.format(html.escape(response)),
}
await client.room_send(room_id=room.room_id, message_type="m.room.message", content=content)
async def invite_callback(source, sender):
log.info("invite:{}".format(source.room_id))
await client.join(source.room_id)
async def login_and_sync_forever():
await client.login(PASSWORD)
# This extra sync is a hack to avoid seeing every event since our
# (currently non-existent) saved sync token. We aren't even bothering with
# saving a sync_token yet because it requires e2e (not sure why) and there
# is no olm-dev package in our version of alpine (there is one in edge).
await client.sync(30000)
client.add_event_callback(room_message_text_callback, RoomMessageText)
client.add_event_callback(invite_callback, InviteEvent)
await client.sync_forever(30000)
# Slack callbacks
@RTMClient.run_on(event='message')
def run_on_message(**payload):
try:
data = payload['data']
web_client = payload['web_client']
if 'text' in data:
user = data['user']
channel = data['channel']
text = html.unescape(data.get('text', []))
thread_ts = data['ts']
response = handle_message(user, channel, text)
if response:
web_client.chat_postMessage(
channel=channel,
text=response,
thread_ts=thread_ts
)
except SlackApiError as e:
log.error(f"Got an error: {e.response['error']}")
except Exception as e:
log.error(f"{e}")
# Globals and other ugly, stateful stuff
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler(sys.stderr))
log.setLevel(logging.DEBUG)
ensure_dir('var')
ensure_dir('var/root')
config = configparser.ConfigParser()
config.read('etc/irsh.ini')
config = config['irsh']
KIND = config['kind']
LEADER = config['leader']
MAXPIPES = int(config['maxpipes'])
TIMEOUT = int(config['timeout'])
if KIND == 'matrix':
URL = config['url']
USERNAME = config['username']
if 'password' in config:
log.warning('using plaintext password from config file')
PASSWORD = config['password']
else:
PASSWORD = getpass.getpass()
client = AsyncClient(URL, USERNAME)
asyncio.run(login_and_sync_forever())
elif KIND == 'slack':
TOKEN=config['token']
RTMClient(token=TOKEN).start()
else:
log.exception('unknown kind in config file')