From d4477ff61794500f5947d5197547f49dcc397c09 Mon Sep 17 00:00:00 2001 From: Delirious Lettuce Date: Wed, 24 May 2017 21:20:07 -0600 Subject: [PATCH] * 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 --- onionshare/common.py | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/onionshare/common.py b/onionshare/common.py index 508acd36..adeae06b 100644 --- a/onionshare/common.py +++ b/onionshare/common.py @@ -17,10 +17,22 @@ 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 . """ -import sys, os, inspect, hashlib, base64, platform, zipfile, tempfile, math, time, socket, random -from random import SystemRandom +import base64 +import hashlib +import inspect +import math +import os +import platform +import random +import socket +import sys +import tempfile +import time +import zipfile debug = False + + def log(module, func, msg=None): """ 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) print(final_msg) + def set_debug(new_debug): global debug debug = new_debug @@ -71,6 +84,7 @@ def get_resource_path(filename): return os.path.join(prefix, filename) + def get_tor_paths(): p = get_platform() if p == 'Linux': @@ -90,6 +104,7 @@ def get_tor_paths(): return (tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path) + def get_version(): """ Returns the version of OnionShare that is running. @@ -138,7 +153,7 @@ def build_slug(): with open(get_resource_path('wordlist.txt')) as f: wordlist = f.read().split() - r = SystemRandom() + r = random.SystemRandom() 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. """ - tmpsock = socket.socket() - while True: - try: - tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port))) - break - except OSError: - pass - port = tmpsock.getsockname()[1] - tmpsock.close() - + with socket.socket() as tmpsock: + while True: + try: + tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port))) + break + except OSError: + pass + _, port = tmpsock.getsockname() return port