* Use context manager inside of get_available_port

* Rearrange imports, one per line
* Reuse original `import random` for `random.SystemRandom` (instead of a separate `from random import SystemRandom`)
* Two blank lines above each function definition
This commit is contained in:
Delirious Lettuce 2017-05-24 21:20:07 -06:00
parent 47b58a7565
commit 9f35ebc287

View file

@ -17,10 +17,22 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import sys, os, inspect, hashlib, base64, platform, zipfile, tempfile, math, time, socket, random import base64
from random import SystemRandom import hashlib
import inspect
import math
import os
import platform
import random
import socket
import sys
import tempfile
import time
import zipfile
debug = False debug = False
def log(module, func, msg=None): def log(module, func, msg=None):
""" """
If debug mode is on, log error messages to stdout If debug mode is on, log error messages to stdout
@ -34,6 +46,7 @@ def log(module, func, msg=None):
final_msg = '{}: {}'.format(final_msg, msg) final_msg = '{}: {}'.format(final_msg, msg)
print(final_msg) print(final_msg)
def set_debug(new_debug): def set_debug(new_debug):
global debug global debug
debug = new_debug debug = new_debug
@ -71,6 +84,7 @@ def get_resource_path(filename):
return os.path.join(prefix, filename) return os.path.join(prefix, filename)
def get_tor_paths(): def get_tor_paths():
p = get_platform() p = get_platform()
if p == 'Linux': if p == 'Linux':
@ -90,6 +104,7 @@ def get_tor_paths():
return (tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path) return (tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path)
def get_version(): def get_version():
""" """
Returns the version of OnionShare that is running. Returns the version of OnionShare that is running.
@ -138,7 +153,7 @@ def build_slug():
with open(get_resource_path('wordlist.txt')) as f: with open(get_resource_path('wordlist.txt')) as f:
wordlist = f.read().split() wordlist = f.read().split()
r = SystemRandom() r = random.SystemRandom()
return '-'.join(r.choice(wordlist) for _ in range(2)) return '-'.join(r.choice(wordlist) for _ in range(2))
@ -200,16 +215,14 @@ def get_available_port(min_port, max_port):
""" """
Find a random available port within the given range. Find a random available port within the given range.
""" """
tmpsock = socket.socket() with socket.socket() as tmpsock:
while True: while True:
try: try:
tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port))) tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port)))
break break
except OSError: except OSError:
pass pass
port = tmpsock.getsockname()[1] _, port = tmpsock.getsockname()
tmpsock.close()
return port return port