server.py 2.4 KB

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