server.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import datetime
  4. import socket
  5. import random, string
  6. import daemon, getopt, sys
  7. import daemon.pidlockfile
  8. import os
  9. def myrandom(length):
  10. return ''.join(random.choice(string.lowercase) for i in range(length))
  11. def server(port, bindTo):
  12. BUFFER_SIZE = 1024
  13. s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  14. s.bind((bindTo, port))
  15. s.listen(1)
  16. print('DebugReport server listening on [{0}]:{1}'.format(bindTo, port))
  17. while 1:
  18. conn, addr = s.accept()
  19. report_id = myrandom(10)
  20. filename = '/opt/debugserver/reports/' + datetime.date.today().strftime('%Y-%m-%d_') + report_id + '.gz'
  21. with open(filename, 'w') as f:
  22. try:
  23. while 1:
  24. data = conn.recv(BUFFER_SIZE)
  25. if not data: break
  26. f.write(data) # python will convert \n to os.linesep
  27. except:
  28. # delete the incompletely received report
  29. f.close()
  30. os.remove(filename)
  31. # try to send a zero-length response back to the peer to indicate a problem
  32. try:
  33. conn.sendall("\r\n")
  34. finally:
  35. conn.close()
  36. continue
  37. f.flush()
  38. # f will be closed automatically by leaving the 'with'-scope
  39. # send reply to reportee
  40. response = "%s\r\n" % report_id
  41. try:
  42. conn.sendall(response)
  43. finally:
  44. conn.close()
  45. command = 'echo "'+'new report \\\"{0}\\\" from [{2}]:{3} stored as \\\"{1}\\\""'.format(report_id, filename, addr[0], addr[1])
  46. command = command + ' | /usr/local/bin/ff_log_to_bot'
  47. os.system(command)
  48. print('new report "{0}" from [{2}]:{3} stored as "{1}"'.format(report_id, filename, addr[0], addr[1]))
  49. pass
  50. if __name__ == '__main__':
  51. try:
  52. opts, args = getopt.getopt(sys.argv[1:], "dp:b:", ["do-not-daemonize", "port", "bind-to"])
  53. except:
  54. print ('Unrecognized option')
  55. sys.exit(2)
  56. daemonize = True
  57. port = 1337
  58. bindTo = '::'
  59. for opt, arg in opts:
  60. if opt in ("-d", "--do-not-daemonize"):
  61. daemonize = False
  62. elif opt in ("-p", "--port"):
  63. port = int(arg)
  64. elif opt in ("-b", "--bind-to"):
  65. try:
  66. socket.inet_aton(arg)
  67. bindTo = str(arg)
  68. except:
  69. print('Invalid IPAdress. Using default ::')
  70. else:
  71. assert False
  72. if daemonize == False:
  73. server(port, bindTo)
  74. else:
  75. daemonContext = daemon.DaemonContext(pidfile = daemon.pidlockfile.PIDLockFile("/var/run/ffpb-debugserver.pid"))
  76. with daemonContext:
  77. server(port, bindTo)