├── .github └── workflows │ ├── cron.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── Containerfile.alpine ├── Containerfile.debian ├── INSTALL.md ├── LICENSE.txt ├── README.md ├── config-sample.toml ├── docker-compose.yml ├── kubernetes ├── README.md ├── deployment.yaml ├── ingress.yaml ├── pvc.yaml ├── secret.yaml └── service.yaml ├── mollysocket-vapid.service ├── mollysocket.service ├── proto ├── SignalService.proto └── WebSocketResources.proto ├── reverse_proxy_samples ├── Caddyfile └── apache.conf └── src ├── build_proto.rs ├── cli.rs ├── cli ├── connection.rs ├── qrcode.rs ├── server.rs ├── test.rs └── vapid.rs ├── config.rs ├── db.rs ├── db └── migrations.rs ├── main.rs ├── qrcode.rs ├── server.rs ├── server ├── connections.rs ├── metrics.rs ├── web.rs └── web │ └── html.rs ├── utils.rs ├── utils └── post_allowed.rs ├── vapid.rs ├── ws.rs └── ws ├── certs └── signal-messenger.pem ├── proto_signalservice.rs ├── proto_websocketresources.rs ├── signalwebsocket.rs ├── tls.rs └── websocket_connection.rs /.github/workflows/cron.yml: -------------------------------------------------------------------------------- 1 | name: Cron to rebuild latest 2 | 3 | on: 4 | workflow_dispatch: 5 | schedule: 6 | # rebuild latest regulary - to resolve CVEs in base images 7 | - cron: "0 10 * * *" 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | flavor: ['debian', 'alpine'] 19 | steps: 20 | - uses: actions/checkout@v4 21 | with: 22 | fetch-tags: true 23 | filter: blob:none 24 | fetch-depth: 0 25 | 26 | - name: Checkout last commit 27 | id: checkout 28 | run: | 29 | LAST_TAG=$(git for-each-ref refs/tags --sort=-authordate --format='%(refname:short)' | grep '^[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]$' | head -n1) 30 | echo "LAST_TAG: $LAST_TAG" 31 | echo "tag=$LAST_TAG" >> "$GITHUB_OUTPUT" 32 | git checkout $LAST_TAG 33 | 34 | - name: Docker meta 35 | id: meta 36 | uses: docker/metadata-action@v5 37 | with: 38 | # list of Docker images to use as base name for tags 39 | images: | 40 | ghcr.io/${{ github.repository }} 41 | # add flavor to set latest to false and add those with raw values instead 42 | flavor: | 43 | latest=false 44 | prefix= 45 | suffix= 46 | # generate Docker tags based on the following events/attributes 47 | tags: | 48 | type=schedule 49 | type=raw,value=latest,enable=${{matrix.flavor == 'debian'}} 50 | type=raw,value=latest-${{matrix.flavor}} 51 | type=semver,pattern={{version}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 52 | type=semver,pattern={{major}}.{{minor}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 53 | type=semver,pattern={{major}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 54 | type=semver,pattern={{version}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 55 | type=semver,pattern={{major}}.{{minor}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 56 | type=semver,pattern={{major}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 57 | 58 | - name: Set up QEMU 59 | uses: docker/setup-qemu-action@v3 60 | 61 | - name: Set up Docker Buildx 62 | uses: docker/setup-buildx-action@v3 63 | 64 | - name: Login to GitHub Container Registry 65 | if: github.event_name != 'pull_request' 66 | uses: docker/login-action@v3 67 | with: 68 | registry: ghcr.io 69 | username: ${{ github.actor }} 70 | password: ${{ secrets.GITHUB_TOKEN }} 71 | 72 | - name: Build and push 73 | uses: docker/build-push-action@v5 74 | with: 75 | context: . 76 | push: ${{ github.event_name != 'pull_request' }} 77 | file: Containerfile.${{ matrix.flavor }} 78 | platforms: linux/amd64,linux/arm64/v8${{ matrix.flavor == 'debian' && ',linux/arm/v7' || '' }} 79 | tags: ${{ steps.meta.outputs.tags }} 80 | labels: ${{ steps.meta.outputs.labels }} 81 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | tags: 7 | - "[0-9]+.[0-9]+.[0-9]+" 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | flavor: ['debian', 'alpine'] 19 | steps: 20 | - uses: actions/checkout@v4 21 | with: 22 | fetch-tags: true 23 | filter: blob:none 24 | fetch-depth: 0 25 | 26 | - name: Docker meta 27 | id: meta 28 | uses: docker/metadata-action@v5 29 | with: 30 | # list of Docker images to use as base name for tags 31 | images: | 32 | ghcr.io/${{ github.repository }} 33 | # add flavor to set latest to false and add those with raw values instead 34 | flavor: | 35 | latest=false 36 | prefix= 37 | suffix= 38 | # generate Docker tags based on the following events/attributes 39 | tags: | 40 | type=schedule 41 | type=raw,value=latest,enable=${{matrix.flavor == 'debian'}} 42 | type=raw,value=latest-${{matrix.flavor}} 43 | type=semver,pattern={{version}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 44 | type=semver,pattern={{major}}.{{minor}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 45 | type=semver,pattern={{major}},value=${{ steps.checkout.outputs.tag }},enable=${{matrix.flavor == 'debian'}} 46 | type=semver,pattern={{version}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 47 | type=semver,pattern={{major}}.{{minor}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 48 | type=semver,pattern={{major}}-${{matrix.flavor}},value=${{ steps.checkout.outputs.tag }} 49 | 50 | - name: Set up QEMU 51 | uses: docker/setup-qemu-action@v3 52 | 53 | - name: Set up Docker Buildx 54 | uses: docker/setup-buildx-action@v3 55 | 56 | - name: Set Up containerd image store 57 | shell: bash 58 | run: | 59 | ( cat /etc/docker/daemon.json || echo '{}' ) | jq '. | .+{"features": {"containerd-snapshotter": true}}' | sudo tee /etc/docker/daemon.json 60 | sudo systemctl restart docker 61 | 62 | - name: Login to GitHub Container Registry 63 | if: github.event_name != 'pull_request' 64 | uses: docker/login-action@v3 65 | with: 66 | registry: ghcr.io 67 | username: ${{ github.actor }} 68 | password: ${{ secrets.GITHUB_TOKEN }} 69 | 70 | - name: Prepare artifacts 71 | run: | 72 | mkdir -p artifacts-${{ matrix.flavor }} 73 | mkdir -p out 74 | 75 | - name: Build and publish 76 | id: build 77 | uses: docker/build-push-action@v5 78 | with: 79 | context: . 80 | push: true 81 | file: Containerfile.${{ matrix.flavor }} 82 | platforms: linux/amd64,linux/arm64/v8${{ matrix.flavor == 'debian' && ',linux/arm/v7' || '' }} 83 | tags: ${{ steps.meta.outputs.tags }} 84 | labels: ${{ steps.meta.outputs.labels }} 85 | outputs: | 86 | type=local,dest=out 87 | type=docker 88 | 89 | - name: Copy artifacts 90 | run: | 91 | for k in $(ls out/); do 92 | ARCH=$(basename $k) 93 | if [[ "${{ matrix.flavor }}" == "alpine" ]]; then 94 | ARCH="musl-$ARCH" 95 | fi 96 | echo $ARCH 97 | if [ -f out/$k/usr/local/bin/mollysocket ]; then 98 | cp out/$k/usr/local/bin/mollysocket artifacts-${{ matrix.flavor }}/mollysocket-$ARCH 99 | fi 100 | done 101 | 102 | - name: Archive artifact 103 | uses: actions/upload-artifact@v4 104 | with: 105 | name: artifacts-${{ matrix.flavor }} 106 | path: | 107 | ./artifacts-${{ matrix.flavor }} 108 | 109 | publish: 110 | name: Publish 111 | needs: build 112 | runs-on: ubuntu-latest 113 | if: ${{ startsWith(github.ref, 'refs/tags/') }} 114 | 115 | steps: 116 | - uses: actions/checkout@v4 117 | 118 | - name: Download artifacts 119 | uses: actions/download-artifact@v4 120 | with: 121 | path: artifacts 122 | pattern: artifacts-* 123 | merge-multiple: true 124 | 125 | - run: ls -R ./artifacts 126 | 127 | - name: Create release draft 128 | run: gh release create -d -t "$GITHUB_REF_NAME" "$GITHUB_REF_NAME" ./artifacts/* 129 | env: 130 | GITHUB_TOKEN: ${{ secrets.PUBLISH_PAT || secrets.GITHUB_TOKEN }} 131 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: "**" 6 | pull_request: 7 | branches: "**" 8 | 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Install deps 19 | run: sudo apt update -y && sudo apt install -y libsqlite3-dev 20 | - name: Run tests 21 | run: cargo test --verbose 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /tmp 3 | mollysocket.db 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mollysocket" 3 | version = "1.6.0" 4 | edition = "2021" 5 | license = "AGPL-3.0-or-later" 6 | authors = ["S1m"] 7 | description = "MollySocket allows getting signal notifications via UnifiedPush." 8 | readme = "README.md" 9 | repository = "https://github.com/mollyim/mollysocket" 10 | keywords = ["unifiedpush", "molly", "signal"] 11 | # build = "src/build_proto.rs" 12 | 13 | [profile.release] 14 | strip = true # Automatically strip symbols from the binary. 15 | opt-level = "s" # Optimize for size 16 | lto = true # Link time optimization 17 | codegen-units = 1 # Limit code generation units 18 | 19 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 20 | 21 | [dependencies] 22 | async-trait = "0.1.85" 23 | env_logger = "0.11.6" 24 | futures-channel = "0.3" 25 | futures-util = "0.3" 26 | http = "1.2.0" 27 | # until https://github.com/rust-lang/rust/issues/27709 is merged 28 | ip_rfc = "0.1.0" 29 | lazy_static = "1.5.0" 30 | log = "0.4.25" 31 | native-tls = "0.2.12" 32 | prost = "0.13" 33 | reqwest = { version = "0.12.12", features = ["json"]} 34 | serde = { version = "1.0.217", features = ["derive"]} 35 | tokio-tungstenite = { version = "0.26.1", features = ["native-tls", "url"] } 36 | tokio = { version = "1", features = ["macros", "rt-multi-thread"] } 37 | url = "2.5.4" 38 | rusqlite = "0.32.1" 39 | rocket = { version = "0.5.1", features = ["json"]} 40 | rocket_prometheus = "0.10.1" 41 | trust-dns-resolver = { version = "0.23.2", features = ["tokio-runtime"]} 42 | eyre = "0.6.12" 43 | clap = {version = "4.5.26", features = ["derive"]} 44 | figment = { version = "0.10.19", features = ["toml", "env"] } 45 | directories = "6.0.0" 46 | regex = "1.11.1" 47 | qrcodegen = "1.8.0" 48 | base64 = "0.22.1" 49 | openssl = "0.10.68" 50 | jwt-simple = { version = "0.12.11", default-features = false, features = ["pure-rust"] } 51 | 52 | # [build-dependencies] 53 | # prost-build = { version = "0.12" } 54 | -------------------------------------------------------------------------------- /Containerfile.alpine: -------------------------------------------------------------------------------- 1 | FROM rust:alpine AS builder 2 | WORKDIR app 3 | 4 | RUN apk -U upgrade \ 5 | && apk add musl-dev openssl-dev openssl-libs-static sqlite-dev sqlite-static \ 6 | && rm -rf /var/cache/apk/* 7 | 8 | COPY . . 9 | RUN cargo build --release --bin mollysocket 10 | 11 | 12 | FROM alpine:latest AS runtime 13 | WORKDIR /data 14 | 15 | ENV MOLLY_HOST=0.0.0.0 16 | ENV MOLLY_PORT=8020 17 | 18 | RUN apk -U upgrade \ 19 | && apk add ca-certificates \ 20 | && rm -rf /var/cache/apk/* 21 | 22 | COPY --from=builder /app/target/release/mollysocket /usr/local/bin/ 23 | HEALTHCHECK --interval=1m --timeout=3s \ 24 | CMD wget -q --tries=1 "http://$MOLLY_HOST:$MOLLY_PORT/discover" -O - | grep '"mollysocket":{"version":' 25 | ENTRYPOINT ["/usr/local/bin/mollysocket"] 26 | -------------------------------------------------------------------------------- /Containerfile.debian: -------------------------------------------------------------------------------- 1 | FROM docker.io/rust:bookworm AS builder 2 | WORKDIR app 3 | 4 | RUN apt update \ 5 | && apt full-upgrade -y \ 6 | && rm -rf /var/lib/apt/lists/* 7 | 8 | COPY . . 9 | RUN cargo build --release --bin mollysocket 10 | 11 | 12 | FROM docker.io/debian:bookworm-slim AS runtime 13 | WORKDIR /data 14 | 15 | ENV MOLLY_HOST=0.0.0.0 16 | ENV MOLLY_PORT=8020 17 | 18 | RUN apt update \ 19 | && apt full-upgrade -y \ 20 | && apt install -y wget libssl3 libsqlite3-0 ca-certificates \ 21 | && rm -rf /var/lib/apt/lists/* 22 | 23 | COPY --from=builder /app/target/release/mollysocket /usr/local/bin/ 24 | HEALTHCHECK --interval=1m --timeout=3s \ 25 | CMD wget -q --tries=1 "http://$MOLLY_HOST:$MOLLY_PORT/discover" -O - | grep '"mollysocket":{"version":' 26 | ENTRYPOINT ["/usr/local/bin/mollysocket"] 27 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | This file shows how to install and configure mollysocket **on your system using a systemd service**. 4 | 5 | **This should be relevant if you use docker** 6 | 7 | ## Install the binary with a dedicated user 8 | 9 | First of all, you need to install mollysocket on your system. 10 | 11 | #### Create a dedicated account 12 | 13 | The service will run with a dedicated account, so create it and switch to that user: 14 | 15 | ```console 16 | # useradd mollysocket -M 17 | ``` 18 | 19 | #### Install the binary 20 | 21 | You have 2 solutions to install the binary. 22 | 23 | 1. Use an already compiled binary: . Download it to `/usr/local/bin/` and link the executable: `ln -s /usr/local/bin/{REPLACE_WITH_DOWNLOADED_MS} /usr/local/bin/ms` 24 | 25 | 2. Use cargo. This method allows you to use cargo to maintain mollysocket up to date. First of all, you need to [install cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) (you need at least version 1.59). Then, install mollysocket using cargo: `cargo install mollysocket`. *You probably need to install some system packages, like libssl-dev libsqlite3-dev*. Then copy the compile binary to your system: `cp ~/.cargo/bin/mollysocket /usr/local/bin/ms`. 26 | 27 | ## Install systemd services 28 | 29 | Download the 2 systemd unit files [mollysocket.service](https://github.com/mollyim/mollysocket/raw/main/mollysocket.service) and [mollysocket-vapid.service](https://github.com/mollyim/mollysocket/raw/main/mollysocket-vapid.service) and place them in the right direction `/etc/systemd/system/`. 30 | 31 | ### Start the service 32 | 33 | You should be able to see that service now `systemctl status mollysocket`. 34 | 35 | You can enable it `systemctl enable --now mollysocket`, the service is now active (`systemctl status mollysocket`), and will be started on system boot. 36 | 37 | ## App configuration 38 | 39 | *If you host your own Push server*, then explicitly add it to the allowed endpoints. In `/etc/mollysocket/conf.toml`, edit `allowed_endpoints = ['*', 'https://push.mydomain.tld']` (remove `'*'` if you will use your push server only). Then restart the service `systemctl restart mollysocket`. 40 | 41 | 42 | ## (Option A) Proxy server 43 | 44 | You will need to proxy everything from `/` to `http://127.0.0.1:8020/` (8020 is the value define in the systemd unit file for `$ROCKET_PORT`, it can be changed if needed). 45 | 46 | You also need to forward the `Host` header. 47 | 48 | If you proxy from another path like `/molly/` instead of `/`, you also need to pass the original URL. 49 | 50 | For Nginx, it looks like: 51 | 52 | ``` 53 | location / { 54 | proxy_pass http://127.0.0.1:8020/; 55 | proxy_set_header Host $host; 56 | proxy_set_header X-Original-URL $uri; 57 | } 58 | ``` 59 | 60 | ## (Option B) Air gapped mode 61 | 62 | To find the MollySocket QR code: 63 | 64 | - If you can use port-forwarding through SSH to your server, then run the following command: `ssh -L 8020:localhost:8020 your_server`, then open http://localhost:8020 on your machine. You can ignore alerts if there are any. Then click on _airgapped mode_. 65 | 66 | - If you can't use port-forwarding, change `webserver` to `false` in your config file (_/opt/mollysocket/prod.toml_) and restart your service: 67 | 68 | ```console 69 | # systemctl restart mollysocket 70 | # journalctl -u mollysocket 71 | # # This should show a QR code 72 | ``` 73 | 74 | After scanning the QR code, you will have a command to copy to run on your server. You must run this command as user `mollysocket` with `MOLLY_CONF=/opt/mollysocket/prod.toml`. 75 | 76 | For instance `sudo -su mollysocket MOLLY_CONF=/opt/mollysocket/prod.toml /opt/mollysocket/ms connection add baab32b9-d60b-4c39-9e14-15d8f6e1527e 2 thisisrandom 'https://push.mydomain.tld/upthisisrandom?up'`. 77 | 78 | ## (Optional) More restrictive configuration 79 | 80 | Once you have registered Molly (with option A or B), and you will be the only user using this service, you can restrict `allowed_uuids = ['baab32b9-d60b-4c39-9e14-15d8f6e1527e']` and `allowed_endpoints = ['https://push.mydomain.tld/upthisisrandom?up']` in the config file. 81 | 82 | ## Backup the VAPID privkey 83 | 84 | If you wish to backup your VAPID privkey, you can run the following: 85 | 86 | ```console 87 | # systemd-creds decrypt /etc/mollysocket/vapid.key 88 | ``` 89 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | Copyright (C) 2022 Simon Gougeon 633 | 634 | This program is free software: you can redistribute it and/or modify 635 | it under the terms of the GNU Affero General Public License as published 636 | by the Free Software Foundation, either version 3 of the License, or 637 | (at your option) any later version. 638 | 639 | This program is distributed in the hope that it will be useful, 640 | but WITHOUT ANY WARRANTY; without even the implied warranty of 641 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 642 | GNU Affero General Public License for more details. 643 | 644 | You should have received a copy of the GNU Affero General Public License 645 | along with this program. If not, see . 646 | 647 | Also add information on how to contact you by electronic and paper mail. 648 | 649 | If your software can interact with users remotely through a computer 650 | network, you should also make sure that it provides a way for users to 651 | get its source. For example, if your program is a web application, its 652 | interface could display a "Source" link that leads users to an archive 653 | of the code. There are many ways you could offer source, and different 654 | solutions will be better for different programs; see section 13 for the 655 | specific requirements. 656 | 657 | You should also get your employer (if you work as a programmer) or school, 658 | if any, to sign a "copyright disclaimer" for the program, if necessary. 659 | For more information on this, and how to apply and follow the GNU AGPL, see 660 | . 661 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MollySocket 2 | 3 | MollySocket allows getting signal notifications via [UnifiedPush](https://unifiedpush.org/). It works like a linked device, which doesn't have an encryption key, connected to the Signal server. Everytime it receives an encrypted event, it notifies your mobile via UnifiedPush. 4 | 5 | ## Overview 6 | 7 | ```mermaid 8 | --- 9 | title: Message flow 10 | --- 11 | graph TD 12 | 13 | MS[fa:fa-tablets MollySocket] 14 | S[fa:fa-comment Signal Server] 15 | P[fa:fa-server Push server] 16 | subgraph "fa:fa-mobile Android" 17 | D[fa:fa-tower-broadcast Distributor App] 18 | MA[fa:fa-tablets Molly Android] 19 | end 20 | MS -- #8203;1. Persistent connection --> S 21 | MS -- #8203;2. 'Notifications present' --> P 22 | P -- #8203;3. 'Notifications present for Molly' --> D 23 | D -- #8203;4. 'Check Signal servers' --> MA 24 | MA -- #8203;5. 'Got messages?' --> S 25 | S -- #8203;6. Messages --> MA 26 | ``` 27 | 28 | ## Setup 29 | 30 | 1. You can install MollySocket via: 31 | 1. Docker/Podman: `docker pull ghcr.io/mollyim/mollysocket:latest` 32 | 2. Crates.io: `cargo install mollysocket` (see [INSTALL.md](INSTALL.md) for the setup) 33 | 3. Direct download: (see [INSTALL.md](INSTALL.md) for the setup) 34 | 2. A [distributor app](https://unifiedpush.org/users/distributors/) (easiest is [ntfy](https://f-droid.org/en/packages/io.heckel.ntfy/)) 35 | 3. Go to the Settings > Notifications, change the delivery method to _UnifiedPush_ and scan the QR code shown on your MollySocket homepage 36 | 37 | You can optionally install your own push server like ntfy or NextPush. 38 | For beginners, you can use a free service like ntfy.sh (do consider donating if you have the means). 39 | 40 | ## Web Server 41 | 42 | MollySocket exposes a web server so that Molly can send the information it needs to operate. You must configure TLS with a reverse proxy in front of MollySocket. Molly can only connect to the server over HTTPS. 43 | 44 | It is possible to use MollySocket without the web server, but you will have to manually register the information MollySocket needs: see the **Air Gapped** mode on Android settings. 45 | 46 | ## Configuration 47 | 48 | The configuration file uses the [TOML format](https://toml.io/). Below is an overview of configuration options. You can configure each parameter using either the conf file, the environment variable or the cli option (if available). 49 | 50 | | Parameter (conf. file) | Environment variable | Cli Option | Description | Default | Examples | 51 | |------------------------|----------------------------|-------------|---------------------------------------------------|----------------------|---------------------------------------------------------| 52 | | | RUST_LOG \* | -v/-vv/-vvv | Verbosity | error | RUST_LOG=info, RUST_LOG=debug | 53 | | | MOLLY_CONF | -c \* | Path to the configuration file, optional | | /etc/mollysocket.conf | 54 | | host | MOLLY_HOST \* | | Listening address of the web server | 127.0.0.1 | 0.0.0.0 | 55 | | port | MOLLY_PORT \* | | Listening port of the web server | 8020 | 8080 | 56 | | webserver | MOLLY_WEBSERVER \* | | Wether to start the web server | true | false | 57 | | allowed_endpoints | MOLLY_ALLOWED_ENDPOINTS \* | | List of UnifiedPush servers | `["*"]` | `["*"]`,`["https://yourdomain.tld","https://ntfy.sh"]` | 58 | | allowed_uuids | MOLLY_ALLOWED_UUIDS \* | | UUIDs of signal accounts that may use this server | `["*"]` | `["*"]`, `["abcdef-12345-tuxyz-67890"]` | 59 | | db | MOLLY_DB \* | | Path to the DB | `db.sqlite` | `"/data/ms.sqlite"` | 60 | | vapid_privkey | MOLLY_VAPID_PRIVKEY \* | | VAPID key, see [VAPID key](#vapid-key) | None | "DSqYuWchrB6yIMYJtidvqANeRQic4uWy34afzZRsZnI" | 61 | | vapid_key_file | MOLLY_VAPID_KEY_FILE \* | | File with VAPID key, see [VAPID key](#vapid-key) | None | "/etc/ms_vapid_key" | 62 | 63 | \* Takes the precedence 64 | 65 | ### VAPID key 66 | 67 | VAPID key is used to authorize mollysocket server to send requests to your push server, if it supports it. 68 | 69 | To generate a new key, you can run this command `mollysocket vapid gen`. Or using docker, `docker compose run mollysocket vapid gen`. 70 | 71 | This value can be passed to mollysocket via a file, location given with `vapid_key_file` parameter, or directly in the `vapid_privkey` parameter. _The key file takes the precedence_. 72 | 73 | #### With docker-compose 74 | 75 | The easiest way to pass the VAPID key when using docker compose is to pass it with the `MOLLY_VAPID_PRIVKEY` environment variable. See [docker-compose.yml](docker-compose.yml). 76 | 77 | #### With a systemd service 78 | 79 | If you use a [systemd service](mollysocket.service) for MollySocket, installation steps are listed in <./INSTALL.md> 80 | 81 | Alternatively, you can store the VAPID key in cleartext in the systemd unit file: 82 | 83 | ```ini 84 | [Service] 85 | Environment=MOLLY_VAPID_PRIVKEY=DSqYuWchrB6yIMYJtidvqANeRQic4uWy34afzZRsZnI 86 | ``` 87 | 88 | ### `allowed_endpoints` 89 | 90 | These are the UnifiedPush endpoints that MollySocket may use to push notifications with. 91 | 92 | ⚠️ **If you self-host your push server, add your push server to the `allowed_endpoints`.** ⚠️ 93 | 94 | That's because, for security reasons, endpoints on your local network must be allowed explicitly. You just have to set the scheme (https), the domain and the port if required. For instance `allowed_endpoints=['https://push.mydomain.tld']` 95 | 96 | ### `allowed_uuids` 97 | 98 | You can allow registration for all accounts by setting `allowed_uuids` to `['*']`. Else set your account ids in the array: `['account_id1','account_id2']`. 99 | 100 | The account IDs are showing in the Molly application under Settings > Notifications > UnifiedPush. 101 | You need to activate UnifiedPush first before your account ID is shown. 102 | 103 | ## Troubleshoot 104 | 105 | * **Where is the MollySocket QR code?** 106 | 107 | First of all, setting up VAPID is a requirement to get this QR code, if you haven't please refer to section above. 108 | 109 | MollySocket is primarily designed to be run behind a reverse proxy. If this is the case, open your MollySocket URL in your browser and scan the QR code, or take a screenshot. 110 | 111 | If you don't use MollySocket behind a reverse proxy, you wish to use it in air-gapped mode, then: 112 | - If you can use port-forwarding through SSH to your server, then run the following command: `ssh -L 8020:localhost:8020 your_server`, then open http://localhost:8020 on your machine. You can ignore alerts if there are any. Then click on _airgapped mode_. 113 | 114 | - If you can't use port-forwarding, change `webserver` to `false` in your config file, or via the environment variable `MOLLY_WEBSERVER=false` and restart your service: 115 | 116 | ```console 117 | # systemctl restart mollysocket 118 | # journalctl -u mollysocket 119 | # # This should show a QR code 120 | ``` 121 | 122 | Scanning a QR code displayed on a dark theme currently doesn't work, so turn on your light theme before scanning. 123 | 124 | * **How to backup VAPID key?** 125 | 126 | MollySocket is designed for self-hoster, and the idea is to renew the VAPID key if you have to reinstall MollySocket somewhere else. If you are asking for this, you are probably trying to use systemd-creds, else you'd have the VAPID private key in plain text. 127 | 128 | If you haven't generated the VAPID key yet, just pipe the command to a temporary file: `mollysocket vapid gen | tee key.tmp | systemd-creds encrypt --name=ms_vapid -p - -`, key.tmp will contain the key, you can store it in a safe and remove the file. 129 | 130 | If you have already generated the key, and want to back up this key, you can retrieve it this way: First, copy the content of `SetCredentialEncrypted` to a file `ms_vapid`. Then use systemd-creds to decrypt it. You can then store it in a safe. 131 | 132 | ```console 133 | # cat cipher.cred 134 | k6iUCUh0RJCQyvL8k8q1UyAAAAABAAAADAAAABAAAAC1lFmbWAqWZ8dCCQkAAAAAgAAAA 135 | AAAAAALACMA0AAAACAAAAAAfgAg9uNpGmj8LL2nHE0ixcycvM3XkpOCaf+9rwGscwmqRJ 136 | cAEO24kB08FMtd/hfkZBX8PqoHd/yPTzRxJQBoBsvo9VqolKdy9Wkvih0HQnQ6NkTKEdP 137 | HQ08+x8sv5sr+Mkv4ubp3YT1Jvv7CIPCbNhFtag1n5y9J7bTOKt2SQwBOAAgACwAAABIA 138 | ID8H3RbsT7rIBH02CIgm/Gv1ukSXO3DMHmVQkDG0wEciABAAII6LvrmL60uEZcp5qnEkx 139 | SuhUjsDoXrJs0rfSWX4QAx5PwfdFuxPusgE== 140 | # systemd-creds decrypt ms_vapid 141 | DSqYuWchrB6yIMYJtidvqANeRQic4uWy34afzZRsZnI 142 | ``` 143 | 144 | * **On MollySocket webpage, I see a alert saying the origin or the Pathname isn't correct** 145 | 146 | You are using MollySocket behind a reverse proxy and the URL received by MollySocket doesn't match the one you are using in your web browser. 147 | 148 | You need to pass the original Host and the original URL to MollySocket with the `Host` and the `X-Original-URL` header. For instance, the Nginx config looks like this: 149 | 150 | ```nginx 151 | # change to /molly/ if you don't expose it on the root of your domain 152 | location / { 153 | proxy_pass http://127.0.0.1:8020/; 154 | proxy_set_header Host $host; 155 | proxy_set_header X-Original-URL $uri; 156 | } 157 | 158 | ``` 159 | 160 | * **On the Android app, the status states _Invalid response from server_** 161 | 162 | The MollySocket server can't be reached on that URL or doesn't respond correctly. Does opening the URL in your mobile browser works ? You should see a QR code. Else, try to reconfigure MollySocket, by clicking on "MollySocket server" in Molly settings. 163 | 164 | * **On the Android app, the status states _The account ID is refused by the server_** 165 | 166 | You have restricted the allowed account ID who can use your MollySocket server. 167 | 168 | Add your account ID[1] to _allowed_uuids_ to allow your account, or add a wildcard `["*"]` to allow all the accounts to use your server. See [Configuration](#configuration) to configure your server correctly. 169 | 170 | [1] Your account ID can be copied on the Android app, under the UnifiedPush settings 171 | 172 | * **On the Android app, the status states _The endpoint is forbidden by the server_** 173 | 174 | You have restricted the allowed UnifiedPush endpoints, or you are using a self-hosted server you haven't whitelisted. 175 | 176 | Add your server to the _allowed_endpoints_: `["https://push.mydomain.tld"]`. _This is NOT your MollySocket URL_ but the one from your push provider. See [Configuration](#configuration) to configure your server correctly. 177 | 178 | * **On the Android app, the status is _Waiting for confirmation from the MollySocket server_** 179 | 180 | It means you are using MollySocket in air-gapped mode and you don't have receive a test notification from the server. 181 | 182 | There might be 3 reasons for that: 183 | - You don't have yet registered your connection on a MollySocket server. 184 | - It is better to use MollySocket configured with a web interface, see [Web Server](#web-server) for more information. 185 | - If you can't have a web interface, you can use it in air gapped mode. The MollySocket server should be constantly running. You can use the docker-compose or follow the [Install doc](/Install.md). 186 | - Then, if you stick with air gapped mode, you will need to add your account to the MollySocket registration. You can copy the parameter on the Android settings view. Then run: 187 | 188 | ```console 189 | $ # If you use docker-compose: 190 | $ docker compose run mollysocket 191 | $ # Else, if you use the binary: 192 | $ mollysocket 193 | ``` 194 | 195 | - It is possible you don't use a recent enough version of MollySocket and it hasn't send a request during the registration. You can run : 196 | ```console 197 | $ # Replace the UUID with your account Id 198 | $ # If you use docker-compose: 199 | $ docker compose run mollysocket connection ping c8d44128-5c99-4810-a7d3-71c079891c27 200 | $ # Else, if you use the binary: 201 | $ mollysocket connection ping c8d44128-5c99-4810-a7d3-71c079891c27 202 | ``` 203 | - You have a problem with your UnifiedPush setup. You can get further troubleshooting information on this page: . 204 | 205 | * **I use the Air-gapped mode and I don't receive notifications**. 206 | 207 | If you use air-gapped mode, then Molly (android) can't test the setup and it assumes you have correctly setup everything. You should double check that the account ID is accepted by your mollysocket server and the endpoint is allowed by your mollysocket server (check the output logs). 208 | 209 | * **The status is _OK_ but I still don't get notifications** 210 | 211 | **If you are using MollySocket with a webserver,** go to Molly Settings > Notifications > UnifiedPush and click "Test configuration". If it doesn't work, you should try to reconfigure MollySocket, by clicking on "MollySocket server" in Molly settings. 212 | 213 | **If you are using in air-gapped mode,** run this command: 214 | 215 | ```console 216 | $ # Replace the UUID with your account Id 217 | $ # If you use docker-compose: 218 | $ docker compose run mollysocket mollysocket connection ping c8d44128-5c99-4810-a7d3-71c079891c27 219 | $ # Else, if you use the binary: 220 | $ mollysocket connection ping c8d44128-5c99-4810-a7d3-71c079891c27 221 | ``` 222 | 223 | If you receive a test notification (image bellow), then you should check that Molly and your [distributor](https://unifiedpush.org/users/distributors/) have unrestricted battery usage. You should check if you have additional configuration for your device regarding battery management: . 224 | 225 | 226 | 227 | If you don't receive a test notification, then your MollySocket server can't reach your push server or your phone don't have network access. 228 | 229 | You can get further troubleshooting information on this page: . 230 | 231 | ## About security 232 | 233 | **Relative to Signal security** 234 | 235 | **MollySocket never has any encryption key** 236 | 237 | MollySocket receives the credentials for a linked device and does not receive any encryption key. Which means: 238 | * Someone with access to MollySocket database can't change the identity key, to impersonate users. See [setKeys](https://github.com/signalapp/Signal-Server/blob/v8.67.0/service/src/main/java/org/whispersystems/textsecuregcm/controllers/KeysController.java#L111). 239 | * Someone with access to MollySocket database may be able to use the credentials of linked devices to spam the Signal server and hit the rate limits. I haven't checked if this would temporarily block the account or just the linked device. (Availability risk) 240 | * Someone with access to MollySocket database may be able to change some account field in a destructive way. For instance changing the account Name to something random. The cleartext will be random since these field are encrypted and require encryption keys to be properly encrypted. 241 | 242 | ## License 243 | AGPLv3: see [LICENSE.txt](./LICENSE.txt). 244 | 245 | ## Disclaimer 246 | This project is NOT sponsored by or affiliated to Signal Messenger or Signal Foundation. 247 | 248 | The software is produced independently of Signal and carries no guarantee about quality, security or anything else. Use at your own risk. 249 | 250 | -------------------------------------------------------------------------------- /config-sample.toml: -------------------------------------------------------------------------------- 1 | db = '/opt/mollysocket/mollysocket.db' 2 | allowed_endpoints = ['*'] 3 | allowed_uuids = ['*'] 4 | webserver = true 5 | port = 8020 6 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | mollysocket: 3 | image: ghcr.io/mollyim/mollysocket:1 4 | container_name: mollysocket 5 | restart: always 6 | volumes: 7 | - ./data:/data 8 | working_dir: /data 9 | command: server 10 | environment: 11 | - MOLLY_DB="/data/mollysocket.db" 12 | # Do not add space in the array ["http://a.tld","*"] 13 | - MOLLY_ALLOWED_ENDPOINTS=["*"] 14 | - MOLLY_ALLOWED_UUIDS=["*"] 15 | # TODO: 16 | #- MOLLY_VAPID_PRIVKEY="paste output of `docker compose exec mollysocket mollysocket vapid gen` here" 17 | - MOLLY_HOST=0.0.0.0 18 | - MOLLY_PORT=8020 19 | - RUST_LOG=info 20 | ports: 21 | - "8020:8020" 22 | -------------------------------------------------------------------------------- /kubernetes/README.md: -------------------------------------------------------------------------------- 1 | Proper manifest files for a deployment using Kubernetes. Obviously feel free to adjust to your needs. In this example, Traefik is used but feel free to use whatever ingress method (Nginx, HA Proxy, etc.) you would like. Also, you can create the Kubernetes secret via the CLI. 2 | 3 | 1. After deployed, enter the Kubernetes pod via a command such as "kubectl exec -it mollysocket-5c767fb96d-8gfzz -n default -- /bin/sh" 4 | 5 | 2. Generate the VAPID key in the pod by running the command "mollysocket vapid gen" 6 | 7 | 3. Copy the VAPID key from the prior command and paste into the secret.yaml file, under the ENV variable/key of "vapid_privkey". 8 | 9 | Restart the Mollysocket pod, and you should be good to go! 10 | 11 | -------------------------------------------------------------------------------- /kubernetes/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: mollysocket 5 | namespace: default 6 | spec: 7 | replicas: 1 8 | selector: 9 | matchLabels: 10 | app: mollysocket 11 | template: 12 | metadata: 13 | labels: 14 | app: mollysocket 15 | spec: 16 | containers: 17 | - name: mollysocket 18 | image: ghcr.io/mollyim/mollysocket:1 19 | args: ["server"] 20 | workingDir: /data 21 | ports: 22 | - containerPort: 8020 23 | env: 24 | - name: MOLLY_ALLOWED_ENDPOINTS 25 | valueFrom: 26 | secretKeyRef: 27 | name: mollysocket-config 28 | key: allowed_endpoints 29 | - name: MOLLY_VAPID_PRIVKEY 30 | valueFrom: 31 | secretKeyRef: 32 | name: mollysocket-config 33 | key: vapid_privkey 34 | - name: MOLLY_DB 35 | value: "/data/mollysocket.db" 36 | - name: MOLLY_ALLOWED_UUIDS 37 | value: '["*"]' 38 | - name: MOLLY_HOST 39 | value: "0.0.0.0" 40 | - name: MOLLY_PORT 41 | value: "8020" 42 | - name: RUST_LOG 43 | value: "info" 44 | volumeMounts: 45 | - name: data 46 | mountPath: /data 47 | volumes: 48 | - name: data 49 | persistentVolumeClaim: 50 | claimName: mollysocket-pvc 51 | -------------------------------------------------------------------------------- /kubernetes/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: traefik.io/v1alpha1 2 | kind: IngressRoute 3 | metadata: 4 | name: mollysocket 5 | namespace: default 6 | annotations: 7 | kubernetes.io/ingress.class: traefik-external 8 | spec: 9 | entryPoints: 10 | - websecure 11 | routes: 12 | - match: Host(`mollysocket.domain.tld`) 13 | kind: Rule 14 | services: 15 | - name: mollysocket 16 | port: 8020 17 | tls: 18 | secretName: domain-tld-tls 19 | 20 | 21 | -------------------------------------------------------------------------------- /kubernetes/pvc.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolumeClaim 3 | metadata: 4 | name: mollysocket-pvc 5 | namespace: default 6 | spec: 7 | accessModes: 8 | - ReadWriteOnce 9 | storageClassName: placeholder 10 | resources: 11 | requests: 12 | storage: 1Gi 13 | -------------------------------------------------------------------------------- /kubernetes/secret.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: mollysocket-config 5 | namespace: default 6 | type: Opaque 7 | stringData: 8 | allowed_endpoints: '["*"]' # If self-hosting, use domain of custom provider such as '["https://ntfy.domain.tld"]' 9 | vapid_privkey: "placeholder" 10 | -------------------------------------------------------------------------------- /kubernetes/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: mollysocket 5 | namespace: default 6 | spec: 7 | type: ClusterIP 8 | selector: 9 | app: mollysocket 10 | ports: 11 | - protocol: TCP 12 | port: 8020 13 | targetPort: 8020 14 | -------------------------------------------------------------------------------- /mollysocket-vapid.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Generate MollySocket VAPID key 3 | 4 | [Service] 5 | Type=oneshot 6 | ExecStart=sh -c '( [ -f $CONFIGURATION_DIRECTORY/conf.toml ] || echo "db = \'$STATE_DIRECTORY/ms.db\'" > $CONFIGURATION_DIRECTORY/conf.toml ); ( [ -f $CONFIGURATION_DIRECTORY/vapid.key ] || ( ms vapid gen | systemd-creds encrypt - $CONFIGURATION_DIRECTORY/vapid.key ) )' 7 | RemainAfterExit=true 8 | 9 | ConfigurationDirectory=mollysocket 10 | StateDirectory=mollysocket 11 | ProtectHome=true 12 | ProtectSystem=true 13 | 14 | 15 | -------------------------------------------------------------------------------- /mollysocket.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=MollySocket 3 | After=network-online.target mollysocket-vapid.service 4 | Wants=mollysocket-vapid.service 5 | 6 | [Service] 7 | Type=simple 8 | Environment="RUST_LOG=info" 9 | Environment="MOLLY_CONF=/etc/mollysocket/conf.toml" 10 | 11 | # /etc/mollysocket/vapid.key is generated by mollysocket-vapid.service, 12 | # you can also store the key in plaintext: 13 | # by replacing the 2 following lines with 14 | # Environment=MOLLY_VAPID_PRIVKEY=[...] output of `mollysocket vapid gen` 15 | 16 | LoadCredentialEncrypted=vapid.key:/etc/mollysocket/vapid.key 17 | Environment=MOLLY_VAPID_KEY_FILE=%d/vapid.key 18 | 19 | User=mollysocket 20 | Group=mollysocket 21 | ConfigurationDirectory=mollysocket::ro 22 | StateDirectory=mollysocket 23 | UMask=0007 24 | ProtectHome=true 25 | ProtectSystem=true 26 | 27 | ExecStart=ms server 28 | KillSignal=SIGINT 29 | 30 | Restart=on-failure 31 | 32 | # Configures the time to wait before service is stopped forcefully. 33 | TimeoutStopSec=5 34 | 35 | [Install] 36 | WantedBy=multi-user.target 37 | -------------------------------------------------------------------------------- /proto/SignalService.proto: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2014-2016 Open Whisper Systems 3 | * 4 | * Licensed according to the LICENSE file in this repository. 5 | */ 6 | syntax = "proto2"; 7 | 8 | package proto.signalservice; 9 | 10 | option java_package = "org.whispersystems.signalservice.internal.push"; 11 | option java_outer_classname = "SignalServiceProtos"; 12 | 13 | message Envelope { 14 | enum Type { 15 | UNKNOWN = 0; 16 | CIPHERTEXT = 1; 17 | KEY_EXCHANGE = 2; 18 | PREKEY_BUNDLE = 3; 19 | RECEIPT = 5; 20 | UNIDENTIFIED_SENDER = 6; 21 | reserved 7; // SENDERKEY_MESSAGE 22 | PLAINTEXT_CONTENT = 8; 23 | } 24 | 25 | optional Type type = 1; 26 | reserved /*sourceE164*/ 2; 27 | optional string sourceServiceId = 11; 28 | optional uint32 sourceDevice = 7; 29 | optional string destinationServiceId = 13; 30 | reserved /*relay*/ 3; 31 | optional uint64 timestamp = 5; 32 | reserved /*legacyMessage*/ 6; 33 | optional bytes content = 8; // Contains an encrypted Content 34 | optional string serverGuid = 9; 35 | optional uint64 serverTimestamp = 10; 36 | optional bool urgent = 14 [default = true]; 37 | optional string updatedPni = 15; // MOLLY: Used by linked device if primary device changes phone number 38 | optional bool story = 16; 39 | optional bytes reportingToken = 17; 40 | // NEXT ID: 18 41 | } 42 | 43 | message Content { 44 | optional DataMessage dataMessage = 1; 45 | optional SyncMessage syncMessage = 2; 46 | optional CallMessage callMessage = 3; 47 | optional NullMessage nullMessage = 4; 48 | optional ReceiptMessage receiptMessage = 5; 49 | optional TypingMessage typingMessage = 6; 50 | optional bytes senderKeyDistributionMessage = 7; 51 | optional bytes decryptionErrorMessage = 8; 52 | optional StoryMessage storyMessage = 9; 53 | optional PniSignatureMessage pniSignatureMessage = 10; 54 | optional EditMessage editMessage = 11; 55 | } 56 | 57 | message CallMessage { 58 | message Offer { 59 | enum Type { 60 | OFFER_AUDIO_CALL = 0; 61 | OFFER_VIDEO_CALL = 1; 62 | reserved /* OFFER_NEED_PERMISSION */ 2; // removed 63 | } 64 | 65 | optional uint64 id = 1; 66 | // Legacy/deprecated; replaced by 'opaque' 67 | optional string sdp = 2; 68 | optional Type type = 3; 69 | optional bytes opaque = 4; 70 | } 71 | 72 | message Answer { 73 | optional uint64 id = 1; 74 | // Legacy/deprecated; replaced by 'opaque' 75 | optional string sdp = 2; 76 | optional bytes opaque = 3; 77 | } 78 | 79 | message IceUpdate { 80 | optional uint64 id = 1; 81 | // Legacy/deprecated; remove when old clients are gone. 82 | optional string mid = 2; 83 | // Legacy/deprecated; remove when old clients are gone. 84 | optional uint32 line = 3; 85 | // Legacy/deprecated; replaced by 'opaque' 86 | optional string sdp = 4; 87 | optional bytes opaque = 5; 88 | } 89 | 90 | message Busy { 91 | optional uint64 id = 1; 92 | } 93 | 94 | message Hangup { 95 | enum Type { 96 | HANGUP_NORMAL = 0; 97 | HANGUP_ACCEPTED = 1; 98 | HANGUP_DECLINED = 2; 99 | HANGUP_BUSY = 3; 100 | HANGUP_NEED_PERMISSION = 4; 101 | } 102 | 103 | optional uint64 id = 1; 104 | optional Type type = 2; 105 | optional uint32 deviceId = 3; 106 | } 107 | 108 | message Opaque { 109 | enum Urgency { 110 | DROPPABLE = 0; 111 | HANDLE_IMMEDIATELY = 1; 112 | } 113 | 114 | optional bytes data = 1; 115 | optional Urgency urgency = 2; 116 | } 117 | 118 | optional Offer offer = 1; 119 | optional Answer answer = 2; 120 | repeated IceUpdate iceUpdate = 3; 121 | optional Hangup legacyHangup = 4; 122 | optional Busy busy = 5; 123 | reserved /* profileKey */ 6; 124 | optional Hangup hangup = 7; 125 | reserved /* multiRing */ 8; 126 | optional uint32 destinationDeviceId = 9; 127 | optional Opaque opaque = 10; 128 | } 129 | 130 | message BodyRange { 131 | enum Style { 132 | NONE = 0; 133 | BOLD = 1; 134 | ITALIC = 2; 135 | SPOILER = 3; 136 | STRIKETHROUGH = 4; 137 | MONOSPACE = 5; 138 | } 139 | 140 | optional uint32 start = 1; 141 | optional uint32 length = 2; 142 | 143 | oneof associatedValue { 144 | string mentionAci = 3; 145 | Style style = 4; 146 | } 147 | } 148 | 149 | message DataMessage { 150 | enum Flags { 151 | END_SESSION = 1; 152 | EXPIRATION_TIMER_UPDATE = 2; 153 | PROFILE_KEY_UPDATE = 4; 154 | } 155 | 156 | message Quote { 157 | enum Type { 158 | NORMAL = 0; 159 | GIFT_BADGE = 1; 160 | } 161 | 162 | message QuotedAttachment { 163 | optional string contentType = 1; 164 | optional string fileName = 2; 165 | optional AttachmentPointer thumbnail = 3; 166 | } 167 | 168 | optional uint64 id = 1; 169 | reserved /*authorE164*/ 2; 170 | optional string authorAci = 5; 171 | optional string text = 3; 172 | repeated QuotedAttachment attachments = 4; 173 | repeated BodyRange bodyRanges = 6; 174 | optional Type type = 7; 175 | } 176 | 177 | message Contact { 178 | message Name { 179 | optional string givenName = 1; 180 | optional string familyName = 2; 181 | optional string prefix = 3; 182 | optional string suffix = 4; 183 | optional string middleName = 5; 184 | optional string displayName = 6; 185 | } 186 | 187 | message Phone { 188 | enum Type { 189 | HOME = 1; 190 | MOBILE = 2; 191 | WORK = 3; 192 | CUSTOM = 4; 193 | } 194 | 195 | optional string value = 1; 196 | optional Type type = 2; 197 | optional string label = 3; 198 | } 199 | 200 | message Email { 201 | enum Type { 202 | HOME = 1; 203 | MOBILE = 2; 204 | WORK = 3; 205 | CUSTOM = 4; 206 | } 207 | 208 | optional string value = 1; 209 | optional Type type = 2; 210 | optional string label = 3; 211 | } 212 | 213 | message PostalAddress { 214 | enum Type { 215 | HOME = 1; 216 | WORK = 2; 217 | CUSTOM = 3; 218 | } 219 | 220 | optional Type type = 1; 221 | optional string label = 2; 222 | optional string street = 3; 223 | optional string pobox = 4; 224 | optional string neighborhood = 5; 225 | optional string city = 6; 226 | optional string region = 7; 227 | optional string postcode = 8; 228 | optional string country = 9; 229 | } 230 | 231 | message Avatar { 232 | optional AttachmentPointer avatar = 1; 233 | optional bool isProfile = 2; 234 | } 235 | 236 | optional Name name = 1; 237 | repeated Phone number = 3; 238 | repeated Email email = 4; 239 | repeated PostalAddress address = 5; 240 | optional Avatar avatar = 6; 241 | optional string organization = 7; 242 | } 243 | 244 | message Sticker { 245 | optional bytes packId = 1; 246 | optional bytes packKey = 2; 247 | optional uint32 stickerId = 3; 248 | optional AttachmentPointer data = 4; 249 | optional string emoji = 5; 250 | } 251 | 252 | message Reaction { 253 | optional string emoji = 1; 254 | optional bool remove = 2; 255 | reserved /*targetAuthorE164*/ 3; 256 | optional string targetAuthorAci = 4; 257 | optional uint64 targetSentTimestamp = 5; 258 | } 259 | 260 | message Delete { 261 | optional uint64 targetSentTimestamp = 1; 262 | } 263 | 264 | message GroupCallUpdate { 265 | optional string eraId = 1; 266 | } 267 | 268 | message StoryContext { 269 | optional string authorAci = 1; 270 | optional uint64 sentTimestamp = 2; 271 | } 272 | 273 | message Payment { 274 | message Amount { 275 | message MobileCoin { 276 | optional uint64 picoMob = 1; 277 | } 278 | 279 | oneof Amount { 280 | MobileCoin mobileCoin = 1; 281 | } 282 | } 283 | 284 | message Notification { 285 | message MobileCoin { 286 | optional bytes receipt = 1; 287 | } 288 | 289 | oneof Transaction { 290 | MobileCoin mobileCoin = 1; 291 | } 292 | 293 | optional string note = 2; 294 | reserved /*requestId*/ 1003; 295 | } 296 | 297 | message Activation { 298 | enum Type { 299 | REQUEST = 0; 300 | ACTIVATED = 1; 301 | } 302 | 303 | optional Type type = 1; 304 | } 305 | 306 | oneof Item { 307 | Notification notification = 1; 308 | Activation activation = 2; 309 | } 310 | 311 | reserved /*request*/ 1002; 312 | reserved /*cancellation*/ 1003; 313 | } 314 | 315 | message GiftBadge { 316 | optional bytes receiptCredentialPresentation = 1; 317 | } 318 | 319 | enum ProtocolVersion { 320 | option allow_alias = true; 321 | 322 | INITIAL = 0; 323 | MESSAGE_TIMERS = 1; 324 | VIEW_ONCE = 2; 325 | VIEW_ONCE_VIDEO = 3; 326 | REACTIONS = 4; 327 | CDN_SELECTOR_ATTACHMENTS = 5; 328 | MENTIONS = 6; 329 | PAYMENTS = 7; 330 | CURRENT = 7; 331 | } 332 | 333 | optional string body = 1; 334 | repeated AttachmentPointer attachments = 2; 335 | reserved /*groupV1*/ 3; 336 | optional GroupContextV2 groupV2 = 15; 337 | optional uint32 flags = 4; 338 | optional uint32 expireTimer = 5; 339 | optional bytes profileKey = 6; 340 | optional uint64 timestamp = 7; 341 | optional Quote quote = 8; 342 | repeated Contact contact = 9; 343 | repeated Preview preview = 10; 344 | optional Sticker sticker = 11; 345 | optional uint32 requiredProtocolVersion = 12; 346 | optional bool isViewOnce = 14; 347 | optional Reaction reaction = 16; 348 | optional Delete delete = 17; 349 | repeated BodyRange bodyRanges = 18; 350 | optional GroupCallUpdate groupCallUpdate = 19; 351 | optional Payment payment = 20; 352 | optional StoryContext storyContext = 21; 353 | optional GiftBadge giftBadge = 22; 354 | } 355 | 356 | message NullMessage { 357 | optional bytes padding = 1; 358 | } 359 | 360 | message ReceiptMessage { 361 | enum Type { 362 | DELIVERY = 0; 363 | READ = 1; 364 | VIEWED = 2; 365 | } 366 | 367 | optional Type type = 1; 368 | repeated uint64 timestamp = 2; 369 | } 370 | 371 | message TypingMessage { 372 | enum Action { 373 | STARTED = 0; 374 | STOPPED = 1; 375 | } 376 | 377 | optional uint64 timestamp = 1; 378 | optional Action action = 2; 379 | optional bytes groupId = 3; 380 | } 381 | 382 | message StoryMessage { 383 | optional bytes profileKey = 1; 384 | optional GroupContextV2 group = 2; 385 | oneof attachment { 386 | AttachmentPointer fileAttachment = 3; 387 | TextAttachment textAttachment = 4; 388 | } 389 | optional bool allowsReplies = 5; 390 | repeated BodyRange bodyRanges = 6; 391 | } 392 | 393 | message Preview { 394 | optional string url = 1; 395 | optional string title = 2; 396 | optional AttachmentPointer image = 3; 397 | optional string description = 4; 398 | optional uint64 date = 5; 399 | } 400 | 401 | message TextAttachment { 402 | enum Style { 403 | DEFAULT = 0; 404 | REGULAR = 1; 405 | BOLD = 2; 406 | SERIF = 3; 407 | SCRIPT = 4; 408 | CONDENSED = 5; 409 | } 410 | 411 | message Gradient { 412 | optional uint32 startColor = 1; // deprecated: this field will be removed in a future release. 413 | optional uint32 endColor = 2; // deprecated: this field will be removed in a future release. 414 | optional uint32 angle = 3; // degrees 415 | repeated uint32 colors = 4; 416 | repeated float positions = 5; // percent from 0 to 1 417 | } 418 | 419 | optional string text = 1; 420 | optional Style textStyle = 2; 421 | optional uint32 textForegroundColor = 3; // integer representation of hex color 422 | optional uint32 textBackgroundColor = 4; 423 | optional Preview preview = 5; 424 | oneof background { 425 | Gradient gradient = 6; 426 | uint32 color = 7; 427 | } 428 | } 429 | 430 | message Verified { 431 | enum State { 432 | DEFAULT = 0; 433 | VERIFIED = 1; 434 | UNVERIFIED = 2; 435 | } 436 | 437 | reserved /*destinationE164*/ 1; 438 | optional string destinationAci = 5; 439 | optional bytes identityKey = 2; 440 | optional State state = 3; 441 | optional bytes nullMessage = 4; 442 | } 443 | 444 | message SyncMessage { 445 | message Sent { 446 | message UnidentifiedDeliveryStatus { 447 | reserved /*destinationE164*/ 1; 448 | optional string destinationServiceId = 3; 449 | optional bool unidentified = 2; 450 | } 451 | 452 | message StoryMessageRecipient { 453 | optional string destinationServiceId = 1; 454 | repeated string distributionListIds = 2; 455 | optional bool isAllowedToReply = 3; 456 | } 457 | 458 | optional string destinationE164 = 1; 459 | optional string destinationServiceId = 7; 460 | optional uint64 timestamp = 2; 461 | optional DataMessage message = 3; 462 | optional uint64 expirationStartTimestamp = 4; 463 | repeated UnidentifiedDeliveryStatus unidentifiedStatus = 5; 464 | optional bool isRecipientUpdate = 6 [default = false]; 465 | optional StoryMessage storyMessage = 8; 466 | repeated StoryMessageRecipient storyMessageRecipients = 9; 467 | optional EditMessage editMessage = 10; 468 | } 469 | 470 | message Contacts { 471 | optional AttachmentPointer blob = 1; 472 | optional bool complete = 2 [default = false]; 473 | } 474 | 475 | message Blocked { 476 | repeated string numbers = 1; 477 | repeated string acis = 3; 478 | repeated bytes groupIds = 2; 479 | } 480 | 481 | message Request { 482 | enum Type { 483 | UNKNOWN = 0; 484 | CONTACTS = 1; 485 | // GROUPS = 2; 486 | BLOCKED = 3; 487 | CONFIGURATION = 4; 488 | KEYS = 5; 489 | PNI_IDENTITY = 6; 490 | } 491 | 492 | optional Type type = 1; 493 | } 494 | 495 | message Read { 496 | reserved /*senderE164*/ 1; 497 | optional string senderAci = 3; 498 | optional uint64 timestamp = 2; 499 | } 500 | 501 | message Viewed { 502 | reserved /*senderE164*/ 1; 503 | optional string senderAci = 3; 504 | optional uint64 timestamp = 2; 505 | } 506 | 507 | message Configuration { 508 | optional bool readReceipts = 1; 509 | optional bool unidentifiedDeliveryIndicators = 2; 510 | optional bool typingIndicators = 3; 511 | reserved /* linkPreviews */ 4; 512 | optional uint32 provisioningVersion = 5; 513 | optional bool linkPreviews = 6; 514 | } 515 | 516 | message StickerPackOperation { 517 | enum Type { 518 | INSTALL = 0; 519 | REMOVE = 1; 520 | } 521 | 522 | optional bytes packId = 1; 523 | optional bytes packKey = 2; 524 | optional Type type = 3; 525 | } 526 | 527 | message ViewOnceOpen { 528 | reserved /*senderE164*/ 1; 529 | optional string senderAci = 3; 530 | optional uint64 timestamp = 2; 531 | } 532 | 533 | message FetchLatest { 534 | enum Type { 535 | UNKNOWN = 0; 536 | LOCAL_PROFILE = 1; 537 | STORAGE_MANIFEST = 2; 538 | SUBSCRIPTION_STATUS = 3; 539 | } 540 | 541 | optional Type type = 1; 542 | } 543 | 544 | message Keys { 545 | // @deprecated 546 | optional bytes storageService = 1; 547 | optional bytes master = 2; 548 | } 549 | 550 | message MessageRequestResponse { 551 | enum Type { 552 | UNKNOWN = 0; 553 | ACCEPT = 1; 554 | DELETE = 2; 555 | BLOCK = 3; 556 | BLOCK_AND_DELETE = 4; 557 | } 558 | 559 | reserved /*threadE164*/ 1; 560 | optional string threadAci = 2; 561 | optional bytes groupId = 3; 562 | optional Type type = 4; 563 | } 564 | 565 | message OutgoingPayment { 566 | message MobileCoin { 567 | optional bytes recipientAddress = 1; 568 | // @required 569 | optional uint64 amountPicoMob = 2; 570 | // @required 571 | optional uint64 feePicoMob = 3; 572 | optional bytes receipt = 4; 573 | optional uint64 ledgerBlockTimestamp = 5; 574 | // @required 575 | optional uint64 ledgerBlockIndex = 6; 576 | repeated bytes spentKeyImages = 7; 577 | repeated bytes outputPublicKeys = 8; 578 | } 579 | optional string recipientServiceId = 1; 580 | optional string note = 2; 581 | 582 | oneof paymentDetail { 583 | MobileCoin mobileCoin = 3; 584 | } 585 | } 586 | 587 | message PniChangeNumber { 588 | optional bytes identityKeyPair = 1; // Serialized libsignal-client IdentityKeyPair 589 | optional bytes signedPreKey = 2; // Serialized libsignal-client SignedPreKeyRecord 590 | optional bytes lastResortKyberPreKey = 5; // Serialized libsignal-client KyberPreKeyRecord 591 | optional uint32 registrationId = 3; 592 | optional string newE164 = 4; // The e164 we have changed our number to 593 | // Next ID: 6 594 | } 595 | 596 | message CallEvent { 597 | enum Type { 598 | UNKNOWN_TYPE = 0; 599 | AUDIO_CALL = 1; 600 | VIDEO_CALL = 2; 601 | GROUP_CALL = 3; 602 | AD_HOC_CALL = 4; 603 | } 604 | 605 | enum Direction { 606 | UNKNOWN_DIRECTION = 0; 607 | INCOMING = 1; 608 | OUTGOING = 2; 609 | } 610 | 611 | enum Event { 612 | UNKNOWN_ACTION = 0; 613 | ACCEPTED = 1; 614 | NOT_ACCEPTED = 2; 615 | DELETE = 3; 616 | } 617 | 618 | optional bytes conversationId = 1; 619 | optional uint64 id = 2; 620 | optional uint64 timestamp = 3; 621 | optional Type type = 4; 622 | optional Direction direction = 5; 623 | optional Event event = 6; 624 | } 625 | 626 | message CallLinkUpdate { 627 | optional bytes rootKey = 1; 628 | optional bytes adminPassKey = 2; 629 | } 630 | 631 | message CallLogEvent { 632 | enum Type { 633 | CLEAR = 0; 634 | } 635 | 636 | optional Type type = 1; 637 | optional uint64 timestamp = 2; 638 | } 639 | 640 | optional Sent sent = 1; 641 | optional Contacts contacts = 2; 642 | reserved /*groups*/ 3; 643 | optional Request request = 4; 644 | repeated Read read = 5; 645 | optional Blocked blocked = 6; 646 | optional Verified verified = 7; 647 | optional Configuration configuration = 9; 648 | optional bytes padding = 8; 649 | repeated StickerPackOperation stickerPackOperation = 10; 650 | optional ViewOnceOpen viewOnceOpen = 11; 651 | optional FetchLatest fetchLatest = 12; 652 | optional Keys keys = 13; 653 | optional MessageRequestResponse messageRequestResponse = 14; 654 | optional OutgoingPayment outgoingPayment = 15; 655 | repeated Viewed viewed = 16; 656 | reserved /*pniIdentity*/ 17; 657 | optional PniChangeNumber pniChangeNumber = 18; 658 | optional CallEvent callEvent = 19; 659 | optional CallLinkUpdate callLinkUpdate = 20; 660 | optional CallLogEvent callLogEvent = 21; 661 | } 662 | 663 | message AttachmentPointer { 664 | enum Flags { 665 | VOICE_MESSAGE = 1; 666 | BORDERLESS = 2; 667 | reserved 3; 668 | GIF = 4; 669 | } 670 | 671 | oneof attachment_identifier { 672 | fixed64 cdnId = 1; 673 | string cdnKey = 15; 674 | } 675 | optional string contentType = 2; 676 | optional bytes key = 3; 677 | optional uint32 size = 4; 678 | optional bytes thumbnail = 5; 679 | optional bytes digest = 6; 680 | reserved 16; 681 | optional bytes incrementalMac = 18; 682 | optional uint32 incrementalMacChunkSize = 17; 683 | optional string fileName = 7; 684 | optional uint32 flags = 8; 685 | optional uint32 width = 9; 686 | optional uint32 height = 10; 687 | optional string caption = 11; 688 | optional string blurHash = 12; 689 | optional uint64 uploadTimestamp = 13; 690 | optional uint32 cdnNumber = 14; 691 | // Next ID: 19 692 | } 693 | 694 | message GroupContext { 695 | enum Type { 696 | UNKNOWN = 0; 697 | UPDATE = 1; 698 | DELIVER = 2; 699 | QUIT = 3; 700 | REQUEST_INFO = 4; 701 | } 702 | 703 | message Member { 704 | reserved /* uuid */ 1; // removed 705 | optional string e164 = 2; 706 | } 707 | 708 | optional bytes id = 1; 709 | optional Type type = 2; 710 | optional string name = 3; 711 | repeated string membersE164 = 4; 712 | repeated Member members = 6; 713 | optional AttachmentPointer avatar = 5; 714 | } 715 | 716 | message GroupContextV2 { 717 | optional bytes masterKey = 1; 718 | optional uint32 revision = 2; 719 | optional bytes groupChange = 3; 720 | } 721 | 722 | message ContactDetails { 723 | message Avatar { 724 | optional string contentType = 1; 725 | optional uint32 length = 2; 726 | } 727 | 728 | optional string number = 1; 729 | optional string aci = 9; 730 | optional string name = 2; 731 | optional Avatar avatar = 3; 732 | optional string color = 4; 733 | optional Verified verified = 5; 734 | optional bytes profileKey = 6; 735 | optional bool blocked = 7; 736 | optional uint32 expireTimer = 8; 737 | optional uint32 inboxPosition = 10; 738 | optional bool archived = 11; 739 | } 740 | 741 | message GroupDetails { 742 | message Avatar { 743 | optional string contentType = 1; 744 | optional uint32 length = 2; 745 | } 746 | 747 | message Member { 748 | reserved /* uuid */ 1; // removed 749 | optional string e164 = 2; 750 | } 751 | 752 | optional bytes id = 1; 753 | optional string name = 2; 754 | repeated string membersE164 = 3; 755 | repeated Member members = 9; 756 | optional Avatar avatar = 4; 757 | optional bool active = 5 [default = true]; 758 | optional uint32 expireTimer = 6; 759 | optional string color = 7; 760 | optional bool blocked = 8; 761 | optional uint32 inboxPosition = 10; 762 | optional bool archived = 11; 763 | } 764 | 765 | message PaymentAddress { 766 | oneof Address { 767 | MobileCoinAddress mobileCoinAddress = 1; 768 | } 769 | 770 | message MobileCoinAddress { 771 | optional bytes address = 1; 772 | optional bytes signature = 2; 773 | } 774 | } 775 | 776 | message DecryptionErrorMessage { 777 | optional bytes ratchetKey = 1; 778 | optional uint64 timestamp = 2; 779 | optional uint32 deviceId = 3; 780 | } 781 | 782 | message PniSignatureMessage { 783 | optional bytes pni = 1; 784 | optional bytes signature = 2; 785 | } 786 | 787 | message EditMessage { 788 | optional uint64 targetSentTimestamp = 1; 789 | optional DataMessage dataMessage = 2; 790 | } 791 | -------------------------------------------------------------------------------- /proto/WebSocketResources.proto: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2014-2016 Open Whisper Systems 3 | * 4 | * Licensed according to the LICENSE file in this repository. 5 | */ 6 | syntax = "proto2"; 7 | 8 | package proto.websocketresources; 9 | 10 | option java_package = "org.whispersystems.signalservice.internal.websocket"; 11 | option java_outer_classname = "WebSocketProtos"; 12 | 13 | message WebSocketRequestMessage { 14 | optional string verb = 1; 15 | optional string path = 2; 16 | optional bytes body = 3; 17 | repeated string headers = 5; 18 | optional uint64 id = 4; 19 | } 20 | 21 | message WebSocketResponseMessage { 22 | optional uint64 id = 1; 23 | optional uint32 status = 2; 24 | optional string message = 3; 25 | repeated string headers = 5; 26 | optional bytes body = 4; 27 | } 28 | 29 | message WebSocketMessage { 30 | enum Type { 31 | UNKNOWN = 0; 32 | REQUEST = 1; 33 | RESPONSE = 2; 34 | } 35 | 36 | optional Type type = 1; 37 | optional WebSocketRequestMessage request = 2; 38 | optional WebSocketResponseMessage response = 3; 39 | } 40 | -------------------------------------------------------------------------------- /reverse_proxy_samples/Caddyfile: -------------------------------------------------------------------------------- 1 | { 2 | auto_https disable_redirects 3 | 4 | servers { 5 | metrics 6 | } 7 | } 8 | 9 | (upgrade) { 10 | @upgradable { 11 | header Upgrade-Insecure-Requests 1 12 | protocol http 13 | } 14 | 15 | redir @upgradable https://{host}{uri} 308 16 | 17 | } 18 | 19 | # Caddy pass the request `Host` header by default 20 | molly.domain.tld { 21 | reverse_proxy 127.0.0.1:8020 22 | } 23 | 24 | # # If you need to set on another path 25 | # www.domain.tld { 26 | # reverse_proxy /molly/ 127.0.0.1:8020 { 27 | # header_up X-Original-URL "/molly/" 28 | # } 29 | # } 30 | -------------------------------------------------------------------------------- /reverse_proxy_samples/apache.conf: -------------------------------------------------------------------------------- 1 | # You can integrate this into your (virtual) host configuration or using 2 | # Debian you might put this to /etc/apache2/conf-available/mollysocket.conf 3 | # and use a2enconf mollysocket afterwards 4 | 5 | ProxyPass http://localhost:8020/ 6 | ProxyPassReverse http://localhost:8020/ 7 | RequestHeader set X-Original-URL "/molly/" 8 | ProxyPreserveHost On 9 | 10 | -------------------------------------------------------------------------------- /src/build_proto.rs: -------------------------------------------------------------------------------- 1 | use std::io::Result; 2 | fn main() -> Result<()> { 3 | println!("cargo:warning=STARTING"); 4 | prost_build::compile_protos( 5 | &[ 6 | "proto/SignalService.proto", 7 | "proto/WebSocketResources.proto", 8 | ], 9 | &["proto/"], 10 | )?; 11 | println!("cargo:warning=DONE: `fd signal target` to find .rs"); 12 | Ok(()) 13 | } 14 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use clap::{ArgAction, Parser, Subcommand}; 2 | use qrcode::QrcodeCommand; 3 | use std::{env, path::PathBuf}; 4 | use vapid::VapidCommand; 5 | 6 | use crate::cli::{connection::ConnectionCommand, test::TestCommand}; 7 | use crate::config; 8 | 9 | mod connection; 10 | mod qrcode; 11 | mod server; 12 | mod test; 13 | mod vapid; 14 | 15 | #[derive(Parser)] 16 | #[command(author, version, about, long_about = None)] 17 | #[command(infer_subcommands = true)] 18 | struct Cli { 19 | /// Sets a custom config file 20 | #[arg(short, long, value_name = "FILE")] 21 | config: Option, 22 | 23 | /// Verbosity level 24 | #[arg(short, action = ArgAction::Count)] 25 | verbose: u8, 26 | 27 | #[command(subcommand)] 28 | command: Command, 29 | } 30 | 31 | #[derive(Subcommand)] 32 | enum Command { 33 | /// Run webserver and websockets 34 | Server {}, 35 | 36 | /// Generate and test VAPID keys 37 | Vapid { 38 | #[command(subcommand)] 39 | command: VapidCommand, 40 | }, 41 | 42 | /// Print mollysocket link URL and show the associated QR code 43 | QRCode { 44 | #[command(subcommand)] 45 | command: QrcodeCommand, 46 | }, 47 | 48 | /// Add, remove and list connections 49 | Connection { 50 | #[command(subcommand)] 51 | command: ConnectionCommand, 52 | }, 53 | 54 | /// Test account and endpoint validity 55 | Test { 56 | #[command(subcommand)] 57 | command: TestCommand, 58 | }, 59 | } 60 | 61 | pub async fn cli() { 62 | let cli = Cli::parse(); 63 | 64 | match cli.verbose { 65 | 0 => (), 66 | 1 => match env::var("RUST_LOG") { 67 | Ok(v) if (v.as_str() == "trace" || v.as_str() == "debug") => (), 68 | _ => env::set_var("RUST_LOG", "info"), 69 | }, 70 | 2 => match env::var("RUST_LOG") { 71 | Ok(v) if (v.as_str() == "trace") => (), 72 | _ => env::set_var("RUST_LOG", "debug"), 73 | }, 74 | _ => env::set_var("RUST_LOG", "trace"), 75 | } 76 | 77 | match &cli.command { 78 | Command::Server {} => (), 79 | Command::Vapid { .. } => (), 80 | _ => { 81 | if env::var("RUST_LOG").is_err() { 82 | env::set_var("RUST_LOG", "info"); 83 | } 84 | } 85 | } 86 | env_logger::init(); 87 | 88 | log::debug!("env_logger initialized"); 89 | 90 | config::load_config(cli.config); 91 | 92 | match &cli.command { 93 | Command::Server {} => server::server().await, 94 | Command::QRCode { command } => qrcode::qrcode(command), 95 | Command::Connection { command } => connection::connection(command).await, 96 | Command::Test { command } => test::test(command).await, 97 | Command::Vapid { command } => vapid::vapid(command), 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/cli/connection.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use crate::{ 4 | config, db, 5 | utils::{self, anonymize_url}, 6 | }; 7 | use clap::Subcommand; 8 | use lazy_static::lazy_static; 9 | use regex::Regex; 10 | use url::Url; 11 | 12 | #[derive(Subcommand)] 13 | pub enum ConnectionCommand { 14 | /// Add a new account connection 15 | Add { 16 | /// Account UUID 17 | account_id: String, 18 | 19 | /// Device number 20 | #[arg(value_parser = clap::value_parser!(u32).range(1..))] 21 | device_id: u32, 22 | 23 | /// Device token 24 | password: String, 25 | 26 | /// UnifiedPush endpoint 27 | endpoint: String, 28 | }, 29 | 30 | /// List all account connections 31 | List { 32 | /// Anonymize account id and password 33 | #[arg(short, long)] 34 | anonymized: bool, 35 | }, 36 | 37 | /// Remove account connection 38 | Remove { 39 | /// Account UUID 40 | account_id: String, 41 | }, 42 | 43 | /// Send test notification to the endpoint associated 44 | Ping { 45 | /// Account UUID 46 | account_id: String, 47 | }, 48 | } 49 | 50 | pub async fn connection(command: &ConnectionCommand) { 51 | match command { 52 | ConnectionCommand::Add { 53 | account_id, 54 | device_id, 55 | password, 56 | endpoint, 57 | } => add(account_id, device_id, password, endpoint).await, 58 | ConnectionCommand::List { anonymized } => list(*anonymized), 59 | ConnectionCommand::Remove { account_id } => rm(account_id), 60 | ConnectionCommand::Ping { account_id } => ping(account_id).await, 61 | } 62 | } 63 | 64 | async fn add(uuid: &str, device_id: &u32, password: &str, endpoint: &str) { 65 | if !config::is_uuid_valid(uuid) { 66 | println!("UUID invalid or forbidden: {}", uuid); 67 | return; 68 | } 69 | if !config::is_endpoint_valid(endpoint).await { 70 | println!("Endpoint invalid or forbidden: {}", endpoint); 71 | return; 72 | } 73 | let _ = db::MollySocketDb::new().unwrap().add(&db::Connection::new( 74 | uuid.to_string(), 75 | *device_id, 76 | password.to_string(), 77 | endpoint.to_string(), 78 | )); 79 | if let Err(e) = utils::ping(Url::from_str(endpoint).unwrap()).await { 80 | log::warn!("Cound not ping the new connection (uuid={}): {e:?}", uuid); 81 | } 82 | println!("Connection for {} added.", uuid); 83 | } 84 | 85 | fn list(anonymized: bool) { 86 | lazy_static! { 87 | static ref RE: Regex = Regex::new(r"[^-]").unwrap(); 88 | } 89 | if anonymized { 90 | println!(" 91 | /!\\ The endpoints are not fully anonymized. /!\\ 92 | This is required to help to debug some setups. You should unregister Molly from your distributor to get a new endpoint if you share this output. 93 | "); 94 | } 95 | db::MollySocketDb::new() 96 | .unwrap() 97 | .list() 98 | .unwrap() 99 | .iter_mut() 100 | .for_each(|connection| { 101 | if anonymized { 102 | connection.uuid = RE.replace_all(&connection.uuid, "x").into(); 103 | connection.password = RE.replace_all(&connection.password, "x").into(); 104 | connection.endpoint = anonymize_url(&connection.endpoint); 105 | } 106 | dbg!(&connection); 107 | }); 108 | } 109 | 110 | fn rm(uuid: &str) { 111 | db::MollySocketDb::new().unwrap().rm(uuid).unwrap(); 112 | println!("Connection for {} successfully removed.", uuid) 113 | } 114 | 115 | async fn ping(uuid: &str) { 116 | let connection = match db::MollySocketDb::new().unwrap().get(uuid) { 117 | Ok(c) => c, 118 | Err(_) => { 119 | println!("No connection found with this Id"); 120 | return; 121 | } 122 | }; 123 | let url = url::Url::parse(&connection.endpoint).unwrap(); 124 | // We unwrap to catch some config errors 125 | utils::ping(url).await.unwrap(); 126 | } 127 | -------------------------------------------------------------------------------- /src/cli/qrcode.rs: -------------------------------------------------------------------------------- 1 | use crate::{qrcode, vapid}; 2 | use clap::Subcommand; 3 | 4 | #[derive(Subcommand)] 5 | pub enum QrcodeCommand { 6 | /// Generate link QR code for the associated URL 7 | Url { 8 | /// URL of mollysocket 9 | url: String, 10 | }, 11 | 12 | /// Generate link QR code for mollysocket used in airgapped mode 13 | Airgapped {}, 14 | } 15 | 16 | /// Print mollysocket link URL and show the associated QR Code 17 | pub fn qrcode(command: &QrcodeCommand) { 18 | let url = match command { 19 | QrcodeCommand::Url { url } => qrcode::gen_url(url), 20 | QrcodeCommand::Airgapped {} => qrcode::gen_url_airgapped(), 21 | }; 22 | if let Err(e) = &url { 23 | if let Some(vapid::Error::VapidKeyError) = e.downcast_ref::() { 24 | println!("{}", e); 25 | return; 26 | } 27 | } 28 | let url = url.unwrap(); 29 | let qr_code = qrcode::url_to_printable_qr(&url); 30 | println!("{}\n{}", qrcode::INTRO, qr_code) 31 | } 32 | -------------------------------------------------------------------------------- /src/cli/server.rs: -------------------------------------------------------------------------------- 1 | use crate::server; 2 | 3 | pub async fn server() { 4 | server::run().await; 5 | } 6 | -------------------------------------------------------------------------------- /src/cli/test.rs: -------------------------------------------------------------------------------- 1 | use crate::{config, db::MollySocketDb}; 2 | use clap::Subcommand; 3 | 4 | #[derive(Subcommand)] 5 | pub enum TestCommand { 6 | /// Test allowed UnifiedPush endpoint 7 | Endpoint { 8 | /// UnifiedPush endpoint 9 | endpoint: String, 10 | }, 11 | 12 | /// Test allowed account uuid 13 | Uuid { 14 | /// Account uuid 15 | account_id: String, 16 | }, 17 | } 18 | 19 | pub async fn test(command: &TestCommand) { 20 | config::print(); 21 | match command { 22 | TestCommand::Endpoint { endpoint } => test_endpoint(endpoint).await, 23 | TestCommand::Uuid { account_id } => test_uuid(account_id), 24 | } 25 | } 26 | 27 | fn test_uuid(uuid: &str) { 28 | if !config::is_uuid_valid(uuid) { 29 | println!("UUID {} is not valid", uuid); 30 | } else { 31 | println!("UUID {} is valid", uuid); 32 | } 33 | 34 | let db = match MollySocketDb::new() { 35 | Ok(db) => db, 36 | Err(_) => { 37 | println!(" An error occured while opening the DB."); 38 | return; 39 | } 40 | }; 41 | let co = match db.get(uuid) { 42 | Ok(co) => co, 43 | Err(_) => { 44 | println!(" No connection is registered with this UUID."); 45 | return; 46 | } 47 | }; 48 | if co.forbidden { 49 | println!(" The connection associated to this UUID is forbidden."); 50 | return; 51 | } 52 | println!(" A connection is associated to this UUID and is ok."); 53 | } 54 | 55 | async fn test_endpoint(endpoint: &str) { 56 | if config::is_endpoint_valid(endpoint).await { 57 | println!("Endpoint {} is valid", endpoint); 58 | } else { 59 | println!("Endpoint {} is not valid", endpoint); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/cli/vapid.rs: -------------------------------------------------------------------------------- 1 | use crate::vapid; 2 | use clap::Subcommand; 3 | 4 | #[derive(Subcommand)] 5 | pub enum VapidCommand { 6 | /// Try to generate a VAPID header for endpoint 7 | Test { 8 | /// UnifiedPush endpoint 9 | endpoint: String, 10 | }, 11 | 12 | /// Generate VAPID key and print to STDOUT 13 | Generate {}, 14 | } 15 | 16 | pub fn vapid(command: &VapidCommand) { 17 | match command { 18 | VapidCommand::Test { endpoint } => print_vapid_for_endpoint(endpoint), 19 | VapidCommand::Generate {} => generate_vapid(), 20 | } 21 | } 22 | 23 | fn generate_vapid() { 24 | let key = vapid::gen_vapid_key(); 25 | println!("{}", key); 26 | } 27 | 28 | fn print_vapid_for_endpoint(endpoint: &str) { 29 | let origin = url::Url::parse(endpoint) 30 | .expect(&format!("Could not parse {}.", endpoint)) 31 | .origin(); 32 | let header = match vapid::get_vapid_header(origin) { 33 | Err(e) if matches!(e.downcast_ref(), Some(vapid::Error::VapidKeyError)) => { 34 | println!("{}", e); 35 | return; 36 | } 37 | h => h, 38 | } 39 | .expect("Cannot generate header"); 40 | println!("{}", header); 41 | } 42 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use directories::ProjectDirs; 2 | use figment::{ 3 | providers::{Env, Format, Serialized, Toml}, 4 | Figment, 5 | }; 6 | use serde::{Deserialize, Serialize}; 7 | use std::{env, fmt::Debug, path::PathBuf, process, sync::OnceLock}; 8 | 9 | use crate::utils::post_allowed::ResolveAllowed; 10 | 11 | static CONFIG: OnceLock = OnceLock::new(); 12 | 13 | #[derive(Debug, Serialize, Deserialize)] 14 | pub enum SignalEnvironment { 15 | Production, 16 | Staging, 17 | } 18 | 19 | #[derive(Debug, Serialize, Deserialize)] 20 | struct Config { 21 | host: String, 22 | port: u16, 23 | webserver: bool, 24 | vapid_privkey: Option, 25 | vapid_key_file: Option, 26 | signal_env: SignalEnvironment, 27 | allowed_endpoints: Vec, 28 | allowed_uuids: Vec, 29 | db: String, 30 | } 31 | 32 | #[derive(Debug, PartialEq, Eq)] 33 | enum EndpointValidity { 34 | Ok, 35 | NotInConfig, 36 | Private, 37 | } 38 | 39 | impl Default for Config { 40 | fn default() -> Self { 41 | Self { 42 | host: String::from("127.0.0.1"), 43 | port: 8020, 44 | webserver: true, 45 | vapid_privkey: None, 46 | vapid_key_file: None, 47 | signal_env: SignalEnvironment::Production, 48 | allowed_endpoints: vec![String::from("*")], 49 | allowed_uuids: vec![String::from("*")], 50 | db: String::from("./mollysocket.db"), 51 | } 52 | } 53 | } 54 | 55 | fn get_cfg() -> &'static Config { 56 | CONFIG.get().expect("Config is not initialized yet.") 57 | } 58 | 59 | /// Get db filename 60 | pub fn get_db() -> &'static str { 61 | &get_cfg().db 62 | } 63 | 64 | pub fn get_host() -> &'static str { 65 | &get_cfg().host 66 | } 67 | 68 | pub fn get_port() -> u16 { 69 | get_cfg().port 70 | } 71 | 72 | pub fn is_uuid_valid(uuid: &str) -> bool { 73 | get_cfg().is_uuid_valid(uuid) 74 | } 75 | 76 | pub fn should_start_webserver() -> bool { 77 | get_cfg().webserver 78 | } 79 | 80 | pub fn get_vapid_privkey() -> Option<&'static str> { 81 | get_cfg().vapid_privkey.as_deref() 82 | } 83 | 84 | pub fn get_ws_endpoint() -> &'static str { 85 | get_cfg().get_ws_endpoint() 86 | } 87 | 88 | pub async fn is_endpoint_valid(url: &str) -> bool { 89 | get_cfg().is_endpoint_valid(url).await 90 | } 91 | 92 | pub fn is_endpoint_allowed_by_user(url: &url::Url) -> bool { 93 | get_cfg().is_endpoint_allowed_by_user(url) 94 | } 95 | 96 | pub fn print() { 97 | let cfg = get_cfg(); 98 | println!("{:#?}", cfg) 99 | } 100 | 101 | pub fn load_config(cli_config_path: Option) { 102 | CONFIG.get_or_init(move || { 103 | let mut figment = Figment::new(); 104 | 105 | figment = figment.merge(Serialized::defaults(Config::default())); 106 | 107 | if let Some(path) = get_config_path(cli_config_path) { 108 | log::info!("Config file: {}", path.display()); 109 | figment = figment.merge(Toml::file(path)); 110 | } else { 111 | log::info!("No config file supplied"); 112 | } 113 | 114 | figment = figment.merge(Env::prefixed("MOLLY_").ignore(&["conf"])); 115 | 116 | let mut config: Config = match figment.extract() { 117 | Ok(config) => config, 118 | Err(figment_err) => { 119 | for err in figment_err { 120 | log::error!("Config parse error: {}", err); 121 | } 122 | process::exit(0x0001); 123 | } 124 | }; 125 | if let Some(file) = &config.vapid_key_file { 126 | config.vapid_privkey = Some( 127 | std::fs::read_to_string(file) 128 | .expect("Cannot read MOLLY_VAPID_KEY_FILE") 129 | .trim_end() 130 | .to_string(), 131 | ); 132 | } 133 | config 134 | }); 135 | } 136 | 137 | fn get_config_path(cli_config_path: Option) -> Option { 138 | let mut paths: Vec = Vec::new(); 139 | 140 | // from cli argument 141 | if let Some(cli_path) = cli_config_path { 142 | if cli_path.exists() { 143 | return Some(cli_path); 144 | } else { 145 | panic!("{} not found.", cli_path.display()); 146 | } 147 | } 148 | 149 | // from environment variable 150 | if let Some(env_path) = env::var_os("MOLLY_CONF") { 151 | let path = Into::::into(env_path); 152 | if path.exists() { 153 | return Some(path); 154 | } else { 155 | panic!("MOLLY_CONF={}, file not found.", path.display()); 156 | } 157 | } 158 | 159 | // from xdg_config_home 160 | let proj_dirs = ProjectDirs::from("org", "mollyim", "mollysocket").unwrap(); 161 | paths.push(proj_dirs.config_dir().join("config.toml")); 162 | 163 | // in current directory 164 | paths.push(PathBuf::from("./mollysocket.toml")); 165 | 166 | // in linux /etc dir 167 | if cfg!(target_os = "linux") { 168 | paths.push(PathBuf::from("/etc/mollysocket/config.toml")); 169 | } 170 | 171 | for p in paths.iter() { 172 | if p.exists() { 173 | return Some(p.to_path_buf()); 174 | } 175 | } 176 | None 177 | } 178 | 179 | impl Config { 180 | fn is_uuid_valid(&self, uuid: &str) -> bool { 181 | self.allowed_uuids 182 | .clone() 183 | .iter() 184 | .any(|allowed| allowed == "*" || allowed == uuid) 185 | } 186 | 187 | fn endpoint_to_conf(&self, url: &url::Url) -> String { 188 | let mut conf_url = url::Url::parse("http://example.tld/").unwrap(); 189 | let _ = conf_url.set_scheme(url.scheme()); 190 | let _ = conf_url.set_host(url.host_str()); 191 | let _ = conf_url.set_port(url.port()); 192 | let _ = conf_url.set_username(url.username()); 193 | let _ = conf_url.set_password(url.password()); 194 | conf_url.into() 195 | } 196 | 197 | async fn is_endpoint_valid(&self, url: &str) -> bool { 198 | if let Ok(url) = url::Url::parse(url) { 199 | let endpoint_validity = self.is_url_endpoint_valid(&url).await; 200 | match endpoint_validity { 201 | EndpointValidity::Ok => true, 202 | EndpointValidity::NotInConfig => { 203 | log::warn!( 204 | "Endpoint not allowed: {}\n\ 205 | You may want to add \"{}\" to allowed_endpoints", 206 | url, 207 | self.endpoint_to_conf(&url) 208 | ); 209 | false 210 | } 211 | EndpointValidity::Private => { 212 | log::warn!( 213 | "Endpoint resolves to a private IP: {}\n\ 214 | You may want to add \"{}\" to allowed_endpoints", 215 | url, 216 | self.endpoint_to_conf(&url) 217 | ); 218 | false 219 | } 220 | } 221 | } else { 222 | false 223 | } 224 | } 225 | 226 | fn get_ws_endpoint(&self) -> &'static str { 227 | match self.signal_env { 228 | SignalEnvironment::Production => "wss://chat.signal.org/v1/websocket/", 229 | SignalEnvironment::Staging => "wss://chat.staging.signal.org/v1/websocket/", 230 | } 231 | } 232 | async fn is_url_endpoint_valid(&self, url: &url::Url) -> EndpointValidity { 233 | if self.is_endpoint_allowed_by_user(url) { 234 | EndpointValidity::Ok 235 | } else { 236 | if self.allowed_endpoints.contains(&"*".into()) { 237 | if url.resolve_allowed().await.unwrap_or(vec![]).len().gt(&0) { 238 | EndpointValidity::Ok 239 | } else { 240 | EndpointValidity::Private 241 | } 242 | } else { 243 | EndpointValidity::NotInConfig 244 | } 245 | } 246 | } 247 | 248 | fn is_endpoint_allowed_by_user(&self, url: &url::Url) -> bool { 249 | self.allowed_endpoints.iter().any(|allowed| { 250 | if let Ok(allowed_url) = url::Url::parse(allowed) { 251 | url.host() == allowed_url.host() 252 | && url.port() == allowed_url.port() 253 | && url.scheme() == allowed_url.scheme() 254 | && url.username() == allowed_url.username() 255 | && url.password() == allowed_url.password() 256 | } else { 257 | false 258 | } 259 | }) 260 | } 261 | } 262 | 263 | #[cfg(test)] 264 | mod tests { 265 | use super::*; 266 | 267 | fn test_config(uuid: &str, endpoint: &str) -> Config { 268 | let allowed_uuids = vec![String::from(uuid)]; 269 | let allowed_endpoints = vec![String::from(endpoint)]; 270 | dbg!(Config { 271 | allowed_endpoints, 272 | allowed_uuids, 273 | ..Config::default() 274 | }) 275 | } 276 | 277 | #[test] 278 | fn check_wildcard_uuid() { 279 | let cfg = test_config("*", ""); 280 | assert!(cfg.is_uuid_valid("0d2ff653-3d88-43de-bcdb-f6657d3484e4")); 281 | } 282 | 283 | #[test] 284 | fn check_defined_uuid() { 285 | let cfg = test_config("0d2ff653-3d88-43de-bcdb-f6657d3484e4", ""); 286 | assert!(cfg.is_uuid_valid("0d2ff653-3d88-43de-bcdb-f6657d3484e4")); 287 | assert!(!cfg.is_uuid_valid("11111111-3d88-43de-bcdb-f6657d3484e4")); 288 | } 289 | 290 | #[tokio::test] 291 | async fn check_endpoint() { 292 | let cfg = test_config("", "https://ntfy.sh/"); 293 | assert_eq!( 294 | cfg.is_url_endpoint_valid(&url::Url::parse("https://ntfy.sh/foo?blah").unwrap()) 295 | .await, 296 | EndpointValidity::Ok 297 | ); 298 | assert_eq!( 299 | cfg.is_url_endpoint_valid(&url::Url::parse("https://ntfy.sh:8080/foo?blah").unwrap()) 300 | .await, 301 | EndpointValidity::NotInConfig 302 | ); 303 | assert_eq!( 304 | cfg.is_url_endpoint_valid( 305 | &url::Url::parse("https://user:pass@ntfy.sh/foo?blah").unwrap() 306 | ) 307 | .await, 308 | EndpointValidity::NotInConfig 309 | ); 310 | assert_eq!( 311 | cfg.is_url_endpoint_valid(&url::Url::parse("http://ntfy.sh/foo?blah").unwrap()) 312 | .await, 313 | EndpointValidity::NotInConfig 314 | ); 315 | } 316 | 317 | #[tokio::test] 318 | async fn check_wildcard_endpoint() { 319 | let cfg = test_config("", "*"); 320 | assert_eq!( 321 | cfg.is_url_endpoint_valid(&url::Url::parse("http://ntfy.sh/foo?blah").unwrap()) 322 | .await, 323 | EndpointValidity::Ok 324 | ); 325 | assert_eq!( 326 | cfg.is_url_endpoint_valid(&url::Url::parse("http://localhost/foo?blah").unwrap()) 327 | .await, 328 | EndpointValidity::Private 329 | ); 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /src/db.rs: -------------------------------------------------------------------------------- 1 | use eyre::Result; 2 | use rusqlite::{self, Row}; 3 | use std::{ 4 | sync::{Arc, Mutex}, 5 | time::{Duration, SystemTime, UNIX_EPOCH}, 6 | }; 7 | 8 | use crate::config; 9 | 10 | mod migrations; 11 | 12 | pub struct MollySocketDb { 13 | db: Arc>, 14 | } 15 | 16 | #[derive(Debug)] 17 | pub struct Connection { 18 | pub uuid: String, 19 | pub device_id: u32, 20 | pub password: String, 21 | pub endpoint: String, 22 | pub forbidden: bool, 23 | pub last_registration: OptTime, 24 | } 25 | 26 | impl Connection { 27 | pub fn new(uuid: String, device_id: u32, password: String, endpoint: String) -> Self { 28 | Connection { 29 | uuid, 30 | device_id, 31 | password, 32 | endpoint, 33 | forbidden: false, 34 | last_registration: OptTime::from(SystemTime::now()), 35 | } 36 | } 37 | } 38 | 39 | #[derive(Debug)] 40 | pub struct OptTime(pub Option); 41 | 42 | impl From<&OptTime> for u64 { 43 | fn from(i: &OptTime) -> u64 { 44 | let instant = match i.0 { 45 | Some(instant) => instant, 46 | None => return 0, 47 | }; 48 | match instant.duration_since(UNIX_EPOCH) { 49 | Ok(duration) => duration.as_secs(), 50 | Err(_) => 0, 51 | } 52 | } 53 | } 54 | 55 | impl From for OptTime { 56 | fn from(i: u64) -> OptTime { 57 | if i == 0 { 58 | return OptTime(None); 59 | } 60 | let duration = Duration::from_secs(i); 61 | OptTime(UNIX_EPOCH.checked_add(duration)) 62 | } 63 | } 64 | 65 | impl From for OptTime { 66 | fn from(t: SystemTime) -> Self { 67 | OptTime(Some(t)) 68 | } 69 | } 70 | 71 | impl Connection { 72 | fn map(row: &Row) -> Result { 73 | Ok(Connection { 74 | uuid: row.get(0)?, 75 | device_id: row.get(1)?, 76 | password: row.get(2)?, 77 | endpoint: row.get(3)?, 78 | forbidden: row.get(4)?, 79 | last_registration: OptTime::from(row.get::(5)?), 80 | }) 81 | } 82 | } 83 | 84 | impl MollySocketDb { 85 | pub fn new() -> Result { 86 | let db = rusqlite::Connection::open(config::get_db())?; 87 | db.execute_batch( 88 | " 89 | CREATE TABLE IF NOT EXISTS connections( 90 | uuid TEXT UNIQUE ON CONFLICT REPLACE, 91 | device_id INTEGER, 92 | password TEXT, 93 | endpoint TEXT, 94 | forbidden BOOLEAN NOT NULL CHECK (forbidden IN (0, 1)), 95 | last_registration INTEGER 96 | ) 97 | ", 98 | )?; 99 | Ok(MollySocketDb { 100 | db: Arc::new(Mutex::new(db)), 101 | }) 102 | } 103 | 104 | pub fn add(&self, co: &Connection) -> Result<()> { 105 | self.db.lock().unwrap().execute( 106 | "INSERT INTO connections(uuid, device_id, password, endpoint, forbidden, last_registration) 107 | VALUES (?, ?, ?, ?, ?, ?);", 108 | [&co.uuid, &co.device_id.to_string(), &co.password, &co.endpoint, &String::from(if co.forbidden { "1" } else { "0" }), &u64::from(&co.last_registration).to_string()] 109 | )?; 110 | Ok(()) 111 | } 112 | 113 | pub fn update_last_registration(&self, uuid: &str) -> Result<()> { 114 | let now = OptTime::from(SystemTime::now()); 115 | self.db.lock().unwrap().execute( 116 | "UPDATE connections 117 | SET last_registration = ? 118 | WHERE uuid = ?;", 119 | [&u64::from(&now).to_string(), uuid], 120 | )?; 121 | Ok(()) 122 | } 123 | 124 | pub fn list(&self) -> Result> { 125 | self.db 126 | .lock() 127 | .unwrap() 128 | .prepare("SELECT * FROM connections;")? 129 | .query_and_then([], Connection::map)? 130 | .collect::>>() 131 | } 132 | 133 | pub fn get(&self, uuid: &str) -> Result { 134 | self.db 135 | .lock() 136 | .unwrap() 137 | .prepare("SELECT * FROM connections WHERE uuid=?1 LIMIT 1")? 138 | .query_and_then([uuid], Connection::map)? 139 | .next() 140 | .ok_or(rusqlite::Error::QueryReturnedNoRows)? 141 | } 142 | 143 | pub fn rm(&self, uuid: &str) -> Result<()> { 144 | self.db 145 | .lock() 146 | .unwrap() 147 | .execute("DELETE FROM connections WHERE uuid=?1;", [&uuid])?; 148 | Ok(()) 149 | } 150 | } 151 | 152 | #[cfg(test)] 153 | mod tests { 154 | use super::*; 155 | 156 | #[test] 157 | fn test_db() { 158 | config::load_config(None); 159 | let db = MollySocketDb::new().unwrap(); 160 | let uuid = "0d2ff653-3d88-43de-bcdb-f6657d3484e4"; 161 | db.add(&Connection::new( 162 | String::from(uuid), 163 | 1, 164 | String::from("pass"), 165 | String::from("http://0.0.0.0/"), 166 | )) 167 | .unwrap(); 168 | assert!(db 169 | .list() 170 | .unwrap() 171 | .iter() 172 | .map(|co| &co.uuid) 173 | .any(|row_uuid| row_uuid == uuid)); 174 | db.rm(uuid).unwrap(); 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/db/migrations.rs: -------------------------------------------------------------------------------- 1 | use eyre::Result; 2 | 3 | const CURRENT_VERSION: i32 = 1; 4 | 5 | pub trait Migration { 6 | fn migrate(&self) -> Result<()>; 7 | } 8 | 9 | impl Migration for rusqlite::Connection { 10 | fn migrate(&self) -> Result<()> { 11 | let _user_version: i32 = 12 | self.query_row("SELECT user_version FROM pragma_user_version;", [], |row| { 13 | row.get(0) 14 | })?; 15 | 16 | // Upgrade version 17 | Ok(self.pragma_update(None, "user_version", CURRENT_VERSION)?) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod cli; 2 | mod config; 3 | mod db; 4 | mod qrcode; 5 | mod server; 6 | mod utils; 7 | mod vapid; 8 | mod ws; 9 | 10 | #[tokio::main] 11 | async fn main() { 12 | cli::cli().await; 13 | } 14 | -------------------------------------------------------------------------------- /src/qrcode.rs: -------------------------------------------------------------------------------- 1 | use eyre::Result; 2 | use qrcodegen::{QrCode, QrCodeEcc}; 3 | use url::Url; 4 | 5 | use crate::vapid; 6 | 7 | pub const INTRO: &str = "Scan the following QR code to link mollysocket:"; 8 | 9 | /// Generate deep link to link mollysocket to molly with url 10 | pub fn gen_url(ms_url: &str) -> Result { 11 | let mut url = Url::parse("mollysocket://link")?; 12 | let vapid = vapid::get_vapid_pubkey()?; 13 | url.query_pairs_mut().append_pair("vapid", vapid); 14 | url.query_pairs_mut().append_pair("url", ms_url); 15 | url.query_pairs_mut().append_pair("type", "webserver"); 16 | Ok(url) 17 | } 18 | 19 | /// Generate deep link to link mollysocket to molly in airgapped mode 20 | pub fn gen_url_airgapped() -> Result { 21 | let mut url = Url::parse("mollysocket://link")?; 22 | let vapid = vapid::get_vapid_pubkey()?; 23 | url.query_pairs_mut().append_pair("vapid", vapid); 24 | url.query_pairs_mut().append_pair("type", "airgapped"); 25 | Ok(url) 26 | } 27 | 28 | /// Return QRCode made with characters 29 | pub fn url_to_printable_qr(url: &Url) -> String { 30 | let qr = QrCode::encode_text(&url.as_str(), QrCodeEcc::Low).unwrap(); 31 | let mut result = String::new(); 32 | let border: i32 = 4; 33 | for y in (-border..qr.size() + border).step_by(2) { 34 | for x in -border..qr.size() + border { 35 | let c: char = if qr.get_module(x, y) { 36 | if qr.get_module(x, y + 1) { 37 | '█' 38 | } else { 39 | '▀' 40 | } 41 | } else { 42 | if qr.get_module(x, y + 1) { 43 | '▄' 44 | } else { 45 | ' ' 46 | } 47 | }; 48 | result.push(c); 49 | } 50 | result.push('\n'); 51 | } 52 | result.push('\n'); 53 | result 54 | } 55 | 56 | /// Return QRCode in svg format 57 | pub fn url_to_svg_qr(url: &Url) -> String { 58 | let qr = QrCode::encode_text(&url.as_str(), QrCodeEcc::Low).unwrap(); 59 | let mut result = String::new(); 60 | let border: i32 = 4; 61 | result += "\n"; 62 | result += "\n"; 63 | let dimension = qr 64 | .size() 65 | .checked_add(border.checked_mul(2).unwrap()) 66 | .unwrap(); 67 | result += &format!( 68 | "\n", dimension); 69 | result += "\t\n"; 70 | result += "\t\n"; 82 | result += "\n"; 83 | result 84 | } 85 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | use crate::{db::MollySocketDb, server::metrics::Metrics}; 2 | use futures_util::{future::join, pin_mut, select, FutureExt}; 3 | use lazy_static::lazy_static; 4 | use std::sync::{Arc, Mutex}; 5 | use tokio::signal; 6 | 7 | mod connections; 8 | mod metrics; 9 | mod web; 10 | 11 | lazy_static! { 12 | static ref DB: MollySocketDb = MollySocketDb::new().unwrap(); 13 | static ref METRICS: Metrics = Metrics::new().unwrap(); 14 | /** 15 | Vec of [connections::KillLoopRef]. 16 | 17 | Filled by [connections]. 18 | 19 | When a message is sent to the kill channel associated to the uuid, the loop for the registration stops. 20 | */ 21 | static ref KILL_VEC: Arc>> = Arc::new(Mutex::new(vec![])); 22 | /** 23 | Channel to do action when a new connection is registered. 24 | 25 | Bounded by [connections]. 26 | 27 | When a new connection is sent, loops for connection with this [Connection][crate::db::Connection]#uuid is kill, and a new loop is started. 28 | */ 29 | static ref NEW_CO_TX: Arc> = Arc::new(Mutex::new(None)); 30 | } 31 | 32 | pub async fn run() { 33 | let signal_future = signal::ctrl_c().fuse(); 34 | let joined_future = join(web::launch().fuse(), connections::run().fuse()); 35 | 36 | pin_mut!(signal_future, joined_future); 37 | 38 | select!( 39 | _ = signal_future => log::info!("SIGINT received"), 40 | _ = joined_future => log::warn!("Server stopped"), 41 | ) 42 | } 43 | -------------------------------------------------------------------------------- /src/server/connections.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | db::Connection, 3 | server::{DB, KILL_VEC, METRICS, NEW_CO_TX}, 4 | ws::SignalWebSocket, 5 | }; 6 | use eyre::Result; 7 | use futures_channel::mpsc::{self, UnboundedReceiver, UnboundedSender}; 8 | use futures_util::{future::join_all, join, select, Future, FutureExt, StreamExt}; 9 | use tokio_tungstenite::tungstenite; 10 | 11 | /** 12 | Associates the kill channel to the [Connection][crate::db::Connection]#uuid. 13 | */ 14 | pub struct KillLoopRef { 15 | uuid: String, 16 | tx: UnboundedSender, 17 | } 18 | 19 | pub type OptSender = Option>; 20 | 21 | pub async fn run() { 22 | let mut connections = DB.list().unwrap(); 23 | let loops: Vec<_> = connections 24 | .iter_mut() 25 | .map(|co| connection_loop(co).fuse()) 26 | .collect(); 27 | 28 | let (new_connections_tx, new_connections_rx) = mpsc::unbounded(); 29 | { 30 | let mut s_tx = NEW_CO_TX.lock().unwrap(); 31 | *s_tx = Some(new_connections_tx); 32 | } 33 | 34 | let new_loops = gen_new_loops(new_connections_rx).fuse(); 35 | 36 | join!(join_all(loops), new_loops); 37 | } 38 | 39 | pub async fn gen_new_loops(rx: UnboundedReceiver) { 40 | rx.for_each_concurrent(None, |mut co| async move { 41 | kill(&co.uuid).await; 42 | connection_loop(&mut co).await; 43 | }) 44 | .await; 45 | } 46 | 47 | async fn connection_loop(co: &mut Connection) { 48 | loop { 49 | if co.forbidden { 50 | log::info!("Ignoring connection for {}", &co.uuid); 51 | METRICS.forbiddens.inc(); 52 | return; 53 | } 54 | log::info!("Starting connection for {}", &co.uuid); 55 | let mut socket = 56 | match SignalWebSocket::new(&co.uuid, co.device_id, &co.password, &co.endpoint) { 57 | Ok(s) => s, 58 | Err(e) => { 59 | log::info!("An error occured for {}: {}", co.uuid, e); 60 | return; 61 | } 62 | }; 63 | let metrics_future = set_metrics(&mut socket); 64 | // Add the channel to kill the connection if needed 65 | let (kill_tx, mut kill_rx) = mpsc::unbounded(); 66 | { 67 | KILL_VEC.lock().unwrap().push(KillLoopRef { 68 | uuid: co.uuid.clone(), 69 | tx: kill_tx, 70 | }); 71 | } 72 | METRICS.connections.inc(); 73 | // bool to stop looping if the connection has been explicitely killed. 74 | let mut stop_loop = false; 75 | // loop connection 76 | select!( 77 | res = socket.connection_loop().fuse() => handle_connection_closed(res, co), 78 | _ = metrics_future.fuse() => log::warn!("[{}] One of the metrics channel has been closed.", co.uuid), 79 | _ = kill_rx.next().fuse() => { 80 | log::info!("[{}] Connection killed", co.uuid); 81 | // We don't want the loop to restart if the connection has been killed. 82 | stop_loop = true; 83 | }, 84 | ); 85 | // Remove the channel to kill the connection 86 | let mut refs = KILL_VEC.lock().unwrap(); 87 | if let Some(i_ref) = refs.iter().position(|l_ref| l_ref.uuid.eq(&co.uuid)) { 88 | refs.remove(i_ref); 89 | } 90 | METRICS.connections.dec(); 91 | // the connection has been killed, we don't loop. 92 | if stop_loop { 93 | return; 94 | } 95 | } 96 | } 97 | 98 | fn set_metrics(socket: &mut SignalWebSocket) -> impl Future { 99 | let (on_message_tx, on_message_rx) = mpsc::unbounded::(); 100 | let (on_push_tx, on_push_rx) = mpsc::unbounded::(); 101 | let (on_reconnection_tx, on_reconnection_rx) = mpsc::unbounded::(); 102 | socket.channels.on_message_tx = Some(on_message_tx); 103 | socket.channels.on_push_tx = Some(on_push_tx); 104 | socket.channels.on_reconnection_tx = Some(on_reconnection_tx); 105 | async move { 106 | select!( 107 | _ = on_message_rx 108 | .for_each(|_| async { 109 | METRICS.messages.inc(); 110 | }) 111 | .fuse() => (), 112 | _ = on_push_rx 113 | .for_each(|_| async { 114 | METRICS.pushs.inc(); 115 | }) 116 | .fuse() => (), 117 | _ = on_reconnection_rx 118 | .for_each(|_| async { 119 | METRICS.reconnections.inc(); 120 | }) 121 | .fuse() => (), 122 | ) 123 | } 124 | } 125 | 126 | fn handle_connection_closed(res: Result<()>, co: &mut Connection) { 127 | log::debug!("Connection closed."); 128 | 129 | match res { 130 | Ok(()) => (), 131 | Err(error) => { 132 | if let Some(tungstenite::Error::Http(resp)) = error.downcast_ref::() 133 | { 134 | let status = resp.status(); 135 | log::info!("Connection for {} closed with status: {}", &co.uuid, status); 136 | if status == 403 { 137 | co.forbidden = true; 138 | let _ = DB.add(co); 139 | } 140 | } 141 | } 142 | } 143 | } 144 | 145 | async fn kill(uuid: &str) { 146 | let refs = KILL_VEC.lock().unwrap(); 147 | if let Some(l_ref) = refs.iter().find(|&l_ref| l_ref.uuid.eq(uuid)) { 148 | let _ = l_ref.tx.clone().unbounded_send(true); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/server/metrics.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use eyre::Result; 4 | use rocket::{http::uri::Origin, Build, Rocket}; 5 | use rocket_prometheus::{ 6 | prometheus::{register_int_counter, register_int_gauge, IntCounter, IntGauge}, 7 | PrometheusMetrics, 8 | }; 9 | 10 | pub struct Metrics { 11 | pub connections: IntGauge, 12 | pub forbiddens: IntGauge, 13 | pub reconnections: IntCounter, 14 | pub messages: IntCounter, 15 | pub pushs: IntCounter, 16 | } 17 | 18 | impl Metrics { 19 | pub fn new() -> Result { 20 | let connections = 21 | register_int_gauge!("mollysocket_connections", "Connections to Signal server")?; 22 | let forbiddens = register_int_gauge!( 23 | "mollysocket_forbiddens", 24 | "Forbidden connections to Signal server" 25 | )?; 26 | let reconnections = 27 | register_int_counter!("mollysocket_reconnections", "Reconnections since the start")?; 28 | let messages = 29 | register_int_counter!("mollysocket_messages", "Messages received from Signal")?; 30 | let pushs = register_int_counter!( 31 | "mollysocket_pushs", 32 | "Push messages sent to UnifiedPush endpoint" 33 | )?; 34 | 35 | Ok(Self { 36 | connections, 37 | forbiddens, 38 | reconnections, 39 | messages, 40 | pushs, 41 | }) 42 | } 43 | } 44 | 45 | pub trait MountMetrics { 46 | fn mount_metrics<'a, B>(self, base: B, metrics: &Metrics) -> Self 47 | where 48 | B: TryInto> + Clone + Display, 49 | B::Error: Display; 50 | } 51 | 52 | impl MountMetrics for Rocket { 53 | fn mount_metrics<'a, B>(self, base: B, metrics: &Metrics) -> Self 54 | where 55 | B: TryInto> + Clone + Display, 56 | B::Error: Display, 57 | { 58 | let prometheus = PrometheusMetrics::new(); 59 | let prom_registry = prometheus.registry(); 60 | prom_registry 61 | .register(Box::new(metrics.connections.clone())) 62 | .unwrap(); 63 | prom_registry 64 | .register(Box::new(metrics.forbiddens.clone())) 65 | .unwrap(); 66 | prom_registry 67 | .register(Box::new(metrics.reconnections.clone())) 68 | .unwrap(); 69 | prom_registry 70 | .register(Box::new(metrics.messages.clone())) 71 | .unwrap(); 72 | prom_registry 73 | .register(Box::new(metrics.pushs.clone())) 74 | .unwrap(); 75 | 76 | self.attach(prometheus.clone()).mount(base, prometheus) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/server/web.rs: -------------------------------------------------------------------------------- 1 | use crate::{config, db::Connection, qrcode, utils::ping, vapid}; 2 | use eyre::Result; 3 | use html::get_index; 4 | use rocket::{ 5 | get, post, 6 | response::{content::RawHtml, Responder}, 7 | routes, 8 | serde::{json::Json, Deserialize, Serialize}, 9 | }; 10 | use std::{collections::HashMap, env, str::FromStr}; 11 | use url::Url; 12 | 13 | use super::{metrics::MountMetrics, DB, METRICS, NEW_CO_TX}; 14 | 15 | mod html; 16 | 17 | #[derive(Serialize)] 18 | struct ApiResponse { 19 | mollysocket: HashMap, 20 | } 21 | 22 | #[derive(Debug, Deserialize)] 23 | struct ConnectionData { 24 | pub uuid: String, 25 | pub device_id: u32, 26 | pub password: String, 27 | pub endpoint: String, 28 | pub ping: Option, 29 | } 30 | 31 | /** 32 | Order of the status: 33 | 1. If the connection is refused: [Refused] 34 | 2. If this is a new connection: [New] 35 | 3. If the credentials are updated: [CredsUpdated] 36 | 4. If the connection is known and forbidden: [Forbidden] 37 | 5. If the endpoint is updated: [EndpointUpdated] 38 | 6. Else: [Running] 39 | 40 | If an error occured during the process: [InternalError] 41 | */ 42 | #[derive(Debug)] 43 | enum RegistrationStatus { 44 | /// The connection is refused 45 | Refused(RefusedStatus), 46 | /// This is a new connection 47 | New, 48 | /// The registration credentials are updated, 49 | CredsUpdated(CredsUpdateStatus), 50 | /// The credentials are the same, and the connection in forbidden 51 | Forbidden, 52 | /// The endpoint is updated 53 | EndpointUpdated, 54 | /// The credentials and the endpoint are the same, and the connection in healthy 55 | Running, 56 | /// An error occurred 57 | InternalError, 58 | } 59 | 60 | // This is used to send the reponse to Molly 61 | impl From for String { 62 | fn from(s: RegistrationStatus) -> Self { 63 | match s { 64 | RegistrationStatus::Refused(s) => s.into(), 65 | RegistrationStatus::New 66 | | RegistrationStatus::EndpointUpdated 67 | | RegistrationStatus::Running => "ok", 68 | RegistrationStatus::CredsUpdated(s) => s.into(), 69 | RegistrationStatus::Forbidden => "forbidden", 70 | RegistrationStatus::InternalError => "internal_error", 71 | } 72 | .into() 73 | } 74 | } 75 | 76 | /** 77 | Order of the status: 78 | 1. If UUID is forbidden [InvalidUuid] 79 | 2. If endpoint is forbidden [InvalidEndpoint] 80 | */ 81 | #[derive(Debug)] 82 | enum RefusedStatus { 83 | /// The account id is forbidden 84 | InvalidUuid, 85 | /// The endpoint is forbidden 86 | InvalidEndpoint, 87 | } 88 | 89 | impl Into<&str> for RefusedStatus { 90 | fn into(self) -> &'static str { 91 | match &self { 92 | RefusedStatus::InvalidUuid => "invalid_uuid", 93 | RefusedStatus::InvalidEndpoint => "invalid_endpoint", 94 | } 95 | } 96 | } 97 | 98 | /** 99 | Order of the status: 100 | 1. If the current connection is healthy [Ignore] 101 | 2. Else [Ok] 102 | */ 103 | #[derive(Debug)] 104 | enum CredsUpdateStatus { 105 | /// The credentials are updated but the current connection is not forbidden 106 | Ignore, 107 | /// The credentials are updated 108 | Ok, 109 | } 110 | 111 | impl Into<&str> for CredsUpdateStatus { 112 | fn into(self) -> &'static str { 113 | match &self { 114 | CredsUpdateStatus::Ok => "ok", 115 | // If someone tries to register new creds for an healthy connection, 116 | // we return an internal_error. 117 | CredsUpdateStatus::Ignore => "internal_error", 118 | } 119 | } 120 | } 121 | 122 | struct Req<'r> { 123 | ua: &'r str, 124 | uri: Option, 125 | airgapped: bool, 126 | } 127 | 128 | #[rocket::async_trait] 129 | impl<'r> rocket::request::FromRequest<'r> for Req<'r> { 130 | type Error = (); 131 | 132 | async fn from_request( 133 | request: &'r rocket::request::Request<'_>, 134 | ) -> rocket::request::Outcome, ()> { 135 | let ua = request.headers().get_one("user-agent").unwrap_or(""); 136 | let airgapped = request.query_value::<&str>("airgapped").is_some(); 137 | let origin = request 138 | .headers() 139 | .get_one("X-Original-URL") 140 | .map(|h| rocket::http::uri::Origin::parse(h).ok()) 141 | .flatten() 142 | .unwrap_or_else(|| request.uri().clone()); 143 | let path = origin.path().as_str(); 144 | // We assume this is https 145 | let uri = request 146 | .host() 147 | .map(|h| format!("https://{}{}", h.to_string(), path)); 148 | rocket::request::Outcome::Success(Req { ua, uri, airgapped }) 149 | } 150 | } 151 | 152 | enum Resp { 153 | Json(Json), 154 | Html(RawHtml), 155 | } 156 | 157 | impl<'r> Responder<'r, 'r> for Resp { 158 | fn respond_to(self, request: &'r rocket::Request<'_>) -> rocket::response::Result<'r> { 159 | match self { 160 | Resp::Json(r) => r.respond_to(request), 161 | Resp::Html(r) => r.respond_to(request), 162 | } 163 | } 164 | } 165 | 166 | #[get("/")] 167 | fn index(req: Req) -> Resp { 168 | if req.ua.contains("Signal-Android") { 169 | Resp::Json(gen_api_rep(HashMap::new())) 170 | } else { 171 | Resp::Html(RawHtml(get_index(req.airgapped, req.uri.as_deref()))) 172 | } 173 | } 174 | 175 | #[get("/discover")] 176 | fn discover() -> Json { 177 | gen_api_rep(HashMap::new()) 178 | } 179 | 180 | #[post("/", format = "application/json", data = "")] 181 | async fn register(co_data: Json) -> Json { 182 | let mut status = registration_status(&co_data).await; 183 | // Any error will be turned into internal_error 184 | match status { 185 | RegistrationStatus::New => handle_new_connection(&co_data, true, false).await, 186 | RegistrationStatus::CredsUpdated(CredsUpdateStatus::Ok) => { 187 | handle_new_connection(&co_data, true, true).await 188 | } 189 | RegistrationStatus::EndpointUpdated => { 190 | handle_new_connection(&co_data, co_data.ping.unwrap_or(false), false).await 191 | } 192 | RegistrationStatus::Running => { 193 | // If the connection is "Running" then the device creds still exists, 194 | // if the user register on another server or delete the linked device, 195 | // then the connection ends with a 403 Forbidden 196 | // If the connection is for an invalid uuid or an error occured : we 197 | // have nothing to do, except if the request ask for a ping 198 | DB.update_last_registration(&co_data.uuid).unwrap(); 199 | if co_data.ping.unwrap_or(false) { 200 | ping_endpoint(&co_data).await; 201 | } 202 | Ok(()) 203 | } 204 | // Else, do nothing 205 | _ => Ok(()), 206 | } 207 | .unwrap_or_else(|_| status = RegistrationStatus::InternalError); 208 | 209 | log::debug!("Status: {status:?}"); 210 | gen_api_rep(HashMap::from([( 211 | String::from("status"), 212 | String::from(status), 213 | )])) 214 | } 215 | 216 | /** 217 | Add new a connection. Ping the endpoint if [ping], 218 | decrease forbidden connections in metrics if 219 | [dec_forbidden] 220 | */ 221 | async fn handle_new_connection( 222 | co_data: &Json, 223 | ping: bool, 224 | dec_forbidden: bool, 225 | ) -> Result<()> { 226 | if new_connection(&co_data).is_ok() { 227 | log::debug!("Connection successfully added."); 228 | if ping { 229 | ping_endpoint(&co_data).await; 230 | } 231 | if dec_forbidden { 232 | METRICS.forbiddens.dec(); 233 | } 234 | } else { 235 | log::debug!("Could not start new connection"); 236 | } 237 | Ok(()) 238 | } 239 | 240 | fn new_connection(co_data: &Json) -> Result<()> { 241 | let co = Connection::new( 242 | co_data.uuid.clone(), 243 | co_data.device_id, 244 | co_data.password.clone(), 245 | co_data.endpoint.clone(), 246 | ); 247 | DB.add(&co).unwrap(); 248 | if let Some(tx) = &*NEW_CO_TX.lock().unwrap() { 249 | let _ = tx.unbounded_send(co); 250 | } 251 | Ok(()) 252 | } 253 | 254 | async fn ping_endpoint(co_data: &ConnectionData) { 255 | if let Err(e) = ping(Url::from_str(&co_data.endpoint).unwrap()).await { 256 | log::warn!( 257 | "Cound not ping the connection (uuid={}): {e:?}", 258 | &co_data.uuid 259 | ); 260 | } 261 | } 262 | 263 | async fn registration_status(co_data: &ConnectionData) -> RegistrationStatus { 264 | let endpoint_valid = config::is_endpoint_valid(&co_data.endpoint).await; 265 | let uuid_valid = config::is_uuid_valid(&co_data.uuid); 266 | 267 | if !uuid_valid { 268 | return RegistrationStatus::Refused(RefusedStatus::InvalidUuid); 269 | } 270 | 271 | if !endpoint_valid { 272 | return RegistrationStatus::Refused(RefusedStatus::InvalidEndpoint); 273 | } 274 | 275 | let co = match DB.get(&co_data.uuid) { 276 | Ok(co) => co, 277 | Err(_) => { 278 | return RegistrationStatus::New; 279 | } 280 | }; 281 | 282 | if co.device_id == co_data.device_id && co.password == co_data.password { 283 | // Credentials are not updated 284 | if co.forbidden { 285 | RegistrationStatus::Forbidden 286 | } else if co.endpoint != co_data.endpoint { 287 | RegistrationStatus::EndpointUpdated 288 | } else { 289 | RegistrationStatus::Running 290 | } 291 | } else { 292 | // We return CredsUpdated only if the current connection is forbidden. 293 | // So it is impossible for someone to update a healthy connection 294 | // without the linked device password. 295 | if co.forbidden { 296 | RegistrationStatus::CredsUpdated(CredsUpdateStatus::Ok) 297 | } else { 298 | RegistrationStatus::CredsUpdated(CredsUpdateStatus::Ignore) 299 | } 300 | } 301 | } 302 | 303 | fn gen_api_rep(mut map: HashMap) -> Json { 304 | map.insert( 305 | String::from("version"), 306 | env!("CARGO_PKG_VERSION").to_string(), 307 | ); 308 | Json(ApiResponse { mollysocket: map }) 309 | } 310 | 311 | pub async fn launch() { 312 | if !config::should_start_webserver() { 313 | log::warn!("The web server is disabled, making mollysocket run in an air gapped mode. With this clients are less easy to set up and push might break."); 314 | log_qr_code(); 315 | return; 316 | } 317 | 318 | let rocket_cfg = rocket::Config::figment() 319 | .merge(("address", config::get_host())) 320 | .merge(("port", config::get_port())); 321 | 322 | let _ = rocket::build() 323 | .configure(rocket_cfg) 324 | .mount("/", routes![index, discover, register]) 325 | .mount_metrics("/metrics", &METRICS) 326 | .launch() 327 | .await; 328 | } 329 | 330 | fn log_qr_code() { 331 | match qrcode::gen_url_airgapped() { 332 | Ok(url) => { 333 | let qr_code = qrcode::url_to_printable_qr(&url); 334 | log::error!("Use the following QRcode: \n{}", qr_code); 335 | } 336 | Err(e) => { 337 | if let Some(vapid::Error::VapidKeyError) = e.downcast_ref::() { 338 | log::error!("VAPID key not found. Configure a VAPID key: https://github.com/mollyim/mollysocket?tab=readme-ov-file#vapid-key") 339 | } 340 | } 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /src/server/web/html.rs: -------------------------------------------------------------------------------- 1 | use crate::{qrcode, vapid}; 2 | 3 | macro_rules! index { 4 | ($v:expr) => { 5 | format!( 6 | r#" 7 | 8 | 9 | 10 | MollySocket 11 | 12 | 13 |

MollySocket

14 | {} 15 |

Version {}

16 | 32 | 33 | 34 | "#, 35 | $v, 36 | env!("CARGO_PKG_VERSION") 37 | ) 38 | }; 39 | } 40 | 41 | pub fn get_index(airgapped: bool, ms_url: Option<&str>) -> String { 42 | let intro = qrcode::INTRO; 43 | let url = if airgapped { 44 | qrcode::gen_url_airgapped() 45 | } else { 46 | let ms_url = match ms_url { 47 | Some(u) => u, 48 | None => return no_url(), 49 | }; 50 | qrcode::gen_url(ms_url) 51 | }; 52 | 53 | let url = match url { 54 | Ok(u) => u, 55 | Err(e) => { 56 | if let Some(vapid::Error::VapidKeyError) = e.downcast_ref::() { 57 | return no_vapid(); 58 | } 59 | return generic_error(); 60 | } 61 | }; 62 | let qr = qrcode::url_to_svg_qr(&url); 63 | 64 | if airgapped { 65 | index!(format!( 66 | r#" 67 |

⚠️This will configure your server in air gapped mode⚠️
68 | Molly won't be able to update push information if necessary.
69 | You can also keep a screenshot of this QR code in case you need to reconfigure your server without having access to it.

70 |

{intro}

71 | 72 |
73 | 74 | {qr} 75 |
76 |

Wish to use with the webserver?

77 | "#, 78 | )) 79 | } else { 80 | index!(format!( 81 | r#" 82 |

{intro}

83 | 84 |
85 | {qr} 86 |
87 |

Wish to use in airgapped mode?

88 | "#, 89 | )) 90 | } 91 | } 92 | 93 | fn no_vapid() -> String { 94 | index!("

VAPID Key not found. Configure a VAPID key and try again.

") 95 | } 96 | 97 | fn no_url() -> String { 98 | index!("

URL not found. The request seems to be incorrectly formatted.

") 99 | } 100 | 101 | fn generic_error() -> String { 102 | index!("

An error occurred. You should check the server logs.

") 103 | } 104 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use eyre::Result; 2 | use rocket::serde::json::json; 3 | use url::Url; 4 | 5 | pub mod post_allowed; 6 | 7 | pub fn anonymize_url(url_in: &str) -> String { 8 | let mut mut_url = url::Url::parse(url_in).unwrap(); 9 | mut_url.set_host(Some("fake.domain.tld")).unwrap(); 10 | mut_url.into() 11 | } 12 | 13 | pub async fn ping(url: Url) -> Result { 14 | let res = post_allowed::post_allowed(url, &json!({"test":true}), Some("test")).await?; 15 | res.error_for_status_ref()?; 16 | Ok(res) 17 | } 18 | -------------------------------------------------------------------------------- /src/utils/post_allowed.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use eyre::{eyre, Result}; 3 | use lazy_static::lazy_static; 4 | use reqwest::dns::Addrs; 5 | use reqwest::{dns::Resolve, redirect::Policy}; 6 | use serde::Serialize; 7 | use std::net; 8 | use std::{ 9 | fmt::{Display, Formatter}, 10 | iter, 11 | net::{IpAddr, Ipv4Addr, SocketAddr}, 12 | sync::Arc, 13 | }; 14 | use trust_dns_resolver::{lookup_ip::LookupIp, TokioAsyncResolver}; 15 | use url::{Host, Url}; 16 | 17 | use crate::{config, vapid}; 18 | 19 | lazy_static! { 20 | static ref RESOLVER: TokioAsyncResolver = TokioAsyncResolver::tokio_from_system_conf().unwrap(); 21 | } 22 | 23 | #[derive(Debug)] 24 | enum Error { 25 | SchemeNotAllowed, 26 | HostNotAllowed, 27 | } 28 | 29 | impl Display for Error { 30 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 31 | write!(f, "{:?}", self) 32 | } 33 | } 34 | 35 | impl std::error::Error for Error {} 36 | 37 | struct ResolveNothing; 38 | 39 | impl Resolve for ResolveNothing { 40 | fn resolve(&self, _: reqwest::dns::Name) -> reqwest::dns::Resolving { 41 | let addrs = Box::new(iter::once(net::SocketAddr::new( 42 | IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 43 | 0, 44 | ))) as Addrs; 45 | Box::pin(futures_util::future::ready(Ok(addrs))) 46 | } 47 | } 48 | 49 | pub async fn post_allowed( 50 | url: Url, 51 | body: &T, 52 | topic: Option<&str>, 53 | ) -> Result { 54 | let port = match url.port() { 55 | Some(p) => p, 56 | None if url.scheme() == "http" => 80, 57 | None if url.scheme() == "https" => 443, 58 | _ => return Err(eyre!(Error::SchemeNotAllowed)), 59 | }; 60 | 61 | let client = if config::is_endpoint_allowed_by_user(&url) { 62 | reqwest::ClientBuilder::new().redirect(Policy::none()) 63 | } else { 64 | let resolved_socket_addrs = url 65 | .resolve_allowed() 66 | .await? 67 | .into_iter() 68 | .map(|ip| SocketAddr::new(ip, port)) 69 | .collect::>(); 70 | 71 | if resolved_socket_addrs.is_empty() { 72 | log::info!( 73 | "Ignoring request to {}: no allowed ip", 74 | url.host_str().unwrap_or("No host") 75 | ); 76 | return Err(eyre!(Error::HostNotAllowed)); 77 | } 78 | 79 | reqwest::ClientBuilder::new() 80 | .redirect(Policy::none()) 81 | .dns_resolver(Arc::new(ResolveNothing)) 82 | .resolve_to_addrs(url.host_str().unwrap(), &resolved_socket_addrs) 83 | } 84 | .build() 85 | .unwrap(); 86 | 87 | // That's OK to generate a new VAPID header for each request 88 | // It doesn't do too many calculations, and we push at most once per seconde. 89 | let vapid = vapid::get_vapid_header(url.origin()).ok(); 90 | 91 | let mut builder = client 92 | .post(url) 93 | .header("TTL", "2592000") // 30 days 94 | .header("Content-Encoding", "aes128gcm") // Fake this encoding to be web push compliant 95 | .header("Urgency", "high"); 96 | builder = if let Some(topic) = topic { 97 | builder.header("Topic", topic) // Should override previous push messages with same topic 98 | } else { 99 | builder 100 | }; 101 | builder = if let Some(vapid) = vapid { 102 | builder.header("Authorization", vapid) 103 | } else { 104 | builder 105 | }; 106 | Ok(builder.json(&body).send().await?) 107 | } 108 | 109 | #[async_trait] 110 | pub trait ResolveAllowed { 111 | async fn resolve_allowed(&self) -> Result>; 112 | } 113 | 114 | #[async_trait] 115 | impl ResolveAllowed for Url { 116 | async fn resolve_allowed(&self) -> Result> { 117 | if ["http", "https"].contains(&self.scheme()) { 118 | self.host() 119 | .ok_or(Error::HostNotAllowed)? 120 | .resolve_allowed() 121 | .await 122 | } else { 123 | Err(eyre!(Error::SchemeNotAllowed)) 124 | } 125 | } 126 | } 127 | 128 | #[async_trait] 129 | impl ResolveAllowed for Host<&str> { 130 | async fn resolve_allowed(&self) -> Result> { 131 | match self { 132 | Host::Domain(d) => { 133 | RESOLVER 134 | .lookup_ip(*d) 135 | .await 136 | .map_err(|_| Error::HostNotAllowed)? 137 | .resolve_allowed() 138 | .await 139 | } 140 | Host::Ipv4(ip) if ip_rfc::global_v4(ip) => Ok(vec![IpAddr::V4(*ip)]), 141 | Host::Ipv6(ip) if ip_rfc::global_v6(ip) => Ok(vec![IpAddr::V6(*ip)]), 142 | _ => Err(eyre!(Error::HostNotAllowed)), 143 | } 144 | } 145 | } 146 | 147 | #[async_trait] 148 | impl ResolveAllowed for LookupIp { 149 | async fn resolve_allowed(&self) -> Result> { 150 | Ok(self.iter().filter(ip_rfc::global).collect()) 151 | } 152 | } 153 | 154 | #[cfg(test)] 155 | mod tests { 156 | use rocket::serde::json::serde_json::json; 157 | 158 | use super::*; 159 | use std::str::FromStr; 160 | 161 | async fn len_from_str(url: &str) -> usize { 162 | Url::from_str(url) 163 | .unwrap() 164 | .resolve_allowed() 165 | .await 166 | .unwrap_or(vec![]) 167 | .len() 168 | } 169 | 170 | #[tokio::test] 171 | async fn test_post() { 172 | config::load_config(None); 173 | post_allowed( 174 | Url::from_str("https://httpbin.org/post").unwrap(), 175 | &json!({"urgent": true}), 176 | None, 177 | ) 178 | .await 179 | .unwrap(); 180 | } 181 | 182 | /* 183 | #[tokio::test] 184 | async fn test_post_localhost() { 185 | env::set_var("MOLLY_ALLOWED_ENDPOINTS", "[\"http://127.0.0.1:8001\"]"); 186 | env::set_var( 187 | "MOLLY_VAPID_PRIVKEY", 188 | "DSqYuWchrB6yIMYJtidvqANeRQic4uWy34afzZRsZnI", 189 | ); 190 | config::load_config(None); 191 | post_allowed( 192 | Url::from_str("http://127.0.0.1:8001/test").unwrap(), 193 | &json!({"urgent": true}), 194 | None, 195 | ) 196 | .await 197 | .unwrap(); 198 | }*/ 199 | 200 | #[tokio::test] 201 | async fn test_not_allowed() { 202 | config::load_config(None); 203 | assert_eq!(len_from_str("unix://signal.org").await, 0); 204 | assert_eq!(len_from_str("http://127.1").await, 0); 205 | assert_eq!(len_from_str("http://localhost").await, 0); 206 | assert_eq!(len_from_str("http://[::1]").await, 0); 207 | assert_eq!(len_from_str("http://10.10.1.1").await, 0); 208 | assert_eq!(len_from_str("http://[fc01::2]").await, 0); 209 | } 210 | 211 | #[tokio::test] 212 | async fn test_allowed() { 213 | config::load_config(None); 214 | assert!(len_from_str("http://signal.org").await.gt(&0)); 215 | assert!(len_from_str("http://signal.org:8080").await.gt(&0)); 216 | assert!(len_from_str("https://signal.org").await.gt(&0)); 217 | assert!(len_from_str("http://18.244.114.115").await.gt(&0)); 218 | assert!( 219 | len_from_str("http://[2600:9000:2550:ae00:13:5d53:5740:93a1]") 220 | .await 221 | .gt(&0) 222 | ); 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /src/vapid.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | fmt::{Display, Formatter}, 4 | ops::Add, 5 | sync::{Arc, Mutex}, 6 | time::{Duration, Instant}, 7 | }; 8 | 9 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; 10 | use eyre::{eyre, Result}; 11 | use jwt_simple::{ 12 | self, 13 | algorithms::{ECDSAP256KeyPairLike, ECDSAP256PublicKeyLike, ES256KeyPair}, 14 | claims::Claims, 15 | }; 16 | use lazy_static::lazy_static; 17 | use openssl::{ 18 | ec::{EcGroup, EcKey}, 19 | nid::Nid, 20 | }; 21 | 22 | use crate::config; 23 | 24 | lazy_static! { 25 | static ref KEY: Option = get_signer_from_conf().ok(); 26 | /** Cache of VAPID keys */ 27 | static ref VAPID_CACHE: Arc>> = Arc::new(Mutex::new(HashMap::new())); 28 | } 29 | 30 | const DURATION_VAPID: u64 = 4500; /* 1h15 */ 31 | const DURATION_VAPID_CACHE: u64 = 3600; /* 1h */ 32 | 33 | /** 34 | Wrapper containing the signer and the associated public key. 35 | */ 36 | struct SignerWithPubKey { 37 | signer: ES256KeyPair, 38 | pubkey: String, 39 | } 40 | 41 | struct VapidCache { 42 | header: String, 43 | expire: Instant, 44 | } 45 | 46 | #[derive(Debug)] 47 | pub enum Error { 48 | VapidKeyError, 49 | } 50 | 51 | impl Display for Error { 52 | fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { 53 | // We have a single kind of error: VapidKeyError 54 | write!(f, "VAPID key is probably missing. See https://github.com/mollyim/mollysocket?tab=readme-ov-file#vapid-key") 55 | } 56 | } 57 | 58 | impl std::error::Error for Error {} 59 | 60 | pub fn get_vapid_pubkey() -> Result<&'static str> { 61 | let key = KEY.as_ref().ok_or(Error::VapidKeyError)?; 62 | Ok(&key.pubkey) 63 | } 64 | 65 | /** 66 | Generate VAPID header for origin. 67 | */ 68 | pub fn get_vapid_header(origin: url::Origin) -> Result { 69 | let key = KEY.as_ref().ok_or(Error::VapidKeyError)?; 70 | if let Some(h) = get_vapid_header_from_cache(&origin) { 71 | return Ok(h); 72 | } 73 | gen_vapid_header_with_key(origin, key) 74 | } 75 | 76 | /** 77 | Get VAPID header from cache if not expire 78 | */ 79 | fn get_vapid_header_from_cache(origin: &url::Origin) -> Option { 80 | let origin_str = origin.unicode_serialization(); 81 | let now = Instant::now(); 82 | let cache = VAPID_CACHE.lock().unwrap(); 83 | if let Some(c) = cache.get(&origin_str) { 84 | if c.expire > now { 85 | log::debug!("Found VAPID from cache"); 86 | Some(c.header.clone()) 87 | } else { 88 | log::debug!("VAPID from cache has expired"); 89 | None 90 | } 91 | } else { 92 | None 93 | } 94 | } 95 | 96 | fn add_vapid_header_to_cache(origin_str: &str, header: &str) { 97 | let mut cache = VAPID_CACHE.lock().unwrap(); 98 | cache.insert( 99 | origin_str.into(), 100 | VapidCache { 101 | header: header.into(), 102 | expire: Instant::now().add(Duration::from_secs(DURATION_VAPID_CACHE)), 103 | }, 104 | ); 105 | } 106 | 107 | fn gen_vapid_header_with_key(origin: url::Origin, key: &SignerWithPubKey) -> Result { 108 | let origin_str = origin.unicode_serialization(); 109 | let claims = Claims::create(jwt_simple::prelude::Duration::from_secs(DURATION_VAPID)) 110 | .with_audience(&origin_str) 111 | .with_subject("https://github.com/mollyim/mollysocket"); 112 | let token = key.signer.sign(claims).unwrap(); 113 | 114 | let header = format!("vapid t={},k={}", token.as_str(), &key.pubkey); 115 | add_vapid_header_to_cache(&origin_str, &header); 116 | Ok(header) 117 | } 118 | 119 | /** 120 | Get [SignerWithPubKey] from the config private key. 121 | */ 122 | fn get_signer_from_conf() -> Result { 123 | match config::get_vapid_privkey() { 124 | Some(k) => get_signer(k), 125 | None => Err(eyre!(Error::VapidKeyError)), 126 | } 127 | } 128 | 129 | /** 130 | Get [SignerWithPubKey] from the private key. 131 | */ 132 | fn get_signer(private_bytes: &str) -> Result { 133 | let private_key_bytes = URL_SAFE_NO_PAD.decode(private_bytes).unwrap(); 134 | let size = private_key_bytes.len(); 135 | if size != 32 { 136 | if size == 0 { 137 | log::warn!("No VAPID key was provided.") 138 | } else { 139 | log::warn!( 140 | "The private key has an unexpected size: {}, expected 32.", 141 | size 142 | ) 143 | } 144 | return Err(eyre!(Error::VapidKeyError)); 145 | } 146 | let kp = ES256KeyPair::from_bytes(&private_key_bytes).unwrap(); 147 | let pubkey = URL_SAFE_NO_PAD.encode(kp.public_key().public_key().to_bytes_uncompressed()); 148 | 149 | log::info!("VAPID public key: {:?}", pubkey); 150 | Ok(SignerWithPubKey { signer: kp, pubkey }) 151 | } 152 | 153 | /** 154 | Generate a new VAPID key. 155 | */ 156 | pub fn gen_vapid_key() -> String { 157 | let key = EcKey::generate(&EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap()); 158 | URL_SAFE_NO_PAD.encode(key.unwrap().private_key().to_vec()) 159 | } 160 | 161 | #[cfg(test)] 162 | mod tests { 163 | 164 | use super::*; 165 | 166 | const TEST_PRIVKEY: &str = "DSqYuWchrB6yIMYJtidvqANeRQic4uWy34afzZRsZnI"; 167 | const TEST_PUBKEY: &str = 168 | "BOniQ9xHBPNY9gnQW4o-16vHqOb40pEIMifyUdFsxAgyzVkFMguxw0QrdbZcq8hRjN2zpeInRvKVPlkzABvuTnI"; 169 | 170 | /** 171 | Test [get_signer] returns the right public key. 172 | */ 173 | #[test] 174 | fn test_signer_pubkey() { 175 | assert_eq!(get_signer(TEST_PRIVKEY).unwrap().pubkey, (TEST_PUBKEY)) 176 | } 177 | 178 | /** 179 | Test [gen_vapid_key] generate a key in the right format. 180 | */ 181 | #[test] 182 | fn test_gen_vapid_key() { 183 | assert_eq!(get_signer(&gen_vapid_key()).unwrap().pubkey.len(), 87); 184 | } 185 | 186 | /** 187 | Test vapid with a wrong key 188 | */ 189 | #[test] 190 | fn test_wrong_vapid() { 191 | assert!(get_signer(TEST_PUBKEY).is_err()); 192 | assert!(get_signer("").is_err()); 193 | } 194 | 195 | /** 196 | To verify the signature with another tool. This must be run with --nocapture: 197 | `cargo test vapid_other_tool -- -nocapture` 198 | */ 199 | #[test] 200 | fn test_vapid_other_tool() { 201 | let signer = get_signer(&gen_vapid_key()).unwrap(); 202 | let pubkey = signer.signer.public_key().to_pem().unwrap(); 203 | let url = url::Url::parse("https://example.tld").unwrap(); 204 | println!("PUB: \n{}", pubkey); 205 | println!( 206 | "header: {}", 207 | gen_vapid_header_with_key(url.origin(), &signer).unwrap() 208 | ); 209 | } 210 | 211 | /* The following example depends on the config initialization 212 | /** 213 | Test vapid from conf 214 | */ 215 | #[test] 216 | fn test_vapid_from_conf() { 217 | let key = gen_vapid_key(); 218 | env::set_var("MOLLY_VAPID_PRIVKEY", &key); 219 | config::load_config(None); 220 | assert_eq!( 221 | get_signer_from_conf().unwrap().pubkey, 222 | get_signer(&key).unwrap().pubkey 223 | ) 224 | } 225 | 226 | /** 227 | Test unset vapid from conf 228 | */ 229 | //#[test] 230 | fn test_no_vapid_from_conf() { 231 | env::remove_var("MOLLY_VAPID_PRIVKEY"); 232 | config::load_config(None); 233 | let res = match get_signer_from_conf() { 234 | Ok(_) => false, 235 | Err(_) => true, 236 | }; 237 | assert_eq!(res, true); 238 | } 239 | 240 | */ 241 | } 242 | -------------------------------------------------------------------------------- /src/ws.rs: -------------------------------------------------------------------------------- 1 | mod proto_signalservice; 2 | mod proto_websocketresources; 3 | mod signalwebsocket; 4 | mod tls; 5 | mod websocket_connection; 6 | 7 | pub use signalwebsocket::SignalWebSocket; 8 | -------------------------------------------------------------------------------- /src/ws/certs/signal-messenger.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIF2zCCA8OgAwIBAgIUAMHz4g60cIDBpPr1gyZ/JDaaPpcwDQYJKoZIhvcNAQEL 3 | BQAwdTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcT 4 | DU1vdW50YWluIFZpZXcxHjAcBgNVBAoTFVNpZ25hbCBNZXNzZW5nZXIsIExMQzEZ 5 | MBcGA1UEAxMQU2lnbmFsIE1lc3NlbmdlcjAeFw0yMjAxMjYwMDQ1NTFaFw0zMjAx 6 | MjQwMDQ1NTBaMHUxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYw 7 | FAYDVQQHEw1Nb3VudGFpbiBWaWV3MR4wHAYDVQQKExVTaWduYWwgTWVzc2VuZ2Vy 8 | LCBMTEMxGTAXBgNVBAMTEFNpZ25hbCBNZXNzZW5nZXIwggIiMA0GCSqGSIb3DQEB 9 | AQUAA4ICDwAwggIKAoICAQDEecifxMHHlDhxbERVdErOhGsLO08PUdNkATjZ1kT5 10 | 1uPf5JPiRbus9F4J/GgBQ4ANSAjIDZuFY0WOvG/i0qvxthpW70ocp8IjkiWTNiA8 11 | 1zQNQdCiWbGDU4B1sLi2o4JgJMweSkQFiyDynqWgHpw+KmvytCzRWnvrrptIfE4G 12 | PxNOsAtXFbVH++8JO42IaKRVlbfpe/lUHbjiYmIpQroZPGPY4Oql8KM3o39ObPnT 13 | o1WoM4moyOOZpU3lV1awftvWBx1sbTBL02sQWfHRxgNVF+Pj0fdDMMFdFJobArrL 14 | VfK2Ua+dYN4pV5XIxzVarSRW73CXqQ+2qloPW/ynpa3gRtYeGWV4jl7eD0PmeHpK 15 | OY78idP4H1jfAv0TAVeKpuB5ZFZ2szcySxrQa8d7FIf0kNJe9gIRjbQ+XrvnN+ZZ 16 | vj6d+8uBJq8LfQaFhlVfI0/aIdggScapR7w8oLpvdflUWqcTLeXVNLVrg15cEDwd 17 | lV8PVscT/KT0bfNzKI80qBq8LyRmauAqP0CDjayYGb2UAabnhefgmRY6aBE5mXxd 18 | byAEzzCS3vDxjeTD8v8nbDq+SD6lJi0i7jgwEfNDhe9XK50baK15Udc8Cr/ZlhGM 19 | jNmWqBd0jIpaZm1rzWA0k4VwXtDwpBXSz8oBFshiXs3FD6jHY2IhOR3ppbyd4qRU 20 | pwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV 21 | HQ4EFgQUtfNLxuXWS9DlgGuMUMNnW7yx83EwHwYDVR0jBBgwFoAUtfNLxuXWS9Dl 22 | gGuMUMNnW7yx83EwDQYJKoZIhvcNAQELBQADggIBABUeiryS0qjykBN75aoHO9bV 23 | PrrX+DSJIB9V2YzkFVyh/io65QJMG8naWVGOSpVRwUwhZVKh3JVp/miPgzTGAo7z 24 | hrDIoXc+ih7orAMb19qol/2Ha8OZLa75LojJNRbZoCR5C+gM8C+spMLjFf9k3JVx 25 | dajhtRUcR0zYhwsBS7qZ5Me0d6gRXD0ZiSbadMMxSw6KfKk3ePmPb9gX+MRTS63c 26 | 8mLzVYB/3fe/bkpq4RUwzUHvoZf+SUD7NzSQRQQMfvAHlxk11TVNxScYPtxXDyiy 27 | 3Cssl9gWrrWqQ/omuHipoH62J7h8KAYbr6oEIq+Czuenc3eCIBGBBfvCpuFOgckA 28 | XXE4MlBasEU0MO66GrTCgMt9bAmSw3TrRP12+ZUFxYNtqWluRU8JWQ4FCCPcz9pg 29 | MRBOgn4lTxDZG+I47OKNuSRjFEP94cdgxd3H/5BK7WHUz1tAGQ4BgepSXgmjzifF 30 | T5FVTDTl3ZnWUVBXiHYtbOBgLiSIkbqGMCLtrBtFIeQ7RRTb3L+IE9R0UB0cJB3A 31 | Xbf1lVkOcmrdu2h8A32aCwtr5S1fBF1unlG7imPmqJfpOMWa8yIF/KWVm29JAPq8 32 | Lrsybb0z5gg8w7ZblEuB9zOW9M3l60DXuJO6l7g+deV6P96rv2unHS8UlvWiVWDy 33 | 9qfgAJizyy3kqM4lOwBH 34 | -----END CERTIFICATE----- 35 | -------------------------------------------------------------------------------- /src/ws/proto_websocketresources.rs: -------------------------------------------------------------------------------- 1 | #[allow(clippy::derive_partial_eq_without_eq)] 2 | #[derive(Clone, PartialEq, ::prost::Message)] 3 | pub struct WebSocketRequestMessage { 4 | #[prost(string, optional, tag = "1")] 5 | pub verb: ::core::option::Option<::prost::alloc::string::String>, 6 | #[prost(string, optional, tag = "2")] 7 | pub path: ::core::option::Option<::prost::alloc::string::String>, 8 | #[prost(bytes = "vec", optional, tag = "3")] 9 | pub body: ::core::option::Option<::prost::alloc::vec::Vec>, 10 | #[prost(string, repeated, tag = "5")] 11 | pub headers: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, 12 | #[prost(uint64, optional, tag = "4")] 13 | pub id: ::core::option::Option, 14 | } 15 | #[allow(clippy::derive_partial_eq_without_eq)] 16 | #[derive(Clone, PartialEq, ::prost::Message)] 17 | pub struct WebSocketResponseMessage { 18 | #[prost(uint64, optional, tag = "1")] 19 | pub id: ::core::option::Option, 20 | #[prost(uint32, optional, tag = "2")] 21 | pub status: ::core::option::Option, 22 | #[prost(string, optional, tag = "3")] 23 | pub message: ::core::option::Option<::prost::alloc::string::String>, 24 | #[prost(string, repeated, tag = "5")] 25 | pub headers: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, 26 | #[prost(bytes = "vec", optional, tag = "4")] 27 | pub body: ::core::option::Option<::prost::alloc::vec::Vec>, 28 | } 29 | #[allow(clippy::derive_partial_eq_without_eq)] 30 | #[derive(Clone, PartialEq, ::prost::Message)] 31 | pub struct WebSocketMessage { 32 | #[prost(enumeration = "web_socket_message::Type", optional, tag = "1")] 33 | pub r#type: ::core::option::Option, 34 | #[prost(message, optional, tag = "2")] 35 | pub request: ::core::option::Option, 36 | #[prost(message, optional, tag = "3")] 37 | pub response: ::core::option::Option, 38 | } 39 | /// Nested message and enum types in `WebSocketMessage`. 40 | pub mod web_socket_message { 41 | #[derive( 42 | Clone, 43 | Copy, 44 | Debug, 45 | PartialEq, 46 | Eq, 47 | Hash, 48 | PartialOrd, 49 | Ord, 50 | ::prost::Enumeration 51 | )] 52 | #[repr(i32)] 53 | pub enum Type { 54 | Unknown = 0, 55 | Request = 1, 56 | Response = 2, 57 | } 58 | impl Type { 59 | /// String value of the enum field names used in the ProtoBuf definition. 60 | /// 61 | /// The values are not transformed in any way and thus are considered stable 62 | /// (if the ProtoBuf definition does not change) and safe for programmatic use. 63 | pub fn as_str_name(&self) -> &'static str { 64 | match self { 65 | Type::Unknown => "UNKNOWN", 66 | Type::Request => "REQUEST", 67 | Type::Response => "RESPONSE", 68 | } 69 | } 70 | /// Creates an enum from field names used in the ProtoBuf definition. 71 | pub fn from_str_name(value: &str) -> ::core::option::Option { 72 | match value { 73 | "UNKNOWN" => Some(Self::Unknown), 74 | "REQUEST" => Some(Self::Request), 75 | "RESPONSE" => Some(Self::Response), 76 | _ => None, 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/ws/signalwebsocket.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use eyre::Result; 3 | use futures_channel::mpsc; 4 | use prost::Message; 5 | use rocket::serde::json::serde_json::json; 6 | use std::{ 7 | sync::{Arc, Mutex}, 8 | time::{Duration, Instant}, 9 | }; 10 | use tokio::time; 11 | use tokio_tungstenite::tungstenite; 12 | 13 | use super::tls; 14 | use super::websocket_connection::WebSocketConnection; 15 | use super::{ 16 | proto_signalservice::Envelope, 17 | proto_websocketresources::{ 18 | web_socket_message::Type, WebSocketMessage, WebSocketRequestMessage, 19 | WebSocketResponseMessage, 20 | }, 21 | }; 22 | use crate::{config, utils::post_allowed::post_allowed}; 23 | 24 | const PUSH_TIMEOUT: Duration = Duration::from_secs(1); 25 | 26 | #[derive(Debug)] 27 | pub struct Channels { 28 | ws_tx: Option>, 29 | pub on_message_tx: Option>, 30 | pub on_push_tx: Option>, 31 | pub on_reconnection_tx: Option>, 32 | } 33 | 34 | impl Channels { 35 | fn none() -> Self { 36 | Self { 37 | ws_tx: None, 38 | on_message_tx: None, 39 | on_push_tx: None, 40 | on_reconnection_tx: None, 41 | } 42 | } 43 | } 44 | 45 | #[derive(Debug)] 46 | pub struct SignalWebSocket { 47 | creds: String, 48 | push_endpoint: url::Url, 49 | pub channels: Channels, 50 | push_instant: Arc>, 51 | last_keepalive: Arc>, 52 | } 53 | 54 | #[async_trait(?Send)] 55 | impl WebSocketConnection for SignalWebSocket { 56 | fn get_url(&self) -> &str { 57 | &config::get_ws_endpoint() 58 | } 59 | 60 | fn get_creds(&self) -> &str { 61 | &self.creds 62 | } 63 | 64 | fn get_websocket_tx(&self) -> &Option> { 65 | &self.channels.ws_tx 66 | } 67 | 68 | fn set_websocket_tx(&mut self, tx: Option>) { 69 | self.channels.ws_tx = tx; 70 | } 71 | 72 | fn get_last_keepalive(&self) -> Arc> { 73 | Arc::clone(&self.last_keepalive) 74 | } 75 | 76 | async fn on_message(&self, message: WebSocketMessage) { 77 | if let Some(type_int) = message.r#type { 78 | if let Ok(type_) = Type::try_from(type_int) { 79 | match type_ { 80 | Type::Response => self.on_response(message.response), 81 | Type::Request => self.on_request(message.request).await, 82 | _ => (), 83 | }; 84 | } 85 | } 86 | } 87 | } 88 | 89 | impl SignalWebSocket { 90 | pub fn new<'a, 'b: 'a>( 91 | uuid: &str, 92 | device_id: u32, 93 | password: &str, 94 | push_endpoint: &str, 95 | ) -> Result { 96 | let push_endpoint = url::Url::parse(&push_endpoint)?; 97 | Ok(Self { 98 | creds: format!("{}.{}:{}", uuid, device_id, password), 99 | push_endpoint, 100 | channels: Channels::none(), 101 | push_instant: Arc::new(Mutex::new( 102 | Instant::now().checked_sub(PUSH_TIMEOUT).unwrap(), 103 | )), 104 | last_keepalive: Arc::new(Mutex::new(Instant::now())), 105 | }) 106 | } 107 | 108 | pub async fn connection_loop(&mut self) -> Result<()> { 109 | let mut count = 0; 110 | loop { 111 | let instant = Instant::now(); 112 | { 113 | let mut keepalive = self.last_keepalive.lock().unwrap(); 114 | *keepalive = Instant::now(); 115 | } 116 | if let Err(e) = self.connect(tls::build_tls_connector()?).await { 117 | if let Some(tungstenite::Error::Http(resp)) = e.downcast_ref::() 118 | { 119 | if resp.status() == 403 { 120 | return Err(e); 121 | } 122 | } 123 | } 124 | if let Some(duration) = Instant::now().checked_duration_since(instant) { 125 | if duration > Duration::from_secs(60) { 126 | count = 0; 127 | } 128 | } 129 | if let Some(tx) = &self.channels.on_reconnection_tx { 130 | let _ = tx.unbounded_send(1); 131 | } 132 | count += 1; 133 | log::info!("Retrying to connect in {}0 seconds.", count); 134 | time::sleep(Duration::from_secs(count * 10)).await; 135 | } 136 | } 137 | 138 | fn on_response(&self, response: Option) { 139 | log::debug!("New response"); 140 | if response.is_some() { 141 | let mut keepalive = self.last_keepalive.lock().unwrap(); 142 | *keepalive = Instant::now(); 143 | } 144 | } 145 | 146 | /** 147 | * That's when we must send a notification 148 | */ 149 | async fn on_request(&self, request: Option) { 150 | log::debug!("New request"); 151 | if let Some(request) = request { 152 | if let Some(envelope) = self.request_to_envelope(request).await { 153 | if let Some(tx) = &self.channels.on_message_tx { 154 | let _ = tx.unbounded_send(1); 155 | } 156 | if self.waiting_timeout_reached() { 157 | if envelope.urgent() { 158 | self.send_push().await; 159 | } 160 | } else { 161 | log::debug!("The waiting timeout is not reached: the request is ignored."); 162 | } 163 | } 164 | } 165 | } 166 | 167 | /** 168 | * Extract [`Envelope`] from [`request`] and send response to server. 169 | */ 170 | async fn request_to_envelope(&self, request: WebSocketRequestMessage) -> Option { 171 | // dbg!(&request.path); 172 | let response = self.create_websocket_response(&request); 173 | // dbg!(&response); 174 | if self.is_signal_service_envelope(&request) { 175 | self.send_response(response).await; 176 | return match request.body { 177 | None => Some(Envelope { 178 | r#type: None, 179 | source_service_id: None, 180 | source_device: None, 181 | destination_service_id: None, 182 | timestamp: None, 183 | content: None, 184 | server_guid: None, 185 | server_timestamp: None, 186 | urgent: Some(false), 187 | updated_pni: None, 188 | story: None, 189 | reporting_token: None, 190 | }), 191 | Some(body) => Envelope::decode(&body[..]).ok(), 192 | }; 193 | } 194 | None 195 | } 196 | 197 | fn is_signal_service_envelope( 198 | &self, 199 | WebSocketRequestMessage { 200 | verb, 201 | path, 202 | body: _, 203 | headers: _, 204 | id: _, 205 | }: &WebSocketRequestMessage, 206 | ) -> bool { 207 | if let Some(verb) = verb { 208 | if let Some(path) = path { 209 | return verb.eq("PUT") && path.eq("/api/v1/message"); 210 | } 211 | } 212 | false 213 | } 214 | 215 | fn create_websocket_response( 216 | &self, 217 | request: &WebSocketRequestMessage, 218 | ) -> WebSocketResponseMessage { 219 | if self.is_signal_service_envelope(request) { 220 | return WebSocketResponseMessage { 221 | id: request.id, 222 | status: Some(200), 223 | message: Some(String::from("OK")), 224 | headers: Vec::new(), 225 | body: None, 226 | }; 227 | } 228 | WebSocketResponseMessage { 229 | id: request.id, 230 | status: Some(400), 231 | message: Some(String::from("Unknown")), 232 | headers: Vec::new(), 233 | body: None, 234 | } 235 | } 236 | 237 | async fn send_push(&self) { 238 | log::debug!("Sending the notification."); 239 | { 240 | let mut instant = self.push_instant.lock().unwrap(); 241 | *instant = Instant::now(); 242 | } 243 | 244 | let url = self.push_endpoint.clone(); 245 | let _ = post_allowed(url, &json!({"urgent": true}), Some("mollysocket")).await; 246 | if let Some(tx) = &self.channels.on_push_tx { 247 | let _ = tx.unbounded_send(1); 248 | } 249 | } 250 | 251 | fn waiting_timeout_reached(&self) -> bool { 252 | let instant = self.push_instant.lock().unwrap(); 253 | instant.elapsed() > PUSH_TIMEOUT 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /src/ws/tls.rs: -------------------------------------------------------------------------------- 1 | use native_tls::{Certificate, TlsConnector}; 2 | 3 | pub fn build_tls_connector() -> Result { 4 | let root_ca = include_bytes!("certs/signal-messenger.pem"); 5 | let root_ca = Certificate::from_pem(root_ca).unwrap(); 6 | let mut builder = TlsConnector::builder(); 7 | builder.disable_built_in_roots(true); 8 | builder.add_root_certificate(root_ca); 9 | builder.build() 10 | } 11 | 12 | #[cfg(test)] 13 | mod tests { 14 | use std::net::TcpStream; 15 | 16 | use super::*; 17 | 18 | #[test] 19 | fn connect_trusted_server() { 20 | let builder = build_tls_connector().unwrap(); 21 | let s = TcpStream::connect("chat.staging.signal.org:443").unwrap(); 22 | builder.connect("chat.staging.signal.org", s).unwrap(); 23 | } 24 | 25 | #[test] 26 | fn connect_untrusted_server() { 27 | let builder = build_tls_connector().unwrap(); 28 | let s = TcpStream::connect("signal.org:443").unwrap(); 29 | builder.connect("signal.org", s).unwrap_err(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/ws/websocket_connection.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use base64::{prelude::BASE64_STANDARD, Engine}; 3 | use eyre::Result; 4 | use futures_channel::mpsc; 5 | use futures_util::{pin_mut, select, FutureExt, SinkExt, StreamExt}; 6 | use native_tls::TlsConnector; 7 | use prost::Message; 8 | use std::{ 9 | sync::{Arc, Mutex}, 10 | time::{Duration, Instant, SystemTime, UNIX_EPOCH}, 11 | }; 12 | use tokio::time; 13 | use tokio_tungstenite::{ 14 | tungstenite::{self, ClientRequestBuilder}, 15 | Connector::NativeTls, 16 | }; 17 | 18 | use super::proto_websocketresources::{ 19 | web_socket_message::Type, WebSocketMessage, WebSocketRequestMessage, WebSocketResponseMessage, 20 | }; 21 | 22 | const KEEPALIVE: Duration = Duration::from_secs(30); 23 | const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(40); 24 | 25 | #[async_trait(?Send)] 26 | pub trait WebSocketConnection { 27 | fn get_url(&self) -> &str; 28 | /// return "login:password" 29 | fn get_creds(&self) -> &str; 30 | fn get_websocket_tx(&self) -> &Option>; 31 | fn set_websocket_tx(&mut self, tx: Option>); 32 | fn get_last_keepalive(&self) -> Arc>; 33 | async fn on_message(&self, message: WebSocketMessage); 34 | 35 | async fn connect(&mut self, tls_connector: TlsConnector) -> Result<()> { 36 | let request = ClientRequestBuilder::new(self.get_url().parse()?) 37 | .with_header("X-Signal-Agent", "\"OWA\"") 38 | .with_header( 39 | "Authorization", 40 | format!("Basic {}", BASE64_STANDARD.encode(self.get_creds())), 41 | ); 42 | 43 | let (ws_stream, _) = tokio_tungstenite::connect_async_tls_with_config( 44 | request, 45 | None, 46 | false, 47 | Some(NativeTls(tls_connector)), 48 | ) 49 | .await?; 50 | 51 | log::info!("WebSocket handshake has been successfully completed"); 52 | 53 | // Websocket I/O 54 | let (ws_write, ws_read) = ws_stream.split(); 55 | // channel to websocket ws_write 56 | let (tx, rx) = mpsc::unbounded(); 57 | // other channels: msg, keepalive, abort 58 | let (timer_tx, timer_rx) = mpsc::unbounded(); 59 | 60 | // Saving to socket Sender 61 | self.set_websocket_tx(Some(tx)); 62 | 63 | // handlers 64 | let to_ws_handle = rx.map(Ok).forward(ws_write).fuse(); 65 | 66 | let from_ws_handle = ws_read 67 | .for_each(|message| async { 68 | log::debug!("New message"); 69 | if let Ok(message) = message { 70 | self.handle_message(message).await; 71 | } 72 | }) 73 | .fuse(); 74 | 75 | let from_keepalive_handle = timer_rx 76 | .for_each(|_| async { self.send_keepalive().await }) 77 | .fuse(); 78 | 79 | let to_keepalive_handle = self.loop_keepalive(timer_tx).fuse(); 80 | 81 | pin_mut!( 82 | to_ws_handle, 83 | from_ws_handle, 84 | from_keepalive_handle, 85 | to_keepalive_handle 86 | ); 87 | 88 | // handle websocket 89 | select!( 90 | _ = to_ws_handle => log::warn!("Messages finished"), 91 | _ = from_ws_handle => log::warn!("Websocket finished"), 92 | _ = from_keepalive_handle => log::warn!("Keepalive finished"), 93 | _ = to_keepalive_handle => log::warn!("Keepalive finished"), 94 | ); 95 | Ok(()) 96 | } 97 | 98 | async fn handle_message(&self, message: tungstenite::Message) { 99 | let data = message.into_data(); 100 | let ws_message = match WebSocketMessage::decode(data) { 101 | Ok(msg) => msg, 102 | Err(e) => { 103 | log::error!("Failed to decode protobuf: {}", e); 104 | return; 105 | } 106 | }; 107 | self.on_message(ws_message).await; 108 | } 109 | 110 | async fn send_message(&self, message: WebSocketMessage) { 111 | if let Some(mut tx) = self.get_websocket_tx().as_ref() { 112 | let bytes = message.encode_to_vec(); 113 | tx.send(tungstenite::Message::binary(bytes)).await.unwrap(); 114 | } 115 | } 116 | 117 | async fn send_response(&self, response: WebSocketResponseMessage) { 118 | let message = WebSocketMessage { 119 | r#type: Some(Type::Response as i32), 120 | response: Some(response), 121 | request: None, 122 | }; 123 | self.send_message(message).await; 124 | } 125 | 126 | async fn send_keepalive(&self) { 127 | log::debug!("send_keepalive"); 128 | let message = WebSocketMessage { 129 | r#type: Some(Type::Request as i32), 130 | response: None, 131 | request: Some(WebSocketRequestMessage { 132 | verb: Some(String::from("GET")), 133 | path: Some(String::from("/v1/keepalive")), 134 | body: None, 135 | headers: Vec::new(), 136 | id: Some( 137 | SystemTime::now() 138 | .duration_since(UNIX_EPOCH) 139 | .unwrap() 140 | .as_millis() as u64, 141 | ), 142 | }), 143 | }; 144 | self.send_message(message).await; 145 | } 146 | 147 | async fn loop_keepalive(&self, timer_tx: mpsc::UnboundedSender) { 148 | // Get the ref of last_keepalive 149 | let last_keepalive = self.get_last_keepalive(); 150 | loop { 151 | // read last_keepalive 152 | if last_keepalive.lock().unwrap().elapsed() > KEEPALIVE_TIMEOUT { 153 | log::warn!("Did not receive the last keepalive: aborting."); 154 | break; 155 | } 156 | time::sleep(KEEPALIVE).await; 157 | log::debug!("Sending Keepalive"); 158 | timer_tx.unbounded_send(true).unwrap(); 159 | } 160 | } 161 | } 162 | --------------------------------------------------------------------------------