12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- #!/usr/bin/python
- from __future__ import print_function
- import datetime
- import socket
- import random, string
- import daemon, getopt, sys
- import daemon.pidlockfile
- import os
- def myrandom(length):
- return ''.join(random.choice(string.lowercase) for i in range(length))
- def serve(port, bindTo):
- BUFFER_SIZE = 1024
-
- s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
- s.settimeout(30.0)
- s.bind((bindTo, port))
- s.listen(1)
- print('DebugReport server listening on [{0}]:{1}'.format(bindTo, port))
- while 1:
- conn, addr = s.accept()
- report_id = myrandom(10)
- filename = '/opt/debugserver/reports/' + datetime.date.today().strftime('%Y-%m-%d_') + report_id + '.gz'
- with open(filename, 'w') as f:
- try:
- while 1:
- data = conn.recv(BUFFER_SIZE)
- if not data: break
- f.write(data) # python will convert \n to os.linesep
- except:
- # delete the incompletely received report
- f.close()
- os.remove(filename)
- # try to send a zero-length response back to the peer to indicate a problem
- try:
- conn.sendall("\r\n")
- finally:
- conn.close()
- continue
- f.flush()
- # f will be closed automatically by leaving the 'with'-scope
- # send reply to reportee
- response = "%s\r\n" % report_id
- try:
- conn.sendall(response)
- finally:
- conn.close()
- command = 'echo "'+'new report \\\"{0}\\\" from [{2}]:{3} stored as \\\"{1}\\\""'.format(report_id, filename, addr[0], addr[1])
- command = command + ' | /usr/local/bin/ff_log_to_bot'
- os.system(command)
- print('new report "{0}" from [{2}]:{3} stored as "{1}"'.format(report_id, filename, addr[0], addr[1]))
- pass
- if __name__ == '__main__':
- try:
- opts, args = getopt.getopt(sys.argv[1:], "dp:b:", ["do-not-daemonize", "port=", "bind-to="])
- except:
- print ('Unrecognized option')
- sys.exit(2)
- daemonize = True
- port = 1337
- bindTo = '::'
- for opt, arg in opts:
- if opt in ("-d", "--do-not-daemonize"):
- daemonize = False
- elif opt in ("-p", "--port"):
- port = int(arg)
- elif opt in ("-b", "--bind-to"):
- try:
- socket.inet_aton(arg)
- bindTo = str(arg)
- except:
- print('Listening IP address is either invalid or unset. Using default ::')
- else:
- assert False
-
- if daemonize == False:
- serve(port, bindTo)
- else:
- daemonContext = daemon.DaemonContext(pidfile = daemon.pidlockfile.PIDLockFile("/var/run/ffpb-debugserver.pid"))
- with daemonContext:
- serve(port, bindTo)
|