summaryrefslogtreecommitdiffstats
path: root/plugin.py
blob: ea537df06d63ffb6d3b2fe33b6b580f6e2fef24a (plain)
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
###
# Copyright (c) 2021, mogad0n
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

###

# My Imports



from supybot import utils, plugins, ircutils, callbacks, irclib, ircmsgs,
from supybot import conf, world, log, ircdb, registry, schedule
from supybot.commands import *
try:
    from supybot.i18n import PluginInternationalization
    _ = PluginInternationalization('EgoServ')
except ImportError:
    # Placeholder that allows to run the plugin on a bot
    # without the i18n module
    _ = lambda x: x


# import pickle
# import sys

# filename = conf.supybot.directories.data.dirize("EgoServ.db")

# Perms Decorator
def ensure_permissions(min_permission_group):
    "Ensures user belongs to a least permission group"
    def decorator(function):
        def wrapper(*args,**kwargs):
            print(args) 
            print(kwargs)
            return function(*args, **kwargs) 
        return wrapper
    return decorator

# Taken from plugins.Time.seconds
def getTs(irc, msg, args, state):
    """[<years>y] [<weeks>w] [<days>d] [<hours>h] [<minutes>m] [<seconds>s]
    Returns the number of seconds in the number of <years>, <weeks>,
    <days>, <hours>, <minutes>, and <seconds> given.  An example usage is
    "seconds 2h 30m", which would return 9000, which is '3600*2 + 30*60'.
    Useful for scheduling events at a given number of seconds in the
    future.
    """
    # here there is some glitch / ugly hack to allow any('getTs'), with rest('test') after...
    # TODO: check that bot can't kill itself with loop
    seconds = -1
    items = list(args)
    for arg in items:
        if not (arg and arg[-1] in 'ywdhms'):
            try:
                n = int(arg)
                state.args.append(n)
            except:
                state.args.append(float(seconds))
                raise callbacks.ArgumentError
        (s, kind) = arg[:-1], arg[-1]
        try:
            i = int(s)
        except ValueError:
            state.args.append(float(seconds))
            raise callbacks.ArgumentError
        if kind == 'y':
            seconds += i*31536000
        elif kind == 'w':
            seconds += i*604800
        elif kind == 'd':
            seconds += i*86400
        elif kind == 'h':
            seconds += i*3600
        elif kind == 'm':
            seconds += i*60
        elif kind == 's':
            if i == 0:
                i = 1
            seconds += i
        elif kind == '-':
            state.args.append(float(seconds))
            raise callbacks.ArgumentError
        args.pop(0)
    state.args.append(float(seconds))


addConverter('getTs', getTs)



class EgoServ(callbacks.Plugin):
    """Suite of tools to help Network Operators run their ErgoIRCd nets"""
    threaded = True

    # OPER
    # This should check if it has OPER right away
    
    # PERMS
    # This is designed to be a single network ErgoIRCd administrative bot
    # So maybe I just set default perms to owner!

    #####
    # WHO
    #####

    # Listen for 354; when recieved send payload for various queries
    # and internal functions below

    # _isAccount()

    # IP address from `ircmsgs.who()`
    # @wrap(['nick'])
    # def getip(self, irc, msg, args, nick):
    #     """<nick>
        
    #     returns current IP address of a nick
    #     """

    ######
    # OPER Commands
    ######

    # DEFCON

    @wrap([("literal", (1, 2, 3, 4, 5))])
    def defcon(self, irc, msg, args, level):
        """<level>
        
        The DEFCON system can disable server features at runtime, to mitigate
        spam or other hostile activity. It has five levels, which are cumulative

        5: Normal operation
        4: No new account or channel registrations; if Tor is enabled, no new
            unauthenticated connections from Tor
        3: All users are +R; no changes to vhosts
        2: No new unauthenticated connections; all channels are +R
        1: No new connections except from localhost or other trusted IPs
        """

        arg = []
        arg.append(level)
        irc.sendMsg(msg=ircmsgs.IrcMsg(command='DEFCON', args=arg))
        irc.replySuccess(f'Setting DEFCON level to {arg}! Good Luck!')

        
    # KILL
    @ensure_permissions(5)
    @wrap(['nick', optional('something')])
    def kill(self, irc, msg, args, nick, reason):
        """<nick> [<reason>]

        Issues a KILL command on the <nick> with <reason> if provided.
        """
        arg = [nick]
        if reason:
            arg.append(reason)
        irc.queueMsg(msg=ircmsgs.IrcMsg(command='KILL',
                    args=arg))
        irc.replySuccess(f'Killed connection for {nick}')

    # SAJOIN
    @wrap([getopts({'nick': 'nick'}), 'channel'])
    def sajoin(self, irc, msg, args, opts, channel):
        """[--nick <nick>] [<channel>]

        Forcibly joins a <nick> to a <channel>, ignoring restrictions like bans, user limits
        and channel keys. If <nick> is omitted, it defaults to the bot itself.
        <channel> is only necessary if the message is not sent on the channel itself
        """
        opts = dict(opts)
        arg = []
        if 'nick' in opts:
            arg.append(opts['nick'])
        arg.append(channel)
        irc.queueMsg(msg=ircmsgs.IrcMsg(command='SAJOIN',
                            args=arg))
        if 'nick' in opts:
            re = f"attempting to force join {opts['nick']} to {channel}"
        else:
            re = f'I am attempting to forcibly join {channel}'
        irc.reply(re)

    # SANICK
    @wrap(['nick', 'something'])
    def sanick(self, irc, msg, args, current, new):
        """<current> <new>

        Issues a SANICK command and forcibly changes the <current> nick to the <new> nick
        """
        arg = [current, new]
        irc.queueMsg(msg=ircmsgs.IrcMsg(command='SANICK',
                            args=arg))
        # This isn't handling any nick collision errors
        irc.reply(f'Forcing nick change for {current} to {new}')

    #####
    # NickServ
    # Nick and Account Administration
    #####

    # Figure out some clean way to start talking to
    # and parsing information from NS. For eg NS CLIENTS LIST



    ######
    # Channel Administration
    ######

    def _ban(self, irc, msg, args,
            channel, optlist, target, getTs, reason, kick):
        # Check that they're not trying to make us kickban ourself.
        if irc.isNick(target):
            bannedNick = target
            try:
                bannedHostmask = irc.state.nickToHostmask(target)
                banmaskstyle = conf.supybot.protocols.irc.banmask
                banmask = banmaskstyle.makeBanmask(bannedHostmask, [o[0] for o in optlist])
            except KeyError:
                ## WTF IS THIS
                if not conf.supybot.protocols.irc.strictRfc() and \
                        target.startswith('$'):
                    # Select the last part, or the whole target:
                    bannedNick = target.split(':')[-1]
                    banmask = bannedHostmask = target
                else:
                    irc.error(format(_('I haven\'t seen %s.'), bannedNick), Raise=True)
        else:
            bannedNick = ircutils.nickFromHostmask(target)
            banmask = bannedHostmask = target
        if not irc.isNick(bannedNick):
            self.log.warning('%q tried to kban a non nick: %q',
                             msg.prefix, bannedNick)
            raise callbacks.ArgumentError
        elif bannedNick == irc.nick:
            self.log.warning('%q tried to make me kban myself.', msg.prefix)
            irc.error(_('I cowardly refuse to kickban myself.'))
            return
        if not reason:
            reason = msg.nick
        
        capability = ircdb.makeChannelCapability(channel, 'op')
        # Check (again) that they're not trying to make us kickban ourself.
        if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
            if ircutils.hostmaskPatternEqual(bannedHostmask, irc.prefix):
                self.log.warning('%q tried to make me kban myself.',msg.prefix)
                irc.error(_('I cowardly refuse to ban myself.'))
                return
            else:
                self.log.warning('Using exact hostmask since banmask would '
                                 'ban myself.')
                banmask = bannedHostmask
        # Now, let's actually get to it.  Check to make sure they have
        # #channel,op and the bannee doesn't have #channel,op; or that the
        # bannee and the banner are both the same person.
        def doBan():
            if irc.state.channels[channel].isOp(bannedNick):
                irc.queueMsg(ircmsgs.deop(channel, bannedNick))
            irc.queueMsg(ircmsgs.ban(channel, banmask))
            if kick:
                irc.queueMsg(ircmsgs.kick(channel, bannedNick, reason))
            if getTs > 0:
                def f():
                    if channel in irc.state.channels and \
                       banmask in irc.state.channels[channel].bans:
                        irc.queueMsg(ircmsgs.unban(channel, banmask))
                schedule.addEvent(f, )
        if bannedNick == msg.nick:
            doBan()
        elif ircdb.checkCapability(msg.prefix, capability):
            if ircdb.checkCapability(bannedHostmask, capability) and \
                    not ircdb.checkCapability(msg.prefix, 'owner'):
                self.log.warning('%s tried to ban %q, but both have %s',
                                 msg.prefix, bannedHostmask, capability)
                irc.error(format(_('%s has %s too, you can\'t ban '
                                 'them.'), bannedNick, capability))
            else:
                doBan()
        else:
            self.log.warning('%q attempted kban without %s',
                             msg.prefix, capability)
            irc.errorNoCapability(capability)

    def nban(self, irc, msg, args,
            bannedNick, getTs, reason):
        """ <nick> [<seconds>] [<reason>]
        If you have the #channel,op capability, this will kickban <nick>'s banmask from
        for 
        the time period specified. Not specifying the time period it will ban the user
        indefinitely. <reason> is optional but recommended.
        """
        self._ban(irc, msg, args, bannedNick, reason, True)
    nban = wrap(nban,
                ['haveOp',
                 
                 ('haveHalfop+', _('kick or ban someone')),
                 'nickInChannel',
                 optional('', 0),
                 additional('text')])




    @wrap