Config.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import argparse
  2. import sys
  3. import os
  4. import locale
  5. import re
  6. import ConfigParser
  7. class Config(object):
  8. def __init__(self, argv):
  9. self.version = "0.5.5"
  10. self.rev = 2105
  11. self.argv = argv
  12. self.action = None
  13. self.config_file = "zeronet.conf"
  14. self.createParser()
  15. self.createArguments()
  16. def createParser(self):
  17. # Create parser
  18. self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  19. self.parser.register('type', 'bool', self.strToBool)
  20. self.subparsers = self.parser.add_subparsers(title="Action to perform", dest="action")
  21. def __str__(self):
  22. return str(self.arguments).replace("Namespace", "Config") # Using argparse str output
  23. # Convert string to bool
  24. def strToBool(self, v):
  25. return v.lower() in ("yes", "true", "t", "1")
  26. # Create command line arguments
  27. def createArguments(self):
  28. trackers = [
  29. "zero://boot3rdez4rzn36x.onion:15441",
  30. "zero://boot.zeronet.io#f36ca555bee6ba216b14d10f38c16f7769ff064e0e37d887603548cc2e64191d:15441",
  31. "udp://tracker.coppersurfer.tk:6969",
  32. "udp://tracker.leechers-paradise.org:6969",
  33. "udp://9.rarbg.com:2710",
  34. "http://tracker.opentrackr.org:1337/announce",
  35. "http://explodie.org:6969/announce",
  36. "http://tracker1.wasabii.com.tw:6969/announce"
  37. ]
  38. # Platform specific
  39. if sys.platform.startswith("win"):
  40. coffeescript = "type %s | tools\\coffee\\coffee.cmd"
  41. else:
  42. coffeescript = None
  43. try:
  44. language, enc = locale.getdefaultlocale()
  45. language = language.split("_")[0]
  46. except Exception:
  47. language = "en"
  48. use_openssl = True
  49. if repr(1483108852.565) != "1483108852.565":
  50. fix_float_decimals = True
  51. else:
  52. fix_float_decimals = False
  53. this_file = os.path.abspath(__file__).replace("\\", "/")
  54. if this_file.endswith("/Contents/Resources/core/src/Config.py"):
  55. # Running as ZeroNet.app
  56. if this_file.startswith("/Application") or this_file.startswith("/private") or this_file.startswith(os.path.expanduser("~/Library")):
  57. # Runnig from non-writeable directory, put data to Application Support
  58. start_dir = os.path.expanduser("~/Library/Application Support/ZeroNet").decode(sys.getfilesystemencoding())
  59. else:
  60. # Running from writeable directory put data next to .app
  61. start_dir = re.sub("/[^/]+/Contents/Resources/core/src/Config.py", "", this_file).decode(sys.getfilesystemencoding())
  62. config_file = start_dir + "/zeronet.conf"
  63. data_dir = start_dir + "/data"
  64. log_dir = start_dir + "/log"
  65. elif this_file.endswith("/core/src/Config.py"):
  66. # Running as exe or source is at Application Support directory, put var files to outside of core dir
  67. start_dir = this_file.replace("/core/src/Config.py", "").decode(sys.getfilesystemencoding())
  68. config_file = start_dir + "/zeronet.conf"
  69. data_dir = start_dir + "/data"
  70. log_dir = start_dir + "/log"
  71. elif this_file.endswith("usr/share/zeronet/src/Config.py"):
  72. # Running from non-writeable location, e.g., AppImage
  73. start_dir = os.path.expanduser("~/ZeroNet").decode(sys.getfilesystemencoding())
  74. config_file = start_dir + "/zeronet.conf"
  75. data_dir = start_dir + "/data"
  76. log_dir = start_dir + "/log"
  77. else:
  78. config_file = "zeronet.conf"
  79. data_dir = "data"
  80. log_dir = "log"
  81. ip_local = ["127.0.0.1"]
  82. # Main
  83. action = self.subparsers.add_parser("main", help='Start UiServer and FileServer (default)')
  84. # SiteCreate
  85. action = self.subparsers.add_parser("siteCreate", help='Create a new site')
  86. # SiteNeedFile
  87. action = self.subparsers.add_parser("siteNeedFile", help='Get a file from site')
  88. action.add_argument('address', help='Site address')
  89. action.add_argument('inner_path', help='File inner path')
  90. # SiteDownload
  91. action = self.subparsers.add_parser("siteDownload", help='Download a new site')
  92. action.add_argument('address', help='Site address')
  93. # SiteSign
  94. action = self.subparsers.add_parser("siteSign", help='Update and sign content.json: address [privatekey]')
  95. action.add_argument('address', help='Site to sign')
  96. action.add_argument('privatekey', help='Private key (default: ask on execute)', nargs='?')
  97. action.add_argument('--inner_path', help='File you want to sign (default: content.json)',
  98. default="content.json", metavar="inner_path")
  99. action.add_argument('--remove_missing_optional', help='Remove optional files that is not present in the directory', action='store_true')
  100. action.add_argument('--publish', help='Publish site after the signing', action='store_true')
  101. # SitePublish
  102. action = self.subparsers.add_parser("sitePublish", help='Publish site to other peers: address')
  103. action.add_argument('address', help='Site to publish')
  104. action.add_argument('peer_ip', help='Peer ip to publish (default: random peers ip from tracker)',
  105. default=None, nargs='?')
  106. action.add_argument('peer_port', help='Peer port to publish (default: random peer port from tracker)',
  107. default=15441, nargs='?')
  108. action.add_argument('--inner_path', help='Content.json you want to publish (default: content.json)',
  109. default="content.json", metavar="inner_path")
  110. # SiteVerify
  111. action = self.subparsers.add_parser("siteVerify", help='Verify site files using sha512: address')
  112. action.add_argument('address', help='Site to verify')
  113. # dbRebuild
  114. action = self.subparsers.add_parser("dbRebuild", help='Rebuild site database cache')
  115. action.add_argument('address', help='Site to rebuild')
  116. # dbQuery
  117. action = self.subparsers.add_parser("dbQuery", help='Query site sql cache')
  118. action.add_argument('address', help='Site to query')
  119. action.add_argument('query', help='Sql query')
  120. # PeerPing
  121. action = self.subparsers.add_parser("peerPing", help='Send Ping command to peer')
  122. action.add_argument('peer_ip', help='Peer ip')
  123. action.add_argument('peer_port', help='Peer port', nargs='?')
  124. # PeerGetFile
  125. action = self.subparsers.add_parser("peerGetFile", help='Request and print a file content from peer')
  126. action.add_argument('peer_ip', help='Peer ip')
  127. action.add_argument('peer_port', help='Peer port')
  128. action.add_argument('site', help='Site address')
  129. action.add_argument('filename', help='File name to request')
  130. action.add_argument('--benchmark', help='Request file 10x then displays the total time', action='store_true')
  131. # PeerCmd
  132. action = self.subparsers.add_parser("peerCmd", help='Request and print a file content from peer')
  133. action.add_argument('peer_ip', help='Peer ip')
  134. action.add_argument('peer_port', help='Peer port')
  135. action.add_argument('cmd', help='Command to execute')
  136. action.add_argument('parameters', help='Parameters to command', nargs='?')
  137. # CryptSign
  138. action = self.subparsers.add_parser("cryptSign", help='Sign message using Bitcoin private key')
  139. action.add_argument('message', help='Message to sign')
  140. action.add_argument('privatekey', help='Private key')
  141. # Config parameters
  142. self.parser.add_argument('--verbose', help='More detailed logging', action='store_true')
  143. self.parser.add_argument('--debug', help='Debug mode', action='store_true')
  144. self.parser.add_argument('--debug_socket', help='Debug socket connections', action='store_true')
  145. self.parser.add_argument('--debug_gevent', help='Debug gevent functions', action='store_true')
  146. self.parser.add_argument('--batch', help="Batch mode (No interactive input for commands)", action='store_true')
  147. self.parser.add_argument('--config_file', help='Path of config file', default=config_file, metavar="path")
  148. self.parser.add_argument('--data_dir', help='Path of data directory', default=data_dir, metavar="path")
  149. self.parser.add_argument('--log_dir', help='Path of logging directory', default=log_dir, metavar="path")
  150. self.parser.add_argument('--language', help='Web interface language', default=language, metavar='language')
  151. self.parser.add_argument('--ui_ip', help='Web interface bind address', default="127.0.0.1", metavar='ip')
  152. self.parser.add_argument('--ui_port', help='Web interface bind port', default=43110, type=int, metavar='port')
  153. self.parser.add_argument('--ui_restrict', help='Restrict web access', default=False, metavar='ip', nargs='*')
  154. self.parser.add_argument('--ui_host', help='Allow access using this hosts', metavar='host', nargs='*')
  155. self.parser.add_argument('--open_browser', help='Open homepage in web browser automatically',
  156. nargs='?', const="default_browser", metavar='browser_name')
  157. self.parser.add_argument('--homepage', help='Web interface Homepage', default='1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D',
  158. metavar='address')
  159. self.parser.add_argument('--updatesite', help='Source code update site', default='1UPDatEDxnvHDo7TXvq6AEBARfNkyfxsp',
  160. metavar='address')
  161. self.parser.add_argument('--size_limit', help='Default site size limit in MB', default=10, type=int, metavar='limit')
  162. self.parser.add_argument('--file_size_limit', help='Maximum per file size limit in MB', default=10, type=int, metavar='limit')
  163. self.parser.add_argument('--connected_limit', help='Max connected peer per site', default=8, type=int, metavar='connected_limit')
  164. self.parser.add_argument('--workers', help='Download workers per site', default=5, type=int, metavar='workers')
  165. self.parser.add_argument('--fileserver_ip', help='FileServer bind address', default="*", metavar='ip')
  166. self.parser.add_argument('--fileserver_port', help='FileServer bind port', default=15441, type=int, metavar='port')
  167. self.parser.add_argument('--ip_local', help='My local ips', default=ip_local, type=int, metavar='ip', nargs='*')
  168. self.parser.add_argument('--disable_udp', help='Disable UDP connections', action='store_true')
  169. self.parser.add_argument('--proxy', help='Socks proxy address', metavar='ip:port')
  170. self.parser.add_argument('--bind', help='Bind outgoing sockets to this address', metavar='ip')
  171. self.parser.add_argument('--ip_external', help='Set reported external ip (tested on start if None)', metavar='ip')
  172. self.parser.add_argument('--trackers', help='Bootstraping torrent trackers', default=trackers, metavar='protocol://address', nargs='*')
  173. self.parser.add_argument('--trackers_file', help='Load torrent trackers dynamically from a file', default=False, metavar='path')
  174. self.parser.add_argument('--use_openssl', help='Use OpenSSL liblary for speedup',
  175. type='bool', choices=[True, False], default=use_openssl)
  176. self.parser.add_argument('--disable_db', help='Disable database updating', action='store_true')
  177. self.parser.add_argument('--disable_encryption', help='Disable connection encryption', action='store_true')
  178. self.parser.add_argument('--disable_sslcompression', help='Disable SSL compression to save memory',
  179. type='bool', choices=[True, False], default=True)
  180. self.parser.add_argument('--keep_ssl_cert', help='Disable new SSL cert generation on startup', action='store_true')
  181. self.parser.add_argument('--max_files_opened', help='Change maximum opened files allowed by OS to this value on startup',
  182. default=2048, type=int, metavar='limit')
  183. self.parser.add_argument('--stack_size', help='Change thread stack size', default=None, type=int, metavar='thread_stack_size')
  184. self.parser.add_argument('--use_tempfiles', help='Use temporary files when downloading (experimental)',
  185. type='bool', choices=[True, False], default=False)
  186. self.parser.add_argument('--stream_downloads', help='Stream download directly to files (experimental)',
  187. type='bool', choices=[True, False], default=False)
  188. self.parser.add_argument("--msgpack_purepython", help='Use less memory, but a bit more CPU power',
  189. type='bool', choices=[True, False], default=True)
  190. self.parser.add_argument("--fix_float_decimals", help='Fix content.json modification date float precision on verification',
  191. type='bool', choices=[True, False], default=fix_float_decimals)
  192. self.parser.add_argument("--db_mode", choices=["speed", "security"], default="speed")
  193. self.parser.add_argument('--coffeescript_compiler', help='Coffeescript compiler for developing', default=coffeescript,
  194. metavar='executable_path')
  195. self.parser.add_argument('--tor', help='enable: Use only for Tor peers, always: Use Tor for every connection', choices=["disable", "enable", "always"], default='enable')
  196. self.parser.add_argument('--tor_controller', help='Tor controller address', metavar='ip:port', default='127.0.0.1:9051')
  197. self.parser.add_argument('--tor_proxy', help='Tor proxy address', metavar='ip:port', default='127.0.0.1:9050')
  198. self.parser.add_argument('--tor_password', help='Tor controller password', metavar='password')
  199. self.parser.add_argument('--tor_hs_limit', help='Maximum number of hidden services', metavar='limit', type=int, default=10)
  200. self.parser.add_argument('--version', action='version', version='ZeroNet %s r%s' % (self.version, self.rev))
  201. self.parser.add_argument('--end', help='Stop multi value argument parsing', action='store_true')
  202. return self.parser
  203. def loadTrackersFile(self):
  204. self.trackers = []
  205. for tracker in open(self.trackers_file):
  206. if "://" in tracker:
  207. self.trackers.append(tracker.strip())
  208. # Find arguments specified for current action
  209. def getActionArguments(self):
  210. back = {}
  211. arguments = self.parser._subparsers._group_actions[0].choices[self.action]._actions[1:] # First is --version
  212. for argument in arguments:
  213. back[argument.dest] = getattr(self, argument.dest)
  214. return back
  215. # Try to find action from argv
  216. def getAction(self, argv):
  217. actions = [action.choices.keys() for action in self.parser._actions if action.dest == "action"][0] # Valid actions
  218. found_action = False
  219. for action in actions: # See if any in argv
  220. if action in argv:
  221. found_action = action
  222. break
  223. return found_action
  224. # Move plugin parameters to end of argument list
  225. def moveUnknownToEnd(self, argv, default_action):
  226. valid_actions = sum([action.option_strings for action in self.parser._actions], [])
  227. valid_parameters = []
  228. plugin_parameters = []
  229. plugin = False
  230. for arg in argv:
  231. if arg.startswith("--"):
  232. if arg not in valid_actions:
  233. plugin = True
  234. else:
  235. plugin = False
  236. elif arg == default_action:
  237. plugin = False
  238. if plugin:
  239. plugin_parameters.append(arg)
  240. else:
  241. valid_parameters.append(arg)
  242. return valid_parameters + plugin_parameters
  243. # Parse arguments from config file and command line
  244. def parse(self, silent=False, parse_config=True):
  245. if silent: # Don't display messages or quit on unknown parameter
  246. original_print_message = self.parser._print_message
  247. original_exit = self.parser.exit
  248. def silencer(parser, function_name):
  249. parser.exited = True
  250. return None
  251. self.parser.exited = False
  252. self.parser._print_message = lambda *args, **kwargs: silencer(self.parser, "_print_message")
  253. self.parser.exit = lambda *args, **kwargs: silencer(self.parser, "exit")
  254. argv = self.argv[:] # Copy command line arguments
  255. self.parseCommandline(argv, silent) # Parse argv
  256. self.setAttributes()
  257. if parse_config:
  258. argv = self.parseConfig(argv) # Add arguments from config file
  259. self.parseCommandline(argv, silent) # Parse argv
  260. self.setAttributes()
  261. if not silent:
  262. if self.fileserver_ip != "*" and self.fileserver_ip not in self.ip_local:
  263. self.ip_local.append(self.fileserver_ip)
  264. if silent: # Restore original functions
  265. if self.parser.exited and self.action == "main": # Argument parsing halted, don't start ZeroNet with main action
  266. self.action = None
  267. self.parser._print_message = original_print_message
  268. self.parser.exit = original_exit
  269. # Parse command line arguments
  270. def parseCommandline(self, argv, silent=False):
  271. # Find out if action is specificed on start
  272. action = self.getAction(argv)
  273. if not action:
  274. argv.append("--end")
  275. argv.append("main")
  276. action = "main"
  277. argv = self.moveUnknownToEnd(argv, action)
  278. if silent:
  279. res = self.parser.parse_known_args(argv[1:])
  280. if res:
  281. self.arguments = res[0]
  282. else:
  283. self.arguments = {}
  284. else:
  285. self.arguments = self.parser.parse_args(argv[1:])
  286. # Parse config file
  287. def parseConfig(self, argv):
  288. # Find config file path from parameters
  289. if "--config_file" in argv:
  290. self.config_file = argv[argv.index("--config_file") + 1]
  291. # Load config file
  292. if os.path.isfile(self.config_file):
  293. config = ConfigParser.ConfigParser(allow_no_value=True)
  294. config.read(self.config_file)
  295. for section in config.sections():
  296. for key, val in config.items(section):
  297. if section != "global": # If not global prefix key with section
  298. key = section + "_" + key
  299. if val:
  300. for line in val.strip().split("\n"): # Allow multi-line values
  301. argv.insert(1, line)
  302. argv.insert(1, "--%s" % key)
  303. return argv
  304. # Expose arguments as class attributes
  305. def setAttributes(self):
  306. # Set attributes from arguments
  307. if self.arguments:
  308. args = vars(self.arguments)
  309. for key, val in args.items():
  310. setattr(self, key, val)
  311. def loadPlugins(self):
  312. from Plugin import PluginManager
  313. @PluginManager.acceptPlugins
  314. class ConfigPlugin(object):
  315. def __init__(self, config):
  316. self.parser = config.parser
  317. self.createArguments()
  318. def createArguments(self):
  319. pass
  320. ConfigPlugin(self)
  321. def saveValue(self, key, value):
  322. if not os.path.isfile(self.config_file):
  323. content = ""
  324. else:
  325. content = open(self.config_file).read()
  326. lines = content.splitlines()
  327. global_line_i = None
  328. key_line_i = None
  329. i = 0
  330. for line in lines:
  331. if line.strip() == "[global]":
  332. global_line_i = i
  333. if line.startswith(key + " = "):
  334. key_line_i = i
  335. i += 1
  336. if value is None: # Delete line
  337. if key_line_i:
  338. del lines[key_line_i]
  339. else: # Add / update
  340. new_line = "%s = %s" % (key, str(value).replace("\n", "").replace("\r", ""))
  341. if key_line_i: # Already in the config, change the line
  342. lines[key_line_i] = new_line
  343. elif global_line_i is None: # No global section yet, append to end of file
  344. lines.append("[global]")
  345. lines.append(new_line)
  346. else: # Has global section, append the line after it
  347. lines.insert(global_line_i + 1, new_line)
  348. open(self.config_file, "w").write("\n".join(lines))
  349. config = Config(sys.argv)