Config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import argparse
  2. import sys
  3. import os
  4. import ConfigParser
  5. class Config(object):
  6. def __init__(self, argv):
  7. self.version = "0.3.6"
  8. self.rev = 989
  9. self.argv = argv
  10. self.action = None
  11. self.config_file = "zeronet.conf"
  12. self.createParser()
  13. self.createArguments()
  14. def createParser(self):
  15. # Create parser
  16. self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  17. self.parser.register('type', 'bool', self.strToBool)
  18. self.subparsers = self.parser.add_subparsers(title="Action to perform", dest="action")
  19. def __str__(self):
  20. return str(self.arguments).replace("Namespace", "Config") # Using argparse str output
  21. # Convert string to bool
  22. def strToBool(self, v):
  23. return v.lower() in ("yes", "true", "t", "1")
  24. # Create command line arguments
  25. def createArguments(self):
  26. trackers = [
  27. "zero://boot3rdez4rzn36x.onion:15441",
  28. "zero://boot.zeronet.io#f36ca555bee6ba216b14d10f38c16f7769ff064e0e37d887603548cc2e64191d:15441",
  29. "udp://tracker.coppersurfer.tk:6969",
  30. "udp://tracker.leechers-paradise.org:6969",
  31. "udp://9.rarbg.com:2710",
  32. "http://tracker.aletorrenty.pl:2710/announce",
  33. "http://explodie.org:6969/announce",
  34. "http://torrent.gresille.org/announce"
  35. ]
  36. # Platform specific
  37. if sys.platform.startswith("win"):
  38. coffeescript = "type %s | tools\\coffee\\coffee.cmd"
  39. else:
  40. coffeescript = None
  41. use_openssl = True
  42. # Main
  43. action = self.subparsers.add_parser("main", help='Start UiServer and FileServer (default)')
  44. # SiteCreate
  45. action = self.subparsers.add_parser("siteCreate", help='Create a new site')
  46. # SiteNeedFile
  47. action = self.subparsers.add_parser("siteNeedFile", help='Get a file from site')
  48. action.add_argument('address', help='Site address')
  49. action.add_argument('inner_path', help='File inner path')
  50. # SiteSign
  51. action = self.subparsers.add_parser("siteSign", help='Update and sign content.json: address [privatekey]')
  52. action.add_argument('address', help='Site to sign')
  53. action.add_argument('privatekey', help='Private key (default: ask on execute)', nargs='?')
  54. action.add_argument('--inner_path', help='File you want to sign (default: content.json)',
  55. default="content.json", metavar="inner_path")
  56. action.add_argument('--publish', help='Publish site after the signing', action='store_true')
  57. # SitePublish
  58. action = self.subparsers.add_parser("sitePublish", help='Publish site to other peers: address')
  59. action.add_argument('address', help='Site to publish')
  60. action.add_argument('peer_ip', help='Peer ip to publish (default: random peers ip from tracker)',
  61. default=None, nargs='?')
  62. action.add_argument('peer_port', help='Peer port to publish (default: random peer port from tracker)',
  63. default=15441, nargs='?')
  64. action.add_argument('--inner_path', help='Content.json you want to publish (default: content.json)',
  65. default="content.json", metavar="inner_path")
  66. # SiteVerify
  67. action = self.subparsers.add_parser("siteVerify", help='Verify site files using sha512: address')
  68. action.add_argument('address', help='Site to verify')
  69. # dbRebuild
  70. action = self.subparsers.add_parser("dbRebuild", help='Rebuild site database cache')
  71. action.add_argument('address', help='Site to rebuild')
  72. # dbQuery
  73. action = self.subparsers.add_parser("dbQuery", help='Query site sql cache')
  74. action.add_argument('address', help='Site to query')
  75. action.add_argument('query', help='Sql query')
  76. # PeerPing
  77. action = self.subparsers.add_parser("peerPing", help='Send Ping command to peer')
  78. action.add_argument('peer_ip', help='Peer ip')
  79. action.add_argument('peer_port', help='Peer port', nargs='?')
  80. # PeerGetFile
  81. action = self.subparsers.add_parser("peerGetFile", help='Request and print a file content from peer')
  82. action.add_argument('peer_ip', help='Peer ip')
  83. action.add_argument('peer_port', help='Peer port')
  84. action.add_argument('site', help='Site address')
  85. action.add_argument('filename', help='File name to request')
  86. action.add_argument('--benchmark', help='Request file 10x then displays the total time', action='store_true')
  87. # PeerCmd
  88. action = self.subparsers.add_parser("peerCmd", help='Request and print a file content from peer')
  89. action.add_argument('peer_ip', help='Peer ip')
  90. action.add_argument('peer_port', help='Peer port')
  91. action.add_argument('cmd', help='Command to execute')
  92. action.add_argument('parameters', help='Parameters to command', nargs='?')
  93. # CryptSign
  94. action = self.subparsers.add_parser("cryptSign", help='Sign message using Bitcoin private key')
  95. action.add_argument('message', help='Message to sign')
  96. action.add_argument('privatekey', help='Private key')
  97. # Config parameters
  98. self.parser.add_argument('--verbose', help='More detailed logging', action='store_true')
  99. self.parser.add_argument('--debug', help='Debug mode', action='store_true')
  100. self.parser.add_argument('--debug_socket', help='Debug socket connections', action='store_true')
  101. self.parser.add_argument('--batch', help="Batch mode (No interactive input for commands)", action='store_true')
  102. self.parser.add_argument('--config_file', help='Path of config file', default="zeronet.conf", metavar="path")
  103. self.parser.add_argument('--data_dir', help='Path of data directory', default="data", metavar="path")
  104. self.parser.add_argument('--log_dir', help='Path of logging directory', default="log", metavar="path")
  105. self.parser.add_argument('--ui_ip', help='Web interface bind address', default="127.0.0.1", metavar='ip')
  106. self.parser.add_argument('--ui_port', help='Web interface bind port', default=43110, type=int, metavar='port')
  107. self.parser.add_argument('--ui_restrict', help='Restrict web access', default=False, metavar='ip', nargs='*')
  108. self.parser.add_argument('--open_browser', help='Open homepage in web browser automatically',
  109. nargs='?', const="default_browser", metavar='browser_name')
  110. self.parser.add_argument('--homepage', help='Web interface Homepage', default='1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D',
  111. metavar='address')
  112. self.parser.add_argument('--size_limit', help='Default site size limit in MB', default=10, metavar='size')
  113. self.parser.add_argument('--connected_limit', help='Max connected peer per site', default=15, metavar='connected_limit')
  114. self.parser.add_argument('--fileserver_ip', help='FileServer bind address', default="*", metavar='ip')
  115. self.parser.add_argument('--fileserver_port', help='FileServer bind port', default=15441, type=int, metavar='port')
  116. self.parser.add_argument('--disable_udp', help='Disable UDP connections', action='store_true')
  117. self.parser.add_argument('--proxy', help='Socks proxy address', metavar='ip:port')
  118. self.parser.add_argument('--ip_external', help='Set reported external ip (tested on start if None)', metavar='ip')
  119. self.parser.add_argument('--trackers', help='Bootstraping torrent trackers', default=trackers, metavar='protocol://address', nargs='*')
  120. self.parser.add_argument('--trackers_file', help='Load torrent trackers dynamically from a file', default=False, metavar='path')
  121. self.parser.add_argument('--use_openssl', help='Use OpenSSL liblary for speedup',
  122. type='bool', choices=[True, False], default=use_openssl)
  123. self.parser.add_argument('--disable_encryption', help='Disable connection encryption', action='store_true')
  124. self.parser.add_argument('--disable_sslcompression', help='Disable SSL compression to save memory',
  125. type='bool', choices=[True, False], default=True)
  126. self.parser.add_argument('--keep_ssl_cert', help='Disable new SSL cert generation on startup', action='store_true')
  127. self.parser.add_argument('--max_files_opened', help='Change maximum opened files allowed by OS to this value on startup',
  128. default=1024, type=int, metavar='limit')
  129. self.parser.add_argument('--use_tempfiles', help='Use temporary files when downloading (experimental)',
  130. type='bool', choices=[True, False], default=False)
  131. self.parser.add_argument('--stream_downloads', help='Stream download directly to files (experimental)',
  132. type='bool', choices=[True, False], default=False)
  133. self.parser.add_argument("--msgpack_purepython", help='Use less memory, but a bit more CPU power',
  134. type='bool', choices=[True, False], default=True)
  135. self.parser.add_argument('--coffeescript_compiler', help='Coffeescript compiler for developing', default=coffeescript,
  136. metavar='executable_path')
  137. self.parser.add_argument('--tor', help='enable: Use only for Tor peers, always: Use Tor for every connection', choices=["disable", "enable", "always"], default='enable')
  138. self.parser.add_argument('--tor_controller', help='Tor controller address', metavar='ip:port', default='127.0.0.1:9051')
  139. self.parser.add_argument('--tor_proxy', help='Tor proxy address', metavar='ip:port', default='127.0.0.1:9050')
  140. self.parser.add_argument('--version', action='version', version='ZeroNet %s r%s' % (self.version, self.rev))
  141. return self.parser
  142. def loadTrackersFile(self):
  143. self.trackers = []
  144. for tracker in open(self.trackers_file):
  145. if "://" in tracker:
  146. self.trackers.append(tracker.strip())
  147. # Find arguments specified for current action
  148. def getActionArguments(self):
  149. back = {}
  150. arguments = self.parser._subparsers._group_actions[0].choices[self.action]._actions[1:] # First is --version
  151. for argument in arguments:
  152. back[argument.dest] = getattr(self, argument.dest)
  153. return back
  154. # Try to find action from argv
  155. def getAction(self, argv):
  156. actions = [action.choices.keys() for action in self.parser._actions if action.dest == "action"][0] # Valid actions
  157. found_action = False
  158. for action in actions: # See if any in argv
  159. if action in argv:
  160. found_action = action
  161. break
  162. return found_action
  163. # Move plugin parameters to end of argument list
  164. def moveUnknownToEnd(self, argv, default_action):
  165. valid_actions = sum([action.option_strings for action in self.parser._actions], [])
  166. valid_parameters = []
  167. plugin_parameters = []
  168. plugin = False
  169. for arg in argv:
  170. if arg.startswith("--"):
  171. if arg not in valid_actions:
  172. plugin = True
  173. else:
  174. plugin = False
  175. elif arg == default_action:
  176. plugin = False
  177. if plugin:
  178. plugin_parameters.append(arg)
  179. else:
  180. valid_parameters.append(arg)
  181. return valid_parameters + plugin_parameters
  182. # Parse arguments from config file and command line
  183. def parse(self, silent=False, parse_config=True):
  184. if silent: # Don't display messages or quit on unknown parameter
  185. original_print_message = self.parser._print_message
  186. original_exit = self.parser.exit
  187. def silencer(parser, function_name):
  188. parser.exited = True
  189. return None
  190. self.parser.exited = False
  191. self.parser._print_message = lambda *args, **kwargs: silencer(self.parser, "_print_message")
  192. self.parser.exit = lambda *args, **kwargs: silencer(self.parser, "exit")
  193. argv = self.argv[:] # Copy command line arguments
  194. if parse_config:
  195. argv = self.parseConfig(argv) # Add arguments from config file
  196. self.parseCommandline(argv, silent) # Parse argv
  197. self.setAttributes()
  198. if silent: # Restore original functions
  199. if self.parser.exited and self.action == "main": # Argument parsing halted, don't start ZeroNet with main action
  200. self.action = None
  201. self.parser._print_message = original_print_message
  202. self.parser.exit = original_exit
  203. # Parse command line arguments
  204. def parseCommandline(self, argv, silent=False):
  205. # Find out if action is specificed on start
  206. action = self.getAction(argv)
  207. if not action:
  208. argv.append("main")
  209. action = "main"
  210. argv = self.moveUnknownToEnd(argv, action)
  211. if silent:
  212. res = self.parser.parse_known_args(argv[1:])
  213. if res:
  214. self.arguments = res[0]
  215. else:
  216. self.arguments = {}
  217. else:
  218. self.arguments = self.parser.parse_args(argv[1:])
  219. # Parse config file
  220. def parseConfig(self, argv):
  221. # Find config file path from parameters
  222. if "--config_file" in argv:
  223. self.config_file = argv[argv.index("--config_file") + 1]
  224. # Load config file
  225. if os.path.isfile(self.config_file):
  226. config = ConfigParser.ConfigParser(allow_no_value=True)
  227. config.read(self.config_file)
  228. for section in config.sections():
  229. for key, val in config.items(section):
  230. if section != "global": # If not global prefix key with section
  231. key = section + "_" + key
  232. if val:
  233. for line in val.strip().split("\n"): # Allow multi-line values
  234. argv.insert(1, line)
  235. argv.insert(1, "--%s" % key)
  236. return argv
  237. # Expose arguments as class attributes
  238. def setAttributes(self):
  239. # Set attributes from arguments
  240. if self.arguments:
  241. args = vars(self.arguments)
  242. for key, val in args.items():
  243. setattr(self, key, val)
  244. def loadPlugins(self):
  245. from Plugin import PluginManager
  246. @PluginManager.acceptPlugins
  247. class ConfigPlugin(object):
  248. def __init__(self, config):
  249. self.parser = config.parser
  250. self.createArguments()
  251. def createArguments(self):
  252. pass
  253. ConfigPlugin(self)
  254. config = Config(sys.argv)