Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
cmake_minimum_required(VERSION 3.26)
project(pyquickshare LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
find_package(pybind11 REQUIRED CONFIG)
find_package(PkgConfig)


pkg_check_modules(BLUEZ bluez)
if(NOT BLUEZ_FOUND)
pkg_check_modules(BLUEZ REQUIRED bluetooth)
endif()

pybind11_add_module(_rfcomm pyquickshare/rfcomm/_rfcomm.cpp)
target_include_directories(_rfcomm PRIVATE ${BLUEZ_INCLUDE_DIRS})
target_link_libraries(_rfcomm PRIVATE ${BLUEZ_LINK_LIBRARIES})

install(TARGETS _rfcomm DESTINATION pyquickshare/rfcomm)
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# pyquickshare

![Ruff logo](https://img.shields.io/endpoint?url=https%3A%2F%2Fteaishealthy.me%2Fv2.json&style=flat-square)
![Ruff logo](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/teaishealthy/teaishealthy/refs/heads/main/ruff-badge.json&style=flat-square)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/teaishealthy/pyquickshare/ruff.yml?style=flat-square&label=lint+and+format)
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/teaishealthy/pyquickshare/test.yml?style=flat-square&label=tests)
![Coveralls](https://img.shields.io/coverallsCoverage/github/teaishealthy/pyquickshare?style=flat-square)


An implementation of Quick Share in Python.
An asynchronous Python implementation of the Android Quick Share (Nearby Share) protocol

## System requirements

Expand All @@ -29,15 +29,18 @@ Communication with `firewalld` is done over D-Bus, `polkit` may prompt for authe
## Installation

```bash
pip install git+https://github.com/teaishealthy/pyquickshare
pip install pyquickshare

# or, to install with extras (QR code support)
pip install pyquickshare[extras]
```

## Features

Receive is fully implemented, namely WiFi credentials, files, and text. Sending only supports files, but support for sending text and WiFi credentials is planned.

### Transfer
Only LAN/Wifi is supported at the moment, but Bluetooth is planned.
Quick Share supports two "bare" transports: WiFi/Lan and Bluetooth Classic. Bluetooth Classic *can* transfer files, but can also be used to trigger an upgrade to a faster medium (e.g. WiFi Direct or Hotspot).

### Discovery
pyquickshare uses mDNS to discover other devices on the local network. BLE is only used to trigger advertisment at the moment.
Expand All @@ -58,10 +61,12 @@ uv run example.py send <file>

## Notes and Acknowledgements

The code in [`pyquickshare/protos`](https://github.com/teaishealthy/pyquickshare/blob/main/pyquickshare/protos/) is generated from protobuf sources licensed under Apache 2.0.
- The code in [`pyquickshare/protos`](https://github.com/teaishealthy/pyquickshare/blob/main/pyquickshare/protos/) is generated from protobuf sources licensed under Apache 2.0.
As a derivative work, these generated files remain under the original Apache 2.0 license.
A copy of the original license can be found in the [`pyquickshare/protos`](https://github.com/teaishealthy/pyquickshare/blob/main/pyquickshare/protos/) directory.

- This project would not have been possible without the amazing reverse engineering work done by [grishka](https://github.com/grishka/) on the Quick Share protocol.
Check out [NearDrop](https://github.com/grishka/NearDrop/), a similar project for Mac OS.

This project would not have been possible without the amazing reverse engineering work done by [grishka](https://github.com/grishka/) on the Quick Share protocol.
Check out [NearDrop](https://github.com/grishka/NearDrop/), a similar project for Mac OS.
- **WiFi-Direct**: While according to Google's Nearby documentation and the protobuf fields WiFi-Direct is supposed to be an available medium, it seems that Quick Share does not use it.
It more likely uses WiFi-Aware which isn't widely supported outside of Android devices.
5 changes: 4 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@


async def send(file: str) -> None:
first = await anext(pyquickshare.discover_services())
quickshare = await pyquickshare.discover_services()
quickshare.qr_code.print()

first = await anext(quickshare)

return await pyquickshare.send_to(first, file=file)

Expand Down
56 changes: 50 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "pyquickshare"
version = "0.1.0"
description = ""
version = "0.1.0.post1"
description = "An asynchronous Python implementation of the Android Quick Share (Nearby Share) protocol"
authors = [{ name = "teaishealthy", email = "teaishealthy@protonmail.com" }]
requires-python = "~=3.10.0"
readme = "README.md"
Expand All @@ -11,14 +11,55 @@ dependencies = [
"bless>=0.2.6",
"cryptography>=44.0.1",
"dbus-next>=0.2.3",
"protobuf>=5.29.3",
"protobuf>=6.32.0",
"python-magic>=0.4.27",
"zeroconf>=0.145.1",

# need to pin bleak (dependency of bless)
"bleak==0.22.3",
]

keywords = [
"quick share",
"quickshare",
"nearby share",
"nearbyshare",
"file transfer",
"file sharing",
"asyncio",
"linux",
"android",
]

classifiers = [
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Operating System :: POSIX :: Linux",
"Operating System :: Android",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"Topic :: Communications :: File Sharing",

# Things we integrate with
"Topic :: System :: Networking",
"Topic :: System :: Networking :: Firewalls",
"Topic :: Security :: Cryptography",
"Topic :: Internet :: Name Service (DNS)",

"Topic :: Software Development :: Libraries :: Python Modules",
"Typing :: Typed",
"Framework :: AsyncIO",
]

[project.urls]
Repository = "https://github.com/teaishealthy/pyquickshare"
Issues = "https://github.com/teaishealthy/pyquickshare/issues"

[project.optional-dependencies]
extras = ["qrcode>=8.2"]

[dependency-groups]
dev = [
"pytest>=8.3.4",
Expand Down Expand Up @@ -76,5 +117,8 @@ exclude_also = ["pragma: no cover", "if TYPE_CHECKING:"]
asyncio_default_fixture_loop_scope = "session"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
requires = ["scikit-build-core>=0.10", "pybind11>=2.13"]
build-backend = "scikit_build_core.build"

[tool.scikit-build]
wheel.packages = ["pyquickshare"]
123 changes: 123 additions & 0 deletions pyquickshare/bluetooth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import asyncio
import logging
import socket
from dataclasses import dataclass
from typing import Any, AsyncGenerator, cast

from dbus_next.aio.message_bus import MessageBus
from dbus_next.constants import BusType

from . import rfcomm
from .dbus.dbus import get_proxy_object

logger = logging.getLogger(__name__)


BLEUTOOTH_QUICKSHARE_UUID = "a82efa21-ae5c-3dde-9bbc-f16da7b16c5a"
BLEUTOOTH_QUICKSHARE_RECEIVE_UUID = "0000fef3-0000-1000-8000-00805f9b34fb"
BLUETOOTH_QUICKSHARE_NEW_UUID = "00001101-0000-1000-8000-00805f9b34fb"
UUIDS = [
BLEUTOOTH_QUICKSHARE_UUID,
BLEUTOOTH_QUICKSHARE_RECEIVE_UUID,
BLUETOOTH_QUICKSHARE_NEW_UUID,
]


@dataclass
class BluetoothDevice:
name: str
address: str
channel: int


async def find_receiving_devices() -> AsyncGenerator[BluetoothDevice, None]:
logger.debug("Connecting to the system bus")
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
logger.info("Connected to the system bus")

bluez_root = await get_proxy_object(
bus,
"org.bluez",
"/",
)

object_manager = bluez_root.get_interface("org.freedesktop.DBus.ObjectManager")
objects = await object_manager.call_get_managed_objects()

adapter_path = None
for path, interfaces in objects.items():
if "org.bluez.Adapter1" in interfaces:
logger.debug("Found adapter at %s", path)
adapter_path = path
break

if adapter_path is None:
logger.error("No Bluetooth adapter found")
return

queue: asyncio.Queue[str] = asyncio.Queue()

for path, interface in objects.items():
if "org.bluez.Device1" in interface:
await queue.put(path)

register_new_devices(object_manager, queue)

adapter_proxy = await get_proxy_object(bus, "org.bluez", adapter_path)
adapter = adapter_proxy.get_interface("org.bluez.Adapter1")
await adapter.call_start_discovery()

while True:
path = await queue.get()
device_proxy = await get_proxy_object(bus, "org.bluez", path)
device = device_proxy.get_interface("org.bluez.Device1")
uuids = [u.casefold() for u in await device.get_uui_ds()]
if BLEUTOOTH_QUICKSHARE_UUID in uuids:
name = await device.get_name()
address = await device.get_address()
logger.info("Found QuickShare device: %s (%s) at %s", name, address, path)

channel = cast(
int,
rfcomm.find_rfcomm_channel(address, BLEUTOOTH_QUICKSHARE_UUID), # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
)

yield BluetoothDevice(name, address, channel)


def register_new_devices(object_manager: Any, queue: asyncio.Queue[str]) -> None:
def on_interfaces_added(object_path: str, interfaces: dict[str, Any]) -> None:
if "org.bluez.Device1" in interfaces:
logger.debug("Found new device at %s", object_path)
queue.put_nowait(object_path)

object_manager.on_interfaces_added(on_interfaces_added)


async def connect_bluetooth_device(device: BluetoothDevice) -> socket.socket:
logger.info(
"Connecting to device %s (%s) on channel %d", device.name, device.address, device.channel
)

sock = rfcomm.open_rfcomm_socket()
rfcomm.connect_rfcomm(sock.fileno(), device.address, device.channel) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
logger.info(
"Connected to device %s (%s) on channel %d", device.name, device.address, device.channel
)

return sock


async def tinker() -> None:
async for device in find_receiving_devices():
sock = await connect_bluetooth_device(device)
sock.close()
break


if __name__ == "__main__":
import asyncio

logging.basicConfig(level=logging.DEBUG)

asyncio.run(tinker())
11 changes: 9 additions & 2 deletions pyquickshare/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from cryptography.hazmat.primitives import hashes, hmac, padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from pyquickshare.protos import (
from .protos import (
device_to_device_messages_pb2,
offline_wire_formats_pb2,
securegcm_pb2,
Expand Down Expand Up @@ -268,13 +268,20 @@ async def send(frame: bytes, *, id: int | None = None) -> None:
return send


def generate_paired_key_encryption() -> wire_format_pb2.Frame:
def generate_paired_key_encryption(
qr_code_handshake_data: bytes | None = None,
) -> wire_format_pb2.Frame:
paired_key_encryption = wire_format_pb2.Frame()
paired_key_encryption.v1.type = wire_format_pb2.V1Frame.PAIRED_KEY_ENCRYPTION
paired_key_encryption.version = wire_format_pb2.Frame.V1
paired_key_encryption.v1.paired_key_encryption.secret_id_hash = bytes(
[0x00] * 6,
) # fmt: off
if qr_code_handshake_data:
paired_key_encryption.v1.paired_key_encryption.qr_code_handshake_data = (
qr_code_handshake_data
)

paired_key_encryption.v1.paired_key_encryption.signed_data = bytes([0x00] * 72)
return paired_key_encryption

Expand Down
Empty file added pyquickshare/dbus/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions pyquickshare/dbus/dbus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import Any

from dbus_next.aio.message_bus import MessageBus


async def get_proxy_object(
bus: MessageBus,
name: str,
path: str,
introspection: Any = None,
) -> Any:
if introspection is None:
introspection = await bus.introspect(
name,
path,
)

return bus.get_proxy_object(
name,
path,
introspection,
)
22 changes: 2 additions & 20 deletions pyquickshare/firewalld.py → pyquickshare/dbus/firewalld.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,18 @@
"""Module to command firewalld to open a port to allow incoming connections temporarily."""

import logging
from typing import Any

from dbus_next.aio.message_bus import MessageBus
from dbus_next.constants import BusType

from .dbus import get_proxy_object

logger = logging.getLogger(__name__)


__all__ = ("temporarily_open_port",)


async def get_proxy_object(
bus: MessageBus,
name: str,
path: str,
introspection: Any = None,
) -> Any:
if introspection is None:
introspection = await bus.introspect(
name,
path,
)

return bus.get_proxy_object(
name,
path,
introspection,
)


async def temporarily_open_port(interface: str, port: int = 8080) -> None:
logger.info("Opening port %d for 5 minutes", port)

Expand Down
Loading