in process of refactoring onionr.py

This commit is contained in:
Kevin Froman 2019-03-07 19:08:06 -06:00
parent 4d2a1cab1e
commit e0a18e2adf
6 changed files with 491 additions and 401 deletions

View File

@ -35,6 +35,7 @@ from netcontroller import NetController
from onionrblockapi import Block from onionrblockapi import Block
import onionrproofs, onionrexceptions, communicator import onionrproofs, onionrexceptions, communicator
from onionrusers import onionrusers from onionrusers import onionrusers
import onionrcommands as commands # Many command definitions are here
try: try:
from urllib3.contrib.socks import SOCKSProxyManager from urllib3.contrib.socks import SOCKSProxyManager
@ -128,126 +129,8 @@ class Onionr:
if type(config.get('client.api_version')) is type(None): if type(config.get('client.api_version')) is type(None):
config.set('client.api_version', API_VERSION, savefile=True) config.set('client.api_version', API_VERSION, savefile=True)
self.cmds = { self.cmds = commands.get_commands(self)
'': self.showHelpSuggestion, self.cmdhelp = commands.cmd_help
'help': self.showHelp,
'version': self.version,
'config': self.configure,
'start': self.start,
'stop': self.killDaemon,
'status': self.showStats,
'statistics': self.showStats,
'stats': self.showStats,
'details' : self.showDetails,
'detail' : self.showDetails,
'show-details' : self.showDetails,
'show-detail' : self.showDetails,
'showdetails' : self.showDetails,
'showdetail' : self.showDetails,
'get-details' : self.showDetails,
'get-detail' : self.showDetails,
'getdetails' : self.showDetails,
'getdetail' : self.showDetails,
'enable-plugin': self.enablePlugin,
'enplugin': self.enablePlugin,
'enableplugin': self.enablePlugin,
'enmod': self.enablePlugin,
'disable-plugin': self.disablePlugin,
'displugin': self.disablePlugin,
'disableplugin': self.disablePlugin,
'dismod': self.disablePlugin,
'reload-plugin': self.reloadPlugin,
'reloadplugin': self.reloadPlugin,
'reload-plugins': self.reloadPlugin,
'reloadplugins': self.reloadPlugin,
'create-plugin': self.createPlugin,
'createplugin': self.createPlugin,
'plugin-create': self.createPlugin,
'listkeys': self.listKeys,
'list-keys': self.listKeys,
'addpeer': self.addPeer,
'add-peer': self.addPeer,
'add-address': self.addAddress,
'add-addr': self.addAddress,
'addaddr': self.addAddress,
'addaddress': self.addAddress,
'list-peers': self.listPeers,
'blacklist-block': self.banBlock,
'add-file': self.addFile,
'addfile': self.addFile,
'addhtml': self.addWebpage,
'add-html': self.addWebpage,
'add-site': self.addWebpage,
'addsite': self.addWebpage,
'openhome': self.openHome,
'open-home': self.openHome,
'export-block': self.exportBlock,
'exportblock': self.exportBlock,
'get-file': self.getFile,
'getfile': self.getFile,
'listconn': self.listConn,
'list-conn': self.listConn,
'import-blocks': self.onionrUtils.importNewBlocks,
'importblocks': self.onionrUtils.importNewBlocks,
'introduce': self.onionrCore.introduceNode,
'connect': self.addAddress,
'pex': self.doPEX,
'getpassword': self.printWebPassword,
'get-password': self.printWebPassword,
'getpwd': self.printWebPassword,
'get-pwd': self.printWebPassword,
'getpass': self.printWebPassword,
'get-pass': self.printWebPassword,
'getpasswd': self.printWebPassword,
'get-passwd': self.printWebPassword,
'friend': self.friendCmd,
'add-id': self.addID,
'change-id': self.changeID
}
self.cmdhelp = {
'help': 'Displays this Onionr help menu',
'version': 'Displays the Onionr version',
'config': 'Configures something and adds it to the file',
'start': 'Starts the Onionr daemon',
'stop': 'Stops the Onionr daemon',
'stats': 'Displays node statistics',
'details': 'Displays the web password, public key, and human readable public key',
'enable-plugin': 'Enables and starts a plugin',
'disable-plugin': 'Disables and stops a plugin',
'reload-plugin': 'Reloads a plugin',
'create-plugin': 'Creates directory structure for a plugin',
'add-peer': 'Adds a peer to database',
'list-peers': 'Displays a list of peers',
'add-file': 'Create an Onionr block from a file',
'get-file': 'Get a file from Onionr blocks',
'import-blocks': 'import blocks from the disk (Onionr is transport-agnostic!)',
'listconn': 'list connected peers',
'pex': 'exchange addresses with peers (done automatically)',
'blacklist-block': 'deletes a block by hash and permanently removes it from your node',
'introduce': 'Introduce your node to the public Onionr network',
'friend': '[add|remove] [public key/id]',
'add-id': 'Generate a new ID (key pair)',
'change-id': 'Change active ID',
'open-home': 'Open your node\'s home/info screen'
}
# initialize plugins # initialize plugins
events.event('init', onionr = self, threaded = False) events.event('init', onionr = self, threaded = False)
@ -292,68 +175,16 @@ class Onionr:
self.doExport(bHash) self.doExport(bHash)
def showDetails(self): def showDetails(self):
details = { commands.onionrstatistics.show_details(self)
'Node Address' : self.get_hostname(),
'Web Password' : self.getWebPassword(),
'Public Key' : self.onionrCore._crypto.pubKey,
'Human-readable Public Key' : self.onionrCore._utils.getHumanReadableID()
}
for detail in details:
logger.info('%s%s: \n%s%s\n' % (logger.colors.fg.lightgreen, detail, logger.colors.fg.green, details[detail]), sensitive = True)
def openHome(self): def openHome(self):
try: commands.open_home(self)
url = self.onionrUtils.getClientAPIServer()
except FileNotFoundError:
logger.error('Onionr seems to not be running (could not get api host)')
else:
url = 'http://%s/#%s' % (url, config.get('client.webpassword'))
print('If Onionr does not open automatically, use this URL:', url)
webbrowser.open_new_tab(url)
def addID(self): def addID(self):
try: commands.pubkeymanager.add_ID(self)
sys.argv[2]
assert sys.argv[2] == 'true'
except (IndexError, AssertionError) as e:
newID = self.onionrCore._crypto.keyManager.addKey()[0]
else:
logger.warn('Deterministic keys require random and long passphrases.')
logger.warn('If a good passphrase is not used, your key can be easily stolen.')
logger.warn('You should use a series of hard to guess words, see this for reference: https://www.xkcd.com/936/')
pass1 = getpass.getpass(prompt='Enter at least %s characters: ' % (self.onionrCore._crypto.deterministicRequirement,))
pass2 = getpass.getpass(prompt='Confirm entry: ')
if self.onionrCore._crypto.safeCompare(pass1, pass2):
try:
logger.info('Generating deterministic key. This can take a while.')
newID, privKey = self.onionrCore._crypto.generateDeterministic(pass1)
except onionrexceptions.PasswordStrengthError:
logger.error('Must use at least 25 characters.')
sys.exit(1)
else:
logger.error('Passwords do not match.')
sys.exit(1)
self.onionrCore._crypto.keyManager.addKey(pubKey=newID,
privKey=privKey)
logger.info('Added ID: %s' % (self.onionrUtils.bytesToStr(newID),))
def changeID(self): def changeID(self):
try: commands.pubkeymanager.change_ID(self)
key = sys.argv[2]
except IndexError:
logger.error('Specify pubkey to use')
else:
if self.onionrUtils.validatePubKey(key):
if key in self.onionrCore._crypto.keyManager.getPubkeyList():
config.set('general.public_key', key)
config.save()
logger.info('Set active key to: %s' % (key,))
logger.info('Restart Onionr if it is running.')
else:
logger.error('That key does not exist')
else:
logger.error('Invalid key %s' % (key,))
def getCommands(self): def getCommands(self):
return self.cmds return self.cmds
@ -362,40 +193,7 @@ class Onionr:
'''List, add, or remove friend(s) '''List, add, or remove friend(s)
Changes their peer DB entry. Changes their peer DB entry.
''' '''
friend = '' commands.pubkeymanager.friend_command(self)
try:
# Get the friend command
action = sys.argv[2]
except IndexError:
logger.info('Syntax: friend add/remove/list [address]')
else:
action = action.lower()
if action == 'list':
# List out peers marked as our friend
for friend in onionrusers.OnionrUser.list_friends(self.onionrCore):
logger.info(friend.publicKey + ' - ' + friend.getName())
elif action in ('add', 'remove'):
try:
friend = sys.argv[3]
if not self.onionrUtils.validatePubKey(friend):
raise onionrexceptions.InvalidPubkey('Public key is invalid')
if friend not in self.onionrCore.listPeers():
raise onionrexceptions.KeyNotKnown
friend = onionrusers.OnionrUser(self.onionrCore, friend)
except IndexError:
logger.error('Friend ID is required.')
except onionrexceptions.KeyNotKnown:
self.onionrCore.addPeer(friend)
friend = onionrusers.OnionrUser(self.onionrCore, friend)
finally:
if action == 'add':
friend.setTrust(1)
logger.info('Added %s as friend.' % (friend.publicKey,))
else:
friend.setTrust(0)
logger.info('Removed %s as friend.' % (friend.publicKey,))
else:
logger.info('Syntax: friend add/remove/list [address]')
def deleteRunFiles(self): def deleteRunFiles(self):
try: try:
@ -579,27 +377,6 @@ class Onionr:
logger.warn("Unable to add address.") logger.warn("Unable to add address.")
return return
def addMessage(self, header="txt"):
'''
Broadcasts a message to the Onionr network
'''
while True:
try:
messageToAdd = logger.readline('Broadcast message to network: ')
if len(messageToAdd) >= 1:
break
except KeyboardInterrupt:
return
#addedHash = Block(type = 'txt', content = messageToAdd).save()
addedHash = self.onionrCore.insertBlock(messageToAdd)
if addedHash != None and addedHash != False and addedHash != "":
logger.info("Message inserted as as block %s" % addedHash)
else:
logger.error('Failed to insert block.', timestamp = False)
return
def enablePlugin(self): def enablePlugin(self):
''' '''
Enables and starts the given plugin Enables and starts the given plugin
@ -726,167 +503,19 @@ class Onionr:
''' '''
Starts the Onionr communication daemon Starts the Onionr communication daemon
''' '''
commands.daemonlaunch.daemon(self)
# remove runcheck if it exists
if os.path.isfile('data/.runcheck'):
logger.debug('Runcheck file found on daemon start, deleting in advance.')
os.remove('data/.runcheck')
Thread(target=api.API, args=(self, self.debug, API_VERSION)).start()
Thread(target=api.PublicAPI, args=[self.getClientApi()]).start()
try:
time.sleep(0)
except KeyboardInterrupt:
logger.debug('Got keyboard interrupt, shutting down...')
time.sleep(1)
self.onionrUtils.localCommand('shutdown')
apiHost = ''
while apiHost == '':
try:
with open(self.onionrCore.publicApiHostFile, 'r') as hostFile:
apiHost = hostFile.read()
except FileNotFoundError:
pass
time.sleep(0.5)
Onionr.setupConfig('data/', self = self)
if self._developmentMode:
logger.warn('DEVELOPMENT MODE ENABLED (NOT RECOMMENDED)', timestamp = False)
net = NetController(config.get('client.public.port', 59497), apiServerIP=apiHost)
logger.debug('Tor is starting...')
if not net.startTor():
self.onionrUtils.localCommand('shutdown')
sys.exit(1)
if len(net.myID) > 0 and config.get('general.security_level') == 0:
logger.debug('Started .onion service: %s' % (logger.colors.underline + net.myID))
else:
logger.debug('.onion service disabled')
logger.debug('Using public key: %s' % (logger.colors.underline + self.onionrCore._crypto.pubKey))
time.sleep(1)
self.onionrCore.torPort = net.socksPort
communicatorThread = Thread(target=communicator.startCommunicator, args=(self, str(net.socksPort)))
communicatorThread.start()
while self.communicatorInst is None:
time.sleep(0.1)
# print nice header thing :)
if config.get('general.display_header', True):
self.header()
# print out debug info
self.version(verbosity = 5, function = logger.debug)
logger.debug('Python version %s' % platform.python_version())
logger.debug('Started communicator.')
events.event('daemon_start', onionr = self)
try:
while True:
time.sleep(3)
# Debug to print out used FDs (regular and net)
#proc = psutil.Process()
#print('api-files:',proc.open_files(), len(psutil.net_connections()))
# Break if communicator process ends, so we don't have left over processes
if self.communicatorInst.shutdown:
break
if self.killed:
break # Break out if sigterm for clean exit
except KeyboardInterrupt:
pass
finally:
self.onionrCore.daemonQueueAdd('shutdown')
self.onionrUtils.localCommand('shutdown')
net.killTor()
time.sleep(3)
self.deleteRunFiles()
return
def killDaemon(self): def killDaemon(self):
''' '''
Shutdown the Onionr daemon Shutdown the Onionr daemon
''' '''
commands.daemonlaunch.kill_daemon(self)
logger.warn('Stopping the running daemon...', timestamp = False)
try:
events.event('daemon_stop', onionr = self)
net = NetController(config.get('client.port', 59496))
try:
self.onionrCore.daemonQueueAdd('shutdown')
except sqlite3.OperationalError:
pass
net.killTor()
except Exception as e:
logger.error('Failed to shutdown daemon.', error = e, timestamp = False)
return
def showStats(self): def showStats(self):
''' '''
Displays statistics and exits Displays statistics and exits
''' '''
commands.onionrstatistics.show_stats(self)
try:
# define stats messages here
totalBlocks = len(self.onionrCore.getBlockList())
signedBlocks = len(Block.getBlocks(signed = True))
messages = {
# info about local client
'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if self.onionrUtils.isCommunicatorRunning(timeout = 9) else logger.colors.fg.red + 'Offline'),
# file and folder size stats
'div1' : True, # this creates a solid line across the screen, a div
'Total Block Size' : onionrutils.humanSize(onionrutils.size(self.dataDir + 'blocks/')),
'Total Plugin Size' : onionrutils.humanSize(onionrutils.size(self.dataDir + 'plugins/')),
'Log File Size' : onionrutils.humanSize(onionrutils.size(self.dataDir + 'output.log')),
# count stats
'div2' : True,
'Known Peers' : str(len(self.onionrCore.listPeers()) - 1),
'Enabled Plugins' : str(len(config.get('plugins.enabled', list()))) + ' / ' + str(len(os.listdir(self.dataDir + 'plugins/'))),
'Stored Blocks' : str(totalBlocks),
'Percent Blocks Signed' : str(round(100 * signedBlocks / max(totalBlocks, 1), 2)) + '%'
}
# color configuration
colors = {
'title' : logger.colors.bold,
'key' : logger.colors.fg.lightgreen,
'val' : logger.colors.fg.green,
'border' : logger.colors.fg.lightblue,
'reset' : logger.colors.reset
}
# pre-processing
maxlength = 0
width = self.getConsoleWidth()
for key, val in messages.items():
if not (type(val) is bool and val is True):
maxlength = max(len(key), maxlength)
prewidth = maxlength + len(' | ')
groupsize = width - prewidth - len('[+] ')
# generate stats table
logger.info(colors['title'] + 'Onionr v%s Statistics' % ONIONR_VERSION + colors['reset'])
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
for key, val in messages.items():
if not (type(val) is bool and val is True):
val = [str(val)[i:i + groupsize] for i in range(0, len(str(val)), groupsize)]
logger.info(colors['key'] + str(key).rjust(maxlength) + colors['reset'] + colors['border'] + ' | ' + colors['reset'] + colors['val'] + str(val.pop(0)) + colors['reset'])
for value in val:
logger.info(' ' * maxlength + colors['border'] + ' | ' + colors['reset'] + colors['val'] + str(value) + colors['reset'])
else:
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
except Exception as e:
logger.error('Failed to generate statistics table.', error = e, timestamp = False)
return
def showHelp(self, command = None): def showHelp(self, command = None):
''' '''
@ -967,24 +596,7 @@ class Onionr:
''' '''
Adds a file to the onionr network Adds a file to the onionr network
''' '''
commands.filecommands.add_file(self, singleBlock, blockType)
if len(sys.argv) >= 3:
filename = sys.argv[2]
contents = None
if not os.path.exists(filename):
logger.error('That file does not exist. Improper path (specify full path)?')
return
logger.info('Adding file... this might take a long time.')
try:
with open(filename, 'rb') as singleFile:
blockhash = self.onionrCore.insertBlock(base64.b64encode(singleFile.read()), header=blockType)
if len(blockhash) > 0:
logger.info('File %s saved in block %s' % (filename, blockhash))
except:
logger.error('Failed to save file in block.', timestamp = False)
else:
logger.error('%s add-file <filename>' % sys.argv[0], timestamp = False)
def setupConfig(dataDir, self = None): def setupConfig(dataDir, self = None):
data_exists = os.path.exists(dataDir) data_exists = os.path.exists(dataDir)

View File

@ -0,0 +1,155 @@
'''
Onionr - P2P Anonymous Storage Network
This module defines commands for CLI usage
'''
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
import webbrowser
import logger
from . import pubkeymanager, onionrstatistics, daemonlaunch, filecommands
def open_home(o_inst):
try:
url = o_inst.onionrUtils.getClientAPIServer()
except FileNotFoundError:
logger.error('Onionr seems to not be running (could not get api host)')
else:
url = 'http://%s/#%s' % (url, config.get('client.webpassword'))
print('If Onionr does not open automatically, use this URL:', url)
webbrowser.open_new_tab(url)
def get_commands(onionr_inst):
return {'': onionr_inst.showHelpSuggestion,
'help': onionr_inst.showHelp,
'version': onionr_inst.version,
'config': onionr_inst.configure,
'start': onionr_inst.start,
'stop': onionr_inst.killDaemon,
'status': onionr_inst.showStats,
'statistics': onionr_inst.showStats,
'stats': onionr_inst.showStats,
'details' : onionr_inst.showDetails,
'detail' : onionr_inst.showDetails,
'show-details' : onionr_inst.showDetails,
'show-detail' : onionr_inst.showDetails,
'showdetails' : onionr_inst.showDetails,
'showdetail' : onionr_inst.showDetails,
'get-details' : onionr_inst.showDetails,
'get-detail' : onionr_inst.showDetails,
'getdetails' : onionr_inst.showDetails,
'getdetail' : onionr_inst.showDetails,
'enable-plugin': onionr_inst.enablePlugin,
'enplugin': onionr_inst.enablePlugin,
'enableplugin': onionr_inst.enablePlugin,
'enmod': onionr_inst.enablePlugin,
'disable-plugin': onionr_inst.disablePlugin,
'displugin': onionr_inst.disablePlugin,
'disableplugin': onionr_inst.disablePlugin,
'dismod': onionr_inst.disablePlugin,
'reload-plugin': onionr_inst.reloadPlugin,
'reloadplugin': onionr_inst.reloadPlugin,
'reload-plugins': onionr_inst.reloadPlugin,
'reloadplugins': onionr_inst.reloadPlugin,
'create-plugin': onionr_inst.createPlugin,
'createplugin': onionr_inst.createPlugin,
'plugin-create': onionr_inst.createPlugin,
'listkeys': onionr_inst.listKeys,
'list-keys': onionr_inst.listKeys,
'addpeer': onionr_inst.addPeer,
'add-peer': onionr_inst.addPeer,
'add-address': onionr_inst.addAddress,
'add-addr': onionr_inst.addAddress,
'addaddr': onionr_inst.addAddress,
'addaddress': onionr_inst.addAddress,
'list-peers': onionr_inst.listPeers,
'blacklist-block': onionr_inst.banBlock,
'add-file': onionr_inst.addFile,
'addfile': onionr_inst.addFile,
'addhtml': onionr_inst.addWebpage,
'add-html': onionr_inst.addWebpage,
'add-site': onionr_inst.addWebpage,
'addsite': onionr_inst.addWebpage,
'openhome': onionr_inst.openHome,
'open-home': onionr_inst.openHome,
'export-block': onionr_inst.exportBlock,
'exportblock': onionr_inst.exportBlock,
'get-file': onionr_inst.getFile,
'getfile': onionr_inst.getFile,
'listconn': onionr_inst.listConn,
'list-conn': onionr_inst.listConn,
'import-blocks': onionr_inst.onionrUtils.importNewBlocks,
'importblocks': onionr_inst.onionrUtils.importNewBlocks,
'introduce': onionr_inst.onionrCore.introduceNode,
'connect': onionr_inst.addAddress,
'pex': onionr_inst.doPEX,
'getpassword': onionr_inst.printWebPassword,
'get-password': onionr_inst.printWebPassword,
'getpwd': onionr_inst.printWebPassword,
'get-pwd': onionr_inst.printWebPassword,
'getpass': onionr_inst.printWebPassword,
'get-pass': onionr_inst.printWebPassword,
'getpasswd': onionr_inst.printWebPassword,
'get-passwd': onionr_inst.printWebPassword,
'friend': onionr_inst.friendCmd,
'addid': onionr_inst.addID,
'add-id': onionr_inst.addID,
'change-id': onionr_inst.changeID
}
cmd_help = {
'help': 'Displays this Onionr help menu',
'version': 'Displays the Onionr version',
'config': 'Configures something and adds it to the file',
'start': 'Starts the Onionr daemon',
'stop': 'Stops the Onionr daemon',
'stats': 'Displays node statistics',
'details': 'Displays the web password, public key, and human readable public key',
'enable-plugin': 'Enables and starts a plugin',
'disable-plugin': 'Disables and stops a plugin',
'reload-plugin': 'Reloads a plugin',
'create-plugin': 'Creates directory structure for a plugin',
'add-peer': 'Adds a peer to database',
'list-peers': 'Displays a list of peers',
'add-file': 'Create an Onionr block from a file',
'get-file': 'Get a file from Onionr blocks',
'import-blocks': 'import blocks from the disk (Onionr is transport-agnostic!)',
'listconn': 'list connected peers',
'pex': 'exchange addresses with peers (done automatically)',
'blacklist-block': 'deletes a block by hash and permanently removes it from your node',
'introduce': 'Introduce your node to the public Onionr network',
'friend': '[add|remove] [public key/id]',
'add-id': 'Generate a new ID (key pair)',
'change-id': 'Change active ID',
'open-home': 'Open your node\'s home/info screen'
}

View File

@ -0,0 +1,105 @@
import os, time, sys, platform, sqlite3
from threading import Thread
import onionr, api, logger, communicator
import onionrevents as events
from netcontroller import NetController
def daemon(o_inst):
'''
Starts the Onionr communication daemon
'''
# remove runcheck if it exists
if os.path.isfile('data/.runcheck'):
logger.debug('Runcheck file found on daemon start, deleting in advance.')
os.remove('data/.runcheck')
Thread(target=api.API, args=(o_inst, o_inst.debug, onionr.API_VERSION)).start()
Thread(target=api.PublicAPI, args=[o_inst.getClientApi()]).start()
try:
time.sleep(0)
except KeyboardInterrupt:
logger.debug('Got keyboard interrupt, shutting down...')
time.sleep(1)
o_inst.onionrUtils.localCommand('shutdown')
apiHost = ''
while apiHost == '':
try:
with open(o_inst.onionrCore.publicApiHostFile, 'r') as hostFile:
apiHost = hostFile.read()
except FileNotFoundError:
pass
time.sleep(0.5)
onionr.Onionr.setupConfig('data/', self = o_inst)
if o_inst._developmentMode:
logger.warn('DEVELOPMENT MODE ENABLED (NOT RECOMMENDED)', timestamp = False)
net = NetController(o_inst.onionrCore.config.get('client.public.port', 59497), apiServerIP=apiHost)
logger.debug('Tor is starting...')
if not net.startTor():
o_inst.onionrUtils.localCommand('shutdown')
sys.exit(1)
if len(net.myID) > 0 and o_inst.onionrCore.config.get('general.security_level') == 0:
logger.debug('Started .onion service: %s' % (logger.colors.underline + net.myID))
else:
logger.debug('.onion service disabled')
logger.debug('Using public key: %s' % (logger.colors.underline + o_inst.onionrCore._crypto.pubKey))
time.sleep(1)
o_inst.onionrCore.torPort = net.socksPort
communicatorThread = Thread(target=communicator.startCommunicator, args=(o_inst, str(net.socksPort)))
communicatorThread.start()
while o_inst.communicatorInst is None:
time.sleep(0.1)
# print nice header thing :)
if o_inst.onionrCore.config.get('general.display_header', True):
o_inst.header()
# print out debug info
o_inst.version(verbosity = 5, function = logger.debug)
logger.debug('Python version %s' % platform.python_version())
logger.debug('Started communicator.')
events.event('daemon_start', onionr = o_inst)
try:
while True:
time.sleep(3)
# Debug to print out used FDs (regular and net)
#proc = psutil.Process()
#print('api-files:',proc.open_files(), len(psutil.net_connections()))
# Break if communicator process ends, so we don't have left over processes
if o_inst.communicatorInst.shutdown:
break
if o_inst.killed:
break # Break out if sigterm for clean exit
except KeyboardInterrupt:
pass
finally:
o_inst.onionrCore.daemonQueueAdd('shutdown')
o_inst.onionrUtils.localCommand('shutdown')
net.killTor()
time.sleep(3)
o_inst.deleteRunFiles()
return
def kill_daemon(o_inst):
'''
Shutdown the Onionr daemon
'''
logger.warn('Stopping the running daemon...', timestamp = False)
try:
events.event('daemon_stop', onionr = o_inst)
net = NetController(o_inst.onionrCore.config.get('client.port', 59496))
try:
o_inst.onionrCore.daemonQueueAdd('shutdown')
except sqlite3.OperationalError:
pass
net.killTor()
except Exception as e:
logger.error('Failed to shutdown daemon.', error = e, timestamp = False)
return

View File

@ -0,0 +1,24 @@
import base64, sys, os
import logger
def add_file(o_inst, singleBlock=False, blockType='bin'):
'''
Adds a file to the onionr network
'''
if len(sys.argv) >= 3:
filename = sys.argv[2]
contents = None
if not os.path.exists(filename):
logger.error('That file does not exist. Improper path (specify full path)?')
return
logger.info('Adding file... this might take a long time.')
try:
with open(filename, 'rb') as singleFile:
blockhash = o_inst.onionrCore.insertBlock(base64.b64encode(singleFile.read()), header=blockType)
if len(blockhash) > 0:
logger.info('File %s saved in block %s' % (filename, blockhash))
except:
logger.error('Failed to save file in block.', timestamp = False)
else:
logger.error('%s add-file <filename>' % sys.argv[0], timestamp = False)

View File

@ -0,0 +1,93 @@
'''
Onionr - P2P Anonymous Storage Network
This module defines commands to show stats/details about the local node
'''
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
import os
import logger, onionrutils
from onionrblockapi import Block
import onionr
def show_stats(o_inst):
try:
# define stats messages here
totalBlocks = len(o_inst.onionrCore.getBlockList())
signedBlocks = len(Block.getBlocks(signed = True))
messages = {
# info about local client
'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if o_inst.onionrUtils.isCommunicatorRunning(timeout = 9) else logger.colors.fg.red + 'Offline'),
# file and folder size stats
'div1' : True, # this creates a solid line across the screen, a div
'Total Block Size' : onionrutils.humanSize(onionrutils.size(o_inst.dataDir + 'blocks/')),
'Total Plugin Size' : onionrutils.humanSize(onionrutils.size(o_inst.dataDir + 'plugins/')),
'Log File Size' : onionrutils.humanSize(onionrutils.size(o_inst.dataDir + 'output.log')),
# count stats
'div2' : True,
'Known Peers' : str(len(o_inst.onionrCore.listPeers()) - 1),
'Enabled Plugins' : str(len(o_inst.onionrCore.config.get('plugins.enabled', list()))) + ' / ' + str(len(os.listdir(o_inst.dataDir + 'plugins/'))),
'Stored Blocks' : str(totalBlocks),
'Percent Blocks Signed' : str(round(100 * signedBlocks / max(totalBlocks, 1), 2)) + '%'
}
# color configuration
colors = {
'title' : logger.colors.bold,
'key' : logger.colors.fg.lightgreen,
'val' : logger.colors.fg.green,
'border' : logger.colors.fg.lightblue,
'reset' : logger.colors.reset
}
# pre-processing
maxlength = 0
width = o_inst.getConsoleWidth()
for key, val in messages.items():
if not (type(val) is bool and val is True):
maxlength = max(len(key), maxlength)
prewidth = maxlength + len(' | ')
groupsize = width - prewidth - len('[+] ')
# generate stats table
logger.info(colors['title'] + 'Onionr v%s Statistics' % onionr.ONIONR_VERSION + colors['reset'])
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
for key, val in messages.items():
if not (type(val) is bool and val is True):
val = [str(val)[i:i + groupsize] for i in range(0, len(str(val)), groupsize)]
logger.info(colors['key'] + str(key).rjust(maxlength) + colors['reset'] + colors['border'] + ' | ' + colors['reset'] + colors['val'] + str(val.pop(0)) + colors['reset'])
for value in val:
logger.info(' ' * maxlength + colors['border'] + ' | ' + colors['reset'] + colors['val'] + str(value) + colors['reset'])
else:
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
logger.info(colors['border'] + '-' * (maxlength + 1) + '+' + colors['reset'])
except Exception as e:
logger.error('Failed to generate statistics table.', error = e, timestamp = False)
def show_details(o_inst):
details = {
'Node Address' : o_inst.get_hostname(),
'Web Password' : o_inst.getWebPassword(),
'Public Key' : o_inst.onionrCore._crypto.pubKey,
'Human-readable Public Key' : o_inst.onionrCore._utils.getHumanReadableID()
}
for detail in details:
logger.info('%s%s: \n%s%s\n' % (logger.colors.fg.lightgreen, detail, logger.colors.fg.green, details[detail]), sensitive = True)

View File

@ -0,0 +1,101 @@
'''
Onionr - P2P Anonymous Storage Network
This module defines ID-related CLI commands
'''
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
import sys
import logger
from onionrusers import onionrusers
def add_ID(o_inst):
try:
sys.argv[2]
assert sys.argv[2] == 'true'
except (IndexError, AssertionError) as e:
newID = o_inst.onionrCore._crypto.keyManager.addKey()[0]
else:
logger.warn('Deterministic keys require random and long passphrases.')
logger.warn('If a good passphrase is not used, your key can be easily stolen.')
logger.warn('You should use a series of hard to guess words, see this for reference: https://www.xkcd.com/936/')
pass1 = getpass.getpass(prompt='Enter at least %s characters: ' % (o_inst.onionrCore._crypto.deterministicRequirement,))
pass2 = getpass.getpass(prompt='Confirm entry: ')
if o_inst.onionrCore._crypto.safeCompare(pass1, pass2):
try:
logger.info('Generating deterministic key. This can take a while.')
newID, privKey = o_inst.onionrCore._crypto.generateDeterministic(pass1)
except onionrexceptions.PasswordStrengthError:
logger.error('Must use at least 25 characters.')
sys.exit(1)
else:
logger.error('Passwords do not match.')
sys.exit(1)
o_inst.onionrCore._crypto.keyManager.addKey(pubKey=newID,
privKey=privKey)
logger.info('Added ID: %s' % (o_inst.onionrUtils.bytesToStr(newID),))
def change_ID(o_inst):
try:
key = sys.argv[2]
except IndexError:
logger.error('Specify pubkey to use')
else:
if o_inst.onionrUtils.validatePubKey(key):
if key in o_inst.onionrCore._crypto.keyManager.getPubkeyList():
o_inst.onionrCore.config.set('general.public_key', key)
o_inst.onionrCore.config.save()
logger.info('Set active key to: %s' % (key,))
logger.info('Restart Onionr if it is running.')
else:
logger.error('That key does not exist')
else:
logger.error('Invalid key %s' % (key,))
def friend_command(o_inst):
friend = ''
try:
# Get the friend command
action = sys.argv[2]
except IndexError:
logger.info('Syntax: friend add/remove/list [address]')
else:
action = action.lower()
if action == 'list':
# List out peers marked as our friend
for friend in onionrusers.OnionrUser.list_friends(o_inst.onionrCore):
logger.info(friend.publicKey + ' - ' + friend.getName())
elif action in ('add', 'remove'):
try:
friend = sys.argv[3]
if not o_inst.onionrUtils.validatePubKey(friend):
raise onionrexceptions.InvalidPubkey('Public key is invalid')
if friend not in o_inst.onionrCore.listPeers():
raise onionrexceptions.KeyNotKnown
friend = onionrusers.OnionrUser(o_inst.onionrCore, friend)
except IndexError:
logger.error('Friend ID is required.')
except onionrexceptions.KeyNotKnown:
o_inst.onionrCore.addPeer(friend)
friend = onionrusers.OnionrUser(o_inst.onionrCore, friend)
finally:
if action == 'add':
friend.setTrust(1)
logger.info('Added %s as friend.' % (friend.publicKey,))
else:
friend.setTrust(0)
logger.info('Removed %s as friend.' % (friend.publicKey,))
else:
logger.info('Syntax: friend add/remove/list [address]')