server.py 2.8 KB

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