magic-wormhole/bin/receive_file.py

49 lines
1.6 KiB
Python
Raw Normal View History

2015-02-11 09:18:31 +00:00
from __future__ import print_function
2015-02-11 01:04:28 +00:00
import os, sys, json
2015-02-11 00:50:32 +00:00
from binascii import unhexlify
from nacl.secret import SecretBox
2015-02-15 17:53:59 +00:00
from wormhole.blocking.transcribe import Receiver
from wormhole.codes import input_code_with_completion
from wormhole.blocking.transit import TransitReceiver
2015-02-11 00:50:32 +00:00
APPID = "lothar.com/wormhole/file-xfer"
# we're receiving
2015-02-15 17:53:59 +00:00
transit_receiver = TransitReceiver()
direct_hints = transit_receiver.get_direct_hints()
2015-02-15 22:42:59 +00:00
mydata = json.dumps({
"transit": {
"direct_connection_hints": direct_hints,
},
}).encode("utf-8")
r = Receiver(APPID, mydata)
2015-02-15 17:53:59 +00:00
r.set_code(r.input_code("Enter receive-text wormhole code: "))
2015-02-15 22:42:59 +00:00
data = json.loads(r.get_data().decode("utf-8"))
print("their data: %r" % (data,))
2015-02-15 17:53:59 +00:00
2015-02-15 22:42:59 +00:00
file_data = data["file"]
xfer_key = unhexlify(file_data["key"].encode("ascii"))
filename = os.path.basename(file_data["filename"]) # unicode
filesize = file_data["filesize"]
2015-02-11 00:50:32 +00:00
# now receive the rest of the owl
2015-02-15 22:42:59 +00:00
tdata = data["transit"]
transit_receiver.set_transit_key(tdata["key"])
transit_receiver.add_sender_direct_hints(tdata["direct_connection_hints"])
transit_receiver.add_sender_relay_hints(tdata["relay_connection_hints"])
transit_receiver.establish_connection()
2015-02-15 17:53:59 +00:00
encrypted = transit_receiver.receive()
2015-02-11 01:04:28 +00:00
decrypted = SecretBox(xfer_key).decrypt(encrypted)
# only write to the current directory, and never overwrite anything
here = os.path.abspath(os.getcwd())
target = os.path.abspath(os.path.join(here, filename))
assert os.path.dirname(target) == here
assert not os.path.exists(target)
with open(target, "wb") as f:
f.write(decrypted)
print("%s written" % filename)