mirror of
https://github.com/onionshare/onionshare.git
synced 2025-09-26 02:50:56 -04:00
Add onionshare CLI to cli folder, move GUI to desktop folder, and start refactoring it to work with briefcase
This commit is contained in:
parent
b81a55f546
commit
f4abcf1be9
583 changed files with 14871 additions and 474 deletions
514
cli/onionshare_cli/__init__.py
Normal file
514
cli/onionshare_cli/__init__.py
Normal file
|
@ -0,0 +1,514 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os, sys, time, argparse, threading
|
||||
from datetime import datetime
|
||||
from datetime import timedelta
|
||||
|
||||
from .common import Common
|
||||
from .web import Web
|
||||
from .onion import *
|
||||
from .onionshare import OnionShare
|
||||
from .mode_settings import ModeSettings
|
||||
|
||||
|
||||
def build_url(mode_settings, app, web):
|
||||
# Build the URL
|
||||
if mode_settings.get("general", "public"):
|
||||
return f"http://{app.onion_host}"
|
||||
else:
|
||||
return f"http://onionshare:{web.password}@{app.onion_host}"
|
||||
|
||||
|
||||
def main(cwd=None):
|
||||
"""
|
||||
The main() function implements all of the logic that the command-line version of
|
||||
onionshare uses.
|
||||
"""
|
||||
common = Common()
|
||||
|
||||
# Display OnionShare banner
|
||||
print(f"OnionShare {common.version} | https://onionshare.org/")
|
||||
reset = "\033[0m"
|
||||
purple = "\33[95m"
|
||||
print(purple)
|
||||
print(" @@@@@@@@@ ")
|
||||
print(" @@@@@@@@@@@@@@@@@@@ ")
|
||||
print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ")
|
||||
print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ")
|
||||
print(
|
||||
" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ___ _ "
|
||||
)
|
||||
print(
|
||||
" @@@@@@ @@@@@@@@@@@@@ / _ \ (_) "
|
||||
)
|
||||
print(
|
||||
" @@@@ @ @@@@@@@@@@@ | | | |_ __ _ ___ _ __ "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@ @@@@@@@@@@ | | | | '_ \| |/ _ \| '_ \ "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@@@ @@@@@@@@@@ \ \_/ / | | | | (_) | | | | "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@@@@@@@ @@@@@@@@@ \___/|_| |_|_|\___/|_| |_| "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@ @@@@@@@@@@@@@@@@ _____ _ "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@ @@@@@@@@@@@@ / ___| | "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@ @@@@@@@@ \ `--.| |__ __ _ _ __ ___ "
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@@ @ @@@@ `--. \ '_ \ / _` | '__/ _ \\"
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@@@@ @@@@@@ /\__/ / | | | (_| | | | __/"
|
||||
)
|
||||
print(
|
||||
" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \____/|_| |_|\__,_|_| \___|"
|
||||
)
|
||||
print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ")
|
||||
print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ")
|
||||
print(" @@@@@@@@@@@@@@@@@@@ ")
|
||||
print(" @@@@@@@@@ ")
|
||||
print(reset)
|
||||
|
||||
# OnionShare CLI in OSX needs to change current working directory (#132)
|
||||
if common.platform == "Darwin":
|
||||
if cwd:
|
||||
os.chdir(cwd)
|
||||
|
||||
# Parse arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28)
|
||||
)
|
||||
# Select modes
|
||||
parser.add_argument(
|
||||
"--receive", action="store_true", dest="receive", help="Receive files"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--website", action="store_true", dest="website", help="Publish website"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--chat", action="store_true", dest="chat", help="Start chat server"
|
||||
)
|
||||
# Tor connection-related args
|
||||
parser.add_argument(
|
||||
"--local-only",
|
||||
action="store_true",
|
||||
dest="local_only",
|
||||
default=False,
|
||||
help="Don't use Tor (only for development)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--connect-timeout",
|
||||
metavar="SECONDS",
|
||||
dest="connect_timeout",
|
||||
default=120,
|
||||
help="Give up connecting to Tor after a given amount of seconds (default: 120)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--config",
|
||||
metavar="FILENAME",
|
||||
default=None,
|
||||
help="Filename of custom global settings",
|
||||
)
|
||||
# Persistent file
|
||||
parser.add_argument(
|
||||
"--persistent",
|
||||
metavar="FILENAME",
|
||||
default=None,
|
||||
help="Filename of persistent session",
|
||||
)
|
||||
# General args
|
||||
parser.add_argument(
|
||||
"--public",
|
||||
action="store_true",
|
||||
dest="public",
|
||||
default=False,
|
||||
help="Don't use a password",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--auto-start-timer",
|
||||
metavar="SECONDS",
|
||||
dest="autostart_timer",
|
||||
default=0,
|
||||
help="Start onion service at scheduled time (N seconds from now)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--auto-stop-timer",
|
||||
metavar="SECONDS",
|
||||
dest="autostop_timer",
|
||||
default=0,
|
||||
help="Stop onion service at schedule time (N seconds from now)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--legacy",
|
||||
action="store_true",
|
||||
dest="legacy",
|
||||
default=False,
|
||||
help="Use legacy address (v2 onion service, not recommended)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--client-auth",
|
||||
action="store_true",
|
||||
dest="client_auth",
|
||||
default=False,
|
||||
help="Use client authorization (requires --legacy)",
|
||||
)
|
||||
# Share args
|
||||
parser.add_argument(
|
||||
"--autostop-sharing",
|
||||
action="store_true",
|
||||
dest="autostop_sharing",
|
||||
default=True,
|
||||
help="Share files: Stop sharing after files have been sent",
|
||||
)
|
||||
# Receive args
|
||||
parser.add_argument(
|
||||
"--data-dir",
|
||||
metavar="data_dir",
|
||||
default=None,
|
||||
help="Receive files: Save files received to this directory",
|
||||
)
|
||||
# Website args
|
||||
parser.add_argument(
|
||||
"--disable_csp",
|
||||
action="store_true",
|
||||
dest="disable_csp",
|
||||
default=False,
|
||||
help="Publish website: Disable Content Security Policy header (allows your website to use third-party resources)",
|
||||
)
|
||||
# Other
|
||||
parser.add_argument(
|
||||
"-v",
|
||||
"--verbose",
|
||||
action="store_true",
|
||||
dest="verbose",
|
||||
help="Log OnionShare errors to stdout, and web errors to disk",
|
||||
)
|
||||
parser.add_argument(
|
||||
"filename",
|
||||
metavar="filename",
|
||||
nargs="*",
|
||||
help="List of files or folders to share",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
filenames = args.filename
|
||||
for i in range(len(filenames)):
|
||||
filenames[i] = os.path.abspath(filenames[i])
|
||||
|
||||
receive = bool(args.receive)
|
||||
website = bool(args.website)
|
||||
chat = bool(args.chat)
|
||||
local_only = bool(args.local_only)
|
||||
connect_timeout = int(args.connect_timeout)
|
||||
config_filename = args.config
|
||||
persistent_filename = args.persistent
|
||||
public = bool(args.public)
|
||||
autostart_timer = int(args.autostart_timer)
|
||||
autostop_timer = int(args.autostop_timer)
|
||||
legacy = bool(args.legacy)
|
||||
client_auth = bool(args.client_auth)
|
||||
autostop_sharing = bool(args.autostop_sharing)
|
||||
data_dir = args.data_dir
|
||||
disable_csp = bool(args.disable_csp)
|
||||
verbose = bool(args.verbose)
|
||||
|
||||
if receive:
|
||||
mode = "receive"
|
||||
elif website:
|
||||
mode = "website"
|
||||
elif chat:
|
||||
mode = "chat"
|
||||
else:
|
||||
mode = "share"
|
||||
|
||||
# Verbose mode?
|
||||
common.verbose = verbose
|
||||
|
||||
# client_auth can only be set if legacy is also set
|
||||
if client_auth and not legacy:
|
||||
print(
|
||||
"Client authentication (--client-auth) is only supported with with legacy onion services (--legacy)"
|
||||
)
|
||||
sys.exit()
|
||||
|
||||
# Re-load settings, if a custom config was passed in
|
||||
if config_filename:
|
||||
common.load_settings(config_filename)
|
||||
else:
|
||||
common.load_settings()
|
||||
|
||||
# Mode settings
|
||||
if persistent_filename:
|
||||
mode_settings = ModeSettings(common, persistent_filename)
|
||||
mode_settings.set("persistent", "enabled", True)
|
||||
else:
|
||||
mode_settings = ModeSettings(common)
|
||||
|
||||
if mode_settings.just_created:
|
||||
# This means the mode settings were just created, not loaded from disk
|
||||
mode_settings.set("general", "public", public)
|
||||
mode_settings.set("general", "autostart_timer", autostart_timer)
|
||||
mode_settings.set("general", "autostop_timer", autostop_timer)
|
||||
mode_settings.set("general", "legacy", legacy)
|
||||
mode_settings.set("general", "client_auth", client_auth)
|
||||
if mode == "share":
|
||||
mode_settings.set("share", "autostop_sharing", autostop_sharing)
|
||||
if mode == "receive":
|
||||
if data_dir:
|
||||
mode_settings.set("receive", "data_dir", data_dir)
|
||||
if mode == "website":
|
||||
mode_settings.set("website", "disable_csp", disable_csp)
|
||||
else:
|
||||
# See what the persistent mode was
|
||||
mode = mode_settings.get("persistent", "mode")
|
||||
|
||||
# In share and website mode, you must supply a list of filenames
|
||||
if mode == "share" or mode == "website":
|
||||
# Unless you passed in a persistent filename, in which case get the filenames from
|
||||
# the mode settings
|
||||
if persistent_filename and not mode_settings.just_created:
|
||||
filenames = mode_settings.get(mode, "filenames")
|
||||
|
||||
else:
|
||||
# Make sure filenames given if not using receiver mode
|
||||
if len(filenames) == 0:
|
||||
if persistent_filename:
|
||||
mode_settings.delete()
|
||||
|
||||
parser.print_help()
|
||||
sys.exit()
|
||||
|
||||
# Validate filenames
|
||||
valid = True
|
||||
for filename in filenames:
|
||||
if not os.path.isfile(filename) and not os.path.isdir(filename):
|
||||
print(f"{filename} is not a valid file.")
|
||||
valid = False
|
||||
if not os.access(filename, os.R_OK):
|
||||
print(f"{filename} is not a readable file.")
|
||||
valid = False
|
||||
if not valid:
|
||||
sys.exit()
|
||||
|
||||
# Create the Web object
|
||||
web = Web(common, False, mode_settings, mode)
|
||||
|
||||
# Start the Onion object
|
||||
onion = Onion(common, use_tmp_dir=True)
|
||||
try:
|
||||
onion.connect(
|
||||
custom_settings=False,
|
||||
config=config_filename,
|
||||
connect_timeout=connect_timeout,
|
||||
local_only=local_only,
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
print("")
|
||||
sys.exit()
|
||||
except Exception as e:
|
||||
sys.exit(e.args[0])
|
||||
|
||||
# Start the onionshare app
|
||||
try:
|
||||
common.settings.load()
|
||||
if not mode_settings.get("general", "public"):
|
||||
web.generate_password(mode_settings.get("onion", "password"))
|
||||
else:
|
||||
web.password = None
|
||||
app = OnionShare(common, onion, local_only, autostop_timer)
|
||||
app.choose_port()
|
||||
|
||||
# Delay the startup if a startup timer was set
|
||||
if autostart_timer > 0:
|
||||
# Can't set a schedule that is later than the auto-stop timer
|
||||
if autostop_timer > 0 and autostop_timer < autostart_timer:
|
||||
print(
|
||||
"The auto-stop time can't be the same or earlier than the auto-start time. Please update it to start sharing."
|
||||
)
|
||||
sys.exit()
|
||||
|
||||
app.start_onion_service(mode_settings, False, True)
|
||||
url = build_url(mode_settings, app, web)
|
||||
schedule = datetime.now() + timedelta(seconds=autostart_timer)
|
||||
if mode == "receive":
|
||||
print(
|
||||
f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}"
|
||||
)
|
||||
print("")
|
||||
print(
|
||||
"Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing."
|
||||
)
|
||||
print("")
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
print(
|
||||
f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
|
||||
)
|
||||
print(app.auth_string)
|
||||
else:
|
||||
print(
|
||||
f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
|
||||
)
|
||||
else:
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
print(
|
||||
f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
|
||||
)
|
||||
print(app.auth_string)
|
||||
else:
|
||||
print(
|
||||
f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
|
||||
)
|
||||
print(url)
|
||||
print("")
|
||||
print("Waiting for the scheduled time before starting...")
|
||||
app.onion.cleanup(False)
|
||||
time.sleep(autostart_timer)
|
||||
app.start_onion_service(mode_settings)
|
||||
else:
|
||||
app.start_onion_service(mode_settings)
|
||||
except KeyboardInterrupt:
|
||||
print("")
|
||||
sys.exit()
|
||||
except (TorTooOld, TorErrorProtocolError) as e:
|
||||
print("")
|
||||
print(e.args[0])
|
||||
sys.exit()
|
||||
|
||||
if mode == "website":
|
||||
# Prepare files to share
|
||||
try:
|
||||
web.website_mode.set_file_info(filenames)
|
||||
except OSError as e:
|
||||
print(e.strerror)
|
||||
sys.exit(1)
|
||||
|
||||
if mode == "share":
|
||||
# Prepare files to share
|
||||
print("Compressing files.")
|
||||
try:
|
||||
web.share_mode.set_file_info(filenames)
|
||||
app.cleanup_filenames += web.share_mode.cleanup_filenames
|
||||
except OSError as e:
|
||||
print(e.strerror)
|
||||
sys.exit(1)
|
||||
|
||||
# Warn about sending large files over Tor
|
||||
if web.share_mode.download_filesize >= 157286400: # 150mb
|
||||
print("")
|
||||
print("Warning: Sending a large share could take hours")
|
||||
print("")
|
||||
|
||||
# Start OnionShare http service in new thread
|
||||
t = threading.Thread(target=web.start, args=(app.port,))
|
||||
t.daemon = True
|
||||
t.start()
|
||||
|
||||
try: # Trap Ctrl-C
|
||||
# Wait for web.generate_password() to finish running
|
||||
time.sleep(0.2)
|
||||
|
||||
# start auto-stop timer thread
|
||||
if app.autostop_timer > 0:
|
||||
app.autostop_timer_thread.start()
|
||||
|
||||
# Save the web password if we are using a persistent private key
|
||||
if mode_settings.get("persistent", "enabled"):
|
||||
if not mode_settings.get("onion", "password"):
|
||||
mode_settings.set("onion", "password", web.password)
|
||||
# mode_settings.save()
|
||||
|
||||
# Build the URL
|
||||
url = build_url(mode_settings, app, web)
|
||||
|
||||
print("")
|
||||
if autostart_timer > 0:
|
||||
print("Server started")
|
||||
else:
|
||||
if mode == "receive":
|
||||
print(
|
||||
f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}"
|
||||
)
|
||||
print("")
|
||||
print(
|
||||
"Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing."
|
||||
)
|
||||
print("")
|
||||
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
print("Give this address and HidServAuth to the sender:")
|
||||
print(url)
|
||||
print(app.auth_string)
|
||||
else:
|
||||
print("Give this address to the sender:")
|
||||
print(url)
|
||||
else:
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
print("Give this address and HidServAuth line to the recipient:")
|
||||
print(url)
|
||||
print(app.auth_string)
|
||||
else:
|
||||
print("Give this address to the recipient:")
|
||||
print(url)
|
||||
print("")
|
||||
print("Press Ctrl+C to stop the server")
|
||||
|
||||
# Wait for app to close
|
||||
while t.is_alive():
|
||||
if app.autostop_timer > 0:
|
||||
# if the auto-stop timer was set and has run out, stop the server
|
||||
if not app.autostop_timer_thread.is_alive():
|
||||
if mode == "share" or (mode == "website"):
|
||||
# If there were no attempts to download the share, or all downloads are done, we can stop
|
||||
if web.share_mode.cur_history_id == 0 or web.done:
|
||||
print("Stopped because auto-stop timer ran out")
|
||||
web.stop(app.port)
|
||||
break
|
||||
if mode == "receive":
|
||||
if (
|
||||
web.receive_mode.cur_history_id == 0
|
||||
or not web.receive_mode.uploads_in_progress
|
||||
):
|
||||
print("Stopped because auto-stop timer ran out")
|
||||
web.stop(app.port)
|
||||
break
|
||||
else:
|
||||
web.receive_mode.can_upload = False
|
||||
# Allow KeyboardInterrupt exception to be handled with threads
|
||||
# https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception
|
||||
time.sleep(0.2)
|
||||
except KeyboardInterrupt:
|
||||
web.stop(app.port)
|
||||
finally:
|
||||
# Shutdown
|
||||
app.cleanup()
|
||||
onion.cleanup()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
300
cli/onionshare_cli/common.py
Normal file
300
cli/onionshare_cli/common.py
Normal file
|
@ -0,0 +1,300 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import shutil
|
||||
|
||||
from .settings import Settings
|
||||
|
||||
|
||||
class Common:
|
||||
"""
|
||||
The Common object is shared amongst all parts of OnionShare.
|
||||
"""
|
||||
|
||||
def __init__(self, verbose=False):
|
||||
self.verbose = verbose
|
||||
|
||||
# The platform OnionShare is running on
|
||||
self.platform = platform.system()
|
||||
if self.platform.endswith("BSD") or self.platform == "DragonFly":
|
||||
self.platform = "BSD"
|
||||
|
||||
# The current version of OnionShare
|
||||
with open(self.get_resource_path("version.txt")) as f:
|
||||
self.version = f.read().strip()
|
||||
|
||||
def load_settings(self, config=None):
|
||||
"""
|
||||
Loading settings, optionally from a custom config json file.
|
||||
"""
|
||||
self.settings = Settings(self, config)
|
||||
self.settings.load()
|
||||
|
||||
def log(self, module, func, msg=None):
|
||||
"""
|
||||
If verbose mode is on, log error messages to stdout
|
||||
"""
|
||||
if self.verbose:
|
||||
timestamp = time.strftime("%b %d %Y %X")
|
||||
|
||||
final_msg = f"[{timestamp}] {module}.{func}"
|
||||
if msg:
|
||||
final_msg = f"{final_msg}: {msg}"
|
||||
print(final_msg)
|
||||
|
||||
def get_resource_path(self, filename):
|
||||
"""
|
||||
Returns the absolute path of a resource
|
||||
"""
|
||||
resources_path = os.path.join(
|
||||
os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))),
|
||||
"resources",
|
||||
)
|
||||
return os.path.join(resources_path, filename)
|
||||
|
||||
def get_tor_paths(self):
|
||||
if self.platform == "Linux":
|
||||
tor_path = shutil.which("tor")
|
||||
obfs4proxy_file_path = shutil.which("obfs4proxy")
|
||||
prefix = os.path.dirname(os.path.dirname(tor_path))
|
||||
tor_geo_ip_file_path = os.path.join(prefix, "share/tor/geoip")
|
||||
tor_geo_ipv6_file_path = os.path.join(prefix, "share/tor/geoip6")
|
||||
elif self.platform == "Windows":
|
||||
base_path = os.path.join(
|
||||
os.path.dirname(os.path.dirname(self.get_resource_path(""))), "tor"
|
||||
)
|
||||
tor_path = os.path.join(os.path.join(base_path, "Tor"), "tor.exe")
|
||||
obfs4proxy_file_path = os.path.join(
|
||||
os.path.join(base_path, "Tor"), "obfs4proxy.exe"
|
||||
)
|
||||
tor_geo_ip_file_path = os.path.join(
|
||||
os.path.join(os.path.join(base_path, "Data"), "Tor"), "geoip"
|
||||
)
|
||||
tor_geo_ipv6_file_path = os.path.join(
|
||||
os.path.join(os.path.join(base_path, "Data"), "Tor"), "geoip6"
|
||||
)
|
||||
elif self.platform == "Darwin":
|
||||
base_path = os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(self.get_resource_path("")))
|
||||
)
|
||||
tor_path = os.path.join(base_path, "Resources", "Tor", "tor")
|
||||
tor_geo_ip_file_path = os.path.join(base_path, "Resources", "Tor", "geoip")
|
||||
tor_geo_ipv6_file_path = os.path.join(
|
||||
base_path, "Resources", "Tor", "geoip6"
|
||||
)
|
||||
obfs4proxy_file_path = os.path.join(
|
||||
base_path, "Resources", "Tor", "obfs4proxy"
|
||||
)
|
||||
elif self.platform == "BSD":
|
||||
tor_path = "/usr/local/bin/tor"
|
||||
tor_geo_ip_file_path = "/usr/local/share/tor/geoip"
|
||||
tor_geo_ipv6_file_path = "/usr/local/share/tor/geoip6"
|
||||
obfs4proxy_file_path = "/usr/local/bin/obfs4proxy"
|
||||
|
||||
return (
|
||||
tor_path,
|
||||
tor_geo_ip_file_path,
|
||||
tor_geo_ipv6_file_path,
|
||||
obfs4proxy_file_path,
|
||||
)
|
||||
|
||||
def build_data_dir(self):
|
||||
"""
|
||||
Returns the path of the OnionShare data directory.
|
||||
"""
|
||||
if self.platform == "Windows":
|
||||
try:
|
||||
appdata = os.environ["APPDATA"]
|
||||
onionshare_data_dir = f"{appdata}\\OnionShare"
|
||||
except:
|
||||
# If for some reason we don't have the 'APPDATA' environment variable
|
||||
# (like running tests in Linux while pretending to be in Windows)
|
||||
onionshare_data_dir = os.path.expanduser("~/.config/onionshare")
|
||||
elif self.platform == "Darwin":
|
||||
onionshare_data_dir = os.path.expanduser(
|
||||
"~/Library/Application Support/OnionShare"
|
||||
)
|
||||
else:
|
||||
onionshare_data_dir = os.path.expanduser("~/.config/onionshare")
|
||||
|
||||
# Modify the data dir if running tests
|
||||
if getattr(sys, "onionshare_test_mode", False):
|
||||
onionshare_data_dir += "-testdata"
|
||||
|
||||
os.makedirs(onionshare_data_dir, 0o700, True)
|
||||
return onionshare_data_dir
|
||||
|
||||
def build_tmp_dir(self):
|
||||
"""
|
||||
Returns path to a folder that can hold temporary files
|
||||
"""
|
||||
tmp_dir = os.path.join(self.build_data_dir(), "tmp")
|
||||
os.makedirs(tmp_dir, 0o700, True)
|
||||
return tmp_dir
|
||||
|
||||
def build_persistent_dir(self):
|
||||
"""
|
||||
Returns the path to the folder that holds persistent files
|
||||
"""
|
||||
persistent_dir = os.path.join(self.build_data_dir(), "persistent")
|
||||
os.makedirs(persistent_dir, 0o700, True)
|
||||
return persistent_dir
|
||||
|
||||
def build_tor_dir(self):
|
||||
"""
|
||||
Returns path to the tor data directory
|
||||
"""
|
||||
tor_dir = os.path.join(self.build_data_dir(), "tor_data")
|
||||
os.makedirs(tor_dir, 0o700, True)
|
||||
return tor_dir
|
||||
|
||||
def build_password(self, word_count=2):
|
||||
"""
|
||||
Returns a random string made of words from the wordlist, such as "deter-trig".
|
||||
"""
|
||||
with open(self.get_resource_path("wordlist.txt")) as f:
|
||||
wordlist = f.read().split()
|
||||
|
||||
r = random.SystemRandom()
|
||||
return "-".join(r.choice(wordlist) for _ in range(word_count))
|
||||
|
||||
def build_username(self, word_count=2):
|
||||
"""
|
||||
Returns a random string made of words from the wordlist, such as "deter-trig".
|
||||
"""
|
||||
with open(self.get_resource_path("wordlist.txt")) as f:
|
||||
wordlist = f.read().split()
|
||||
|
||||
r = random.SystemRandom()
|
||||
return "-".join(r.choice(wordlist) for _ in range(word_count))
|
||||
|
||||
@staticmethod
|
||||
def random_string(num_bytes, output_len=None):
|
||||
"""
|
||||
Returns a random string with a specified number of bytes.
|
||||
"""
|
||||
b = os.urandom(num_bytes)
|
||||
h = hashlib.sha256(b).digest()[:16]
|
||||
s = base64.b32encode(h).lower().replace(b"=", b"").decode("utf-8")
|
||||
if not output_len:
|
||||
return s
|
||||
return s[:output_len]
|
||||
|
||||
@staticmethod
|
||||
def human_readable_filesize(b):
|
||||
"""
|
||||
Returns filesize in a human readable format.
|
||||
"""
|
||||
thresh = 1024.0
|
||||
if b < thresh:
|
||||
return "{:.1f} B".format(b)
|
||||
units = ("KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")
|
||||
u = 0
|
||||
b /= thresh
|
||||
while b >= thresh:
|
||||
b /= thresh
|
||||
u += 1
|
||||
return "{:.1f} {}".format(b, units[u])
|
||||
|
||||
@staticmethod
|
||||
def format_seconds(seconds):
|
||||
"""Return a human-readable string of the format 1d2h3m4s"""
|
||||
days, seconds = divmod(seconds, 86400)
|
||||
hours, seconds = divmod(seconds, 3600)
|
||||
minutes, seconds = divmod(seconds, 60)
|
||||
|
||||
human_readable = []
|
||||
if days:
|
||||
human_readable.append("{:.0f}d".format(days))
|
||||
if hours:
|
||||
human_readable.append("{:.0f}h".format(hours))
|
||||
if minutes:
|
||||
human_readable.append("{:.0f}m".format(minutes))
|
||||
if seconds or not human_readable:
|
||||
human_readable.append("{:.0f}s".format(seconds))
|
||||
return "".join(human_readable)
|
||||
|
||||
@staticmethod
|
||||
def estimated_time_remaining(bytes_downloaded, total_bytes, started):
|
||||
now = time.time()
|
||||
time_elapsed = now - started # in seconds
|
||||
download_rate = bytes_downloaded / time_elapsed
|
||||
remaining_bytes = total_bytes - bytes_downloaded
|
||||
eta = remaining_bytes / download_rate
|
||||
return Common.format_seconds(eta)
|
||||
|
||||
@staticmethod
|
||||
def get_available_port(min_port, max_port):
|
||||
"""
|
||||
Find a random available port within the given range.
|
||||
"""
|
||||
with socket.socket() as tmpsock:
|
||||
while True:
|
||||
try:
|
||||
tmpsock.bind(("127.0.0.1", random.randint(min_port, max_port)))
|
||||
break
|
||||
except OSError as e:
|
||||
pass
|
||||
_, port = tmpsock.getsockname()
|
||||
return port
|
||||
|
||||
@staticmethod
|
||||
def dir_size(start_path):
|
||||
"""
|
||||
Calculates the total size, in bytes, of all of the files in a directory.
|
||||
"""
|
||||
total_size = 0
|
||||
for dirpath, dirnames, filenames in os.walk(start_path):
|
||||
for f in filenames:
|
||||
fp = os.path.join(dirpath, f)
|
||||
if not os.path.islink(fp):
|
||||
total_size += os.path.getsize(fp)
|
||||
return total_size
|
||||
|
||||
|
||||
class AutoStopTimer(threading.Thread):
|
||||
"""
|
||||
Background thread sleeps t hours and returns.
|
||||
"""
|
||||
|
||||
def __init__(self, common, time):
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
self.common = common
|
||||
|
||||
self.setDaemon(True)
|
||||
self.time = time
|
||||
|
||||
def run(self):
|
||||
self.common.log(
|
||||
"AutoStopTimer", f"Server will shut down after {self.time} seconds"
|
||||
)
|
||||
time.sleep(self.time)
|
||||
return 1
|
146
cli/onionshare_cli/mode_settings.py
Normal file
146
cli/onionshare_cli/mode_settings.py
Normal file
|
@ -0,0 +1,146 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import platform
|
||||
|
||||
if platform.system() == "Darwin":
|
||||
import pwd
|
||||
|
||||
|
||||
class ModeSettings:
|
||||
"""
|
||||
This stores the settings for a single instance of an OnionShare mode. In CLI there
|
||||
is only one ModeSettings, and in the GUI there is a separate ModeSettings for each tab
|
||||
"""
|
||||
|
||||
def __init__(self, common, filename=None, id=None):
|
||||
self.common = common
|
||||
|
||||
self.default_settings = {
|
||||
"onion": {
|
||||
"private_key": None,
|
||||
"hidservauth_string": None,
|
||||
"password": None,
|
||||
},
|
||||
"persistent": {"mode": None, "enabled": False},
|
||||
"general": {
|
||||
"public": False,
|
||||
"autostart_timer": False,
|
||||
"autostop_timer": False,
|
||||
"legacy": False,
|
||||
"client_auth": False,
|
||||
"service_id": None,
|
||||
},
|
||||
"share": {"autostop_sharing": True, "filenames": []},
|
||||
"receive": {"data_dir": self.build_default_receive_data_dir()},
|
||||
"website": {"disable_csp": False, "filenames": []},
|
||||
"chat": {"room": "default"},
|
||||
}
|
||||
self._settings = {}
|
||||
|
||||
self.just_created = False
|
||||
if id:
|
||||
self.id = id
|
||||
else:
|
||||
self.id = self.common.build_password(3)
|
||||
|
||||
self.load(filename)
|
||||
|
||||
def fill_in_defaults(self):
|
||||
"""
|
||||
If there are any missing settings from self._settings, replace them with
|
||||
their default values.
|
||||
"""
|
||||
for key in self.default_settings:
|
||||
if key in self._settings:
|
||||
for inner_key in self.default_settings[key]:
|
||||
if inner_key not in self._settings[key]:
|
||||
self._settings[key][inner_key] = self.default_settings[key][
|
||||
inner_key
|
||||
]
|
||||
else:
|
||||
self._settings[key] = self.default_settings[key]
|
||||
|
||||
def get(self, group, key):
|
||||
return self._settings[group][key]
|
||||
|
||||
def set(self, group, key, val):
|
||||
self._settings[group][key] = val
|
||||
self.common.log(
|
||||
"ModeSettings", "set", f"updating {self.id}: {group}.{key} = {val}"
|
||||
)
|
||||
self.save()
|
||||
|
||||
def build_default_receive_data_dir(self):
|
||||
"""
|
||||
Returns the path of the default Downloads directory for receive mode.
|
||||
"""
|
||||
|
||||
if self.common.platform == "Darwin":
|
||||
# We can't use os.path.expanduser() in macOS because in the sandbox it
|
||||
# returns the path to the sandboxed homedir
|
||||
real_homedir = pwd.getpwuid(os.getuid()).pw_dir
|
||||
return os.path.join(real_homedir, "OnionShare")
|
||||
elif self.common.platform == "Windows":
|
||||
# On Windows, os.path.expanduser() needs to use backslash, or else it
|
||||
# retains the forward slash, which breaks opening the folder in explorer.
|
||||
return os.path.expanduser("~\OnionShare")
|
||||
else:
|
||||
# All other OSes
|
||||
return os.path.expanduser("~/OnionShare")
|
||||
|
||||
def load(self, filename=None):
|
||||
# Load persistent settings from disk. If the file doesn't exist, create it
|
||||
if filename:
|
||||
self.filename = filename
|
||||
else:
|
||||
self.filename = os.path.join(
|
||||
self.common.build_persistent_dir(), f"{self.id}.json"
|
||||
)
|
||||
|
||||
if os.path.exists(self.filename):
|
||||
try:
|
||||
with open(self.filename, "r") as f:
|
||||
self._settings = json.load(f)
|
||||
self.fill_in_defaults()
|
||||
self.common.log("ModeSettings", "load", f"loaded {self.filename}")
|
||||
return
|
||||
except:
|
||||
pass
|
||||
|
||||
# If loading settings didn't work, create the settings file
|
||||
self.common.log("ModeSettings", "load", f"creating {self.filename}")
|
||||
self.fill_in_defaults()
|
||||
self.just_created = True
|
||||
|
||||
def save(self):
|
||||
# Save persistent setting to disk
|
||||
if not self.get("persistent", "enabled"):
|
||||
return
|
||||
|
||||
if self.filename:
|
||||
with open(self.filename, "w") as file:
|
||||
file.write(json.dumps(self._settings, indent=2))
|
||||
|
||||
def delete(self):
|
||||
# Delete the file from disk
|
||||
if os.path.exists(self.filename):
|
||||
os.remove(self.filename)
|
805
cli/onionshare_cli/onion.py
Normal file
805
cli/onionshare_cli/onion.py
Normal file
|
@ -0,0 +1,805 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from stem.control import Controller
|
||||
from stem import ProtocolError, SocketClosed
|
||||
from stem.connection import MissingPassword, UnreadableCookieFile, AuthenticationFailure
|
||||
from Crypto.PublicKey import RSA
|
||||
import base64, os, sys, tempfile, shutil, urllib, platform, subprocess, time, shlex
|
||||
|
||||
from distutils.version import LooseVersion as Version
|
||||
from . import common
|
||||
from .settings import Settings
|
||||
|
||||
# TODO: Figure out how to localize this for the GUI
|
||||
|
||||
|
||||
class TorErrorAutomatic(Exception):
|
||||
"""
|
||||
OnionShare is failing to connect and authenticate to the Tor controller,
|
||||
using automatic settings that should work with Tor Browser.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorInvalidSetting(Exception):
|
||||
"""
|
||||
This exception is raised if the settings just don't make sense.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorSocketPort(Exception):
|
||||
"""
|
||||
OnionShare can't connect to the Tor controller using the supplied address and port.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorSocketFile(Exception):
|
||||
"""
|
||||
OnionShare can't connect to the Tor controller using the supplied socket file.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorMissingPassword(Exception):
|
||||
"""
|
||||
OnionShare connected to the Tor controller, but it requires a password.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorUnreadableCookieFile(Exception):
|
||||
"""
|
||||
OnionShare connected to the Tor controller, but your user does not have permission
|
||||
to access the cookie file.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorAuthError(Exception):
|
||||
"""
|
||||
OnionShare connected to the address and port, but can't authenticate. It's possible
|
||||
that a Tor controller isn't listening on this port.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorErrorProtocolError(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare connects to the Tor controller, but it
|
||||
isn't acting like a Tor controller (such as in Whonix).
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TorTooOld(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare needs to use a feature of Tor or stem
|
||||
(like stealth ephemeral onion services) but the version you have installed
|
||||
is too old.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class BundledTorNotSupported(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare is set to use the bundled Tor binary,
|
||||
but it's not supported on that platform, or in dev mode.
|
||||
"""
|
||||
|
||||
|
||||
class BundledTorTimeout(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare is set to use the bundled Tor binary,
|
||||
but Tor doesn't finish connecting promptly.
|
||||
"""
|
||||
|
||||
|
||||
class BundledTorCanceled(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare is set to use the bundled Tor binary,
|
||||
and the user cancels connecting to Tor
|
||||
"""
|
||||
|
||||
|
||||
class BundledTorBroken(Exception):
|
||||
"""
|
||||
This exception is raised if onionshare is set to use the bundled Tor binary,
|
||||
but the process seems to fail to run.
|
||||
"""
|
||||
|
||||
|
||||
class Onion(object):
|
||||
"""
|
||||
Onion is an abstraction layer for connecting to the Tor control port and
|
||||
creating onion services. OnionShare supports creating onion services by
|
||||
connecting to the Tor controller and using ADD_ONION, DEL_ONION.
|
||||
|
||||
stealth: Should the onion service be stealth?
|
||||
|
||||
settings: A Settings object. If it's not passed in, load from disk.
|
||||
|
||||
bundled_connection_func: If the tor connection type is bundled, optionally
|
||||
call this function and pass in a status string while connecting to tor. This
|
||||
is necessary for status updates to reach the GUI.
|
||||
"""
|
||||
|
||||
def __init__(self, common, use_tmp_dir=False):
|
||||
self.common = common
|
||||
self.common.log("Onion", "__init__")
|
||||
|
||||
self.use_tmp_dir = use_tmp_dir
|
||||
|
||||
# Is bundled tor supported?
|
||||
if (
|
||||
self.common.platform == "Windows" or self.common.platform == "Darwin"
|
||||
) and getattr(sys, "onionshare_dev_mode", False):
|
||||
self.bundle_tor_supported = False
|
||||
else:
|
||||
self.bundle_tor_supported = True
|
||||
|
||||
# Set the path of the tor binary, for bundled tor
|
||||
(
|
||||
self.tor_path,
|
||||
self.tor_geo_ip_file_path,
|
||||
self.tor_geo_ipv6_file_path,
|
||||
self.obfs4proxy_file_path,
|
||||
) = self.common.get_tor_paths()
|
||||
|
||||
# The tor process
|
||||
self.tor_proc = None
|
||||
|
||||
# The Tor controller
|
||||
self.c = None
|
||||
|
||||
# Start out not connected to Tor
|
||||
self.connected_to_tor = False
|
||||
|
||||
# Assigned later if we are using stealth mode
|
||||
self.auth_string = None
|
||||
|
||||
def connect(
|
||||
self,
|
||||
custom_settings=None,
|
||||
config=None,
|
||||
tor_status_update_func=None,
|
||||
connect_timeout=120,
|
||||
local_only=False,
|
||||
):
|
||||
if local_only:
|
||||
self.common.log(
|
||||
"Onion", "connect", "--local-only, so skip trying to connect"
|
||||
)
|
||||
return
|
||||
|
||||
self.common.log("Onion", "connect")
|
||||
|
||||
# Either use settings that are passed in, or use them from common
|
||||
if custom_settings:
|
||||
self.settings = custom_settings
|
||||
elif config:
|
||||
self.common.load_settings(config)
|
||||
self.settings = self.common.settings
|
||||
else:
|
||||
self.common.load_settings()
|
||||
self.settings = self.common.settings
|
||||
|
||||
# The Tor controller
|
||||
self.c = None
|
||||
|
||||
if self.settings.get("connection_type") == "bundled":
|
||||
if not self.bundle_tor_supported:
|
||||
raise BundledTorNotSupported(
|
||||
# strings._("settings_error_bundled_tor_not_supported")
|
||||
"Using the Tor version that comes with OnionShare does not work in developer mode on Windows or macOS."
|
||||
)
|
||||
|
||||
# Create a torrc for this session
|
||||
if self.use_tmp_dir:
|
||||
self.tor_data_directory = tempfile.TemporaryDirectory(
|
||||
dir=self.common.build_tmp_dir()
|
||||
)
|
||||
self.tor_data_directory_name = self.tor_data_directory.name
|
||||
else:
|
||||
self.tor_data_directory_name = self.common.build_tor_dir()
|
||||
self.common.log(
|
||||
"Onion",
|
||||
"connect",
|
||||
f"tor_data_directory_name={self.tor_data_directory_name}",
|
||||
)
|
||||
|
||||
# Create the torrc
|
||||
with open(self.common.get_resource_path("torrc_template")) as f:
|
||||
torrc_template = f.read()
|
||||
self.tor_cookie_auth_file = os.path.join(
|
||||
self.tor_data_directory_name, "cookie"
|
||||
)
|
||||
try:
|
||||
self.tor_socks_port = self.common.get_available_port(1000, 65535)
|
||||
except:
|
||||
raise OSError("OnionShare port not available")
|
||||
self.tor_torrc = os.path.join(self.tor_data_directory_name, "torrc")
|
||||
|
||||
if self.common.platform == "Windows" or self.common.platform == "Darwin":
|
||||
# Windows doesn't support unix sockets, so it must use a network port.
|
||||
# macOS can't use unix sockets either because socket filenames are limited to
|
||||
# 100 chars, and the macOS sandbox forces us to put the socket file in a place
|
||||
# with a really long path.
|
||||
torrc_template += "ControlPort {{control_port}}\n"
|
||||
try:
|
||||
self.tor_control_port = self.common.get_available_port(1000, 65535)
|
||||
except:
|
||||
raise OSError("OnionShare port not available")
|
||||
self.tor_control_socket = None
|
||||
else:
|
||||
# Linux and BSD can use unix sockets
|
||||
torrc_template += "ControlSocket {{control_socket}}\n"
|
||||
self.tor_control_port = None
|
||||
self.tor_control_socket = os.path.join(
|
||||
self.tor_data_directory_name, "control_socket"
|
||||
)
|
||||
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{data_directory}}", self.tor_data_directory_name
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{control_port}}", str(self.tor_control_port)
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{control_socket}}", str(self.tor_control_socket)
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{cookie_auth_file}}", self.tor_cookie_auth_file
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{geo_ip_file}}", self.tor_geo_ip_file_path
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{geo_ipv6_file}}", self.tor_geo_ipv6_file_path
|
||||
)
|
||||
torrc_template = torrc_template.replace(
|
||||
"{{socks_port}}", str(self.tor_socks_port)
|
||||
)
|
||||
|
||||
with open(self.tor_torrc, "w") as f:
|
||||
f.write(torrc_template)
|
||||
|
||||
# Bridge support
|
||||
if self.settings.get("tor_bridges_use_obfs4"):
|
||||
f.write(
|
||||
f"ClientTransportPlugin obfs4 exec {self.obfs4proxy_file_path}\n"
|
||||
)
|
||||
with open(
|
||||
self.common.get_resource_path("torrc_template-obfs4")
|
||||
) as o:
|
||||
for line in o:
|
||||
f.write(line)
|
||||
elif self.settings.get("tor_bridges_use_meek_lite_azure"):
|
||||
f.write(
|
||||
f"ClientTransportPlugin meek_lite exec {self.obfs4proxy_file_path}\n"
|
||||
)
|
||||
with open(
|
||||
self.common.get_resource_path("torrc_template-meek_lite_azure")
|
||||
) as o:
|
||||
for line in o:
|
||||
f.write(line)
|
||||
|
||||
if self.settings.get("tor_bridges_use_custom_bridges"):
|
||||
if "obfs4" in self.settings.get("tor_bridges_use_custom_bridges"):
|
||||
f.write(
|
||||
f"ClientTransportPlugin obfs4 exec {self.obfs4proxy_file_path}\n"
|
||||
)
|
||||
elif "meek_lite" in self.settings.get(
|
||||
"tor_bridges_use_custom_bridges"
|
||||
):
|
||||
f.write(
|
||||
f"ClientTransportPlugin meek_lite exec {self.obfs4proxy_file_path}\n"
|
||||
)
|
||||
f.write(self.settings.get("tor_bridges_use_custom_bridges"))
|
||||
f.write("\nUseBridges 1")
|
||||
|
||||
# Execute a tor subprocess
|
||||
start_ts = time.time()
|
||||
if self.common.platform == "Windows":
|
||||
# In Windows, hide console window when opening tor.exe subprocess
|
||||
startupinfo = subprocess.STARTUPINFO()
|
||||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||
self.tor_proc = subprocess.Popen(
|
||||
[self.tor_path, "-f", self.tor_torrc],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
startupinfo=startupinfo,
|
||||
)
|
||||
else:
|
||||
self.tor_proc = subprocess.Popen(
|
||||
[self.tor_path, "-f", self.tor_torrc],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
|
||||
# Wait for the tor controller to start
|
||||
time.sleep(2)
|
||||
|
||||
# Connect to the controller
|
||||
try:
|
||||
if (
|
||||
self.common.platform == "Windows"
|
||||
or self.common.platform == "Darwin"
|
||||
):
|
||||
self.c = Controller.from_port(port=self.tor_control_port)
|
||||
self.c.authenticate()
|
||||
else:
|
||||
self.c = Controller.from_socket_file(path=self.tor_control_socket)
|
||||
self.c.authenticate()
|
||||
except Exception as e:
|
||||
raise BundledTorBroken(
|
||||
# strings._("settings_error_bundled_tor_broken").format(e.args[0])
|
||||
"OnionShare could not connect to Tor:\n{}".format(e.args[0])
|
||||
)
|
||||
|
||||
while True:
|
||||
try:
|
||||
res = self.c.get_info("status/bootstrap-phase")
|
||||
except SocketClosed:
|
||||
raise BundledTorCanceled()
|
||||
|
||||
res_parts = shlex.split(res)
|
||||
progress = res_parts[2].split("=")[1]
|
||||
summary = res_parts[4].split("=")[1]
|
||||
|
||||
# "\033[K" clears the rest of the line
|
||||
print(
|
||||
f"\rConnecting to the Tor network: {progress}% - {summary}\033[K",
|
||||
end="",
|
||||
)
|
||||
|
||||
if callable(tor_status_update_func):
|
||||
if not tor_status_update_func(progress, summary):
|
||||
# If the dialog was canceled, stop connecting to Tor
|
||||
self.common.log(
|
||||
"Onion",
|
||||
"connect",
|
||||
"tor_status_update_func returned false, canceling connecting to Tor",
|
||||
)
|
||||
print()
|
||||
return False
|
||||
|
||||
if summary == "Done":
|
||||
print("")
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
# If using bridges, it might take a bit longer to connect to Tor
|
||||
if (
|
||||
self.settings.get("tor_bridges_use_custom_bridges")
|
||||
or self.settings.get("tor_bridges_use_obfs4")
|
||||
or self.settings.get("tor_bridges_use_meek_lite_azure")
|
||||
):
|
||||
# Only override timeout if a custom timeout has not been passed in
|
||||
if connect_timeout == 120:
|
||||
connect_timeout = 150
|
||||
if time.time() - start_ts > connect_timeout:
|
||||
print("")
|
||||
try:
|
||||
self.tor_proc.terminate()
|
||||
raise BundledTorTimeout(
|
||||
# strings._("settings_error_bundled_tor_timeout")
|
||||
"Taking too long to connect to Tor. Maybe you aren't connected to the Internet, or have an inaccurate system clock?"
|
||||
)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
elif self.settings.get("connection_type") == "automatic":
|
||||
# Automatically try to guess the right way to connect to Tor Browser
|
||||
|
||||
# Try connecting to control port
|
||||
found_tor = False
|
||||
|
||||
# If the TOR_CONTROL_PORT environment variable is set, use that
|
||||
env_port = os.environ.get("TOR_CONTROL_PORT")
|
||||
if env_port:
|
||||
try:
|
||||
self.c = Controller.from_port(port=int(env_port))
|
||||
found_tor = True
|
||||
except:
|
||||
pass
|
||||
|
||||
else:
|
||||
# Otherwise, try default ports for Tor Browser, Tor Messenger, and system tor
|
||||
try:
|
||||
ports = [9151, 9153, 9051]
|
||||
for port in ports:
|
||||
self.c = Controller.from_port(port=port)
|
||||
found_tor = True
|
||||
except:
|
||||
pass
|
||||
|
||||
# If this still didn't work, try guessing the default socket file path
|
||||
socket_file_path = ""
|
||||
if not found_tor:
|
||||
try:
|
||||
if self.common.platform == "Darwin":
|
||||
socket_file_path = os.path.expanduser(
|
||||
"~/Library/Application Support/TorBrowser-Data/Tor/control.socket"
|
||||
)
|
||||
|
||||
self.c = Controller.from_socket_file(path=socket_file_path)
|
||||
found_tor = True
|
||||
except:
|
||||
pass
|
||||
|
||||
# If connecting to default control ports failed, so let's try
|
||||
# guessing the socket file name next
|
||||
if not found_tor:
|
||||
try:
|
||||
if self.common.platform == "Linux" or self.common.platform == "BSD":
|
||||
socket_file_path = (
|
||||
f"/run/user/{os.geteuid()}/Tor/control.socket"
|
||||
)
|
||||
elif self.common.platform == "Darwin":
|
||||
socket_file_path = (
|
||||
f"/run/user/{os.geteuid()}/Tor/control.socket"
|
||||
)
|
||||
elif self.common.platform == "Windows":
|
||||
# Windows doesn't support unix sockets
|
||||
raise TorErrorAutomatic(
|
||||
# strings._("settings_error_automatic")
|
||||
"Could not connect to the Tor controller. Is Tor Browser (available from torproject.org) running in the background?"
|
||||
)
|
||||
|
||||
self.c = Controller.from_socket_file(path=socket_file_path)
|
||||
|
||||
except:
|
||||
raise TorErrorAutomatic(
|
||||
# strings._("settings_error_automatic")
|
||||
"Could not connect to the Tor controller. Is Tor Browser (available from torproject.org) running in the background?"
|
||||
)
|
||||
|
||||
# Try authenticating
|
||||
try:
|
||||
self.c.authenticate()
|
||||
except:
|
||||
raise TorErrorAutomatic(
|
||||
# strings._("settings_error_automatic")
|
||||
"Could not connect to the Tor controller. Is Tor Browser (available from torproject.org) running in the background?"
|
||||
)
|
||||
|
||||
else:
|
||||
# Use specific settings to connect to tor
|
||||
|
||||
# Try connecting
|
||||
try:
|
||||
if self.settings.get("connection_type") == "control_port":
|
||||
self.c = Controller.from_port(
|
||||
address=self.settings.get("control_port_address"),
|
||||
port=self.settings.get("control_port_port"),
|
||||
)
|
||||
elif self.settings.get("connection_type") == "socket_file":
|
||||
self.c = Controller.from_socket_file(
|
||||
path=self.settings.get("socket_file_path")
|
||||
)
|
||||
else:
|
||||
raise TorErrorInvalidSetting(
|
||||
# strings._("settings_error_unknown")
|
||||
"Can't connect to Tor controller because your settings don't make sense."
|
||||
)
|
||||
|
||||
except:
|
||||
if self.settings.get("connection_type") == "control_port":
|
||||
raise TorErrorSocketPort(
|
||||
# strings._("settings_error_socket_port")
|
||||
"Can't connect to the Tor controller at {}:{}.".format(
|
||||
self.settings.get("control_port_address"),
|
||||
self.settings.get("control_port_port"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
raise TorErrorSocketFile(
|
||||
# strings._("settings_error_socket_file")
|
||||
"Can't connect to the Tor controller using socket file {}.".format(
|
||||
self.settings.get("socket_file_path")
|
||||
)
|
||||
)
|
||||
|
||||
# Try authenticating
|
||||
try:
|
||||
if self.settings.get("auth_type") == "no_auth":
|
||||
self.c.authenticate()
|
||||
elif self.settings.get("auth_type") == "password":
|
||||
self.c.authenticate(self.settings.get("auth_password"))
|
||||
else:
|
||||
raise TorErrorInvalidSetting(
|
||||
# strings._("settings_error_unknown")
|
||||
"Can't connect to Tor controller because your settings don't make sense."
|
||||
)
|
||||
|
||||
except MissingPassword:
|
||||
raise TorErrorMissingPassword(
|
||||
# strings._("settings_error_missing_password")
|
||||
"Connected to Tor controller, but it requires a password to authenticate."
|
||||
)
|
||||
except UnreadableCookieFile:
|
||||
raise TorErrorUnreadableCookieFile(
|
||||
# strings._("settings_error_unreadable_cookie_file")
|
||||
"Connected to the Tor controller, but password may be wrong, or your user is not permitted to read the cookie file."
|
||||
)
|
||||
except AuthenticationFailure:
|
||||
raise TorErrorAuthError(
|
||||
# strings._("settings_error_auth")
|
||||
"Connected to {}:{}, but can't authenticate. Maybe this isn't a Tor controller?".format(
|
||||
self.settings.get("control_port_address"),
|
||||
self.settings.get("control_port_port"),
|
||||
)
|
||||
)
|
||||
|
||||
# If we made it this far, we should be connected to Tor
|
||||
self.connected_to_tor = True
|
||||
|
||||
# Get the tor version
|
||||
self.tor_version = self.c.get_version().version_str
|
||||
self.common.log("Onion", "connect", f"Connected to tor {self.tor_version}")
|
||||
|
||||
# Do the versions of stem and tor that I'm using support ephemeral onion services?
|
||||
list_ephemeral_hidden_services = getattr(
|
||||
self.c, "list_ephemeral_hidden_services", None
|
||||
)
|
||||
self.supports_ephemeral = (
|
||||
callable(list_ephemeral_hidden_services) and self.tor_version >= "0.2.7.1"
|
||||
)
|
||||
|
||||
# Do the versions of stem and tor that I'm using support stealth onion services?
|
||||
try:
|
||||
res = self.c.create_ephemeral_hidden_service(
|
||||
{1: 1},
|
||||
basic_auth={"onionshare": None},
|
||||
await_publication=False,
|
||||
key_type="NEW",
|
||||
key_content="RSA1024",
|
||||
)
|
||||
tmp_service_id = res.service_id
|
||||
self.c.remove_ephemeral_hidden_service(tmp_service_id)
|
||||
self.supports_stealth = True
|
||||
except:
|
||||
# ephemeral stealth onion services are not supported
|
||||
self.supports_stealth = False
|
||||
|
||||
# Does this version of Tor support next-gen ('v3') onions?
|
||||
# Note, this is the version of Tor where this bug was fixed:
|
||||
# https://trac.torproject.org/projects/tor/ticket/28619
|
||||
self.supports_v3_onions = self.tor_version >= Version("0.3.5.7")
|
||||
|
||||
def is_authenticated(self):
|
||||
"""
|
||||
Returns True if the Tor connection is still working, or False otherwise.
|
||||
"""
|
||||
if self.c is not None:
|
||||
return self.c.is_authenticated()
|
||||
else:
|
||||
return False
|
||||
|
||||
def start_onion_service(self, mode_settings, port, await_publication):
|
||||
"""
|
||||
Start a onion service on port 80, pointing to the given port, and
|
||||
return the onion hostname.
|
||||
"""
|
||||
self.common.log("Onion", "start_onion_service", f"port={port}")
|
||||
|
||||
if not self.supports_ephemeral:
|
||||
raise TorTooOld(
|
||||
# strings._("error_ephemeral_not_supported")
|
||||
"Your version of Tor is too old, ephemeral onion services are not supported"
|
||||
)
|
||||
if mode_settings.get("general", "client_auth") and not self.supports_stealth:
|
||||
raise TorTooOld(
|
||||
# strings._("error_stealth_not_supported")
|
||||
"Your version of Tor is too old, stealth onion services are not supported"
|
||||
)
|
||||
|
||||
auth_cookie = None
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
if mode_settings.get("onion", "hidservauth_string"):
|
||||
auth_cookie = mode_settings.get("onion", "hidservauth_string").split()[
|
||||
2
|
||||
]
|
||||
if auth_cookie:
|
||||
basic_auth = {"onionshare": auth_cookie}
|
||||
else:
|
||||
# If we had neither a scheduled auth cookie or a persistent hidservauth string,
|
||||
# set the cookie to 'None', which means Tor will create one for us
|
||||
basic_auth = {"onionshare": None}
|
||||
else:
|
||||
# Not using client auth at all
|
||||
basic_auth = None
|
||||
|
||||
if mode_settings.get("onion", "private_key"):
|
||||
key_content = mode_settings.get("onion", "private_key")
|
||||
if self.is_v2_key(key_content):
|
||||
key_type = "RSA1024"
|
||||
else:
|
||||
# Assume it was a v3 key. Stem will throw an error if it's something illegible
|
||||
key_type = "ED25519-V3"
|
||||
else:
|
||||
key_type = "NEW"
|
||||
# Work out if we can support v3 onion services, which are preferred
|
||||
if self.supports_v3_onions and not mode_settings.get("general", "legacy"):
|
||||
key_content = "ED25519-V3"
|
||||
else:
|
||||
# fall back to v2 onion services
|
||||
key_content = "RSA1024"
|
||||
|
||||
# v3 onions don't yet support basic auth. Our ticket:
|
||||
# https://github.com/micahflee/onionshare/issues/697
|
||||
if (
|
||||
key_type == "NEW"
|
||||
and key_content == "ED25519-V3"
|
||||
and not mode_settings.get("general", "legacy")
|
||||
):
|
||||
basic_auth = None
|
||||
|
||||
debug_message = f"key_type={key_type}"
|
||||
if key_type == "NEW":
|
||||
debug_message += f", key_content={key_content}"
|
||||
self.common.log("Onion", "start_onion_service", debug_message)
|
||||
try:
|
||||
res = self.c.create_ephemeral_hidden_service(
|
||||
{80: port},
|
||||
await_publication=await_publication,
|
||||
basic_auth=basic_auth,
|
||||
key_type=key_type,
|
||||
key_content=key_content,
|
||||
)
|
||||
|
||||
except ProtocolError as e:
|
||||
raise TorErrorProtocolError(
|
||||
# strings._("error_tor_protocol_error")
|
||||
"Tor error: {}".format(e.args[0])
|
||||
)
|
||||
|
||||
onion_host = res.service_id + ".onion"
|
||||
|
||||
# Save the service_id
|
||||
mode_settings.set("general", "service_id", res.service_id)
|
||||
|
||||
# Save the private key and hidservauth string
|
||||
if not mode_settings.get("onion", "private_key"):
|
||||
mode_settings.set("onion", "private_key", res.private_key)
|
||||
if mode_settings.get("general", "client_auth") and not mode_settings.get(
|
||||
"onion", "hidservauth_string"
|
||||
):
|
||||
auth_cookie = list(res.client_auth.values())[0]
|
||||
self.auth_string = f"HidServAuth {onion_host} {auth_cookie}"
|
||||
mode_settings.set("onion", "hidservauth_string", self.auth_string)
|
||||
|
||||
return onion_host
|
||||
|
||||
def stop_onion_service(self, mode_settings):
|
||||
"""
|
||||
Stop a specific onion service
|
||||
"""
|
||||
onion_host = mode_settings.get("general", "service_id")
|
||||
if onion_host:
|
||||
self.common.log("Onion", "stop_onion_service", f"onion host: {onion_host}")
|
||||
try:
|
||||
self.c.remove_ephemeral_hidden_service(
|
||||
mode_settings.get("general", "service_id")
|
||||
)
|
||||
except:
|
||||
self.common.log(
|
||||
"Onion", "stop_onion_service", f"failed to remove {onion_host}"
|
||||
)
|
||||
|
||||
def cleanup(self, stop_tor=True):
|
||||
"""
|
||||
Stop onion services that were created earlier. If there's a tor subprocess running, kill it.
|
||||
"""
|
||||
self.common.log("Onion", "cleanup")
|
||||
|
||||
# Cleanup the ephemeral onion services, if we have any
|
||||
try:
|
||||
onions = self.c.list_ephemeral_hidden_services()
|
||||
for service_id in onions:
|
||||
onion_host = f"{service_id}.onion"
|
||||
try:
|
||||
self.common.log(
|
||||
"Onion", "cleanup", f"trying to remove onion {onion_host}"
|
||||
)
|
||||
self.c.remove_ephemeral_hidden_service(service_id)
|
||||
except:
|
||||
self.common.log(
|
||||
"Onion", "cleanup", f"failed to remove onion {onion_host}"
|
||||
)
|
||||
pass
|
||||
except:
|
||||
pass
|
||||
|
||||
if stop_tor:
|
||||
# Stop tor process
|
||||
if self.tor_proc:
|
||||
self.tor_proc.terminate()
|
||||
time.sleep(0.2)
|
||||
if self.tor_proc.poll() is None:
|
||||
self.common.log(
|
||||
"Onion",
|
||||
"cleanup",
|
||||
"Tried to terminate tor process but it's still running",
|
||||
)
|
||||
try:
|
||||
self.tor_proc.kill()
|
||||
time.sleep(0.2)
|
||||
if self.tor_proc.poll() is None:
|
||||
self.common.log(
|
||||
"Onion",
|
||||
"cleanup",
|
||||
"Tried to kill tor process but it's still running",
|
||||
)
|
||||
except:
|
||||
self.common.log(
|
||||
"Onion", "cleanup", "Exception while killing tor process"
|
||||
)
|
||||
self.tor_proc = None
|
||||
|
||||
# Reset other Onion settings
|
||||
self.connected_to_tor = False
|
||||
|
||||
try:
|
||||
# Delete the temporary tor data directory
|
||||
if self.use_tmp_dir:
|
||||
self.tor_data_directory.cleanup()
|
||||
except:
|
||||
pass
|
||||
|
||||
def get_tor_socks_port(self):
|
||||
"""
|
||||
Returns a (address, port) tuple for the Tor SOCKS port
|
||||
"""
|
||||
self.common.log("Onion", "get_tor_socks_port")
|
||||
|
||||
if self.settings.get("connection_type") == "bundled":
|
||||
return ("127.0.0.1", self.tor_socks_port)
|
||||
elif self.settings.get("connection_type") == "automatic":
|
||||
return ("127.0.0.1", 9150)
|
||||
else:
|
||||
return (self.settings.get("socks_address"), self.settings.get("socks_port"))
|
||||
|
||||
def is_v2_key(self, key):
|
||||
"""
|
||||
Helper function for determining if a key is RSA1024 (v2) or not.
|
||||
"""
|
||||
try:
|
||||
# Import the key
|
||||
key = RSA.importKey(base64.b64decode(key))
|
||||
# Is this a v2 Onion key? (1024 bits) If so, we should keep using it.
|
||||
if key.n.bit_length() == 1024:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except:
|
||||
return False
|
111
cli/onionshare_cli/onionshare.py
Normal file
111
cli/onionshare_cli/onionshare.py
Normal file
|
@ -0,0 +1,111 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os, shutil
|
||||
|
||||
from . import common
|
||||
from .onion import TorTooOld, TorErrorProtocolError
|
||||
from .common import AutoStopTimer
|
||||
|
||||
|
||||
class OnionShare(object):
|
||||
"""
|
||||
OnionShare is the main application class. Pass in options and run
|
||||
start_onion_service and it will do the magic.
|
||||
"""
|
||||
|
||||
def __init__(self, common, onion, local_only=False, autostop_timer=0):
|
||||
self.common = common
|
||||
|
||||
self.common.log("OnionShare", "__init__")
|
||||
|
||||
# The Onion object
|
||||
self.onion = onion
|
||||
|
||||
self.hidserv_dir = None
|
||||
self.onion_host = None
|
||||
self.port = None
|
||||
|
||||
# files and dirs to delete on shutdown
|
||||
self.cleanup_filenames = []
|
||||
|
||||
# do not use tor -- for development
|
||||
self.local_only = local_only
|
||||
|
||||
# optionally shut down after N hours
|
||||
self.autostop_timer = autostop_timer
|
||||
# init auto-stop timer thread
|
||||
self.autostop_timer_thread = None
|
||||
|
||||
def choose_port(self):
|
||||
"""
|
||||
Choose a random port.
|
||||
"""
|
||||
try:
|
||||
self.port = self.common.get_available_port(17600, 17650)
|
||||
except:
|
||||
raise OSError("Cannot find an available OnionShare port")
|
||||
|
||||
def start_onion_service(self, mode_settings, await_publication=True):
|
||||
"""
|
||||
Start the onionshare onion service.
|
||||
"""
|
||||
self.common.log("OnionShare", "start_onion_service")
|
||||
|
||||
if not self.port:
|
||||
self.choose_port()
|
||||
|
||||
if self.autostop_timer > 0:
|
||||
self.autostop_timer_thread = AutoStopTimer(self.common, self.autostop_timer)
|
||||
|
||||
if self.local_only:
|
||||
self.onion_host = f"127.0.0.1:{self.port}"
|
||||
return
|
||||
|
||||
self.onion_host = self.onion.start_onion_service(
|
||||
mode_settings, self.port, await_publication
|
||||
)
|
||||
|
||||
if mode_settings.get("general", "client_auth"):
|
||||
self.auth_string = self.onion.auth_string
|
||||
|
||||
def stop_onion_service(self, mode_settings):
|
||||
"""
|
||||
Stop the onion service
|
||||
"""
|
||||
self.onion.stop_onion_service(mode_settings)
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Shut everything down and clean up temporary files, etc.
|
||||
"""
|
||||
self.common.log("OnionShare", "cleanup")
|
||||
|
||||
# Cleanup files
|
||||
try:
|
||||
for filename in self.cleanup_filenames:
|
||||
if os.path.isfile(filename):
|
||||
os.remove(filename)
|
||||
elif os.path.isdir(filename):
|
||||
shutil.rmtree(filename)
|
||||
except:
|
||||
# Don't crash if file is still in use
|
||||
pass
|
||||
self.cleanup_filenames = []
|
393
cli/onionshare_cli/resources/static/css/style.css
Normal file
393
cli/onionshare_cli/resources/static/css/style.css
Normal file
|
@ -0,0 +1,393 @@
|
|||
.clearfix:after {
|
||||
content: ".";
|
||||
display: block;
|
||||
clear: both;
|
||||
visibility: hidden;
|
||||
line-height: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
.d-flex {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
header {
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
|
||||
background: #fcfcfc;
|
||||
background: -webkit-linear-gradient(top, #fcfcfc 0%, #f2f2f2 100%);
|
||||
padding: 0.8rem;
|
||||
}
|
||||
|
||||
header .logo {
|
||||
vertical-align: middle;
|
||||
width: 45px;
|
||||
height: 45px;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
display: inline-block;
|
||||
margin: 0 0 0 0.5rem;
|
||||
vertical-align: middle;
|
||||
font-weight: normal;
|
||||
font-size: 1.5rem;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
header .information {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.button {
|
||||
color: #ffffff;
|
||||
background-color: #4e064f;
|
||||
padding: 10px;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
text-decoration: none;
|
||||
margin-left: 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
a.button:visited {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.close-button {
|
||||
color: #ffffff;
|
||||
background-color: #c90c0c;
|
||||
padding: 10px;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
text-decoration: none;
|
||||
margin-left: 1rem;
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
}
|
||||
|
||||
ul.breadcrumbs {
|
||||
display: block;
|
||||
list-style: none;
|
||||
margin: 10px 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
ul.breadcrumbs li {
|
||||
display: inline-block;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 5px;
|
||||
color: #999999;
|
||||
}
|
||||
|
||||
ul.breadcrumbs li span.sep {
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
ul.breadcrumbs li a:link, ul.breadcrumbs li a:visited {
|
||||
color: #666666;
|
||||
border-bottom: 1px solid #666666;
|
||||
}
|
||||
|
||||
.file-list {
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.file-list .heading {
|
||||
text-align: left;
|
||||
text-transform: uppercase;
|
||||
font-weight: normal;
|
||||
color: #666666;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.file-list div.d-flex {
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.file-list div.d-flex div {
|
||||
white-space: nowrap;
|
||||
padding: 0.5rem 0.8rem 0.5rem 0.8rem;
|
||||
}
|
||||
|
||||
.file-list div.d-flex div img {
|
||||
vertical-align: middle;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.file-list div.d-flex div:last-child {
|
||||
padding-right: 0.8rem;
|
||||
flex-basis: 0;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.file-list div.d-flex div:first-child {
|
||||
flex-basis: 0;
|
||||
flex-grow: 2;
|
||||
}
|
||||
|
||||
@media (max-width: 950px) {
|
||||
.file-list div.d-flex div:last-child {
|
||||
flex-basis: auto;
|
||||
flex-grow: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 655px) {
|
||||
.file-list div.d-flex {
|
||||
display: block;
|
||||
}
|
||||
.file-list div.d-flex span {
|
||||
max-width: 100%;
|
||||
word-break: break-all;
|
||||
white-space: normal;
|
||||
}
|
||||
.file-list div.d-flex #size-header {
|
||||
display: none;
|
||||
}
|
||||
.file-list div.d-flex div:last-child {
|
||||
padding-left: 3.5rem;
|
||||
font-size: 0.85rem;
|
||||
padding-top: 0;
|
||||
}
|
||||
header .information {
|
||||
padding: 1rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
display: flex;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.chat-users {
|
||||
width: 20%;
|
||||
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||
border-radius: 2px;
|
||||
overflow: auto;
|
||||
background: #f2f2f2;
|
||||
margin: 1rem 0 1rem 1rem;
|
||||
}
|
||||
|
||||
.chat-users .editable-username {
|
||||
display: flex;
|
||||
padding: 1rem;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.chat-users .editable-username input {
|
||||
font-family: monospace;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
.chat-users .editable-username #username-error {
|
||||
color: #c90c0c;
|
||||
margin: 0.5rem;
|
||||
}
|
||||
|
||||
.chat-users #user-list li {
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.chat-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
margin: 1rem 1rem 0 1rem;
|
||||
height: calc(100vh - (65px + 2em));
|
||||
}
|
||||
|
||||
.chat-wrapper #chat {
|
||||
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||
border-radius: 2px;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
background: #f2f2f2;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
.chat-wrapper .status {
|
||||
font-style: italic;
|
||||
font-size: 0.8em;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
.chat-wrapper .username {
|
||||
font-weight: bold;
|
||||
display: block;
|
||||
}
|
||||
.chat-wrapper .message {
|
||||
font-weight: normal;
|
||||
display: block;
|
||||
margin-bottom: 0.3em;
|
||||
}
|
||||
|
||||
.chat-wrapper .chat-form {
|
||||
display: block;
|
||||
margin: 0.2rem 1rem 1rem 0;
|
||||
padding: -0.5em;
|
||||
}
|
||||
|
||||
.chat-wrapper input#new-message {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
font-family: monospace;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
.chat-users .editable-username {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.chat-users input#username {
|
||||
width: 90%;
|
||||
}
|
||||
}
|
||||
|
||||
.no-js {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.upload-wrapper {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 400px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.upload-wrapper img.logo {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
}
|
||||
|
||||
.upload-wrapper .upload-header {
|
||||
font-size: 30px;
|
||||
font-weight: normal;
|
||||
color: #666666;
|
||||
margin: 0 0 10px 0;
|
||||
}
|
||||
|
||||
.upload-wrapper .upload-description {
|
||||
color: #666666;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
div#uploads {
|
||||
width: 800px;
|
||||
max-width: 90%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
div#uploads .upload {
|
||||
border: 1px solid #DDDDDD;
|
||||
margin: 20px 0;
|
||||
padding: 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
div#uploads .upload .upload-filename {
|
||||
font-weight: bold;
|
||||
font-family: monospace;
|
||||
font-size: 1.1em;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
div#uploads .upload .upload-status {
|
||||
color: #999999;
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
div#uploads .upload input.cancel {
|
||||
color: #d0011b;
|
||||
border: 0;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0px;
|
||||
cursor: pointer;
|
||||
font-family: sans-serif;
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
float:right;
|
||||
}
|
||||
|
||||
div#uploads .upload progress {
|
||||
width: 100%;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
ul.flashes {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 800px;
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
ul.flashes li {
|
||||
margin: 0 0 5px 0;
|
||||
padding: 5px;
|
||||
list-style: none;
|
||||
text-align: center;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
li.error {
|
||||
color: #d0011b;
|
||||
}
|
||||
|
||||
li.info {
|
||||
color: #5fa416;
|
||||
}
|
||||
|
||||
.closed-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.info {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.info img {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
}
|
||||
|
||||
.info .info-header {
|
||||
font-size: 30px;
|
||||
font-weight: normal;
|
||||
color: #666666;
|
||||
margin: 0 0 10px 0;
|
||||
}
|
||||
|
||||
.info .info-description {
|
||||
color: #666666;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #1c1ca0;
|
||||
}
|
||||
|
||||
a:visited {
|
||||
color: #601ca0;
|
||||
}
|
BIN
cli/onionshare_cli/resources/static/img/ajax.gif
Normal file
BIN
cli/onionshare_cli/resources/static/img/ajax.gif
Normal file
Binary file not shown.
After Width: | Height: | Size: 847 B |
BIN
cli/onionshare_cli/resources/static/img/favicon.ico
Normal file
BIN
cli/onionshare_cli/resources/static/img/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.2 KiB |
BIN
cli/onionshare_cli/resources/static/img/logo.png
Normal file
BIN
cli/onionshare_cli/resources/static/img/logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.7 KiB |
BIN
cli/onionshare_cli/resources/static/img/logo_large.png
Normal file
BIN
cli/onionshare_cli/resources/static/img/logo_large.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.4 KiB |
BIN
cli/onionshare_cli/resources/static/img/web_file.png
Normal file
BIN
cli/onionshare_cli/resources/static/img/web_file.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 251 B |
BIN
cli/onionshare_cli/resources/static/img/web_folder.png
Normal file
BIN
cli/onionshare_cli/resources/static/img/web_folder.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 338 B |
165
cli/onionshare_cli/resources/static/js/chat.js
Normal file
165
cli/onionshare_cli/resources/static/js/chat.js
Normal file
|
@ -0,0 +1,165 @@
|
|||
$(function () {
|
||||
$(document).ready(function () {
|
||||
$('.chat-container').removeClass('no-js');
|
||||
var socket = io.connect('http://' + document.domain + ':' + location.port + '/chat');
|
||||
|
||||
// Store current username received from app context
|
||||
var current_username = $('#username').val();
|
||||
|
||||
// On browser connect, emit a socket event to be added to
|
||||
// room and assigned random username
|
||||
socket.on('connect', function () {
|
||||
socket.emit('joined', {});
|
||||
});
|
||||
|
||||
// Triggered on any status change by any user, such as some
|
||||
// user joined, or changed username, or left, etc.
|
||||
socket.on('status', function (data) {
|
||||
addMessageToRoom(data, current_username, 'status');
|
||||
console.log(data, current_username);
|
||||
});
|
||||
|
||||
// Triggered when message is received from a user. Even when sent
|
||||
// by self, it get triggered after the server sends back the emit.
|
||||
socket.on('message', function (data) {
|
||||
addMessageToRoom(data, current_username, 'chat');
|
||||
console.log(data, current_username);
|
||||
});
|
||||
|
||||
// Triggered when disconnected either by server stop or timeout
|
||||
socket.on('disconnect', function (data) {
|
||||
addMessageToRoom({ 'msg': 'The chat server is disconnected.' }, current_username, 'status');
|
||||
})
|
||||
socket.on('connect_error', function (error) {
|
||||
console.log("error");
|
||||
})
|
||||
|
||||
// Trigger new message on enter or click of send message button.
|
||||
$('#new-message').on('keypress', function (e) {
|
||||
var code = e.keyCode || e.which;
|
||||
if (code == 13) {
|
||||
emitMessage(socket);
|
||||
}
|
||||
});
|
||||
|
||||
// Keep buttons disabled unless changed or not empty
|
||||
$('#username').on('keyup', function (event) {
|
||||
if ($('#username').val() !== '' && $('#username').val() !== current_username) {
|
||||
if (event.keyCode == 13) {
|
||||
current_username = updateUsername(socket) || current_username;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Show warning of losing data
|
||||
$(window).on('beforeunload', function (e) {
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
return '';
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
var addMessageToRoom = function (data, current_username, messageType) {
|
||||
var scrollDiff = getScrollDiffBefore();
|
||||
if (messageType === 'status') {
|
||||
addStatusMessage(data.msg);
|
||||
if (data.connected_users) {
|
||||
addUserList(data.connected_users, current_username);
|
||||
}
|
||||
} else if (messageType === 'chat') {
|
||||
addChatMessage(data.username, data.msg)
|
||||
}
|
||||
scrollBottomMaybe(scrollDiff);
|
||||
}
|
||||
|
||||
var emitMessage = function (socket) {
|
||||
var text = $('#new-message').val();
|
||||
$('#new-message').val('');
|
||||
$('#chat').scrollTop($('#chat')[0].scrollHeight);
|
||||
socket.emit('text', { msg: text });
|
||||
}
|
||||
|
||||
var updateUsername = function (socket) {
|
||||
var username = $('#username').val();
|
||||
if (!checkUsernameExists(username)) {
|
||||
socket.emit('update_username', { username: username });
|
||||
$.ajax({
|
||||
method: 'POST',
|
||||
url: `http://${document.domain}:${location.port}/update-session-username`,
|
||||
contentType: 'application/json',
|
||||
dataType: 'json',
|
||||
data: JSON.stringify({ 'username': username })
|
||||
}).done(function (response) {
|
||||
console.log(response);
|
||||
});
|
||||
return username;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/************************************/
|
||||
/********* Util Functions ***********/
|
||||
/************************************/
|
||||
|
||||
var createUserListHTML = function (connected_users, current_user) {
|
||||
var userListHTML = '';
|
||||
connected_users.sort();
|
||||
connected_users.forEach(function (username) {
|
||||
if (username !== current_user) {
|
||||
userListHTML += `<li>${sanitizeHTML(username)}</li>`;
|
||||
}
|
||||
});
|
||||
return userListHTML;
|
||||
}
|
||||
|
||||
var checkUsernameExists = function (username) {
|
||||
$('#username-error').text('');
|
||||
var userMatches = $('#user-list li').filter(function () {
|
||||
return $(this).text() === username;
|
||||
});
|
||||
if (userMatches.length) {
|
||||
$('#username-error').text('User with that username exists!');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
var getScrollDiffBefore = function () {
|
||||
return $('#chat').scrollTop() - ($('#chat')[0].scrollHeight - $('#chat')[0].offsetHeight);
|
||||
}
|
||||
|
||||
var scrollBottomMaybe = function (scrollDiff) {
|
||||
// Scrolls to bottom if the user is scrolled at bottom
|
||||
// if the user has scrolled upp, it wont scroll at bottom.
|
||||
// Note: when a user themselves send a message, it will still
|
||||
// scroll to the bottom even if they had scrolled up before.
|
||||
if (scrollDiff > 0) {
|
||||
$('#chat').scrollTop($('#chat')[0].scrollHeight);
|
||||
}
|
||||
}
|
||||
|
||||
var addStatusMessage = function (message) {
|
||||
$('#chat').append(
|
||||
`<p class="status">${sanitizeHTML(message)}</p>`
|
||||
);
|
||||
}
|
||||
|
||||
var addChatMessage = function (username, message) {
|
||||
$('#chat').append(`<p><span class="username">${sanitizeHTML(username)}</span><span class="message">${sanitizeHTML(message)}</span></p>`);
|
||||
}
|
||||
|
||||
var addUserList = function (connected_users, current_username) {
|
||||
$('#user-list').html(
|
||||
createUserListHTML(
|
||||
connected_users,
|
||||
current_username
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
var sanitizeHTML = function (str) {
|
||||
var temp = document.createElement('span');
|
||||
temp.textContent = str;
|
||||
return temp.innerHTML;
|
||||
};
|
2
cli/onionshare_cli/resources/static/js/jquery-3.5.1.min.js
vendored
Normal file
2
cli/onionshare_cli/resources/static/js/jquery-3.5.1.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
130
cli/onionshare_cli/resources/static/js/receive.js
Normal file
130
cli/onionshare_cli/resources/static/js/receive.js
Normal file
|
@ -0,0 +1,130 @@
|
|||
$(function(){
|
||||
// Add a flash message
|
||||
var flash = function(category, message) {
|
||||
$('#flashes').append($('<li>').addClass(category).text(message));
|
||||
};
|
||||
|
||||
var scriptSrc = document.getElementById('receive-script').src;
|
||||
var staticImgPath = scriptSrc.substr(0, scriptSrc.lastIndexOf( '/' )+1).replace('js', 'img');
|
||||
|
||||
// Intercept submitting the form
|
||||
$('#send').submit(function(event){
|
||||
event.preventDefault();
|
||||
|
||||
// Create form data, and list of filenames
|
||||
var files = $('#file-select').get(0).files;
|
||||
var filenames = [];
|
||||
var formData = new FormData();
|
||||
for(var i = 0; i < files.length; i++) {
|
||||
var file = files[i];
|
||||
filenames.push(file.name);
|
||||
formData.append('file[]', file, file.name);
|
||||
}
|
||||
|
||||
// Reset the upload form
|
||||
$('#send').get(0).reset();
|
||||
|
||||
// Don't use jQuery for ajax request, because the upload progress event doesn't
|
||||
// have access to the the XMLHttpRequest object
|
||||
var ajax = new XMLHttpRequest();
|
||||
|
||||
ajax.upload.addEventListener('progress', function(event){
|
||||
// Update progress bar for this specific upload
|
||||
if(event.lengthComputable) {
|
||||
$('progress', ajax.$upload_div).attr({
|
||||
value: event.loaded,
|
||||
max: event.total,
|
||||
});
|
||||
}
|
||||
|
||||
// If it's finished sending all data to the first Tor node, remove cancel button
|
||||
// and update the status
|
||||
if(event.loaded == event.total) {
|
||||
$('.cancel', ajax.$upload_div).remove();
|
||||
$('.upload-status', ajax.$upload_div).html('<img src="' + staticImgPath + '/ajax.gif" alt="" /> Waiting for data to finish traversing Tor network ...');
|
||||
}
|
||||
}, false);
|
||||
|
||||
ajax.addEventListener('load', function(event){
|
||||
// Remove the upload div
|
||||
ajax.$upload_div.remove();
|
||||
|
||||
// Parse response
|
||||
try {
|
||||
var response = JSON.parse(ajax.response);
|
||||
|
||||
// The 'new_body' response replaces the whole HTML document and ends
|
||||
if('new_body' in response) {
|
||||
$('body').html(response['new_body']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show error flashes
|
||||
if('error_flashes' in response) {
|
||||
for(var i=0; i<response['error_flashes'].length; i++) {
|
||||
flash('error', response['error_flashes'][i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Show info flashes
|
||||
if('info_flashes' in response) {
|
||||
for(var i=0; i<response['info_flashes'].length; i++) {
|
||||
flash('info', response['info_flashes'][i]);
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
flash('error', 'Invalid response from server: '+data);
|
||||
}
|
||||
}, false);
|
||||
|
||||
ajax.addEventListener('error', function(event){
|
||||
flash('error', 'Error uploading: '+filenames.join(', '));
|
||||
|
||||
// Remove the upload div
|
||||
ajax.$upload_div.remove()
|
||||
}, false);
|
||||
|
||||
ajax.addEventListener('abort', function(event){
|
||||
flash('error', 'Upload aborted: '+filenames.join(', '));
|
||||
}, false);
|
||||
|
||||
// Make the upload div
|
||||
|
||||
/* The DOM for an upload looks something like this:
|
||||
<div class="upload">
|
||||
<div class="upload-meta">
|
||||
<input class="cancel" type="button" value="Cancel" />
|
||||
<div class="upload-filename">educational-video.mp4, secret-plans.pdf</div>
|
||||
<div class="upload-status">Sending to first Tor node ...</div>
|
||||
</div>
|
||||
<progress value="25" max="100"></progress>
|
||||
</div> */
|
||||
var $progress = $('<progress>').attr({ value: '0', max: 100 });
|
||||
var $cancel_button = $('<input>').addClass('cancel').attr({ type: 'button', value: 'Cancel' });
|
||||
var $upload_filename = $('<div>').addClass('upload-filename').text(filenames.join(', '));
|
||||
var $upload_status = $('<div>').addClass('upload-status').text('Sending data to initial Tor node ...');
|
||||
|
||||
var $upload_div = $('<div>')
|
||||
.addClass('upload')
|
||||
.append(
|
||||
$('<div>').addClass('upload-meta')
|
||||
.append($cancel_button)
|
||||
.append($upload_filename)
|
||||
.append($upload_status)
|
||||
)
|
||||
.append($progress);
|
||||
|
||||
$cancel_button.click(function(){
|
||||
// Abort the upload, and remove the upload div
|
||||
ajax.abort();
|
||||
$upload_div.remove()
|
||||
});
|
||||
|
||||
ajax.$upload_div = $upload_div;
|
||||
$('#uploads').append($upload_div);
|
||||
|
||||
// Send the request
|
||||
ajax.open('POST', '/upload-ajax', true);
|
||||
ajax.send(formData);
|
||||
});
|
||||
});
|
75
cli/onionshare_cli/resources/static/js/send.js
Normal file
75
cli/onionshare_cli/resources/static/js/send.js
Normal file
|
@ -0,0 +1,75 @@
|
|||
// Function to convert human-readable sizes back to bytes, for sorting
|
||||
function unhumanize(text) {
|
||||
var powers = {'b': 0, 'k': 1, 'm': 2, 'g': 3, 't': 4};
|
||||
var regex = /(\d+(?:\.\d+)?)\s?(B|K|M|G|T)?/i;
|
||||
var res = regex.exec(text);
|
||||
if(res[2] === undefined) {
|
||||
// Account for alphabetical words (file/dir names)
|
||||
return text;
|
||||
} else {
|
||||
return res[1] * Math.pow(1024, powers[res[2].toLowerCase()]);
|
||||
}
|
||||
}
|
||||
function sortTable(n) {
|
||||
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
|
||||
table = document.getElementById("file-list");
|
||||
switching = true;
|
||||
// Set the sorting direction to ascending:
|
||||
dir = "asc";
|
||||
/* Make a loop that will continue until
|
||||
no switching has been done: */
|
||||
while (switching) {
|
||||
// Start by saying: no switching is done:
|
||||
switching = false;
|
||||
rows = table.getElementsByTagName("TR");
|
||||
/* Loop through all table rows (except the
|
||||
first, which contains table headers): */
|
||||
for (i = 1; i < (rows.length - 1); i++) {
|
||||
// Start by saying there should be no switching:
|
||||
shouldSwitch = false;
|
||||
/* Get the two elements you want to compare,
|
||||
one from current row and one from the next: */
|
||||
x = rows[i].getElementsByTagName("TD")[n];
|
||||
y = rows[i + 1].getElementsByTagName("TD")[n];
|
||||
/* Check if the two rows should switch place,
|
||||
based on the direction, asc or desc: */
|
||||
if (dir == "asc") {
|
||||
if (unhumanize(x.innerHTML.toLowerCase()) > unhumanize(y.innerHTML.toLowerCase())) {
|
||||
// If so, mark as a switch and break the loop:
|
||||
shouldSwitch= true;
|
||||
break;
|
||||
}
|
||||
} else if (dir == "desc") {
|
||||
if (unhumanize(x.innerHTML.toLowerCase()) < unhumanize(y.innerHTML.toLowerCase())) {
|
||||
// If so, mark as a switch and break the loop:
|
||||
shouldSwitch= true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldSwitch) {
|
||||
/* If a switch has been marked, make the switch
|
||||
and mark that a switch has been done: */
|
||||
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
|
||||
switching = true;
|
||||
// Each time a switch is done, increase this count by 1:
|
||||
switchcount ++;
|
||||
} else {
|
||||
/* If no switching has been done AND the direction is "asc",
|
||||
set the direction to "desc" and run the while loop again. */
|
||||
if (switchcount == 0 && dir == "asc") {
|
||||
dir = "desc";
|
||||
switching = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Set click handlers
|
||||
document.getElementById("filename-header").addEventListener("click", function(){
|
||||
sortTable(0);
|
||||
});
|
||||
document.getElementById("size-header").addEventListener("click", function(){
|
||||
sortTable(1);
|
||||
});
|
3
cli/onionshare_cli/resources/static/js/socket.io.min.js
vendored
Normal file
3
cli/onionshare_cli/resources/static/js/socket.io.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
21
cli/onionshare_cli/resources/templates/401.html
Normal file
21
cli/onionshare_cli/resources/templates/401.html
Normal file
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare: 401 Unauthorized Access</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="info-wrapper">
|
||||
<div class="info">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
<p class="info-header">401 Unauthorized Access</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
21
cli/onionshare_cli/resources/templates/403.html
Normal file
21
cli/onionshare_cli/resources/templates/403.html
Normal file
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare: 403 Forbidden</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="info-wrapper">
|
||||
<div class="info">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
<p class="info-header">You are not allowed to perform that action at this time.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
21
cli/onionshare_cli/resources/templates/404.html
Normal file
21
cli/onionshare_cli/resources/templates/404.html
Normal file
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare: 404 Not Found</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="info-wrapper">
|
||||
<div class="info">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
<p class="info-header">404 Not Found</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
21
cli/onionshare_cli/resources/templates/405.html
Normal file
21
cli/onionshare_cli/resources/templates/405.html
Normal file
|
@ -0,0 +1,21 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare: 405 Method Not Allowed</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="info-wrapper">
|
||||
<div class="info">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
<p class="info-header">405 Method Not Allowed</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
46
cli/onionshare_cli/resources/templates/chat.html
Normal file
46
cli/onionshare_cli/resources/templates/chat.html
Normal file
|
@ -0,0 +1,46 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare</title>
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<header class="clearfix">
|
||||
<img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
|
||||
<h1>OnionShare</h1>
|
||||
</header>
|
||||
<noscript>
|
||||
<p>
|
||||
Chat <b>requires JavaScript</b>, so you must set your Tor Browser security
|
||||
level to <b>Safer</b> or <b>Standard</b> to join.
|
||||
</p>
|
||||
</noscript>
|
||||
|
||||
<div class="chat-container no-js">
|
||||
<div class="chat-users">
|
||||
<div class="editable-username">
|
||||
<input id="username" value="{{ username }}" />
|
||||
<p id="username-error"></p>
|
||||
</div>
|
||||
<ul id="user-list">
|
||||
</ul>
|
||||
</div>
|
||||
<div class="chat-wrapper">
|
||||
<div id="chat"></div>
|
||||
|
||||
<div class="chat-form">
|
||||
<input type="text" id="new-message" name="new-message" placeholder="Type your message" />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<script src="{{ static_url_path }}/js/jquery-3.5.1.min.js"></script>
|
||||
<script src="{{ static_url_path }}/js/socket.io.min.js"></script>
|
||||
<script async src="{{ static_url_path }}/js/chat.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
15
cli/onionshare_cli/resources/templates/denied.html
Normal file
15
cli/onionshare_cli/resources/templates/denied.html
Normal file
|
@ -0,0 +1,15 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<p>OnionShare download in progress</p>
|
||||
</body>
|
||||
|
||||
</html>
|
55
cli/onionshare_cli/resources/templates/listing.html
Normal file
55
cli/onionshare_cli/resources/templates/listing.html
Normal file
|
@ -0,0 +1,55 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>OnionShare</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
|
||||
<link href="{{ static_url_path }}/css/style.css" rel="stylesheet" type="text/css" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="clearfix">
|
||||
<img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
|
||||
<h1>OnionShare</h1>
|
||||
</header>
|
||||
|
||||
{% if breadcrumbs %}
|
||||
<ul class="breadcrumbs">
|
||||
{% for breadcrumb in breadcrumbs %}<li><a href="{{ breadcrumb[1] }}">{{ breadcrumb[0] }}</a> <span class="sep">‣</span></li>{% endfor %}<li>{{ breadcrumbs_leaf }}</li>
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
<table class="file-list" id="file-list">
|
||||
<tr>
|
||||
<th id="filename-header">Filename</th>
|
||||
<th id="size-header">Size</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
|
||||
{% for info in dirs %}
|
||||
<tr>
|
||||
<td>
|
||||
<img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_folder.png" />
|
||||
<a href="{{ info.basename }}">
|
||||
{{ info.basename }}
|
||||
</a>
|
||||
</td>
|
||||
<td>—</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
{% for info in files %}
|
||||
<tr>
|
||||
<td>
|
||||
<img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_file.png" />
|
||||
<a href="{{ info.basename }}">
|
||||
{{ info.basename }}
|
||||
</a>
|
||||
</td>
|
||||
<td>{{ info.size_human }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
46
cli/onionshare_cli/resources/templates/receive.html
Normal file
46
cli/onionshare_cli/resources/templates/receive.html
Normal file
|
@ -0,0 +1,46 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>OnionShare</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="clearfix">
|
||||
<img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
|
||||
<h1>OnionShare</h1>
|
||||
</header>
|
||||
|
||||
<div class="upload-wrapper">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
|
||||
<p class="upload-header">Send Files</p>
|
||||
<p class="upload-description">Select the files you want to send, then click "Send Files"...</p>
|
||||
|
||||
<div id="uploads"></div>
|
||||
|
||||
<div>
|
||||
<ul id="flashes" class="flashes">
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<li class="{{ category }}">{{ message }}</li>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<form id="send" method="post" enctype="multipart/form-data" action="/upload">
|
||||
<p><input type="file" id="file-select" name="file[]" multiple /></p>
|
||||
<p><button type="submit" id="send-button" class="button">Send Files</button></p>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
<script src="{{ static_url_path }}/js/jquery-3.5.1.min.js"></script>
|
||||
<script async src="{{ static_url_path }}/js/receive.js" id="receive-script"></script>
|
||||
</body>
|
||||
</html>
|
69
cli/onionshare_cli/resources/templates/send.html
Normal file
69
cli/onionshare_cli/resources/templates/send.html
Normal file
|
@ -0,0 +1,69 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
<meta name="onionshare-filename" content="{{ filename }}">
|
||||
<meta name="onionshare-filesize" content="{{ filesize }}">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<header class="d-flex">
|
||||
<div class="logo-container">
|
||||
<img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
|
||||
<h1>OnionShare</h1>
|
||||
</div>
|
||||
<div class="information d-flex">
|
||||
<div>Total size: <strong>{{ filesize_human }}</strong> {% if is_zipped %} (compressed){% endif %}</div>
|
||||
<a class="button" href='/download'>Download Files</a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{% if breadcrumbs %}
|
||||
<ul class="breadcrumbs">
|
||||
{% for breadcrumb in breadcrumbs %}<li><a href="{{ breadcrumb[1] }}">{{ breadcrumb[0] }}</a> <span class="sep">‣</span></li>{% endfor %}<li>{{ breadcrumbs_leaf }}</li>
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
<div class="file-list" id="file-list">
|
||||
<div class="d-flex">
|
||||
<div id="filename-header" class="heading">Filename</div>
|
||||
<div id="size-header" class="heading">Size</div>
|
||||
</div>
|
||||
{% for info in dirs %}
|
||||
<div class="d-flex">
|
||||
<div>
|
||||
<img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_folder.png" />
|
||||
<a href="{{ info.basename }}">
|
||||
<span>{{ info.basename }}</span>
|
||||
</a>
|
||||
</div>
|
||||
<div>—</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{% for info in files %}
|
||||
<div class="d-flex">
|
||||
<div>
|
||||
<img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_file.png" />
|
||||
{% if download_individual_files %}
|
||||
<a href="{{ info.basename }}">
|
||||
<span>{{ info.basename }}</span>
|
||||
</a>
|
||||
{% else %}
|
||||
<span>{{ info.basename }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div>{{ info.size_human }}</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<script async src="{{ static_url_path }}/js/send.js" charset="utf-8"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
27
cli/onionshare_cli/resources/templates/thankyou.html
Normal file
27
cli/onionshare_cli/resources/templates/thankyou.html
Normal file
|
@ -0,0 +1,27 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>OnionShare is closed</title>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="stylesheet" rel="subresource" type="text/css" href="{{ static_url_path }}/css/style.css" media="all">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header class="clearfix">
|
||||
<img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
|
||||
<h1>OnionShare</h1>
|
||||
</header>
|
||||
|
||||
<div class="info-wrapper">
|
||||
<div class="info">
|
||||
<p><img class="logo" src="{{ static_url_path }}/img/logo_large.png" title="OnionShare"></p>
|
||||
<p class="info-header">Thank you for using OnionShare</p>
|
||||
<p class="info-description">You may now close this window.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
8
cli/onionshare_cli/resources/torrc_template
Normal file
8
cli/onionshare_cli/resources/torrc_template
Normal file
|
@ -0,0 +1,8 @@
|
|||
DataDirectory {{data_directory}}
|
||||
SocksPort {{socks_port}}
|
||||
CookieAuthentication 1
|
||||
CookieAuthFile {{cookie_auth_file}}
|
||||
AvoidDiskWrites 1
|
||||
Log notice stdout
|
||||
GeoIPFile {{geo_ip_file}}
|
||||
GeoIPv6File {{geo_ipv6_file}}
|
|
@ -0,0 +1,2 @@
|
|||
Bridge meek_lite 0.0.2.0:2 B9E7141C594AF25699E0079C1F0146F409495296 url=https://d2cly7j4zqgua7.cloudfront.net/ front=a0.awsstatic.com
|
||||
UseBridges 1
|
|
@ -0,0 +1,2 @@
|
|||
Bridge meek_lite 0.0.2.0:3 97700DFE9F483596DDA6264C4D7DF7641E1E39CE url=https://meek.azureedge.net/ front=ajax.aspnetcdn.com
|
||||
UseBridges 1
|
27
cli/onionshare_cli/resources/torrc_template-obfs4
Normal file
27
cli/onionshare_cli/resources/torrc_template-obfs4
Normal file
|
@ -0,0 +1,27 @@
|
|||
Bridge obfs4 154.35.22.10:80 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0
|
||||
Bridge obfs4 83.212.101.3:50002 A09D536DD1752D542E1FBB3C9CE4449D51298239 cert=lPRQ/MXdD1t5SRZ9MquYQNT9m5DV757jtdXdlePmRCudUU9CFUOX1Tm7/meFSyPOsud7Cw iat-mode=0
|
||||
Bridge obfs4 109.105.109.165:10527 8DFCD8FB3285E855F5A55EDDA35696C743ABFC4E cert=Bvg/itxeL4TWKLP6N1MaQzSOC6tcRIBv6q57DYAZc3b2AzuM+/TfB7mqTFEfXILCjEwzVA iat-mode=1
|
||||
Bridge obfs4 154.35.22.11:80 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0
|
||||
Bridge obfs4 37.218.245.14:38224 D9A82D2F9C2F65A18407B1D2B764F130847F8B5D cert=bjRaMrr1BRiAW8IE9U5z27fQaYgOhX1UCmOpg2pFpoMvo6ZgQMzLsaTzzQNTlm7hNcb+Sg iat-mode=0
|
||||
Bridge obfs4 154.35.22.9:443 C73ADBAC8ADFDBF0FC0F3F4E8091C0107D093716 cert=gEGKc5WN/bSjFa6UkG9hOcft1tuK+cV8hbZ0H6cqXiMPLqSbCh2Q3PHe5OOr6oMVORhoJA iat-mode=0
|
||||
Bridge obfs4 154.35.22.11:443 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0
|
||||
Bridge obfs4 154.35.22.13:443 FE7840FE1E21FE0A0639ED176EDA00A3ECA1E34D cert=fKnzxr+m+jWXXQGCaXe4f2gGoPXMzbL+bTBbXMYXuK0tMotd+nXyS33y2mONZWU29l81CA iat-mode=0
|
||||
Bridge obfs4 154.35.22.10:443 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0
|
||||
Bridge obfs4 154.35.22.9:80 C73ADBAC8ADFDBF0FC0F3F4E8091C0107D093716 cert=gEGKc5WN/bSjFa6UkG9hOcft1tuK+cV8hbZ0H6cqXiMPLqSbCh2Q3PHe5OOr6oMVORhoJA iat-mode=0
|
||||
Bridge obfs4 192.99.11.54:443 7B126FAB960E5AC6A629C729434FF84FB5074EC2 cert=VW5f8+IBUWpPFxF+rsiVy2wXkyTQG7vEd+rHeN2jV5LIDNu8wMNEOqZXPwHdwMVEBdqXEw iat-mode=0
|
||||
Bridge obfs4 154.35.22.13:16815 FE7840FE1E21FE0A0639ED176EDA00A3ECA1E34D cert=fKnzxr+m+jWXXQGCaXe4f2gGoPXMzbL+bTBbXMYXuK0tMotd+nXyS33y2mONZWU29l81CA iat-mode=0
|
||||
Bridge obfs4 85.31.186.26:443 91A6354697E6B02A386312F68D82CF86824D3606 cert=PBwr+S8JTVZo6MPdHnkTwXJPILWADLqfMGoVvhZClMq/Urndyd42BwX9YFJHZnBB3H0XCw iat-mode=0
|
||||
Bridge obfs4 38.229.33.83:80 0BAC39417268B96B9F514E7F63FA6FBA1A788955 cert=VwEFpk9F/UN9JED7XpG1XOjm/O8ZCXK80oPecgWnNDZDv5pdkhq1OpbAH0wNqOT6H6BmRQ iat-mode=1
|
||||
Bridge obfs4 154.35.22.11:16488 A832D176ECD5C7C6B58825AE22FC4C90FA249637 cert=YPbQqXPiqTUBfjGFLpm9JYEFTBvnzEJDKJxXG5Sxzrr/v2qrhGU4Jls9lHjLAhqpXaEfZw iat-mode=0
|
||||
Bridge obfs4 154.35.22.9:12166 C73ADBAC8ADFDBF0FC0F3F4E8091C0107D093716 cert=gEGKc5WN/bSjFa6UkG9hOcft1tuK+cV8hbZ0H6cqXiMPLqSbCh2Q3PHe5OOr6oMVORhoJA iat-mode=0
|
||||
Bridge obfs4 109.105.109.147:13764 BBB28DF0F201E706BE564EFE690FE9577DD8386D cert=KfMQN/tNMFdda61hMgpiMI7pbwU1T+wxjTulYnfw+4sgvG0zSH7N7fwT10BI8MUdAD7iJA iat-mode=2
|
||||
Bridge obfs4 38.229.1.78:80 C8CBDB2464FC9804A69531437BCF2BE31FDD2EE4 cert=Hmyfd2ev46gGY7NoVxA9ngrPF2zCZtzskRTzoWXbxNkzeVnGFPWmrTtILRyqCTjHR+s9dg iat-mode=1
|
||||
Bridge obfs4 [2001:470:b381:bfff:216:3eff:fe23:d6c3]:443 CDF2E852BF539B82BD10E27E9115A31734E378C2 cert=qUVQ0srL1JI/vO6V6m/24anYXiJD3QP2HgzUKQtQ7GRqqUvs7P+tG43RtAqdhLOALP7DJQ iat-mode=1
|
||||
Bridge obfs4 85.17.30.79:443 FC259A04A328A07FED1413E9FC6526530D9FD87A cert=RutxZlu8BtyP+y0NX7bAVD41+J/qXNhHUrKjFkRSdiBAhIHIQLhKQ2HxESAKZprn/lR3KA iat-mode=0
|
||||
Bridge obfs4 154.35.22.10:15937 8FB9F4319E89E5C6223052AA525A192AFBC85D55 cert=GGGS1TX4R81m3r0HBl79wKy1OtPPNR2CZUIrHjkRg65Vc2VR8fOyo64f9kmT1UAFG7j0HQ iat-mode=0
|
||||
Bridge obfs4 37.218.240.34:40035 88CD36D45A35271963EF82E511C8827A24730913 cert=eGXYfWODcgqIdPJ+rRupg4GGvVGfh25FWaIXZkit206OSngsp7GAIiGIXOJJROMxEqFKJg iat-mode=1
|
||||
Bridge obfs4 192.95.36.142:443 CDF2E852BF539B82BD10E27E9115A31734E378C2 cert=qUVQ0srL1JI/vO6V6m/24anYXiJD3QP2HgzUKQtQ7GRqqUvs7P+tG43RtAqdhLOALP7DJQ iat-mode=1
|
||||
Bridge obfs4 154.35.22.12:80 00DC6C4FA49A65BD1472993CF6730D54F11E0DBB cert=N86E9hKXXXVz6G7w2z8wFfhIDztDAzZ/3poxVePHEYjbKDWzjkRDccFMAnhK75fc65pYSg iat-mode=0
|
||||
Bridge obfs4 85.31.186.98:443 011F2599C0E9B27EE74B353155E244813763C3E5 cert=ayq0XzCwhpdysn5o0EyDUbmSOx3X/oTEbzDMvczHOdBJKlvIdHHLJGkZARtT4dcBFArPPg iat-mode=0
|
||||
Bridge obfs4 154.35.22.12:4304 00DC6C4FA49A65BD1472993CF6730D54F11E0DBB cert=N86E9hKXXXVz6G7w2z8wFfhIDztDAzZ/3poxVePHEYjbKDWzjkRDccFMAnhK75fc65pYSg iat-mode=0
|
||||
UseBridges 1
|
1
cli/onionshare_cli/resources/version.txt
Normal file
1
cli/onionshare_cli/resources/version.txt
Normal file
|
@ -0,0 +1 @@
|
|||
0.1.3
|
7776
cli/onionshare_cli/resources/wordlist.txt
Normal file
7776
cli/onionshare_cli/resources/wordlist.txt
Normal file
File diff suppressed because it is too large
Load diff
197
cli/onionshare_cli/settings.py
Normal file
197
cli/onionshare_cli/settings.py
Normal file
|
@ -0,0 +1,197 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import locale
|
||||
|
||||
try:
|
||||
# We only need pwd module in macOS, and it's not available in Windows
|
||||
import pwd
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
class Settings(object):
|
||||
"""
|
||||
This class stores all of the settings for OnionShare, specifically for how
|
||||
to connect to Tor. If it can't find the settings file, it uses the default,
|
||||
which is to attempt to connect automatically using default Tor Browser
|
||||
settings.
|
||||
"""
|
||||
|
||||
def __init__(self, common, config=False):
|
||||
self.common = common
|
||||
|
||||
self.common.log("Settings", "__init__")
|
||||
|
||||
# If a readable config file was provided, use that instead
|
||||
if config:
|
||||
if os.path.isfile(config):
|
||||
self.filename = config
|
||||
else:
|
||||
self.common.log(
|
||||
"Settings",
|
||||
"__init__",
|
||||
"Supplied config does not exist or is unreadable. Falling back to default location",
|
||||
)
|
||||
self.filename = self.build_filename()
|
||||
|
||||
else:
|
||||
# Default config
|
||||
self.filename = self.build_filename()
|
||||
|
||||
# Dictionary of available languages in this version of OnionShare,
|
||||
# mapped to the language name, in that language
|
||||
self.available_locales = {
|
||||
"ar": "العربية", # Arabic
|
||||
#'bn': 'বাংলা', # Bengali (commented out because not at 90% translation)
|
||||
"ca": "Català", # Catalan
|
||||
"zh_Hant": "正體中文 (繁體)", # Traditional Chinese
|
||||
"zh_Hans": "中文 (简体)", # Simplified Chinese
|
||||
"da": "Dansk", # Danish
|
||||
"nl": "Nederlands", # Dutch
|
||||
"en": "English", # English
|
||||
# "fi": "Suomi", # Finnish (commented out because not at 90% translation)
|
||||
"fr": "Français", # French
|
||||
"de": "Deutsch", # German
|
||||
"el": "Ελληνικά", # Greek
|
||||
"is": "Íslenska", # Icelandic
|
||||
"ga": "Gaeilge", # Irish
|
||||
"it": "Italiano", # Italian
|
||||
"ja": "日本語", # Japanese
|
||||
"nb_NO": "Norsk Bokmål", # Norwegian Bokmål
|
||||
"fa": "فارسی", # Persian
|
||||
"pl": "Polski", # Polish
|
||||
"pt_BR": "Português (Brasil)", # Portuguese Brazil
|
||||
"pt_PT": "Português (Portugal)", # Portuguese Portugal
|
||||
"ro": "Română", # Romanian
|
||||
"ru": "Русский", # Russian
|
||||
"sr_Latn": "Srpska (latinica)", # Serbian (latin)
|
||||
"es": "Español", # Spanish
|
||||
"sv": "Svenska", # Swedish
|
||||
"te": "తెలుగు", # Telugu
|
||||
"tr": "Türkçe", # Turkish
|
||||
"uk": "Українська", # Ukrainian
|
||||
}
|
||||
|
||||
# These are the default settings. They will get overwritten when loading from disk
|
||||
self.default_settings = {
|
||||
"version": self.common.version,
|
||||
"connection_type": "bundled",
|
||||
"control_port_address": "127.0.0.1",
|
||||
"control_port_port": 9051,
|
||||
"socks_address": "127.0.0.1",
|
||||
"socks_port": 9050,
|
||||
"socket_file_path": "/var/run/tor/control",
|
||||
"auth_type": "no_auth",
|
||||
"auth_password": "",
|
||||
"use_autoupdate": True,
|
||||
"autoupdate_timestamp": None,
|
||||
"no_bridges": True,
|
||||
"tor_bridges_use_obfs4": False,
|
||||
"tor_bridges_use_meek_lite_azure": False,
|
||||
"tor_bridges_use_custom_bridges": "",
|
||||
"persistent_tabs": [],
|
||||
"locale": None, # this gets defined in fill_in_defaults()
|
||||
}
|
||||
self._settings = {}
|
||||
self.fill_in_defaults()
|
||||
|
||||
def fill_in_defaults(self):
|
||||
"""
|
||||
If there are any missing settings from self._settings, replace them with
|
||||
their default values.
|
||||
"""
|
||||
for key in self.default_settings:
|
||||
if key not in self._settings:
|
||||
self._settings[key] = self.default_settings[key]
|
||||
|
||||
# Choose the default locale based on the OS preference, and fall-back to English
|
||||
if self._settings["locale"] is None:
|
||||
language_code, encoding = locale.getdefaultlocale()
|
||||
|
||||
# Default to English
|
||||
if not language_code:
|
||||
language_code = "en_US"
|
||||
|
||||
if language_code == "pt_PT" and language_code == "pt_BR":
|
||||
# Portuguese locales include country code
|
||||
default_locale = language_code
|
||||
else:
|
||||
# All other locales cut off the country code
|
||||
default_locale = language_code[:2]
|
||||
|
||||
if default_locale not in self.available_locales:
|
||||
default_locale = "en"
|
||||
self._settings["locale"] = default_locale
|
||||
|
||||
def build_filename(self):
|
||||
"""
|
||||
Returns the path of the settings file.
|
||||
"""
|
||||
return os.path.join(self.common.build_data_dir(), "onionshare.json")
|
||||
|
||||
def load(self):
|
||||
"""
|
||||
Load the settings from file.
|
||||
"""
|
||||
self.common.log("Settings", "load")
|
||||
|
||||
# If the settings file exists, load it
|
||||
if os.path.exists(self.filename):
|
||||
try:
|
||||
self.common.log("Settings", "load", f"Trying to load {self.filename}")
|
||||
with open(self.filename, "r") as f:
|
||||
self._settings = json.load(f)
|
||||
self.fill_in_defaults()
|
||||
except:
|
||||
pass
|
||||
|
||||
# Make sure data_dir exists
|
||||
try:
|
||||
os.makedirs(self.get("data_dir"), exist_ok=True)
|
||||
except:
|
||||
pass
|
||||
|
||||
def save(self):
|
||||
"""
|
||||
Save settings to file.
|
||||
"""
|
||||
self.common.log("Settings", "save")
|
||||
open(self.filename, "w").write(json.dumps(self._settings, indent=2))
|
||||
self.common.log("Settings", "save", f"Settings saved in {self.filename}")
|
||||
|
||||
def get(self, key):
|
||||
return self._settings[key]
|
||||
|
||||
def set(self, key, val):
|
||||
# If typecasting int values fails, fallback to default values
|
||||
if key == "control_port_port" or key == "socks_port":
|
||||
try:
|
||||
val = int(val)
|
||||
except:
|
||||
if key == "control_port_port":
|
||||
val = self.default_settings["control_port_port"]
|
||||
elif key == "socks_port":
|
||||
val = self.default_settings["socks_port"]
|
||||
|
||||
self._settings[key] = val
|
21
cli/onionshare_cli/web/__init__.py
Normal file
21
cli/onionshare_cli/web/__init__.py
Normal file
|
@ -0,0 +1,21 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from .web import Web
|
159
cli/onionshare_cli/web/chat_mode.py
Normal file
159
cli/onionshare_cli/web/chat_mode.py
Normal file
|
@ -0,0 +1,159 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
from flask import (
|
||||
Request,
|
||||
request,
|
||||
render_template,
|
||||
make_response,
|
||||
jsonify,
|
||||
redirect,
|
||||
session,
|
||||
)
|
||||
from werkzeug.utils import secure_filename
|
||||
from flask_socketio import emit, join_room, leave_room
|
||||
|
||||
|
||||
class ChatModeWeb:
|
||||
"""
|
||||
All of the web logic for chat mode
|
||||
"""
|
||||
|
||||
def __init__(self, common, web):
|
||||
self.common = common
|
||||
self.common.log("ChatModeWeb", "__init__")
|
||||
|
||||
self.web = web
|
||||
|
||||
# This tracks users in the room
|
||||
self.connected_users = []
|
||||
|
||||
# This tracks the history id
|
||||
self.cur_history_id = 0
|
||||
|
||||
self.define_routes()
|
||||
|
||||
def define_routes(self):
|
||||
"""
|
||||
The web app routes for chatting
|
||||
"""
|
||||
|
||||
@self.web.app.route("/")
|
||||
def index():
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
session["name"] = (
|
||||
session.get("name")
|
||||
if session.get("name")
|
||||
else self.common.build_username()
|
||||
)
|
||||
session["room"] = self.web.settings.default_settings["chat"]["room"]
|
||||
self.web.add_request(
|
||||
request.path, {"id": history_id, "status_code": 200},
|
||||
)
|
||||
|
||||
self.web.add_request(self.web.REQUEST_LOAD, request.path)
|
||||
r = make_response(
|
||||
render_template(
|
||||
"chat.html",
|
||||
static_url_path=self.web.static_url_path,
|
||||
username=session.get("name"),
|
||||
)
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
@self.web.app.route("/update-session-username", methods=["POST"])
|
||||
def update_session_username():
|
||||
history_id = self.cur_history_id
|
||||
data = request.get_json()
|
||||
if data.get("username", "") not in self.connected_users:
|
||||
session["name"] = data.get("username", session.get("name"))
|
||||
self.web.add_request(
|
||||
request.path, {"id": history_id, "status_code": 200},
|
||||
)
|
||||
|
||||
self.web.add_request(self.web.REQUEST_LOAD, request.path)
|
||||
r = make_response(jsonify(username=session.get("name"), success=True,))
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
@self.web.socketio.on("joined", namespace="/chat")
|
||||
def joined(message):
|
||||
"""Sent by clients when they enter a room.
|
||||
A status message is broadcast to all people in the room."""
|
||||
self.connected_users.append(session.get("name"))
|
||||
join_room(session.get("room"))
|
||||
emit(
|
||||
"status",
|
||||
{
|
||||
"username": session.get("name"),
|
||||
"msg": "{} has joined.".format(session.get("name")),
|
||||
"connected_users": self.connected_users,
|
||||
"user": session.get("name"),
|
||||
},
|
||||
room=session.get("room"),
|
||||
)
|
||||
|
||||
@self.web.socketio.on("text", namespace="/chat")
|
||||
def text(message):
|
||||
"""Sent by a client when the user entered a new message.
|
||||
The message is sent to all people in the room."""
|
||||
emit(
|
||||
"message",
|
||||
{"username": session.get("name"), "msg": message["msg"]},
|
||||
room=session.get("room"),
|
||||
)
|
||||
|
||||
@self.web.socketio.on("update_username", namespace="/chat")
|
||||
def update_username(message):
|
||||
"""Sent by a client when the user updates their username.
|
||||
The message is sent to all people in the room."""
|
||||
current_name = session.get("name")
|
||||
if message["username"] not in self.connected_users:
|
||||
session["name"] = message["username"]
|
||||
self.connected_users[
|
||||
self.connected_users.index(current_name)
|
||||
] = session.get("name")
|
||||
emit(
|
||||
"status",
|
||||
{
|
||||
"msg": "{} has updated their username to: {}".format(
|
||||
current_name, session.get("name")
|
||||
),
|
||||
"connected_users": self.connected_users,
|
||||
"old_name": current_name,
|
||||
"new_name": session.get("name"),
|
||||
},
|
||||
room=session.get("room"),
|
||||
)
|
||||
|
||||
@self.web.socketio.on("disconnect", namespace="/chat")
|
||||
def disconnect():
|
||||
"""Sent by clients when they disconnect from a room.
|
||||
A status message is broadcast to all people in the room."""
|
||||
self.connected_users.remove(session.get("name"))
|
||||
leave_room(session.get("room"))
|
||||
emit(
|
||||
"status",
|
||||
{
|
||||
"msg": "{} has left the room.".format(session.get("name")),
|
||||
"connected_users": self.connected_users,
|
||||
},
|
||||
room=session.get("room"),
|
||||
)
|
488
cli/onionshare_cli/web/receive_mode.py
Normal file
488
cli/onionshare_cli/web/receive_mode.py
Normal file
|
@ -0,0 +1,488 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import json
|
||||
from datetime import datetime
|
||||
from flask import Request, request, render_template, make_response, flash, redirect
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
|
||||
class ReceiveModeWeb:
|
||||
"""
|
||||
All of the web logic for receive mode
|
||||
"""
|
||||
|
||||
def __init__(self, common, web):
|
||||
self.common = common
|
||||
self.common.log("ReceiveModeWeb", "__init__")
|
||||
|
||||
self.web = web
|
||||
|
||||
self.can_upload = True
|
||||
self.uploads_in_progress = []
|
||||
|
||||
# This tracks the history id
|
||||
self.cur_history_id = 0
|
||||
|
||||
self.define_routes()
|
||||
|
||||
def define_routes(self):
|
||||
"""
|
||||
The web app routes for receiving files
|
||||
"""
|
||||
|
||||
@self.web.app.route("/")
|
||||
def index():
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_INDIVIDUAL_FILE_STARTED,
|
||||
request.path,
|
||||
{"id": history_id, "status_code": 200},
|
||||
)
|
||||
|
||||
self.web.add_request(self.web.REQUEST_LOAD, request.path)
|
||||
r = make_response(
|
||||
render_template(
|
||||
"receive.html", static_url_path=self.web.static_url_path
|
||||
)
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
@self.web.app.route("/upload", methods=["POST"])
|
||||
def upload(ajax=False):
|
||||
"""
|
||||
Handle the upload files POST request, though at this point, the files have
|
||||
already been uploaded and saved to their correct locations.
|
||||
"""
|
||||
files = request.files.getlist("file[]")
|
||||
filenames = []
|
||||
for f in files:
|
||||
if f.filename != "":
|
||||
filename = secure_filename(f.filename)
|
||||
filenames.append(filename)
|
||||
local_path = os.path.join(request.receive_mode_dir, filename)
|
||||
basename = os.path.basename(local_path)
|
||||
|
||||
# Tell the GUI the receive mode directory for this file
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_UPLOAD_SET_DIR,
|
||||
request.path,
|
||||
{
|
||||
"id": request.history_id,
|
||||
"filename": basename,
|
||||
"dir": request.receive_mode_dir,
|
||||
},
|
||||
)
|
||||
|
||||
self.common.log(
|
||||
"ReceiveModeWeb",
|
||||
"define_routes",
|
||||
f"/upload, uploaded {f.filename}, saving to {local_path}",
|
||||
)
|
||||
print(f"\nReceived: {local_path}")
|
||||
|
||||
if request.upload_error:
|
||||
self.common.log(
|
||||
"ReceiveModeWeb",
|
||||
"define_routes",
|
||||
"/upload, there was an upload error",
|
||||
)
|
||||
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE,
|
||||
request.path,
|
||||
{"receive_mode_dir": request.receive_mode_dir},
|
||||
)
|
||||
print(
|
||||
f"Could not create OnionShare data folder: {request.receive_mode_dir}"
|
||||
)
|
||||
|
||||
msg = "Error uploading, please inform the OnionShare user"
|
||||
if ajax:
|
||||
return json.dumps({"error_flashes": [msg]})
|
||||
else:
|
||||
flash(msg, "error")
|
||||
return redirect("/")
|
||||
|
||||
if ajax:
|
||||
info_flashes = []
|
||||
|
||||
if len(filenames) == 0:
|
||||
msg = "No files uploaded"
|
||||
if ajax:
|
||||
info_flashes.append(msg)
|
||||
else:
|
||||
flash(msg, "info")
|
||||
else:
|
||||
msg = "Sent "
|
||||
for filename in filenames:
|
||||
msg += f"{filename}, "
|
||||
msg = msg.rstrip(", ")
|
||||
if ajax:
|
||||
info_flashes.append(msg)
|
||||
else:
|
||||
flash(msg, "info")
|
||||
|
||||
if self.can_upload:
|
||||
if ajax:
|
||||
return json.dumps({"info_flashes": info_flashes})
|
||||
else:
|
||||
return redirect("/")
|
||||
else:
|
||||
if ajax:
|
||||
return json.dumps(
|
||||
{
|
||||
"new_body": render_template(
|
||||
"thankyou.html",
|
||||
static_url_path=self.web.static_url_path,
|
||||
)
|
||||
}
|
||||
)
|
||||
else:
|
||||
# It was the last upload and the timer ran out
|
||||
r = make_response(
|
||||
render_template("thankyou.html"),
|
||||
static_url_path=self.web.static_url_path,
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
@self.web.app.route("/upload-ajax", methods=["POST"])
|
||||
def upload_ajax_public():
|
||||
if not self.can_upload:
|
||||
return self.web.error403()
|
||||
return upload(ajax=True)
|
||||
|
||||
|
||||
class ReceiveModeWSGIMiddleware(object):
|
||||
"""
|
||||
Custom WSGI middleware in order to attach the Web object to environ, so
|
||||
ReceiveModeRequest can access it.
|
||||
"""
|
||||
|
||||
def __init__(self, app, web):
|
||||
self.app = app
|
||||
self.web = web
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
environ["web"] = self.web
|
||||
environ["stop_q"] = self.web.stop_q
|
||||
return self.app(environ, start_response)
|
||||
|
||||
|
||||
class ReceiveModeFile(object):
|
||||
"""
|
||||
A custom file object that tells ReceiveModeRequest every time data gets
|
||||
written to it, in order to track the progress of uploads. It starts out with
|
||||
a .part file extension, and when it's complete it removes that extension.
|
||||
"""
|
||||
|
||||
def __init__(self, request, filename, write_func, close_func):
|
||||
self.onionshare_request = request
|
||||
self.onionshare_filename = filename
|
||||
self.onionshare_write_func = write_func
|
||||
self.onionshare_close_func = close_func
|
||||
|
||||
self.filename = os.path.join(self.onionshare_request.receive_mode_dir, filename)
|
||||
self.filename_in_progress = f"{self.filename}.part"
|
||||
|
||||
# Open the file
|
||||
self.upload_error = False
|
||||
try:
|
||||
self.f = open(self.filename_in_progress, "wb+")
|
||||
except:
|
||||
# This will only happen if someone is messing with the data dir while
|
||||
# OnionShare is running, but if it does make sure to throw an error
|
||||
self.upload_error = True
|
||||
self.f = tempfile.TemporaryFile("wb+")
|
||||
|
||||
# Make all the file-like methods and attributes actually access the
|
||||
# TemporaryFile, except for write
|
||||
attrs = [
|
||||
"closed",
|
||||
"detach",
|
||||
"fileno",
|
||||
"flush",
|
||||
"isatty",
|
||||
"mode",
|
||||
"name",
|
||||
"peek",
|
||||
"raw",
|
||||
"read",
|
||||
"read1",
|
||||
"readable",
|
||||
"readinto",
|
||||
"readinto1",
|
||||
"readline",
|
||||
"readlines",
|
||||
"seek",
|
||||
"seekable",
|
||||
"tell",
|
||||
"truncate",
|
||||
"writable",
|
||||
"writelines",
|
||||
]
|
||||
for attr in attrs:
|
||||
setattr(self, attr, getattr(self.f, attr))
|
||||
|
||||
def write(self, b):
|
||||
"""
|
||||
Custom write method that calls out to onionshare_write_func
|
||||
"""
|
||||
if self.upload_error or (not self.onionshare_request.stop_q.empty()):
|
||||
self.close()
|
||||
self.onionshare_request.close()
|
||||
return
|
||||
|
||||
try:
|
||||
bytes_written = self.f.write(b)
|
||||
self.onionshare_write_func(self.onionshare_filename, bytes_written)
|
||||
|
||||
except:
|
||||
self.upload_error = True
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Custom close method that calls out to onionshare_close_func
|
||||
"""
|
||||
try:
|
||||
self.f.close()
|
||||
|
||||
if not self.upload_error:
|
||||
# Rename the in progress file to the final filename
|
||||
os.rename(self.filename_in_progress, self.filename)
|
||||
|
||||
except:
|
||||
self.upload_error = True
|
||||
|
||||
self.onionshare_close_func(self.onionshare_filename, self.upload_error)
|
||||
|
||||
|
||||
class ReceiveModeRequest(Request):
|
||||
"""
|
||||
A custom flask Request object that keeps track of how much data has been
|
||||
uploaded for each file, for receive mode.
|
||||
"""
|
||||
|
||||
def __init__(self, environ, populate_request=True, shallow=False):
|
||||
super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow)
|
||||
self.web = environ["web"]
|
||||
self.stop_q = environ["stop_q"]
|
||||
|
||||
self.web.common.log("ReceiveModeRequest", "__init__")
|
||||
|
||||
# Prevent running the close() method more than once
|
||||
self.closed = False
|
||||
|
||||
# Is this a valid upload request?
|
||||
self.upload_request = False
|
||||
if self.method == "POST":
|
||||
if self.path == "/upload" or self.path == "/upload-ajax":
|
||||
self.upload_request = True
|
||||
|
||||
if self.upload_request:
|
||||
# No errors yet
|
||||
self.upload_error = False
|
||||
|
||||
# Figure out what files should be saved
|
||||
now = datetime.now()
|
||||
date_dir = now.strftime("%Y-%m-%d")
|
||||
time_dir = now.strftime("%H.%M.%S")
|
||||
self.receive_mode_dir = os.path.join(
|
||||
self.web.settings.get("receive", "data_dir"), date_dir, time_dir
|
||||
)
|
||||
|
||||
# Create that directory, which shouldn't exist yet
|
||||
try:
|
||||
os.makedirs(self.receive_mode_dir, 0o700, exist_ok=False)
|
||||
except OSError:
|
||||
# If this directory already exists, maybe someone else is uploading files at
|
||||
# the same second, so use a different name in that case
|
||||
if os.path.exists(self.receive_mode_dir):
|
||||
# Keep going until we find a directory name that's available
|
||||
i = 1
|
||||
while True:
|
||||
new_receive_mode_dir = f"{self.receive_mode_dir}-{i}"
|
||||
try:
|
||||
os.makedirs(new_receive_mode_dir, 0o700, exist_ok=False)
|
||||
self.receive_mode_dir = new_receive_mode_dir
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
i += 1
|
||||
# Failsafe
|
||||
if i == 100:
|
||||
self.web.common.log(
|
||||
"ReceiveModeRequest",
|
||||
"__init__",
|
||||
"Error finding available receive mode directory",
|
||||
)
|
||||
self.upload_error = True
|
||||
break
|
||||
except PermissionError:
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE,
|
||||
request.path,
|
||||
{"receive_mode_dir": self.receive_mode_dir},
|
||||
)
|
||||
print(
|
||||
f"Could not create OnionShare data folder: {self.receive_mode_dir}"
|
||||
)
|
||||
self.web.common.log(
|
||||
"ReceiveModeRequest",
|
||||
"__init__",
|
||||
"Permission denied creating receive mode directory",
|
||||
)
|
||||
self.upload_error = True
|
||||
|
||||
# If there's an error so far, finish early
|
||||
if self.upload_error:
|
||||
return
|
||||
|
||||
# A dictionary that maps filenames to the bytes uploaded so far
|
||||
self.progress = {}
|
||||
|
||||
# Prevent new uploads if we've said so (timer expired)
|
||||
if self.web.receive_mode.can_upload:
|
||||
|
||||
# Create an history_id, attach it to the request
|
||||
self.history_id = self.web.receive_mode.cur_history_id
|
||||
self.web.receive_mode.cur_history_id += 1
|
||||
|
||||
# Figure out the content length
|
||||
try:
|
||||
self.content_length = int(self.headers["Content-Length"])
|
||||
except:
|
||||
self.content_length = 0
|
||||
|
||||
date_str = datetime.now().strftime("%b %d, %I:%M%p")
|
||||
size_str = self.web.common.human_readable_filesize(self.content_length)
|
||||
print(f"{date_str}: Upload of total size {size_str} is starting")
|
||||
|
||||
# Don't tell the GUI that a request has started until we start receiving files
|
||||
self.told_gui_about_request = False
|
||||
|
||||
self.previous_file = None
|
||||
|
||||
def _get_file_stream(
|
||||
self, total_content_length, content_type, filename=None, content_length=None
|
||||
):
|
||||
"""
|
||||
This gets called for each file that gets uploaded, and returns an file-like
|
||||
writable stream.
|
||||
"""
|
||||
if self.upload_request:
|
||||
if not self.told_gui_about_request:
|
||||
# Tell the GUI about the request
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_STARTED,
|
||||
self.path,
|
||||
{"id": self.history_id, "content_length": self.content_length},
|
||||
)
|
||||
self.web.receive_mode.uploads_in_progress.append(self.history_id)
|
||||
|
||||
self.told_gui_about_request = True
|
||||
|
||||
self.filename = secure_filename(filename)
|
||||
|
||||
self.progress[self.filename] = {"uploaded_bytes": 0, "complete": False}
|
||||
|
||||
f = ReceiveModeFile(
|
||||
self, self.filename, self.file_write_func, self.file_close_func
|
||||
)
|
||||
if f.upload_error:
|
||||
self.web.common.log(
|
||||
"ReceiveModeRequest", "_get_file_stream", "Error creating file"
|
||||
)
|
||||
self.upload_error = True
|
||||
return f
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Closing the request.
|
||||
"""
|
||||
super(ReceiveModeRequest, self).close()
|
||||
|
||||
# Prevent calling this method more than once per request
|
||||
if self.closed:
|
||||
return
|
||||
self.closed = True
|
||||
|
||||
self.web.common.log("ReceiveModeRequest", "close")
|
||||
|
||||
try:
|
||||
if self.told_gui_about_request:
|
||||
history_id = self.history_id
|
||||
|
||||
if (
|
||||
not self.web.stop_q.empty()
|
||||
or not self.progress[self.filename]["complete"]
|
||||
):
|
||||
# Inform the GUI that the upload has canceled
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_UPLOAD_CANCELED, self.path, {"id": history_id}
|
||||
)
|
||||
else:
|
||||
# Inform the GUI that the upload has finished
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_UPLOAD_FINISHED, self.path, {"id": history_id}
|
||||
)
|
||||
self.web.receive_mode.uploads_in_progress.remove(history_id)
|
||||
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def file_write_func(self, filename, length):
|
||||
"""
|
||||
This function gets called when a specific file is written to.
|
||||
"""
|
||||
if self.closed:
|
||||
return
|
||||
|
||||
if self.upload_request:
|
||||
self.progress[filename]["uploaded_bytes"] += length
|
||||
|
||||
if self.previous_file != filename:
|
||||
self.previous_file = filename
|
||||
|
||||
size_str = self.web.common.human_readable_filesize(
|
||||
self.progress[filename]["uploaded_bytes"]
|
||||
)
|
||||
print(f"\r=> {size_str} {filename} ", end="")
|
||||
|
||||
# Update the GUI on the upload progress
|
||||
if self.told_gui_about_request:
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_PROGRESS,
|
||||
self.path,
|
||||
{"id": self.history_id, "progress": self.progress},
|
||||
)
|
||||
|
||||
def file_close_func(self, filename, upload_error=False):
|
||||
"""
|
||||
This function gets called when a specific file is closed.
|
||||
"""
|
||||
self.progress[filename]["complete"] = True
|
||||
|
||||
# If the file tells us there was an upload error, let the request know as well
|
||||
if upload_error:
|
||||
self.upload_error = True
|
321
cli/onionshare_cli/web/send_base_mode.py
Normal file
321
cli/onionshare_cli/web/send_base_mode.py
Normal file
|
@ -0,0 +1,321 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import mimetypes
|
||||
import gzip
|
||||
from flask import Response, request, render_template, make_response
|
||||
|
||||
|
||||
class SendBaseModeWeb:
|
||||
"""
|
||||
All of the web logic shared between share and website mode (modes where the user sends files)
|
||||
"""
|
||||
|
||||
def __init__(self, common, web):
|
||||
super(SendBaseModeWeb, self).__init__()
|
||||
self.common = common
|
||||
self.web = web
|
||||
|
||||
# Information about the file to be shared
|
||||
self.is_zipped = False
|
||||
self.download_filename = None
|
||||
self.download_filesize = None
|
||||
self.gzip_filename = None
|
||||
self.gzip_filesize = None
|
||||
self.zip_writer = None
|
||||
|
||||
# If autostop_sharing, only allow one download at a time
|
||||
self.download_in_progress = False
|
||||
|
||||
# This tracks the history id
|
||||
self.cur_history_id = 0
|
||||
|
||||
self.define_routes()
|
||||
self.init()
|
||||
|
||||
def set_file_info(self, filenames, processed_size_callback=None):
|
||||
"""
|
||||
Build a data structure that describes the list of files
|
||||
"""
|
||||
# If there's just one folder, replace filenames with a list of files inside that folder
|
||||
if len(filenames) == 1 and os.path.isdir(filenames[0]):
|
||||
filenames = [
|
||||
os.path.join(filenames[0], x) for x in os.listdir(filenames[0])
|
||||
]
|
||||
|
||||
# Re-initialize
|
||||
self.files = {} # Dictionary mapping file paths to filenames on disk
|
||||
self.root_files = (
|
||||
{}
|
||||
) # This is only the root files and dirs, as opposed to all of them
|
||||
self.cleanup_filenames = []
|
||||
self.cur_history_id = 0
|
||||
self.file_info = {"files": [], "dirs": []}
|
||||
self.gzip_individual_files = {}
|
||||
self.init()
|
||||
|
||||
# Build the file list
|
||||
for filename in filenames:
|
||||
basename = os.path.basename(filename.rstrip("/"))
|
||||
|
||||
# If it's a filename, add it
|
||||
if os.path.isfile(filename):
|
||||
self.files[basename] = filename
|
||||
self.root_files[basename] = filename
|
||||
|
||||
# If it's a directory, add it recursively
|
||||
elif os.path.isdir(filename):
|
||||
self.root_files[basename + "/"] = filename
|
||||
|
||||
for root, _, nested_filenames in os.walk(filename):
|
||||
# Normalize the root path. So if the directory name is "/home/user/Documents/some_folder",
|
||||
# and it has a nested folder foobar, the root is "/home/user/Documents/some_folder/foobar".
|
||||
# The normalized_root should be "some_folder/foobar"
|
||||
normalized_root = os.path.join(
|
||||
basename, root[len(filename) :].lstrip("/")
|
||||
).rstrip("/")
|
||||
|
||||
# Add the dir itself
|
||||
self.files[normalized_root + "/"] = root
|
||||
|
||||
# Add the files in this dir
|
||||
for nested_filename in nested_filenames:
|
||||
self.files[
|
||||
os.path.join(normalized_root, nested_filename)
|
||||
] = os.path.join(root, nested_filename)
|
||||
|
||||
self.set_file_info_custom(filenames, processed_size_callback)
|
||||
|
||||
def directory_listing(self, filenames, path="", filesystem_path=None):
|
||||
# Tell the GUI about the directory listing
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_INDIVIDUAL_FILE_STARTED,
|
||||
f"/{path}",
|
||||
{"id": history_id, "method": request.method, "status_code": 200},
|
||||
)
|
||||
|
||||
breadcrumbs = [("☗", "/")]
|
||||
parts = path.split("/")[:-1]
|
||||
for i in range(len(parts)):
|
||||
breadcrumbs.append((parts[i], f"/{'/'.join(parts[0 : i + 1])}/"))
|
||||
breadcrumbs_leaf = breadcrumbs.pop()[0]
|
||||
|
||||
# If filesystem_path is None, this is the root directory listing
|
||||
files, dirs = self.build_directory_listing(filenames, filesystem_path)
|
||||
r = self.directory_listing_template(
|
||||
path, files, dirs, breadcrumbs, breadcrumbs_leaf
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
def build_directory_listing(self, filenames, filesystem_path):
|
||||
files = []
|
||||
dirs = []
|
||||
|
||||
for filename in filenames:
|
||||
if filesystem_path:
|
||||
this_filesystem_path = os.path.join(filesystem_path, filename)
|
||||
else:
|
||||
this_filesystem_path = self.files[filename]
|
||||
|
||||
is_dir = os.path.isdir(this_filesystem_path)
|
||||
|
||||
if is_dir:
|
||||
dirs.append({"basename": filename})
|
||||
else:
|
||||
size = os.path.getsize(this_filesystem_path)
|
||||
size_human = self.common.human_readable_filesize(size)
|
||||
files.append({"basename": filename, "size_human": size_human})
|
||||
return files, dirs
|
||||
|
||||
def stream_individual_file(self, filesystem_path):
|
||||
"""
|
||||
Return a flask response that's streaming the download of an individual file, and gzip
|
||||
compressing it if the browser supports it.
|
||||
"""
|
||||
use_gzip = self.should_use_gzip()
|
||||
|
||||
# gzip compress the individual file, if it hasn't already been compressed
|
||||
if use_gzip:
|
||||
if filesystem_path not in self.gzip_individual_files:
|
||||
gzip_filename = tempfile.mkstemp("wb+")[1]
|
||||
self._gzip_compress(filesystem_path, gzip_filename, 6, None)
|
||||
self.gzip_individual_files[filesystem_path] = gzip_filename
|
||||
|
||||
# Make sure the gzip file gets cleaned up when onionshare stops
|
||||
self.cleanup_filenames.append(gzip_filename)
|
||||
|
||||
file_to_download = self.gzip_individual_files[filesystem_path]
|
||||
filesize = os.path.getsize(self.gzip_individual_files[filesystem_path])
|
||||
else:
|
||||
file_to_download = filesystem_path
|
||||
filesize = os.path.getsize(filesystem_path)
|
||||
|
||||
path = request.path
|
||||
|
||||
# Tell GUI the individual file started
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
|
||||
# Only GET requests are allowed, any other method should fail
|
||||
if request.method != "GET":
|
||||
return self.web.error405(history_id)
|
||||
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_INDIVIDUAL_FILE_STARTED,
|
||||
path,
|
||||
{"id": history_id, "filesize": filesize},
|
||||
)
|
||||
|
||||
def generate():
|
||||
chunk_size = 102400 # 100kb
|
||||
|
||||
fp = open(file_to_download, "rb")
|
||||
done = False
|
||||
while not done:
|
||||
chunk = fp.read(chunk_size)
|
||||
if chunk == b"":
|
||||
done = True
|
||||
else:
|
||||
try:
|
||||
yield chunk
|
||||
|
||||
# Tell GUI the progress
|
||||
downloaded_bytes = fp.tell()
|
||||
percent = (1.0 * downloaded_bytes / filesize) * 100
|
||||
if (
|
||||
not self.web.is_gui
|
||||
or self.common.platform == "Linux"
|
||||
or self.common.platform == "BSD"
|
||||
):
|
||||
sys.stdout.write(
|
||||
"\r{0:s}, {1:.2f}% ".format(
|
||||
self.common.human_readable_filesize(
|
||||
downloaded_bytes
|
||||
),
|
||||
percent,
|
||||
)
|
||||
)
|
||||
sys.stdout.flush()
|
||||
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_INDIVIDUAL_FILE_PROGRESS,
|
||||
path,
|
||||
{
|
||||
"id": history_id,
|
||||
"bytes": downloaded_bytes,
|
||||
"filesize": filesize,
|
||||
},
|
||||
)
|
||||
done = False
|
||||
except:
|
||||
# Looks like the download was canceled
|
||||
done = True
|
||||
|
||||
# Tell the GUI the individual file was canceled
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_INDIVIDUAL_FILE_CANCELED,
|
||||
path,
|
||||
{"id": history_id},
|
||||
)
|
||||
|
||||
fp.close()
|
||||
|
||||
if self.common.platform != "Darwin":
|
||||
sys.stdout.write("\n")
|
||||
|
||||
basename = os.path.basename(filesystem_path)
|
||||
|
||||
r = Response(generate())
|
||||
if use_gzip:
|
||||
r.headers.set("Content-Encoding", "gzip")
|
||||
r.headers.set("Content-Length", filesize)
|
||||
r.headers.set("Content-Disposition", "inline", filename=basename)
|
||||
r = self.web.add_security_headers(r)
|
||||
(content_type, _) = mimetypes.guess_type(basename, strict=False)
|
||||
if content_type is not None:
|
||||
r.headers.set("Content-Type", content_type)
|
||||
return r
|
||||
|
||||
def should_use_gzip(self):
|
||||
"""
|
||||
Should we use gzip for this browser?
|
||||
"""
|
||||
return (not self.is_zipped) and (
|
||||
"gzip" in request.headers.get("Accept-Encoding", "").lower()
|
||||
)
|
||||
|
||||
def _gzip_compress(
|
||||
self, input_filename, output_filename, level, processed_size_callback=None
|
||||
):
|
||||
"""
|
||||
Compress a file with gzip, without loading the whole thing into memory
|
||||
Thanks: https://stackoverflow.com/questions/27035296/python-how-to-gzip-a-large-text-file-without-memoryerror
|
||||
"""
|
||||
bytes_processed = 0
|
||||
blocksize = 1 << 16 # 64kB
|
||||
with open(input_filename, "rb") as input_file:
|
||||
output_file = gzip.open(output_filename, "wb", level)
|
||||
while True:
|
||||
if processed_size_callback is not None:
|
||||
processed_size_callback(bytes_processed)
|
||||
|
||||
block = input_file.read(blocksize)
|
||||
if len(block) == 0:
|
||||
break
|
||||
output_file.write(block)
|
||||
bytes_processed += blocksize
|
||||
|
||||
output_file.close()
|
||||
|
||||
def init(self):
|
||||
"""
|
||||
Inherited class will implement this
|
||||
"""
|
||||
pass
|
||||
|
||||
def define_routes(self):
|
||||
"""
|
||||
Inherited class will implement this
|
||||
"""
|
||||
pass
|
||||
|
||||
def directory_listing_template(self):
|
||||
"""
|
||||
Inherited class will implement this. It should call render_template and return
|
||||
the response.
|
||||
"""
|
||||
pass
|
||||
|
||||
def set_file_info_custom(self, filenames, processed_size_callback):
|
||||
"""
|
||||
Inherited class will implement this.
|
||||
"""
|
||||
pass
|
||||
|
||||
def render_logic(self, path=""):
|
||||
"""
|
||||
Inherited class will implement this.
|
||||
"""
|
||||
pass
|
411
cli/onionshare_cli/web/share_mode.py
Normal file
411
cli/onionshare_cli/web/share_mode.py
Normal file
|
@ -0,0 +1,411 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
import mimetypes
|
||||
from flask import Response, request, render_template, make_response
|
||||
|
||||
from .send_base_mode import SendBaseModeWeb
|
||||
|
||||
|
||||
class ShareModeWeb(SendBaseModeWeb):
|
||||
"""
|
||||
All of the web logic for share mode
|
||||
"""
|
||||
|
||||
def init(self):
|
||||
self.common.log("ShareModeWeb", "init")
|
||||
|
||||
# Allow downloading individual files if "Stop sharing after files have been sent" is unchecked
|
||||
self.download_individual_files = not self.web.settings.get(
|
||||
"share", "autostop_sharing"
|
||||
)
|
||||
|
||||
def define_routes(self):
|
||||
"""
|
||||
The web app routes for sharing files
|
||||
"""
|
||||
|
||||
@self.web.app.route("/", defaults={"path": ""})
|
||||
@self.web.app.route("/<path:path>")
|
||||
def index(path):
|
||||
"""
|
||||
Render the template for the onionshare landing page.
|
||||
"""
|
||||
self.web.add_request(self.web.REQUEST_LOAD, request.path)
|
||||
|
||||
# Deny new downloads if "Stop sharing after files have been sent" is checked and there is
|
||||
# currently a download
|
||||
deny_download = (
|
||||
self.web.settings.get("share", "autostop_sharing")
|
||||
and self.download_in_progress
|
||||
)
|
||||
if deny_download:
|
||||
r = make_response(
|
||||
render_template("denied.html"),
|
||||
static_url_path=self.web.static_url_path,
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
# If download is allowed to continue, serve download page
|
||||
if self.should_use_gzip():
|
||||
self.filesize = self.gzip_filesize
|
||||
else:
|
||||
self.filesize = self.download_filesize
|
||||
|
||||
return self.render_logic(path)
|
||||
|
||||
@self.web.app.route("/download")
|
||||
def download():
|
||||
"""
|
||||
Download the zip file.
|
||||
"""
|
||||
# Deny new downloads if "Stop After First Download" is checked and there is
|
||||
# currently a download
|
||||
deny_download = (
|
||||
self.web.settings.get("share", "autostop_sharing")
|
||||
and self.download_in_progress
|
||||
)
|
||||
if deny_download:
|
||||
r = make_response(
|
||||
render_template(
|
||||
"denied.html", static_url_path=self.web.static_url_path
|
||||
)
|
||||
)
|
||||
return self.web.add_security_headers(r)
|
||||
|
||||
# Prepare some variables to use inside generate() function below
|
||||
# which is outside of the request context
|
||||
shutdown_func = request.environ.get("werkzeug.server.shutdown")
|
||||
path = request.path
|
||||
|
||||
# If this is a zipped file, then serve as-is. If it's not zipped, then,
|
||||
# if the http client supports gzip compression, gzip the file first
|
||||
# and serve that
|
||||
use_gzip = self.should_use_gzip()
|
||||
if use_gzip:
|
||||
file_to_download = self.gzip_filename
|
||||
self.filesize = self.gzip_filesize
|
||||
else:
|
||||
file_to_download = self.download_filename
|
||||
self.filesize = self.download_filesize
|
||||
|
||||
# Tell GUI the download started
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_STARTED, path, {"id": history_id, "use_gzip": use_gzip}
|
||||
)
|
||||
|
||||
basename = os.path.basename(self.download_filename)
|
||||
|
||||
def generate():
|
||||
# Starting a new download
|
||||
if self.web.settings.get("share", "autostop_sharing"):
|
||||
self.download_in_progress = True
|
||||
|
||||
chunk_size = 102400 # 100kb
|
||||
|
||||
fp = open(file_to_download, "rb")
|
||||
self.web.done = False
|
||||
canceled = False
|
||||
while not self.web.done:
|
||||
# The user has canceled the download, so stop serving the file
|
||||
if not self.web.stop_q.empty():
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_CANCELED, path, {"id": history_id}
|
||||
)
|
||||
break
|
||||
|
||||
chunk = fp.read(chunk_size)
|
||||
if chunk == b"":
|
||||
self.web.done = True
|
||||
else:
|
||||
try:
|
||||
yield chunk
|
||||
|
||||
# tell GUI the progress
|
||||
downloaded_bytes = fp.tell()
|
||||
percent = (1.0 * downloaded_bytes / self.filesize) * 100
|
||||
|
||||
# only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304)
|
||||
if (
|
||||
not self.web.is_gui
|
||||
or self.common.platform == "Linux"
|
||||
or self.common.platform == "BSD"
|
||||
):
|
||||
sys.stdout.write(
|
||||
"\r{0:s}, {1:.2f}% ".format(
|
||||
self.common.human_readable_filesize(
|
||||
downloaded_bytes
|
||||
),
|
||||
percent,
|
||||
)
|
||||
)
|
||||
sys.stdout.flush()
|
||||
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_PROGRESS,
|
||||
path,
|
||||
{"id": history_id, "bytes": downloaded_bytes},
|
||||
)
|
||||
self.web.done = False
|
||||
except:
|
||||
# looks like the download was canceled
|
||||
self.web.done = True
|
||||
canceled = True
|
||||
|
||||
# tell the GUI the download has canceled
|
||||
self.web.add_request(
|
||||
self.web.REQUEST_CANCELED, path, {"id": history_id}
|
||||
)
|
||||
|
||||
fp.close()
|
||||
|
||||
if self.common.platform != "Darwin":
|
||||
sys.stdout.write("\n")
|
||||
|
||||
# Download is finished
|
||||
if self.web.settings.get("share", "autostop_sharing"):
|
||||
self.download_in_progress = False
|
||||
|
||||
# Close the server, if necessary
|
||||
if self.web.settings.get("share", "autostop_sharing") and not canceled:
|
||||
print("Stopped because transfer is complete")
|
||||
self.web.running = False
|
||||
try:
|
||||
if shutdown_func is None:
|
||||
raise RuntimeError("Not running with the Werkzeug Server")
|
||||
shutdown_func()
|
||||
except:
|
||||
pass
|
||||
|
||||
r = Response(generate())
|
||||
if use_gzip:
|
||||
r.headers.set("Content-Encoding", "gzip")
|
||||
r.headers.set("Content-Length", self.filesize)
|
||||
r.headers.set("Content-Disposition", "attachment", filename=basename)
|
||||
r = self.web.add_security_headers(r)
|
||||
# guess content type
|
||||
(content_type, _) = mimetypes.guess_type(basename, strict=False)
|
||||
if content_type is not None:
|
||||
r.headers.set("Content-Type", content_type)
|
||||
return r
|
||||
|
||||
def directory_listing_template(
|
||||
self, path, files, dirs, breadcrumbs, breadcrumbs_leaf
|
||||
):
|
||||
return make_response(
|
||||
render_template(
|
||||
"send.html",
|
||||
file_info=self.file_info,
|
||||
files=files,
|
||||
dirs=dirs,
|
||||
breadcrumbs=breadcrumbs,
|
||||
breadcrumbs_leaf=breadcrumbs_leaf,
|
||||
filename=os.path.basename(self.download_filename),
|
||||
filesize=self.filesize,
|
||||
filesize_human=self.common.human_readable_filesize(
|
||||
self.download_filesize
|
||||
),
|
||||
is_zipped=self.is_zipped,
|
||||
static_url_path=self.web.static_url_path,
|
||||
download_individual_files=self.download_individual_files,
|
||||
)
|
||||
)
|
||||
|
||||
def set_file_info_custom(self, filenames, processed_size_callback):
|
||||
self.common.log("ShareModeWeb", "set_file_info_custom")
|
||||
self.web.cancel_compression = False
|
||||
self.build_zipfile_list(filenames, processed_size_callback)
|
||||
|
||||
def render_logic(self, path=""):
|
||||
if path in self.files:
|
||||
filesystem_path = self.files[path]
|
||||
|
||||
# If it's a directory
|
||||
if os.path.isdir(filesystem_path):
|
||||
# Render directory listing
|
||||
filenames = []
|
||||
for filename in os.listdir(filesystem_path):
|
||||
if os.path.isdir(os.path.join(filesystem_path, filename)):
|
||||
filenames.append(filename + "/")
|
||||
else:
|
||||
filenames.append(filename)
|
||||
filenames.sort()
|
||||
return self.directory_listing(filenames, path, filesystem_path)
|
||||
|
||||
# If it's a file
|
||||
elif os.path.isfile(filesystem_path):
|
||||
if self.download_individual_files:
|
||||
return self.stream_individual_file(filesystem_path)
|
||||
else:
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
return self.web.error404(history_id)
|
||||
|
||||
# If it's not a directory or file, throw a 404
|
||||
else:
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
return self.web.error404(history_id)
|
||||
else:
|
||||
# Special case loading /
|
||||
|
||||
if path == "":
|
||||
# Root directory listing
|
||||
filenames = list(self.root_files)
|
||||
filenames.sort()
|
||||
return self.directory_listing(filenames, path)
|
||||
|
||||
else:
|
||||
# If the path isn't found, throw a 404
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
return self.web.error404(history_id)
|
||||
|
||||
def build_zipfile_list(self, filenames, processed_size_callback=None):
|
||||
self.common.log("ShareModeWeb", "build_zipfile_list")
|
||||
for filename in filenames:
|
||||
info = {
|
||||
"filename": filename,
|
||||
"basename": os.path.basename(filename.rstrip("/")),
|
||||
}
|
||||
if os.path.isfile(filename):
|
||||
info["size"] = os.path.getsize(filename)
|
||||
info["size_human"] = self.common.human_readable_filesize(info["size"])
|
||||
self.file_info["files"].append(info)
|
||||
if os.path.isdir(filename):
|
||||
info["size"] = self.common.dir_size(filename)
|
||||
info["size_human"] = self.common.human_readable_filesize(info["size"])
|
||||
self.file_info["dirs"].append(info)
|
||||
self.file_info["files"] = sorted(
|
||||
self.file_info["files"], key=lambda k: k["basename"]
|
||||
)
|
||||
self.file_info["dirs"] = sorted(
|
||||
self.file_info["dirs"], key=lambda k: k["basename"]
|
||||
)
|
||||
|
||||
# Check if there's only 1 file and no folders
|
||||
if len(self.file_info["files"]) == 1 and len(self.file_info["dirs"]) == 0:
|
||||
self.download_filename = self.file_info["files"][0]["filename"]
|
||||
self.download_filesize = self.file_info["files"][0]["size"]
|
||||
|
||||
# Compress the file with gzip now, so we don't have to do it on each request
|
||||
self.gzip_filename = tempfile.mkstemp("wb+")[1]
|
||||
self._gzip_compress(
|
||||
self.download_filename, self.gzip_filename, 6, processed_size_callback
|
||||
)
|
||||
self.gzip_filesize = os.path.getsize(self.gzip_filename)
|
||||
|
||||
# Make sure the gzip file gets cleaned up when onionshare stops
|
||||
self.cleanup_filenames.append(self.gzip_filename)
|
||||
|
||||
self.is_zipped = False
|
||||
|
||||
else:
|
||||
# Zip up the files and folders
|
||||
self.zip_writer = ZipWriter(
|
||||
self.common, processed_size_callback=processed_size_callback
|
||||
)
|
||||
self.download_filename = self.zip_writer.zip_filename
|
||||
for info in self.file_info["files"]:
|
||||
self.zip_writer.add_file(info["filename"])
|
||||
# Canceling early?
|
||||
if self.web.cancel_compression:
|
||||
self.zip_writer.close()
|
||||
return False
|
||||
|
||||
for info in self.file_info["dirs"]:
|
||||
if not self.zip_writer.add_dir(info["filename"]):
|
||||
return False
|
||||
|
||||
self.zip_writer.close()
|
||||
self.download_filesize = os.path.getsize(self.download_filename)
|
||||
|
||||
# Make sure the zip file gets cleaned up when onionshare stops
|
||||
self.cleanup_filenames.append(self.zip_writer.zip_filename)
|
||||
|
||||
self.is_zipped = True
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class ZipWriter(object):
|
||||
"""
|
||||
ZipWriter accepts files and directories and compresses them into a zip file
|
||||
with. If a zip_filename is not passed in, it will use the default onionshare
|
||||
filename.
|
||||
"""
|
||||
|
||||
def __init__(self, common, zip_filename=None, processed_size_callback=None):
|
||||
self.common = common
|
||||
self.cancel_compression = False
|
||||
|
||||
if zip_filename:
|
||||
self.zip_filename = zip_filename
|
||||
else:
|
||||
self.zip_filename = (
|
||||
f"{tempfile.mkdtemp()}/onionshare_{self.common.random_string(4, 6)}.zip"
|
||||
)
|
||||
|
||||
self.z = zipfile.ZipFile(self.zip_filename, "w", allowZip64=True)
|
||||
self.processed_size_callback = processed_size_callback
|
||||
if self.processed_size_callback is None:
|
||||
self.processed_size_callback = lambda _: None
|
||||
self._size = 0
|
||||
self.processed_size_callback(self._size)
|
||||
|
||||
def add_file(self, filename):
|
||||
"""
|
||||
Add a file to the zip archive.
|
||||
"""
|
||||
self.z.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
|
||||
self._size += os.path.getsize(filename)
|
||||
self.processed_size_callback(self._size)
|
||||
|
||||
def add_dir(self, filename):
|
||||
"""
|
||||
Add a directory, and all of its children, to the zip archive.
|
||||
"""
|
||||
dir_to_strip = os.path.dirname(filename.rstrip("/")) + "/"
|
||||
for dirpath, dirnames, filenames in os.walk(filename):
|
||||
for f in filenames:
|
||||
# Canceling early?
|
||||
if self.cancel_compression:
|
||||
return False
|
||||
|
||||
full_filename = os.path.join(dirpath, f)
|
||||
if not os.path.islink(full_filename):
|
||||
arc_filename = full_filename[len(dir_to_strip) :]
|
||||
self.z.write(full_filename, arc_filename, zipfile.ZIP_DEFLATED)
|
||||
self._size += os.path.getsize(full_filename)
|
||||
self.processed_size_callback(self._size)
|
||||
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
Close the zip archive.
|
||||
"""
|
||||
self.z.close()
|
424
cli/onionshare_cli/web/web.py
Normal file
424
cli/onionshare_cli/web/web.py
Normal file
|
@ -0,0 +1,424 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import requests
|
||||
from distutils.version import LooseVersion as Version
|
||||
from urllib.request import urlopen
|
||||
|
||||
import flask
|
||||
from flask import (
|
||||
Flask,
|
||||
request,
|
||||
render_template,
|
||||
abort,
|
||||
make_response,
|
||||
send_file,
|
||||
__version__ as flask_version,
|
||||
)
|
||||
from flask_httpauth import HTTPBasicAuth
|
||||
from flask_socketio import SocketIO
|
||||
|
||||
from .share_mode import ShareModeWeb
|
||||
from .receive_mode import ReceiveModeWeb, ReceiveModeWSGIMiddleware, ReceiveModeRequest
|
||||
from .website_mode import WebsiteModeWeb
|
||||
from .chat_mode import ChatModeWeb
|
||||
|
||||
# Stub out flask's show_server_banner function, to avoiding showing warnings that
|
||||
# are not applicable to OnionShare
|
||||
def stubbed_show_server_banner(env, debug, app_import_path, eager_loading):
|
||||
pass
|
||||
|
||||
|
||||
try:
|
||||
flask.cli.show_server_banner = stubbed_show_server_banner
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
class Web:
|
||||
"""
|
||||
The Web object is the OnionShare web server, powered by flask
|
||||
"""
|
||||
|
||||
REQUEST_LOAD = 0
|
||||
REQUEST_STARTED = 1
|
||||
REQUEST_PROGRESS = 2
|
||||
REQUEST_CANCELED = 3
|
||||
REQUEST_RATE_LIMIT = 4
|
||||
REQUEST_UPLOAD_FILE_RENAMED = 5
|
||||
REQUEST_UPLOAD_SET_DIR = 6
|
||||
REQUEST_UPLOAD_FINISHED = 7
|
||||
REQUEST_UPLOAD_CANCELED = 8
|
||||
REQUEST_INDIVIDUAL_FILE_STARTED = 9
|
||||
REQUEST_INDIVIDUAL_FILE_PROGRESS = 10
|
||||
REQUEST_INDIVIDUAL_FILE_CANCELED = 11
|
||||
REQUEST_ERROR_DATA_DIR_CANNOT_CREATE = 12
|
||||
REQUEST_OTHER = 13
|
||||
REQUEST_INVALID_PASSWORD = 14
|
||||
|
||||
def __init__(self, common, is_gui, mode_settings, mode="share"):
|
||||
self.common = common
|
||||
self.common.log("Web", "__init__", f"is_gui={is_gui}, mode={mode}")
|
||||
|
||||
self.settings = mode_settings
|
||||
|
||||
# The flask app
|
||||
self.app = Flask(
|
||||
__name__,
|
||||
static_folder=self.common.get_resource_path("static"),
|
||||
static_url_path=f"/static_{self.common.random_string(16)}", # randomize static_url_path to avoid making /static unusable
|
||||
template_folder=self.common.get_resource_path("templates"),
|
||||
)
|
||||
self.app.secret_key = self.common.random_string(8)
|
||||
self.generate_static_url_path()
|
||||
self.auth = HTTPBasicAuth()
|
||||
self.auth.error_handler(self.error401)
|
||||
|
||||
# Verbose mode?
|
||||
if self.common.verbose:
|
||||
self.verbose_mode()
|
||||
|
||||
# Are we running in GUI mode?
|
||||
self.is_gui = is_gui
|
||||
|
||||
# If the user stops the server while a transfer is in progress, it should
|
||||
# immediately stop the transfer. In order to make it thread-safe, stop_q
|
||||
# is a queue. If anything is in it, then the user stopped the server
|
||||
self.stop_q = queue.Queue()
|
||||
|
||||
# Are we using receive mode?
|
||||
self.mode = mode
|
||||
if self.mode == "receive":
|
||||
# Use custom WSGI middleware, to modify environ
|
||||
self.app.wsgi_app = ReceiveModeWSGIMiddleware(self.app.wsgi_app, self)
|
||||
# Use a custom Request class to track upload progess
|
||||
self.app.request_class = ReceiveModeRequest
|
||||
|
||||
# Starting in Flask 0.11, render_template_string autoescapes template variables
|
||||
# by default. To prevent content injection through template variables in
|
||||
# earlier versions of Flask, we force autoescaping in the Jinja2 template
|
||||
# engine if we detect a Flask version with insecure default behavior.
|
||||
if Version(flask_version) < Version("0.11"):
|
||||
# Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc
|
||||
Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape
|
||||
|
||||
self.security_headers = [
|
||||
("X-Frame-Options", "DENY"),
|
||||
("X-Xss-Protection", "1; mode=block"),
|
||||
("X-Content-Type-Options", "nosniff"),
|
||||
("Referrer-Policy", "no-referrer"),
|
||||
("Server", "OnionShare"),
|
||||
]
|
||||
|
||||
self.q = queue.Queue()
|
||||
self.password = None
|
||||
|
||||
self.reset_invalid_passwords()
|
||||
|
||||
self.done = False
|
||||
|
||||
# shutting down the server only works within the context of flask, so the easiest way to do it is over http
|
||||
self.shutdown_password = self.common.random_string(16)
|
||||
|
||||
# Keep track if the server is running
|
||||
self.running = False
|
||||
|
||||
# Define the web app routes
|
||||
self.define_common_routes()
|
||||
|
||||
# Create the mode web object, which defines its own routes
|
||||
self.share_mode = None
|
||||
self.receive_mode = None
|
||||
self.website_mode = None
|
||||
self.chat_mode = None
|
||||
if self.mode == "share":
|
||||
self.share_mode = ShareModeWeb(self.common, self)
|
||||
elif self.mode == "receive":
|
||||
self.receive_mode = ReceiveModeWeb(self.common, self)
|
||||
elif self.mode == "website":
|
||||
self.website_mode = WebsiteModeWeb(self.common, self)
|
||||
elif self.mode == "chat":
|
||||
self.socketio = SocketIO()
|
||||
self.socketio.init_app(self.app)
|
||||
self.chat_mode = ChatModeWeb(self.common, self)
|
||||
|
||||
def get_mode(self):
|
||||
if self.mode == "share":
|
||||
return self.share_mode
|
||||
elif self.mode == "receive":
|
||||
return self.receive_mode
|
||||
elif self.mode == "website":
|
||||
return self.website_mode
|
||||
elif self.mode == "chat":
|
||||
return self.chat_mode
|
||||
else:
|
||||
return None
|
||||
|
||||
def generate_static_url_path(self):
|
||||
# The static URL path has a 128-bit random number in it to avoid having name
|
||||
# collisions with files that might be getting shared
|
||||
self.static_url_path = f"/static_{self.common.random_string(16)}"
|
||||
self.common.log(
|
||||
"Web",
|
||||
"generate_static_url_path",
|
||||
f"new static_url_path is {self.static_url_path}",
|
||||
)
|
||||
|
||||
# Update the flask route to handle the new static URL path
|
||||
self.app.static_url_path = self.static_url_path
|
||||
self.app.add_url_rule(
|
||||
self.static_url_path + "/<path:filename>",
|
||||
endpoint="static",
|
||||
view_func=self.app.send_static_file,
|
||||
)
|
||||
|
||||
def define_common_routes(self):
|
||||
"""
|
||||
Common web app routes between all modes.
|
||||
"""
|
||||
|
||||
@self.auth.get_password
|
||||
def get_pw(username):
|
||||
if username == "onionshare":
|
||||
return self.password
|
||||
else:
|
||||
return None
|
||||
|
||||
@self.app.before_request
|
||||
def conditional_auth_check():
|
||||
# Allow static files without basic authentication
|
||||
if request.path.startswith(self.static_url_path + "/"):
|
||||
return None
|
||||
|
||||
# If public mode is disabled, require authentication
|
||||
if not self.settings.get("general", "public"):
|
||||
|
||||
@self.auth.login_required
|
||||
def _check_login():
|
||||
return None
|
||||
|
||||
return _check_login()
|
||||
|
||||
@self.app.errorhandler(404)
|
||||
def not_found(e):
|
||||
mode = self.get_mode()
|
||||
history_id = mode.cur_history_id
|
||||
mode.cur_history_id += 1
|
||||
return self.error404(history_id)
|
||||
|
||||
@self.app.route("/<password_candidate>/shutdown")
|
||||
def shutdown(password_candidate):
|
||||
"""
|
||||
Stop the flask web server, from the context of an http request.
|
||||
"""
|
||||
if password_candidate == self.shutdown_password:
|
||||
self.force_shutdown()
|
||||
return ""
|
||||
abort(404)
|
||||
|
||||
if self.mode != "website":
|
||||
|
||||
@self.app.route("/favicon.ico")
|
||||
def favicon():
|
||||
return send_file(
|
||||
f"{self.common.get_resource_path('static')}/img/favicon.ico"
|
||||
)
|
||||
|
||||
def error401(self):
|
||||
auth = request.authorization
|
||||
if auth:
|
||||
if (
|
||||
auth["username"] == "onionshare"
|
||||
and auth["password"] not in self.invalid_passwords
|
||||
):
|
||||
print(f"Invalid password guess: {auth['password']}")
|
||||
self.add_request(Web.REQUEST_INVALID_PASSWORD, data=auth["password"])
|
||||
|
||||
self.invalid_passwords.append(auth["password"])
|
||||
self.invalid_passwords_count += 1
|
||||
|
||||
if self.invalid_passwords_count == 20:
|
||||
self.add_request(Web.REQUEST_RATE_LIMIT)
|
||||
self.force_shutdown()
|
||||
print(
|
||||
"Someone has made too many wrong attempts to guess your password, so OnionShare has stopped the server. Start sharing again and send the recipient a new address to share."
|
||||
)
|
||||
|
||||
r = make_response(
|
||||
render_template("401.html", static_url_path=self.static_url_path), 401
|
||||
)
|
||||
return self.add_security_headers(r)
|
||||
|
||||
def error403(self):
|
||||
self.add_request(Web.REQUEST_OTHER, request.path)
|
||||
r = make_response(
|
||||
render_template("403.html", static_url_path=self.static_url_path), 403
|
||||
)
|
||||
return self.add_security_headers(r)
|
||||
|
||||
def error404(self, history_id):
|
||||
self.add_request(
|
||||
self.REQUEST_INDIVIDUAL_FILE_STARTED,
|
||||
request.path,
|
||||
{"id": history_id, "status_code": 404},
|
||||
)
|
||||
|
||||
self.add_request(Web.REQUEST_OTHER, request.path)
|
||||
r = make_response(
|
||||
render_template("404.html", static_url_path=self.static_url_path), 404
|
||||
)
|
||||
return self.add_security_headers(r)
|
||||
|
||||
def error405(self, history_id):
|
||||
self.add_request(
|
||||
self.REQUEST_INDIVIDUAL_FILE_STARTED,
|
||||
request.path,
|
||||
{"id": history_id, "status_code": 405},
|
||||
)
|
||||
|
||||
self.add_request(Web.REQUEST_OTHER, request.path)
|
||||
r = make_response(
|
||||
render_template("405.html", static_url_path=self.static_url_path), 405
|
||||
)
|
||||
return self.add_security_headers(r)
|
||||
|
||||
def add_security_headers(self, r):
|
||||
"""
|
||||
Add security headers to a request
|
||||
"""
|
||||
for header, value in self.security_headers:
|
||||
r.headers.set(header, value)
|
||||
# Set a CSP header unless in website mode and the user has disabled it
|
||||
if not self.settings.get("website", "disable_csp") or self.mode != "website":
|
||||
r.headers.set(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:;",
|
||||
)
|
||||
return r
|
||||
|
||||
def _safe_select_jinja_autoescape(self, filename):
|
||||
if filename is None:
|
||||
return True
|
||||
return filename.endswith((".html", ".htm", ".xml", ".xhtml"))
|
||||
|
||||
def add_request(self, request_type, path=None, data=None):
|
||||
"""
|
||||
Add a request to the queue, to communicate with the GUI.
|
||||
"""
|
||||
self.q.put({"type": request_type, "path": path, "data": data})
|
||||
|
||||
def generate_password(self, saved_password=None):
|
||||
self.common.log("Web", "generate_password", f"saved_password={saved_password}")
|
||||
if saved_password != None and saved_password != "":
|
||||
self.password = saved_password
|
||||
self.common.log(
|
||||
"Web",
|
||||
"generate_password",
|
||||
f'saved_password sent, so password is: "{self.password}"',
|
||||
)
|
||||
else:
|
||||
self.password = self.common.build_password()
|
||||
self.common.log(
|
||||
"Web", "generate_password", f'built random password: "{self.password}"'
|
||||
)
|
||||
|
||||
def verbose_mode(self):
|
||||
"""
|
||||
Turn on verbose mode, which will log flask errors to a file.
|
||||
"""
|
||||
flask_log_filename = os.path.join(self.common.build_data_dir(), "flask.log")
|
||||
log_handler = logging.FileHandler(flask_log_filename)
|
||||
log_handler.setLevel(logging.WARNING)
|
||||
self.app.logger.addHandler(log_handler)
|
||||
|
||||
def reset_invalid_passwords(self):
|
||||
self.invalid_passwords_count = 0
|
||||
self.invalid_passwords = []
|
||||
|
||||
def force_shutdown(self):
|
||||
"""
|
||||
Stop the flask web server, from the context of the flask app.
|
||||
"""
|
||||
# Shutdown the flask service
|
||||
try:
|
||||
func = request.environ.get("werkzeug.server.shutdown")
|
||||
if func is None:
|
||||
raise RuntimeError("Not running with the Werkzeug Server")
|
||||
func()
|
||||
except:
|
||||
pass
|
||||
self.running = False
|
||||
|
||||
def start(self, port):
|
||||
"""
|
||||
Start the flask web server.
|
||||
"""
|
||||
self.common.log("Web", "start", f"port={port}")
|
||||
|
||||
# Make sure the stop_q is empty when starting a new server
|
||||
while not self.stop_q.empty():
|
||||
try:
|
||||
self.stop_q.get(block=False)
|
||||
except queue.Empty:
|
||||
pass
|
||||
|
||||
# In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220)
|
||||
if os.path.exists("/usr/share/anon-ws-base-files/workstation"):
|
||||
host = "0.0.0.0"
|
||||
else:
|
||||
host = "127.0.0.1"
|
||||
|
||||
self.running = True
|
||||
if self.mode == "chat":
|
||||
self.socketio.run(self.app, host=host, port=port)
|
||||
else:
|
||||
self.app.run(host=host, port=port, threaded=True)
|
||||
|
||||
def stop(self, port):
|
||||
"""
|
||||
Stop the flask web server by loading /shutdown.
|
||||
"""
|
||||
self.common.log("Web", "stop", "stopping server")
|
||||
|
||||
# Let the mode know that the user stopped the server
|
||||
self.stop_q.put(True)
|
||||
|
||||
# To stop flask, load http://shutdown:[shutdown_password]@127.0.0.1/[shutdown_password]/shutdown
|
||||
# (We're putting the shutdown_password in the path as well to make routing simpler)
|
||||
if self.running:
|
||||
if self.password:
|
||||
requests.get(
|
||||
f"http://127.0.0.1:{port}/{self.shutdown_password}/shutdown",
|
||||
auth=requests.auth.HTTPBasicAuth("onionshare", self.password),
|
||||
)
|
||||
else:
|
||||
requests.get(
|
||||
f"http://127.0.0.1:{port}/{self.shutdown_password}/shutdown"
|
||||
)
|
||||
|
||||
# Reset any password that was in use
|
||||
self.password = None
|
123
cli/onionshare_cli/web/website_mode.py
Normal file
123
cli/onionshare_cli/web/website_mode.py
Normal file
|
@ -0,0 +1,123 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OnionShare | https://onionshare.org/
|
||||
|
||||
Copyright (C) 2014-2020 Micah Lee, et al. <micah@micahflee.com>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import mimetypes
|
||||
from flask import Response, request, render_template, make_response
|
||||
|
||||
from .send_base_mode import SendBaseModeWeb
|
||||
|
||||
|
||||
class WebsiteModeWeb(SendBaseModeWeb):
|
||||
"""
|
||||
All of the web logic for website mode
|
||||
"""
|
||||
|
||||
def init(self):
|
||||
pass
|
||||
|
||||
def define_routes(self):
|
||||
"""
|
||||
The web app routes for sharing a website
|
||||
"""
|
||||
|
||||
@self.web.app.route("/", defaults={"path": ""})
|
||||
@self.web.app.route("/<path:path>")
|
||||
def path_public(path):
|
||||
return path_logic(path)
|
||||
|
||||
def path_logic(path=""):
|
||||
"""
|
||||
Render the onionshare website.
|
||||
"""
|
||||
return self.render_logic(path)
|
||||
|
||||
def directory_listing_template(
|
||||
self, path, files, dirs, breadcrumbs, breadcrumbs_leaf
|
||||
):
|
||||
return make_response(
|
||||
render_template(
|
||||
"listing.html",
|
||||
path=path,
|
||||
files=files,
|
||||
dirs=dirs,
|
||||
breadcrumbs=breadcrumbs,
|
||||
breadcrumbs_leaf=breadcrumbs_leaf,
|
||||
static_url_path=self.web.static_url_path,
|
||||
)
|
||||
)
|
||||
|
||||
def set_file_info_custom(self, filenames, processed_size_callback):
|
||||
self.common.log("WebsiteModeWeb", "set_file_info_custom")
|
||||
self.web.cancel_compression = True
|
||||
|
||||
def render_logic(self, path=""):
|
||||
if path in self.files:
|
||||
filesystem_path = self.files[path]
|
||||
|
||||
# If it's a directory
|
||||
if os.path.isdir(filesystem_path):
|
||||
# Is there an index.html?
|
||||
index_path = os.path.join(path, "index.html")
|
||||
if index_path in self.files:
|
||||
# Render it
|
||||
return self.stream_individual_file(self.files[index_path])
|
||||
|
||||
else:
|
||||
# Otherwise, render directory listing
|
||||
filenames = []
|
||||
for filename in os.listdir(filesystem_path):
|
||||
if os.path.isdir(os.path.join(filesystem_path, filename)):
|
||||
filenames.append(filename + "/")
|
||||
else:
|
||||
filenames.append(filename)
|
||||
filenames.sort()
|
||||
return self.directory_listing(filenames, path, filesystem_path)
|
||||
|
||||
# If it's a file
|
||||
elif os.path.isfile(filesystem_path):
|
||||
return self.stream_individual_file(filesystem_path)
|
||||
|
||||
# If it's not a directory or file, throw a 404
|
||||
else:
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
return self.web.error404(history_id)
|
||||
else:
|
||||
# Special case loading /
|
||||
|
||||
if path == "":
|
||||
index_path = "index.html"
|
||||
if index_path in self.files:
|
||||
# Render it
|
||||
return self.stream_individual_file(self.files[index_path])
|
||||
else:
|
||||
# Root directory listing
|
||||
filenames = list(self.root_files)
|
||||
filenames.sort()
|
||||
return self.directory_listing(filenames, path)
|
||||
|
||||
else:
|
||||
# If the path isn't found, throw a 404
|
||||
history_id = self.cur_history_id
|
||||
self.cur_history_id += 1
|
||||
return self.web.error404(history_id)
|
Loading…
Add table
Add a link
Reference in a new issue