server.py 2.4 KB

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