fixed file bug, removed username setting

master
Kevin Froman 2019-01-16 23:31:56 -06:00
parent 1ebed8d606
commit 9429afba18
10 changed files with 40 additions and 59 deletions

View File

@ -82,6 +82,9 @@ class PublicAPI:
@app.before_request @app.before_request
def validateRequest(): def validateRequest():
'''Validate request has the correct hostname''' '''Validate request has the correct hostname'''
# If high security level, deny requests to public
if config.get('general.security_level', default=0) > 0:
abort(403)
if type(self.torAdder) is None and type(self.i2pAdder) is None: if type(self.torAdder) is None and type(self.i2pAdder) is None:
# abort if our hs addresses are not known # abort if our hs addresses are not known
abort(403) abort(403)
@ -248,6 +251,7 @@ class API:
bindPort = int(config.get('client.client.port', 59496)) bindPort = int(config.get('client.client.port', 59496))
self.bindPort = bindPort self.bindPort = bindPort
# Be extremely mindful of this
self.whitelistEndpoints = ('site', 'www', 'onionrhome', 'board', 'boardContent', 'sharedContent') self.whitelistEndpoints = ('site', 'www', 'onionrhome', 'board', 'boardContent', 'sharedContent')
self.clientToken = config.get('client.webpassword') self.clientToken = config.get('client.webpassword')

View File

@ -201,7 +201,7 @@ class OnionrCommunicatorDaemon:
else: else:
listLookupCommand += '?date=%s' % (lastLookupTime,) listLookupCommand += '?date=%s' % (lastLookupTime,)
try: try:
newBlocks = self.peerAction(peer, 'getblocklist') # get list of new block hashes newBlocks = self.peerAction(peer, listLookupCommand) # get list of new block hashes
except Exception as error: except Exception as error:
logger.warn('Could not get new blocks from %s.' % peer, error = error) logger.warn('Could not get new blocks from %s.' % peer, error = error)
newBlocks = False newBlocks = False
@ -241,7 +241,8 @@ class OnionrCommunicatorDaemon:
break break
self.currentDownloading.append(blockHash) # So we can avoid concurrent downloading in other threads of same block self.currentDownloading.append(blockHash) # So we can avoid concurrent downloading in other threads of same block
peerUsed = self.pickOnlinePeer() peerUsed = self.pickOnlinePeer()
logger.info("Attempting to download %s from %s..." % (blockHash[:12], peerUsed)) if not self.shutdown and peerUsed.strip() != '':
logger.info("Attempting to download %s from %s..." % (blockHash[:12], peerUsed))
content = self.peerAction(peerUsed, 'getdata/' + blockHash) # block content from random peer (includes metadata) content = self.peerAction(peerUsed, 'getdata/' + blockHash) # block content from random peer (includes metadata)
if content != False and len(content) > 0: if content != False and len(content) > 0:
try: try:
@ -506,7 +507,6 @@ class OnionrCommunicatorDaemon:
logger.debug('Status check; looks good.') logger.debug('Status check; looks good.')
open(self._core.dataDir + '.runcheck', 'w+').close() open(self._core.dataDir + '.runcheck', 'w+').close()
elif cmd[0] == 'connectedPeers': elif cmd[0] == 'connectedPeers':
print('yup')
response = '\n'.join(list(self.onlinePeers)).strip() response = '\n'.join(list(self.onlinePeers)).strip()
if response == '': if response == '':
response = 'none' response = 'none'

View File

@ -598,7 +598,7 @@ class Core:
else: else:
c.execute('UPDATE adders SET ' + key + ' = ? WHERE address=?', command) c.execute('UPDATE adders SET ' + key + ' = ? WHERE address=?', command)
conn.commit() conn.commit()
conn.close() conn.close()
return return
@ -622,6 +622,7 @@ class Core:
for row in c.execute(execute, args): for row in c.execute(execute, args):
for i in row: for i in row:
rows.append(i) rows.append(i)
conn.close()
return rows return rows
def getBlockDate(self, blockHash): def getBlockDate(self, blockHash):
@ -637,7 +638,7 @@ class Core:
for row in c.execute(execute, args): for row in c.execute(execute, args):
for i in row: for i in row:
return int(i) return int(i)
conn.close()
return None return None
def getBlocksByType(self, blockType, orderDate=True): def getBlocksByType(self, blockType, orderDate=True):
@ -659,7 +660,7 @@ class Core:
for row in c.execute(execute, args): for row in c.execute(execute, args):
for i in row: for i in row:
rows.append(i) rows.append(i)
conn.close()
return rows return rows
def getExpiredBlocks(self): def getExpiredBlocks(self):
@ -674,6 +675,7 @@ class Core:
for row in c.execute(execute): for row in c.execute(execute):
for i in row: for i in row:
rows.append(i) rows.append(i)
conn.close()
return rows return rows
def setBlockType(self, hash, blockType): def setBlockType(self, hash, blockType):

View File

@ -132,8 +132,11 @@ def raw(data, fd = sys.stdout, sensitive = False):
if get_settings() & OUTPUT_TO_CONSOLE: if get_settings() & OUTPUT_TO_CONSOLE:
ts = fd.write('%s\n' % data) ts = fd.write('%s\n' % data)
if get_settings() & OUTPUT_TO_FILE and not sensitive: if get_settings() & OUTPUT_TO_FILE and not sensitive:
with open(_outputfile, "a+") as f: try:
f.write(colors.filter(data) + '\n') with open(_outputfile, "a+") as f:
f.write(colors.filter(data) + '\n')
except OSError:
pass
def log(prefix, data, color = '', timestamp=True, fd = sys.stdout, prompt = True, sensitive = False): def log(prefix, data, color = '', timestamp=True, fd = sys.stdout, prompt = True, sensitive = False):
''' '''

View File

@ -647,6 +647,7 @@ class Block:
buffer += contents.decode() buffer += contents.decode()
else: else:
file.write(contents) file.write(contents)
file.close()
return (None if not file is None else buffer) return (None if not file is None else buffer)
@ -735,6 +736,7 @@ class Block:
# return different things depending on verbosity # return different things depending on verbosity
if verbose: if verbose:
return (blocks[-1], blocks) return (blocks[-1], blocks)
file.close()
return blocks[-1] return blocks[-1]
def exists(bHash): def exists(bHash):

View File

@ -162,7 +162,7 @@ class OnionrUtils:
retData += '%s:%s' % (hostname, config.get('client.client.port')) retData += '%s:%s' % (hostname, config.get('client.client.port'))
return retData return retData
def localCommand(self, command, data='', silent = True, post=False, postData = {}): def localCommand(self, command, data='', silent = True, post=False, postData = {}, maxWait=10):
''' '''
Send a command to the local http API server, securely. Intended for local clients, DO NOT USE for remote peers. Send a command to the local http API server, securely. Intended for local clients, DO NOT USE for remote peers.
''' '''
@ -170,7 +170,6 @@ class OnionrUtils:
self.getTimeBypassToken() self.getTimeBypassToken()
# TODO: URL encode parameters, just as an extra measure. May not be needed, but should be added regardless. # TODO: URL encode parameters, just as an extra measure. May not be needed, but should be added regardless.
hostname = '' hostname = ''
maxWait = 5
waited = 0 waited = 0
while hostname == '': while hostname == '':
try: try:
@ -185,9 +184,9 @@ class OnionrUtils:
payload = 'http://%s/%s%s' % (hostname, command, data) payload = 'http://%s/%s%s' % (hostname, command, data)
try: try:
if post: if post:
retData = requests.post(payload, data=postData, headers={'token': config.get('client.webpassword')}, timeout=(15, 30)).text retData = requests.post(payload, data=postData, headers={'token': config.get('client.webpassword')}, timeout=(maxWait, 30)).text
else: else:
retData = requests.get(payload, headers={'token': config.get('client.webpassword')}, timeout=(15, 30)).text retData = requests.get(payload, headers={'token': config.get('client.webpassword')}, timeout=(maxWait, 30)).text
except Exception as error: except Exception as error:
if not silent: if not silent:
logger.error('Failed to make local request (command: %s):%s' % (command, error)) logger.error('Failed to make local request (command: %s):%s' % (command, error))

View File

@ -31,11 +31,14 @@ class OnionrCLIUI:
self.myCore = apiInst.get_core() self.myCore = apiInst.get_core()
return return
def subCommand(self, command): def subCommand(self, command, args=None):
try: try:
#subprocess.run(["./onionr.py", command]) #subprocess.run(["./onionr.py", command])
#subprocess.Popen(['./onionr.py', command], stdin=subprocess.STD, stdout=subprocess.STDOUT, stderr=subprocess.STDOUT) #subprocess.Popen(['./onionr.py', command], stdin=subprocess.STD, stdout=subprocess.STDOUT, stderr=subprocess.STDOUT)
subprocess.call(['./onionr.py', command]) if args != None:
subprocess.call(['./onionr.py', command, args])
else:
subprocess.call(['./onionr.py', command])
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
@ -48,12 +51,11 @@ class OnionrCLIUI:
isOnline = 'No' isOnline = 'No'
firstRun = True firstRun = True
choice = '' choice = ''
if self.myCore._utils.localCommand('ping', maxWait=10) == 'pong!':
if self.myCore._utils.localCommand('ping') == 'pong':
firstRun = False firstRun = False
while showMenu: while showMenu:
if self.myCore._utils.localCommand('ping') == 'pong': if self.myCore._utils.localCommand('ping', maxWait=2) == 'pong!':
isOnline = "Yes" isOnline = "Yes"
else: else:
isOnline = "No" isOnline = "No"
@ -62,8 +64,7 @@ class OnionrCLIUI:
1. Flow (Anonymous public chat, use at your own risk) 1. Flow (Anonymous public chat, use at your own risk)
2. Mail (Secure email-like service) 2. Mail (Secure email-like service)
3. File Sharing 3. File Sharing
4. User Settings 4. Quit (Does not shutdown daemon)
5. Quit (Does not shutdown daemon)
''') ''')
try: try:
choice = input(">").strip().lower() choice = input(">").strip().lower()
@ -75,13 +76,9 @@ class OnionrCLIUI:
elif choice in ("2", "mail"): elif choice in ("2", "mail"):
self.subCommand("mail") self.subCommand("mail")
elif choice in ("3", "file sharing", "file"): elif choice in ("3", "file sharing", "file"):
print("Not supported yet") filename = input("Enter full path to file: ").strip()
elif choice in ("4", "user settings", "settings"): self.subCommand("addfile", filename)
try: elif choice in ("4", "quit"):
self.setName()
except (KeyboardInterrupt, EOFError) as e:
pass
elif choice in ("5", "quit"):
showMenu = False showMenu = False
elif choice == "": elif choice == "":
pass pass
@ -89,14 +86,6 @@ class OnionrCLIUI:
logger.error("Invalid choice") logger.error("Invalid choice")
return return
def setName(self):
try:
name = input("Enter your name: ")
if name != "":
self.myCore.insertBlock("userInfo-" + str(uuid.uuid1()), sign=True, header='userInfo', meta={'name': name})
except KeyboardInterrupt:
pass
return
def on_init(api, data = None): def on_init(api, data = None):
''' '''

View File

@ -28,24 +28,6 @@ plugin_name = 'metadataprocessor'
# event listeners # event listeners
def _processUserInfo(api, newBlock):
'''
Set the username for a particular user, from a signed block by them
'''
myBlock = newBlock
peerName = myBlock.getMetadata('name')
try:
if len(peerName) > 20:
raise onionrexceptions.InvalidMetdata('Peer name specified is too large')
except TypeError:
pass
except onionrexceptions.InvalidMetadata:
pass
else:
if signer in self.api.get_core().listPeers():
api.get_core().setPeerInfo(signer, 'name', peerName)
logger.info('%s is now using the name %s.' % (signer, api.get_utils().escapeAnsi(peerName)))
def _processForwardKey(api, myBlock): def _processForwardKey(api, myBlock):
''' '''
Get the forward secrecy key specified by the user for us to use Get the forward secrecy key specified by the user for us to use
@ -67,12 +49,8 @@ def on_processblocks(api):
# Process specific block types # Process specific block types
# userInfo blocks, such as for setting username
if blockType == 'userInfo':
if api.data['validSig'] == True: # we use == True for type safety
_processUserInfo(api, myBlock)
# forwardKey blocks, add a new forward secrecy key for a peer # forwardKey blocks, add a new forward secrecy key for a peer
elif blockType == 'forwardKey': if blockType == 'forwardKey':
if api.data['validSig'] == True: if api.data['validSig'] == True:
_processForwardKey(api, myBlock) _processForwardKey(api, myBlock)
# socket blocks # socket blocks

View File

@ -1,4 +1,5 @@
webpass = document.location.hash.replace('#', '') webpass = document.location.hash.replace('#', '')
nowebpass = false
if (typeof webpass == "undefined"){ if (typeof webpass == "undefined"){
webpass = localStorage['webpass'] webpass = localStorage['webpass']
} }
@ -8,6 +9,7 @@ else{
} }
if (typeof webpass == "undefined" || webpass == ""){ if (typeof webpass == "undefined" || webpass == ""){
alert('Web password was not found in memory or URL') alert('Web password was not found in memory or URL')
nowebpass = true
} }
function httpGet(theUrl) { function httpGet(theUrl) {

View File

@ -1,6 +1,8 @@
shutdownBtn = document.getElementById('shutdownNode') shutdownBtn = document.getElementById('shutdownNode')
shutdownBtn.onclick = function(){ shutdownBtn.onclick = function(){
httpGet('shutdownclean') if (! nowebpass){
overlay('shutdownNotice') httpGet('shutdownclean')
overlay('shutdownNotice')
}
} }