Paste number 140467: ref

Paste number 140467: ref
Pasted by: kurin
When:7 months, 2 weeks ago
Share:Tweet this! | http://paste.lisp.org/+30DV
Channel:None
Paste contents:
Raw Source | XML | Display As
#!/usr/bin/env python

import sys, os
import socket
import threading

import dns.resolver as resolver

class ShovelBytes(threading.Thread):
    def __init__(self, src, dst, flag):
        src.settimeout(5)
        dst.settimeout(5)
        self.src = src
        self.dst = dst
        self.flag = flag
        threading.Thread.__init__(self)
        self.daemon = True

    def run(self):
        while True:
            try:
                n = self.src.recv(1024)
                if n == '':
                    print "got no bytes, bye"
                    self.src.close()
                    self.dst.close()
                    flag[0] = True
                    return
                self.dst.send(n)
            except socket.timeout:
                if self.flag[0] == True:
                    self.src.close()
                    self.dst.close()
                    return
            except:
                print "other end is dead, see ya"
                self.src.close()
                self.dst.close()
                self.flag[0] = True
                return
def readtonewline(client):
    ans = ''
    while not '\n' in ans:
        res = client.recv(1024)
        if len(res) == 0:
            # connection was closed
            return ''
        ans += res
    return ans

def run(client):
    hline = readtonewline(client)
    if hline == '':
        client.close()
        return
    lines = hline.split('\n')
    if not " " in lines[0]:
        client.close()
        return
    greet, hostv = lines[0].split()
    if ":" in hostv:
        host, port = hostv.split(":")
    else:
        host = hostv
    hname = host.split(".")[0]
    if hname == 'root':
        client.close()
        return
    host = "%s.internal.redacted.com"%hname
    try:
        resolver.query(host)
    except resolver.NXDOMAIN:
        client.close()
        return
    server = socket.socket()
    server.connect((host, 2130))
    server.send(hline)
    flag = [False]
    left = ShovelBytes(client, server, flag)
    right = ShovelBytes(server, client, flag)
    left.start()
    right.start()

def go():
    daemonize()
    sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("0.0.0.0", 2130))

    while True:
        try:
            sock.listen(5)
            conn, address = sock.accept()
            run(conn)
        except KeyboardInterrupt:
            sys.exit(0)
        except Exception, e:
            print e
            # NOBODY CARES
            pass

def pidfile():
    return "/var/run/%s.pid"%os.path.basename(sys.argv[0])

def pid_running(pid):
    """ Check For the existence of a unix pid. """
    if not pid:
        return False
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

def daemonize():
    '''
    Gee, I dunno what this function does.
    '''
    pid = os.fork()
    if pid > 0:
        os._exit(0)

    os.setsid()
    os.chdir("/")
    pid = os.fork()
    if pid > 0:
        os._exit(0)

    pid = os.getpid()
    pf = open(pidfile(), 'w')
    pf.write("%d\n"%pid)
    pf.close()

    close_fds()

def close_fds():
    sys.stdout.flush()
    sys.stderr.flush()
    dn = os.open(os.devnull, os.O_RDWR)
    os.dup2(dn, 0)
    os.dup2(dn, 1)
    os.dup2(dn, 2)

if __name__ == '__main__':
    go()

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.