2015-07-12 20:36:46 +02:00
import argparse
import sys
import os
2016-11-18 20:00:15 +01:00
import locale
2017-01-21 23:00:13 +01:00
import re
2019-03-15 21:06:59 +01:00
import configparser
2018-11-08 01:32:31 +01:00
import logging
import logging . handlers
import stat
2020-09-09 18:29:24 +02:00
import time
2015-04-18 03:02:08 +02:00
2015-07-12 20:36:46 +02:00
2015-04-18 03:02:08 +02:00
class Config ( object ) :
2015-07-12 20:36:46 +02:00
2015-07-17 00:28:43 +02:00
def __init__ ( self , argv ) :
2022-05-17 16:03:20 +02:00
self . version = " 0.7.5 "
2022-01-26 21:18:32 +01:00
# DEPRECATED ; replace with git-generated commit
2022-05-17 16:03:20 +02:00
self . rev = 5010
2015-07-17 00:28:43 +02:00
self . argv = argv
self . action = None
2019-11-19 02:14:29 +01:00
self . test_parser = None
2018-07-10 03:39:33 +02:00
self . pending_changes = { }
self . need_restart = False
2019-01-20 03:15:21 +01:00
self . keys_api_change_allowed = set ( [
" tor " , " fileserver_port " , " language " , " tor_use_bridges " , " trackers_proxy " , " trackers " ,
2019-11-20 14:07:04 +01:00
" trackers_file " , " open_browser " , " log_level " , " fileserver_ip_type " , " ip_external " , " offline " ,
2019-11-30 02:14:54 +01:00
" threads_fs_read " , " threads_fs_write " , " threads_crypt " , " threads_db "
] )
self . keys_restart_need = set ( [
" tor " , " fileserver_port " , " fileserver_ip_type " , " threads_fs_read " , " threads_fs_write " , " threads_crypt " , " threads_db "
2019-01-20 03:15:21 +01:00
] )
2018-07-21 04:25:40 +02:00
self . start_dir = self . getStartDir ( )
2018-07-10 03:39:33 +02:00
2019-05-21 15:53:32 +02:00
self . config_file = self . start_dir + " /zeronet.conf "
self . data_dir = self . start_dir + " /data "
self . log_dir = self . start_dir + " /log "
2020-02-20 17:23:00 +01:00
self . openssl_lib_file = None
self . openssl_bin_file = None
2019-05-21 15:53:32 +02:00
2018-10-04 15:42:11 +02:00
self . trackers_file = False
2015-07-17 00:28:43 +02:00
self . createParser ( )
self . createArguments ( )
def createParser ( self ) :
# Create parser
self . parser = argparse . ArgumentParser ( formatter_class = argparse . ArgumentDefaultsHelpFormatter )
self . parser . register ( ' type ' , ' bool ' , self . strToBool )
self . subparsers = self . parser . add_subparsers ( title = " Action to perform " , dest = " action " )
2015-07-12 20:36:46 +02:00
def __str__ ( self ) :
return str ( self . arguments ) . replace ( " Namespace " , " Config " ) # Using argparse str output
# Convert string to bool
def strToBool ( self , v ) :
return v . lower ( ) in ( " yes " , " true " , " t " , " 1 " )
2018-07-21 04:25:40 +02:00
def getStartDir ( self ) :
this_file = os . path . abspath ( __file__ ) . replace ( " \\ " , " / " ) . rstrip ( " cd " )
2020-02-20 17:25:06 +01:00
if " --start_dir " in self . argv :
start_dir = self . argv [ self . argv . index ( " --start_dir " ) + 1 ]
elif this_file . endswith ( " /Contents/Resources/core/src/Config.py " ) :
2018-07-21 04:25:40 +02:00
# Running as ZeroNet.app
if this_file . startswith ( " /Application " ) or this_file . startswith ( " /private " ) or this_file . startswith ( os . path . expanduser ( " ~/Library " ) ) :
# Runnig from non-writeable directory, put data to Application Support
2019-04-01 03:58:06 +02:00
start_dir = os . path . expanduser ( " ~/Library/Application Support/ZeroNet " )
2018-07-21 04:25:40 +02:00
else :
# Running from writeable directory put data next to .app
2019-04-01 03:58:06 +02:00
start_dir = re . sub ( " /[^/]+/Contents/Resources/core/src/Config.py " , " " , this_file )
2018-07-21 04:25:40 +02:00
elif this_file . endswith ( " /core/src/Config.py " ) :
# Running as exe or source is at Application Support directory, put var files to outside of core dir
2019-04-01 03:58:06 +02:00
start_dir = this_file . replace ( " /core/src/Config.py " , " " )
2018-07-21 04:25:40 +02:00
elif this_file . endswith ( " usr/share/zeronet/src/Config.py " ) :
# Running from non-writeable location, e.g., AppImage
2019-04-01 03:58:06 +02:00
start_dir = os . path . expanduser ( " ~/ZeroNet " )
2018-07-21 04:25:40 +02:00
else :
start_dir = " . "
return start_dir
2015-07-12 20:36:46 +02:00
# Create command line arguments
def createArguments ( self ) :
2015-09-10 23:25:09 +02:00
trackers = [
2022-05-08 19:11:29 +02:00
# more trackers from Syncronite (TODO: check if any of the old ones still work)
' zero://kgsvasoakvj4gnjiy7zemu34l3hq46dn5eauqkn76jpowmilci5t2vqd.onion:15445 ' ,
' zero://hb6ozikfiaafeuqvgseiik4r46szbpjfu66l67wjinnyv6dtopuwhtqd.onion:15445 ' ,
' zero://75pmmcbp4vvo2zndmjnrkandvbg6jyptygvvpwsf2zguj7urq7t4jzyd.onion:7777 ' ,
' zero://dw4f4sckg2ultdj5qu7vtkf3jsfxsah3mz6pivwfd6nv3quji3vfvhyd.onion:6969 ' ,
' zero://5vczpwawviukvd7grfhsfxp7a6huz77hlis4fstjkym5kmf4pu7i7myd.onion:15441 ' ,
' zero://ow7in4ftwsix5klcbdfqvfqjvimqshbm2o75rhtpdnsderrcbx74wbad.onion:15441 ' ,
' zero://agufghdtniyfwty3wk55drxxwj2zxgzzo7dbrtje73gmvcpxy4ngs4ad.onion:15441 ' ,
' zero://qn65si4gtcwdiliq7vzrwu62qrweoxb6tx2cchwslaervj6szuje66qd.onion:26117 ' ,
' udp://tracker.opentrackr.org:1337/announce ' ,
' udp://tracker.moeking.me:6969/announce ' ,
' http://tracker.files.fm:6969/announce ' ,
' http://t.overflow.biz:6969/announce ' ,
' udp://fe.dealclub.de:6969/announce ' ,
' udp://movies.zsw.ca:6969/announce ' ,
' udp://6ahddutb1ucc3cp.ru:6969/announce ' ,
' zero://145.239.95.38:15441 ' ,
' zero://23.184.48.134:15441 ' ,
' zero://95.110.227.231:15441 ' ,
' zero://159.65.50.3:26117 ' ,
' zero://2a03:b0c0:1:d0::f52:1:26117 ' ,
' zero://k5w77dozo3hy5zualyhni6vrh73iwfkaofa64abbilwyhhd3wgenbjqd.onion:15441 ' ,
2021-10-20 11:28:28 +02:00
# by zeroseed at http://127.0.0.1:43110/19HKdTAeBh5nRiKn791czY7TwRB1QNrf1Q/?:users/1HvNGwHKqhj3ZMEM53tz6jbdqe4LRpanEu:zn:dc17f896-bf3f-4962-bdd4-0a470040c9c5
" zero://k5w77dozo3hy5zualyhni6vrh73iwfkaofa64abbilwyhhd3wgenbjqd.onion:15441 " ,
" zero://2kcb2fqesyaevc4lntogupa4mkdssth2ypfwczd2ov5a3zo6ytwwbayd.onion:15441 " ,
" zero://my562dxpjropcd5hy3nd5pemsc4aavbiptci5amwxzbelmzgkkuxpvid.onion:15441 " ,
" zero://pn4q2zzt2pw4nk7yidxvsxmydko7dfibuzxdswi6gu6ninjpofvqs2id.onion:15441 " ,
" zero://6i54dd5th73oelv636ivix6sjnwfgk2qsltnyvswagwphub375t3xcad.onion:15441 " ,
" zero://tl74auz4tyqv4bieeclmyoe4uwtoc2dj7fdqv4nc4gl5j2bwg2r26bqd.onion:15441 " ,
" zero://wlxav3szbrdhest4j7dib2vgbrd7uj7u7rnuzg22cxbih7yxyg2hsmid.onion:15441 " ,
" zero://zy7wttvjtsijt5uwmlar4yguvjc2gppzbdj4v6bujng6xwjmkdg7uvqd.onion:15441 " ,
# ZeroNet 0.7.2 defaults:
Version 0.3.5, Rev830, Full Tor mode support with hidden services, Onion stats in Sidebar, GeoDB download fix using Tor, Gray out disabled sites in Stats page, Tor hidden service status in stat page, Benchmark sha256, Skyts tracker out expodie in, 2 new tracker using ZeroNet protocol, Keep SSL cert option between restarts, SSL Certificate pinning support for connections, Site lock support for connections, Certificate pinned connections using implicit SSL, Flood protection whitelist support, Foreign keys support for DB layer, Not support for SQL query helper, 0 length file get bugfix, Pex onion address support, Faster port testing, Faster uPnP port opening, Need connections more often on owned sites, Delay ZeroHello startup message if port check or Tor manager not ready yet, Use lockfiles to avoid double start, Save original socket on proxy monkey patching to get ability to connect localhost directly, Handle atomic write errors, Broken gevent https workaround helper, Rsa crypt functions, Plugin to Bootstrap using ZeroNet protocol
2016-01-05 00:20:52 +01:00
" zero://boot3rdez4rzn36x.onion:15441 " ,
2018-04-03 14:42:16 +02:00
" zero://zero.booth.moe#f36ca555bee6ba216b14d10f38c16f7769ff064e0e37d887603548cc2e64191d:443 " , # US/NY
2018-02-10 01:00:50 +01:00
" udp://tracker.coppersurfer.tk:6969 " , # DE
2018-04-18 13:13:20 +02:00
" udp://104.238.198.186:8000 " , # US/LA
2020-02-25 16:47:04 +01:00
" udp://retracker.akado-ural.ru:80 " , # RU
" http://h4.trakx.nibba.trade:80/announce " , # US/VA
2018-04-29 01:00:50 +02:00
" http://open.acgnxtracker.com:80/announce " , # DE
2019-12-17 14:26:14 +01:00
" http://tracker.bt4g.com:2095/announce " , # Cloudflare
2019-01-20 19:08:49 +01:00
" zero://2602:ffc5::c5b2:5360:26312 " # US/ATL
2015-09-10 23:25:09 +02:00
]
2015-07-12 20:36:46 +02:00
# Platform specific
if sys . platform . startswith ( " win " ) :
coffeescript = " type %s | tools \\ coffee \\ coffee.cmd "
else :
coffeescript = None
2016-11-18 21:39:53 +01:00
try :
language , enc = locale . getdefaultlocale ( )
2018-10-04 15:42:45 +02:00
language = language . lower ( ) . replace ( " _ " , " - " )
2018-10-15 13:19:33 +02:00
if language not in [ " pt-br " , " zh-tw " ] :
2018-10-04 15:42:45 +02:00
language = language . split ( " - " ) [ 0 ]
2016-11-18 21:39:53 +01:00
except Exception :
language = " en "
2016-11-18 20:00:15 +01:00
2015-07-17 00:28:43 +02:00
use_openssl = True
2015-07-12 20:36:46 +02:00
2018-10-04 15:43:12 +02:00
if repr ( 1483108852.565 ) != " 1483108852.565 " : # Fix for weird Android issue
2017-01-07 01:06:24 +01:00
fix_float_decimals = True
else :
fix_float_decimals = False
2018-07-21 04:25:40 +02:00
config_file = self . start_dir + " /zeronet.conf "
data_dir = self . start_dir + " /data "
log_dir = self . start_dir + " /log "
2017-01-09 01:28:50 +01:00
2019-01-20 03:26:45 +01:00
ip_local = [ " 127.0.0.1 " , " ::1 " ]
2017-02-16 20:56:07 +01:00
2015-07-12 20:36:46 +02:00
# Main
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " main " , help = ' Start UiServer and FileServer (default) ' )
2015-07-12 20:36:46 +02:00
# SiteCreate
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " siteCreate " , help = ' Create a new site ' )
2019-10-30 02:30:01 +01:00
action . register ( ' type ' , ' bool ' , self . strToBool )
action . add_argument ( ' --use_master_seed ' , help = " Allow created site ' s private key to be recovered using the master seed in users.json (default: True) " , type = " bool " , choices = [ True , False ] , default = True )
2015-07-12 20:36:46 +02:00
2016-01-19 20:42:00 +01:00
# SiteNeedFile
action = self . subparsers . add_parser ( " siteNeedFile " , help = ' Get a file from site ' )
action . add_argument ( ' address ' , help = ' Site address ' )
action . add_argument ( ' inner_path ' , help = ' File inner path ' )
2016-03-19 18:11:12 +01:00
# SiteDownload
action = self . subparsers . add_parser ( " siteDownload " , help = ' Download a new site ' )
action . add_argument ( ' address ' , help = ' Site address ' )
2015-07-12 20:36:46 +02:00
# SiteSign
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " siteSign " , help = ' Update and sign content.json: address [privatekey] ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' address ' , help = ' Site to sign ' )
action . add_argument ( ' privatekey ' , help = ' Private key (default: ask on execute) ' , nargs = ' ? ' )
action . add_argument ( ' --inner_path ' , help = ' File you want to sign (default: content.json) ' ,
default = " content.json " , metavar = " inner_path " )
2017-01-27 12:02:14 +01:00
action . add_argument ( ' --remove_missing_optional ' , help = ' Remove optional files that is not present in the directory ' , action = ' store_true ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' --publish ' , help = ' Publish site after the signing ' , action = ' store_true ' )
# SitePublish
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " sitePublish " , help = ' Publish site to other peers: address ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' address ' , help = ' Site to publish ' )
action . add_argument ( ' peer_ip ' , help = ' Peer ip to publish (default: random peers ip from tracker) ' ,
default = None , nargs = ' ? ' )
action . add_argument ( ' peer_port ' , help = ' Peer port to publish (default: random peer port from tracker) ' ,
default = 15441 , nargs = ' ? ' )
action . add_argument ( ' --inner_path ' , help = ' Content.json you want to publish (default: content.json) ' ,
default = " content.json " , metavar = " inner_path " )
# SiteVerify
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " siteVerify " , help = ' Verify site files using sha512: address ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' address ' , help = ' Site to verify ' )
2018-04-03 14:50:58 +02:00
# SiteCmd
action = self . subparsers . add_parser ( " siteCmd " , help = ' Execute a ZeroFrame API command on a site ' )
action . add_argument ( ' address ' , help = ' Site address ' )
action . add_argument ( ' cmd ' , help = ' API command name ' )
action . add_argument ( ' parameters ' , help = ' Parameters of the command ' , nargs = ' ? ' )
2015-07-12 20:36:46 +02:00
# dbRebuild
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " dbRebuild " , help = ' Rebuild site database cache ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' address ' , help = ' Site to rebuild ' )
# dbQuery
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " dbQuery " , help = ' Query site sql cache ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' address ' , help = ' Site to query ' )
action . add_argument ( ' query ' , help = ' Sql query ' )
# PeerPing
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " peerPing " , help = ' Send Ping command to peer ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' peer_ip ' , help = ' Peer ip ' )
action . add_argument ( ' peer_port ' , help = ' Peer port ' , nargs = ' ? ' )
# PeerGetFile
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " peerGetFile " , help = ' Request and print a file content from peer ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' peer_ip ' , help = ' Peer ip ' )
action . add_argument ( ' peer_port ' , help = ' Peer port ' )
action . add_argument ( ' site ' , help = ' Site address ' )
action . add_argument ( ' filename ' , help = ' File name to request ' )
2015-07-25 13:38:58 +02:00
action . add_argument ( ' --benchmark ' , help = ' Request file 10x then displays the total time ' , action = ' store_true ' )
2015-07-12 20:36:46 +02:00
2015-07-25 13:38:58 +02:00
# PeerCmd
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " peerCmd " , help = ' Request and print a file content from peer ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' peer_ip ' , help = ' Peer ip ' )
action . add_argument ( ' peer_port ' , help = ' Peer port ' )
action . add_argument ( ' cmd ' , help = ' Command to execute ' )
action . add_argument ( ' parameters ' , help = ' Parameters to command ' , nargs = ' ? ' )
# CryptSign
2015-07-17 00:28:43 +02:00
action = self . subparsers . add_parser ( " cryptSign " , help = ' Sign message using Bitcoin private key ' )
2015-07-12 20:36:46 +02:00
action . add_argument ( ' message ' , help = ' Message to sign ' )
action . add_argument ( ' privatekey ' , help = ' Private key ' )
2017-10-28 02:39:49 +02:00
# Crypt Verify
action = self . subparsers . add_parser ( " cryptVerify " , help = ' Verify message using Bitcoin public address ' )
action . add_argument ( ' message ' , help = ' Message to verify ' )
action . add_argument ( ' sign ' , help = ' Signiture for message ' )
action . add_argument ( ' address ' , help = ' Signer \' s address ' )
2018-03-19 02:58:38 +01:00
# Crypt GetPrivatekey
action = self . subparsers . add_parser ( " cryptGetPrivatekey " , help = ' Generate a privatekey from master seed ' )
action . add_argument ( ' master_seed ' , help = ' Source master seed ' )
action . add_argument ( ' site_address_index ' , help = ' Site address index ' , type = int )
2017-09-25 18:09:59 +02:00
action = self . subparsers . add_parser ( " getConfig " , help = ' Return json-encoded info ' )
2017-10-28 02:40:42 +02:00
action = self . subparsers . add_parser ( " testConnection " , help = ' Testing ' )
2018-01-28 16:44:52 +01:00
action = self . subparsers . add_parser ( " testAnnounce " , help = ' Testing ' )
2017-09-25 18:09:59 +02:00
2019-11-19 02:14:29 +01:00
self . test_parser = self . subparsers . add_parser ( " test " , help = ' Run a test ' )
self . test_parser . add_argument ( ' test_name ' , help = ' Test name ' , nargs = " ? " )
2019-11-25 14:50:16 +01:00
# self.test_parser.add_argument('--benchmark', help='Run the tests multiple times to measure the performance', action='store_true')
2015-07-12 20:36:46 +02:00
# Config parameters
2016-03-06 00:55:50 +01:00
self . parser . add_argument ( ' --verbose ' , help = ' More detailed logging ' , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --debug ' , help = ' Debug mode ' , action = ' store_true ' )
2019-08-12 17:58:23 +02:00
self . parser . add_argument ( ' --silent ' , help = ' Only log errors to terminal output ' , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --debug_socket ' , help = ' Debug socket connections ' , action = ' store_true ' )
2019-08-20 10:16:35 +02:00
self . parser . add_argument ( ' --merge_media ' , help = ' Merge all.js and all.css ' , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
2015-09-02 19:15:55 +02:00
self . parser . add_argument ( ' --batch ' , help = " Batch mode (No interactive input for commands) " , action = ' store_true ' )
2020-02-20 17:25:06 +01:00
self . parser . add_argument ( ' --start_dir ' , help = ' Path of working dir for variable content (data, log, .conf) ' , default = self . start_dir , metavar = " path " )
2017-01-09 01:28:50 +01:00
self . parser . add_argument ( ' --config_file ' , help = ' Path of config file ' , default = config_file , metavar = " path " )
self . parser . add_argument ( ' --data_dir ' , help = ' Path of data directory ' , default = data_dir , metavar = " path " )
2018-11-08 01:32:31 +01:00
2019-08-12 17:58:23 +02:00
self . parser . add_argument ( ' --console_log_level ' , help = ' Level of logging to console ' , default = " default " , choices = [ " default " , " DEBUG " , " INFO " , " ERROR " , " off " ] )
2017-01-09 01:28:50 +01:00
self . parser . add_argument ( ' --log_dir ' , help = ' Path of logging directory ' , default = log_dir , metavar = " path " )
2019-08-12 17:58:23 +02:00
self . parser . add_argument ( ' --log_level ' , help = ' Level of logging to file ' , default = " DEBUG " , choices = [ " DEBUG " , " INFO " , " ERROR " , " off " ] )
2018-11-08 01:32:31 +01:00
self . parser . add_argument ( ' --log_rotate ' , help = ' Log rotate interval ' , default = " daily " , choices = [ " hourly " , " daily " , " weekly " , " off " ] )
self . parser . add_argument ( ' --log_rotate_backup_count ' , help = ' Log rotate backup count ' , default = 5 , type = int )
2015-07-17 00:28:43 +02:00
2016-11-18 20:00:15 +01:00
self . parser . add_argument ( ' --language ' , help = ' Web interface language ' , default = language , metavar = ' language ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --ui_ip ' , help = ' Web interface bind address ' , default = " 127.0.0.1 " , metavar = ' ip ' )
self . parser . add_argument ( ' --ui_port ' , help = ' Web interface bind port ' , default = 43110 , type = int , metavar = ' port ' )
self . parser . add_argument ( ' --ui_restrict ' , help = ' Restrict web access ' , default = False , metavar = ' ip ' , nargs = ' * ' )
2017-06-15 19:48:01 +02:00
self . parser . add_argument ( ' --ui_host ' , help = ' Allow access using this hosts ' , metavar = ' host ' , nargs = ' * ' )
2018-06-02 14:17:10 +02:00
self . parser . add_argument ( ' --ui_trans_proxy ' , help = ' Allow access using a transparent proxy ' , action = ' store_true ' )
2017-06-15 19:48:01 +02:00
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --open_browser ' , help = ' Open homepage in web browser automatically ' ,
nargs = ' ? ' , const = " default_browser " , metavar = ' browser_name ' )
2022-02-02 13:19:47 +01:00
self . parser . add_argument ( ' --homepage ' , help = ' Web interface Homepage ' , default = ' 126NXcevn1AUehWFZLTBw7FrX1crEizQdr ' ,
2016-12-04 18:57:08 +01:00
metavar = ' address ' )
2022-02-02 13:19:47 +01:00
# self.parser.add_argument('--updatesite', help='Source code update site', default='1uPDaT3uSyWAPdCv1WkMb5hBQjWSNNACf',
# metavar='address')
2022-01-24 03:05:41 +01:00
self . parser . add_argument ( ' --admin_pages ' , help = ' Pages with admin privileges ' , default = [ ] , metavar = ' address ' , nargs = ' * ' )
2019-04-04 13:29:11 +02:00
self . parser . add_argument ( ' --dist_type ' , help = ' Type of installed distribution ' , default = ' source ' )
2017-05-23 12:41:37 +02:00
self . parser . add_argument ( ' --size_limit ' , help = ' Default site size limit in MB ' , default = 10 , type = int , metavar = ' limit ' )
self . parser . add_argument ( ' --file_size_limit ' , help = ' Maximum per file size limit in MB ' , default = 10 , type = int , metavar = ' limit ' )
2017-02-27 00:03:10 +01:00
self . parser . add_argument ( ' --connected_limit ' , help = ' Max connected peer per site ' , default = 8 , type = int , metavar = ' connected_limit ' )
2018-01-27 12:20:40 +01:00
self . parser . add_argument ( ' --global_connected_limit ' , help = ' Max connections ' , default = 512 , type = int , metavar = ' global_connected_limit ' )
2017-02-27 00:02:56 +01:00
self . parser . add_argument ( ' --workers ' , help = ' Download workers per site ' , default = 5 , type = int , metavar = ' workers ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --fileserver_ip ' , help = ' FileServer bind address ' , default = " * " , metavar = ' ip ' )
2018-04-03 14:45:04 +02:00
self . parser . add_argument ( ' --fileserver_port ' , help = ' FileServer bind port (0: randomize) ' , default = 0 , type = int , metavar = ' port ' )
self . parser . add_argument ( ' --fileserver_port_range ' , help = ' FileServer randomization range ' , default = " 10000-40000 " , metavar = ' port ' )
2019-01-23 02:13:13 +01:00
self . parser . add_argument ( ' --fileserver_ip_type ' , help = ' FileServer ip type ' , default = " dual " , choices = [ " ipv4 " , " ipv6 " , " dual " ] )
2017-02-16 20:56:07 +01:00
self . parser . add_argument ( ' --ip_local ' , help = ' My local ips ' , default = ip_local , type = int , metavar = ' ip ' , nargs = ' * ' )
2019-01-25 01:26:50 +01:00
self . parser . add_argument ( ' --ip_external ' , help = ' Set reported external ip (tested on start if None) ' , metavar = ' ip ' , nargs = ' * ' )
2019-04-15 15:06:25 +02:00
self . parser . add_argument ( ' --offline ' , help = ' Disable network communication ' , action = ' store_true ' )
2017-02-16 20:56:07 +01:00
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --disable_udp ' , help = ' Disable UDP connections ' , action = ' store_true ' )
self . parser . add_argument ( ' --proxy ' , help = ' Socks proxy address ' , metavar = ' ip:port ' )
2017-04-14 11:13:29 +02:00
self . parser . add_argument ( ' --bind ' , help = ' Bind outgoing sockets to this address ' , metavar = ' ip ' )
2015-09-10 23:25:09 +02:00
self . parser . add_argument ( ' --trackers ' , help = ' Bootstraping torrent trackers ' , default = trackers , metavar = ' protocol://address ' , nargs = ' * ' )
2019-08-07 14:12:45 +02:00
self . parser . add_argument ( ' --trackers_file ' , help = ' Load torrent trackers dynamically from a file ' , metavar = ' path ' , nargs = ' * ' )
2018-07-16 01:47:49 +02:00
self . parser . add_argument ( ' --trackers_proxy ' , help = ' Force use proxy to connect to trackers (disable, tor, ip:port) ' , default = " disable " )
2019-03-16 02:45:06 +01:00
self . parser . add_argument ( ' --use_libsecp256k1 ' , help = ' Use Libsecp256k1 liblary for speedup ' , type = ' bool ' , choices = [ True , False ] , default = True )
self . parser . add_argument ( ' --use_openssl ' , help = ' Use OpenSSL liblary for speedup ' , type = ' bool ' , choices = [ True , False ] , default = True )
2020-02-20 17:23:00 +01:00
self . parser . add_argument ( ' --openssl_lib_file ' , help = ' Path for OpenSSL library file (default: detect) ' , default = argparse . SUPPRESS , metavar = " path " )
self . parser . add_argument ( ' --openssl_bin_file ' , help = ' Path for OpenSSL binary file (default: detect) ' , default = argparse . SUPPRESS , metavar = " path " )
2016-03-19 18:05:49 +01:00
self . parser . add_argument ( ' --disable_db ' , help = ' Disable database updating ' , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --disable_encryption ' , help = ' Disable connection encryption ' , action = ' store_true ' )
2018-03-14 22:22:45 +01:00
self . parser . add_argument ( ' --force_encryption ' , help = " Enforce encryption to all peer connections " , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --disable_sslcompression ' , help = ' Disable SSL compression to save memory ' ,
type = ' bool ' , choices = [ True , False ] , default = True )
Version 0.3.5, Rev830, Full Tor mode support with hidden services, Onion stats in Sidebar, GeoDB download fix using Tor, Gray out disabled sites in Stats page, Tor hidden service status in stat page, Benchmark sha256, Skyts tracker out expodie in, 2 new tracker using ZeroNet protocol, Keep SSL cert option between restarts, SSL Certificate pinning support for connections, Site lock support for connections, Certificate pinned connections using implicit SSL, Flood protection whitelist support, Foreign keys support for DB layer, Not support for SQL query helper, 0 length file get bugfix, Pex onion address support, Faster port testing, Faster uPnP port opening, Need connections more often on owned sites, Delay ZeroHello startup message if port check or Tor manager not ready yet, Use lockfiles to avoid double start, Save original socket on proxy monkey patching to get ability to connect localhost directly, Handle atomic write errors, Broken gevent https workaround helper, Rsa crypt functions, Plugin to Bootstrap using ZeroNet protocol
2016-01-05 00:20:52 +01:00
self . parser . add_argument ( ' --keep_ssl_cert ' , help = ' Disable new SSL cert generation on startup ' , action = ' store_true ' )
2016-03-06 02:17:58 +01:00
self . parser . add_argument ( ' --max_files_opened ' , help = ' Change maximum opened files allowed by OS to this value on startup ' ,
2016-03-12 23:11:08 +01:00
default = 2048 , type = int , metavar = ' limit ' )
2017-02-19 13:20:49 +01:00
self . parser . add_argument ( ' --stack_size ' , help = ' Change thread stack size ' , default = None , type = int , metavar = ' thread_stack_size ' )
2015-07-25 13:38:58 +02:00
self . parser . add_argument ( ' --use_tempfiles ' , help = ' Use temporary files when downloading (experimental) ' ,
type = ' bool ' , choices = [ True , False ] , default = False )
self . parser . add_argument ( ' --stream_downloads ' , help = ' Stream download directly to files (experimental) ' ,
type = ' bool ' , choices = [ True , False ] , default = False )
2015-08-06 00:51:25 +02:00
self . parser . add_argument ( " --msgpack_purepython " , help = ' Use less memory, but a bit more CPU power ' ,
2017-08-09 14:17:58 +02:00
type = ' bool ' , choices = [ True , False ] , default = False )
2017-01-07 01:06:24 +01:00
self . parser . add_argument ( " --fix_float_decimals " , help = ' Fix content.json modification date float precision on verification ' ,
type = ' bool ' , choices = [ True , False ] , default = fix_float_decimals )
2017-02-15 12:43:05 +01:00
self . parser . add_argument ( " --db_mode " , choices = [ " speed " , " security " ] , default = " speed " )
2019-11-25 14:50:16 +01:00
2019-11-19 02:15:00 +01:00
self . parser . add_argument ( ' --threads_fs_read ' , help = ' Number of threads for file read operations ' , default = 1 , type = int )
self . parser . add_argument ( ' --threads_fs_write ' , help = ' Number of threads for file write operations ' , default = 1 , type = int )
2019-11-25 14:37:55 +01:00
self . parser . add_argument ( ' --threads_crypt ' , help = ' Number of threads for cryptographic operations ' , default = 2 , type = int )
2019-11-30 02:14:54 +01:00
self . parser . add_argument ( ' --threads_db ' , help = ' Number of threads for database operations ' , default = 1 , type = int )
2019-11-25 14:50:16 +01:00
2017-07-31 14:39:21 +02:00
self . parser . add_argument ( " --download_optional " , choices = [ " manual " , " auto " ] , default = " manual " )
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --coffeescript_compiler ' , help = ' Coffeescript compiler for developing ' , default = coffeescript ,
metavar = ' executable_path ' )
Version 0.3.5, Rev830, Full Tor mode support with hidden services, Onion stats in Sidebar, GeoDB download fix using Tor, Gray out disabled sites in Stats page, Tor hidden service status in stat page, Benchmark sha256, Skyts tracker out expodie in, 2 new tracker using ZeroNet protocol, Keep SSL cert option between restarts, SSL Certificate pinning support for connections, Site lock support for connections, Certificate pinned connections using implicit SSL, Flood protection whitelist support, Foreign keys support for DB layer, Not support for SQL query helper, 0 length file get bugfix, Pex onion address support, Faster port testing, Faster uPnP port opening, Need connections more often on owned sites, Delay ZeroHello startup message if port check or Tor manager not ready yet, Use lockfiles to avoid double start, Save original socket on proxy monkey patching to get ability to connect localhost directly, Handle atomic write errors, Broken gevent https workaround helper, Rsa crypt functions, Plugin to Bootstrap using ZeroNet protocol
2016-01-05 00:20:52 +01:00
self . parser . add_argument ( ' --tor ' , help = ' enable: Use only for Tor peers, always: Use Tor for every connection ' , choices = [ " disable " , " enable " , " always " ] , default = ' enable ' )
self . parser . add_argument ( ' --tor_controller ' , help = ' Tor controller address ' , metavar = ' ip:port ' , default = ' 127.0.0.1:9051 ' )
self . parser . add_argument ( ' --tor_proxy ' , help = ' Tor proxy address ' , metavar = ' ip:port ' , default = ' 127.0.0.1:9050 ' )
2016-12-27 15:15:02 +01:00
self . parser . add_argument ( ' --tor_password ' , help = ' Tor controller password ' , metavar = ' password ' )
2018-04-28 21:42:57 +02:00
self . parser . add_argument ( ' --tor_use_bridges ' , help = ' Use obfuscated bridge relays to avoid Tor block ' , action = ' store_true ' )
2018-04-06 18:18:10 +02:00
self . parser . add_argument ( ' --tor_hs_limit ' , help = ' Maximum number of hidden services in Tor always mode ' , metavar = ' limit ' , type = int , default = 10 )
self . parser . add_argument ( ' --tor_hs_port ' , help = ' Hidden service port in Tor always mode ' , metavar = ' limit ' , type = int , default = 15441 )
Version 0.3.5, Rev830, Full Tor mode support with hidden services, Onion stats in Sidebar, GeoDB download fix using Tor, Gray out disabled sites in Stats page, Tor hidden service status in stat page, Benchmark sha256, Skyts tracker out expodie in, 2 new tracker using ZeroNet protocol, Keep SSL cert option between restarts, SSL Certificate pinning support for connections, Site lock support for connections, Certificate pinned connections using implicit SSL, Flood protection whitelist support, Foreign keys support for DB layer, Not support for SQL query helper, 0 length file get bugfix, Pex onion address support, Faster port testing, Faster uPnP port opening, Need connections more often on owned sites, Delay ZeroHello startup message if port check or Tor manager not ready yet, Use lockfiles to avoid double start, Save original socket on proxy monkey patching to get ability to connect localhost directly, Handle atomic write errors, Broken gevent https workaround helper, Rsa crypt functions, Plugin to Bootstrap using ZeroNet protocol
2016-01-05 00:20:52 +01:00
2015-07-17 00:28:43 +02:00
self . parser . add_argument ( ' --version ' , action = ' version ' , version = ' ZeroNet %s r %s ' % ( self . version , self . rev ) )
2017-06-15 19:49:00 +02:00
self . parser . add_argument ( ' --end ' , help = ' Stop multi value argument parsing ' , action = ' store_true ' )
2015-07-17 00:28:43 +02:00
return self . parser
2015-07-12 20:36:46 +02:00
2015-09-12 17:13:34 +02:00
def loadTrackersFile ( self ) :
2018-07-10 03:33:32 +02:00
if not self . trackers_file :
return None
self . trackers = self . arguments . trackers [ : ]
2019-08-07 14:12:45 +02:00
for trackers_file in self . trackers_file :
try :
if trackers_file . startswith ( " / " ) : # Absolute
trackers_file_path = trackers_file
elif trackers_file . startswith ( " {data_dir} " ) : # Relative to data_dir
trackers_file_path = trackers_file . replace ( " {data_dir} " , self . data_dir )
else : # Relative to zeronet.py
trackers_file_path = self . start_dir + " / " + trackers_file
for line in open ( trackers_file_path ) :
tracker = line . strip ( )
if " :// " in tracker and tracker not in self . trackers :
self . trackers . append ( tracker )
except Exception as err :
print ( " Error loading trackers file: %s " % err )
2018-07-10 03:33:32 +02:00
2015-09-12 17:13:34 +02:00
# Find arguments specified for current action
2015-07-12 20:36:46 +02:00
def getActionArguments ( self ) :
back = { }
arguments = self . parser . _subparsers . _group_actions [ 0 ] . choices [ self . action ] . _actions [ 1 : ] # First is --version
for argument in arguments :
back [ argument . dest ] = getattr ( self , argument . dest )
return back
2015-07-17 00:28:43 +02:00
# Try to find action from argv
2015-07-12 20:36:46 +02:00
def getAction ( self , argv ) :
2019-03-15 21:06:59 +01:00
actions = [ list ( action . choices . keys ( ) ) for action in self . parser . _actions if action . dest == " action " ] [ 0 ] # Valid actions
2015-07-12 20:36:46 +02:00
found_action = False
2015-07-17 00:28:43 +02:00
for action in actions : # See if any in argv
2015-07-12 20:36:46 +02:00
if action in argv :
found_action = action
break
return found_action
2015-07-17 00:28:43 +02:00
# Move plugin parameters to end of argument list
def moveUnknownToEnd ( self , argv , default_action ) :
valid_actions = sum ( [ action . option_strings for action in self . parser . _actions ] , [ ] )
valid_parameters = [ ]
plugin_parameters = [ ]
plugin = False
for arg in argv :
if arg . startswith ( " -- " ) :
if arg not in valid_actions :
plugin = True
else :
plugin = False
elif arg == default_action :
plugin = False
if plugin :
plugin_parameters . append ( arg )
else :
valid_parameters . append ( arg )
return valid_parameters + plugin_parameters
2019-11-19 02:14:29 +01:00
def getParser ( self , argv ) :
action = self . getAction ( argv )
if not action :
return self . parser
else :
return self . subparsers . choices [ action ]
2015-07-17 00:28:43 +02:00
# Parse arguments from config file and command line
def parse ( self , silent = False , parse_config = True ) :
2019-11-19 02:14:29 +01:00
argv = self . argv [ : ] # Copy command line arguments
current_parser = self . getParser ( argv )
2015-07-17 00:28:43 +02:00
if silent : # Don't display messages or quit on unknown parameter
original_print_message = self . parser . _print_message
original_exit = self . parser . exit
2015-09-27 02:08:53 +02:00
def silencer ( parser , function_name ) :
2015-07-17 00:28:43 +02:00
parser . exited = True
return None
2019-11-19 02:14:29 +01:00
current_parser . exited = False
current_parser . _print_message = lambda * args , * * kwargs : silencer ( current_parser , " _print_message " )
current_parser . exit = lambda * args , * * kwargs : silencer ( current_parser , " exit " )
2015-07-17 00:28:43 +02:00
2017-03-06 15:28:37 +01:00
self . parseCommandline ( argv , silent ) # Parse argv
self . setAttributes ( )
2015-07-17 00:28:43 +02:00
if parse_config :
argv = self . parseConfig ( argv ) # Add arguments from config file
2017-03-06 15:28:37 +01:00
2015-07-17 00:28:43 +02:00
self . parseCommandline ( argv , silent ) # Parse argv
self . setAttributes ( )
2017-02-27 00:05:08 +01:00
if not silent :
if self . fileserver_ip != " * " and self . fileserver_ip not in self . ip_local :
self . ip_local . append ( self . fileserver_ip )
2017-02-16 20:56:07 +01:00
2015-07-17 00:28:43 +02:00
if silent : # Restore original functions
2019-11-19 02:14:29 +01:00
if current_parser . exited and self . action == " main " : # Argument parsing halted, don't start ZeroNet with main action
2015-07-17 00:28:43 +02:00
self . action = None
2019-11-19 02:14:29 +01:00
current_parser . _print_message = original_print_message
current_parser . exit = original_exit
2015-07-17 00:28:43 +02:00
2018-07-19 20:43:46 +02:00
self . loadTrackersFile ( )
2015-07-12 20:36:46 +02:00
# Parse command line arguments
2015-07-17 00:28:43 +02:00
def parseCommandline ( self , argv , silent = False ) :
2015-07-12 20:36:46 +02:00
# Find out if action is specificed on start
action = self . getAction ( argv )
2015-07-17 00:28:43 +02:00
if not action :
2017-06-15 19:49:00 +02:00
argv . append ( " --end " )
2015-07-12 20:36:46 +02:00
argv . append ( " main " )
2015-07-17 00:28:43 +02:00
action = " main "
argv = self . moveUnknownToEnd ( argv , action )
if silent :
res = self . parser . parse_known_args ( argv [ 1 : ] )
if res :
self . arguments = res [ 0 ]
else :
self . arguments = { }
else :
self . arguments = self . parser . parse_args ( argv [ 1 : ] )
2015-07-12 20:36:46 +02:00
# Parse config file
def parseConfig ( self , argv ) :
# Find config file path from parameters
if " --config_file " in argv :
Version 0.3.6, Rev879, Fix sidebar error on description missing, New trayicon, New favicon, Disable some functions on MultiUser proxies, New homepage, Replace only the last ? in SQL queries, Alwaays grant ADMIN permission to homepage site, Announce before publish if no peers, configSet, serverShutdown, ADMIN WebsocketAPI command, Stop Tor client before updating, Ignore peer ip packing error, Ignore db files from git, Fix safari ajax error when UiPassword enabled
2016-02-02 11:40:45 +01:00
self . config_file = argv [ argv . index ( " --config_file " ) + 1 ]
2015-07-12 20:36:46 +02:00
# Load config file
Version 0.3.6, Rev879, Fix sidebar error on description missing, New trayicon, New favicon, Disable some functions on MultiUser proxies, New homepage, Replace only the last ? in SQL queries, Alwaays grant ADMIN permission to homepage site, Announce before publish if no peers, configSet, serverShutdown, ADMIN WebsocketAPI command, Stop Tor client before updating, Ignore peer ip packing error, Ignore db files from git, Fix safari ajax error when UiPassword enabled
2016-02-02 11:40:45 +01:00
if os . path . isfile ( self . config_file ) :
2019-07-17 16:30:32 +02:00
config = configparser . RawConfigParser ( allow_no_value = True , strict = False )
Version 0.3.6, Rev879, Fix sidebar error on description missing, New trayicon, New favicon, Disable some functions on MultiUser proxies, New homepage, Replace only the last ? in SQL queries, Alwaays grant ADMIN permission to homepage site, Announce before publish if no peers, configSet, serverShutdown, ADMIN WebsocketAPI command, Stop Tor client before updating, Ignore peer ip packing error, Ignore db files from git, Fix safari ajax error when UiPassword enabled
2016-02-02 11:40:45 +01:00
config . read ( self . config_file )
2015-07-12 20:36:46 +02:00
for section in config . sections ( ) :
for key , val in config . items ( section ) :
2019-01-02 01:21:00 +01:00
if val == " True " :
val = None
2015-07-12 20:36:46 +02:00
if section != " global " : # If not global prefix key with section
key = section + " _ " + key
2018-07-10 03:37:38 +02:00
2019-01-02 02:31:04 +01:00
if key == " open_browser " : # Prefer config file value over cli argument
2019-08-11 11:18:55 +02:00
while " -- %s " % key in argv :
2019-01-02 02:31:04 +01:00
pos = argv . index ( " --open_browser " )
del argv [ pos : pos + 2 ]
2018-07-10 03:37:38 +02:00
argv_extend = [ " -- %s " % key ]
2015-07-12 20:36:46 +02:00
if val :
2015-09-12 17:13:34 +02:00
for line in val . strip ( ) . split ( " \n " ) : # Allow multi-line values
2018-07-10 03:37:38 +02:00
argv_extend . append ( line )
2019-01-29 02:54:56 +01:00
if " \n " in val :
argv_extend . append ( " --end " )
2018-07-10 03:37:38 +02:00
2019-01-02 02:31:04 +01:00
argv = argv [ : 1 ] + argv_extend + argv [ 1 : ]
2015-07-12 20:36:46 +02:00
return argv
2019-11-19 02:14:29 +01:00
# Return command line value of given argument
def getCmdlineValue ( self , key ) :
if key not in self . argv :
return None
argv_index = self . argv . index ( key )
if argv_index == len ( self . argv ) - 1 : # last arg, test not specified
return None
return self . argv [ argv_index + 1 ]
2015-07-12 20:36:46 +02:00
# Expose arguments as class attributes
def setAttributes ( self ) :
# Set attributes from arguments
2015-07-17 00:28:43 +02:00
if self . arguments :
args = vars ( self . arguments )
for key , val in args . items ( ) :
2018-07-10 03:45:33 +02:00
if type ( val ) is list :
val = val [ : ]
2020-02-20 17:23:00 +01:00
if key in ( " data_dir " , " log_dir " , " start_dir " , " openssl_bin_file " , " openssl_lib_file " ) :
if val :
val = val . replace ( " \\ " , " / " )
2015-07-17 00:28:43 +02:00
setattr ( self , key , val )
def loadPlugins ( self ) :
from Plugin import PluginManager
@PluginManager.acceptPlugins
class ConfigPlugin ( object ) :
def __init__ ( self , config ) :
2019-11-19 02:14:29 +01:00
self . argv = config . argv
2015-07-17 00:28:43 +02:00
self . parser = config . parser
2019-11-19 02:14:29 +01:00
self . subparsers = config . subparsers
self . test_parser = config . test_parser
self . getCmdlineValue = config . getCmdlineValue
2015-07-17 00:28:43 +02:00
self . createArguments ( )
def createArguments ( self ) :
pass
ConfigPlugin ( self )
2015-04-18 03:02:08 +02:00
2016-11-07 22:51:43 +01:00
def saveValue ( self , key , value ) :
if not os . path . isfile ( self . config_file ) :
content = " "
else :
content = open ( self . config_file ) . read ( )
lines = content . splitlines ( )
global_line_i = None
key_line_i = None
i = 0
for line in lines :
if line . strip ( ) == " [global] " :
global_line_i = i
2019-07-01 16:19:32 +02:00
if line . startswith ( key + " = " ) or line == key :
2016-11-07 22:51:43 +01:00
key_line_i = i
i + = 1
2018-07-10 04:00:16 +02:00
if key_line_i and len ( lines ) > key_line_i + 1 :
2018-07-10 03:45:57 +02:00
while True : # Delete previous multiline values
is_value_line = lines [ key_line_i + 1 ] . startswith ( " " ) or lines [ key_line_i + 1 ] . startswith ( " \t " )
if not is_value_line :
break
del lines [ key_line_i + 1 ]
2016-11-07 22:51:43 +01:00
if value is None : # Delete line
if key_line_i :
del lines [ key_line_i ]
2018-07-10 03:45:57 +02:00
2016-11-07 22:51:43 +01:00
else : # Add / update
2018-07-10 03:45:57 +02:00
if type ( value ) is list :
value_lines = [ " " ] + [ str ( line ) . replace ( " \n " , " " ) . replace ( " \r " , " " ) for line in value ]
else :
value_lines = [ str ( value ) . replace ( " \n " , " " ) . replace ( " \r " , " " ) ]
new_line = " %s = %s " % ( key , " \n " . join ( value_lines ) )
2016-11-07 22:51:43 +01:00
if key_line_i : # Already in the config, change the line
lines [ key_line_i ] = new_line
elif global_line_i is None : # No global section yet, append to end of file
lines . append ( " [global] " )
lines . append ( new_line )
else : # Has global section, append the line after it
lines . insert ( global_line_i + 1 , new_line )
open ( self . config_file , " w " ) . write ( " \n " . join ( lines ) )
2015-04-18 03:02:08 +02:00
2017-09-25 18:09:59 +02:00
def getServerInfo ( self ) :
from Plugin import PluginManager
2019-04-15 12:31:33 +02:00
import main
2017-09-25 18:09:59 +02:00
info = {
" platform " : sys . platform ,
" fileserver_ip " : self . fileserver_ip ,
" fileserver_port " : self . fileserver_port ,
" ui_ip " : self . ui_ip ,
" ui_port " : self . ui_port ,
" version " : self . version ,
" rev " : self . rev ,
" language " : self . language ,
" debug " : self . debug ,
2017-09-22 14:55:41 +02:00
" plugins " : PluginManager . plugin_manager . plugin_names ,
2020-02-20 17:23:00 +01:00
2017-09-22 14:55:41 +02:00
" log_dir " : os . path . abspath ( self . log_dir ) ,
" data_dir " : os . path . abspath ( self . data_dir ) ,
" src_dir " : os . path . dirname ( os . path . abspath ( __file__ ) )
2017-09-25 18:09:59 +02:00
}
try :
2019-04-15 12:31:33 +02:00
info [ " ip_external " ] = main . file_server . port_opened
info [ " tor_enabled " ] = main . file_server . tor_manager . enabled
info [ " tor_status " ] = main . file_server . tor_manager . status
2019-05-21 15:53:53 +02:00
except Exception :
2017-09-25 18:09:59 +02:00
pass
return info
2018-11-08 01:32:31 +01:00
def initConsoleLogger ( self ) :
if self . action == " main " :
format = ' [ %(asctime)s ] %(name)s %(message)s '
else :
format = ' %(name)s %(message)s '
2019-08-12 17:58:23 +02:00
if self . console_log_level == " default " :
if self . silent :
level = logging . ERROR
elif self . debug :
level = logging . DEBUG
else :
level = logging . INFO
2018-11-08 01:32:31 +01:00
else :
2019-08-12 17:58:23 +02:00
level = logging . getLevelName ( self . console_log_level )
2018-11-08 01:32:31 +01:00
console_logger = logging . StreamHandler ( )
console_logger . setFormatter ( logging . Formatter ( format , " % H: % M: % S " ) )
console_logger . setLevel ( level )
logging . getLogger ( ' ' ) . addHandler ( console_logger )
def initFileLogger ( self ) :
if self . action == " main " :
log_file_path = " %s /debug.log " % self . log_dir
else :
log_file_path = " %s /cmd.log " % self . log_dir
2019-03-16 02:44:22 +01:00
2018-11-08 01:32:31 +01:00
if self . log_rotate == " off " :
2019-03-16 02:44:22 +01:00
file_logger = logging . FileHandler ( log_file_path , " w " , " utf-8 " )
2018-11-08 01:32:31 +01:00
else :
when_names = { " weekly " : " w " , " daily " : " d " , " hourly " : " h " }
file_logger = logging . handlers . TimedRotatingFileHandler (
2019-03-16 02:44:22 +01:00
log_file_path , when = when_names [ self . log_rotate ] , interval = 1 , backupCount = self . log_rotate_backup_count ,
encoding = " utf8 "
2018-11-08 01:32:31 +01:00
)
2019-03-16 02:44:22 +01:00
if os . path . isfile ( log_file_path ) :
file_logger . doRollover ( ) # Always start with empty log file
2018-11-08 01:32:31 +01:00
file_logger . setFormatter ( logging . Formatter ( ' [ %(asctime)s ] %(levelname)-8s %(name)s %(message)s ' ) )
file_logger . setLevel ( logging . getLevelName ( self . log_level ) )
logging . getLogger ( ' ' ) . setLevel ( logging . getLevelName ( self . log_level ) )
logging . getLogger ( ' ' ) . addHandler ( file_logger )
2019-08-12 17:58:23 +02:00
def initLogging ( self , console_logging = None , file_logging = None ) :
if console_logging == None :
console_logging = self . console_log_level != " off "
if file_logging == None :
file_logging = self . log_level != " off "
2018-11-08 01:32:31 +01:00
# Create necessary files and dirs
if not os . path . isdir ( self . log_dir ) :
os . mkdir ( self . log_dir )
try :
os . chmod ( self . log_dir , stat . S_IRUSR | stat . S_IWUSR | stat . S_IXUSR )
except Exception as err :
2019-03-15 21:06:59 +01:00
print ( " Can ' t change permission of %s : %s " % ( self . log_dir , err ) )
2018-11-08 01:32:31 +01:00
# Make warning hidden from console
logging . WARNING = 15 # Don't display warnings if not in debug mode
logging . addLevelName ( 15 , " WARNING " )
logging . getLogger ( ' ' ) . name = " - " # Remove root prefix
2020-09-09 18:29:24 +02:00
self . error_logger = ErrorLogHandler ( )
self . error_logger . setLevel ( logging . getLevelName ( " ERROR " ) )
logging . getLogger ( ' ' ) . addHandler ( self . error_logger )
2019-07-10 03:12:56 +02:00
if console_logging :
self . initConsoleLogger ( )
if file_logging :
self . initFileLogger ( )
2018-11-08 01:32:31 +01:00
2020-09-09 18:29:24 +02:00
class ErrorLogHandler ( logging . StreamHandler ) :
def __init__ ( self ) :
self . lines = [ ]
return super ( ) . __init__ ( )
def emit ( self , record ) :
self . lines . append ( [ time . time ( ) , record . levelname , self . format ( record ) ] )
def onNewRecord ( self , record ) :
pass
2019-07-04 14:39:41 +02:00
config = Config ( sys . argv )