Compare commits

...

118 Commits

Author SHA1 Message Date
dependabot[bot] 8a42e93bcc chore(deps): bump androidx.compose:compose-bom
Bumps androidx.compose:compose-bom from 2025.08.00 to 2025.08.01.

---
updated-dependencies:
- dependency-name: androidx.compose:compose-bom
  dependency-version: 2025.08.01
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-28 13:45:31 +00:00
Zane Schepke d07cf7a24b chore: bump deps 2025-08-24 01:35:26 -04:00
Zane Schepke 74c4efe477 fix: proguard rules consume bug 2025-08-23 20:08:16 -04:00
Zane Schepke 3256da1cfa fix: proguard minification bug 2025-08-23 19:11:42 -04:00
Zane Schepke 132728f5dd fix: add missing db migration query 2025-08-23 15:32:51 -04:00
Zane Schepke 3eb72cd43c feat!: proxied backend and lockdown mode (#911)
Another big one. 

- SOCKS5/HTTP proxy integration via "proxy mode"
- Kill switch (which was hacky and leaky) has been replace by a robust "lockdown mode" which keeps a dummy vpnservice tunnel active, capturing all device traffic and fowarding it to a netstack/gvisor tunnel via the SOCKS5 proxy. If a tunnel requires DNS resolution for peer endpoints, we punch a hole by bypassing a socket for DoH resolution to keep things secure and private. 
- DoH support for peer endpoint resolutions for proxy, lockdown, and regular vpn mode (not kernel, yet) with support for cloudflare and Adguard DoH providers.
2025-08-23 03:56:13 -04:00
Zane Schepke 8a3d781bb3 fix: standalone can accidentally install fdroid version, progress indicator bug 2025-08-14 02:06:00 -04:00
Zane Schepke 99cd1d917a chore: bump version with notes 2025-08-14 01:10:58 -04:00
Zane Schepke 7940b97329 fix: edit tunnel save config name append bug 2025-08-14 00:31:44 -04:00
Zane Schepke 99419ebe9f fix: allow ping target to override all defaults 2025-08-12 21:57:58 -04:00
Zane Schepke 3e2ffc1b64 fix: tunnel re-establish bug
closes #881
2025-08-12 16:01:43 -04:00
Zane Schepke 5d8fb38906 fix: uapi socket connection with support for dynamic packages 2025-08-09 19:21:40 -04:00
Zane Schepke 6d100a2f46 fix: kill switch stuck on bug 2025-08-09 02:19:30 -04:00
Zane Schepke 5feb2827fd refactor: share import save logic 2025-08-08 19:37:01 -04:00
Zane Schepke 0336c2ac9f fix: duplicate tunnel names overwrite bug
closes #886
2025-08-08 19:33:49 -04:00
Zane Schepke 96d8114d37 fix: split tunneling for AndroidTV only apps typo
#805
2025-08-08 17:20:53 -04:00
Zane Schepke e78469c730 fix: split tunneling for AndroidTV only apps
closes #805
2025-08-08 16:46:58 -04:00
dependabot[bot] 6f365a4490 chore(deps): bump actions/download-artifact from 4 to 5 (#884)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-08 16:20:16 -04:00
Zane Schepke 2885d1a539 fix: ping target empty bug 2025-08-08 16:03:19 -04:00
Zane Schepke c56b11599f ci: fix debug build path 2025-08-08 15:28:51 -04:00
Zane Schepke 753575c50d chore: gradle checksum 2025-08-08 15:12:15 -04:00
Zane Schepke 78b419dc6e chore: bump deps 2025-08-08 04:46:32 -04:00
Zane Schepke e8681af273 feat: app database backup and restore
closes #541
2025-08-08 04:07:04 -04:00
Zane Schepke cb92c9605f fix: startup splash bug 2025-08-08 02:35:58 -04:00
Zane Schepke 38ecb0b66b feat!: tun monitoring, move ping restarts to auto-tunnel w/recovery (#885)
This is a big one.. oops.

Main changes:
- Make ping monitor more robust and global, with ping target overrides of the default cloudflare fallback target per tunnel (for full tunnels, otherwise we ping the internal tun ip)
- Include ping restart recovery to prevent tun being down if dns failures happen after a bounce
- Ping monitoring itself remains per tunnel and works without auto tunnel active, but moves the restart feature back to be managed by and integrated with auto tunnel to prevent inconsistencies and conflicts
- Ping statistics can be optionally included to be displayed with tun statistics
- Adds the beginnings of monitoring logs for handshake and data packet failures for userspace tuns (to be incorporated with restarts/tun status later)
- Improve tun error notifications, adds ping restart notifications
- Major refactor of auto tunnel logic to make it more modular and extensible for new auto tunnel conditions
- A bunch of other stuff..
2025-08-07 18:19:36 -04:00
Zane Schepke 230cd0adb8 refactor: remove prelease build, change icon color for nightly 2025-08-01 11:41:17 -04:00
Zane Schepke 33b51823ab chore: deprecation, warnings 2025-08-01 08:56:09 -04:00
Zane Schepke f333319576 feat: auto-tunnel warning notifications for location permissions and services 2025-08-01 02:06:53 -04:00
Zane Schepke e6ad1531c9 fix: improve permission flow, location permission detection, accessibility, tunnel notifications
Minor changes to Auto-tunnel ui to make starting auto tunnel more intuitive.

Better monitoring of location services and location permission changes to be immediately reflected in network monitor, with warnings displayed on auto tunnel screen if necessary depending on wifi detection method.

Improved detection of when app is backgrounded so we notify user of tunnel errors in notifications vs ui.

Fixes bug where prominent location screen was not showing properly.
2025-07-31 18:45:27 -04:00
Zane Schepke 030082df34 fix: miui segmented button color issue
#875
2025-07-26 07:58:25 -04:00
Zane Schepke a825a2f2a4 fix: tunnel position bug after toggle 2025-07-26 01:13:01 -04:00
Zane Schepke aa1a344bb2 chore: fix short description vi 2025-07-25 23:57:18 -04:00
Zane Schepke 3aa03c1896 chore: fix fastlane missing full descriptions 2025-07-25 21:36:54 -04:00
Zane Schepke 21e56cda80 chore: bump app version with notes 2025-07-25 14:58:37 -04:00
Zane Schepke b5196fbf01 fix: android tv sorting bug, improve hover visibility 2025-07-23 02:09:34 -04:00
Zane Schepke e46fe93ae0 fix: improve network detection reliability, permission change detection
#848
2025-07-22 17:28:18 -04:00
Zane Schepke 872ff83a12 feat!: tunnel sorting
#847
closes #846
closes #299
2025-07-17 11:45:46 -04:00
Zane Schepke 5563292a87 build(deps): bump upstream libraries to latest versions after sync 2025-07-13 13:29:26 -04:00
Zane Schepke 8ba760a5ff refactor: auto expand tunnel stats on active 2025-07-11 17:09:52 -04:00
Zane Schepke d431c2d39f chore: bump deps, fix localization sync duplicates 2025-07-11 14:07:05 -04:00
Zane Schepke 33437ab237 chore: fix weblate sync 2025-07-11 13:38:03 -04:00
Zane Schepke 4a432d2bb7 refactor: remove rudundant pt 2025-07-11 13:22:08 -04:00
Zane Schepke 3df972d031 feat(lang): weblate localization changes (#857)
Co-authored-by: Matthaiks <kitynska@gmail.com>
Co-authored-by: kometchtech <kometch@gmail.com>
Co-authored-by: 翻譯得真好下次別翻了 <x86_64-pc-linux-gnu@proton.me>
Co-authored-by: solokot <solokot@gmail.com>
Co-authored-by: Kachelkaiser <kachelkaiser@htpst.de>
Co-authored-by: catelixor <catelixor+weblate@proton.me>
Co-authored-by: 大王叫我来巡山 <hamburger2048@users.noreply.hosted.weblate.org>
Co-authored-by: Faisal Gull <mail.faisalrehman.345@gmail.com>
Co-authored-by: vm <varga.m007@gmail.com>
Co-authored-by: தமிழ்நேரம் <anishprabu.t@gmail.com>
Co-authored-by: sgauthiertremblay <info@sgauthiertremblay.dev>
Co-authored-by: ssantos <ssantos@web.de>
Co-authored-by: Valentin <velentin.s@yandex.ru>
Co-authored-by: adkostatt <adkostatt@gmail.com>
Co-authored-by: VertekPlus <vertekplus@users.noreply.hosted.weblate.org>
Co-authored-by: Jasper <jasper@ennik.com>
Co-authored-by: Tommaso <mrduckhunt@users.noreply.hosted.weblate.org>
Co-authored-by: dct <dct@trnh.org>
Co-authored-by: Languages add-on <noreply-addon-languages@weblate.org>
Co-authored-by: angrybb <lijadolija@gmail.com>
Co-authored-by: Saratoga79 <ordizi79@gmail.com>
Co-authored-by: Deleted User <noreply+48943@weblate.org>
Co-authored-by: François-Xavier Choinière <fx@efficks.com>
Co-authored-by: Noureddine <noureddinex@protonmail.com>
Co-authored-by: Hamed Ap <hamed.ap1366@gmail.com>
Co-authored-by: igor <igor.lachaud@aol.fr>
Co-authored-by: EESF-2 <eesf-2@users.noreply.hosted.weblate.org>
Co-authored-by: Priit Jõerüüt <hwlate@joeruut.com>
Co-authored-by: Jan-Erik Moen <jemoen@gmail.com>
Co-authored-by: teemue <eemil.koivula@gmail.com>
Co-authored-by: Priit Jõerüüt <jrthwlate@users.noreply.hosted.weblate.org>
Co-authored-by: Andras <andras0602@hotmail.com>
2025-07-11 13:00:24 -04:00
Zane Schepke 8b828cca55 fix: nightly installer permission bug 2025-07-06 04:13:59 -04:00
Zane Schepke a223289949 feat: add shizuku support (#852) 2025-07-05 20:49:02 -04:00
Zane Schepke c8b65fb7fa ci: fix token 2025-06-19 00:58:34 -04:00
Zane Schepke feec7f0ffc chore: bump version 2025-06-17 15:43:46 -04:00
Zane Schepke b63c6a9b73 fix: simplify update check dialog ui 2025-06-17 15:34:24 -04:00
Zane Schepke 46975607c4 fix: version check name change 2025-06-17 14:04:00 -04:00
Zane Schepke 0c7bcb5453 fix: nightly version check 2025-06-14 16:59:40 -04:00
Zane Schepke 599bf9c9e0 fix: wifi name surrounding quotes, prevent multiple auto-tunnel jobs
#768
#797
2025-06-14 15:39:22 -04:00
Zane Schepke 03345bdf86 fix!: deprecated wifi info api, add detection option selection
This will break for users who have selected get tunnel name via root shell. They will need to select the new option on update. Also, this will cause more location pings. Users who want less location pings will have to enable the legacy api option manually.

#768
#797
2025-06-12 21:49:48 -04:00
Zane Schepke b07e604003 chore: bump deps 2025-06-11 07:16:24 -04:00
Zane Schepke c8b3af4857 refactor: format 2025-05-28 04:07:50 -04:00
Zane Schepke 0a3447c63d fix: improve auto tunnel reliability with delayed check
refactor: add more auto tunnel logging

#797
2025-05-28 04:06:26 -04:00
Zane Schepke 7f3297db79 fix: rapid toggling crash bug, typo 2025-05-28 02:25:25 -04:00
Zane Schepke aa33aebd2f chore: add full description fastlane 2025-05-16 05:51:13 -04:00
Zane Schepke 53b1d03ca8 ci: permission fix 2025-05-16 05:28:39 -04:00
Zane Schepke 53f72850e2 refactor: remove redundant pt 2025-05-16 05:10:33 -04:00
Zane Schepke b8deb7b644 chore: bump version
ci: add tag deploy
2025-05-16 01:38:01 -04:00
Zane Schepke d5a3090782 chore(deps): bump ksp, kotlin, agp 2025-05-16 00:23:00 -04:00
Zane Schepke 063cbf3ea6 fix: active network tracking bug
#768
closes #789
2025-05-16 00:07:54 -04:00
Zane Schepke 4a45387efd fix: fdroid reproducibility baseline profile bug
closes #780
2025-05-12 02:30:10 -04:00
Zane Schepke fa064ef3a6 fix: qr scanner bug, disable beep
closes #776
2025-05-12 02:16:49 -04:00
Zane Schepke 3f8894a566 chore(deps): bump deps 2025-05-12 02:03:37 -04:00
Weblate (bot) 6d77ef878d Translations update from Hosted Weblate (#702)
Co-authored-by: Matthaiks <kitynska@gmail.com>
Co-authored-by: kometchtech <kometch@gmail.com>
Co-authored-by: 翻譯得真好下次別翻了 <x86_64-pc-linux-gnu@proton.me>
Co-authored-by: solokot <solokot@gmail.com>
Co-authored-by: Kachelkaiser <kachelkaiser@htpst.de>
Co-authored-by: catelixor <catelixor+weblate@proton.me>
Co-authored-by: 大王叫我来巡山 <hamburger2048@users.noreply.hosted.weblate.org>
Co-authored-by: Faisal Gull <mail.faisalrehman.345@gmail.com>
Co-authored-by: vm <varga.m007@gmail.com>
Co-authored-by: தமிழ்நேரம் <anishprabu.t@gmail.com>
Co-authored-by: sgauthiertremblay <info@sgauthiertremblay.dev>
Co-authored-by: ssantos <ssantos@web.de>
Co-authored-by: Valentin <velentin.s@yandex.ru>
Co-authored-by: adkostatt <adkostatt@gmail.com>
Co-authored-by: VertekPlus <vertekplus@users.noreply.hosted.weblate.org>
Co-authored-by: Jasper <jasper@ennik.com>
Co-authored-by: Tommaso <mrduckhunt@users.noreply.hosted.weblate.org>
Co-authored-by: dct <dct@trnh.org>
Co-authored-by: Languages add-on <noreply-addon-languages@weblate.org>
2025-05-06 20:58:29 -04:00
Zane Schepke a05f11739d chore: bump version with notes 2025-05-01 15:25:09 -04:00
Zane Schepke fe519be5cc refactor: remove use cache setting 2025-05-01 15:16:16 -04:00
dependabot[bot] ab0f67c897 chore(deps): bump com.zaneschepke:wireguard-android from 1.2.16 to 1.3.0 (#772)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-01 14:56:25 -04:00
dependabot[bot] a5639cd129 chore(deps): bump com.google.devtools.ksp from 2.1.20-2.0.0 to 2.1.20-2.0.1 (#774)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-01 14:56:08 -04:00
dependabot[bot] babbab051f chore(deps): bump org.semver4j:semver4j from 5.6.0 to 5.7.0 (#773)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-01 14:55:54 -04:00
dependabot[bot] 2e984e8b6f chore(deps): bump accompanist from 0.37.2 to 0.37.3 (#762)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-01 14:55:42 -04:00
Zane Schepke 044e6da7f5 fix: tunnel connectivity bug (#769) 2025-05-01 14:55:15 -04:00
Zane Schepke 77aa2c30d7 feat: display qr for individual tunnels 2025-04-30 06:23:23 -04:00
Zane Schepke e773238e6b ci: refactor and fix bugs (#767) 2025-04-29 07:31:18 -04:00
Zane Schepke 85316bec3f build: change flavor name to improve clarity 2025-04-29 04:59:22 -04:00
Zane Schepke 1935653309 chore(deps): bump compose, datastore 2025-04-29 04:45:11 -04:00
Zane Schepke e3e24b4a06 fix: cleanup logs on update 2025-04-29 04:37:32 -04:00
Zane Schepke 7af53dcc18 fix: skip ping job for static configured tunnels
#741
2025-04-28 17:35:31 -04:00
Zane Schepke 2eb0ab0f19 fix: vpn permission bug
closes #754
2025-04-28 16:07:01 -04:00
Zane Schepke 07857a53c2 fix: regenerate icon to also trigger auth
closes #757
2025-04-28 15:17:55 -04:00
Zane Schepke 25fd31e252 fix: tunnel lock (#765)
fix: start up logger bug
refactor: switch to bound services
refactor: expose resolved peer endpoint
2025-04-28 15:06:43 -04:00
Zane Schepke 0c90b33813 feat: display Wi-Fi security type for Android 12 and greater
refactor: deprecated clipboard manager
2025-04-25 19:25:06 -04:00
Zane Schepke e6671fd3b4 fix: switching APs or Wi-Fi bands with same SSID bug
#741
closes #154
2025-04-25 16:11:37 -04:00
Zane Schepke 735e38e989 feat: add darker theme options
closes #706
2025-04-25 01:59:57 -04:00
Zane Schepke 90698c2b17 fix: select split tunnel apps should appear at top of list
#662
closes #640
2025-04-25 01:17:14 -04:00
Zane Schepke 245b8ee3e7 ci: sort primary to always be first 2025-04-25 00:19:35 -04:00
dependabot[bot] 343554407a chore(deps): bump androidx.datastore:datastore-preferences from 1.1.4 to 1.1.5 (#748)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-25 00:12:22 -04:00
dependabot[bot] b493d83730 chore(deps): bump androidx.compose:compose-bom from 2025.04.00 to 2025.04.01 (#747)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-25 00:12:14 -04:00
dependabot[bot] 53cd717340 chore(deps): bump ClementTsang/delete-tag-and-release from 0.3.1 to 0.4.0 (#738)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-25 00:11:52 -04:00
dependabot[bot] 76574e3dd2 chore(deps): bump androidx.work:work-runtime-ktx from 2.10.0 to 2.10.1 (#746)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-25 00:11:16 -04:00
dependabot[bot] 282a752389 chore(deps): bump roomVersion from 2.7.0 to 2.7.1 (#745)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-25 00:11:06 -04:00
Zane Schepke 5aa9145361 fix: single click in select mode
closes #739
2025-04-25 00:04:30 -04:00
Zane Schepke 586726c848 ci: fix multiple artifacts 2025-04-23 06:32:04 -04:00
Zane Schepke af759a3909 ci: fix removed publish actions 2025-04-23 06:10:18 -04:00
Zane Schepke b467d66554 chore: bump version with notes 2025-04-23 05:59:03 -04:00
Zane Schepke c833e15c8f fix: disable version checker for google, for now 2025-04-23 05:58:42 -04:00
Zane Schepke eec1bbd2f6 ci: fix publish (#737) 2025-04-23 05:27:57 -04:00
Zane Schepke 969e9dfe03 fix: support screen padding 2025-04-23 01:41:50 -04:00
Zane Schepke aeb590db8c refactor: version code generation 2025-04-23 01:32:30 -04:00
Zane Schepke 312062aa36 refactor: app versioning and flavors 2025-04-23 01:23:01 -04:00
dependabot[bot] 287732dfb8 chore(deps): bump ktorClientCore from 3.1.1 to 3.1.2 (#734)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-22 19:42:39 -04:00
dependabot[bot] dca72a70e8 chore(deps): bump hiltAndroid from 2.56.1 to 2.56.2 (#703)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-22 19:42:30 -04:00
dependabot[bot] 1c6543554f chore(deps): bump app.cash.licensee from 1.12.0 to 1.13.0 (#735)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-22 19:42:20 -04:00
dependabot[bot] 8c01f5bea4 chore(deps): bump androidGradlePlugin from 8.9.1 to 8.9.2 (#733)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-22 19:42:12 -04:00
Zane Schepke dd9f329721 fix: banner foreground 2025-04-22 16:51:03 -04:00
Zane Schepke f30c48a90a fix: android tv banner 2025-04-22 16:47:36 -04:00
Zane Schepke 4707d3eb95 fix: app versioning 2025-04-22 03:03:24 -04:00
Zane Schepke cedc2db326 feat: add app licenses screen 2025-04-21 15:33:14 -04:00
Zane Schepke 256e3f7951 fix: version changed while testing 2025-04-21 11:52:40 -04:00
Zane Schepke 9e797b24d6 feat: add in-app updater for release versions
closes #636
2025-04-21 11:51:18 -04:00
Zane Schepke f2b9eb526e fix: amnezia compatibility action
closes #711
2025-04-21 06:56:16 -04:00
Zane Schepke abb29607d3 refactor: ui section divider padding 2025-04-21 06:45:26 -04:00
Zane Schepke f6d7cbc032 fix: recomposition bug, improve cancel scenario
#704
2025-04-20 22:00:26 -04:00
Zane Schepke 9304d79775 feat: variable number tunnel export with file explorer support
feat: listen for user present AndroidTV
#606
closes #704
2025-04-20 21:30:20 -04:00
Zane Schepke 4d18decbf7 fix: simplify bottom nav
closes #716
closes #705
2025-04-19 18:01:09 -04:00
Zane Schepke 76186c092f feat: export variable number of tunnels 2025-04-18 22:41:45 -04:00
Zane Schepke c90a7bbaf5 feat: add multi-select support
closes #332
2025-04-18 18:32:12 -04:00
410 changed files with 12670 additions and 5651 deletions
+47 -44
View File
@@ -1,4 +1,7 @@
name: build name: build
permissions:
contents: read
on: on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
@@ -9,9 +12,16 @@ on:
default: debug default: debug
options: options:
- debug - debug
- prerelease
- nightly - nightly
- release - release
flavor:
type: choice
description: "Product flavor"
required: true
default: fdroid
options:
- fdroid
- standalone
secrets: secrets:
SIGNING_KEY_ALIAS: SIGNING_KEY_ALIAS:
required: false required: false
@@ -30,6 +40,11 @@ on:
description: "Build type" description: "Build type"
required: true required: true
default: debug default: debug
flavor:
type: string
description: "Product flavor"
required: false
default: fdroid
secrets: secrets:
SIGNING_KEY_ALIAS: SIGNING_KEY_ALIAS:
required: false required: false
@@ -41,6 +56,7 @@ on:
required: false required: false
KEYSTORE: KEYSTORE:
required: false required: false
env: env:
UPLOAD_DIR_ANDROID: android_artifacts UPLOAD_DIR_ANDROID: android_artifacts
@@ -48,15 +64,17 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
SIGNING_KEY_ALIAS: ${{ secrets.ANDROID_SIGNING_KEY_ALIAS }} SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.ANDROID_SIGNING_KEY_PASSWORD }} SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.ANDROID_SIGNING_STORE_PASSWORD }} SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks' KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/ KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
outputs: outputs:
UPLOAD_DIR_ANDROID: ${{ env.UPLOAD_DIR_ANDROID }} UPLOAD_DIR_ANDROID: ${{ env.UPLOAD_DIR_ANDROID }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 17 - name: Set up JDK 17
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
@@ -65,61 +83,46 @@ jobs:
cache: gradle cache: gradle
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
# Here we need to decode keystore.jks from base64 string and place it
# in the folder specified in the release signing configuration
- name: Decode Keystore - name: Decode Keystore
id: decode_keystore id: decode_keystore
uses: timheuer/base64-to-file@v1.2 uses: timheuer/base64-to-file@v1.2
with: with:
fileName: ${{ env.KEY_STORE_FILE }} fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }} fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.ANDROID_KEYSTORE }} encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read
- name: Create keystore path env var - name: Create keystore path env var
if: ${{ inputs.build_type != 'debug' }} if: ${{ inputs.build_type != 'debug' }}
run: | run: |
store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }} store_path=${{ env.KEY_STORE_LOCATION }}${{ env.KEY_STORE_FILE }}
echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV echo "KEY_STORE_PATH=$store_path" >> $GITHUB_ENV
- name: Create service_account.json - name: Build APK
if: ${{ inputs.build_type != 'debug' }}
id: createServiceAccount
run: echo '${{ secrets.ANDROID_SERVICE_ACCOUNT_JSON }}' > service_account.json
- name: Build Fdroid Release APK
if: ${{ inputs.build_type == 'release' }}
run: ./gradlew :app:assembleFdroidRelease --info
- name: Build Fdroid Prerelease APK
if: ${{ inputs.build_type == 'prerelease' }}
run: ./gradlew :app:assembleFdroidPrerelease --info
- name: Build Fdroid Nightly APK
if: ${{ inputs.build_type == 'nightly' }}
run: ./gradlew :app:assembleFdroidNightly --info
- name: Build Debug APK
if: ${{ inputs.build_type == 'debug' }}
run: ./gradlew :app:assembleFdroidDebug --stacktrace
# bump versionCode for nightly and prerelease builds
- name: Commit and push versionCode changes
if: ${{ inputs.build_type == 'nightly' || inputs.build_type == 'prerelease' }}
run: | run: |
git config --global user.name 'GitHub Actions' flavor=${{ inputs.flavor }}
git config --global user.email 'actions@github.com' build_type=${{ inputs.build_type }}
git add versionCode.txt case $build_type in
git commit -m "Automated build update" "release")
./gradlew :app:assemble${flavor^}Release --info
;;
"nightly")
./gradlew :app:assemble${flavor^}Nightly --info
;;
"debug")
./gradlew :app:assemble${flavor^}Debug --stacktrace
;;
esac
- name: Get release apk path - name: Get release apk path
id: apk-path id: apk-path
run: echo "path=$(find . -regex '^.*/build/outputs/apk/fdroid/${{ inputs.build_type }}/.*\.apk$' -type f | head -1 | tail -c+2)" >> $GITHUB_OUTPUT run: echo "path=$(find . -regex '^.*/build/outputs/apk/${{ inputs.flavor }}/${{ inputs.build_type }}/.*\.apk$' -type f | head -1 | tail -c+2)" >> $GITHUB_OUTPUT
- name: Upload APK
- name: Upload release apk
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: ${{ env.UPLOAD_DIR_ANDROID }} name: android_artifacts_${{ inputs.flavor }}
path: ${{github.workspace}}/${{ steps.apk-path.outputs.path }} path: >-
app/build/outputs/apk/${{ inputs.flavor }}/${{ inputs.build_type }}/${{
inputs.flavor == 'fdroid' && inputs.build_type == 'release'
&& 'wgtunnel-fdroid-release-*.apk'
|| format('wgtunnel-{0}-v*.apk', inputs.flavor)
}}
retention-days: 1 retention-days: 1
if-no-files-found: warn
+127
View File
@@ -0,0 +1,127 @@
name: nightly
permissions:
contents: write
packages: write
on:
workflow_dispatch:
schedule:
- cron: "4 3 * * *"
jobs:
check_commits:
name: Check for New Commits
runs-on: ubuntu-latest
outputs:
has_new_commits: ${{ steps.check.outputs.new_commits }}
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check for new commits
id: check
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
build-standalone-nightly:
uses: ./.github/workflows/build.yml
secrets: inherit
with:
build_type: "nightly"
flavor: standalone
publish:
needs:
- check_commits
- build-standalone-nightly
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
name: publish-nightly
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install system dependencies
run: |
sudo apt update && sudo apt install -y gh apksigner
- name: Set latest tag
uses: rickstaa/action-create-tag@v1
id: tag_creation
with:
tag: "latest"
message: "Automated tag for HEAD commit"
force_push_tag: true
github_token: ${{ secrets.GITHUB_TOKEN }}
tag_exists_error: false
- name: Generate Changelog
id: changelog
uses: requarks/changelog-action@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
toTag: "nightly"
fromTag: "latest"
writeToFile: false
- name: Make download dir
run: mkdir ${{ github.workspace }}/temp
- name: Download artifacts
uses: actions/download-artifact@v5
with:
pattern: android_artifacts_*
path: ${{ github.workspace }}/temp
- name: Set release notes
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
- name: Delete previous nightly version
uses: ClementTsang/delete-tag-and-release@v0.4.0
with:
tag_name: "nightly"
delete_release: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Get checksum
id: checksum
run: |
file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | head -n 1)
if [ -z "$file_path" ]; then
echo "No APK file found"
exit 1
fi
checksum=$(apksigner verify --print-certs "$file_path" | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")
echo "checksum=$checksum" >> $GITHUB_OUTPUT
- name: Create nightly release
id: create_release
uses: softprops/action-gh-release@v2
with:
body: |
${{ env.RELEASE_NOTES }}
SHA-256 fingerprints for the 4096-bit signing certificate:
```sh
${{ steps.checksum.outputs.checksum }}
```
To verify fingerprint:
```sh
apksigner verify --print-certs [path to APK file] | grep SHA-256
```
### Changelog
${{ steps.changelog.outputs.changes }}
tag_name: nightly
name: nightly
draft: false
prerelease: true
make_latest: false
files: |
${{ github.workspace }}/temp/**/*.apk
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+2
View File
@@ -1,4 +1,6 @@
name: on-pr name: on-pr
permissions:
contents: read
on: on:
workflow_dispatch: workflow_dispatch:
+75 -110
View File
@@ -1,13 +1,17 @@
name: publish name: publish
permissions:
contents: write
packages: write
on: on:
schedule: push:
- cron: "4 3 * * *" tags:
- '[0-9]*.[0-9]*.[0-9]*'
workflow_dispatch: workflow_dispatch:
inputs: inputs:
track: track:
type: choice type: choice
description: "Google play release track" description: "Google Play release track"
options: options:
- none - none
- internal - internal
@@ -21,81 +25,69 @@ on:
description: "GitHub release type" description: "GitHub release type"
options: options:
- none - none
- prerelease
- nightly
- release - release
default: release default: release
required: true required: true
tag_name: tag_name:
description: "Tag name for release" description: "Tag name for release"
required: false required: false
default: nightly default: 1.1.1
flavor:
type: choice
description: "Product flavor"
required: true
default: standalone
options:
- fdroid
- standalone
workflow_call: workflow_call:
env: inputs:
UPLOAD_DIR_ANDROID: android_artifacts flavor:
type: string
permissions: description: "Product flavor"
contents: write required: false
default: standalone
jobs: jobs:
check_commits:
name: Check for New Commits
runs-on: ubuntu-latest
outputs:
has_new_commits: ${{ steps.check.outputs.new_commits }}
steps: build-fdroid:
- name: Checkout Repository if: ${{ github.event_name == 'push' || inputs.release_type == 'release' || inputs.flavor == 'fdroid' }}
uses: actions/checkout@v4
with:
fetch-depth: 0 # This fetches all history so we can check commits
- name: Check for new commits
id: check
env:
GITHUB_TOKEN: ${{ secrets.PAT }}
run: |
# This script checks for commits newer than 23 hours ago
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
build:
if: ${{ inputs.release_type != 'none' }}
uses: ./.github/workflows/build.yml uses: ./.github/workflows/build.yml
secrets: inherit secrets: inherit
with: with:
build_type: ${{ inputs.release_type == '' && 'nightly' || inputs.release_type }} build_type: ${{ github.event_name == 'push' && 'release' || inputs.release_type }}
flavor: fdroid
build-standalone:
if: ${{ github.event_name == 'push' || inputs.release_type == 'release' || inputs.release_type == 'debug' || inputs.flavor == 'standalone' }}
uses: ./.github/workflows/build.yml
secrets: inherit
with:
build_type: ${{ github.event_name == 'push' && 'release' || inputs.release_type }}
flavor: standalone
publish: publish:
needs: needs:
- check_commits - build-standalone
- build
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
name: publish-github name: publish-github
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
GH_USER: ${{ secrets.PAT_USERNAME }}
# GH needed for gh cli
GH_TOKEN: ${{ secrets.PAT }}
GH_REPO: ${{ github.repository }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'push' && github.ref || 'main' }}
- name: Install system dependencies - name: Install system dependencies
run: | run: |
sudo apt update && sudo apt install -y gh apksigner sudo apt update && sudo apt install -y gh apksigner
# update latest tag
- name: Set latest tag - name: Set latest tag
uses: rickstaa/action-create-tag@v1 uses: rickstaa/action-create-tag@v1
id: tag_creation id: tag_creation
with: with:
tag: "latest" # or any tag name you wish to use tag: "latest"
message: "Automated tag for HEAD commit" message: "Automated tag for HEAD commit"
force_push_tag: true force_push_tag: true
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
tag_exists_error: false tag_exists_error: false
- name: Get latest release - name: Get latest release
id: latest_release id: latest_release
uses: kaliber5/action-get-release@v1 uses: kaliber5/action-get-release@v1
@@ -108,76 +100,48 @@ jobs:
uses: requarks/changelog-action@v1 uses: requarks/changelog-action@v1
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
toTag: ${{ github.event_name == 'schedule' && 'nightly' || steps.latest_release.outputs.tag_name }} toTag: ${{ steps.latest_release.outputs.tag_name }}
fromTag: "latest" fromTag: "latest"
writeToFile: false # we won't write to file, just output writeToFile: false
- name: Get version code
if: ${{ inputs.release_type == 'release' }}
run: |
version_code=$(grep "VERSION_CODE" buildSrc/src/main/kotlin/Constants.kt | awk '{print $5}' | tr -d '\n')
echo "VERSION_CODE=$version_code" >> $GITHUB_ENV
- name: Push changes
if: ${{ inputs.release_type == '' || inputs.release_type == 'nightly' || inputs.release_type == 'prerelease' }}
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.PAT }}
branch: ${{ github.ref }}
- name: Make download dir - name: Make download dir
run: mkdir ${{ github.workspace }}/temp run: mkdir ${{ github.workspace }}/temp
- name: Download artifacts - name: Download artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@v5
with: with:
name: ${{ env.UPLOAD_DIR_ANDROID }} pattern: android_artifacts_*
path: ${{ github.workspace }}/temp path: ${{ github.workspace }}/temp
merge-multiple: true
# Setup TAG_NAME, which is used as a general "name"
- if: github.event_name == 'workflow_dispatch'
run: echo "TAG_NAME=${{ github.event.inputs.tag_name }}" >> $GITHUB_ENV
- if: github.event_name == 'schedule'
run: echo "TAG_NAME=nightly" >> $GITHUB_ENV
- name: Set version release notes - name: Set version release notes
if: ${{ inputs.release_type == 'release' }} if: ${{ github.event_name == 'push' || inputs.release_type == 'release' }}
run: | run: |
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${{ env.VERSION_CODE }}.txt)" VERSION_NAME=$(grep "const val VERSION_NAME" buildSrc/src/main/kotlin/Constants.kt | awk -F'"' '{print $2}')
RELEASE_NOTES="$(cat ${{ github.workspace }}/fastlane/metadata/android/en-US/changelogs/${VERSION_NAME}.txt || echo "No changelog found for ${VERSION_NAME}")"
echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV echo "RELEASE_NOTES<<EOF" >> $GITHUB_ENV
echo "$RELEASE_NOTES" >> $GITHUB_ENV echo "$RELEASE_NOTES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV echo "EOF" >> $GITHUB_ENV
- name: On nightly release notes
if: ${{ contains(env.TAG_NAME, 'nightly') }}
run: |
echo "RELEASE_NOTES=Nightly build for the latest development version of the app." >> $GITHUB_ENV
gh release delete nightly --yes || true
git push origin :nightly || true
- name: On prerelease release notes
if: ${{ inputs.release_type == 'prerelease' }}
run: |
echo "RELEASE_NOTES=Testing version of app for specific feature." >> $GITHUB_ENV
gh release delete ${{ github.event.inputs.tag_name }} --yes || true
- name: Get checksum - name: Get checksum
id: checksum id: checksum
run: | run: |
file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | tail -n1) file_path=$(find ${{ github.workspace }}/temp -type f -iname "*.apk" | head -n 1)
echo "checksum=$(apksigner verify -print-certs $file_path | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")" >> $GITHUB_OUTPUT if [ -z "$file_path" ]; then
echo "No APK file found"
exit 1
fi
checksum=$(apksigner verify --print-certs "$file_path" | grep -Po "(?<=SHA-256 digest:) .*" | tr -d "[:blank:]")
echo "checksum=$checksum" >> $GITHUB_OUTPUT
- name: Create Release
- name: Create Release with Fastlane changelog notes
id: create_release id: create_release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
body: | body: |
${{ env.RELEASE_NOTES }} ${{ env.RELEASE_NOTES }}
SHA-256 fingerprint for the 4096-bit signing certificate: SHA-256 fingerprints for the 4096-bit signing certificate:
```sh ```sh
${{ steps.checksum.outputs.checksum }} ${{ steps.checksum.outputs.checksum }}
``` ```
@@ -189,40 +153,40 @@ jobs:
### Changelog ### Changelog
${{ steps.changelog.outputs.changes }} ${{ steps.changelog.outputs.changes }}
tag_name: ${{ env.TAG_NAME }} tag_name: ${{ github.event_name == 'push' && github.ref_name || github.event.inputs.tag_name }}
name: ${{ env.TAG_NAME }} name: ${{ github.event_name == 'push' && github.ref_name || github.event.inputs.tag_name }}
draft: false draft: false
prerelease: ${{ inputs.release_type == 'prerelease' || inputs.release_type == '' || inputs.release_type == 'nightly' }} prerelease: false
make_latest: ${{ inputs.release_type == 'release' }} make_latest: true
files: | files: |
${{ github.workspace }}/temp/* ${{ github.workspace }}/temp/**/*.apk
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
publish-fdroid: publish-fdroid-public:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- build - build-fdroid
if: inputs.release_type == 'release' if: ${{ github.event_name == 'push' || inputs.release_type == 'release' }}
steps: steps:
- name: Dispatch update for fdroid repo - name: Dispatch update for fdroid repo
uses: peter-evans/repository-dispatch@v3 uses: peter-evans/repository-dispatch@v3
with: with:
token: ${{ secrets.PAT }} token: ${{ secrets.GITHUB_TOKEN }}
repository: zaneschepke/fdroid repository: wgtunnel/fdroid
event-type: fdroid-update event-type: fdroid-update
publish-play: publish-play:
if: ${{ inputs.track != 'none' && inputs.track != '' }} if: ${{ github.event_name == 'push' || inputs.track != 'none' }}
name: Publish to Google Play name: Publish to Google Play
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
SIGNING_KEY_ALIAS: ${{ secrets.ANDROID_SIGNING_KEY_ALIAS }} SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
SIGNING_KEY_PASSWORD: ${{ secrets.ANDROID_SIGNING_KEY_PASSWORD }} SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
SIGNING_STORE_PASSWORD: ${{ secrets.ANDROID_SIGNING_STORE_PASSWORD }} SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
KEY_STORE_FILE: 'android_keystore.jks' KEY_STORE_FILE: 'android_keystore.jks'
KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/ KEY_STORE_LOCATION: ${{ github.workspace }}/app/keystore/
GH_USER: ${{ secrets.PAT_USERNAME }}
GH_TOKEN: ${{ secrets.PAT }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -244,7 +208,7 @@ jobs:
with: with:
fileName: ${{ env.KEY_STORE_FILE }} fileName: ${{ env.KEY_STORE_FILE }}
fileDir: ${{ env.KEY_STORE_LOCATION }} fileDir: ${{ env.KEY_STORE_LOCATION }}
encodedString: ${{ secrets.ANDROID_KEYSTORE }} encodedString: ${{ secrets.KEYSTORE }}
# create keystore path for gradle to read # create keystore path for gradle to read
- name: Create keystore path env var - name: Create keystore path env var
@@ -263,5 +227,6 @@ jobs:
bundler-cache: true bundler-cache: true
- name: Distribute app to Prod track 🚀 - name: Distribute app to Prod track 🚀
run: (cd ${{ github.workspace }} && bundle install && bundle exec fastlane ${{ inputs.track }}) run: |
track=${{ github.event_name == 'push' && 'production' || inputs.track }}
(cd ${{ github.workspace }} && bundle install && bundle exec fastlane $track)
+1 -1
View File
@@ -70,5 +70,5 @@ lint/tmp/
app/release/output.json app/release/output.json
.idea/codeStyles/ .idea/codeStyles/
# where we keep our signing secrets locally # where we keep our signing secrets locally
app/signing.properties
/.kotlin/ /.kotlin/
/app/keystore/
+1
View File
@@ -1,2 +1,3 @@
/build /build
/release /release
/src/main/assets/licenses.json
+98 -101
View File
@@ -1,3 +1,5 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins { plugins {
alias(libs.plugins.android.application) alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.android)
@@ -6,22 +8,7 @@ plugins {
alias(libs.plugins.ksp) alias(libs.plugins.ksp)
alias(libs.plugins.compose.compiler) alias(libs.plugins.compose.compiler)
alias(libs.plugins.grgit) alias(libs.plugins.grgit)
} alias(libs.plugins.licensee)
val versionFile = file("$rootDir/versionCode.txt")
val versionCodeIncrement =
with(getBuildTaskName().lowercase()) {
when {
this.contains(Constants.NIGHTLY) || this.contains(Constants.PRERELEASE) -> {
if (versionFile.exists()) {
versionFile.readText().trim().toInt() + 1
} else {
1
}
}
else -> 0
}
} }
android { android {
@@ -30,32 +17,24 @@ android {
androidResources { generateLocaleConfig = true } androidResources { generateLocaleConfig = true }
// reproducibility
dependenciesInfo { dependenciesInfo {
// Disables dependency metadata when building APKs.
includeInApk = false includeInApk = false
// Disables dependency metadata when building Android App Bundles.
includeInBundle = false includeInBundle = false
} }
ksp { arg("room.schemaLocation", "$projectDir/schemas") }
defaultConfig { defaultConfig {
applicationId = Constants.APP_ID applicationId = Constants.APP_ID
minSdk = Constants.MIN_SDK minSdk = Constants.MIN_SDK
targetSdk = Constants.TARGET_SDK targetSdk = Constants.TARGET_SDK
versionCode = Constants.VERSION_CODE + versionCodeIncrement versionCode = computeVersionCode()
versionName = determineVersionName() versionName = computeVersionName()
ksp { arg("room.schemaLocation", "$projectDir/schemas") } sourceSets { getByName("debug").assets.srcDirs(files("$projectDir/schemas")) }
sourceSets { val languagesArray = buildLanguagesArray(languageList())
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room buildConfigField("String[]", "LANGUAGES", "new String[]{ $languagesArray }")
}
buildConfigField(
"String[]",
"LANGUAGES",
"new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }",
)
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { useSupportLibrary = true } vectorDrawables { useSupportLibrary = true }
@@ -63,15 +42,18 @@ android {
signingConfigs { signingConfigs {
create(Constants.RELEASE) { create(Constants.RELEASE) {
storeFile = getStoreFile() storeFile = file(System.getenv("KEY_STORE_PATH") ?: "keystore/android_keystore.jks")
storePassword = getSigningProperty(Constants.STORE_PASS_VAR) storePassword =
keyAlias = getSigningProperty(Constants.KEY_ALIAS_VAR) LocalProperties.get("SIGNING_STORE_PASSWORD")
keyPassword = getSigningProperty(Constants.KEY_PASS_VAR) ?: System.getenv("SIGNING_STORE_PASSWORD")
keyAlias =
LocalProperties.get("SIGNING_KEY_ALIAS") ?: System.getenv("SIGNING_KEY_ALIAS")
keyPassword =
LocalProperties.get("SIGNING_KEY_PASSWORD") ?: System.getenv("SIGNING_KEY_PASSWORD")
} }
} }
buildTypes { buildTypes {
// don't strip
packaging.jniLibs.keepDebugSymbols.addAll( packaging.jniLibs.keepDebugSymbols.addAll(
listOf("libwg-go.so", "libwg-quick.so", "libwg.so") listOf("libwg-go.so", "libwg-quick.so", "libwg.so")
) )
@@ -87,26 +69,61 @@ android {
signingConfig = signingConfigs.getByName(Constants.RELEASE) signingConfig = signingConfigs.getByName(Constants.RELEASE)
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"") resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
} }
debug { debug {
applicationIdSuffix = ".debug" applicationIdSuffix = ".debug"
resValue("string", "app_name", "WG Tunnel - Debug") resValue("string", "app_name", "WG Tunnel Debug")
isDebuggable = true isDebuggable = true
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"") resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
} }
create(Constants.PRERELEASE) {
initWith(buildTypes.getByName(Constants.RELEASE))
applicationIdSuffix = ".prerelease"
resValue("string", "app_name", "WG Tunnel - Pre")
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
}
create(Constants.NIGHTLY) { create(Constants.NIGHTLY) {
initWith(buildTypes.getByName(Constants.RELEASE)) initWith(buildTypes.getByName(Constants.RELEASE))
applicationIdSuffix = ".nightly" applicationIdSuffix = ".nightly"
resValue("string", "app_name", "WG Tunnel - Nightly") resValue("string", "app_name", "WG Tunnel Nightly")
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"") resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"")
} }
}
flavorDimensions.add("type")
productFlavors {
create("fdroid") {
dimension = "type"
buildConfigField("String", "FLAVOR", "\"fdroid\"")
}
create("google") {
dimension = "type"
buildConfigField("String", "FLAVOR", "\"google\"")
}
create("standalone") {
dimension = "type"
buildConfigField("String", "FLAVOR", "\"standalone\"")
}
}
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
compilerOptions {
jvmTarget = JvmTarget.JVM_17
freeCompilerArgs = listOf("-XXLanguage:+PropertyParamAnnotationDefaultTargetMode")
}
}
buildFeatures {
compose = true
buildConfig = true
}
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
licensee {
allowedLicenses().forEach { allow(it) }
allowedLicenseUrls().forEach { allowUrl(it) }
}
applicationVariants.all { applicationVariants.all {
val variant = this val variant = this
@@ -114,32 +131,15 @@ android {
.map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl } .map { it as com.android.build.gradle.internal.api.BaseVariantOutputImpl }
.forEach { output -> .forEach { output ->
val outputFileName = val outputFileName =
"${Constants.APP_NAME}-${variant.flavorName}-" + if (variant.flavorName == "fdroid" && variant.buildType.name == "release") {
"${variant.buildType.name}-${variant.versionName}.apk" "${Constants.APP_NAME}-fdroid-release-${variant.versionName}.apk"
} else {
"${Constants.APP_NAME}-${variant.flavorName}-v${variant.versionName}.apk"
}
output.outputFileName = outputFileName output.outputFileName = outputFileName
} }
} }
} }
flavorDimensions.add(Constants.TYPE)
productFlavors {
create("fdroid") {
dimension = Constants.TYPE
proguardFile("fdroid-rules.pro")
}
create("general") { dimension = Constants.TYPE }
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
isCoreLibraryDesugaringEnabled = true
}
kotlinOptions { jvmTarget = Constants.JVM_TARGET }
buildFeatures {
compose = true
buildConfig = true
}
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
}
dependencies { dependencies {
implementation(project(":logcatter")) implementation(project(":logcatter"))
@@ -147,8 +147,6 @@ dependencies {
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.runtime.ktx)
// helpers for implementing LifecycleOwner in a Service
implementation(libs.androidx.lifecycle.service) implementation(libs.androidx.lifecycle.service)
implementation(libs.androidx.activity.compose) implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom)) implementation(platform(libs.androidx.compose.bom))
@@ -160,7 +158,6 @@ dependencies {
implementation(libs.material) implementation(libs.material)
implementation(libs.androidx.storage) implementation(libs.androidx.storage)
// test
testImplementation(libs.junit) testImplementation(libs.junit)
testImplementation(libs.androidx.junit) testImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.junit)
@@ -171,83 +168,83 @@ dependencies {
debugImplementation(libs.androidx.compose.ui.tooling) debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.manifest) debugImplementation(libs.androidx.compose.manifest)
// tunnel
implementation(libs.tunnel) implementation(libs.tunnel)
implementation(libs.amneziawg.android) implementation(libs.amneziawg.android)
coreLibraryDesugaring(libs.desugar.jdk.libs) coreLibraryDesugaring(libs.desugar.jdk.libs)
// logging
implementation(libs.timber) implementation(libs.timber)
// compose navigation
implementation(libs.androidx.navigation.compose) implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.hilt.navigation.compose) implementation(libs.androidx.hilt.navigation.compose)
// hilt
implementation(libs.hilt.android) implementation(libs.hilt.android)
ksp(libs.hilt.android.compiler) ksp(libs.hilt.android.compiler)
ksp(libs.androidx.hilt.compiler) ksp(libs.androidx.hilt.compiler)
// accompanist
implementation(libs.accompanist.permissions) implementation(libs.accompanist.permissions)
implementation(libs.accompanist.drawablepainter) implementation(libs.accompanist.drawablepainter)
// storage
implementation(libs.androidx.room.runtime) implementation(libs.androidx.room.runtime)
ksp(libs.androidx.room.compiler) ksp(libs.androidx.room.compiler)
implementation(libs.androidx.room.ktx) implementation(libs.androidx.room.ktx)
implementation(libs.androidx.datastore.preferences) implementation(libs.androidx.datastore.preferences)
// lifecycle
implementation(libs.lifecycle.runtime.compose) implementation(libs.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.process) implementation(libs.androidx.lifecycle.process)
// serialization
implementation(libs.kotlinx.serialization.json) implementation(libs.kotlinx.serialization.json)
// ui
implementation(libs.zxing.android.embedded) implementation(libs.zxing.android.embedded)
implementation(libs.material.icons.core)
implementation(libs.material.icons.extended) implementation(libs.material.icons.extended)
// bio
implementation(libs.androidx.biometric.ktx) implementation(libs.androidx.biometric.ktx)
implementation(libs.pin.lock.compose) implementation(libs.pin.lock.compose)
// shortcuts
implementation(libs.androidx.core) implementation(libs.androidx.core)
// splash
implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.core.splashscreen)
// worker
implementation(libs.androidx.work.runtime) implementation(libs.androidx.work.runtime)
implementation(libs.androidx.hilt.work) implementation(libs.androidx.hilt.work)
}
fun determineVersionName(): String { implementation(libs.qrose)
return with(getBuildTaskName().lowercase()) { implementation(libs.semver4j)
when {
contains(Constants.NIGHTLY) || contains(Constants.PRERELEASE) -> implementation(libs.ktor.client.core)
Constants.VERSION_NAME + "-${grgitService.service.get().grgit.head().abbreviatedId}" implementation(libs.ktor.client.okhttp)
else -> Constants.VERSION_NAME implementation(libs.ktor.client.cio)
} implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.slf4j.android)
implementation(libs.icmp4a)
// shizuku
implementation(libs.shizuku.api)
implementation(libs.shizuku.provider)
implementation(libs.reorderable)
implementation(libs.roomdatabasebackup) {
exclude(group = "org.reactivestreams", module = "reactive-streams")
} }
} }
val incrementVersionCode by tasks.register<Copy>("copyLicenseeJsonToAssets") {
tasks.registering { dependsOn("licensee")
doLast { val outputAssets = layout.projectDirectory.dir("src/main/assets")
val versionFile = file("$rootDir/versionCode.txt") from(layout.buildDirectory.file("reports/licensee/androidFdroidRelease/artifacts.json")) {
if (versionFile.exists()) { rename("artifacts.json", "licenses.json")
versionFile.writeText(versionCodeIncrement.toString())
println("Incremented versionCode to $versionCodeIncrement")
}
} }
into(outputAssets)
} }
tasks.named("preBuild") { dependsOn("copyLicenseeJsonToAssets") }
// https://gist.github.com/obfusk/61046e09cee352ae6dd109911534b12e#fix-proposed-by-linsui-disable-baseline-profiles
tasks.whenTaskAdded { tasks.whenTaskAdded {
if (name.startsWith("assemble") && !name.lowercase().contains("debug")) { if (name.contains("ArtProfile")) {
dependsOn(incrementVersionCode) enabled = false
} }
} }
@@ -155,9 +155,7 @@
"columnNames": [ "columnNames": [
"id" "id"
] ]
}, }
"indices": [],
"foreignKeys": []
}, },
{ {
"tableName": "TunnelConfig", "tableName": "TunnelConfig",
@@ -227,21 +225,18 @@
"fieldPath": "pingInterval", "fieldPath": "pingInterval",
"columnName": "ping_interval", "columnName": "ping_interval",
"affinity": "INTEGER", "affinity": "INTEGER",
"notNull": false,
"defaultValue": "null" "defaultValue": "null"
}, },
{ {
"fieldPath": "pingCooldown", "fieldPath": "pingCooldown",
"columnName": "ping_cooldown", "columnName": "ping_cooldown",
"affinity": "INTEGER", "affinity": "INTEGER",
"notNull": false,
"defaultValue": "null" "defaultValue": "null"
}, },
{ {
"fieldPath": "pingIp", "fieldPath": "pingIp",
"columnName": "ping_ip", "columnName": "ping_ip",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false,
"defaultValue": "null" "defaultValue": "null"
}, },
{ {
@@ -275,11 +270,9 @@
"orders": [], "orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)" "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
} }
], ]
"foreignKeys": []
} }
], ],
"views": [],
"setupQueries": [ "setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ae51793c4d09ea3194ecd26f0606f35c')" "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ae51793c4d09ea3194ecd26f0606f35c')"
@@ -0,0 +1,295 @@
{
"formatVersion": 1,
"database": {
"version": 17,
"identityHash": "380d82359c99933cc9ce783347c4ec31",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_vpn_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `debounce_delay_seconds` INTEGER NOT NULL DEFAULT 3, `is_disable_kill_switch_on_trusted_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_unsecure_enabled` INTEGER NOT NULL DEFAULT false, `split_tunnel_apps` TEXT NOT NULL DEFAULT '', `wifi_detection_method` INTEGER NOT NULL DEFAULT 0)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelEnabled",
"columnName": "is_kernel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isAmneziaEnabled",
"columnName": "is_amnezia_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isWildcardsEnabled",
"columnName": "is_wildcards_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isStopOnNoInternetEnabled",
"columnName": "is_stop_on_no_internet_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isVpnKillSwitchEnabled",
"columnName": "is_vpn_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelKillSwitchEnabled",
"columnName": "is_kernel_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isLanOnKillSwitchEnabled",
"columnName": "is_lan_on_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "debounceDelaySeconds",
"columnName": "debounce_delay_seconds",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "isDisableKillSwitchOnTrustedEnabled",
"columnName": "is_disable_kill_switch_on_trusted_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnUnsecureEnabled",
"columnName": "is_tunnel_on_unsecure_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "splitTunnelApps",
"columnName": "split_tunnel_apps",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "wifiDetectionMethod",
"columnName": "wifi_detection_method",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null, `is_ethernet_tunnel` INTEGER NOT NULL DEFAULT false, `is_ipv4_preferred` INTEGER NOT NULL DEFAULT true)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isActive",
"columnName": "is_Active",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "pingInterval",
"columnName": "ping_interval",
"affinity": "INTEGER",
"defaultValue": "null"
},
{
"fieldPath": "pingCooldown",
"columnName": "ping_cooldown",
"affinity": "INTEGER",
"defaultValue": "null"
},
{
"fieldPath": "pingIp",
"columnName": "ping_ip",
"affinity": "TEXT",
"defaultValue": "null"
},
{
"fieldPath": "isEthernetTunnel",
"columnName": "is_ethernet_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isIpv4Preferred",
"columnName": "is_ipv4_preferred",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '380d82359c99933cc9ce783347c4ec31')"
]
}
}
@@ -0,0 +1,302 @@
{
"formatVersion": 1,
"database": {
"version": 18,
"identityHash": "505728bad740c12bab998a066b569333",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_vpn_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `debounce_delay_seconds` INTEGER NOT NULL DEFAULT 3, `is_disable_kill_switch_on_trusted_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_unsecure_enabled` INTEGER NOT NULL DEFAULT false, `split_tunnel_apps` TEXT NOT NULL DEFAULT '', `wifi_detection_method` INTEGER NOT NULL DEFAULT 0)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelEnabled",
"columnName": "is_kernel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isAmneziaEnabled",
"columnName": "is_amnezia_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isWildcardsEnabled",
"columnName": "is_wildcards_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isStopOnNoInternetEnabled",
"columnName": "is_stop_on_no_internet_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isVpnKillSwitchEnabled",
"columnName": "is_vpn_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelKillSwitchEnabled",
"columnName": "is_kernel_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isLanOnKillSwitchEnabled",
"columnName": "is_lan_on_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "debounceDelaySeconds",
"columnName": "debounce_delay_seconds",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "isDisableKillSwitchOnTrustedEnabled",
"columnName": "is_disable_kill_switch_on_trusted_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnUnsecureEnabled",
"columnName": "is_tunnel_on_unsecure_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "splitTunnelApps",
"columnName": "split_tunnel_apps",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "wifiDetectionMethod",
"columnName": "wifi_detection_method",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null, `is_ethernet_tunnel` INTEGER NOT NULL DEFAULT false, `is_ipv4_preferred` INTEGER NOT NULL DEFAULT true, `position` INTEGER NOT NULL DEFAULT 0)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isActive",
"columnName": "is_Active",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "pingInterval",
"columnName": "ping_interval",
"affinity": "INTEGER",
"defaultValue": "null"
},
{
"fieldPath": "pingCooldown",
"columnName": "ping_cooldown",
"affinity": "INTEGER",
"defaultValue": "null"
},
{
"fieldPath": "pingIp",
"columnName": "ping_ip",
"affinity": "TEXT",
"defaultValue": "null"
},
{
"fieldPath": "isEthernetTunnel",
"columnName": "is_ethernet_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isIpv4Preferred",
"columnName": "is_ipv4_preferred",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "position",
"columnName": "position",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '505728bad740c12bab998a066b569333')"
]
}
}
@@ -0,0 +1,316 @@
{
"formatVersion": 1,
"database": {
"version": 19,
"identityHash": "82bdb96b7a9f8695a34ad1ec21d9aea8",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_vpn_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `debounce_delay_seconds` INTEGER NOT NULL DEFAULT 3, `is_disable_kill_switch_on_trusted_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_unsecure_enabled` INTEGER NOT NULL DEFAULT false, `wifi_detection_method` INTEGER NOT NULL DEFAULT 0, `is_ping_monitoring_enabled` INTEGER NOT NULL DEFAULT true, `tunnel_ping_interval_sec` INTEGER NOT NULL DEFAULT 30, `tunnel_ping_attempts` INTEGER NOT NULL DEFAULT 3, `tunnel_ping_timeout_sec` INTEGER)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelEnabled",
"columnName": "is_kernel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isAmneziaEnabled",
"columnName": "is_amnezia_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isWildcardsEnabled",
"columnName": "is_wildcards_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isStopOnNoInternetEnabled",
"columnName": "is_stop_on_no_internet_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isVpnKillSwitchEnabled",
"columnName": "is_vpn_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isKernelKillSwitchEnabled",
"columnName": "is_kernel_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isLanOnKillSwitchEnabled",
"columnName": "is_lan_on_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "debounceDelaySeconds",
"columnName": "debounce_delay_seconds",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "isDisableKillSwitchOnTrustedEnabled",
"columnName": "is_disable_kill_switch_on_trusted_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnUnsecureEnabled",
"columnName": "is_tunnel_on_unsecure_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "wifiDetectionMethod",
"columnName": "wifi_detection_method",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isPingMonitoringEnabled",
"columnName": "is_ping_monitoring_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "tunnelPingIntervalSeconds",
"columnName": "tunnel_ping_interval_sec",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "30"
},
{
"fieldPath": "tunnelPingAttempts",
"columnName": "tunnel_ping_attempts",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "tunnelPingTimeoutSeconds",
"columnName": "tunnel_ping_timeout_sec",
"affinity": "INTEGER"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `restart_on_ping_failure` INTEGER NOT NULL DEFAULT false, `ping_target` TEXT DEFAULT null, `is_ethernet_tunnel` INTEGER NOT NULL DEFAULT false, `is_ipv4_preferred` INTEGER NOT NULL DEFAULT true, `position` INTEGER NOT NULL DEFAULT 0, `auto_tunnel_apps` TEXT NOT NULL DEFAULT '[]')",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isActive",
"columnName": "is_Active",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "restartOnPingFailure",
"columnName": "restart_on_ping_failure",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "pingTarget",
"columnName": "ping_target",
"affinity": "TEXT",
"defaultValue": "null"
},
{
"fieldPath": "isEthernetTunnel",
"columnName": "is_ethernet_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isIpv4Preferred",
"columnName": "is_ipv4_preferred",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "position",
"columnName": "position",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "autoTunnelApps",
"columnName": "auto_tunnel_apps",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'[]'"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '82bdb96b7a9f8695a34ad1ec21d9aea8')"
]
}
}
@@ -0,0 +1,359 @@
{
"formatVersion": 1,
"database": {
"version": 20,
"identityHash": "51f828868c0ea2f0f5c987410ff5c5a1",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `debounce_delay_seconds` INTEGER NOT NULL DEFAULT 3, `is_disable_kill_switch_on_trusted_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_unsecure_enabled` INTEGER NOT NULL DEFAULT false, `wifi_detection_method` INTEGER NOT NULL DEFAULT 0, `is_ping_monitoring_enabled` INTEGER NOT NULL DEFAULT true, `tunnel_ping_interval_sec` INTEGER NOT NULL DEFAULT 30, `tunnel_ping_attempts` INTEGER NOT NULL DEFAULT 3, `tunnel_ping_timeout_sec` INTEGER, `app_mode` INTEGER NOT NULL DEFAULT 0, `dns_protocol` INTEGER NOT NULL DEFAULT 0, `dns_endpoint` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isWildcardsEnabled",
"columnName": "is_wildcards_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isStopOnNoInternetEnabled",
"columnName": "is_stop_on_no_internet_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isLanOnKillSwitchEnabled",
"columnName": "is_lan_on_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "debounceDelaySeconds",
"columnName": "debounce_delay_seconds",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "isDisableKillSwitchOnTrustedEnabled",
"columnName": "is_disable_kill_switch_on_trusted_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnUnsecureEnabled",
"columnName": "is_tunnel_on_unsecure_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "wifiDetectionMethod",
"columnName": "wifi_detection_method",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isPingMonitoringEnabled",
"columnName": "is_ping_monitoring_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "tunnelPingIntervalSeconds",
"columnName": "tunnel_ping_interval_sec",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "30"
},
{
"fieldPath": "tunnelPingAttempts",
"columnName": "tunnel_ping_attempts",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "tunnelPingTimeoutSeconds",
"columnName": "tunnel_ping_timeout_sec",
"affinity": "INTEGER"
},
{
"fieldPath": "appMode",
"columnName": "app_mode",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "dnsProtocol",
"columnName": "dns_protocol",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "dnsEndpoint",
"columnName": "dns_endpoint",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `restart_on_ping_failure` INTEGER NOT NULL DEFAULT false, `ping_target` TEXT DEFAULT null, `is_ethernet_tunnel` INTEGER NOT NULL DEFAULT false, `is_ipv4_preferred` INTEGER NOT NULL DEFAULT true, `position` INTEGER NOT NULL DEFAULT 0, `auto_tunnel_apps` TEXT NOT NULL DEFAULT '[]')",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isActive",
"columnName": "is_Active",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "restartOnPingFailure",
"columnName": "restart_on_ping_failure",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "pingTarget",
"columnName": "ping_target",
"affinity": "TEXT",
"defaultValue": "null"
},
{
"fieldPath": "isEthernetTunnel",
"columnName": "is_ethernet_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isIpv4Preferred",
"columnName": "is_ipv4_preferred",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "position",
"columnName": "position",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "autoTunnelApps",
"columnName": "auto_tunnel_apps",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'[]'"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
]
},
{
"tableName": "proxy_settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `socks5_proxy_enabled` INTEGER NOT NULL DEFAULT false, `socks5_proxy_bind_address` TEXT, `http_proxy_enable` INTEGER NOT NULL DEFAULT false, `http_proxy_bind_address` TEXT, `proxy_username` TEXT, `proxy_password` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "socks5ProxyEnabled",
"columnName": "socks5_proxy_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "socks5ProxyBindAddress",
"columnName": "socks5_proxy_bind_address",
"affinity": "TEXT"
},
{
"fieldPath": "httpProxyEnabled",
"columnName": "http_proxy_enable",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "httpProxyBindAddress",
"columnName": "http_proxy_bind_address",
"affinity": "TEXT"
},
{
"fieldPath": "proxyUsername",
"columnName": "proxy_username",
"affinity": "TEXT"
},
{
"fieldPath": "proxyPassword",
"columnName": "proxy_password",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '51f828868c0ea2f0f5c987410ff5c5a1')"
]
}
}
@@ -0,0 +1,359 @@
{
"formatVersion": 1,
"database": {
"version": 21,
"identityHash": "51f828868c0ea2f0f5c987410ff5c5a1",
"entities": [
{
"tableName": "Settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_stop_on_no_internet_enabled` INTEGER NOT NULL DEFAULT false, `is_lan_on_kill_switch_enabled` INTEGER NOT NULL DEFAULT false, `debounce_delay_seconds` INTEGER NOT NULL DEFAULT 3, `is_disable_kill_switch_on_trusted_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_unsecure_enabled` INTEGER NOT NULL DEFAULT false, `wifi_detection_method` INTEGER NOT NULL DEFAULT 0, `is_ping_monitoring_enabled` INTEGER NOT NULL DEFAULT true, `tunnel_ping_interval_sec` INTEGER NOT NULL DEFAULT 30, `tunnel_ping_attempts` INTEGER NOT NULL DEFAULT 3, `tunnel_ping_timeout_sec` INTEGER, `app_mode` INTEGER NOT NULL DEFAULT 0, `dns_protocol` INTEGER NOT NULL DEFAULT 0, `dns_endpoint` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isAutoTunnelEnabled",
"columnName": "is_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnMobileDataEnabled",
"columnName": "is_tunnel_on_mobile_data_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "trustedNetworkSSIDs",
"columnName": "trusted_network_ssids",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "isAlwaysOnVpnEnabled",
"columnName": "is_always_on_vpn_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTunnelOnEthernetEnabled",
"columnName": "is_tunnel_on_ethernet_enabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isShortcutsEnabled",
"columnName": "is_shortcuts_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnWifiEnabled",
"columnName": "is_tunnel_on_wifi_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isRestoreOnBootEnabled",
"columnName": "is_restore_on_boot_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isMultiTunnelEnabled",
"columnName": "is_multi_tunnel_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPingEnabled",
"columnName": "is_ping_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isWildcardsEnabled",
"columnName": "is_wildcards_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isStopOnNoInternetEnabled",
"columnName": "is_stop_on_no_internet_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isLanOnKillSwitchEnabled",
"columnName": "is_lan_on_kill_switch_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "debounceDelaySeconds",
"columnName": "debounce_delay_seconds",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "isDisableKillSwitchOnTrustedEnabled",
"columnName": "is_disable_kill_switch_on_trusted_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isTunnelOnUnsecureEnabled",
"columnName": "is_tunnel_on_unsecure_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "wifiDetectionMethod",
"columnName": "wifi_detection_method",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isPingMonitoringEnabled",
"columnName": "is_ping_monitoring_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "tunnelPingIntervalSeconds",
"columnName": "tunnel_ping_interval_sec",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "30"
},
{
"fieldPath": "tunnelPingAttempts",
"columnName": "tunnel_ping_attempts",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "3"
},
{
"fieldPath": "tunnelPingTimeoutSeconds",
"columnName": "tunnel_ping_timeout_sec",
"affinity": "INTEGER"
},
{
"fieldPath": "appMode",
"columnName": "app_mode",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "dnsProtocol",
"columnName": "dns_protocol",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "dnsEndpoint",
"columnName": "dns_endpoint",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "TunnelConfig",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `restart_on_ping_failure` INTEGER NOT NULL DEFAULT false, `ping_target` TEXT DEFAULT null, `is_ethernet_tunnel` INTEGER NOT NULL DEFAULT false, `is_ipv4_preferred` INTEGER NOT NULL DEFAULT true, `position` INTEGER NOT NULL DEFAULT 0, `auto_tunnel_apps` TEXT NOT NULL DEFAULT '[]')",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "wgQuick",
"columnName": "wg_quick",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "tunnelNetworks",
"columnName": "tunnel_networks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isMobileDataTunnel",
"columnName": "is_mobile_data_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isPrimaryTunnel",
"columnName": "is_primary_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "amQuick",
"columnName": "am_quick",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "isActive",
"columnName": "is_Active",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "restartOnPingFailure",
"columnName": "restart_on_ping_failure",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "pingTarget",
"columnName": "ping_target",
"affinity": "TEXT",
"defaultValue": "null"
},
{
"fieldPath": "isEthernetTunnel",
"columnName": "is_ethernet_tunnel",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "isIpv4Preferred",
"columnName": "is_ipv4_preferred",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "true"
},
{
"fieldPath": "position",
"columnName": "position",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "autoTunnelApps",
"columnName": "auto_tunnel_apps",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'[]'"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_TunnelConfig_name",
"unique": true,
"columnNames": [
"name"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
}
]
},
{
"tableName": "proxy_settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `socks5_proxy_enabled` INTEGER NOT NULL DEFAULT false, `socks5_proxy_bind_address` TEXT, `http_proxy_enable` INTEGER NOT NULL DEFAULT false, `http_proxy_bind_address` TEXT, `proxy_username` TEXT, `proxy_password` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "socks5ProxyEnabled",
"columnName": "socks5_proxy_enabled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "socks5ProxyBindAddress",
"columnName": "socks5_proxy_bind_address",
"affinity": "TEXT"
},
{
"fieldPath": "httpProxyEnabled",
"columnName": "http_proxy_enable",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "httpProxyBindAddress",
"columnName": "http_proxy_bind_address",
"affinity": "TEXT"
},
{
"fieldPath": "proxyUsername",
"columnName": "proxy_username",
"affinity": "TEXT"
},
{
"fieldPath": "proxyPassword",
"columnName": "proxy_password",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '51f828868c0ea2f0f5c987410ff5c5a1')"
]
}
}
@@ -4,7 +4,6 @@ import androidx.room.testing.MigrationTestHelper
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry
import com.zaneschepke.wireguardautotunnel.data.AppDatabase import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.Queries
import java.io.IOException import java.io.IOException
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
@@ -24,8 +23,6 @@ class MigrationTest {
helper.createDatabase(dbName, 6).apply { helper.createDatabase(dbName, 6).apply {
// Database has schema version 1. Insert some data using SQL queries. // Database has schema version 1. Insert some data using SQL queries.
// You can't use DAO classes because they expect the latest schema. // You can't use DAO classes because they expect the latest schema.
execSQL(Queries.createDefaultSettings())
execSQL(Queries.createTunnelConfig())
// Prepare for the next version. // Prepare for the next version.
close() close()
} }
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#648DB3</color>
</resources>
+10 -12
View File
@@ -12,11 +12,9 @@
<!--foreground service permissions--> <!--foreground service permissions-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!--start service on boot permission--> <!--start service on boot permission-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!--android tv support-->
<permission <permission
android:name="${applicationId}.permission.CONTROL_TUNNELS" android:name="${applicationId}.permission.CONTROL_TUNNELS"
@@ -49,11 +47,15 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent> </intent>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent>
</queries> </queries>
<application <application
android:name=".WireGuardAutoTunnel" android:name=".WireGuardAutoTunnel"
android:allowBackup="false" android:allowBackup="false"
android:banner="@drawable/ic_banner" android:banner="@mipmap/ic_banner"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
android:enableOnBackInvokedCallback="true" android:enableOnBackInvokedCallback="true"
android:fullBackupContent="@xml/backup_rules" android:fullBackupContent="@xml/backup_rules"
@@ -63,10 +65,13 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.App.Start" android:theme="@style/Theme.App.Start"
tools:targetApi="tiramisu"> tools:targetApi="tiramisu">
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:banner="@mipmap/ic_banner"
android:windowSoftInputMode="adjustNothing" android:windowSoftInputMode="adjustNothing"
android:theme="@style/Theme.WireguardAutoTunnel" android:theme="@style/Theme.WireguardAutoTunnel"
android:configChanges="orientation|screenSize|keyboardHidden" android:configChanges="orientation|screenSize|keyboardHidden"
@@ -80,10 +85,6 @@
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" /> <action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="portrait"
tools:replace="screenOrientation" />
<activity <activity
android:name=".core.shortcut.ShortcutsActivity" android:name=".core.shortcut.ShortcutsActivity"
@@ -168,14 +169,11 @@
<receiver <receiver
android:name=".core.broadcast.RestartReceiver" android:name=".core.broadcast.RestartReceiver"
android:enabled="true" android:enabled="true"
android:exported="false" android:exported="false">
android:directBootAware="true">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" /> <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter> </intent-filter>
</receiver> </receiver>
@@ -1,11 +1,9 @@
package com.zaneschepke.wireguardautotunnel package com.zaneschepke.wireguardautotunnel
import android.Manifest
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color import android.graphics.Color
import android.net.Uri import android.net.VpnService
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.provider.Settings import android.provider.Settings
@@ -22,35 +20,18 @@ import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.material3.*
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.*
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Bolt
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.QuestionMark
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarData
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat import androidx.compose.ui.zIndex
import androidx.core.net.toUri
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.NavHost import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.currentBackStackEntryAsState
@@ -58,43 +39,57 @@ import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute import androidx.navigation.toRoute
import com.zaneschepke.networkmonitor.NetworkMonitor import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.model.AppMode
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.MainDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.ui.Route import com.zaneschepke.wireguardautotunnel.ui.Route
import com.zaneschepke.wireguardautotunnel.ui.common.banner.AppAlertBanner
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.VpnDeniedDialog import com.zaneschepke.wireguardautotunnel.ui.common.dialog.VpnDeniedDialog
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.CustomBottomNavbar
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.DynamicTopAppBar
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.currentNavBackStackEntryAsNavBarState
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar
import com.zaneschepke.wireguardautotunnel.ui.navigation.LocalIsAndroidTV
import com.zaneschepke.wireguardautotunnel.ui.navigation.LocalNavController
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.BottomNavbar
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.DynamicTopAppBar
import com.zaneschepke.wireguardautotunnel.ui.navigation.components.currentNavBackStackEntryAsNavBarState
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.AutoTunnelScreen import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.AutoTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.advanced.AutoTunnelAdvancedScreen import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.advanced.AutoTunnelAdvancedScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.detection.WifiDetectionMethodScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.autotunnel.disclosure.LocationDisclosureScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.autotunnel.TunnelAutoTunnelScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.autotunnel.TunnelAutoTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.config.ConfigScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.config.ConfigScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.scanner.ScannerScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.sort.SortScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.splittunnel.SplitTunnelScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.splittunnel.SplitTunnelScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.main.tunneloptions.TunnelOptionsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.main.tunneloptions.TunnelOptionsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.pin.PinLockScreen import com.zaneschepke.wireguardautotunnel.ui.screens.pin.PinLockScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.advanced.SettingsAdvancedScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display.DisplayScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display.DisplayScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language.LanguageScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language.LanguageScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.disclosure.LocationDisclosureScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.dns.DnsSettingsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.killswitch.KillSwitchScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.logs.LogsScreen import com.zaneschepke.wireguardautotunnel.ui.screens.settings.logs.LogsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.monitoring.TunnelMonitoringScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.proxy.ProxySettingsScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.system.SystemFeaturesScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
import com.zaneschepke.wireguardautotunnel.ui.screens.support.license.LicenseScreen
import com.zaneschepke.wireguardautotunnel.ui.theme.AlertRed
import com.zaneschepke.wireguardautotunnel.ui.theme.OffWhite
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
import com.zaneschepke.wireguardautotunnel.util.extensions.goFromRoot import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
import com.zaneschepke.wireguardautotunnel.util.extensions.restartApp
import com.zaneschepke.wireguardautotunnel.util.extensions.showToast
import com.zaneschepke.wireguardautotunnel.viewmodel.AppViewModel import com.zaneschepke.wireguardautotunnel.viewmodel.AppViewModel
import com.zaneschepke.wireguardautotunnel.viewmodel.event.AppEvent import com.zaneschepke.wireguardautotunnel.viewmodel.event.AppEvent
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import de.raphaelebner.roomdatabasebackup.core.RoomBackup
import java.util.Locale
import javax.inject.Inject import javax.inject.Inject
import kotlin.system.exitProcess import kotlin.system.exitProcess
import org.amnezia.awg.backend.GoBackend.VpnService import kotlinx.coroutines.CoroutineDispatcher
import timber.log.Timber import kotlinx.coroutines.launch
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
@@ -105,8 +100,18 @@ class MainActivity : AppCompatActivity() {
@Inject lateinit var networkMonitor: NetworkMonitor @Inject lateinit var networkMonitor: NetworkMonitor
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher
@Inject @MainDispatcher lateinit var mainDispatcher: CoroutineDispatcher
@Inject lateinit var appDatabase: AppDatabase
private var lastLocationPermissionState: Boolean? = null private var lastLocationPermissionState: Boolean? = null
private lateinit var roomBackup: RoomBackup
val REQUEST_CODE = 123
@SuppressLint("BatteryLife") @SuppressLint("BatteryLife")
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge( enableEdgeToEdge(
@@ -117,6 +122,7 @@ class MainActivity : AppCompatActivity() {
window.isNavigationBarContrastEnforced = false window.isNavigationBarContrastEnforced = false
} }
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
roomBackup = RoomBackup(this)
val viewModel by viewModels<AppViewModel>() val viewModel by viewModels<AppViewModel>()
@@ -125,6 +131,7 @@ class MainActivity : AppCompatActivity() {
} }
setContent { setContent {
val isTv = isRunningOnTv()
val appUiState by viewModel.uiState.collectAsStateWithLifecycle() val appUiState by viewModel.uiState.collectAsStateWithLifecycle()
val appViewState by viewModel.appViewState.collectAsStateWithLifecycle() val appViewState by viewModel.appViewState.collectAsStateWithLifecycle()
@@ -136,6 +143,7 @@ class MainActivity : AppCompatActivity() {
backStackEntry, backStackEntry,
viewModel, viewModel,
appUiState, appUiState,
appViewState,
) )
val snackbar = remember { SnackbarHostState() } val snackbar = remember { SnackbarHostState() }
var showVpnPermissionDialog by remember { mutableStateOf(false) } var showVpnPermissionDialog by remember { mutableStateOf(false) }
@@ -150,6 +158,7 @@ class MainActivity : AppCompatActivity() {
vpnPermissionDenied = true vpnPermissionDenied = true
} else { } else {
vpnPermissionDenied = false vpnPermissionDenied = false
showVpnPermissionDialog = false
} }
}, },
) )
@@ -182,21 +191,6 @@ class MainActivity : AppCompatActivity() {
viewModel.handleEvent(AppEvent.MessageShown) viewModel.handleEvent(AppEvent.MessageShown)
} }
} }
LaunchedEffect(appUiState.activeTunnels) {
appUiState.activeTunnels.mapNotNull { (tunnelConf, tunnelState) ->
(tunnelState.status as? TunnelStatus.Error)?.let { error ->
val message = error.error.toStringRes()
val context = this@MainActivity
snackbar.showSnackbar(
context.getString(
R.string.tunnel_error_template,
context.getString(message),
)
)
viewModel.handleEvent(AppEvent.ClearTunnelError(tunnelConf))
}
}
}
LaunchedEffect(popBackStack) { LaunchedEffect(popBackStack) {
if (popBackStack) { if (popBackStack) {
navController.popBackStack() navController.popBackStack()
@@ -218,25 +212,42 @@ class MainActivity : AppCompatActivity() {
batteryActivity.launch( batteryActivity.launch(
Intent().apply { Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
data = Uri.parse("package:${this@MainActivity.packageName}") data = "package:${this@MainActivity.packageName}".toUri()
} }
) )
} }
} }
} }
CompositionLocalProvider(LocalIsAndroidTV provides isTv) {
CompositionLocalProvider(LocalNavController provides navController) { CompositionLocalProvider(LocalNavController provides navController) {
WireguardAutoTunnelTheme(theme = appUiState.appState.theme) { WireguardAutoTunnelTheme(theme = appUiState.appState.theme) {
VpnDeniedDialog( VpnDeniedDialog(
showVpnPermissionDialog, showVpnPermissionDialog,
onDismiss = { showVpnPermissionDialog = false }, onDismiss = {
showVpnPermissionDialog = false
vpnPermissionDenied = false
},
) )
Box(modifier = Modifier.fillMaxSize()) {
// Top banner if in locked down mode
if (appUiState.appSettings.appMode == AppMode.LOCK_DOWN) {
AppAlertBanner(
stringResource(R.string.locked_down)
.uppercase(Locale.getDefault()),
OffWhite,
AlertRed,
modifier =
Modifier.fillMaxWidth().zIndex(2f), // Draw above everything
)
}
Scaffold( Scaffold(
modifier = modifier =
Modifier.pointerInput(Unit) { Modifier.pointerInput(Unit) {
detectTapGestures { detectTapGestures {
viewModel.handleEvent(AppEvent.SetSelectedTunnel(null)) viewModel.handleEvent(AppEvent.ClearSelectedTunnels)
} }
}, },
snackbarHost = { snackbarHost = {
@@ -245,7 +256,9 @@ class MainActivity : AppCompatActivity() {
snackbarData.visuals.message, snackbarData.visuals.message,
isRtl = false, isRtl = false,
containerColor = containerColor =
MaterialTheme.colorScheme.surfaceColorAtElevation(2.dp), MaterialTheme.colorScheme.surfaceColorAtElevation(
2.dp
),
) )
} }
}, },
@@ -256,45 +269,7 @@ class MainActivity : AppCompatActivity() {
enter = slideInVertically(initialOffsetY = { it }), enter = slideInVertically(initialOffsetY = { it }),
exit = slideOutVertically(targetOffsetY = { it }), exit = slideOutVertically(targetOffsetY = { it }),
) { ) {
CustomBottomNavbar( BottomNavbar(appUiState = appUiState)
listOf(
BottomNavItem(
name = stringResource(R.string.tunnels),
route = Route.Main,
icon = Icons.Rounded.Home,
onClick = { navController.goFromRoot(Route.Main) },
),
BottomNavItem(
name = stringResource(R.string.auto_tunnel),
route = Route.AutoTunnel,
icon = Icons.Rounded.Bolt,
onClick = {
val route =
if (
appUiState.appState
.isLocationDisclosureShown
)
Route.AutoTunnel
else Route.LocationDisclosure
navController.goFromRoot(route)
},
active = appUiState.isAutoTunnelActive,
),
BottomNavItem(
name = stringResource(R.string.settings),
route = Route.Settings,
icon = Icons.Rounded.Settings,
onClick = { navController.goFromRoot(Route.Settings) },
),
BottomNavItem(
name = stringResource(R.string.support),
route = Route.Support,
icon = Icons.Rounded.QuestionMark,
onClick = { navController.goFromRoot(Route.Support) },
),
),
navBarState = navBarState,
)
} }
}, },
) { padding -> ) { padding ->
@@ -318,42 +293,55 @@ class MainActivity : AppCompatActivity() {
composable<Route.Settings> { composable<Route.Settings> {
SettingsScreen(appUiState, appViewState, viewModel) SettingsScreen(appUiState, appViewState, viewModel)
} }
composable<Route.SettingsAdvanced> {
SettingsAdvancedScreen(appUiState, viewModel)
}
composable<Route.LocationDisclosure> { composable<Route.LocationDisclosure> {
LocationDisclosureScreen(appUiState, viewModel) LocationDisclosureScreen(viewModel)
} }
composable<Route.AutoTunnel> { composable<Route.AutoTunnel> {
AutoTunnelScreen(appUiState, viewModel) AutoTunnelScreen(appUiState, viewModel)
} }
composable<Route.Appearance> { AppearanceScreen() } composable<Route.Appearance> { AppearanceScreen() }
composable<Route.Language> { LanguageScreen(appUiState, viewModel) } composable<Route.Language> {
composable<Route.Display> { DisplayScreen(appUiState, viewModel) } LanguageScreen(appUiState, viewModel)
composable<Route.Support> { SupportScreen() } }
composable<Route.Display> {
DisplayScreen(appUiState, viewModel)
}
composable<Route.Support> {
SupportScreen(appViewModel = viewModel)
}
composable<Route.License> { LicenseScreen() }
composable<Route.AutoTunnelAdvanced> { composable<Route.AutoTunnelAdvanced> {
AutoTunnelAdvancedScreen(appUiState, viewModel) AutoTunnelAdvancedScreen(appUiState, viewModel)
} }
composable<Route.Logs> { LogsScreen(appViewState, viewModel) } composable<Route.WifiDetectionMethod> {
WifiDetectionMethodScreen(appUiState, viewModel)
}
composable<Route.Logs> {
LogsScreen(appViewState, viewModel)
}
composable<Route.Config> { backStack -> composable<Route.Config> { backStack ->
val args = backStack.toRoute<Route.Config>() val args = backStack.toRoute<Route.Config>()
val config = appUiState.tunnels.firstOrNull { it.id == args.id } val config =
ConfigScreen(config, viewModel) appUiState.tunnels.firstOrNull { it.id == args.id }
ConfigScreen(config, appUiState, viewModel)
} }
composable<Route.TunnelOptions> { backStack -> composable<Route.TunnelOptions> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>() val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels appUiState.tunnels
.firstOrNull { it.id == args.id } .firstOrNull { it.id == args.id }
?.let { config -> ?.let { config ->
TunnelOptionsScreen(config, appUiState, viewModel) TunnelOptionsScreen(
config,
viewModel,
appViewState,
appUiState.appSettings,
)
} }
} }
composable<Route.Lock> { PinLockScreen(viewModel) } composable<Route.Lock> { PinLockScreen(viewModel) }
composable<Route.Scanner> { ScannerScreen(viewModel) } composable<Route.SplitTunnel> {
composable<Route.KillSwitch> { SplitTunnelScreen(viewModel)
KillSwitchScreen(appUiState, viewModel)
} }
composable<Route.SplitTunnel> { SplitTunnelScreen(viewModel) }
composable<Route.TunnelAutoTunnel> { backStack -> composable<Route.TunnelAutoTunnel> { backStack ->
val args = backStack.toRoute<Route.TunnelOptions>() val args = backStack.toRoute<Route.TunnelOptions>()
appUiState.tunnels appUiState.tunnels
@@ -366,6 +354,21 @@ class MainActivity : AppCompatActivity() {
) )
} }
} }
composable<Route.Sort> { SortScreen(appUiState, viewModel) }
composable<Route.TunnelMonitoring> {
TunnelMonitoringScreen(appUiState, viewModel)
}
composable<Route.ProxySettings> {
ProxySettingsScreen(appUiState, viewModel)
}
composable<Route.SystemFeatures> {
SystemFeaturesScreen(appUiState, viewModel)
}
composable<Route.Dns> {
DnsSettingsScreen(appUiState, viewModel)
}
}
}
} }
} }
} }
@@ -376,19 +379,61 @@ class MainActivity : AppCompatActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
checkPermissionAndNotify() WireGuardAutoTunnel.setUiActive(true)
networkMonitor.checkPermissionsAndUpdateState()
} }
private fun checkPermissionAndNotify() { override fun onPause() {
val hasLocation = super.onPause()
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == WireGuardAutoTunnel.setUiActive(false)
PackageManager.PERMISSION_GRANTED
if (lastLocationPermissionState != hasLocation) {
Timber.d("Location permission changed to: $hasLocation")
if (hasLocation) {
networkMonitor.sendLocationPermissionsGrantedBroadcast()
} }
lastLocationPermissionState = hasLocation
fun performBackup() =
lifecycleScope.launch(ioDispatcher) {
roomBackup
.database(appDatabase)
.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_CUSTOM_DIALOG)
.enableLogDebug(true)
.maxFileCount(5)
.apply {
onCompleteListener { success, message, exitCode ->
lifecycleScope.launch(mainDispatcher) {
if (success) {
showToast(
getString(
R.string.backup_success,
getString(R.string.restarting_app),
)
)
restartApp()
} else showToast(R.string.backup_failed)
} }
} }
} }
.backup()
}
fun performRestore() =
lifecycleScope.launch {
roomBackup
.database(appDatabase)
.enableLogDebug(true)
.backupLocation(RoomBackup.BACKUP_FILE_LOCATION_CUSTOM_DIALOG)
.apply {
onCompleteListener { success, message, exitCode ->
lifecycleScope.launch(mainDispatcher) {
if (success) {
showToast(
getString(
R.string.restore_success,
getString(R.string.restarting_app),
)
)
restartApp()
} else showToast(R.string.restore_failed)
}
}
}
.restore()
}
}
@@ -4,27 +4,25 @@ import android.app.Application
import android.os.StrictMode import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy import android.os.StrictMode.ThreadPolicy
import androidx.hilt.work.HiltWorkerFactory import androidx.hilt.work.HiltWorkerFactory
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.work.Configuration import androidx.work.Configuration
import com.wireguard.android.backend.GoBackend import com.wireguard.android.backend.GoBackend
import com.zaneschepke.logcatter.LogReader import com.zaneschepke.logcatter.LogReader
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationMonitor
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.core.worker.ServiceWorker import com.zaneschepke.wireguardautotunnel.core.worker.ServiceWorker
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.MainDispatcher import com.zaneschepke.wireguardautotunnel.di.MainDispatcher
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.*
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext import kotlinx.coroutines.flow.update
import timber.log.Timber import timber.log.Timber
@HiltAndroidApp @HiltAndroidApp
@@ -45,12 +43,13 @@ class WireGuardAutoTunnel : Application(), Configuration.Provider {
@Inject @MainDispatcher lateinit var mainDispatcher: CoroutineDispatcher @Inject @MainDispatcher lateinit var mainDispatcher: CoroutineDispatcher
@Inject lateinit var notificationMonitor: NotificationMonitor
@Inject lateinit var tunnelManager: TunnelManager @Inject lateinit var tunnelManager: TunnelManager
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this instance = this
ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree()) Timber.plant(Timber.DebugTree())
StrictMode.setThreadPolicy( StrictMode.setThreadPolicy(
@@ -80,6 +79,7 @@ class WireGuardAutoTunnel : Application(), Configuration.Provider {
ServiceWorker.start(this) ServiceWorker.start(this)
applicationScope.launch { applicationScope.launch {
launch { notificationMonitor.handleApplicationNotifications() }
appDataRepository.appState.getLocale()?.let { appDataRepository.appState.getLocale()?.let {
withContext(mainDispatcher) { LocaleUtil.changeLocale(it) } withContext(mainDispatcher) { LocaleUtil.changeLocale(it) }
} }
@@ -90,30 +90,20 @@ class WireGuardAutoTunnel : Application(), Configuration.Provider {
} }
override fun onTerminate() { override fun onTerminate() {
applicationScope.launch { applicationScope.cancel()
tunnelManager.setBackendState(BackendState.INACTIVE, emptyList()) tunnelManager.setBackendMode(BackendMode.Inactive)
}
super.onTerminate() super.onTerminate()
} }
class AppLifecycleObserver : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
Timber.d("Application entered foreground")
foreground = true
}
override fun onPause(owner: LifecycleOwner) {
Timber.d("Application entered background")
foreground = false
}
}
companion object { companion object {
private var foreground = false
fun isForeground(): Boolean { private val _uiActive = MutableStateFlow(false)
return foreground
val uiActive: StateFlow<Boolean>
get() = _uiActive
fun setUiActive(active: Boolean) {
_uiActive.update { active }
} }
@Volatile private var lastActiveTunnels: List<Int> = emptyList() @Volatile private var lastActiveTunnels: List<Int> = emptyList()
@@ -3,12 +3,12 @@ package com.zaneschepke.wireguardautotunnel.core.broadcast
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import com.zaneschepke.logcatter.LogReader
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
@@ -24,29 +24,18 @@ class RestartReceiver : BroadcastReceiver() {
@Inject lateinit var serviceManager: ServiceManager @Inject lateinit var serviceManager: ServiceManager
// injecting this should let tunnelManger handle clean startup
@Inject lateinit var tunnelManager: TunnelManager @Inject lateinit var tunnelManager: TunnelManager
@Inject lateinit var logReader: LogReader
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher @Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
Timber.d("RestartReceiver triggered with action: ${intent.action}") Timber.d("RestartReceiver triggered with action: ${intent.action}")
// screen on for Android TV only to help with sleep shutdowns
if (intent.action == Intent.ACTION_SCREEN_ON && !context.isRunningOnTv()) return
serviceManager.updateTunnelTile() serviceManager.updateTunnelTile()
serviceManager.updateAutoTunnelTile() serviceManager.updateAutoTunnelTile()
applicationScope.launch(ioDispatcher) { if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED)
val settings = appDataRepository.settings.get() applicationScope.launch(ioDispatcher) { logReader.deleteAndClearLogs() }
if (settings.isRestoreOnBootEnabled) {
if (settings.isAutoTunnelEnabled && !serviceManager.autoTunnelActive.value) {
Timber.d("Starting auto-tunnel on boot/update")
serviceManager.startAutoTunnel()
} else {
Timber.d("Restoring previous tunnel state")
tunnelManager.restorePreviousState()
}
} else {
Timber.d("Restore on boot disabled, skipping")
}
}
} }
} }
@@ -43,8 +43,14 @@ interface NotificationManager {
fun show(notificationId: Int, notification: Notification) fun show(notificationId: Int, notification: Notification)
companion object { companion object {
const val AUTO_TUNNEL_LOCATION_PERMISSION_ID = 123
const val AUTO_TUNNEL_LOCATION_SERVICES_ID = 124
// For auto tunnel foreground notification
const val AUTO_TUNNEL_NOTIFICATION_ID = 122 const val AUTO_TUNNEL_NOTIFICATION_ID = 122
// for tunnel foreground notification
const val VPN_NOTIFICATION_ID = 100 const val VPN_NOTIFICATION_ID = 100
const val TUNNEL_ERROR_NOTIFICATION_ID = 101
const val TUNNEL_MESSAGES_NOTIFICATION_ID = 102
const val EXTRA_ID = "id" const val EXTRA_ID = "id"
} }
} }
@@ -0,0 +1,63 @@
package com.zaneschepke.wireguardautotunnel.core.notification
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.util.StringValue
import jakarta.inject.Inject
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class NotificationMonitor
@Inject
constructor(
private val tunnelManager: TunnelManager,
private val notificationManager: NotificationManager,
) {
suspend fun handleApplicationNotifications() = coroutineScope {
launch { handleTunnelErrors() }
launch { handleTunnelMessages() }
}
private suspend fun handleTunnelErrors() =
tunnelManager.errorEvents.collectLatest { (tunnelConf, error) ->
if (!WireGuardAutoTunnel.uiActive.value) {
val notification =
notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = StringValue.DynamicString(tunnelConf.name),
description =
when (error) {
is BackendCoreException.BounceFailed -> error.toStringValue()
else ->
StringValue.StringResource(
R.string.tunnel_error_template,
error.toStringRes(),
)
},
)
notificationManager.show(
NotificationManager.TUNNEL_ERROR_NOTIFICATION_ID,
notification,
)
}
}
private suspend fun handleTunnelMessages() =
tunnelManager.messageEvents.collectLatest { (tunnelConf, message) ->
if (!WireGuardAutoTunnel.uiActive.value) {
val notification =
notificationManager.createNotification(
WireGuardNotification.NotificationChannels.VPN,
title = StringValue.DynamicString(tunnelConf.name),
description = message.toStringValue(),
)
notificationManager.show(
NotificationManager.TUNNEL_MESSAGES_NOTIFICATION_ID,
notification,
)
}
}
}
@@ -1,19 +1,16 @@
package com.zaneschepke.wireguardautotunnel.core.service package com.zaneschepke.wireguardautotunnel.core.service
import android.app.Service import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.ServiceConnection
import android.net.VpnService import android.net.VpnService
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import android.os.IBinder
import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.AutoTunnelService
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.di.MainDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
import jakarta.inject.Inject import jakarta.inject.Inject
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -29,30 +26,44 @@ class ServiceManager
@Inject @Inject
constructor( constructor(
private val context: Context, private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val ioDispatcher: CoroutineDispatcher,
@ApplicationScope private val applicationScope: CoroutineScope, private val applicationScope: CoroutineScope,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher, private val mainDispatcher: CoroutineDispatcher,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
) { ) {
private val autoTunnelMutex = Mutex() private val autoTunnelMutex = Mutex()
private val _autoTunnelActive = MutableStateFlow(false) private val _tunnelService = MutableStateFlow<TunnelForegroundService?>(null)
val autoTunnelActive = _autoTunnelActive.asStateFlow() private val _autoTunnelService = MutableStateFlow<AutoTunnelService?>(null)
val autoTunnelService = _autoTunnelService.asStateFlow()
var autoTunnelService = CompletableDeferred<AutoTunnelService>() private val tunnelServiceConnection =
var backgroundService = CompletableDeferred<TunnelForegroundService>() object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val binder = service as? TunnelForegroundService.LocalBinder
_tunnelService.value = binder?.service
Timber.d("TunnelForegroundService connected")
}
private fun <T : Service> startService(cls: Class<T>, background: Boolean) { override fun onServiceDisconnected(name: ComponentName) {
runCatching { _tunnelService.value = null
val intent = Intent(context, cls) Timber.d("TunnelForegroundService disconnected")
if (background) {
context.startForegroundService(intent)
} else {
context.startService(intent)
} }
} }
.onFailure { Timber.e(it) }
private val autoTunnelServiceConnection =
object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val binder = service as? AutoTunnelService.LocalBinder
_autoTunnelService.value = binder?.service
Timber.d("AutoTunnelService connected")
}
override fun onServiceDisconnected(name: ComponentName) {
_autoTunnelService.value = null
Timber.d("AutoTunnelService disconnected")
}
} }
fun hasVpnPermission(): Boolean { fun hasVpnPermission(): Boolean {
@@ -63,64 +74,62 @@ constructor(
autoTunnelMutex.withLock { autoTunnelMutex.withLock {
val settings = appDataRepository.settings.get() val settings = appDataRepository.settings.get()
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = true)) appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = true))
if (autoTunnelService.isCompleted) { if (_autoTunnelService.value != null) return
_autoTunnelActive.update { true } withContext(ioDispatcher) {
return val intent = Intent(context, AutoTunnelService::class.java)
} context.startForegroundService(intent)
runCatching { context.bindService(intent, autoTunnelServiceConnection, Context.BIND_AUTO_CREATE)
autoTunnelService = CompletableDeferred()
startService(AutoTunnelService::class.java, !WireGuardAutoTunnel.isForeground())
_autoTunnelActive.update { true }
}
.onFailure {
Timber.e(it)
_autoTunnelActive.update { false }
}
withContext(mainDispatcher) { updateAutoTunnelTile() } withContext(mainDispatcher) { updateAutoTunnelTile() }
} }
} }
}
suspend fun stopAutoTunnel() { suspend fun stopAutoTunnel() {
autoTunnelMutex.withLock { autoTunnelMutex.withLock {
val settings = appDataRepository.settings.get() val settings = appDataRepository.settings.get()
appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = false)) appDataRepository.settings.save(settings.copy(isAutoTunnelEnabled = false))
if (!autoTunnelService.isCompleted) return if (_autoTunnelService.value == null) return
runCatching { _autoTunnelService.value?.let { service ->
val service = autoTunnelService.await()
service.stop() service.stop()
_autoTunnelActive.update { false } try {
autoTunnelService = CompletableDeferred() context.unbindService(autoTunnelServiceConnection)
} catch (e: Exception) {
Timber.e(e, "Failed to unbind AutoTunnelService")
} finally {
_tunnelService.value = null
}
} }
.onFailure { Timber.e(it) }
withContext(mainDispatcher) { updateAutoTunnelTile() } withContext(mainDispatcher) { updateAutoTunnelTile() }
} }
} }
fun startTunnelForegroundService() { suspend fun startTunnelForegroundService() {
if (backgroundService.isCompleted) return if (_tunnelService.value != null) return
runCatching { withContext(ioDispatcher) {
backgroundService = CompletableDeferred() applicationScope.launch(ioDispatcher) {
startService( val intent = Intent(context, TunnelForegroundService::class.java)
TunnelForegroundService::class.java, context.startForegroundService(intent)
!WireGuardAutoTunnel.isForeground(), context.bindService(intent, tunnelServiceConnection, Context.BIND_AUTO_CREATE)
) }
} }
.onFailure { Timber.e(it) }
} }
suspend fun stopTunnelForegroundService() { fun stopTunnelForegroundService() {
if (!backgroundService.isCompleted) return _tunnelService.value?.let { service ->
runCatching {
val service = backgroundService.await()
service.stop() service.stop()
backgroundService = CompletableDeferred() try {
context.unbindService(tunnelServiceConnection)
} catch (e: Exception) {
Timber.e(e, "Failed to stop TunnelForegroundService")
} finally {
_tunnelService.value = null
}
} }
.onFailure { Timber.e(it) }
} }
fun toggleAutoTunnel() { fun toggleAutoTunnel() {
applicationScope.launch(ioDispatcher) { applicationScope.launch(ioDispatcher) {
if (_autoTunnelActive.value) stopAutoTunnel() else startAutoTunnel() if (_autoTunnelService.value != null) stopAutoTunnel() else startAutoTunnel()
} }
} }
@@ -131,4 +140,12 @@ constructor(
fun updateTunnelTile() { fun updateTunnelTile() {
context.requestTunnelTileServiceStateUpdate() context.requestTunnelTileServiceStateUpdate()
} }
fun handleTunnelServiceDestroy() {
_tunnelService.update { null }
}
fun handleAutoTunnelServiceDestroy() {
_autoTunnelService.update { null }
}
} }
@@ -2,44 +2,29 @@ package com.zaneschepke.wireguardautotunnel.core.service
import android.app.Notification import android.app.Notification
import android.content.Intent import android.content.Intent
import android.os.Binder
import android.os.IBinder import android.os.IBinder
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import androidx.lifecycle.LifecycleService import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.networkmonitor.NetworkStatus
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelMonitor
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.distinctByKeys import com.zaneschepke.wireguardautotunnel.util.extensions.distinctByKeys
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import java.util.concurrent.ConcurrentHashMap import io.ktor.util.collections.*
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import timber.log.Timber import timber.log.Timber
@AndroidEntryPoint @AndroidEntryPoint
@@ -49,24 +34,22 @@ class TunnelForegroundService : LifecycleService() {
@Inject lateinit var serviceManager: ServiceManager @Inject lateinit var serviceManager: ServiceManager
@Inject lateinit var networkMonitor: NetworkMonitor @Inject lateinit var tunnelManager: TunnelManager
@Inject lateinit var tunnelMonitor: TunnelMonitor
@Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher @Inject @IoDispatcher lateinit var ioDispatcher: CoroutineDispatcher
@Inject lateinit var tunnelRepo: TunnelRepository @Inject lateinit var appDataRepository: AppDataRepository
@Inject lateinit var tunnelManager: TunnelManager class LocalBinder(val service: TunnelForegroundService) : Binder()
private val isNetworkConnected = MutableStateFlow(true) private val tunnelJobs = ConcurrentMap<TunnelConf, Job>()
private val tunnelJobs = ConcurrentHashMap<TunnelConf, Job>() private val binder = LocalBinder(this)
private val pingJobs = ConcurrentHashMap<TunnelConf, Job>()
private val jobsMutex = Mutex()
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
serviceManager.backgroundService.complete(this)
ServiceCompat.startForeground( ServiceCompat.startForeground(
this@TunnelForegroundService, this@TunnelForegroundService,
NotificationManager.VPN_NOTIFICATION_ID, NotificationManager.VPN_NOTIFICATION_ID,
@@ -75,14 +58,13 @@ class TunnelForegroundService : LifecycleService() {
) )
} }
override fun onBind(intent: Intent): IBinder? { override fun onBind(intent: Intent): IBinder {
super.onBind(intent) super.onBind(intent)
return null return binder
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId) super.onStartCommand(intent, flags, startId)
serviceManager.backgroundService.complete(this)
ServiceCompat.startForeground( ServiceCompat.startForeground(
this@TunnelForegroundService, this@TunnelForegroundService,
NotificationManager.VPN_NOTIFICATION_ID, NotificationManager.VPN_NOTIFICATION_ID,
@@ -96,90 +78,23 @@ class TunnelForegroundService : LifecycleService() {
fun start() = fun start() =
lifecycleScope.launch(ioDispatcher) { lifecycleScope.launch(ioDispatcher) {
tunnelManager.activeTunnels.distinctByKeys().collect { activeTunnels -> tunnelManager.activeTunnels.distinctByKeys().collect { activeTunnels ->
// No active tunnels and no jobs: nothing to do val activeTunConfigs = activeTunnels.keys
if (activeTunnels.isEmpty() && tunnelJobs.isEmpty()) return@collect val obsoleteJobs = tunnelJobs.keys - activeTunConfigs
obsoleteJobs.forEach { tunnelConf -> tunnelJobs[tunnelConf]?.cancel() }
// Synchronize jobs with active tunnels activeTunConfigs.forEach { tun ->
synchronizeJobs(activeTunnels) if (tunnelJobs.containsKey(tun)) return@forEach
updateServiceNotification() tunnelJobs[tun] = launch { tunnelMonitor.startMonitoring(tun, true) }
}
updateServiceNotification(activeTunnels)
} }
} }
private suspend fun synchronizeJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
jobsMutex.withLock {
// Stop jobs for tunnels that are no longer active
stopInactiveJobs(activeTunnels)
// Start jobs for new tunnels
startNewJobs(activeTunnels)
}
}
private fun stopInactiveJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
// If no active tunnels, clear all jobs
if (activeTunnels.isEmpty()) {
clearAllJobs()
return
}
// Stop jobs for tunnels not in activeTunnels
val tunnelsToStop = tunnelJobs.keys - activeTunnels.keys
tunnelsToStop.forEach { tun -> stopTunnelJobs(tun) }
}
private fun clearAllJobs() {
tunnelJobs.forEach { (tun, job) ->
Timber.d("Stopping tunnel job for ${tun.tunName}")
job.cancel()
}
tunnelJobs.clear()
pingJobs.forEach { (tun, job) ->
if (isPingBounce(tun)) {
Timber.d("Preserving ping job for ${tun.tunName} due to PING bounce")
return@forEach
}
Timber.d("Stopping ping job for ${tun.tunName}")
job.cancel()
}
pingJobs.entries.removeIf { (tun, _) -> !isPingBounce(tun) }
}
private fun stopTunnelJobs(tun: TunnelConf) {
tunnelJobs.remove(tun)?.cancel()
Timber.d("Stopped tunnel job for ${tun.tunName}")
if (isPingBounce(tun))
return Timber.d("Preserving ${tun.tunName} ping job due to ping bounce")
pingJobs.remove(tun)?.cancel()
Timber.d("Stopped ping job for ${tun.tunName}")
}
private fun startNewJobs(activeTunnels: Map<TunnelConf, TunnelState>) {
val tunnelsToStart = activeTunnels.keys - tunnelJobs.keys
tunnelsToStart.forEach { tun ->
tunnelJobs[tun] = startTunnelJobs(tun)
Timber.d("Started tunnel job for ${tun.tunName}")
if (pingJobs[tun]?.isActive == true) {
Timber.d("Reusing active ping job for ${tun.tunName}")
} else {
pingJobs[tun]?.cancel() // Cancel any stale job
if (tun.isPingEnabled) {
pingJobs[tun] = startPingJob(tun)
Timber.d("Started ping job for ${tun.tunName}")
}
}
}
}
private fun isPingBounce(tun: TunnelConf): Boolean =
tunnelManager.bouncingTunnelIds[tun.id] == TunnelStatus.StopReason.PING
// TODO Would be cool to have this include kill switch // TODO Would be cool to have this include kill switch
// TODO also we need to include errors private fun updateServiceNotification(activeTunnels: Map<TunnelConf, TunnelState>) {
private fun updateServiceNotification() {
val notification = val notification =
when (tunnelJobs.size) { when (activeTunnels.size) {
0 -> onCreateNotification() 0 -> onCreateNotification()
1 -> createTunnelNotification(tunnelJobs.keys.first()) 1 -> createTunnelNotification(activeTunnels.keys.first())
else -> createTunnelsNotification() else -> createTunnelsNotification()
} }
ServiceCompat.startForeground( ServiceCompat.startForeground(
@@ -190,91 +105,18 @@ class TunnelForegroundService : LifecycleService() {
) )
} }
// use same scope so we can cancel all of these
private fun startTunnelJobs(tunnelConf: TunnelConf) =
lifecycleScope.launch(ioDispatcher) {
// monitor if we have internet connectivity
launch { startNetworkMonitorJob() }
// job to trigger stats emit on interval
launch { startTunnelStatsJob(tunnelConf) }
// monitor changes to the tunnel config
launch { startTunnelConfChangesJob(tunnelConf) }
}
private suspend fun startTunnelConfChangesJob(tunnelConf: TunnelConf) {
tunnelRepo.flow
.flowOn(ioDispatcher)
.map { storedTunnels -> storedTunnels.firstOrNull { it.id == tunnelConf.id } }
.filterNotNull()
// only emit when one of these 3 values change
.distinctUntilChanged { old, new -> old == new }
.collect { storedTunnel ->
if (tunnelConf != storedTunnel) {
Timber.d("Config changed for ${storedTunnel.tunName}, bouncing")
// let this complete, even after cancel
withContext(NonCancellable) {
tunnelManager.bounceTunnel(
storedTunnel,
TunnelStatus.StopReason.CONFIG_CHANGED,
)
}
}
}
}
private suspend fun startNetworkMonitorJob() {
networkMonitor.networkStatusFlow.flowOn(ioDispatcher).collectLatest { status ->
val isAvailable = status !is NetworkStatus.Disconnected
isNetworkConnected.value = isAvailable
Timber.d("Network available: $status")
}
}
private suspend fun startTunnelStatsJob(tunnel: TunnelConf) = coroutineScope {
while (isActive) {
tunnelManager.updateTunnelStatistics(tunnel)
delay(STATS_DELAY)
}
}
private fun startPingJob(tunnel: TunnelConf) =
lifecycleScope.launch(ioDispatcher) {
// delay for initial duration
delay(tunnel.pingInterval ?: Constants.PING_INTERVAL)
while (isActive) {
val shouldBounce = shouldBounceTunnel(tunnel)
val delayMs =
if (shouldBounce) {
// let this complete, even after cancel
withContext(NonCancellable) {
tunnelManager.bounceTunnel(tunnel, TunnelStatus.StopReason.PING)
}
tunnel.pingCooldown ?: Constants.PING_COOLDOWN
} else {
tunnel.pingInterval ?: Constants.PING_INTERVAL
}
delay(delayMs)
}
}
private suspend fun shouldBounceTunnel(tunnel: TunnelConf): Boolean {
if (!isNetworkConnected.value) {
Timber.d("Network disconnected, skipping ping for ${tunnel.tunName}")
return false
}
return runCatching { !tunnel.isTunnelPingable(ioDispatcher) }
.onFailure { e -> Timber.e(e, "Ping check failed for ${tunnel.tunName}") }
.getOrDefault(true)
}
fun stop() { fun stop() {
Timber.d("Stop called")
tunnelJobs.forEach { it.value.cancel() }
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
stopSelf() stopSelf()
} }
override fun onDestroy() { override fun onDestroy() {
serviceManager.backgroundService = CompletableDeferred() tunnelJobs.forEach { it.value.cancel() }
serviceManager.handleTunnelServiceDestroy()
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
Timber.d("onDestroy")
super.onDestroy() super.onDestroy()
} }
@@ -309,14 +151,4 @@ class TunnelForegroundService : LifecycleService() {
title = getString(R.string.tunnel_starting), title = getString(R.string.tunnel_starting),
) )
} }
// TODO add notification handling and optional log reading for restart on handshake failures
companion object {
const val STATS_DELAY = 1_000L
// ipv6 disabled or block on network
// Failed to send handshake initiation: write udp [::]"
// Failed to send data packets: write udp [::]
// Failed to send data packets: write udp 0.0.0.0:51820
// Handshake did not complete after 5 seconds, retrying
}
} }
@@ -1,48 +1,40 @@
package com.zaneschepke.wireguardautotunnel.core.service.autotunnel package com.zaneschepke.wireguardautotunnel.core.service.autotunnel
import android.content.Intent import android.content.Intent
import android.os.Binder
import android.os.IBinder import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.ServiceCompat import androidx.core.app.ServiceCompat
import androidx.lifecycle.LifecycleService import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.zaneschepke.networkmonitor.AndroidNetworkMonitor
import com.zaneschepke.networkmonitor.ConnectivityState
import com.zaneschepke.networkmonitor.NetworkMonitor import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.networkmonitor.NetworkStatus
import com.zaneschepke.wireguardautotunnel.R import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelMonitor
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction import com.zaneschepke.wireguardautotunnel.domain.enums.NotificationAction
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus.StopReason.Ping
import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent
import com.zaneschepke.wireguardautotunnel.domain.events.KillSwitchEvent import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.AutoTunnelState import com.zaneschepke.wireguardautotunnel.domain.state.AutoTunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.NetworkState import com.zaneschepke.wireguardautotunnel.domain.state.NetworkState
import com.zaneschepke.wireguardautotunnel.util.Constants import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import com.zaneschepke.wireguardautotunnel.util.extensions.toMillis
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Provider import javax.inject.Provider
import kotlinx.coroutines.CompletableDeferred import kotlin.math.pow
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.*
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.*
import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.Job import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
@AndroidEntryPoint @AndroidEntryPoint
@@ -60,71 +52,57 @@ class AutoTunnelService : LifecycleService() {
@Inject lateinit var tunnelManager: TunnelManager @Inject lateinit var tunnelManager: TunnelManager
@Inject lateinit var tunnelMonitor: TunnelMonitor
private val defaultState = AutoTunnelState() private val defaultState = AutoTunnelState()
private val autoTunMutex = Mutex()
private val autoTunnelStateFlow = MutableStateFlow(defaultState) private val autoTunnelStateFlow = MutableStateFlow(defaultState)
private var wakeLock: PowerManager.WakeLock? = null private val bounceCounts = MutableStateFlow<Map<Int, Int>>(emptyMap())
private var killSwitchJob: Job? = null private var eventHandlerJob: Job? = null
private val lastBounceTimes = mutableMapOf<Int, Long>()
class LocalBinder(val service: AutoTunnelService) : Binder()
private val binder = LocalBinder(this)
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
serviceManager.autoTunnelService.complete(this)
launchWatcherNotification() launchWatcherNotification()
} }
override fun onBind(intent: Intent): IBinder? { override fun onBind(intent: Intent): IBinder {
super.onBind(intent) super.onBind(intent)
return null return binder
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId) super.onStartCommand(intent, flags, startId)
Timber.d("onStartCommand executed with startId: $startId") Timber.d("onStartCommand executed with startId: $startId")
serviceManager.autoTunnelService.complete(this)
start() start()
return START_STICKY return START_STICKY
} }
fun start() { fun start() {
kotlin
.runCatching {
launchWatcherNotification() launchWatcherNotification()
initWakeLock()
startAutoTunnelJob()
startAutoTunnelStateJob() startAutoTunnelStateJob()
killSwitchJob = startKillSwitchJob() startLocationPermissionsNotificationJob()
}
.onFailure { Timber.e(it) }
} }
fun stop() { fun stop() {
wakeLock?.let { if (it.isHeld) it.release() }
stopSelf() stopSelf()
} }
override fun onDestroy() { override fun onDestroy() {
serviceManager.autoTunnelService = CompletableDeferred() serviceManager.handleAutoTunnelServiceDestroy()
restoreVpnKillSwitch() ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
super.onDestroy() super.onDestroy()
} }
private fun restoreVpnKillSwitch() {
with(autoTunnelStateFlow.value) {
if (
settings.isVpnKillSwitchEnabled &&
tunnelManager.getBackendState() != BackendState.KILL_SWITCH_ACTIVE
) {
killSwitchJob?.cancel()
val allowedIps =
if (settings.isLanOnKillSwitchEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS
else emptyList()
tunnelManager.setBackendState(BackendState.KILL_SWITCH_ACTIVE, allowedIps)
}
}
}
private fun launchWatcherNotification( private fun launchWatcherNotification(
description: String = getString(R.string.monitoring_state_changes) description: String = getString(R.string.monitoring_state_changes)
) { ) {
@@ -148,80 +126,141 @@ class AutoTunnelService : LifecycleService() {
) )
} }
private fun initWakeLock() {
wakeLock =
(getSystemService(POWER_SERVICE) as PowerManager).run {
val tag = this.javaClass.name
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
try {
Timber.i("Initiating wakelock with 10 min timeout")
acquire(Constants.BATTERY_SAVER_WATCHER_WAKE_LOCK_TIMEOUT)
} finally {
release()
}
}
}
}
private fun buildNetworkState(networkStatus: NetworkStatus): NetworkState {
return with(autoTunnelStateFlow.value.networkState) {
val wifiName =
when (networkStatus) {
is NetworkStatus.Connected -> {
networkStatus.wifiSsid
}
else -> null
}
copy(
isWifiConnected = networkStatus.wifiConnected,
isMobileDataConnected = networkStatus.cellularConnected,
isEthernetConnected = networkStatus.ethernetConnected,
wifiName = wifiName,
)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun startAutoTunnelStateJob() = private fun startAutoTunnelStateJob() =
lifecycleScope.launch(ioDispatcher) { lifecycleScope.launch(ioDispatcher) {
combine( val networkFlow =
combineSettings(), debouncedConnectivityStateFlow
appDataRepository .flowOn(ioDispatcher)
.get() .map(NetworkState::from)
.settings .map { StateChange.NetworkChange(it) }
.flow .distinctUntilChanged()
.distinctUntilChanged { old, new ->
old.isKernelEnabled == new.isKernelEnabled val settingsFlow =
} // Only emit when isKernelEnabled changes combineSettings().map { StateChange.SettingsChange(it.first, it.second) }
.flatMapLatest {
networkMonitor.networkStatusFlow.flowOn(ioDispatcher).map { val tunnelsFlow =
buildNetworkState(it) tunnelManager.activeTunnels.map { StateChange.ActiveTunnelsChange(it) }
}
} val monitoringFlow =
.distinctUntilChanged(), tunnelManager.activeTunnels
) { double, networkState -> .map { map -> map.mapValues { (_, state) -> state.pingStates } }
AutoTunnelState( .distinctUntilChanged()
tunnelManager.activeTunnels.value, .map { StateChange.MonitoringChange(it) }
networkState,
double.first, var reevaluationJob: Job? = null
double.second,
) // get everything in sync before we use merge
} combine(networkFlow, settingsFlow, tunnelsFlow, monitoringFlow) {
.collect { state -> network,
settings,
tunnels,
monitoring ->
autoTunnelStateFlow.update { autoTunnelStateFlow.update {
it.copy( it.copy(
activeTunnels = state.activeTunnels, activeTunnels = tunnels.activeTunnels,
networkState = state.networkState, networkState = network.networkState,
settings = state.settings, settings = settings.settings,
tunnels = state.tunnels, tunnels = settings.tunnels,
) )
} }
} }
.first()
// use merge to limit the noise of a combine and also increase the scalability of auto
// tunnel handling new states
merge(networkFlow, settingsFlow, tunnelsFlow, monitoringFlow).collect { change ->
if (change !is StateChange.ActiveTunnelsChange) {
Timber.d("New state changed to ${change.javaClass.simpleName}")
}
when (change) {
is StateChange.NetworkChange -> {
reevaluationJob?.cancel()
val previousState = autoTunnelStateFlow.value
autoTunnelStateFlow.update { it.copy(networkState = change.networkState) }
// Android late mobile data state change, we can ignore handling this
if (
isAndroidLateCellularActiveChange(
previousState.networkState,
change.networkState,
)
) {
Timber.d("Android late cellular active state change")
return@collect
}
}
is StateChange.SettingsChange -> {
reevaluationJob?.cancel()
autoTunnelStateFlow.update {
it.copy(settings = change.settings, tunnels = change.tunnels)
}
}
is StateChange.ActiveTunnelsChange -> {
autoTunnelStateFlow.update { it.copy(activeTunnels = change.activeTunnels) }
return@collect
}
is StateChange.MonitoringChange -> {
change.pingStates.forEach { (config, pingState) ->
Timber.d("Ping state $pingState")
if (pingState?.all { it.value.isReachable } == true) {
Timber.d("Clearing bounce count on success")
bounceCounts.update { current ->
current.toMutableMap().apply { remove(config.id) }
}
}
}
return@collect handleAutoTunnelEvent(
autoTunnelStateFlow.value.determineAutoTunnelEvent(
StateChange.MonitoringChange(change.pingStates)
)
)
}
}
handleAutoTunnelEvent(autoTunnelStateFlow.value.determineAutoTunnelEvent(change))
reevaluationJob = launch {
delay(REEVALUATE_CHECK_DELAY)
val currentState = autoTunnelStateFlow.value
if (currentState != defaultState) {
Timber.d("Re-evaluating auto-tunnel state..")
handleAutoTunnelEvent(currentState.determineAutoTunnelEvent(change))
}
}
}
}
private fun isAndroidLateCellularActiveChange(
previous: NetworkState,
new: NetworkState,
): Boolean {
return (previous.isWifiConnected != new.isWifiConnected &&
previous.wifiName == new.wifiName &&
previous.isMobileDataConnected != new.isMobileDataConnected)
}
// all relevant settings to auto tunnel
private fun areAutoTunnelSettingsTheSame(old: AppSettings, new: AppSettings): Boolean {
return (old.isTunnelOnWifiEnabled == new.isTunnelOnWifiEnabled &&
old.isTunnelOnMobileDataEnabled == new.isTunnelOnMobileDataEnabled &&
old.isTunnelOnEthernetEnabled == new.isTunnelOnEthernetEnabled &&
old.trustedNetworkSSIDs == new.trustedNetworkSSIDs &&
old.isPingEnabled == new.isPingEnabled &&
old.debounceDelaySeconds == new.debounceDelaySeconds &&
old.wifiDetectionMethod == new.wifiDetectionMethod &&
old.isVpnKillSwitchEnabled == new.isVpnKillSwitchEnabled &&
old.isLanOnKillSwitchEnabled == new.isLanOnKillSwitchEnabled &&
old.isDisableKillSwitchOnTrustedEnabled == new.isDisableKillSwitchOnTrustedEnabled &&
old.isStopOnNoInternetEnabled == new.isStopOnNoInternetEnabled)
} }
private fun combineSettings(): Flow<Pair<AppSettings, Tunnels>> { private fun combineSettings(): Flow<Pair<AppSettings, Tunnels>> {
return combine( return combine(
appDataRepository.get().settings.flow, appDataRepository
.get()
.settings
.flow
.distinctUntilChanged(::areAutoTunnelSettingsTheSame),
appDataRepository.get().tunnels.flow.map { tunnels -> appDataRepository.get().tunnels.flow.map { tunnels ->
// isActive is ignored for equality checks so user can manually toggle off // isActive is ignored for equality checks so user can manually toggle off
// tunnel with auto-tunnel // tunnel with auto-tunnel
@@ -233,44 +272,166 @@ class AutoTunnelService : LifecycleService() {
.distinctUntilChanged() .distinctUntilChanged()
} }
private fun startKillSwitchJob() = private fun areAutoTunnelPermissionsRequiredTheSame(
old: AutoTunnelState,
new: AutoTunnelState,
): Boolean {
return (old.settings.wifiDetectionMethod == new.settings.wifiDetectionMethod &&
old.networkState.locationPermissionGranted ==
new.networkState.locationPermissionGranted &&
old.networkState.locationServicesEnabled == new.networkState.locationServicesEnabled &&
old.tunnels == new.tunnels &&
old.settings.trustedNetworkSSIDs == new.settings.trustedNetworkSSIDs)
}
// watch for changes to location permission and notify user it will impact auto-tunneling
// TODO or a recheck button for location permission so we dont have to poll it
private fun startLocationPermissionsNotificationJob(): Job =
lifecycleScope.launch(ioDispatcher) { lifecycleScope.launch(ioDispatcher) {
autoTunnelStateFlow.collect { var locationServicesShown = false
if (it == defaultState) return@collect var locationPermissionsShown = false
when (val event = it.asKillSwitchEvent()) {
KillSwitchEvent.DoNothing -> Unit data class NetworkPermissionState(
is KillSwitchEvent.Start -> { val detectionMethod: AndroidNetworkMonitor.WifiDetectionMethod,
Timber.d("Starting kill switch") val locationServicesEnabled: Boolean,
tunnelManager.setBackendState( val locationPermissionsEnabled: Boolean,
BackendState.KILL_SWITCH_ACTIVE, val ssidReadRequired: Boolean,
event.allowedIps, )
autoTunnelStateFlow
.distinctUntilChanged(::areAutoTunnelPermissionsRequiredTheSame)
.map {
NetworkPermissionState(
it.settings.wifiDetectionMethod,
it.networkState.locationServicesEnabled == true,
it.networkState.locationPermissionGranted == true,
(it.tunnels.any { tunnel -> tunnel.tunnelNetworks.isNotEmpty() } ||
it.settings.trustedNetworkSSIDs.isNotEmpty()),
) )
} }
KillSwitchEvent.Stop -> { .collect { state ->
Timber.d("Stopping kill switch") when (state.detectionMethod) {
tunnelManager.setBackendState(BackendState.SERVICE_ACTIVE, emptySet()) AndroidNetworkMonitor.WifiDetectionMethod.DEFAULT,
AndroidNetworkMonitor.WifiDetectionMethod.LEGACY -> {
if (
!state.locationPermissionsEnabled &&
!locationPermissionsShown &&
state.ssidReadRequired
) {
locationPermissionsShown = true
val notification =
notificationManager.createNotification(
WireGuardNotification.NotificationChannels.AUTO_TUNNEL,
title = getString(R.string.warning),
description =
getString(R.string.location_permissions_missing),
)
notificationManager.show(
NotificationManager.AUTO_TUNNEL_LOCATION_PERMISSION_ID,
notification,
)
} }
if (
!state.locationServicesEnabled &&
!locationServicesShown &&
state.ssidReadRequired
) {
locationServicesShown = true
val notification =
notificationManager.createNotification(
WireGuardNotification.NotificationChannels.AUTO_TUNNEL,
title = getString(R.string.warning),
description =
getString(R.string.location_services_not_detected),
)
notificationManager.show(
NotificationManager.AUTO_TUNNEL_LOCATION_SERVICES_ID,
notification,
)
}
if (state.locationServicesEnabled || !state.ssidReadRequired) {
notificationManager.remove(
NotificationManager.AUTO_TUNNEL_LOCATION_SERVICES_ID
)
locationServicesShown = false
}
if (state.locationPermissionsEnabled || !state.ssidReadRequired) {
notificationManager.remove(
NotificationManager.AUTO_TUNNEL_LOCATION_PERMISSION_ID
)
locationPermissionsShown = false
}
}
else -> Unit
} }
} }
} }
@OptIn(FlowPreview::class) private suspend fun handleAutoTunnelEvent(autoTunnelEvent: AutoTunnelEvent) {
private fun startAutoTunnelJob() = autoTunMutex.withLock {
lifecycleScope.launch(ioDispatcher) { when (
Timber.i("Starting auto-tunnel network event watcher") val event =
val settings = appDataRepository.get().settings.get() autoTunnelEvent.also {
Timber.d("Starting with debounce delay of: ${settings.debounceDelaySeconds} seconds") Timber.i("Auto tunnel event: ${it.javaClass.simpleName}")
autoTunnelStateFlow.debounce(settings.debounceDelayMillis()).collect { watcherState -> }
if (watcherState == defaultState) return@collect ) {
Timber.d("New auto tunnel state emitted ${watcherState.networkState}")
when (val event = watcherState.asAutoTunnelEvent()) {
is AutoTunnelEvent.Start -> is AutoTunnelEvent.Start ->
(event.tunnelConf ?: appDataRepository.get().getPrimaryOrFirstTunnel()) (event.tunnelConf ?: appDataRepository.get().getPrimaryOrFirstTunnel())?.let {
?.let { tunnelManager.startTunnel(it) } tunnelManager.startTunnel(it)
// TODO improve this to target specific tunnels to better support multi-tunnel }
is AutoTunnelEvent.Stop -> tunnelManager.stopTunnel() is AutoTunnelEvent.Stop -> tunnelManager.stopTunnel()
AutoTunnelEvent.DoNothing -> Timber.i("Auto-tunneling: no condition met") AutoTunnelEvent.DoNothing -> Timber.i("Auto-tunneling: nothing to do")
is AutoTunnelEvent.Bounce ->
handleBounceWithBackoff(event.configsPeerKeyResolvedMap)
} }
} }
} }
private suspend fun handleBounceWithBackoff(
configsPeerKeyResolvedMap: List<Pair<TunnelConf, Map<String, String?>>>
) { // Simplified param: no failureCount
val settings = appDataRepository.get().settings.get()
val pingIntervalMillis = settings.tunnelPingIntervalSeconds.toMillis()
configsPeerKeyResolvedMap.forEach { (config, peerMap) ->
val bounceCount = bounceCounts.value.getOrDefault(config.id, 0)
val exponent = bounceCount.toDouble()
val backoffDelay =
(pingIntervalMillis * 2.0.pow(exponent)).toLong().coerceAtMost(MAX_BACKOFF_MS)
val currentTime = System.currentTimeMillis()
val lastTime = lastBounceTimes.getOrDefault(config.id, 0L)
if (currentTime - lastTime >= backoffDelay) {
Timber.d(
"Bouncing tunnel ${config.name} after detecting failure, with bounce count $bounceCount and calculated backoff delay $backoffDelay ms"
)
tunnelManager.bounceTunnel(config, Ping(peerMap))
lastBounceTimes[config.id] = currentTime
bounceCounts.update { current ->
current.toMutableMap().apply { this[config.id] = (this[config.id] ?: 0) + 1 }
}
} else {
Timber.d(
"Backoff in progress for tunnel ${config.name}, skipping bounce (required delay: $backoffDelay ms)"
)
}
}
}
@OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
private val debouncedConnectivityStateFlow: Flow<ConnectivityState> by lazy {
appDataRepository
.get()
.settings
.flow
.map { it.debounceDelaySeconds.toMillis() }
.distinctUntilChanged()
.flatMapLatest { debounceMillis ->
networkMonitor.connectivityStateFlow.debounce(debounceMillis)
}
}
companion object {
// try to keep this window short as it will interrupt manual overrides
const val REEVALUATE_CHECK_DELAY = 2_000L
const val MAX_BACKOFF_MS = 300_000L // 5 minutes
}
} }
@@ -0,0 +1,20 @@
package com.zaneschepke.wireguardautotunnel.core.service.autotunnel
import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.state.NetworkState
import com.zaneschepke.wireguardautotunnel.domain.state.PingState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import org.amnezia.awg.crypto.Key
sealed class StateChange {
data class NetworkChange(val networkState: NetworkState) : StateChange()
data class SettingsChange(val settings: AppSettings, val tunnels: Tunnels) : StateChange()
data class ActiveTunnelsChange(val activeTunnels: Map<TunnelConf, TunnelState>) : StateChange()
data class MonitoringChange(val pingStates: Map<TunnelConf, Map<Key, PingState>?>) :
StateChange()
}
@@ -38,8 +38,8 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
Timber.d("Start listening called for auto tunnel tile") Timber.d("Start listening called for auto tunnel tile")
lifecycleScope.launch { lifecycleScope.launch {
serviceManager.autoTunnelActive.collect { serviceManager.autoTunnelService.collect {
if (it) return@collect setActive() if (it != null) return@collect setActive()
setInactive() setInactive()
} }
} }
@@ -56,7 +56,7 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
super.onClick() super.onClick()
unlockAndRun { unlockAndRun {
lifecycleScope.launch { lifecycleScope.launch {
if (serviceManager.autoTunnelActive.value) { if (serviceManager.autoTunnelService.value != null) {
serviceManager.stopAutoTunnel() serviceManager.stopAutoTunnel()
setInactive() setInactive()
} else { } else {
@@ -13,7 +13,7 @@ import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
@@ -1,38 +1,43 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.wireguard.android.backend.BackendException
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendError
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.domain.events.BackendMessage
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.PingState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.ui.state.ConfigProxy
import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState import com.zaneschepke.wireguardautotunnel.util.extensions.asTunnelState
import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import kotlin.concurrent.thread import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import org.amnezia.awg.crypto.Key
import timber.log.Timber import timber.log.Timber
abstract class BaseTunnel( abstract class BaseTunnel(
@ApplicationScope private val applicationScope: CoroutineScope, private val applicationScope: CoroutineScope,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
private val serviceManager: ServiceManager, private val serviceManager: ServiceManager,
) : TunnelProvider { ) : TunnelProvider {
private val _errorEvents = MutableSharedFlow<Pair<TunnelConf, BackendCoreException>>()
override val errorEvents = _errorEvents.asSharedFlow()
private val _messageEvents = MutableSharedFlow<Pair<TunnelConf, BackendMessage>>()
override val messageEvents = _messageEvents.asSharedFlow()
private val activeTuns = MutableStateFlow<Map<TunnelConf, TunnelState>>(emptyMap()) private val activeTuns = MutableStateFlow<Map<TunnelConf, TunnelState>>(emptyMap())
private val tunThreads = ConcurrentHashMap<Int, Thread>() private val tunJobs = ConcurrentHashMap<Int, Job>()
override val activeTunnels = activeTuns.asStateFlow() override val activeTunnels = activeTuns.asStateFlow()
private val tunMutex = Mutex() private val tunMutex = Mutex()
@@ -45,39 +50,47 @@ abstract class BaseTunnel(
abstract fun stopBackend(tunnel: TunnelConf) abstract fun stopBackend(tunnel: TunnelConf)
override suspend fun clearError(tunnelConf: TunnelConf) =
updateTunnelStatus(tunnelConf, TunnelStatus.Down)
override fun hasVpnPermission(): Boolean { override fun hasVpnPermission(): Boolean {
return serviceManager.hasVpnPermission() return serviceManager.hasVpnPermission()
} }
protected suspend fun updateTunnelStatus( override suspend fun updateTunnelStatus(
tunnelConf: TunnelConf, tunnelConf: TunnelConf,
state: TunnelStatus? = null, status: TunnelStatus?,
stats: TunnelStatistics? = null, stats: TunnelStatistics?,
pingStates: Map<Key, PingState>?,
handshakeSuccessLogs: Boolean?,
) { ) {
tunStatusMutex.withLock { tunStatusMutex.withLock {
activeTuns.update { current -> activeTuns.update { currentTuns ->
val originalConf = current.getKeyById(tunnelConf.id) ?: tunnelConf val originalConf = currentTuns.getKeyById(tunnelConf.id) ?: tunnelConf
val existingState = current.getValueById(tunnelConf.id) ?: TunnelState() val existingState = currentTuns.getValueById(tunnelConf.id) ?: TunnelState()
val newState = state ?: existingState.status val newStatus = status ?: existingState.status
if (newState == TunnelStatus.Down) { if (newStatus == TunnelStatus.Down) {
Timber.d("Removing tunnel ${tunnelConf.id} from activeTunnels as state is DOWN") Timber.d("Removing tunnel ${tunnelConf.id} from activeTunnels as state is DOWN")
cleanUpTunThread(tunnelConf) cleanUpTunJob(tunnelConf)
current - originalConf currentTuns - originalConf
} else if (existingState.status == newState && stats == null) { } else if (
Timber.d("Skipping redundant state update for ${tunnelConf.id}: $newState") existingState.status == newStatus &&
current stats == null &&
pingStates == null &&
handshakeSuccessLogs == null
) {
Timber.d("Skipping redundant state update for ${tunnelConf.id}: $newStatus")
currentTuns
} else { } else {
val updated = val updated =
existingState.copy( existingState.copy(
status = newState, status = newStatus,
statistics = stats ?: existingState.statistics, statistics = stats ?: existingState.statistics,
pingStates = pingStates ?: existingState.pingStates,
handshakeSuccessLogs =
handshakeSuccessLogs ?: existingState.handshakeSuccessLogs,
) )
current + (originalConf to updated) currentTuns + (originalConf to updated)
} }
} }
handleServiceStateOnChange()
} }
} }
@@ -107,33 +120,30 @@ abstract class BaseTunnel(
} }
} }
override suspend fun updateTunnelStatistics(tunnel: TunnelConf) {
val stats = getStatistics(tunnel)
updateTunnelStatus(tunnel, null, stats)
}
override suspend fun startTunnel(tunnelConf: TunnelConf) { override suspend fun startTunnel(tunnelConf: TunnelConf) {
if (activeTuns.exists(tunnelConf.id) || tunThreads.containsKey(tunnelConf.id)) return if (activeTuns.exists(tunnelConf.id) || tunJobs.containsKey(tunnelConf.id))
return Timber.w("Tunnel is already running ${tunnelConf.name}")
// For userspace, we need to make sure all previous tunnels are down
if (this@BaseTunnel is UserspaceTunnel) stopActiveTunnels() if (this@BaseTunnel is UserspaceTunnel) stopActiveTunnels()
tunMutex.withLock { tunMutex.withLock {
tunThreads[tunnelConf.id] = thread { val job =
runCatching { applicationScope.launch {
runBlocking {
try { try {
Timber.d("Starting tunnel ${tunnelConf.id}...") Timber.d("Starting tunnel ${tunnelConf.id}...")
startTunnelInner(tunnelConf) startTunnelInner(tunnelConf)
Timber.d("Started complete for tunnel ${tunnelConf.name}...") Timber.d("Started complete for tunnel ${tunnelConf.name}...")
} catch (e: BackendError) { // catch cancellation that could occur before and during startTunnelInner
Timber.e(e, "Failed to start tunnel ${tunnelConf.name} userspace") // and trigger at that suspend point
updateTunnelStatus(tunnelConf, TunnelStatus.Error(e)) } catch (e: CancellationException) {
} catch (e: InterruptedException) {
Timber.w( Timber.w(
"Tunnel start has been interrupted as ${tunnelConf.name} failed to start" "Tunnel start has been cancelled as ${tunnelConf.name} failed to start"
) )
} }
} }
} tunJobs[tunnelConf.id] = job
.onFailure { Timber.w("Tunnel start has been interrupted") } job.invokeOnCompletion {
tunJobs.remove(tunnelConf.id)
Timber.d("Start job completed for tunnel ${tunnelConf.id}")
} }
} }
} }
@@ -141,17 +151,69 @@ abstract class BaseTunnel(
private suspend fun startTunnelInner(tunnelConf: TunnelConf) { private suspend fun startTunnelInner(tunnelConf: TunnelConf) {
configureTunnelCallbacks(tunnelConf) configureTunnelCallbacks(tunnelConf)
Timber.d("Starting backend for tunnel ${tunnelConf.id}...") Timber.d("Starting backend for tunnel ${tunnelConf.id}...")
var currentConf = tunnelConf
var restoreAttempted = false
var originalError: BackendCoreException? = null
while (true) {
try { try {
startBackend(tunnelConf) startBackend(currentConf)
updateTunnelStatus(tunnelConf, TunnelStatus.Up) updateTunnelStatus(currentConf, TunnelStatus.Up)
Timber.d("Started for tun ${tunnelConf.id}...") Timber.d("Started for tun ${currentConf.id}...")
saveTunnelActiveState(tunnelConf, true) saveTunnelActiveState(currentConf, true)
serviceManager.startTunnelForegroundService() serviceManager.startTunnelForegroundService()
} catch (e: BackendException) { if (restoreAttempted)
Timber.e(e, "Failed to start backend for ${tunnelConf.name}") _messageEvents.emit(tunnelConf to BackendMessage.BounceRecovery)
val backendError = e.toBackendError() if (bouncingTunnelIds[currentConf.id] is TunnelStatus.StopReason.Ping) {
updateTunnelStatus(tunnelConf, TunnelStatus.Error(backendError)) _messageEvents.emit(tunnelConf to BackendMessage.BounceSuccess)
throw backendError }
return // Success, return
} catch (e: BackendCoreException) {
originalError = originalError ?: e
val bounceReason = bouncingTunnelIds[currentConf.id]
if (!restoreAttempted && bounceReason is TunnelStatus.StopReason.Ping) {
Timber.i(
"Attempting to recover bounce failure with previously resolved endpoints for ${currentConf.name}"
)
try {
val previouslyResolved = bounceReason.previouslyResolvedEndpoints
val configProxy = ConfigProxy.from(currentConf.toAmConfig())
val updatedConfigProxy =
configProxy.copy(
peers =
configProxy.peers.map {
it.copy(
endpoint =
previouslyResolved[it.publicKey] ?: it.endpoint
)
}
)
val (wg, amnezia) = updatedConfigProxy.buildConfigs()
currentConf =
currentConf.copyWithCallback(
amQuick = amnezia.toAwgQuickString(true, false),
wgQuick = wg.toWgQuickString(true),
)
bouncingTunnelIds.remove(currentConf.id)
restoreAttempted = true
continue // Retry
} catch (e: Exception) {
Timber.e(
e,
"Failed to update config with resolved endpoints for ${currentConf.name}",
)
// Fall through to failure (will emit BounceFailed since
// retryAttempted=true)
}
}
Timber.e(e, "Failed to start backend for ${currentConf.name}")
val emitError =
if (restoreAttempted) BackendCoreException.BounceFailed(originalError) else e
_errorEvents.emit(currentConf to emitError)
updateTunnelStatus(currentConf, TunnelStatus.Down)
return
}
} }
} }
@@ -163,50 +225,44 @@ abstract class BaseTunnel(
override suspend fun stopTunnel(tunnelConf: TunnelConf?, reason: TunnelStatus.StopReason) { override suspend fun stopTunnel(tunnelConf: TunnelConf?, reason: TunnelStatus.StopReason) {
if (tunnelConf == null) return stopActiveTunnels() if (tunnelConf == null) return stopActiveTunnels()
tunMutex.withLock { tunMutex.withLock {
try {
if (activeTuns.isStarting(tunnelConf.id)) if (activeTuns.isStarting(tunnelConf.id))
return handleStuckStartingTunnelShutdown(tunnelConf) return handleStuckStartingTunnelShutdown(tunnelConf)
updateTunnelStatus(tunnelConf, TunnelStatus.Stopping(reason)) updateTunnelStatus(tunnelConf, TunnelStatus.Stopping(reason))
stopTunnelInner(tunnelConf) stopTunnelInner(tunnelConf)
} catch (e: BackendError) {
Timber.e(e, "Failed to stop tunnel ${tunnelConf.id}")
updateTunnelStatus(tunnelConf, TunnelStatus.Error(e))
}
} }
} }
private suspend fun stopTunnelInner(tunnelConf: TunnelConf) { private suspend fun stopTunnelInner(tunnelConf: TunnelConf) {
try {
val tunnel = activeTuns.findTunnel(tunnelConf.id) ?: return val tunnel = activeTuns.findTunnel(tunnelConf.id) ?: return
stopBackend(tunnel) stopBackend(tunnel)
saveTunnelActiveState(tunnelConf, false) saveTunnelActiveState(tunnelConf, false)
removeActiveTunnel(tunnel) removeActiveTunnel(tunnel)
} catch (e: BackendCoreException) {
Timber.e(e, "Failed to stop tunnel ${tunnelConf.id}")
_errorEvents.emit(tunnelConf to e)
updateTunnelStatus(tunnelConf, TunnelStatus.Down)
}
} }
private suspend fun handleServiceStateOnChange() { private fun handleServiceStateOnChange() {
if (activeTuns.value.isEmpty() && bouncingTunnelIds.isEmpty()) if (activeTuns.value.isEmpty()) serviceManager.stopTunnelForegroundService()
serviceManager.stopTunnelForegroundService()
} }
private suspend fun handleStuckStartingTunnelShutdown(tunnel: TunnelConf) { private suspend fun handleStuckStartingTunnelShutdown(tunnel: TunnelConf) {
Timber.d("Stuck in starting state so shutting down tunnel thread for tunnel ${tunnel.name}") Timber.d("Stuck in starting state so cancelling job for tunnel ${tunnel.name}")
try { try {
tunThreads[tunnel.id]?.let { tunJobs[tunnel.id]?.cancel() ?: Timber.d("No job found for ${tunnel.name}")
if (it.state != Thread.State.TERMINATED) {
it.interrupt()
updateTunnelStatus(tunnel, TunnelStatus.Down)
} else {
Timber.d("Thread already terminated")
}
}
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "Failed to stop tunnel thread for ${tunnel.name}") Timber.e(e, "Failed to cancel job for ${tunnel.name}")
} finally {
updateTunnelStatus(tunnel, TunnelStatus.Down)
} }
cleanUpTunThread(tunnel)
} }
private fun cleanUpTunThread(tunnel: TunnelConf) { private fun cleanUpTunJob(tunnel: TunnelConf) {
Timber.d("Removing thread for ${tunnel.name}") Timber.d("Removing job for ${tunnel.name}")
tunThreads -= tunnel.id tunJobs -= tunnel.id
} }
private fun removeActiveTunnel(tunnelConf: TunnelConf) { private fun removeActiveTunnel(tunnelConf: TunnelConf) {
@@ -219,20 +275,18 @@ abstract class BaseTunnel(
"Bounce tunnel ${tunnelConf.name} for reason: $reason, current bouncing: ${bouncingTunnelIds.size}" "Bounce tunnel ${tunnelConf.name} for reason: $reason, current bouncing: ${bouncingTunnelIds.size}"
) )
bouncingTunnelIds[tunnelConf.id] = reason bouncingTunnelIds[tunnelConf.id] = reason
try { runCatching {
stopTunnel(tunnelConf, reason) stopTunnel(tunnelConf, reason)
delay(300L) delay(BOUNCE_DELAY)
startTunnel(tunnelConf) startTunnel(tunnelConf)
} finally {
bouncingTunnelIds.remove(tunnelConf.id)
handleServiceStateOnChange()
Timber.d(
"Cleared bounce state for ${tunnelConf.name}, remaining: ${bouncingTunnelIds.size}"
)
} }
} }
} }
override suspend fun runningTunnelNames(): Set<String> = override suspend fun runningTunnelNames(): Set<String> =
activeTuns.value.keys.map { it.tunName }.toSet() activeTuns.value.keys.map { it.tunName }.toSet()
companion object {
const val BOUNCE_DELAY = 300L
}
} }
@@ -1,7 +1,7 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -5,13 +5,15 @@ import com.wireguard.android.backend.BackendException
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.di.ApplicationScope
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.di.Kernel
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.domain.state.WireGuardStatistics import com.zaneschepke.wireguardautotunnel.domain.state.WireGuardStatistics
import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendCoreException
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import timber.log.Timber import timber.log.Timber
@@ -22,7 +24,7 @@ constructor(
@ApplicationScope private val applicationScope: CoroutineScope, @ApplicationScope private val applicationScope: CoroutineScope,
serviceManager: ServiceManager, serviceManager: ServiceManager,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
private val backend: Backend, @Kernel private val backend: Backend,
) : BaseTunnel(applicationScope, appDataRepository, serviceManager) { ) : BaseTunnel(applicationScope, appDataRepository, serviceManager) {
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? { override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
@@ -35,11 +37,17 @@ constructor(
} }
override suspend fun startBackend(tunnel: TunnelConf) { override suspend fun startBackend(tunnel: TunnelConf) {
// name too long for kernel mode
if (!tunnel.isNameKernelCompatible) throw BackendCoreException.TunnelNameTooLong
try { try {
updateTunnelStatus(tunnel, TunnelStatus.Starting) updateTunnelStatus(tunnel, TunnelStatus.Starting)
backend.setState(tunnel, Tunnel.State.UP, tunnel.toWgConfig()) backend.setState(tunnel, Tunnel.State.UP, tunnel.toWgConfig())
} catch (e: BackendException) { } catch (e: BackendException) {
throw e.toBackendError() Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}")
throw e.toBackendCoreException()
} catch (e: IllegalArgumentException) {
Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}")
throw BackendCoreException.Config
} }
} }
@@ -48,16 +56,16 @@ constructor(
try { try {
backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toWgConfig()) backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toWgConfig())
} catch (e: BackendException) { } catch (e: BackendException) {
throw e.toBackendError() throw e.toBackendCoreException()
} }
} }
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) { override fun setBackendMode(backendMode: BackendMode) {
Timber.w("Not yet implemented for kernel") Timber.w("Not yet implemented for kernel")
} }
override fun getBackendState(): BackendState { override fun getBackendMode(): BackendMode {
return BackendState.INACTIVE return BackendMode.Inactive
} }
override suspend fun runningTunnelNames(): Set<String> { override suspend fun runningTunnelNames(): Set<String> {
@@ -1,67 +1,150 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.data.model.AppMode
import com.zaneschepke.wireguardautotunnel.di.Kernel import com.zaneschepke.wireguardautotunnel.di.*
import com.zaneschepke.wireguardautotunnel.di.Userspace import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.domain.events.BackendMessage
import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.PingState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject import javax.inject.Inject
import kotlin.concurrent.atomics.AtomicBoolean
import kotlin.concurrent.atomics.AtomicReference
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus import kotlinx.coroutines.plus
import org.amnezia.awg.crypto.Key
import timber.log.Timber
@OptIn(ExperimentalCoroutinesApi::class)
class TunnelManager class TunnelManager
@Inject @Inject
constructor( constructor(
@Kernel private val kernelTunnel: TunnelProvider, @Kernel private val kernelTunnel: TunnelProvider,
@Userspace private val userspaceTunnel: TunnelProvider, @Userspace private val userspaceTunnel: TunnelProvider,
@ProxyUserspace private val proxyUserspaceTunnel: TunnelProvider,
private val serviceManager: ServiceManager,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@ApplicationScope private val applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher ioDispatcher: CoroutineDispatcher,
) : TunnelProvider { ) : TunnelProvider {
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalAtomicApi::class)
private val tunnelProviderFlow = private val tunnelProviderFlow: StateFlow<TunnelProvider> = run {
val currentBackend = AtomicReference(userspaceTunnel)
val currentSettings = AtomicReference(AppSettings())
val initialEmit = AtomicBoolean(true)
appDataRepository.settings.flow appDataRepository.settings.flow
.filterNotNull() .filterNotNull()
.flatMapLatest { settings -> // ignore default state
MutableStateFlow(if (settings.isKernelEnabled) kernelTunnel else userspaceTunnel) .filterNot { it == AppSettings() }
.distinctUntilChanged { old, new ->
old.appMode == new.appMode &&
old.isLanOnKillSwitchEnabled == new.isLanOnKillSwitchEnabled
} }
.map { settings ->
Timber.d("App mode changes with ${settings.appMode}")
val backend =
when (settings.appMode) {
AppMode.VPN -> userspaceTunnel
AppMode.PROXY -> proxyUserspaceTunnel
AppMode.LOCK_DOWN -> proxyUserspaceTunnel
AppMode.KERNEL -> kernelTunnel
}
settings to backend
}
.onEach { (settings, newBackend) ->
val isInitialEmit = initialEmit.exchange(false)
val oldBackend = currentBackend.exchange(newBackend)
val oldSettings = currentSettings.exchange(settings)
if ((oldSettings.appMode != settings.appMode) && !isInitialEmit) {
oldBackend.stopTunnel()
if (oldSettings.appMode == AppMode.LOCK_DOWN)
proxyUserspaceTunnel.setBackendMode(BackendMode.Inactive)
}
if (settings.appMode == AppMode.LOCK_DOWN) {
// kill switch will always catch all ipv6, just add ipv4 networks for allowsIps
val allowedIps =
if (settings.isLanOnKillSwitchEnabled) TunnelConf.IPV4_PUBLIC_NETWORKS
else emptySet()
try {
// TODO handle situation where they don't have vpn permission, request it
if (hasVpnPermission()) {
proxyUserspaceTunnel.setBackendMode(BackendMode.KillSwitch(allowedIps))
}
} catch (e: BackendCoreException) {
// TODO expose this error to user
Timber.e(e)
}
}
// restore state if configured
if (isInitialEmit && settings.isRestoreOnBootEnabled) {
Timber.d("Restoring previous state")
if (
settings.isAutoTunnelEnabled &&
serviceManager.autoTunnelService.value == null
) {
serviceManager.startAutoTunnel()
} else {
val previouslyActiveTuns = appDataRepository.tunnels.getActive()
val tunsToStart =
previouslyActiveTuns.filterNot { tun ->
activeTunnels.value.any { tun.id == it.key.id }
}
tunsToStart.forEach { startTunnel(it) }
}
}
}
.map { (_, backend) -> backend }
.stateIn( .stateIn(
scope = applicationScope.plus(ioDispatcher), scope = applicationScope.plus(ioDispatcher),
started = SharingStarted.Eagerly, started = SharingStarted.Eagerly,
initialValue = userspaceTunnel, initialValue = userspaceTunnel,
) )
}
@OptIn(ExperimentalCoroutinesApi::class) override val activeTunnels: StateFlow<Map<TunnelConf, TunnelState>> =
override val activeTunnels = tunnelProviderFlow
appDataRepository.settings.flow .flatMapLatest { it.activeTunnels }
.filterNotNull()
.flatMapLatest { settings ->
if (settings.isKernelEnabled) {
kernelTunnel.activeTunnels
} else {
userspaceTunnel.activeTunnels
}
}
.stateIn( .stateIn(
scope = applicationScope.plus(ioDispatcher), scope = applicationScope.plus(ioDispatcher),
started = SharingStarted.Eagerly, started = SharingStarted.Eagerly,
initialValue = emptyMap(), initialValue = emptyMap(),
) )
@OptIn(ExperimentalCoroutinesApi::class)
override val errorEvents: SharedFlow<Pair<TunnelConf, BackendCoreException>> =
tunnelProviderFlow
.flatMapLatest { it.errorEvents }
.shareIn(
scope = applicationScope.plus(ioDispatcher),
started = SharingStarted.Eagerly,
replay = 0,
)
@OptIn(ExperimentalCoroutinesApi::class)
override val messageEvents: SharedFlow<Pair<TunnelConf, BackendMessage>> =
tunnelProviderFlow
.flatMapLatest { it.messageEvents }
.filterNotNull()
.shareIn(
scope = applicationScope.plus(ioDispatcher),
started = SharingStarted.Eagerly,
replay = 0,
)
override val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason> = override val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason> =
tunnelProviderFlow.value.bouncingTunnelIds tunnelProviderFlow.value.bouncingTunnelIds
@@ -69,12 +152,8 @@ constructor(
return userspaceTunnel.hasVpnPermission() return userspaceTunnel.hasVpnPermission()
} }
override suspend fun clearError(tunnelConf: TunnelConf) { override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? {
tunnelProviderFlow.value.clearError(tunnelConf) return tunnelProviderFlow.value.getStatistics(tunnelConf)
}
override suspend fun updateTunnelStatistics(tunnel: TunnelConf) {
tunnelProviderFlow.value.updateTunnelStatistics(tunnel)
} }
override suspend fun startTunnel(tunnelConf: TunnelConf) { override suspend fun startTunnel(tunnelConf: TunnelConf) {
@@ -89,36 +168,31 @@ constructor(
tunnelProviderFlow.value.bounceTunnel(tunnelConf, reason) tunnelProviderFlow.value.bounceTunnel(tunnelConf, reason)
} }
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) { override fun setBackendMode(backendMode: BackendMode) {
tunnelProviderFlow.value.setBackendState(backendState, allowedIps) tunnelProviderFlow.value.setBackendMode(backendMode)
} }
override fun getBackendState(): BackendState { override fun getBackendMode(): BackendMode {
return tunnelProviderFlow.value.getBackendState() return tunnelProviderFlow.value.getBackendMode()
} }
override suspend fun runningTunnelNames(): Set<String> { override suspend fun runningTunnelNames(): Set<String> {
return tunnelProviderFlow.value.runningTunnelNames() return tunnelProviderFlow.value.runningTunnelNames()
} }
override fun getStatistics(tunnelConf: TunnelConf): TunnelStatistics? { override suspend fun updateTunnelStatus(
return tunnelProviderFlow.value.getStatistics(tunnelConf) tunnelConf: TunnelConf,
} status: TunnelStatus?,
stats: TunnelStatistics?,
fun restorePreviousState() = pingStates: Map<Key, PingState>?,
applicationScope.launch(ioDispatcher) { handshakeSuccessLogs: Boolean?,
val settings = appDataRepository.settings.get() ) {
if (settings.isRestoreOnBootEnabled) { tunnelProviderFlow.value.updateTunnelStatus(
val previouslyActiveTuns = appDataRepository.tunnels.getActive() tunnelConf,
val tunsToStart = status,
previouslyActiveTuns.filterNot { tun -> stats,
activeTunnels.value.any { tun.id == it.key.id } pingStates,
} handshakeSuccessLogs,
if (settings.isKernelEnabled) { )
return@launch tunsToStart.forEach { startTunnel(it) }
} else {
tunsToStart.firstOrNull()?.let { startTunnel(it) }
}
}
} }
} }
@@ -0,0 +1,269 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.logcatter.LogReader
import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.FailureReason
import com.zaneschepke.wireguardautotunnel.domain.state.PingState
import com.zaneschepke.wireguardautotunnel.util.extensions.toMillis
import com.zaneschepke.wireguardautotunnel.util.network.NetworkUtils
import dagger.hilt.android.scopes.ServiceScoped
import io.ktor.util.collections.*
import javax.inject.Inject
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.amnezia.awg.crypto.Key
import timber.log.Timber
@ServiceScoped
class TunnelMonitor
@Inject
constructor(
private val appDataRepository: AppDataRepository,
private val tunnelManager: TunnelManager,
private val networkMonitor: NetworkMonitor,
private val networkUtils: NetworkUtils,
private val logReader: LogReader,
) {
@OptIn(FlowPreview::class)
suspend fun startMonitoring(tunnelConf: TunnelConf, withLogs: Boolean): Job = coroutineScope {
launch {
launch { startTunnelConfChangesJob(tunnelConf) }
launch { startPingMonitor(tunnelConf) }
launch { startWgStatsPoll(tunnelConf) }
if (withLogs) launch { startLogsMonitor(tunnelConf) }
}
}
private suspend fun startTunnelConfChangesJob(tunnelConf: TunnelConf) {
appDataRepository.tunnels.flow
.map { storedTunnels -> storedTunnels.firstOrNull { it.id == tunnelConf.id } }
.filterNotNull()
.distinctUntilChanged { old, new -> old == new }
.collect { storedTunnel ->
if (tunnelConf != storedTunnel) {
Timber.d("Config changed for ${storedTunnel.tunName}, bouncing")
withContext(NonCancellable) {
tunnelManager.bounceTunnel(
storedTunnel,
TunnelStatus.StopReason.ConfigChanged,
)
}
}
}
}
private suspend fun startLogsMonitor(tunnelConf: TunnelConf) {
logReader.liveLogs.collect { log ->
val healthLogs =
when {
log.message.contains(HANDSHAKE_RESPONSE_TEXT, true) ||
log.message.contains(KEEPALIVE_RESPONSE_TEXT, true) -> true
log.message.contains(HANDSHAKE_INIT_FAILED_TEXT, true) ||
log.message.contains(HANDSHAKE_NOT_COMPLETED_TEXT) ||
log.message.contains(DATA_PACKET_FAILED_TEXT) -> false
else -> null
}
healthLogs?.let { healthy ->
tunnelManager.updateTunnelStatus(tunnelConf, null, null, null, healthy)
}
}
}
private suspend fun startPingMonitor(tunnelConf: TunnelConf) = coroutineScope {
val pingStatsFlow = MutableStateFlow<Map<Key, PingState>>(emptyMap())
val tunStateFlow =
tunnelManager.activeTunnels.mapNotNull { it.getValueById(tunnelConf.id) }.stateIn(this)
val connectivityStateFlow = networkMonitor.connectivityStateFlow.stateIn(this)
val isNetworkConnected = connectivityStateFlow.map { it.hasConnectivity() }.stateIn(this)
data class NetworkChangeKey(
val ethernetConnected: Boolean,
val wifiConnected: Boolean,
val cellularConnected: Boolean,
val wifiSsid: String?,
)
connectivityStateFlow
.map {
NetworkChangeKey(
ethernetConnected = it.ethernetConnected,
wifiConnected = it.wifiState.connected,
cellularConnected = it.cellularConnected,
wifiSsid = if (it.wifiState.connected) it.wifiState.ssid else null,
)
}
.distinctUntilChanged()
.stateIn(this)
appDataRepository.settings.flow
.distinctUntilChanged { old, new ->
old.isPingEnabled == new.isPingEnabled &&
old.tunnelPingIntervalSeconds == new.tunnelPingIntervalSeconds &&
old.tunnelPingAttempts == new.tunnelPingAttempts &&
old.tunnelPingTimeoutSeconds == new.tunnelPingTimeoutSeconds
}
.collectLatest { settings ->
if (!settings.isPingEnabled) return@collectLatest
Timber.d("Starting pinger for ${tunnelConf.tunName} with settings")
val config = tunnelConf.toAmConfig()
val pingablePeers = config.peers.filter { it.allowedIps.isNotEmpty() }
if (pingablePeers.isEmpty()) return@collectLatest
suspend fun performPing() {
val updates = ConcurrentMap<Key, PingState>()
pingablePeers.forEach { peer ->
val previousState = pingStatsFlow.value[peer.publicKey] ?: PingState()
val allowedIpStr = peer.allowedIps.firstOrNull()?.toString()
if (allowedIpStr == null) {
updates[peer.publicKey] =
previousState.copy(
isReachable = false,
failureReason = FailureReason.NoResolvedEndpoint,
lastPingAttemptMillis = System.currentTimeMillis(),
)
return@forEach
}
val host =
tunnelConf.pingTarget
?: {
val parts = allowedIpStr.split("/")
val internalIp =
if (parts.size == 2) parts[0] else allowedIpStr
val prefix =
if (parts.size == 2) parts[1].toIntOrNull() ?: 32
else 32
if (prefix <= 1) {
CLOUDFLARE_IPV4_IP
} else {
internalIp.removeSurrounding("[", "]")
}
}
.invoke()
val attemptTime = System.currentTimeMillis()
runCatching {
val pingStats =
settings.tunnelPingTimeoutSeconds?.let {
networkUtils.pingWithStats(
host,
settings.tunnelPingAttempts,
it.toMillis(),
)
}
?: networkUtils.pingWithStats(
host,
settings.tunnelPingAttempts,
)
updates[peer.publicKey] =
previousState.copy(
transmitted = pingStats.transmitted,
received = pingStats.received,
packetLoss = pingStats.packetLoss,
rttMin = pingStats.rttMin,
rttMax = pingStats.rttMax,
rttAvg = pingStats.rttAvg,
rttStddev = pingStats.rttStddev,
isReachable = pingStats.isReachable,
failureReason =
if (pingStats.isReachable) null
else FailureReason.PingFailed,
lastSuccessfulPingMillis =
pingStats.lastSuccessfulPingMillis
?: previousState.lastSuccessfulPingMillis,
pingTarget = host,
lastPingAttemptMillis = attemptTime,
)
Timber.d(
"Ping completed for peer ${peer.publicKey.toBase64().substring(0, 5)}.. to host $host with stats: $pingStats"
)
}
.onFailure {
Timber.e(
it,
"Ping failed for peer ${peer.publicKey} in ${tunnelConf.tunName} to host $host",
)
updates[peer.publicKey] =
previousState.copy(
isReachable = false,
failureReason = FailureReason.PingFailed,
pingTarget = host,
lastPingAttemptMillis = attemptTime,
)
}
}
if (updates.isNotEmpty()) {
pingStatsFlow.update { updates }
tunnelManager.updateTunnelStatus(tunnelConf, null, null, updates)
}
}
// Wait for the tunnel to be fully active
tunStateFlow.filter { state -> state.status == TunnelStatus.Up }.first()
// small delay to make sure tunnel is fully up before we actively monitor
delay(3_000L)
while (isActive) {
if (isNetworkConnected.value) {
performPing()
} else {
pingStatsFlow.update { current ->
current.mapValues { entry ->
entry.value.copy(
isReachable = false,
failureReason = FailureReason.NoConnectivity,
lastPingAttemptMillis = System.currentTimeMillis(),
)
}
}
tunnelManager.updateTunnelStatus(
tunnelConf,
null,
null,
pingStatsFlow.value,
)
}
delay(settings.tunnelPingIntervalSeconds.toMillis())
}
}
}
private suspend fun startWgStatsPoll(tunnelConf: TunnelConf) = coroutineScope {
while (isActive) {
val stats = tunnelManager.getStatistics(tunnelConf)
tunnelManager.updateTunnelStatus(tunnelConf, null, stats, null)
delay(STATS_DELAY)
}
}
companion object {
const val CLOUDFLARE_IPV6_IP = "2606:4700:4700::1111"
const val CLOUDFLARE_IPV4_IP = "1.1.1.1"
const val STATS_DELAY = 1_000L
const val KEEPALIVE_RESPONSE_TEXT = "Receiving keepalive packet"
const val HANDSHAKE_RESPONSE_TEXT = "Received handshake response"
const val HANDSHAKE_INIT_FAILED_TEXT = "Failed to send handshake initiation: write udp"
const val DATA_PACKET_FAILED_TEXT = "Failed to send data packets"
const val HANDSHAKE_NOT_COMPLETED_TEXT =
"Handshake did not complete after 5 seconds, retrying"
}
}
@@ -1,12 +1,17 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.domain.events.BackendMessage
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.state.PingState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState import com.zaneschepke.wireguardautotunnel.domain.state.TunnelState
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import org.amnezia.awg.crypto.Key
interface TunnelProvider { interface TunnelProvider {
/** Starts the specified tunnel configuration. */ /** Starts the specified tunnel configuration. */
@@ -21,24 +26,24 @@ interface TunnelProvider {
*/ */
suspend fun stopTunnel( suspend fun stopTunnel(
tunnelConf: TunnelConf? = null, tunnelConf: TunnelConf? = null,
reason: TunnelStatus.StopReason = TunnelStatus.StopReason.USER, reason: TunnelStatus.StopReason = TunnelStatus.StopReason.User,
) )
/** /**
* Bounces (stops and restarts) the specified tunnel. * Bounces (stops and restarts) the specified tunnel.
* *
* @param tunnelConf The tunnel to bounce. * @param tunnelConf The tunnel to bounce.
* @param reason The reason for bouncing, defaults to USER for manual actions. Callers should * @param reason The reason for bouncing, defaults to User for manual actions. Callers should
* override with specific reasons (e.g., PING, CONFIG_CHANGED) when applicable. * override with specific reasons (e.g., Ping, ConfigChanged) when applicable.
*/ */
suspend fun bounceTunnel( suspend fun bounceTunnel(
tunnelConf: TunnelConf, tunnelConf: TunnelConf,
reason: TunnelStatus.StopReason = TunnelStatus.StopReason.USER, reason: TunnelStatus.StopReason = TunnelStatus.StopReason.User,
) )
fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) fun setBackendMode(backendMode: BackendMode)
fun getBackendState(): BackendState fun getBackendMode(): BackendMode
suspend fun runningTunnelNames(): Set<String> suspend fun runningTunnelNames(): Set<String>
@@ -46,11 +51,19 @@ interface TunnelProvider {
val activeTunnels: StateFlow<Map<TunnelConf, TunnelState>> val activeTunnels: StateFlow<Map<TunnelConf, TunnelState>>
val errorEvents: SharedFlow<Pair<TunnelConf, BackendCoreException>>
val messageEvents: SharedFlow<Pair<TunnelConf, BackendMessage>>
val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason> val bouncingTunnelIds: ConcurrentHashMap<Int, TunnelStatus.StopReason>
fun hasVpnPermission(): Boolean fun hasVpnPermission(): Boolean
suspend fun clearError(tunnelConf: TunnelConf) suspend fun updateTunnelStatus(
tunnelConf: TunnelConf,
suspend fun updateTunnelStatistics(tunnel: TunnelConf) status: TunnelStatus? = null,
stats: TunnelStatistics? = null,
pingStates: Map<Key, PingState>? = null,
handshakeSuccessLogs: Boolean? = null,
)
} }
@@ -1,45 +1,100 @@
package com.zaneschepke.wireguardautotunnel.core.tunnel package com.zaneschepke.wireguardautotunnel.core.tunnel
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.di.ApplicationScope import com.zaneschepke.wireguardautotunnel.data.model.DnsProtocol
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import com.zaneschepke.wireguardautotunnel.domain.events.BackendCoreException
import com.zaneschepke.wireguardautotunnel.domain.model.AppProxySettings
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.state.AmneziaStatistics import com.zaneschepke.wireguardautotunnel.domain.state.AmneziaStatistics
import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics import com.zaneschepke.wireguardautotunnel.domain.state.TunnelStatistics
import com.zaneschepke.wireguardautotunnel.util.extensions.asAmBackendState import com.zaneschepke.wireguardautotunnel.util.extensions.asAmBackendMode
import com.zaneschepke.wireguardautotunnel.util.extensions.asBackendState import com.zaneschepke.wireguardautotunnel.util.extensions.asBackendMode
import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendError import com.zaneschepke.wireguardautotunnel.util.extensions.toBackendCoreException
import java.io.IOException
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import kotlin.jvm.optionals.getOrNull
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import org.amnezia.awg.backend.Backend import org.amnezia.awg.backend.Backend
import org.amnezia.awg.backend.BackendException import org.amnezia.awg.backend.BackendException
import org.amnezia.awg.backend.ProxyGoBackend
import org.amnezia.awg.backend.Tunnel import org.amnezia.awg.backend.Tunnel
import org.amnezia.awg.config.Config import org.amnezia.awg.config.Config
import org.amnezia.awg.config.DnsSettings
import org.amnezia.awg.config.proxy.HttpProxy
import org.amnezia.awg.config.proxy.Proxy
import org.amnezia.awg.config.proxy.Socks5Proxy
import timber.log.Timber import timber.log.Timber
class UserspaceTunnel class UserspaceTunnel
@Inject @Inject
constructor( constructor(
@ApplicationScope private val applicationScope: CoroutineScope, applicationScope: CoroutineScope,
val serviceManager: ServiceManager, val serviceManager: ServiceManager,
val appDataRepository: AppDataRepository, val appDataRepository: AppDataRepository,
private val backend: Backend, private val backend: Backend,
) : BaseTunnel(applicationScope, appDataRepository, serviceManager) { ) : BaseTunnel(applicationScope, appDataRepository, serviceManager) {
private var previousBackendState: Pair<BackendState, Boolean>? = null
override suspend fun startBackend(tunnel: TunnelConf) { override suspend fun startBackend(tunnel: TunnelConf) {
try { try {
updateTunnelStatus(tunnel, TunnelStatus.Starting) updateTunnelStatus(tunnel, TunnelStatus.Starting)
val amConfig = tunnel.toAmConfig()
handleVpnKillSwitchWithDomainEndpoints(amConfig) val proxies: List<Proxy> =
backend.setState(tunnel, Tunnel.State.UP, amConfig) when (backend) {
is ProxyGoBackend -> {
val proxySettings = appDataRepository.proxySettings.get()
Timber.d("Adding proxy configs")
buildList {
if (proxySettings.socks5ProxyEnabled) {
add(
Socks5Proxy(
proxySettings.socks5ProxyBindAddress
?: AppProxySettings.DEFAULT_SOCKS_BIND_ADDRESS,
proxySettings.proxyUsername,
proxySettings.proxyPassword,
)
)
}
if (proxySettings.httpProxyEnabled) {
add(
HttpProxy(
proxySettings.httpProxyBindAddress
?: AppProxySettings.DEFAULT_HTTP_BIND_ADDRESS,
proxySettings.proxyUsername,
proxySettings.proxyPassword,
)
)
}
}
}
else -> emptyList()
}
val setting = appDataRepository.settings.get()
val config = tunnel.toAmConfig()
val updatedConfig =
Config.Builder()
.apply {
setInterface(config.`interface`)
addPeers(config.peers)
addProxies(proxies)
setDnsSettings(
DnsSettings(
setting.dnsProtocol == DnsProtocol.DOH,
Optional.ofNullable(setting.dnsEndpoint),
)
)
}
.build()
backend.setState(tunnel, Tunnel.State.UP, updatedConfig)
} catch (e: BackendException) { } catch (e: BackendException) {
Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}") Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}")
throw e.toBackendError() throw e.toBackendCoreException()
} catch (e: IllegalArgumentException) {
Timber.e(e, "Failed to start up backend for tunnel ${tunnel.name}")
throw BackendCoreException.Config
} }
} }
@@ -49,47 +104,24 @@ constructor(
backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toAmConfig()) backend.setState(tunnel, Tunnel.State.DOWN, tunnel.toAmConfig())
} catch (e: BackendException) { } catch (e: BackendException) {
Timber.e(e, "Failed to stop tunnel ${tunnel.id}") Timber.e(e, "Failed to stop tunnel ${tunnel.id}")
throw e.toBackendError() throw e.toBackendCoreException()
}
handlePreviouslyEnabledVpnKillSwitch()
}
// stop vpn kill switch if we need to resolve DNS for peer endpoints
private suspend fun handleVpnKillSwitchWithDomainEndpoints(config: Config) {
if (
config.peers.any { it.endpoint.getOrNull()?.toString()?.isUrl() == true } &&
backend.backendState.asBackendState() == BackendState.KILL_SWITCH_ACTIVE
) {
val bypassLan = appDataRepository.settings.get().isLanOnKillSwitchEnabled
previousBackendState = Pair(BackendState.KILL_SWITCH_ACTIVE, bypassLan)
setBackendState(BackendState.SERVICE_ACTIVE, emptyList())
} }
} }
// restore vpn kill switch if needed override fun setBackendMode(backendMode: BackendMode) {
private fun handlePreviouslyEnabledVpnKillSwitch() { Timber.d("Setting backend mode: $backendMode")
// let auto tunnel handle this if it is active
if (!serviceManager.autoTunnelActive.value) {
previousBackendState?.let { (state, lanEnabled) ->
Timber.d("Restoring kill switch configuration")
val lan = if (lanEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS else emptyList()
backend.setBackendState(state.asAmBackendState(), lan)
}
}
previousBackendState = null
}
override fun setBackendState(backendState: BackendState, allowedIps: Collection<String>) {
Timber.d("Setting backend state: $backendState with allowedIps: $allowedIps")
try { try {
backend.setBackendState(backendState.asAmBackendState(), allowedIps) backend.backendMode = backendMode.asAmBackendMode()
} catch (e: BackendException) { } catch (e: BackendException) {
throw e.toBackendError() throw e.toBackendCoreException()
// TODO this should be mapped to BackendException in the lib
} catch (e: IOException) {
throw BackendCoreException.NotAuthorized
} }
} }
override fun getBackendState(): BackendState { override fun getBackendMode(): BackendMode {
return backend.backendState.asBackendState() return backend.backendMode.asBackendMode()
} }
override suspend fun runningTunnelNames(): Set<String> { override suspend fun runningTunnelNames(): Set<String> {
@@ -2,13 +2,8 @@ package com.zaneschepke.wireguardautotunnel.core.worker
import android.content.Context import android.content.Context
import androidx.hilt.work.HiltWorker import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker import androidx.work.*
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import dagger.assisted.Assisted import dagger.assisted.Assisted
@@ -27,7 +22,6 @@ constructor(
private val serviceManager: ServiceManager, private val serviceManager: ServiceManager,
private val appDataRepository: AppDataRepository, private val appDataRepository: AppDataRepository,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher, @IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val tunnelManager: TunnelManager,
) : CoroutineWorker(context, params) { ) : CoroutineWorker(context, params) {
companion object { companion object {
@@ -57,10 +51,11 @@ constructor(
withContext(ioDispatcher) { withContext(ioDispatcher) {
Timber.i("Service worker started") Timber.i("Service worker started")
with(appDataRepository.settings.get()) { with(appDataRepository.settings.get()) {
if (isAutoTunnelEnabled && !serviceManager.autoTunnelActive.value) Timber.i("Checking to see if auto-tunnel has been killed by system")
return@with serviceManager.startAutoTunnel() if (isAutoTunnelEnabled && serviceManager.autoTunnelService.value == null) {
if (tunnelManager.activeTunnels.value.isEmpty()) Timber.i("Service has been killed by system, restoring.")
tunnelManager.restorePreviousState() serviceManager.startAutoTunnel()
}
} }
Result.success() Result.success()
} }
@@ -1,19 +1,18 @@
package com.zaneschepke.wireguardautotunnel.data package com.zaneschepke.wireguardautotunnel.data
import androidx.room.AutoMigration import androidx.room.*
import androidx.room.Database
import androidx.room.DeleteColumn
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.AutoMigrationSpec import androidx.room.migration.AutoMigrationSpec
import androidx.sqlite.db.SupportSQLiteDatabase
import com.zaneschepke.wireguardautotunnel.data.dao.ProxySettingsDao
import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.model.Settings import com.zaneschepke.wireguardautotunnel.data.entity.ProxySettings
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.entity.Settings
import com.zaneschepke.wireguardautotunnel.data.entity.TunnelConfig
@Database( @Database(
entities = [Settings::class, TunnelConfig::class], entities = [Settings::class, TunnelConfig::class, ProxySettings::class],
version = 16, version = 21,
autoMigrations = autoMigrations =
[ [
AutoMigration(from = 1, to = 2), AutoMigration(from = 1, to = 2),
@@ -31,14 +30,21 @@ import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
AutoMigration(from = 13, to = 14), AutoMigration(from = 13, to = 14),
AutoMigration(from = 14, to = 15), AutoMigration(from = 14, to = 15),
AutoMigration(from = 15, to = 16), AutoMigration(from = 15, to = 16),
AutoMigration(from = 16, to = 17, spec = WifiDetectionMigration::class),
AutoMigration(from = 17, to = 18),
AutoMigration(from = 18, to = 19, spec = PingMigration::class),
AutoMigration(from = 19, to = 20, spec = ProxyMigration::class),
AutoMigration(from = 20, to = 21, spec = FixProxySettingsMigration::class),
], ],
exportSchema = true, exportSchema = true,
) )
@TypeConverters(DatabaseListConverters::class) @TypeConverters(DatabaseConverters::class)
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
abstract fun settingDao(): SettingsDao abstract fun settingDao(): SettingsDao
abstract fun tunnelConfigDoa(): TunnelConfigDao abstract fun tunnelConfigDoa(): TunnelConfigDao
abstract fun proxySettingsDoa(): ProxySettingsDao
} }
@DeleteColumn(tableName = "Settings", columnName = "default_tunnel") @DeleteColumn(tableName = "Settings", columnName = "default_tunnel")
@@ -47,3 +53,49 @@ class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
@DeleteColumn(tableName = "Settings", columnName = "is_auto_tunnel_paused") @DeleteColumn(tableName = "Settings", columnName = "is_auto_tunnel_paused")
class RemoveTunnelPauseMigration : AutoMigrationSpec class RemoveTunnelPauseMigration : AutoMigrationSpec
@DeleteColumn(tableName = "Settings", columnName = "is_wifi_by_shell_enabled")
class WifiDetectionMigration : AutoMigrationSpec
@DeleteColumn.Entries(
DeleteColumn(tableName = "TunnelConfig", columnName = "ping_interval"),
DeleteColumn(tableName = "TunnelConfig", columnName = "ping_cooldown"),
DeleteColumn(tableName = "Settings", columnName = "split_tunnel_apps"),
)
@RenameColumn.Entries(
RenameColumn(
tableName = "TunnelConfig",
fromColumnName = "is_ping_enabled",
toColumnName = "restart_on_ping_failure",
),
RenameColumn(
tableName = "TunnelConfig",
fromColumnName = "ping_ip",
toColumnName = "ping_target",
),
)
class PingMigration : AutoMigrationSpec
@DeleteColumn.Entries(
DeleteColumn(tableName = "Settings", columnName = "is_amnezia_enabled"),
DeleteColumn(tableName = "Settings", columnName = "is_vpn_kill_switch_enabled"),
DeleteColumn(tableName = "Settings", columnName = "is_kernel_kill_switch_enabled"),
DeleteColumn(tableName = "Settings", columnName = "is_kernel_enabled"),
)
class ProxyMigration : AutoMigrationSpec {
override fun onPostMigrate(db: SupportSQLiteDatabase) {
db.execSQL("INSERT INTO proxy_settings DEFAULT VALUES")
}
}
class FixProxySettingsMigration : AutoMigrationSpec {
override fun onPostMigrate(db: SupportSQLiteDatabase) {
val cursor = db.query("SELECT COUNT(*) FROM proxy_settings")
val count = if (cursor.moveToFirst()) cursor.getInt(0) else 0
cursor.close()
if (count == 0) {
db.execSQL("INSERT INTO proxy_settings DEFAULT VALUES")
}
}
}
@@ -25,12 +25,13 @@ class DataStoreManager(
val locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN") val locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN") val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED") val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED")
val tunnelStatsExpanded = booleanPreferencesKey("TUNNEL_STATS_EXPANDED") val expandedTunnelIds = stringPreferencesKey("EXPANDED_TUNNEL_IDS")
val isLocalLogsEnabled = booleanPreferencesKey("LOCAL_LOGS_ENABLED") val isLocalLogsEnabled = booleanPreferencesKey("LOCAL_LOGS_ENABLED")
val locale = stringPreferencesKey("LOCALE") val locale = stringPreferencesKey("LOCALE")
val theme = stringPreferencesKey("THEME") val theme = stringPreferencesKey("THEME")
val isRemoteControlEnabled = booleanPreferencesKey("IS_REMOTE_CONTROL_ENABLED") val isRemoteControlEnabled = booleanPreferencesKey("IS_REMOTE_CONTROL_ENABLED")
val remoteKey = stringPreferencesKey("REMOTE_KEY") val remoteKey = stringPreferencesKey("REMOTE_KEY")
val showDetailedPingStats = booleanPreferencesKey("SHOW_DETAILED_PING_STATS")
} }
// preferences // preferences
@@ -2,21 +2,25 @@ package com.zaneschepke.wireguardautotunnel.data
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase
import timber.log.Timber import com.zaneschepke.wireguardautotunnel.data.entity.ProxySettings
import com.zaneschepke.wireguardautotunnel.data.entity.Settings
import javax.inject.Inject
import javax.inject.Provider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DatabaseCallback : RoomDatabase.Callback() { class DatabaseCallback @Inject constructor(private val databaseProvider: Provider<AppDatabase>) :
override fun onCreate(db: SupportSQLiteDatabase) = RoomDatabase.Callback() {
db.run {
// Notice non-ui thread is here override fun onCreate(db: SupportSQLiteDatabase) {
beginTransaction() super.onCreate(db)
try {
execSQL(Queries.createDefaultSettings()) // Launch coroutine to insert default entry
Timber.i("Bootstrapping settings data") CoroutineScope(Dispatchers.IO).launch {
setTransactionSuccessful() val db = databaseProvider.get()
} catch (e: Exception) { db.settingDao().save(Settings())
Timber.e(e) db.proxySettingsDoa().save(ProxySettings())
} finally {
endTransaction()
} }
} }
} }
@@ -0,0 +1,39 @@
package com.zaneschepke.wireguardautotunnel.data
import androidx.room.TypeConverter
import com.zaneschepke.wireguardautotunnel.data.model.AppMode
import com.zaneschepke.wireguardautotunnel.data.model.DnsProtocol
import com.zaneschepke.wireguardautotunnel.data.model.WifiDetectionMethod
import kotlinx.serialization.json.Json
class DatabaseConverters {
@TypeConverter
fun listToString(value: List<String>): String {
return Json.encodeToString(value)
}
@TypeConverter
fun stringToList(value: String): List<String> {
if (value.isBlank() || value.isEmpty()) return mutableListOf()
return try {
Json.decodeFromString<List<String>>(value)
} catch (e: Exception) {
val list = value.split(",").toMutableList()
val json = listToString(list)
Json.decodeFromString<List<String>>(json)
}
}
@TypeConverter fun fromStatus(status: WifiDetectionMethod): Int = status.value
@TypeConverter
fun toStatus(value: Int): WifiDetectionMethod = WifiDetectionMethod.fromValue(value)
@TypeConverter fun toMode(value: Int): AppMode = AppMode.fromValue(value)
@TypeConverter fun fromMode(mode: AppMode): Int = mode.value
@TypeConverter fun toDnsProtocol(value: Int): DnsProtocol = DnsProtocol.fromValue(value)
@TypeConverter fun fromDnsProtocol(mode: DnsProtocol): Int = mode.value
}
@@ -1,23 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data
import androidx.room.TypeConverter
import kotlinx.serialization.json.Json
class DatabaseListConverters {
@TypeConverter
fun listToString(value: MutableList<String>): String {
return Json.encodeToString(value)
}
@TypeConverter
fun stringToList(value: String): MutableList<String> {
if (value.isBlank() || value.isEmpty()) return mutableListOf()
return try {
Json.decodeFromString<MutableList<String>>(value)
} catch (e: Exception) {
val list = value.split(",").toMutableList()
val json = listToString(list)
Json.decodeFromString<MutableList<String>>(json)
}
}
}
@@ -1,37 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data
object Queries {
fun createDefaultSettings(): String {
return """
INSERT INTO Settings (is_tunnel_enabled,
is_tunnel_on_mobile_data_enabled,
trusted_network_ssids,
is_always_on_vpn_enabled,
is_tunnel_on_ethernet_enabled,
is_shortcuts_enabled,
is_tunnel_on_wifi_enabled,
is_kernel_enabled,
is_restore_on_boot_enabled,
is_multi_tunnel_enabled)
VALUES
('false',
'false',
'',
'false',
'false',
'false',
'false',
'false',
'false',
'false')
"""
.trimIndent()
}
fun createTunnelConfig(): String {
return """
INSERT INTO TunnelConfig (name, wg_quick) VALUES ('test', 'test')
"""
.trimIndent()
}
}
@@ -0,0 +1,25 @@
package com.zaneschepke.wireguardautotunnel.data.dao
import androidx.room.*
import com.zaneschepke.wireguardautotunnel.data.entity.ProxySettings
import kotlinx.coroutines.flow.Flow
@Dao
interface ProxySettingsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(t: ProxySettings)
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveAll(t: List<ProxySettings>)
@Query("SELECT * FROM proxy_settings WHERE id=:id")
suspend fun getById(id: Long): ProxySettings?
@Query("SELECT * FROM proxy_settings") suspend fun getAll(): List<ProxySettings>
@Query("SELECT * FROM proxy_settings LIMIT 1") fun getSettingsFlow(): Flow<ProxySettings>
@Query("SELECT * FROM proxy_settings") fun getAllFlow(): Flow<List<ProxySettings>>
@Delete suspend fun delete(t: ProxySettings)
@Query("SELECT COUNT('id') FROM proxy_settings") suspend fun count(): Long
}
@@ -1,11 +1,7 @@
package com.zaneschepke.wireguardautotunnel.data.dao package com.zaneschepke.wireguardautotunnel.data.dao
import androidx.room.Dao import androidx.room.*
import androidx.room.Delete import com.zaneschepke.wireguardautotunnel.data.entity.Settings
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.zaneschepke.wireguardautotunnel.data.model.Settings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
@@ -20,7 +16,7 @@ interface SettingsDao {
@Query("SELECT * FROM settings LIMIT 1") fun getSettingsFlow(): Flow<Settings> @Query("SELECT * FROM settings LIMIT 1") fun getSettingsFlow(): Flow<Settings>
@Query("SELECT * FROM settings") fun getAllFlow(): Flow<MutableList<Settings>> @Query("SELECT * FROM settings") fun getAllFlow(): Flow<List<Settings>>
@Delete suspend fun delete(t: Settings) @Delete suspend fun delete(t: Settings)
@@ -1,11 +1,7 @@
package com.zaneschepke.wireguardautotunnel.data.dao package com.zaneschepke.wireguardautotunnel.data.dao
import androidx.room.Dao import androidx.room.*
import androidx.room.Delete import com.zaneschepke.wireguardautotunnel.data.entity.TunnelConfig
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -46,5 +42,6 @@ interface TunnelConfigDao {
@Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1") @Query("SELECT * FROM TUNNELCONFIG WHERE is_mobile_data_tunnel=1")
suspend fun findByMobileDataTunnel(): TunnelConfigs suspend fun findByMobileDataTunnel(): TunnelConfigs
@Query("SELECT * FROM tunnelconfig") fun getAllFlow(): Flow<MutableList<TunnelConfig>> @Query("SELECT * FROM tunnelconfig ORDER BY position")
fun getAllFlow(): Flow<List<TunnelConfig>>
} }
@@ -0,0 +1,10 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Asset(
val name: String,
@SerialName("browser_download_url") val browserDownloadUrl: String,
)
@@ -0,0 +1,26 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
data class GeneralState(
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val expandedTunnelIds: List<Int> = emptyList(),
val isLocalLogsEnabled: Boolean = IS_LOGS_ENABLED_DEFAULT,
val isRemoteControlEnabled: Boolean = IS_REMOTE_CONTROL_ENABLED,
val showDetailedPingStats: Boolean = SHOW_DETAILED_PING_STATS_DEFAULT,
val remoteKey: String? = null,
val locale: String? = null,
val theme: Theme = Theme.AUTOMATIC,
) {
companion object {
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false
const val IS_LOGS_ENABLED_DEFAULT = false
const val IS_REMOTE_CONTROL_ENABLED = false
const val SHOW_DETAILED_PING_STATS_DEFAULT = false
}
}
@@ -0,0 +1,12 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GitHubRelease(
@SerialName("tag_name") val tagName: String,
val name: String?,
val body: String?,
val assets: List<Asset>,
)
@@ -0,0 +1,18 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "proxy_settings")
data class ProxySettings(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@ColumnInfo(name = "socks5_proxy_enabled", defaultValue = "false")
val socks5ProxyEnabled: Boolean = false,
@ColumnInfo(name = "socks5_proxy_bind_address") val socks5ProxyBindAddress: String? = null,
@ColumnInfo(name = "http_proxy_enable", defaultValue = "false")
val httpProxyEnabled: Boolean = false,
@ColumnInfo(name = "http_proxy_bind_address") val httpProxyBindAddress: String? = null,
@ColumnInfo(name = "proxy_username") val proxyUsername: String? = null,
@ColumnInfo(name = "proxy_password") val proxyPassword: String? = null,
)
@@ -0,0 +1,54 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.zaneschepke.wireguardautotunnel.data.model.AppMode
import com.zaneschepke.wireguardautotunnel.data.model.DnsProtocol
import com.zaneschepke.wireguardautotunnel.data.model.WifiDetectionMethod
@Entity
data class Settings(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
val isTunnelOnMobileDataEnabled: Boolean = false,
@ColumnInfo(name = "trusted_network_ssids") val trustedNetworkSSIDs: List<String> = emptyList(),
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
val isTunnelOnEthernetEnabled: Boolean = false,
@ColumnInfo(name = "is_shortcuts_enabled", defaultValue = "false")
val isShortcutsEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_wifi_enabled", defaultValue = "false")
val isTunnelOnWifiEnabled: Boolean = false,
@ColumnInfo(name = "is_restore_on_boot_enabled", defaultValue = "false")
val isRestoreOnBootEnabled: Boolean = false,
@ColumnInfo(name = "is_multi_tunnel_enabled", defaultValue = "false")
val isMultiTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_ping_enabled", defaultValue = "false")
val isPingEnabled: Boolean = false,
@ColumnInfo(name = "is_wildcards_enabled", defaultValue = "false")
val isWildcardsEnabled: Boolean = false,
@ColumnInfo(name = "is_stop_on_no_internet_enabled", defaultValue = "false")
val isStopOnNoInternetEnabled: Boolean = false,
@ColumnInfo(name = "is_lan_on_kill_switch_enabled", defaultValue = "false")
val isLanOnKillSwitchEnabled: Boolean = false,
@ColumnInfo(name = "debounce_delay_seconds", defaultValue = "3")
val debounceDelaySeconds: Int = 3,
@ColumnInfo(name = "is_disable_kill_switch_on_trusted_enabled", defaultValue = "false")
val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_unsecure_enabled", defaultValue = "false")
val isTunnelOnUnsecureEnabled: Boolean = false,
@ColumnInfo(name = "wifi_detection_method", defaultValue = "0")
val wifiDetectionMethod: WifiDetectionMethod = WifiDetectionMethod.fromValue(0),
@ColumnInfo(name = "is_ping_monitoring_enabled", defaultValue = "true")
val isPingMonitoringEnabled: Boolean = true,
@ColumnInfo(name = "tunnel_ping_interval_sec", defaultValue = "30")
val tunnelPingIntervalSeconds: Int = 30,
@ColumnInfo(name = "tunnel_ping_attempts", defaultValue = "3") val tunnelPingAttempts: Int = 3,
@ColumnInfo(name = "tunnel_ping_timeout_sec") val tunnelPingTimeoutSeconds: Int? = null,
@ColumnInfo(name = "app_mode", defaultValue = "0") val appMode: AppMode = AppMode.fromValue(0),
@ColumnInfo(name = "dns_protocol", defaultValue = "0")
val dnsProtocol: DnsProtocol = DnsProtocol.fromValue(0),
@ColumnInfo(name = "dns_endpoint") val dnsEndpoint: String? = null,
)
@@ -0,0 +1,36 @@
package com.zaneschepke.wireguardautotunnel.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(indices = [Index(value = ["name"], unique = true)])
data class TunnelConfig(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "wg_quick") val wgQuick: String,
@ColumnInfo(name = "tunnel_networks", defaultValue = "")
val tunnelNetworks: List<String> = listOf(),
@ColumnInfo(name = "is_mobile_data_tunnel", defaultValue = "false")
val isMobileDataTunnel: Boolean = false,
@ColumnInfo(name = "is_primary_tunnel", defaultValue = "false")
val isPrimaryTunnel: Boolean = false,
@ColumnInfo(name = "am_quick", defaultValue = "") val amQuick: String = AM_QUICK_DEFAULT,
@ColumnInfo(name = "is_Active", defaultValue = "false") val isActive: Boolean = false,
@ColumnInfo(name = "restart_on_ping_failure", defaultValue = "false")
val restartOnPingFailure: Boolean = false,
@ColumnInfo(name = "ping_target", defaultValue = "null") var pingTarget: String? = null,
@ColumnInfo(name = "is_ethernet_tunnel", defaultValue = "false")
val isEthernetTunnel: Boolean = false,
@ColumnInfo(name = "is_ipv4_preferred", defaultValue = "true")
val isIpv4Preferred: Boolean = true,
@ColumnInfo(name = "position", defaultValue = "0") val position: Int = 0,
@ColumnInfo(name = "auto_tunnel_apps", defaultValue = "[]")
val autoTunnelApps: List<String> = listOf(),
) {
companion object {
const val AM_QUICK_DEFAULT = ""
}
}
@@ -0,0 +1,39 @@
package com.zaneschepke.wireguardautotunnel.data.mapper
import com.zaneschepke.wireguardautotunnel.data.entity.GeneralState
import com.zaneschepke.wireguardautotunnel.domain.model.AppState
object GeneralStateMapper {
fun toAppState(generalState: GeneralState): AppState =
with(generalState) {
AppState(
isLocationDisclosureShown,
isBatteryOptimizationDisableShown,
isPinLockEnabled,
expandedTunnelIds,
isLocalLogsEnabled,
isRemoteControlEnabled,
showDetailedPingStats,
remoteKey,
locale,
theme,
)
}
fun toGeneralState(appState: AppState): GeneralState {
return with(appState) {
GeneralState(
isLocationDisclosureShown,
isBatteryOptimizationDisableShown,
isPinLockEnabled,
expandedTunnelIds,
isLocalLogsEnabled,
isRemoteControlEnabled,
showDetailedPingStats,
remoteKey,
locale,
theme,
)
}
}
}
@@ -0,0 +1,19 @@
package com.zaneschepke.wireguardautotunnel.data.mapper
import com.zaneschepke.wireguardautotunnel.data.entity.GitHubRelease
import com.zaneschepke.wireguardautotunnel.domain.model.AppUpdate
object GitHubReleaseMapper {
fun toAppUpdate(gitHubRelease: GitHubRelease, newVersion: String): AppUpdate {
with(gitHubRelease) {
val apkAsset = assets.firstOrNull { it.name.endsWith(".apk") }
return AppUpdate(
version = newVersion,
title = name ?: "Update $tagName",
releaseNotes = body ?: "No release notes provided",
apkUrl = apkAsset?.browserDownloadUrl,
apkFileName = apkAsset?.name,
)
}
}
}
@@ -0,0 +1,32 @@
package com.zaneschepke.wireguardautotunnel.data.mapper
import com.zaneschepke.wireguardautotunnel.data.entity.ProxySettings
import com.zaneschepke.wireguardautotunnel.domain.model.AppProxySettings
object ProxySettingsMapper {
fun to(proxySettings: ProxySettings): AppProxySettings =
with(proxySettings) {
AppProxySettings(
id,
socks5ProxyEnabled,
socks5ProxyBindAddress,
httpProxyEnabled,
httpProxyBindAddress,
proxyUsername,
proxyPassword,
)
}
fun to(proxySettings: AppProxySettings): ProxySettings =
with(proxySettings) {
ProxySettings(
id,
socks5ProxyEnabled,
socks5ProxyBindAddress,
httpProxyEnabled,
httpProxyBindAddress,
proxyUsername,
proxyPassword,
)
}
}
@@ -0,0 +1,79 @@
package com.zaneschepke.wireguardautotunnel.data.mapper
import com.zaneschepke.networkmonitor.AndroidNetworkMonitor
import com.zaneschepke.wireguardautotunnel.data.entity.Settings
import com.zaneschepke.wireguardautotunnel.data.model.DnsProtocol
import com.zaneschepke.wireguardautotunnel.data.model.DnsSettings
import com.zaneschepke.wireguardautotunnel.data.model.WifiDetectionMethod
import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
fun Settings.toAppSettings(): AppSettings {
return AppSettings(
id = id,
isAutoTunnelEnabled = isAutoTunnelEnabled,
isTunnelOnMobileDataEnabled = isTunnelOnMobileDataEnabled,
trustedNetworkSSIDs = trustedNetworkSSIDs,
isAlwaysOnVpnEnabled = isAlwaysOnVpnEnabled,
isTunnelOnEthernetEnabled = isTunnelOnEthernetEnabled,
isShortcutsEnabled = isShortcutsEnabled,
isTunnelOnWifiEnabled = isTunnelOnWifiEnabled,
isRestoreOnBootEnabled = isRestoreOnBootEnabled,
isMultiTunnelEnabled = isMultiTunnelEnabled,
isPingEnabled = isPingEnabled,
isWildcardsEnabled = isWildcardsEnabled,
isStopOnNoInternetEnabled = isStopOnNoInternetEnabled,
isLanOnKillSwitchEnabled = isLanOnKillSwitchEnabled,
debounceDelaySeconds = debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled = isDisableKillSwitchOnTrustedEnabled,
isTunnelOnUnsecureEnabled = isTunnelOnUnsecureEnabled,
wifiDetectionMethod =
AndroidNetworkMonitor.WifiDetectionMethod.fromValue(wifiDetectionMethod.value),
tunnelPingIntervalSeconds = tunnelPingIntervalSeconds,
tunnelPingAttempts = tunnelPingAttempts,
tunnelPingTimeoutSeconds = tunnelPingTimeoutSeconds,
appMode = appMode,
dnsProtocol = dnsProtocol,
dnsEndpoint = dnsEndpoint,
)
}
fun AppSettings.toSettings(): Settings {
return Settings(
id = id,
isAutoTunnelEnabled = isAutoTunnelEnabled,
isTunnelOnMobileDataEnabled = isTunnelOnMobileDataEnabled,
trustedNetworkSSIDs = trustedNetworkSSIDs,
isAlwaysOnVpnEnabled = isAlwaysOnVpnEnabled,
isTunnelOnEthernetEnabled = isTunnelOnEthernetEnabled,
isShortcutsEnabled = isShortcutsEnabled,
isTunnelOnWifiEnabled = isTunnelOnWifiEnabled,
isRestoreOnBootEnabled = isRestoreOnBootEnabled,
isMultiTunnelEnabled = isMultiTunnelEnabled,
isPingEnabled = isPingEnabled,
isWildcardsEnabled = isWildcardsEnabled,
isStopOnNoInternetEnabled = isStopOnNoInternetEnabled,
isLanOnKillSwitchEnabled = isLanOnKillSwitchEnabled,
debounceDelaySeconds = debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled = isDisableKillSwitchOnTrustedEnabled,
isTunnelOnUnsecureEnabled = isTunnelOnUnsecureEnabled,
wifiDetectionMethod = WifiDetectionMethod.fromValue(wifiDetectionMethod.value),
tunnelPingIntervalSeconds = tunnelPingIntervalSeconds,
tunnelPingAttempts = tunnelPingAttempts,
tunnelPingTimeoutSeconds = tunnelPingTimeoutSeconds,
appMode = appMode,
dnsProtocol = dnsProtocol,
dnsEndpoint = dnsEndpoint,
)
}
fun AppSettings.toDomain(): DnsSettings {
return DnsSettings(
protocol =
DnsProtocol.entries.toTypedArray().getOrElse(dnsProtocol.value) { DnsProtocol.SYSTEM },
endpoint = dnsEndpoint,
)
}
fun DnsSettings.toAppSettings(existing: AppSettings): AppSettings {
return existing.copy(dnsProtocol = protocol, dnsEndpoint = endpoint)
}
@@ -0,0 +1,46 @@
package com.zaneschepke.wireguardautotunnel.data.mapper
import com.zaneschepke.wireguardautotunnel.data.entity.TunnelConfig
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
object TunnelConfigMapper {
fun toTunnelConf(tunnelConfig: TunnelConfig): TunnelConf {
return with(tunnelConfig) {
TunnelConf(
id,
name,
wgQuick,
tunnelNetworks,
isMobileDataTunnel,
isPrimaryTunnel,
amQuick,
isActive,
pingTarget,
restartOnPingFailure,
isEthernetTunnel,
isIpv4Preferred,
position,
)
}
}
fun toTunnelConfig(tunnelConf: TunnelConf): TunnelConfig {
return with(tunnelConf) {
TunnelConfig(
id,
tunName,
wgQuick,
tunnelNetworks,
isMobileDataTunnel,
isPrimaryTunnel,
amQuick,
isActive,
restartOnPingFailure,
pingTarget,
isEthernetTunnel,
isIpv4Preferred,
position,
)
}
}
}
@@ -0,0 +1,12 @@
package com.zaneschepke.wireguardautotunnel.data.model
enum class AppMode(val value: Int) {
VPN(0),
PROXY(1),
LOCK_DOWN(2),
KERNEL(3);
companion object {
fun fromValue(value: Int): AppMode = entries.find { it.value == value } ?: VPN
}
}
@@ -0,0 +1,45 @@
package com.zaneschepke.wireguardautotunnel.data.model
import android.content.Context
import com.zaneschepke.wireguardautotunnel.R
enum class DnsProtocol(val value: Int) {
SYSTEM(0),
DOH(1);
fun asString(context: Context): String {
return when (this) {
SYSTEM -> context.getString(R.string.system)
DOH -> context.getString(R.string.doh)
}
}
companion object {
fun fromValue(value: Int): DnsProtocol =
DnsProtocol.entries.find { it.value == value } ?: SYSTEM
}
}
data class DnsSettings(
val protocol: DnsProtocol = DnsProtocol.SYSTEM,
val endpoint: String? = null,
)
enum class DnsProvider(private val systemAddress: String, private val dohAddress: String) {
CLOUDFLARE("1.1.1.1", "https://1.1.1.1/dns-query"),
ADGUARD("94.140.14.14", "https://94.140.14.14/dns-query");
fun asAddress(protocol: DnsProtocol): String {
return when (protocol) {
DnsProtocol.SYSTEM -> systemAddress
DnsProtocol.DOH -> dohAddress
}
}
companion object {
fun fromAddress(address: String): DnsProvider {
return entries.find { it.systemAddress == address || it.dohAddress == address }
?: CLOUDFLARE
}
}
}
@@ -1,55 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.model
import com.zaneschepke.wireguardautotunnel.domain.entity.AppState
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
data class GeneralState(
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
val isLocalLogsEnabled: Boolean = IS_LOGS_ENABLED_DEFAULT,
val isRemoteControlEnabled: Boolean = IS_REMOTE_CONTROL_ENABLED,
val remoteKey: String? = null,
val locale: String? = null,
val theme: Theme = Theme.AUTOMATIC,
) {
fun toAppState(): AppState =
AppState(
isLocationDisclosureShown,
isBatteryOptimizationDisableShown,
isPinLockEnabled,
isTunnelStatsExpanded,
isLocalLogsEnabled,
isRemoteControlEnabled,
remoteKey,
locale,
theme,
)
companion object {
fun from(appState: AppState): GeneralState {
return with(appState) {
GeneralState(
isLocationDisclosureShown,
isBatteryOptimizationDisableShown,
isPinLockEnabled,
isTunnelStatsExpanded,
isLocalLogsEnabled,
isRemoteControlEnabled,
remoteKey,
locale,
theme,
)
}
}
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
const val PIN_LOCK_ENABLED_DEFAULT = false
const val IS_TUNNEL_STATS_EXPANDED = false
const val IS_LOGS_ENABLED_DEFAULT = false
const val IS_REMOTE_CONTROL_ENABLED = false
}
}
@@ -1,106 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
@Entity
data class Settings(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "is_tunnel_enabled") val isAutoTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_mobile_data_enabled")
val isTunnelOnMobileDataEnabled: Boolean = false,
@ColumnInfo(name = "trusted_network_ssids")
val trustedNetworkSSIDs: MutableList<String> = mutableListOf(),
@ColumnInfo(name = "is_always_on_vpn_enabled") val isAlwaysOnVpnEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_ethernet_enabled")
val isTunnelOnEthernetEnabled: Boolean = false,
@ColumnInfo(name = "is_shortcuts_enabled", defaultValue = "false")
val isShortcutsEnabled: Boolean = false,
@ColumnInfo(name = "is_tunnel_on_wifi_enabled", defaultValue = "false")
val isTunnelOnWifiEnabled: Boolean = false,
@ColumnInfo(name = "is_kernel_enabled", defaultValue = "false")
val isKernelEnabled: Boolean = false,
@ColumnInfo(name = "is_restore_on_boot_enabled", defaultValue = "false")
val isRestoreOnBootEnabled: Boolean = false,
@ColumnInfo(name = "is_multi_tunnel_enabled", defaultValue = "false")
val isMultiTunnelEnabled: Boolean = false,
@ColumnInfo(name = "is_ping_enabled", defaultValue = "false")
val isPingEnabled: Boolean = false,
@ColumnInfo(name = "is_amnezia_enabled", defaultValue = "false")
val isAmneziaEnabled: Boolean = false,
@ColumnInfo(name = "is_wildcards_enabled", defaultValue = "false")
val isWildcardsEnabled: Boolean = false,
@ColumnInfo(name = "is_wifi_by_shell_enabled", defaultValue = "false")
val isWifiNameByShellEnabled: Boolean = false,
@ColumnInfo(name = "is_stop_on_no_internet_enabled", defaultValue = "false")
val isStopOnNoInternetEnabled: Boolean = false,
@ColumnInfo(name = "is_vpn_kill_switch_enabled", defaultValue = "false")
val isVpnKillSwitchEnabled: Boolean = false,
@ColumnInfo(name = "is_kernel_kill_switch_enabled", defaultValue = "false")
val isKernelKillSwitchEnabled: Boolean = false,
@ColumnInfo(name = "is_lan_on_kill_switch_enabled", defaultValue = "false")
val isLanOnKillSwitchEnabled: Boolean = false,
@ColumnInfo(name = "debounce_delay_seconds", defaultValue = "3")
val debounceDelaySeconds: Int = 3,
@ColumnInfo(name = "is_disable_kill_switch_on_trusted_enabled", defaultValue = "false")
val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
) {
fun toAppSettings(): AppSettings {
return AppSettings(
id,
isAutoTunnelEnabled,
isTunnelOnMobileDataEnabled,
trustedNetworkSSIDs,
isAlwaysOnVpnEnabled,
isTunnelOnEthernetEnabled,
isShortcutsEnabled,
isTunnelOnWifiEnabled,
isKernelEnabled,
isRestoreOnBootEnabled,
isMultiTunnelEnabled,
isPingEnabled,
isAmneziaEnabled,
isWildcardsEnabled,
isWifiNameByShellEnabled,
isStopOnNoInternetEnabled,
isVpnKillSwitchEnabled,
isKernelKillSwitchEnabled,
isLanOnKillSwitchEnabled,
debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled,
)
}
companion object {
fun from(appSettings: AppSettings): Settings {
return with(appSettings) {
Settings(
id,
isAutoTunnelEnabled,
isTunnelOnMobileDataEnabled,
trustedNetworkSSIDs.toMutableList(),
isAlwaysOnVpnEnabled,
isTunnelOnEthernetEnabled,
isShortcutsEnabled,
isTunnelOnWifiEnabled,
isKernelEnabled,
isRestoreOnBootEnabled,
isMultiTunnelEnabled,
isPingEnabled,
isAmneziaEnabled,
isWildcardsEnabled,
isWifiNameByShellEnabled,
isStopOnNoInternetEnabled,
isVpnKillSwitchEnabled,
isKernelKillSwitchEnabled,
isLanOnKillSwitchEnabled,
debounceDelaySeconds,
isDisableKillSwitchOnTrustedEnabled,
)
}
}
}
}
@@ -1,77 +0,0 @@
package com.zaneschepke.wireguardautotunnel.data.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
@Entity(indices = [Index(value = ["name"], unique = true)])
data class TunnelConfig(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "wg_quick") val wgQuick: String,
@ColumnInfo(name = "tunnel_networks", defaultValue = "")
val tunnelNetworks: MutableList<String> = mutableListOf(),
@ColumnInfo(name = "is_mobile_data_tunnel", defaultValue = "false")
val isMobileDataTunnel: Boolean = false,
@ColumnInfo(name = "is_primary_tunnel", defaultValue = "false")
val isPrimaryTunnel: Boolean = false,
@ColumnInfo(name = "am_quick", defaultValue = "") val amQuick: String = AM_QUICK_DEFAULT,
@ColumnInfo(name = "is_Active", defaultValue = "false") val isActive: Boolean = false,
@ColumnInfo(name = "is_ping_enabled", defaultValue = "false")
val isPingEnabled: Boolean = false,
@ColumnInfo(name = "ping_interval", defaultValue = "null") val pingInterval: Long? = null,
@ColumnInfo(name = "ping_cooldown", defaultValue = "null") val pingCooldown: Long? = null,
@ColumnInfo(name = "ping_ip", defaultValue = "null") var pingIp: String? = null,
@ColumnInfo(name = "is_ethernet_tunnel", defaultValue = "false")
var isEthernetTunnel: Boolean = false,
@ColumnInfo(name = "is_ipv4_preferred", defaultValue = "true")
var isIpv4Preferred: Boolean = true,
) {
fun toTunnel(): TunnelConf {
return TunnelConf(
id,
name,
wgQuick,
tunnelNetworks,
isMobileDataTunnel,
isPrimaryTunnel,
amQuick,
isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp,
isEthernetTunnel,
isIpv4Preferred,
)
}
companion object {
const val AM_QUICK_DEFAULT = ""
fun from(tunnelConf: TunnelConf): TunnelConfig {
return with(tunnelConf) {
return TunnelConfig(
id,
tunName,
wgQuick,
tunnelNetworks.toMutableList(),
isMobileDataTunnel,
isPrimaryTunnel,
amQuick,
isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp,
isEthernetTunnel,
isIpv4Preferred,
)
}
}
}
}
@@ -0,0 +1,13 @@
package com.zaneschepke.wireguardautotunnel.data.model
enum class WifiDetectionMethod(val value: Int) {
DEFAULT(0),
LEGACY(1),
ROOT(2),
SHIZUKU(3);
companion object {
fun fromValue(value: Int): WifiDetectionMethod =
entries.find { it.value == value } ?: DEFAULT
}
}
@@ -0,0 +1,9 @@
package com.zaneschepke.wireguardautotunnel.data.network
import com.zaneschepke.wireguardautotunnel.data.entity.GitHubRelease
interface GitHubApi {
suspend fun getLatestRelease(owner: String, repo: String): Result<GitHubRelease>
suspend fun getNightlyRelease(owner: String, repo: String): Result<GitHubRelease>
}
@@ -0,0 +1,28 @@
package com.zaneschepke.wireguardautotunnel.data.network
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
object KtorClient {
fun create(): HttpClient {
return HttpClient(OkHttp) {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
isLenient = true
}
)
}
install(HttpTimeout) {
requestTimeoutMillis = 15000
connectTimeoutMillis = 15000
socketTimeoutMillis = 15000
}
}
}
}
@@ -0,0 +1,56 @@
package com.zaneschepke.wireguardautotunnel.data.network
import com.zaneschepke.wireguardautotunnel.data.entity.GitHubRelease
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
class KtorGitHubApi(private val client: HttpClient) : GitHubApi {
override suspend fun getLatestRelease(owner: String, repo: String): Result<GitHubRelease> {
return try {
val response: GitHubRelease =
client.get("https://api.github.com/repos/$owner/$repo/releases/latest").body()
Result.success(response)
} catch (e: ClientRequestException) {
when (e.response.status) {
HttpStatusCode.Forbidden -> Result.failure(Exception("Rate limit exceeded"))
HttpStatusCode.NotFound ->
Result.failure(Exception("Repository or release not found"))
else -> Result.failure(e)
}
} catch (e: Exception) {
Result.failure(e)
}
}
override suspend fun getNightlyRelease(owner: String, repo: String): Result<GitHubRelease> {
return try {
// Fetch all releases
val releases: List<GitHubRelease> =
client.get("https://api.github.com/repos/$owner/$repo/releases").body()
// Find the first release with "nightly" in the tag_name (case-insensitive)
val nightlyRelease =
releases.firstOrNull { release ->
release.tagName.contains("nightly", ignoreCase = true)
}
if (nightlyRelease != null) {
Result.success(nightlyRelease)
} else {
Result.failure(Exception("No release with 'nightly' tag found"))
}
} catch (e: ClientRequestException) {
when (e.response.status) {
HttpStatusCode.Forbidden -> Result.failure(Exception("Rate limit exceeded"))
HttpStatusCode.NotFound ->
Result.failure(Exception("Repository or release not found"))
else -> Result.failure(e)
}
} catch (e: Exception) {
Result.failure(e)
}
}
}
@@ -1,10 +1,7 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.*
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import javax.inject.Inject import javax.inject.Inject
class AppDataRoomRepository class AppDataRoomRepository
@@ -13,6 +10,7 @@ constructor(
override val settings: AppSettingRepository, override val settings: AppSettingRepository,
override val tunnels: TunnelRepository, override val tunnels: TunnelRepository,
override val appState: AppStateRepository, override val appState: AppStateRepository,
override val proxySettings: ProxySettingsRepository,
) : AppDataRepository { ) : AppDataRepository {
override suspend fun getPrimaryOrFirstTunnel(): TunnelConf? { override suspend fun getPrimaryOrFirstTunnel(): TunnelConf? {
@@ -1,8 +1,9 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.model.GeneralState import com.zaneschepke.wireguardautotunnel.data.entity.GeneralState
import com.zaneschepke.wireguardautotunnel.domain.entity.AppState import com.zaneschepke.wireguardautotunnel.data.mapper.GeneralStateMapper
import com.zaneschepke.wireguardautotunnel.domain.model.AppState
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -38,13 +39,36 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown) dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown)
} }
override suspend fun isTunnelStatsExpanded(): Boolean { override suspend fun setTunnelExpanded(id: Int) {
return dataStoreManager.getFromStore(DataStoreManager.tunnelStatsExpanded) val ids =
?: GeneralState.IS_TUNNEL_STATS_EXPANDED dataStoreManager
.getFromStore(DataStoreManager.expandedTunnelIds)
?.split(",")
?.mapNotNull { it.toIntOrNull() } ?: emptyList()
if (ids.contains(id)) return
val updatedList = ids.toMutableList().apply { add(id) }
dataStoreManager.saveToDataStore(
DataStoreManager.expandedTunnelIds,
updatedList.joinToString(","),
)
} }
override suspend fun setTunnelStatsExpanded(expanded: Boolean) { override suspend fun removeTunnelExpanded(id: Int) {
dataStoreManager.saveToDataStore(DataStoreManager.tunnelStatsExpanded, expanded) val ids =
dataStoreManager
.getFromStore(DataStoreManager.expandedTunnelIds)
?.split(",")
?.mapNotNull { it.toIntOrNull() } ?: emptyList()
if (ids.isEmpty() || !ids.contains(id)) return
val updatedList = ids.toMutableList().apply { remove(id) }
dataStoreManager.saveToDataStore(
DataStoreManager.expandedTunnelIds,
updatedList.joinToString(","),
)
} }
override suspend fun setTheme(theme: Theme) { override suspend fun setTheme(theme: Theme) {
@@ -95,6 +119,15 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
return dataStoreManager.getFromStore(DataStoreManager.remoteKey) return dataStoreManager.getFromStore(DataStoreManager.remoteKey)
} }
override suspend fun setShowDetailedPingStats(showDetailedPing: Boolean) {
dataStoreManager.saveToDataStore(DataStoreManager.showDetailedPingStats, showDetailedPing)
}
override suspend fun getShowDetailedPing(): Boolean {
return dataStoreManager.getFromStore(DataStoreManager.showDetailedPingStats)
?: GeneralState.SHOW_DETAILED_PING_STATS_DEFAULT
}
override val flow: Flow<AppState> = override val flow: Flow<AppState> =
dataStoreManager.preferencesFlow dataStoreManager.preferencesFlow
.map { prefs -> .map { prefs ->
@@ -110,15 +143,19 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
isPinLockEnabled = isPinLockEnabled =
pref[DataStoreManager.pinLockEnabled] pref[DataStoreManager.pinLockEnabled]
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT, ?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
isTunnelStatsExpanded = expandedTunnelIds =
pref[DataStoreManager.tunnelStatsExpanded] pref[DataStoreManager.expandedTunnelIds]?.split(",")?.mapNotNull {
?: GeneralState.IS_TUNNEL_STATS_EXPANDED, it.toIntOrNull()
} ?: emptyList(),
isLocalLogsEnabled = isLocalLogsEnabled =
pref[DataStoreManager.isLocalLogsEnabled] pref[DataStoreManager.isLocalLogsEnabled]
?: GeneralState.IS_LOGS_ENABLED_DEFAULT, ?: GeneralState.IS_LOGS_ENABLED_DEFAULT,
isRemoteControlEnabled = isRemoteControlEnabled =
pref[DataStoreManager.isRemoteControlEnabled] pref[DataStoreManager.isRemoteControlEnabled]
?: GeneralState.IS_REMOTE_CONTROL_ENABLED, ?: GeneralState.IS_REMOTE_CONTROL_ENABLED,
showDetailedPingStats =
pref[DataStoreManager.showDetailedPingStats]
?: GeneralState.SHOW_DETAILED_PING_STATS_DEFAULT,
remoteKey = pref[DataStoreManager.remoteKey], remoteKey = pref[DataStoreManager.remoteKey],
locale = pref[DataStoreManager.locale], locale = pref[DataStoreManager.locale],
theme = getTheme(), theme = getTheme(),
@@ -129,5 +166,5 @@ class DataStoreAppStateRepository(private val dataStoreManager: DataStoreManager
} }
} ?: GeneralState() } ?: GeneralState()
} }
.map { it.toAppState() } .map(GeneralStateMapper::toAppState)
} }
@@ -0,0 +1,107 @@
package com.zaneschepke.wireguardautotunnel.data.repository
import android.content.Context
import com.zaneschepke.wireguardautotunnel.BuildConfig
import com.zaneschepke.wireguardautotunnel.data.mapper.GitHubReleaseMapper
import com.zaneschepke.wireguardautotunnel.data.network.GitHubApi
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.model.AppUpdate
import com.zaneschepke.wireguardautotunnel.domain.repository.UpdateRepository
import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.utils.io.*
import java.io.File
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import timber.log.Timber
class GitHubUpdateRepository(
private val gitHubApi: GitHubApi,
private val httpClient: HttpClient,
private val githubOwner: String,
private val githubRepo: String,
private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : UpdateRepository {
override suspend fun checkForUpdate(currentVersion: String): Result<AppUpdate?> =
withContext(ioDispatcher) {
Timber.i("Checking for update")
val isNightly = BuildConfig.VERSION_NAME.contains("nightly")
val release =
if (isNightly) {
gitHubApi.getNightlyRelease(githubOwner, githubRepo).onFailure(Timber::e)
} else {
gitHubApi.getLatestRelease(githubOwner, githubRepo).onFailure(Timber::e)
}
release.map { release ->
val standaloneApkAsset =
release.assets.find { asset ->
asset.name.startsWith("wgtunnel-${Constants.STANDALONE_FLAVOR}-v") &&
asset.name.endsWith(".apk")
}
val newVersion =
standaloneApkAsset
?.name
?.removePrefix("wgtunnel-${Constants.STANDALONE_FLAVOR}-v")
?.removeSuffix(".apk") ?: return@map null
Timber.i("Latest version: $newVersion, current version: $currentVersion")
if (isNightly && newVersion != currentVersion)
return@map GitHubReleaseMapper.toAppUpdate(release, newVersion)
if (NumberUtils.compareVersions(newVersion, currentVersion) > 0) {
GitHubReleaseMapper.toAppUpdate(
release.copy(assets = listOf(standaloneApkAsset)),
newVersion,
)
} else {
null
}
}
}
override suspend fun downloadApk(
apkUrl: String,
fileName: String,
onProgress: suspend (Float) -> Unit,
): Result<File> =
withContext(ioDispatcher) {
try {
// clean up old files
context.getExternalFilesDir(null)?.listFiles()?.forEach { file ->
if (file.extension == "apk") file.delete()
}
val response: HttpResponse = httpClient.get(apkUrl)
val apkFile = File(context.getExternalFilesDir(null), fileName)
val channel: ByteReadChannel = response.bodyAsChannel()
val totalBytes: Long = response.contentLength() ?: -1L
var bytesCopied = 0L
apkFile.outputStream().use { output ->
val buffer = ByteArray(8 * 1024)
while (!channel.isClosedForRead) {
val bytesRead = channel.readAvailable(buffer)
if (bytesRead <= 0) break
output.write(buffer, 0, bytesRead)
bytesCopied += bytesRead
if (totalBytes > 0) {
val progress = bytesCopied.toFloat() / totalBytes
onProgress(progress.coerceIn(0f, 1f))
}
}
}
Result.success(apkFile)
} catch (e: Exception) {
Result.failure(e)
}
}
}
@@ -0,0 +1,30 @@
package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.dao.ProxySettingsDao
import com.zaneschepke.wireguardautotunnel.data.entity.ProxySettings
import com.zaneschepke.wireguardautotunnel.data.mapper.ProxySettingsMapper
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.model.AppProxySettings
import com.zaneschepke.wireguardautotunnel.domain.repository.ProxySettingsRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
class RoomProxySettingsRepository(
private val proxySettingsDao: ProxySettingsDao,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
) : ProxySettingsRepository {
override suspend fun save(proxySettings: AppProxySettings) {
withContext(ioDispatcher) { proxySettingsDao.save(ProxySettingsMapper.to(proxySettings)) }
}
override val flow =
proxySettingsDao.getSettingsFlow().flowOn(ioDispatcher).map(ProxySettingsMapper::to)
override suspend fun get(): AppProxySettings {
return withContext(ioDispatcher) {
ProxySettingsMapper.to(proxySettingsDao.getAll().firstOrNull() ?: ProxySettings())
}
}
}
@@ -1,9 +1,11 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.model.Settings import com.zaneschepke.wireguardautotunnel.data.entity.Settings
import com.zaneschepke.wireguardautotunnel.data.mapper.toAppSettings
import com.zaneschepke.wireguardautotunnel.data.mapper.toSettings
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
@@ -16,7 +18,7 @@ class RoomSettingsRepository(
) : AppSettingRepository { ) : AppSettingRepository {
override suspend fun save(appSettings: AppSettings) { override suspend fun save(appSettings: AppSettings) {
withContext(ioDispatcher) { settingsDoa.save(Settings.from(appSettings)) } withContext(ioDispatcher) { settingsDoa.save(appSettings.toSettings()) }
} }
override val flow = override val flow =
@@ -1,9 +1,9 @@
package com.zaneschepke.wireguardautotunnel.data.repository package com.zaneschepke.wireguardautotunnel.data.repository
import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.model.TunnelConfig import com.zaneschepke.wireguardautotunnel.data.mapper.TunnelConfigMapper
import com.zaneschepke.wireguardautotunnel.di.IoDispatcher import com.zaneschepke.wireguardautotunnel.di.IoDispatcher
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
@@ -17,19 +17,25 @@ class RoomTunnelRepository(
) : TunnelRepository { ) : TunnelRepository {
override val flow = override val flow =
tunnelConfigDao.getAllFlow().flowOn(ioDispatcher).map { it.map { it.toTunnel() } } tunnelConfigDao.getAllFlow().flowOn(ioDispatcher).map {
it.map(TunnelConfigMapper::toTunnelConf)
}
override suspend fun getAll(): Tunnels { override suspend fun getAll(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.getAll().map { it.toTunnel() } } return withContext(ioDispatcher) {
tunnelConfigDao.getAll().map(TunnelConfigMapper::toTunnelConf)
}
} }
override suspend fun save(tunnelConf: TunnelConf) { override suspend fun save(tunnelConf: TunnelConf) {
withContext(ioDispatcher) { tunnelConfigDao.save(TunnelConfig.from(tunnelConf)) } withContext(ioDispatcher) {
tunnelConfigDao.save(TunnelConfigMapper.toTunnelConfig(tunnelConf))
}
} }
override suspend fun saveAll(tunnelConfList: List<TunnelConf>) { override suspend fun saveAll(tunnelConfList: List<TunnelConf>) {
withContext(ioDispatcher) { withContext(ioDispatcher) {
tunnelConfigDao.saveAll(tunnelConfList.map(TunnelConfig::from)) tunnelConfigDao.saveAll(tunnelConfList.map(TunnelConfigMapper::toTunnelConfig))
} }
} }
@@ -55,15 +61,21 @@ class RoomTunnelRepository(
} }
override suspend fun delete(tunnelConf: TunnelConf) { override suspend fun delete(tunnelConf: TunnelConf) {
withContext(ioDispatcher) { tunnelConfigDao.delete(TunnelConfig.from(tunnelConf)) } withContext(ioDispatcher) {
tunnelConfigDao.delete(TunnelConfigMapper.toTunnelConfig(tunnelConf))
}
} }
override suspend fun getById(id: Int): TunnelConf? { override suspend fun getById(id: Int): TunnelConf? {
return withContext(ioDispatcher) { tunnelConfigDao.getById(id.toLong())?.toTunnel() } return withContext(ioDispatcher) {
tunnelConfigDao.getById(id.toLong())?.let(TunnelConfigMapper::toTunnelConf)
}
} }
override suspend fun getActive(): Tunnels { override suspend fun getActive(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.getActive().map { it.toTunnel() } } return withContext(ioDispatcher) {
tunnelConfigDao.getActive().map(TunnelConfigMapper::toTunnelConf)
}
} }
override suspend fun count(): Int { override suspend fun count(): Int {
@@ -71,22 +83,26 @@ class RoomTunnelRepository(
} }
override suspend fun findByTunnelName(name: String): TunnelConf? { override suspend fun findByTunnelName(name: String): TunnelConf? {
return withContext(ioDispatcher) { tunnelConfigDao.getByName(name)?.toTunnel() } return withContext(ioDispatcher) {
tunnelConfigDao.getByName(name)?.let(TunnelConfigMapper::toTunnelConf)
}
} }
override suspend fun findByTunnelNetworksName(name: String): Tunnels { override suspend fun findByTunnelNetworksName(name: String): Tunnels {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
tunnelConfigDao.findByTunnelNetworkName(name).map { it.toTunnel() } tunnelConfigDao.findByTunnelNetworkName(name).map(TunnelConfigMapper::toTunnelConf)
} }
} }
override suspend fun findByMobileDataTunnel(): Tunnels { override suspend fun findByMobileDataTunnel(): Tunnels {
return withContext(ioDispatcher) { return withContext(ioDispatcher) {
tunnelConfigDao.findByMobileDataTunnel().map { it.toTunnel() } tunnelConfigDao.findByMobileDataTunnel().map(TunnelConfigMapper::toTunnelConf)
} }
} }
override suspend fun findPrimary(): Tunnels { override suspend fun findPrimary(): Tunnels {
return withContext(ioDispatcher) { tunnelConfigDao.findByPrimary().map { it.toTunnel() } } return withContext(ioDispatcher) {
tunnelConfigDao.findByPrimary().map(TunnelConfigMapper::toTunnelConf)
}
} }
} }
@@ -4,9 +4,12 @@ import android.content.Context
import com.zaneschepke.logcatter.LogReader import com.zaneschepke.logcatter.LogReader
import com.zaneschepke.logcatter.LogcatReader import com.zaneschepke.logcatter.LogcatReader
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager import com.zaneschepke.wireguardautotunnel.core.notification.NotificationManager
import com.zaneschepke.wireguardautotunnel.core.notification.NotificationMonitor
import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification import com.zaneschepke.wireguardautotunnel.core.notification.WireGuardNotification
import com.zaneschepke.wireguardautotunnel.core.shortcut.DynamicShortcutManager import com.zaneschepke.wireguardautotunnel.core.shortcut.DynamicShortcutManager
import com.zaneschepke.wireguardautotunnel.core.shortcut.ShortcutManager import com.zaneschepke.wireguardautotunnel.core.shortcut.ShortcutManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.util.network.NetworkUtils
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
@@ -47,4 +50,19 @@ class AppModule {
): ShortcutManager { ): ShortcutManager {
return DynamicShortcutManager(context, ioDispatcher) return DynamicShortcutManager(context, ioDispatcher)
} }
@Singleton
@Provides
fun provideNetworkUtils(@IoDispatcher ioDispatcher: CoroutineDispatcher): NetworkUtils {
return NetworkUtils(ioDispatcher)
}
@Singleton
@Provides
fun provideNotificationMonitor(
tunnelManager: TunnelManager,
notificationManager: NotificationManager,
): NotificationMonitor {
return NotificationMonitor(tunnelManager, notificationManager)
}
} }
@@ -9,3 +9,5 @@ import javax.inject.Qualifier
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class Kernel @Qualifier @Retention(AnnotationRetention.BINARY) annotation class Kernel
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class Userspace @Qualifier @Retention(AnnotationRetention.BINARY) annotation class Userspace
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class ProxyUserspace
@@ -6,21 +6,20 @@ import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.data.AppDatabase import com.zaneschepke.wireguardautotunnel.data.AppDatabase
import com.zaneschepke.wireguardautotunnel.data.DataStoreManager import com.zaneschepke.wireguardautotunnel.data.DataStoreManager
import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback import com.zaneschepke.wireguardautotunnel.data.DatabaseCallback
import com.zaneschepke.wireguardautotunnel.data.dao.ProxySettingsDao
import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao import com.zaneschepke.wireguardautotunnel.data.dao.SettingsDao
import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao import com.zaneschepke.wireguardautotunnel.data.dao.TunnelConfigDao
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRoomRepository import com.zaneschepke.wireguardautotunnel.data.network.GitHubApi
import com.zaneschepke.wireguardautotunnel.data.repository.DataStoreAppStateRepository import com.zaneschepke.wireguardautotunnel.data.network.KtorClient
import com.zaneschepke.wireguardautotunnel.data.repository.RoomSettingsRepository import com.zaneschepke.wireguardautotunnel.data.network.KtorGitHubApi
import com.zaneschepke.wireguardautotunnel.data.repository.RoomTunnelRepository import com.zaneschepke.wireguardautotunnel.data.repository.*
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.*
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppStateRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.TunnelRepository
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import io.ktor.client.*
import javax.inject.Singleton import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
@@ -29,14 +28,17 @@ import kotlinx.coroutines.CoroutineDispatcher
class RepositoryModule { class RepositoryModule {
@Provides @Provides
@Singleton @Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase { fun provideDatabase(
@ApplicationContext context: Context,
callback: DatabaseCallback,
): AppDatabase {
return Room.databaseBuilder( return Room.databaseBuilder(
context, context,
AppDatabase::class.java, AppDatabase::class.java,
context.getString(R.string.db_name), context.getString(R.string.db_name),
) )
.fallbackToDestructiveMigration(true) .fallbackToDestructiveMigration(true)
.addCallback(DatabaseCallback()) .addCallback(callback)
.build() .build()
} }
@@ -46,6 +48,12 @@ class RepositoryModule {
return appDatabase.settingDao() return appDatabase.settingDao()
} }
@Singleton
@Provides
fun provideProxyDoa(appDatabase: AppDatabase): ProxySettingsDao {
return appDatabase.proxySettingsDoa()
}
@Singleton @Singleton
@Provides @Provides
fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao { fun provideTunnelConfigDoa(appDatabase: AppDatabase): TunnelConfigDao {
@@ -70,6 +78,15 @@ class RepositoryModule {
return RoomSettingsRepository(settingsDao, ioDispatcher) return RoomSettingsRepository(settingsDao, ioDispatcher)
} }
@Singleton
@Provides
fun provideProxySettingsRepository(
proxySettingsDao: ProxySettingsDao,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
): ProxySettingsRepository {
return RoomProxySettingsRepository(proxySettingsDao, ioDispatcher)
}
@Singleton @Singleton
@Provides @Provides
fun providePreferencesDataStore( fun providePreferencesDataStore(
@@ -91,7 +108,43 @@ class RepositoryModule {
settingsRepository: AppSettingRepository, settingsRepository: AppSettingRepository,
tunnelRepository: TunnelRepository, tunnelRepository: TunnelRepository,
appStateRepository: AppStateRepository, appStateRepository: AppStateRepository,
proxySettingsRepository: ProxySettingsRepository,
): AppDataRepository { ): AppDataRepository {
return AppDataRoomRepository(settingsRepository, tunnelRepository, appStateRepository) return AppDataRoomRepository(
settingsRepository,
tunnelRepository,
appStateRepository,
proxySettingsRepository,
)
}
@Provides
@Singleton
fun provideHttpClient(): HttpClient {
return KtorClient.create()
}
@Provides
@Singleton
fun provideGitHubApi(client: HttpClient): GitHubApi {
return KtorGitHubApi(client)
}
@Provides
@Singleton
fun provideUpdateRepository(
gitHubApi: GitHubApi,
client: HttpClient,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
@ApplicationContext context: Context,
): UpdateRepository {
return GitHubUpdateRepository(
gitHubApi,
client,
"wgtunnel",
"wgtunnel",
context,
ioDispatcher,
)
} }
} }
@@ -4,15 +4,14 @@ import android.content.Context
import com.wireguard.android.backend.WgQuickBackend import com.wireguard.android.backend.WgQuickBackend
import com.wireguard.android.util.RootShell import com.wireguard.android.util.RootShell
import com.wireguard.android.util.ToolsInstaller import com.wireguard.android.util.ToolsInstaller
import com.zaneschepke.logcatter.LogReader
import com.zaneschepke.networkmonitor.AndroidNetworkMonitor import com.zaneschepke.networkmonitor.AndroidNetworkMonitor
import com.zaneschepke.networkmonitor.NetworkMonitor import com.zaneschepke.networkmonitor.NetworkMonitor
import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager import com.zaneschepke.wireguardautotunnel.core.service.ServiceManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.KernelTunnel import com.zaneschepke.wireguardautotunnel.core.tunnel.*
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelManager
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelProvider
import com.zaneschepke.wireguardautotunnel.core.tunnel.UserspaceTunnel
import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppDataRepository
import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository import com.zaneschepke.wireguardautotunnel.domain.repository.AppSettingRepository
import com.zaneschepke.wireguardautotunnel.util.network.NetworkUtils
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
@@ -21,9 +20,12 @@ import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.map
import org.amnezia.awg.backend.Backend import org.amnezia.awg.backend.Backend
import org.amnezia.awg.backend.GoBackend import org.amnezia.awg.backend.GoBackend
import org.amnezia.awg.backend.ProxyGoBackend
import org.amnezia.awg.backend.RootTunnelActionHandler import org.amnezia.awg.backend.RootTunnelActionHandler
@Module @Module
@@ -46,10 +48,21 @@ class TunnelModule {
@Provides @Provides
@Singleton @Singleton
@Userspace
fun provideAmneziaBackend(@ApplicationContext context: Context): Backend { fun provideAmneziaBackend(@ApplicationContext context: Context): Backend {
return GoBackend(context, RootTunnelActionHandler(org.amnezia.awg.util.RootShell(context))) return GoBackend(context, RootTunnelActionHandler(org.amnezia.awg.util.RootShell(context)))
} }
@Provides
@Singleton
@ProxyUserspace
fun provideAmneziaProxyBackend(@ApplicationContext context: Context): Backend {
return ProxyGoBackend(
context,
RootTunnelActionHandler(org.amnezia.awg.util.RootShell(context)),
)
}
@Provides @Provides
@Singleton @Singleton
fun provideKernelBackend( fun provideKernelBackend(
@@ -84,7 +97,19 @@ class TunnelModule {
@ApplicationScope applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
serviceManager: ServiceManager, serviceManager: ServiceManager,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
backend: Backend, @Userspace backend: Backend,
): TunnelProvider {
return UserspaceTunnel(applicationScope, serviceManager, appDataRepository, backend)
}
@Provides
@Singleton
@ProxyUserspace
fun provideProxyUserspaceProvider(
@ApplicationScope applicationScope: CoroutineScope,
serviceManager: ServiceManager,
appDataRepository: AppDataRepository,
@ProxyUserspace backend: Backend,
): TunnelProvider { ): TunnelProvider {
return UserspaceTunnel(applicationScope, serviceManager, appDataRepository, backend) return UserspaceTunnel(applicationScope, serviceManager, appDataRepository, backend)
} }
@@ -94,6 +119,8 @@ class TunnelModule {
fun provideTunnelManager( fun provideTunnelManager(
@Kernel kernelTunnel: TunnelProvider, @Kernel kernelTunnel: TunnelProvider,
@Userspace userspaceTunnel: TunnelProvider, @Userspace userspaceTunnel: TunnelProvider,
@ProxyUserspace proxyTunnel: TunnelProvider,
serviceManager: ServiceManager,
appDataRepository: AppDataRepository, appDataRepository: AppDataRepository,
@IoDispatcher ioDispatcher: CoroutineDispatcher, @IoDispatcher ioDispatcher: CoroutineDispatcher,
@ApplicationScope applicationScope: CoroutineScope, @ApplicationScope applicationScope: CoroutineScope,
@@ -101,6 +128,8 @@ class TunnelModule {
return TunnelManager( return TunnelManager(
kernelTunnel, kernelTunnel,
userspaceTunnel, userspaceTunnel,
proxyTunnel,
serviceManager,
appDataRepository, appDataRepository,
applicationScope, applicationScope,
ioDispatcher, ioDispatcher,
@@ -112,10 +141,23 @@ class TunnelModule {
fun provideNetworkMonitor( fun provideNetworkMonitor(
@ApplicationContext context: Context, @ApplicationContext context: Context,
settingsRepository: AppSettingRepository, settingsRepository: AppSettingRepository,
@ApplicationScope applicationScope: CoroutineScope,
@AppShell appShell: RootShell,
): NetworkMonitor { ): NetworkMonitor {
return AndroidNetworkMonitor(context) { return AndroidNetworkMonitor(
runBlocking { settingsRepository.get().isWifiNameByShellEnabled } context,
} object : AndroidNetworkMonitor.ConfigurationListener {
override val detectionMethod: Flow<AndroidNetworkMonitor.WifiDetectionMethod>
get() =
settingsRepository.flow
.distinctUntilChangedBy { it.wifiDetectionMethod }
.map { it.wifiDetectionMethod }
override val rootShell: RootShell
get() = appShell
},
applicationScope,
)
} }
@Singleton @Singleton
@@ -135,4 +177,23 @@ class TunnelModule {
appDataRepository, appDataRepository,
) )
} }
@Singleton
@Provides
fun provideTunnelMonitor(
@ApplicationContext context: Context,
tunnelManager: TunnelManager,
networkMonitor: NetworkMonitor,
networkUtils: NetworkUtils,
logReader: LogReader,
appDataRepository: AppDataRepository,
): TunnelMonitor {
return TunnelMonitor(
appDataRepository,
tunnelManager,
networkMonitor,
networkUtils,
logReader,
)
}
} }
@@ -1,29 +0,0 @@
package com.zaneschepke.wireguardautotunnel.domain.entity
data class AppSettings(
val id: Int = 0,
val isAutoTunnelEnabled: Boolean = false,
val isTunnelOnMobileDataEnabled: Boolean = false,
val trustedNetworkSSIDs: List<String> = emptyList(),
val isAlwaysOnVpnEnabled: Boolean = false,
val isTunnelOnEthernetEnabled: Boolean = false,
val isShortcutsEnabled: Boolean = false,
val isTunnelOnWifiEnabled: Boolean = false,
val isKernelEnabled: Boolean = false,
val isRestoreOnBootEnabled: Boolean = false,
val isMultiTunnelEnabled: Boolean = false,
val isPingEnabled: Boolean = false,
val isAmneziaEnabled: Boolean = false,
val isWildcardsEnabled: Boolean = false,
val isWifiNameByShellEnabled: Boolean = false,
val isStopOnNoInternetEnabled: Boolean = false,
val isVpnKillSwitchEnabled: Boolean = false,
val isKernelKillSwitchEnabled: Boolean = false,
val isLanOnKillSwitchEnabled: Boolean = false,
val debounceDelaySeconds: Int = 3,
val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
) {
fun debounceDelayMillis(): Long {
return debounceDelaySeconds * 1000L
}
}
@@ -1,33 +0,0 @@
package com.zaneschepke.wireguardautotunnel.domain.enums
import com.zaneschepke.wireguardautotunnel.R
sealed class BackendError : Exception() {
data object DNS : BackendError()
data object Unauthorized : BackendError()
data object Config : BackendError()
data object KernelModuleName : BackendError()
data object InvalidConfig : BackendError()
data object NotAuthorized : BackendError()
data object ServiceNotRunning : BackendError()
data object Unknown : BackendError()
fun toStringRes() =
when (this) {
Config -> R.string.config_error
DNS -> R.string.dns_resolve_error
InvalidConfig -> R.string.invalid_config_error
KernelModuleName -> R.string.kernel_name_error
NotAuthorized,
Unauthorized -> R.string.auth_error
ServiceNotRunning -> R.string.service_running_error
Unknown -> R.string.unknown_error
}
}
@@ -0,0 +1,7 @@
package com.zaneschepke.wireguardautotunnel.domain.enums
sealed class BackendMode {
data object Inactive : BackendMode()
data class KillSwitch(val allowedIps: Set<String>) : BackendMode()
}
@@ -1,7 +0,0 @@
package com.zaneschepke.wireguardautotunnel.domain.enums
enum class BackendState {
KILL_SWITCH_ACTIVE,
SERVICE_ACTIVE,
INACTIVE,
}
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
enum class ConfigType { enum class ConfigType {
AMNEZIA, AM,
WG, WG,
} }
@@ -1,7 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.enums package com.zaneschepke.wireguardautotunnel.domain.enums
sealed class TunnelStatus { sealed class TunnelStatus {
data class Error(val error: BackendError) : TunnelStatus()
data object Up : TunnelStatus() data object Up : TunnelStatus()
@@ -11,10 +10,12 @@ sealed class TunnelStatus {
data object Starting : TunnelStatus() data object Starting : TunnelStatus()
enum class StopReason { sealed class StopReason {
USER, data object User : StopReason()
PING,
CONFIG_CHANGED, data class Ping(val previouslyResolvedEndpoints: Map<String, String?>) : StopReason()
data object ConfigChanged : StopReason()
} }
fun isDown(): Boolean { fun isDown(): Boolean {
@@ -1,10 +1,13 @@
package com.zaneschepke.wireguardautotunnel.domain.events package com.zaneschepke.wireguardautotunnel.domain.events
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
sealed class AutoTunnelEvent { sealed class AutoTunnelEvent {
data class Start(val tunnelConf: TunnelConf? = null) : AutoTunnelEvent() data class Start(val tunnelConf: TunnelConf? = null) : AutoTunnelEvent()
data class Bounce(val configsPeerKeyResolvedMap: List<Pair<TunnelConf, Map<String, String?>>>) :
AutoTunnelEvent()
data object Stop : AutoTunnelEvent() data object Stop : AutoTunnelEvent()
data object DoNothing : AutoTunnelEvent() data object DoNothing : AutoTunnelEvent()
@@ -0,0 +1,48 @@
package com.zaneschepke.wireguardautotunnel.domain.events
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.util.StringValue
sealed class BackendCoreException : Exception() {
data object DNS : BackendCoreException()
data object Unauthorized : BackendCoreException()
data object Config : BackendCoreException()
data object KernelModuleName : BackendCoreException()
data object NotAuthorized : BackendCoreException()
data object ServiceNotRunning : BackendCoreException()
data object Unknown : BackendCoreException()
data object TunnelNameTooLong : BackendCoreException()
data class BounceFailed(val error: BackendCoreException) : BackendCoreException()
fun toStringRes() =
when (this) {
Config -> R.string.config_error
DNS -> R.string.dns_resolve_error
KernelModuleName -> R.string.kernel_name_error
NotAuthorized,
Unauthorized -> R.string.auth_error
ServiceNotRunning -> R.string.service_running_error
Unknown -> R.string.unknown_error
TunnelNameTooLong -> R.string.error_tunnel_name
is BounceFailed -> R.string.bounce_failed_template
}
fun toStringValue(): StringValue {
return when (val backendError = this) {
is BounceFailed ->
StringValue.StringResource(
backendError.toStringRes(),
backendError.error.toStringRes(),
)
else -> StringValue.StringResource(backendError.toStringRes())
}
}
}
@@ -0,0 +1,19 @@
package com.zaneschepke.wireguardautotunnel.domain.events
import com.zaneschepke.wireguardautotunnel.R
import com.zaneschepke.wireguardautotunnel.util.StringValue
sealed class BackendMessage {
data object BounceSuccess : BackendMessage()
data object BounceRecovery : BackendMessage()
fun toStringRes() =
when (this) {
BounceRecovery -> R.string.pinger_bounce_recovery
BounceSuccess -> R.string.pinger_bounce_successful
}
fun toStringValue() = StringValue.StringResource(this.toStringRes())
}
@@ -0,0 +1,16 @@
package com.zaneschepke.wireguardautotunnel.domain.model
data class AppProxySettings(
val id: Long = 0,
val socks5ProxyEnabled: Boolean = false,
val socks5ProxyBindAddress: String? = null,
val httpProxyEnabled: Boolean = false,
val httpProxyBindAddress: String? = null,
val proxyUsername: String? = null,
val proxyPassword: String? = null,
) {
companion object {
const val DEFAULT_SOCKS_BIND_ADDRESS = "127.0.0.1:25344"
const val DEFAULT_HTTP_BIND_ADDRESS = "127.0.0.1:25345"
}
}
@@ -0,0 +1,47 @@
package com.zaneschepke.wireguardautotunnel.domain.model
import com.zaneschepke.networkmonitor.AndroidNetworkMonitor
import com.zaneschepke.wireguardautotunnel.data.model.AppMode
import com.zaneschepke.wireguardautotunnel.data.model.DnsProtocol
data class AppSettings(
val id: Int = 0,
val isAutoTunnelEnabled: Boolean = false,
val isTunnelOnMobileDataEnabled: Boolean = false,
val trustedNetworkSSIDs: List<String> = emptyList(),
val isAlwaysOnVpnEnabled: Boolean = false,
val isTunnelOnEthernetEnabled: Boolean = false,
val isShortcutsEnabled: Boolean = false,
val isTunnelOnWifiEnabled: Boolean = false,
val isRestoreOnBootEnabled: Boolean = false,
val isMultiTunnelEnabled: Boolean = false,
val isPingEnabled: Boolean = false,
val isWildcardsEnabled: Boolean = false,
val isStopOnNoInternetEnabled: Boolean = false,
val isVpnKillSwitchEnabled: Boolean = false,
val isKernelKillSwitchEnabled: Boolean = false,
val isLanOnKillSwitchEnabled: Boolean = false,
val debounceDelaySeconds: Int = 3,
val isDisableKillSwitchOnTrustedEnabled: Boolean = false,
val isTunnelOnUnsecureEnabled: Boolean = false,
val wifiDetectionMethod: AndroidNetworkMonitor.WifiDetectionMethod =
AndroidNetworkMonitor.WifiDetectionMethod.DEFAULT,
val tunnelPingIntervalSeconds: Int = 30,
val tunnelPingAttempts: Int = 3,
val tunnelPingTimeoutSeconds: Int? = null,
val appMode: AppMode = AppMode.VPN,
val dnsProtocol: DnsProtocol = DnsProtocol.SYSTEM,
val dnsEndpoint: String? = null,
) {
fun toAutoTunnelStateString(): String {
return """
TunnelOnWifi: $isTunnelOnWifiEnabled
TunnelOnMobileData: $isTunnelOnMobileDataEnabled
TunnelOnEthernet: $isTunnelOnEthernetEnabled
Wildcards: $isWildcardsEnabled
StopOnNoInternet: $isStopOnNoInternetEnabled
Trusted Networks: $trustedNetworkSSIDs
"""
.trimIndent()
}
}
@@ -1,4 +1,4 @@
package com.zaneschepke.wireguardautotunnel.domain.entity package com.zaneschepke.wireguardautotunnel.domain.model
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
@@ -6,9 +6,10 @@ data class AppState(
val isLocationDisclosureShown: Boolean, val isLocationDisclosureShown: Boolean,
val isBatteryOptimizationDisableShown: Boolean, val isBatteryOptimizationDisableShown: Boolean,
val isPinLockEnabled: Boolean, val isPinLockEnabled: Boolean,
val isTunnelStatsExpanded: Boolean, val expandedTunnelIds: List<Int>,
val isLocalLogsEnabled: Boolean, val isLocalLogsEnabled: Boolean,
val isRemoteControlEnabled: Boolean, val isRemoteControlEnabled: Boolean,
val showDetailedPingStats: Boolean,
val remoteKey: String?, val remoteKey: String?,
val locale: String?, val locale: String?,
val theme: Theme, val theme: Theme,
@@ -0,0 +1,9 @@
package com.zaneschepke.wireguardautotunnel.domain.model
data class AppUpdate(
val version: String,
val title: String,
val releaseNotes: String,
val apkUrl: String?,
val apkFileName: String?,
)
@@ -1,15 +1,10 @@
package com.zaneschepke.wireguardautotunnel.domain.entity package com.zaneschepke.wireguardautotunnel.domain.model
import com.wireguard.android.backend.Tunnel import com.wireguard.android.backend.Tunnel
import com.wireguard.config.Config import com.wireguard.config.Config
import com.zaneschepke.wireguardautotunnel.util.Constants
import com.zaneschepke.wireguardautotunnel.util.extensions.* import com.zaneschepke.wireguardautotunnel.util.extensions.*
import java.io.InputStream import java.io.InputStream
import java.net.InetAddress
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.withContext
import timber.log.Timber
data class TunnelConf( data class TunnelConf(
val id: Int = 0, val id: Int = 0,
@@ -20,16 +15,16 @@ data class TunnelConf(
val isPrimaryTunnel: Boolean = false, val isPrimaryTunnel: Boolean = false,
val amQuick: String, val amQuick: String,
val isActive: Boolean = false, val isActive: Boolean = false,
val isPingEnabled: Boolean = false, val pingTarget: String? = null,
val pingInterval: Long? = null, val restartOnPingFailure: Boolean = false,
val pingCooldown: Long? = null,
val pingIp: String? = null,
val isEthernetTunnel: Boolean = false, val isEthernetTunnel: Boolean = false,
val isIpv4Preferred: Boolean = true, val isIpv4Preferred: Boolean = true,
val useCache: Boolean = false, val position: Int = 0,
@Transient private var stateChangeCallback: ((Any) -> Unit)? = null, @Transient private var stateChangeCallback: ((Any) -> Unit)? = null,
) : Tunnel, org.amnezia.awg.backend.Tunnel { ) : Tunnel, org.amnezia.awg.backend.Tunnel {
val isNameKernelCompatible: Boolean = (name.length <= 15)
fun setStateChangeCallback(callback: (Any) -> Unit) { fun setStateChangeCallback(callback: (Any) -> Unit) {
stateChangeCallback = callback stateChangeCallback = callback
} }
@@ -44,10 +39,8 @@ data class TunnelConf(
isPrimaryTunnel == other.isPrimaryTunnel && isPrimaryTunnel == other.isPrimaryTunnel &&
isMobileDataTunnel == other.isMobileDataTunnel && isMobileDataTunnel == other.isMobileDataTunnel &&
isEthernetTunnel == other.isEthernetTunnel && isEthernetTunnel == other.isEthernetTunnel &&
isPingEnabled == other.isPingEnabled && pingTarget == other.pingTarget &&
pingIp == other.pingIp && restartOnPingFailure == other.restartOnPingFailure &&
pingCooldown == other.pingCooldown &&
pingInterval == other.pingInterval &&
tunnelNetworks == other.tunnelNetworks && tunnelNetworks == other.tunnelNetworks &&
isIpv4Preferred == other.isIpv4Preferred isIpv4Preferred == other.isIpv4Preferred
} }
@@ -60,6 +53,10 @@ data class TunnelConf(
return result return result
} }
fun isStaticallyConfigured(): Boolean {
return toAmConfig().peers.all { it.endpoint.get().host.isValidIpv4orIpv6Address() }
}
fun copyWithCallback( fun copyWithCallback(
id: Int = this.id, id: Int = this.id,
tunName: String = this.tunName, tunName: String = this.tunName,
@@ -69,10 +66,8 @@ data class TunnelConf(
isPrimaryTunnel: Boolean = this.isPrimaryTunnel, isPrimaryTunnel: Boolean = this.isPrimaryTunnel,
amQuick: String = this.amQuick, amQuick: String = this.amQuick,
isActive: Boolean = this.isActive, isActive: Boolean = this.isActive,
isPingEnabled: Boolean = this.isPingEnabled, restartOnPingFailure: Boolean = this.restartOnPingFailure,
pingInterval: Long? = this.pingInterval, pingIp: String? = this.pingTarget,
pingCooldown: Long? = this.pingCooldown,
pingIp: String? = this.pingIp,
isEthernetTunnel: Boolean = this.isEthernetTunnel, isEthernetTunnel: Boolean = this.isEthernetTunnel,
isIpv4Preferred: Boolean = this.isIpv4Preferred, isIpv4Preferred: Boolean = this.isIpv4Preferred,
): TunnelConf { ): TunnelConf {
@@ -85,12 +80,11 @@ data class TunnelConf(
isPrimaryTunnel, isPrimaryTunnel,
amQuick, amQuick,
isActive, isActive,
isPingEnabled,
pingInterval,
pingCooldown,
pingIp, pingIp,
restartOnPingFailure,
isEthernetTunnel, isEthernetTunnel,
isIpv4Preferred, isIpv4Preferred,
position,
) )
.apply { stateChangeCallback = this@TunnelConf.stateChangeCallback } .apply { stateChangeCallback = this@TunnelConf.stateChangeCallback }
} }
@@ -105,10 +99,6 @@ data class TunnelConf(
override fun getName(): String = tunName override fun getName(): String = tunName
override fun isIpv4ResolutionPreferred(): Boolean = isIpv4Preferred
override fun useCache(): Boolean = useCache
override fun onStateChange(newState: org.amnezia.awg.backend.Tunnel.State) { override fun onStateChange(newState: org.amnezia.awg.backend.Tunnel.State) {
stateChangeCallback?.invoke(newState) stateChangeCallback?.invoke(newState)
} }
@@ -117,6 +107,10 @@ data class TunnelConf(
stateChangeCallback?.invoke(newState) stateChangeCallback?.invoke(newState)
} }
override fun isIpv4ResolutionPreferred(): Boolean {
return true
}
fun generateUniqueName(tunnelNames: List<String>): String { fun generateUniqueName(tunnelNames: List<String>): String {
var tunnelName = this.tunName var tunnelName = this.tunName
var num = 1 var num = 1
@@ -133,21 +127,6 @@ data class TunnelConf(
return tunnelName return tunnelName
} }
suspend fun isTunnelPingable(context: CoroutineContext): Boolean {
return withContext(context) {
val config = toWgConfig()
if (pingIp != null) {
return@withContext InetAddress.getByName(pingIp)
.isReachable(Constants.PING_TIMEOUT.toInt())
.also { Timber.i("Ping reachable $pingIp: $it") }
}
config.peers
.map { peer -> peer.isReachable() }
.all { true }
.also { Timber.i("Ping of all peers reachable: $it") }
}
}
companion object { companion object {
fun configFromWgQuick(wgQuick: String): Config { fun configFromWgQuick(wgQuick: String): Config {
val inputStream: InputStream = wgQuick.byteInputStream() val inputStream: InputStream = wgQuick.byteInputStream()
@@ -165,7 +144,7 @@ data class TunnelConf(
config: org.amnezia.awg.config.Config, config: org.amnezia.awg.config.Config,
name: String? = null, name: String? = null,
): TunnelConf { ): TunnelConf {
val amQuick = config.toAwgQuickString(true) val amQuick = config.toAwgQuickString(true, false)
val wgQuick = config.toWgQuickString() val wgQuick = config.toWgQuickString()
return TunnelConf( return TunnelConf(
tunName = name ?: config.defaultName(), tunName = name ?: config.defaultName(),
@@ -177,8 +156,8 @@ data class TunnelConf(
private const val IPV6_ALL_NETWORKS = "::/0" private const val IPV6_ALL_NETWORKS = "::/0"
private const val IPV4_ALL_NETWORKS = "0.0.0.0/0" private const val IPV4_ALL_NETWORKS = "0.0.0.0/0"
val ALL_IPS = listOf(IPV4_ALL_NETWORKS, IPV6_ALL_NETWORKS) val ALL_IPS = listOf(IPV4_ALL_NETWORKS, IPV6_ALL_NETWORKS)
private val IPV4_PUBLIC_NETWORKS = val IPV4_PUBLIC_NETWORKS =
listOf( setOf(
"0.0.0.0/5", "0.0.0.0/5",
"8.0.0.0/7", "8.0.0.0/7",
"11.0.0.0/8", "11.0.0.0/8",
@@ -210,6 +189,6 @@ data class TunnelConf(
"200.0.0.0/5", "200.0.0.0/5",
"208.0.0.0/4", "208.0.0.0/4",
) )
val LAN_BYPASS_ALLOWED_IPS = listOf(IPV6_ALL_NETWORKS) + IPV4_PUBLIC_NETWORKS val LAN_BYPASS_ALLOWED_IPS = setOf(IPV6_ALL_NETWORKS) + IPV4_PUBLIC_NETWORKS
} }
} }
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.repository package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
interface AppDataRepository { interface AppDataRepository {
suspend fun getPrimaryOrFirstTunnel(): TunnelConf? suspend fun getPrimaryOrFirstTunnel(): TunnelConf?
@@ -10,4 +10,6 @@ interface AppDataRepository {
val settings: AppSettingRepository val settings: AppSettingRepository
val tunnels: TunnelRepository val tunnels: TunnelRepository
val appState: AppStateRepository val appState: AppStateRepository
val proxySettings: ProxySettingsRepository
} }
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.repository package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface AppSettingRepository { interface AppSettingRepository {
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.repository package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.AppState import com.zaneschepke.wireguardautotunnel.domain.model.AppState
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -17,9 +17,9 @@ interface AppStateRepository {
suspend fun setBatteryOptimizationDisableShown(shown: Boolean) suspend fun setBatteryOptimizationDisableShown(shown: Boolean)
suspend fun isTunnelStatsExpanded(): Boolean suspend fun setTunnelExpanded(id: Int)
suspend fun setTunnelStatsExpanded(expanded: Boolean) suspend fun removeTunnelExpanded(id: Int)
suspend fun setTheme(theme: Theme) suspend fun setTheme(theme: Theme)
@@ -41,5 +41,9 @@ interface AppStateRepository {
suspend fun getRemoteKey(): String? suspend fun getRemoteKey(): String?
suspend fun setShowDetailedPingStats(showDetailedPing: Boolean)
suspend fun getShowDetailedPing(): Boolean
val flow: Flow<AppState> val flow: Flow<AppState>
} }
@@ -0,0 +1,12 @@
package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.model.AppProxySettings
import kotlinx.coroutines.flow.Flow
interface ProxySettingsRepository {
suspend fun save(proxySettings: AppProxySettings)
val flow: Flow<AppProxySettings>
suspend fun get(): AppProxySettings
}
@@ -1,6 +1,6 @@
package com.zaneschepke.wireguardautotunnel.domain.repository package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels import com.zaneschepke.wireguardautotunnel.util.extensions.Tunnels
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -0,0 +1,14 @@
package com.zaneschepke.wireguardautotunnel.domain.repository
import com.zaneschepke.wireguardautotunnel.domain.model.AppUpdate
import java.io.File
interface UpdateRepository {
suspend fun checkForUpdate(currentVersion: String): Result<AppUpdate?>
suspend fun downloadApk(
apkUrl: String,
fileName: String,
onProgress: suspend (Float) -> Unit,
): Result<File>
}
@@ -12,6 +12,7 @@ class AmneziaStatistics(private val statistics: Statistics) : TunnelStatistics()
rxBytes = stats.rxBytes, rxBytes = stats.rxBytes,
txBytes = stats.txBytes, txBytes = stats.txBytes,
latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis, latestHandshakeEpochMillis = stats.latestHandshakeEpochMillis,
resolvedEndpoint = stats.resolvedEndpoint,
) )
} }
} }
@@ -1,12 +1,10 @@
package com.zaneschepke.wireguardautotunnel.domain.state package com.zaneschepke.wireguardautotunnel.domain.state
import com.zaneschepke.wireguardautotunnel.core.tunnel.allDown import com.zaneschepke.wireguardautotunnel.core.service.autotunnel.StateChange
import com.zaneschepke.wireguardautotunnel.core.tunnel.hasActive
import com.zaneschepke.wireguardautotunnel.core.tunnel.isUp
import com.zaneschepke.wireguardautotunnel.domain.entity.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.entity.TunnelConf
import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent
import com.zaneschepke.wireguardautotunnel.domain.events.KillSwitchEvent import com.zaneschepke.wireguardautotunnel.domain.events.AutoTunnelEvent.*
import com.zaneschepke.wireguardautotunnel.domain.model.AppSettings
import com.zaneschepke.wireguardautotunnel.domain.model.TunnelConf
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
data class AutoTunnelState( data class AutoTunnelState(
@@ -16,57 +14,88 @@ data class AutoTunnelState(
val tunnels: List<TunnelConf> = emptyList(), val tunnels: List<TunnelConf> = emptyList(),
) { ) {
fun determineAutoTunnelEvent(stateChange: StateChange): AutoTunnelEvent {
when (val change = stateChange) {
is StateChange.NetworkChange,
is StateChange.SettingsChange -> {
// Compute desired tunnel based on network conditions
var desiredTunnel: TunnelConf? = null
if (networkState.isEthernetConnected && settings.isTunnelOnEthernetEnabled) {
desiredTunnel = preferredEthernetTunnel()
} else if (isMobileDataActive() && settings.isTunnelOnMobileDataEnabled) {
desiredTunnel = preferredMobileDataTunnel()
} else if (
isWifiActive() && settings.isTunnelOnWifiEnabled && !isCurrentSSIDTrusted()
) {
desiredTunnel = preferredWifiTunnel()
}
// Override for no connectivity if enabled
if (isNoConnectivity() && settings.isStopOnNoInternetEnabled) {
desiredTunnel = null
}
// Determine current active tunnel (assuming only one can be active)
val currentTunnel = activeTunnels.entries.firstOrNull()?.key
// Handle tunnel start/stop/change
if (desiredTunnel != null) {
if (currentTunnel != desiredTunnel) {
// Start or switch to the desired tunnel (overrides any kill switch)
return Start(desiredTunnel)
}
// If already active and matching, fall through to kill switch check (though
// unlikely needed)
} else {
if (currentTunnel != null) {
// Stop the active tunnel (then next emission can handle kill switch if
// needed)
return AutoTunnelEvent.Stop
}
}
}
is StateChange.MonitoringChange -> {
val bounceTunnels = bounceOnPingFailed()
if (bounceTunnels.isNotEmpty()) {
return Bounce(bounceTunnels)
}
}
is StateChange.ActiveTunnelsChange -> Unit
}
return DoNothing
}
// also need to check for Wi-Fi state as there is some overlap when they are both connected
private fun isMobileDataActive(): Boolean { private fun isMobileDataActive(): Boolean {
return !networkState.isEthernetConnected && return !networkState.isEthernetConnected &&
!networkState.isWifiConnected && !networkState.isWifiConnected &&
networkState.isMobileDataConnected networkState.isMobileDataConnected
} }
private fun isMobileTunnelDataChangeNeeded(): Boolean {
val preferredTunnel = preferredMobileDataTunnel()
return preferredTunnel != null &&
activeTunnels.isNotEmpty() &&
!activeTunnels.isUp(preferredTunnel)
}
private fun isEthernetTunnelChangeNeeded(): Boolean {
val preferredTunnel = preferredEthernetTunnel()
return preferredTunnel != null &&
activeTunnels.isNotEmpty() &&
!activeTunnels.isUp(preferredTunnel)
}
private fun preferredMobileDataTunnel(): TunnelConf? { private fun preferredMobileDataTunnel(): TunnelConf? {
return tunnels.firstOrNull { it.isMobileDataTunnel } return tunnels.firstOrNull { it.isMobileDataTunnel }
?: tunnels.firstOrNull { it.isPrimaryTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
?: tunnels.firstOrNull()
} }
private fun preferredEthernetTunnel(): TunnelConf? { private fun preferredEthernetTunnel(): TunnelConf? {
return tunnels.firstOrNull { it.isEthernetTunnel } return tunnels.firstOrNull { it.isEthernetTunnel }
?: tunnels.firstOrNull { it.isPrimaryTunnel } ?: tunnels.firstOrNull { it.isPrimaryTunnel }
?: tunnels.firstOrNull()
} }
private fun preferredWifiTunnel(): TunnelConf? { private fun preferredWifiTunnel(): TunnelConf? {
return getTunnelWithMatchingTunnelNetwork() ?: tunnels.firstOrNull { it.isPrimaryTunnel } return getTunnelWithMatchingTunnelNetwork()
?: tunnels.firstOrNull { it.isPrimaryTunnel }
?: tunnels.firstOrNull()
} }
// ignore cellular state as there is overlap where it may still be active, but not prioritized
private fun isWifiActive(): Boolean { private fun isWifiActive(): Boolean {
return !networkState.isEthernetConnected && networkState.isWifiConnected return !networkState.isEthernetConnected && networkState.isWifiConnected
} }
private fun startOnEthernet(): Boolean {
return networkState.isEthernetConnected &&
settings.isTunnelOnEthernetEnabled &&
activeTunnels.allDown()
}
private fun stopOnEthernet(): Boolean {
return networkState.isEthernetConnected &&
!settings.isTunnelOnEthernetEnabled &&
activeTunnels.hasActive()
}
// TODO test removed kill switch state check
private fun stopKillSwitchOnTrusted(): Boolean { private fun stopKillSwitchOnTrusted(): Boolean {
return networkState.isWifiConnected && return networkState.isWifiConnected &&
settings.isVpnKillSwitchEnabled && settings.isVpnKillSwitchEnabled &&
@@ -74,7 +103,6 @@ data class AutoTunnelState(
isCurrentSSIDTrusted() isCurrentSSIDTrusted()
} }
// TODO test, removed kill switch state check
private fun startKillSwitch(): Boolean { private fun startKillSwitch(): Boolean {
return settings.isVpnKillSwitchEnabled && return settings.isVpnKillSwitchEnabled &&
(!settings.isDisableKillSwitchOnTrustedEnabled || !isCurrentSSIDTrusted()) (!settings.isDisableKillSwitchOnTrustedEnabled || !isCurrentSSIDTrusted())
@@ -86,92 +114,20 @@ data class AutoTunnelState(
!networkState.isMobileDataConnected !networkState.isMobileDataConnected
} }
private fun stopOnMobileData(): Boolean { private fun bounceOnPingFailed(): List<Pair<TunnelConf, Map<String, String?>>> {
return isMobileDataActive() && return activeTunnels.entries
!settings.isTunnelOnMobileDataEnabled && .filter { (tunnel, state) ->
activeTunnels.hasActive() tunnel.restartOnPingFailure &&
(state.pingStates?.any { (key, pingState) ->
pingState.failureReason == FailureReason.PingFailed
} ?: false)
} }
.map { (tunnel, state) ->
private fun startOnMobileData(): Boolean { val peerMap =
return isMobileDataActive() && (state.statistics?.getPeers()?.associate { peerKey ->
settings.isTunnelOnMobileDataEnabled && peerKey.toBase64() to state.statistics.peerStats(peerKey)?.resolvedEndpoint
activeTunnels.allDown() } ?: emptyMap())
} Pair(tunnel, peerMap)
private fun changeOnMobileData(): Boolean {
return isMobileDataActive() &&
settings.isTunnelOnMobileDataEnabled &&
isMobileTunnelDataChangeNeeded()
}
private fun changeOnEthernet(): Boolean {
return networkState.isEthernetConnected &&
settings.isTunnelOnEthernetEnabled &&
isEthernetTunnelChangeNeeded()
}
private fun stopOnWifi(): Boolean {
return isWifiActive() && !settings.isTunnelOnWifiEnabled && activeTunnels.hasActive()
}
private fun stopOnTrustedWifi(): Boolean {
return isWifiActive() &&
settings.isTunnelOnWifiEnabled &&
activeTunnels.hasActive() &&
isCurrentSSIDTrusted()
}
private fun startOnUntrustedWifi(): Boolean {
return isWifiActive() &&
settings.isTunnelOnWifiEnabled &&
activeTunnels.allDown() &&
!isCurrentSSIDTrusted()
}
private fun changeOnUntrustedWifi(): Boolean {
return isWifiActive() &&
settings.isTunnelOnWifiEnabled &&
activeTunnels.hasActive() &&
!isCurrentSSIDTrusted() &&
!isWifiTunnelPreferred()
}
private fun isWifiTunnelPreferred(): Boolean {
val preferred = preferredWifiTunnel()
return preferred?.let { activeTunnels.isUp(it) } ?: true
}
fun asAutoTunnelEvent(): AutoTunnelEvent {
return when {
// ethernet scenarios
stopOnEthernet() -> AutoTunnelEvent.Stop
startOnEthernet() || changeOnEthernet() ->
AutoTunnelEvent.Start(preferredEthernetTunnel())
// mobile data scenarios
stopOnMobileData() -> AutoTunnelEvent.Stop
startOnMobileData() || changeOnMobileData() ->
AutoTunnelEvent.Start(preferredMobileDataTunnel())
// wifi scenarios
stopOnWifi() -> AutoTunnelEvent.Stop
stopOnTrustedWifi() -> AutoTunnelEvent.Stop
startOnUntrustedWifi() || changeOnUntrustedWifi() ->
AutoTunnelEvent.Start(preferredWifiTunnel())
// no connectivity
isNoConnectivity() && settings.isStopOnNoInternetEnabled -> AutoTunnelEvent.Stop
else -> AutoTunnelEvent.DoNothing
}
}
fun asKillSwitchEvent(): KillSwitchEvent {
return when {
stopKillSwitchOnTrusted() -> KillSwitchEvent.Stop
startKillSwitch() -> {
val allowedIps =
if (settings.isLanOnKillSwitchEnabled) TunnelConf.LAN_BYPASS_ALLOWED_IPS
else emptyList()
KillSwitchEvent.Start(allowedIps)
}
else -> KillSwitchEvent.DoNothing
} }
} }
@@ -1,12 +1,38 @@
package com.zaneschepke.wireguardautotunnel.domain.state package com.zaneschepke.wireguardautotunnel.domain.state
import com.zaneschepke.networkmonitor.ConnectivityState
import com.zaneschepke.networkmonitor.util.WifiSecurityType
data class NetworkState( data class NetworkState(
val isWifiConnected: Boolean = false, val isWifiConnected: Boolean = false,
val isMobileDataConnected: Boolean = false, val isMobileDataConnected: Boolean = false,
val isEthernetConnected: Boolean = false, val isEthernetConnected: Boolean = false,
val wifiName: String? = null, val wifiName: String? = null,
val isWifiSecure: Boolean? = null,
val locationServicesEnabled: Boolean? = null,
val locationPermissionGranted: Boolean? = null,
) { ) {
fun hasNoCapabilities(): Boolean { fun hasNoCapabilities(): Boolean {
return !isWifiConnected && !isMobileDataConnected && !isEthernetConnected return !isWifiConnected && !isMobileDataConnected && !isEthernetConnected
} }
companion object {
fun from(connectivityState: ConnectivityState): NetworkState {
return NetworkState(
isWifiSecure =
when (connectivityState.wifiState.securityType) {
WifiSecurityType.OPEN,
WifiSecurityType.UNKNOWN -> false
null -> null
else -> true
},
isWifiConnected = connectivityState.wifiState.connected,
isMobileDataConnected = connectivityState.cellularConnected,
isEthernetConnected = connectivityState.ethernetConnected,
wifiName = connectivityState.wifiState.ssid,
locationPermissionGranted = connectivityState.wifiState.locationPermissionsGranted,
locationServicesEnabled = connectivityState.wifiState.locationServicesEnabled,
)
}
}
} }
@@ -0,0 +1,26 @@
package com.zaneschepke.wireguardautotunnel.domain.state
import com.zaneschepke.wireguardautotunnel.core.tunnel.TunnelMonitor.Companion.CLOUDFLARE_IPV4_IP
enum class FailureReason {
NoConnectivity,
PingFailed,
NoResolvedEndpoint,
Timeout,
Unknown,
}
data class PingState(
val transmitted: Int = 0,
val received: Int = 0,
val packetLoss: Double = 0.0,
val rttMin: Double = 0.0,
val rttMax: Double = 0.0,
val rttAvg: Double = 0.0,
val rttStddev: Double = 0.0,
val isReachable: Boolean = false,
val lastSuccessfulPingMillis: Long? = null,
val lastPingAttemptMillis: Long? = null,
val failureReason: FailureReason? = null,
val pingTarget: String = CLOUDFLARE_IPV4_IP,
)
@@ -1,10 +1,13 @@
package com.zaneschepke.wireguardautotunnel.domain.state package com.zaneschepke.wireguardautotunnel.domain.state
import com.zaneschepke.wireguardautotunnel.domain.enums.BackendState import com.zaneschepke.wireguardautotunnel.domain.enums.BackendMode
import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus import com.zaneschepke.wireguardautotunnel.domain.enums.TunnelStatus
import org.amnezia.awg.crypto.Key
data class TunnelState( data class TunnelState(
val status: TunnelStatus = TunnelStatus.Down, val status: TunnelStatus = TunnelStatus.Down,
val backendState: BackendState = BackendState.INACTIVE, val backendState: BackendMode = BackendMode.Inactive,
val statistics: TunnelStatistics? = null, val statistics: TunnelStatistics? = null,
val pingStates: Map<Key, PingState>? = null,
val handshakeSuccessLogs: Boolean? = null,
) )

Some files were not shown because too many files have changed in this diff Show More