This file is indexed.

/usr/lib/python2.7/dist-packages/gplugs/tcp.py is in gozerbot 0.99.1-5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# plugs/tcp.py
#
#

""" allow incoming tcp connection for messaging """

__copyright__ = 'this file is in the public domain'

from gozerbot.fleet import fleet
from gozerbot.generic import rlog, handle_exception, strippedtxt, lockdec
from gozerbot.persist.persistconfig import PersistConfig
from gozerbot.config import config
from gozerbot.plughelp import plughelp
from gozerbot.partyline import partyline
from gozerbot.threads.thr import start_new_thread
from gozerbot.contrib.rijndael import rijndael
import socket, re, time, Queue

plughelp.add('tcp' , 'run the tcp listen thread')

cfg = PersistConfig()
cfg.define('tcp', 0) # set to 1 to enable
cfg.define('tcpparty', 0)
cfg.define('tcpipv6', 0)
cfg.define('tcpmasks', ['192.168*', ]) 
cfg.define('tcphost', "localhost")
cfg.define('tcpport', 5500)
cfg.define('tcpallow', ["127.0.0.1", ])
cfg.define('tcpallowednicks', ["#gozerbot", "dunker"])
cfg.define('tcppassword', "mekker", exposed=False)
cfg.define('tcpseed', "blablablablablaz", exposed=False) # needs to be 16 chars
cfg.define('tcpstrip', 1) # strip all chars < char(32)
cfg.define('tcpsleep', 0) # sleep in sendloop .. can be used to delay packet traffic
cfg.define('tdpdblog', 0)
cfg.define('tcpbot', 'default')

def _inmask(addr):
    """ check if addr matches a mask """
    if not cfg['tcpmasks']:
        return False
    for i in cfg['tcpmasks']:
        i = i.replace('*', '.*')
        if re.match(i, addr):
            return True

class Tcplistener(object):
    """ listen for tcp messages """

    def __init__(self):
        self.outqueue = Queue.Queue()
        self.queue = Queue.Queue()
        self.stop = 0
        if cfg['tcpipv6']:
            self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        else:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except:
            pass
        self.sock.setblocking(1)
        self.sock.settimeout(1)
        self.loggers = []

    def _outloop(self):
        rlog(5, 'tcp', 'starting outloop')
        while not self.stop:
            (printto, txt) = self.outqueue.get()
            if self.stop:
                return
            self.dosay(printto, txt)
        rlog(5, 'tcp', 'stopping outloop')

    def _handleloop(self):
        while not self.stop:
            (input, addr) = self.queue.get()
            if not input or not addr:
                continue
            if self.stop:
                break                
            self._handle(input, addr)
            if cfg['tcpsleep']:
                time.sleep(cfg['tcpsleep'] or 0.001)
        rlog(5, 'tcp', 'shutting down tcplistener')

    def _listen(self):
        """ listen for tcp messages .. /msg via bot"""
        if not cfg['tcp']:
            return
        try:
            fleet.startok.wait()
            bot = fleet.byname(cfg['tcpbot'] or 'default')
            if not bot:
                rlog(10, 'tcp', "can't find main bot .. not starting")
                return
            # get listen socket on host were running on
            self.sock.bind((cfg['tcphost'], cfg['tcpport']))
            self.sock.listen(1)
            rlog(10, 'tcp', 'tcp listening on %s %s' % (cfg['tcphost'], \
cfg['tcpport']))
            self.stop = 0
        except IOError:
            handle_exception()
            self.sock = None
            self.stop = 1
            return
        # loop on listening tcp socket
        bot.connectok.wait()
        while not self.stop:
            try:
                (sock, addr) = self.sock.accept()
                rlog(10, 'tcp', 'connection from %s' % str(addr))
            except socket.timeout:
                continue
            except Exception, ex:
                if 'Invalid argument' in str(ex):
                    continue
                handle_exception()
                break
            if cfg['tcp'] and (addr[0] in cfg['tcpallow'] or \
_inmask(addr[0])):
                start_new_thread(self.handlesocket, (sock, addr))

    def handlesocket(self, sock, addr):
        while 1:
            time.sleep(0.001)
            try:
                input = sock.recv(4096)
                if not input:
                    return
            except socket.timeout:
                continue
            except Exception, ex:
                try:
                    (errno, errstr) = ex
                except ValueError:
                    errno = 0
                    errstr = str(ex)
                if errno == 4:
                    rlog(10, self.name, str(ex))
                    break
                if errno == 35:
                    continue
                else:
                    handle_exception()
                    break
            if self.stop:
                break
            self.queue.put((input, addr))
        rlog(5, 'tcp', 'shutting down main loop')

    def _handle(self, input, addr):
        if cfg['tcpseed']:
            data = ""
            for i in range(len(input)/16):
                try:
                    data += crypt.decrypt(input[i*16:i*16+16])
                except Exception, ex:
                    rlog(10, 'tcp', "can't decrypt: %s" % str(ex))
                    data = input
                    break
        else:
            data = input
        if cfg['tcpstrip']:
            data = strippedtxt(data)
        # check if tcp is enabled and source ip is in tcpallow list
        if cfg['tcp'] and (addr[0] in cfg['tcpallow'] or \
_inmask(addr[0])):
            # get printto and passwd data
            header = re.search('(\S+) (\S+) (.*)', data)
            if header:
                # check password
                if header.group(1) == cfg['tcppassword']:
                    printto = header.group(2)    # is the nick/channel
                    # check if printto is in allowednicks
                    if not printto in cfg['tcpallowednicks']:
                        rlog(10, 'tcp', "tcp denied %s" % printto )
                        return
                    rlog(0, 'tcp', str(addr[0]) +  " tcp allowed")
                    text = header.group(3)    # is the text
                    self.say(printto, text)
                else:
                    rlog(10, 'tcp', "can't match tcppasswd from " + \
str(addr))
            else:
                rlog(10, 'tcp', "can't match tcp from " + str(addr[0]))
        else:
            rlog(10, 'tcp', 'denied tcp from ' + str(addr[0]))

    def say(self, printto, txt):
        self.outqueue.put((printto, txt))

    def dosay(self, printto, txt):
        if cfg['tcpparty'] and partyline.is_on(printto):
            partyline.say_nick(printto, txt)
            return
        bot = fleet.getmainbot()
        if not bot.jabber and not bot.cfg['nolimiter']:
            time.sleep(3)
        bot.say(printto, txt)
        for i in self.loggers:
            i.log(printto, txt)

if cfg['tcp']:
    tcplistener = Tcplistener()

if cfg['tcp'] and cfg['tcpseed']:
    crypt = rijndael(cfg['tcpseed'])

def init():
    """ init the plugin """
    if cfg['tcp']:
        start_new_thread(tcplistener._listen, ())
        start_new_thread(tcplistener._handleloop, ())
        start_new_thread(tcplistener._outloop, ())
    return 1
    
def shutdown():
    """ shutdown the plugin """
    if cfg['tcp']:
        tcplistener.sock.close()
        tcplistener.stop = 1
        tcplistener.outqueue.put_nowait((None, None))
        tcplistener.queue.put_nowait((None, None))
        time.sleep(2)
    return 1

if cfg['tcp'] and cfg['tcpdblog']:

    from gozerbot.database.db import db

    class Tcpdblog:

        """ log tcp data to database """

        # see tables/tcplog for table definition and add tcpdblog = 1 to 
        # the config file

        def log(self, printto, txt):
            """ do the actual logging """
            try:
                res = db.execute("""INSERT into tcplog(time,printto,txt)
values(%s,%s,%s) """, (time.time(), printto, txt))
            except Exception, ex:
                rlog(10, 'tcp', 'failed to log to db: %s' % str(ex))
            return res

    tcplistener.loggers.append(Udpdblog())
    rlog(10, 'tcp', 'registered database tcp logger')