mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-12-02 13:16:18 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36579d4199 | ||
|
|
c1c0c446e6 | ||
|
|
7e3630bd1c |
No files matched your search
@@ -0,0 +1,26 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="390dp"
|
||||
android:height="390dp"
|
||||
android:viewportWidth="390"
|
||||
android:viewportHeight="390">
|
||||
<path
|
||||
android:fillColor="#8009090B"
|
||||
android:fillType="evenOdd"
|
||||
android:pathData="M0 0H390V390H0Z M64 50H326A14 14 0 0 1 340 64V326A14 14 0 0 1 326 340H64A14 14 0 0 1 50 326V64A14 14 0 0 1 64 50Z" />
|
||||
<path
|
||||
android:pathData="M129.5 50H64C56.268 50 50 56.268 50 64V129.5"
|
||||
android:strokeWidth="4"
|
||||
android:strokeColor="#FFFFFFFF" />
|
||||
<path
|
||||
android:pathData="M260.5 50H326C333.732 50 340 56.268 340 64V129.5"
|
||||
android:strokeWidth="4"
|
||||
android:strokeColor="#FFFFFFFF" />
|
||||
<path
|
||||
android:pathData="M340 260.5V326C340 333.732 333.732 340 326 340H260.5"
|
||||
android:strokeWidth="4"
|
||||
android:strokeColor="#FFFFFFFF" />
|
||||
<path
|
||||
android:pathData="M129.5 340H64C56.268 340 50 333.732 50 326V260.5"
|
||||
android:strokeWidth="4"
|
||||
android:strokeColor="#FFFFFFFF" />
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="#FFE4E4E7" />
|
||||
<corners android:radius="12dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,18 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M19 12H5"
|
||||
android:strokeWidth="2"
|
||||
android:strokeColor="#FFE4E4E7"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round" />
|
||||
<path
|
||||
android:pathData="M12 19L5 12L12 5"
|
||||
android:strokeWidth="2"
|
||||
android:strokeColor="#FFE4E4E7"
|
||||
android:strokeLineCap="round"
|
||||
android:strokeLineJoin="round" />
|
||||
</vector>
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FF09090B"
|
||||
android:pathData="M18 1C18.552 1 19 1.448 19 2V6C19 7.44 18.218 8.197 17.707 8.707C17.218 9.197 17 9.44 17 10V20C17 20.796 16.684 21.558 16.121 22.121C15.558 22.684 14.796 23 14 23H10C9.204 23 8.442 22.684 7.879 22.121C7.316 21.558 7 20.796 7 20V10C7 9.44 6.782 9.197 6.293 8.707C5.782 8.197 5 7.44 5 6V2C5 1.448 5.448 1 6 1H18ZM7.426 7C7.507 7.089 7.6 7.186 7.707 7.293C8.218 7.803 9 8.56 9 10V20C9 20.265 9.105 20.519 9.293 20.707C9.481 20.895 9.735 21 10 21H14C14.265 21 14.519 20.895 14.707 20.707C14.895 20.519 15 20.265 15 20V10C15 8.56 15.782 7.803 16.293 7.293C16.4 7.186 16.493 7.089 16.574 7H7.426ZM7 5H17V3H7V5Z" />
|
||||
</vector>
|
||||
@@ -8,4 +8,86 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
</FrameLayout>
|
||||
<LinearLayout
|
||||
android:id="@+id/deviceTransferChrome"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/deviceTransferTopBar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="#8009090B"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="56dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="4dp"
|
||||
android:paddingEnd="4dp">
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/deviceTransferBack"
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp"
|
||||
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/deviceTransferBack"
|
||||
android:src="@drawable/ic_arrow_left" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/deviceTransferTitle"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:ellipsize="end"
|
||||
android:fontFamily="sans-serif-medium"
|
||||
android:gravity="center"
|
||||
android:maxLines="1"
|
||||
android:textColor="#FFE4E4E7"
|
||||
android:textSize="18sp" />
|
||||
|
||||
<Space
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:id="@+id/deviceTransferScanArea"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:background="@drawable/device_transfer_scan_overlay" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/deviceTransferBottomPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:background="#8009090B"
|
||||
android:gravity="center_horizontal"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingEnd="16dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/deviceTransferHint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:lineSpacingExtra="4sp"
|
||||
android:textColor="#FFD4D4D8"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/deviceTransferTorch"
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginTop="26dp"
|
||||
android:background="@drawable/device_transfer_torch_background"
|
||||
android:contentDescription="@string/deviceTransferTorch"
|
||||
android:src="@drawable/ic_flashlight"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
</FrameLayout>
|
||||
@@ -25,4 +25,7 @@
|
||||
<string name="openNotificationSettings">Открыть настройки уведомлений</string>
|
||||
|
||||
<string name="tvNoFileBrowser">Пожалуйста, установите приложение для просмотра файлов</string>
|
||||
|
||||
<string name="deviceTransferBack">Назад</string>
|
||||
<string name="deviceTransferTorch">Фонарик</string>
|
||||
</resources>
|
||||
@@ -25,4 +25,7 @@
|
||||
<string name="openNotificationSettings">Open notification settings</string>
|
||||
|
||||
<string name="tvNoFileBrowser">Please install a file management utility to browse files</string>
|
||||
|
||||
<string name="deviceTransferBack">Back</string>
|
||||
<string name="deviceTransferTorch">Flashlight</string>
|
||||
</resources>
|
||||
@@ -1002,6 +1002,16 @@ class AmneziaActivity : QtActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun startDeviceTransferQrCodeReader(title: String, hint: String) {
|
||||
Log.v(TAG, "Start device transfer camera")
|
||||
Intent(this, CameraActivity::class.java).also {
|
||||
it.putExtra(EXTRA_DEVICE_TRANSFER_TITLE, title)
|
||||
it.putExtra(EXTRA_DEVICE_TRANSFER_HINT, hint)
|
||||
startActivity(it)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun setSaveLogs(enabled: Boolean) {
|
||||
Log.v(TAG, "Set save logs: $enabled")
|
||||
|
||||
@@ -3,21 +3,33 @@ package org.amnezia.vpn
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.RectF
|
||||
import android.os.Bundle
|
||||
import android.view.MotionEvent.ACTION_DOWN
|
||||
import android.view.MotionEvent.ACTION_UP
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
|
||||
import androidx.camera.core.Camera
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ExperimentalGetImage
|
||||
import androidx.camera.core.FocusMeteringAction
|
||||
import androidx.camera.core.FocusMeteringAction.FLAG_AE
|
||||
import androidx.camera.core.FocusMeteringAction.FLAG_AF
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.TransformExperimental
|
||||
import androidx.camera.view.transform.CoordinateTransform
|
||||
import androidx.camera.view.transform.ImageProxyTransformFactory
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.doOnLayout
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.core.view.updatePadding
|
||||
import com.google.mlkit.vision.barcode.BarcodeScannerOptions.Builder
|
||||
import com.google.mlkit.vision.barcode.BarcodeScanning
|
||||
import com.google.mlkit.vision.barcode.ZoomSuggestionOptions
|
||||
@@ -29,20 +41,104 @@ import org.amnezia.vpn.util.Log
|
||||
|
||||
private const val TAG = "CameraActivity"
|
||||
|
||||
const val EXTRA_DEVICE_TRANSFER_TITLE = "org.amnezia.vpn.DEVICE_TRANSFER_TITLE"
|
||||
const val EXTRA_DEVICE_TRANSFER_HINT = "org.amnezia.vpn.DEVICE_TRANSFER_HINT"
|
||||
|
||||
private const val SCAN_AREA_VIEWPORT = 390f
|
||||
private const val SCAN_HOLE_INSET = 50f
|
||||
|
||||
class CameraActivity : ComponentActivity() {
|
||||
|
||||
private lateinit var viewBinding: CameraPreviewBinding
|
||||
private lateinit var cameraProvider: ProcessCameraProvider
|
||||
|
||||
private val isDeviceTransfer: Boolean
|
||||
get() = intent.hasExtra(EXTRA_DEVICE_TRANSFER_TITLE)
|
||||
|
||||
private var isTorchEnabled = false
|
||||
|
||||
@ExperimentalGetImage
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
viewBinding = CameraPreviewBinding.inflate(layoutInflater)
|
||||
setContentView(viewBinding.root)
|
||||
|
||||
if (isDeviceTransfer) {
|
||||
showDeviceTransferChrome()
|
||||
}
|
||||
|
||||
checkPermissions(onSuccess = ::startCamera, onFail = ::finish)
|
||||
}
|
||||
|
||||
private fun showDeviceTransferChrome() {
|
||||
with(viewBinding) {
|
||||
deviceTransferChrome.visibility = View.VISIBLE
|
||||
deviceTransferTitle.text = intent.getStringExtra(EXTRA_DEVICE_TRANSFER_TITLE)
|
||||
deviceTransferHint.text = intent.getStringExtra(EXTRA_DEVICE_TRANSFER_HINT)
|
||||
deviceTransferBack.setOnClickListener { finish() }
|
||||
|
||||
deviceTransferChrome.doOnLayout { chrome ->
|
||||
deviceTransferScanArea.updateLayoutParams { height = chrome.width }
|
||||
}
|
||||
|
||||
ViewCompat.setOnApplyWindowInsetsListener(deviceTransferChrome) { _, insets ->
|
||||
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
|
||||
deviceTransferTopBar.updatePadding(top = systemBars.top)
|
||||
deviceTransferBottomPanel.updatePadding(bottom = systemBars.bottom)
|
||||
insets
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun bindTorchButton(camera: Camera) {
|
||||
if (!isDeviceTransfer || !camera.cameraInfo.hasFlashUnit()) {
|
||||
return
|
||||
}
|
||||
with(viewBinding.deviceTransferTorch) {
|
||||
visibility = View.VISIBLE
|
||||
setOnClickListener {
|
||||
isTorchEnabled = !isTorchEnabled
|
||||
camera.cameraControl.enableTorch(isTorchEnabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun scanHoleInViewFinder(): RectF {
|
||||
val scanArea = viewBinding.deviceTransferScanArea
|
||||
val scanAreaLocation = IntArray(2).also(scanArea::getLocationInWindow)
|
||||
val viewFinderLocation = IntArray(2).also(viewBinding.viewFinder::getLocationInWindow)
|
||||
val left = (scanAreaLocation[0] - viewFinderLocation[0]).toFloat()
|
||||
val top = (scanAreaLocation[1] - viewFinderLocation[1]).toFloat()
|
||||
val inset = scanArea.width * SCAN_HOLE_INSET / SCAN_AREA_VIEWPORT
|
||||
return RectF(left + inset, top + inset, left + scanArea.width - inset, top + scanArea.height - inset)
|
||||
}
|
||||
|
||||
@OptIn(TransformExperimental::class)
|
||||
private fun scanHoleInImage(imageProxy: ImageProxy): RectF? {
|
||||
val previewTransform = viewBinding.viewFinder.outputTransform ?: return null
|
||||
val imageTransform = ImageProxyTransformFactory()
|
||||
.apply { isUsingRotationDegrees = true }
|
||||
.getOutputTransform(imageProxy)
|
||||
return scanHoleInViewFinder().also { CoordinateTransform(previewTransform, imageTransform).mapRect(it) }
|
||||
}
|
||||
|
||||
private fun barcodeFilter(imageProxy: ImageProxy): (Barcode) -> Boolean {
|
||||
if (!isDeviceTransfer) {
|
||||
return { true }
|
||||
}
|
||||
val scanHole = scanHoleInImage(imageProxy) ?: return { false }
|
||||
return { barcode -> barcode.isInside(scanHole) }
|
||||
}
|
||||
|
||||
private fun Barcode.isInside(area: RectF): Boolean {
|
||||
val corners = cornerPoints
|
||||
if (!corners.isNullOrEmpty()) {
|
||||
return corners.all { area.contains(it.x.toFloat(), it.y.toFloat()) }
|
||||
}
|
||||
val box = boundingBox ?: return false
|
||||
return area.contains(RectF(box))
|
||||
}
|
||||
|
||||
private fun checkPermissions(onSuccess: () -> Unit, onFail: () -> Unit) {
|
||||
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||||
onSuccess()
|
||||
@@ -80,6 +176,7 @@ class CameraActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
val camera = cameraProvider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview)
|
||||
bindTorchButton(camera)
|
||||
|
||||
viewFinder.setOnTouchListener { _, motionEvent ->
|
||||
when (motionEvent.action) {
|
||||
@@ -125,13 +222,19 @@ class CameraActivity : ComponentActivity() {
|
||||
val checkedBarcodes = hashSetOf<String>()
|
||||
|
||||
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this)) { imageProxy ->
|
||||
val isAcceptedBarcode = barcodeFilter(imageProxy)
|
||||
imageProxy.image?.let { InputImage.fromMediaImage(it, imageProxy.imageInfo.rotationDegrees) }
|
||||
?.let { image ->
|
||||
barcodeScanner.process(image).addOnSuccessListener { barcodes ->
|
||||
barcodes.firstOrNull()?.let { barcode ->
|
||||
barcodes.firstOrNull(isAcceptedBarcode)?.let { barcode ->
|
||||
barcode.displayValue?.let { code ->
|
||||
if (code.isNotEmpty() && code !in checkedBarcodes) {
|
||||
if (QtAndroidController.decodeQrCode(code)) {
|
||||
val isAccepted = if (isDeviceTransfer) {
|
||||
QtAndroidController.decodeDeviceTransferQrCode(code)
|
||||
} else {
|
||||
QtAndroidController.decodeQrCode(code)
|
||||
}
|
||||
if (isAccepted) {
|
||||
barcodeScanner.close()
|
||||
stopCamera()
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ object QtAndroidController {
|
||||
|
||||
external fun decodeQrCode(data: String): Boolean
|
||||
|
||||
external fun decodeDeviceTransferQrCode(data: String): Boolean
|
||||
|
||||
external fun onImeInsetsChanged(heightDp: Int)
|
||||
external fun onSystemBarsInsetsChanged(navBarHeightDp: Int, statusBarHeightDp: Int)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ find_library(FW_FOUNDATION Foundation)
|
||||
find_library(FW_STOREKIT StoreKit)
|
||||
find_library(FW_USERNOTIFICATIONS UserNotifications)
|
||||
find_library(FW_NETWORKEXTENSION NetworkExtension)
|
||||
find_library(FW_NETWORK Network)
|
||||
|
||||
set(LIBS ${LIBS}
|
||||
${FW_AUTHENTICATIONSERVICES}
|
||||
@@ -24,6 +25,7 @@ set(LIBS ${LIBS}
|
||||
${FW_STOREKIT}
|
||||
${FW_USERNOTIFICATIONS}
|
||||
${FW_NETWORKEXTENSION}
|
||||
${FW_NETWORK}
|
||||
)
|
||||
|
||||
|
||||
@@ -32,6 +34,8 @@ set(HEADERS ${HEADERS}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/ios_controller_wrapper.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosnotificationhandler.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/ioscontextmenu.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosQrScanner.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosLocalNetwork.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/QtAppDelegate.h
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/QtAppDelegate-C-Interface.h
|
||||
)
|
||||
@@ -45,6 +49,8 @@ set(SOURCES ${SOURCES}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/ioscontextmenu.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosglue.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/QRCodeReaderBase.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosQrScanner.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosLocalNetwork.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/QtAppDelegate.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/AmneziaSceneDelegateHooks.mm
|
||||
)
|
||||
@@ -55,6 +61,12 @@ set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/ioscontext
|
||||
PROPERTIES COMPILE_OPTIONS "-fobjc-arc"
|
||||
)
|
||||
|
||||
set_source_files_properties(
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosQrScanner.mm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platforms/ios/iosLocalNetwork.mm
|
||||
PROPERTIES COMPILE_OPTIONS "-fobjc-arc"
|
||||
)
|
||||
|
||||
|
||||
target_include_directories(${PROJECT} PRIVATE ${Qt6Gui_PRIVATE_INCLUDE_DIRS})
|
||||
|
||||
|
||||
@@ -51,6 +51,11 @@ set(HEADERS ${HEADERS}
|
||||
${CLIENT_ROOT_DIR}/core/controllers/api/subscriptionController.h
|
||||
${CLIENT_ROOT_DIR}/core/controllers/api/newsController.h
|
||||
${CLIENT_ROOT_DIR}/core/controllers/updateController.h
|
||||
${CLIENT_ROOT_DIR}/core/controllers/deviceTransferController.h
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferCode.h
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferPackage.h
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferReceiver.h
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferSender.h
|
||||
${CLIENT_ROOT_DIR}/core/repositories/secureServersRepository.h
|
||||
${CLIENT_ROOT_DIR}/core/repositories/secureAppSettingsRepository.h
|
||||
${CLIENT_ROOT_DIR}/core/protocols/qmlRegisterProtocols.h
|
||||
@@ -141,6 +146,11 @@ set(SOURCES ${SOURCES}
|
||||
${CLIENT_ROOT_DIR}/core/controllers/api/subscriptionController.cpp
|
||||
${CLIENT_ROOT_DIR}/core/controllers/api/newsController.cpp
|
||||
${CLIENT_ROOT_DIR}/core/controllers/updateController.cpp
|
||||
${CLIENT_ROOT_DIR}/core/controllers/deviceTransferController.cpp
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferCode.cpp
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferPackage.cpp
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferReceiver.cpp
|
||||
${CLIENT_ROOT_DIR}/core/utils/deviceTransfer/deviceTransferSender.cpp
|
||||
${CLIENT_ROOT_DIR}/core/repositories/secureServersRepository.cpp
|
||||
${CLIENT_ROOT_DIR}/core/repositories/secureAppSettingsRepository.cpp
|
||||
${CLIENT_ROOT_DIR}/ui/utils/qAutoStart.cpp
|
||||
|
||||
@@ -180,6 +180,8 @@ void CoreController::initCoreControllers()
|
||||
m_connectionController = new ConnectionController(m_serversRepository, m_appSettingsRepository, m_vpnConnection.get(), this);
|
||||
m_settingsController = new SettingsController(m_serversRepository, m_appSettingsRepository, this);
|
||||
m_localProxyController = new LocalProxyController(m_serversRepository, m_appSettingsRepository, m_subscriptionController, this);
|
||||
m_deviceTransferController = new DeviceTransferController(m_serversRepository, m_exportController,
|
||||
m_importCoreController, m_subscriptionController, this);
|
||||
}
|
||||
|
||||
void CoreController::initControllers()
|
||||
@@ -256,6 +258,9 @@ void CoreController::initControllers()
|
||||
|
||||
m_updateUiController = new UpdateUiController(m_updateController, this);
|
||||
setQmlContextProperty("UpdateController", m_updateUiController);
|
||||
|
||||
m_deviceTransferUiController = new DeviceTransferUiController(m_deviceTransferController, this);
|
||||
setQmlContextProperty("DeviceTransferController", m_deviceTransferUiController);
|
||||
}
|
||||
|
||||
void CoreController::initAndroidController()
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include "ui/controllers/systemController.h"
|
||||
#include "ui/controllers/languageUiController.h"
|
||||
#include "ui/controllers/updateUiController.h"
|
||||
#include "ui/controllers/deviceTransferUiController.h"
|
||||
#include "ui/controllers/api/servicesCatalogUiController.h"
|
||||
#include "ui/controllers/networkReachabilityController.h"
|
||||
|
||||
@@ -48,6 +49,7 @@
|
||||
#include "core/controllers/localProxyController.h"
|
||||
#include "core/controllers/connectionController.h"
|
||||
#include "core/controllers/updateController.h"
|
||||
#include "core/controllers/deviceTransferController.h"
|
||||
|
||||
#include "core/repositories/secureServersRepository.h"
|
||||
#include "core/repositories/secureAppSettingsRepository.h"
|
||||
@@ -190,6 +192,7 @@ private:
|
||||
AllowedDnsUiController* m_allowedDnsUiController;
|
||||
LanguageUiController* m_languageUiController;
|
||||
UpdateUiController* m_updateUiController;
|
||||
DeviceTransferUiController* m_deviceTransferUiController;
|
||||
|
||||
SubscriptionUiController* m_subscriptionUiController;
|
||||
ApiNewsUiController* m_apiNewsUiController;
|
||||
@@ -211,6 +214,7 @@ private:
|
||||
ConnectionController* m_connectionController;
|
||||
SettingsController* m_settingsController;
|
||||
LocalProxyController* m_localProxyController;
|
||||
DeviceTransferController* m_deviceTransferController;
|
||||
|
||||
ContainersModel* m_containersModel;
|
||||
ContainersModel* m_defaultServerContainersModel;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
#include "deviceTransferController.h"
|
||||
|
||||
#include "core/controllers/api/subscriptionController.h"
|
||||
#include "core/controllers/selfhosted/exportController.h"
|
||||
#include "core/controllers/selfhosted/importController.h"
|
||||
#include "core/repositories/secureServersRepository.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferPackage.h"
|
||||
#include "core/utils/serverConfigUtils.h"
|
||||
#include "logger.h"
|
||||
|
||||
using namespace amnezia;
|
||||
|
||||
namespace
|
||||
{
|
||||
Logger logger("DeviceTransferController");
|
||||
|
||||
QString errorCodeText(ErrorCode errorCode)
|
||||
{
|
||||
return QString::number(static_cast<int>(errorCode));
|
||||
}
|
||||
}
|
||||
|
||||
DeviceTransferController::DeviceTransferController(SecureServersRepository *serversRepository,
|
||||
ExportController *exportController, ImportController *importController,
|
||||
SubscriptionController *subscriptionController, QObject *parent)
|
||||
: QObject(parent),
|
||||
m_serversRepository(serversRepository),
|
||||
m_exportController(exportController),
|
||||
m_importController(importController),
|
||||
m_subscriptionController(subscriptionController)
|
||||
{
|
||||
connect(&m_receiver, &DeviceTransferReceiver::packageReceived, this, [this](const QStringList &configs) {
|
||||
m_receiver.stop();
|
||||
emit packageReceived();
|
||||
importConfigs(configs);
|
||||
});
|
||||
connect(&m_sender, &DeviceTransferSender::finished, this, &DeviceTransferController::sendFinished);
|
||||
}
|
||||
|
||||
ErrorCode DeviceTransferController::startReceiving()
|
||||
{
|
||||
const QStringList addresses = deviceTransfer::localLanAddresses();
|
||||
if (addresses.isEmpty()) {
|
||||
m_receiver.stop();
|
||||
return ErrorCode::DeviceTransferNoLocalNetworkError;
|
||||
}
|
||||
if (!m_receiver.start(addresses, deviceTransfer::localDeviceName())) {
|
||||
logger.error() << "receiver failed to start";
|
||||
return ErrorCode::InternalError;
|
||||
}
|
||||
return ErrorCode::NoError;
|
||||
}
|
||||
|
||||
void DeviceTransferController::stopReceiving()
|
||||
{
|
||||
m_receiver.stop();
|
||||
}
|
||||
|
||||
QString DeviceTransferController::receiveLink() const
|
||||
{
|
||||
const deviceTransfer::TransferCode code = m_receiver.code();
|
||||
return code.port == 0 ? QString() : code.toLink();
|
||||
}
|
||||
|
||||
void DeviceTransferController::send(const deviceTransfer::TransferCode &code, const QStringList &serverIds)
|
||||
{
|
||||
QStringList configs;
|
||||
for (const QString &serverId : serverIds) {
|
||||
QString config;
|
||||
const ErrorCode errorCode = exportServerConfig(serverId, config);
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
logger.error() << "export failed, error" << errorCodeText(errorCode);
|
||||
emit sendFinished(errorCode);
|
||||
return;
|
||||
}
|
||||
configs.append(config);
|
||||
}
|
||||
|
||||
const QByteArray sealedPackage = deviceTransfer::sealPackage(code.publicKey, configs);
|
||||
if (sealedPackage.isEmpty()) {
|
||||
logger.error() << "sealing the package failed";
|
||||
emit sendFinished(ErrorCode::InternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
m_sender.send(code, sealedPackage);
|
||||
}
|
||||
|
||||
void DeviceTransferController::cancelSending()
|
||||
{
|
||||
m_sender.cancel();
|
||||
}
|
||||
|
||||
ErrorCode DeviceTransferController::exportServerConfig(const QString &serverId, QString &config)
|
||||
{
|
||||
const serverConfigUtils::ConfigType kind = m_serversRepository->serverKind(serverId);
|
||||
|
||||
if (serverConfigUtils::isApiV2Subscription(kind)) {
|
||||
return m_subscriptionController->prepareVpnKeyExport(serverId, config);
|
||||
}
|
||||
|
||||
const ExportController::ExportResult result = kind == serverConfigUtils::ConfigType::SelfHostedAdmin
|
||||
? m_exportController->generateFullAccessConfig(serverId)
|
||||
: m_exportController->generateServerConfig(serverId);
|
||||
config = result.config;
|
||||
return result.errorCode;
|
||||
}
|
||||
|
||||
void DeviceTransferController::importConfigs(const QStringList &configs)
|
||||
{
|
||||
for (const QString &config : configs) {
|
||||
const ImportController::ImportResult result = m_importController->extractConfigFromData(config);
|
||||
if (result.errorCode != ErrorCode::NoError) {
|
||||
logger.error() << "received config did not parse, error" << errorCodeText(result.errorCode);
|
||||
emit importFailed(result.errorCode);
|
||||
continue;
|
||||
}
|
||||
m_importController->importConfig(result.config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#ifndef DEVICETRANSFERCONTROLLER_H
|
||||
#define DEVICETRANSFERCONTROLLER_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QStringList>
|
||||
|
||||
#include "core/utils/deviceTransfer/deviceTransferCode.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferReceiver.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferSender.h"
|
||||
#include "core/utils/errorCodes.h"
|
||||
|
||||
class SecureServersRepository;
|
||||
class ExportController;
|
||||
class ImportController;
|
||||
class SubscriptionController;
|
||||
|
||||
class DeviceTransferController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
DeviceTransferController(SecureServersRepository *serversRepository, ExportController *exportController,
|
||||
ImportController *importController, SubscriptionController *subscriptionController,
|
||||
QObject *parent = nullptr);
|
||||
|
||||
amnezia::ErrorCode startReceiving();
|
||||
void stopReceiving();
|
||||
QString receiveLink() const;
|
||||
|
||||
void send(const deviceTransfer::TransferCode &code, const QStringList &serverIds);
|
||||
void cancelSending();
|
||||
|
||||
signals:
|
||||
void packageReceived();
|
||||
void importFailed(amnezia::ErrorCode errorCode);
|
||||
void sendFinished(amnezia::ErrorCode errorCode);
|
||||
|
||||
private:
|
||||
amnezia::ErrorCode exportServerConfig(const QString &serverId, QString &config);
|
||||
void importConfigs(const QStringList &configs);
|
||||
|
||||
SecureServersRepository *m_serversRepository;
|
||||
ExportController *m_exportController;
|
||||
ImportController *m_importController;
|
||||
SubscriptionController *m_subscriptionController;
|
||||
|
||||
DeviceTransferReceiver m_receiver;
|
||||
DeviceTransferSender m_sender;
|
||||
};
|
||||
|
||||
#endif // DEVICETRANSFERCONTROLLER_H
|
||||
@@ -49,6 +49,24 @@ ExportController::ExportResult ExportController::generateFullAccessConfig(const
|
||||
return result;
|
||||
}
|
||||
|
||||
ExportController::ExportResult ExportController::generateServerConfig(const QString &serverId)
|
||||
{
|
||||
ExportResult result;
|
||||
|
||||
QJsonObject serverJson;
|
||||
if (const auto userConfig = m_serversRepository->selfHostedUserConfig(serverId)) {
|
||||
serverJson = userConfig->toJson();
|
||||
} else if (const auto nativeConfig = m_serversRepository->nativeConfig(serverId)) {
|
||||
serverJson = nativeConfig->toJson();
|
||||
} else {
|
||||
result.errorCode = ErrorCode::InternalError;
|
||||
return result;
|
||||
}
|
||||
|
||||
result.config = generateVpnUrl(qCompress(QJsonDocument(serverJson).toJson(), 8));
|
||||
return result;
|
||||
}
|
||||
|
||||
ExportController::ExportResult ExportController::generateConnectionConfig(const QString &serverId, int containerIndex, const QString &clientName)
|
||||
{
|
||||
ExportResult result;
|
||||
|
||||
@@ -38,6 +38,7 @@ public:
|
||||
QObject *parent = nullptr);
|
||||
|
||||
ExportResult generateFullAccessConfig(const QString &serverId);
|
||||
ExportResult generateServerConfig(const QString &serverId);
|
||||
ExportResult generateConnectionConfig(const QString &serverId, int containerIndex, const QString &clientName);
|
||||
ExportResult generateOpenVpnConfig(const QString &serverId, const QString &clientName);
|
||||
ExportResult generateWireGuardConfig(const QString &serverId, const QString &clientName);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
#include "deviceTransferCode.h"
|
||||
|
||||
#include <QNetworkInterface>
|
||||
#include <QSysInfo>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
|
||||
#ifdef Q_OS_MACOS
|
||||
#include "platforms/macos/macosutils.h"
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr QLatin1String scheme("amnezia");
|
||||
constexpr QLatin1String host("receive");
|
||||
constexpr QLatin1String versionKey("v");
|
||||
constexpr QLatin1String nameKey("n");
|
||||
constexpr QLatin1String addressesKey("a");
|
||||
constexpr QLatin1String portKey("p");
|
||||
constexpr QLatin1String publicKeyKey("k");
|
||||
|
||||
constexpr auto base64Options = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals;
|
||||
}
|
||||
|
||||
QString deviceTransfer::TransferCode::toLink() const
|
||||
{
|
||||
QUrlQuery query;
|
||||
query.addQueryItem(versionKey, QString::number(protocolVersion));
|
||||
query.addQueryItem(nameKey, deviceName);
|
||||
query.addQueryItem(addressesKey, addresses.join(','));
|
||||
query.addQueryItem(portKey, QString::number(port));
|
||||
query.addQueryItem(publicKeyKey, QString::fromLatin1(publicKey.toBase64(base64Options)));
|
||||
|
||||
QUrl url;
|
||||
url.setScheme(scheme);
|
||||
url.setHost(host);
|
||||
url.setQuery(query);
|
||||
return url.toString(QUrl::FullyEncoded);
|
||||
}
|
||||
|
||||
std::optional<deviceTransfer::TransferCode> deviceTransfer::TransferCode::parse(const QString &text)
|
||||
{
|
||||
const QUrl url(text.trimmed());
|
||||
if (!url.isValid() || url.scheme() != scheme || url.host() != host) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const QUrlQuery query(url);
|
||||
if (query.queryItemValue(versionKey) != QString::number(protocolVersion)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool isPortValid = false;
|
||||
const uint port = query.queryItemValue(portKey).toUInt(&isPortValid);
|
||||
if (!isPortValid || port == 0 || port > 65535) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
QStringList addresses;
|
||||
for (const QString &candidate : query.queryItemValue(addressesKey).split(',', Qt::SkipEmptyParts)) {
|
||||
const QHostAddress address(candidate);
|
||||
if (address.protocol() == QAbstractSocket::IPv4Protocol && isLanAddress(address)) {
|
||||
addresses.append(address.toString());
|
||||
}
|
||||
}
|
||||
if (addresses.isEmpty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const auto decoded = QByteArray::fromBase64Encoding(query.queryItemValue(publicKeyKey).toLatin1(), base64Options);
|
||||
if (!decoded || decoded.decoded.size() != publicKeySize) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
TransferCode code;
|
||||
code.deviceName = query.queryItemValue(nameKey, QUrl::FullyDecoded);
|
||||
code.addresses = addresses;
|
||||
code.port = static_cast<quint16>(port);
|
||||
code.publicKey = decoded.decoded;
|
||||
return code;
|
||||
}
|
||||
|
||||
bool deviceTransfer::isLanAddress(const QHostAddress &address)
|
||||
{
|
||||
return address.isInSubnet(QHostAddress("10.0.0.0"), 8) || address.isInSubnet(QHostAddress("172.16.0.0"), 12)
|
||||
|| address.isInSubnet(QHostAddress("192.168.0.0"), 16);
|
||||
}
|
||||
|
||||
QStringList deviceTransfer::localLanAddresses()
|
||||
{
|
||||
QStringList addresses;
|
||||
const auto interfaces = QNetworkInterface::allInterfaces();
|
||||
for (const QNetworkInterface &networkInterface : interfaces) {
|
||||
const auto flags = networkInterface.flags();
|
||||
if (!flags.testFlag(QNetworkInterface::IsUp) || !flags.testFlag(QNetworkInterface::IsRunning)
|
||||
|| flags.testFlag(QNetworkInterface::IsLoopBack) || flags.testFlag(QNetworkInterface::IsPointToPoint)
|
||||
|| networkInterface.type() == QNetworkInterface::Virtual) {
|
||||
continue;
|
||||
}
|
||||
for (const QNetworkAddressEntry &entry : networkInterface.addressEntries()) {
|
||||
const QHostAddress address = entry.ip();
|
||||
if (address.protocol() == QAbstractSocket::IPv4Protocol && isLanAddress(address)
|
||||
&& !addresses.contains(address.toString())) {
|
||||
addresses.append(address.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
QString deviceTransfer::localDeviceName()
|
||||
{
|
||||
#ifdef Q_OS_MACOS
|
||||
const QString computerName = MacOSUtils::computerName();
|
||||
if (!computerName.isEmpty()) {
|
||||
return computerName;
|
||||
}
|
||||
#endif
|
||||
const QString hostName = QSysInfo::machineHostName();
|
||||
if (!hostName.isEmpty() && hostName != QLatin1String("localhost")) {
|
||||
return hostName;
|
||||
}
|
||||
return QSysInfo::prettyProductName();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef DEVICETRANSFERCODE_H
|
||||
#define DEVICETRANSFERCODE_H
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QHostAddress>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
namespace deviceTransfer
|
||||
{
|
||||
constexpr int protocolVersion = 1;
|
||||
constexpr int publicKeySize = 32;
|
||||
|
||||
struct TransferCode
|
||||
{
|
||||
QString deviceName;
|
||||
QStringList addresses;
|
||||
quint16 port = 0;
|
||||
QByteArray publicKey;
|
||||
|
||||
QString toLink() const;
|
||||
static std::optional<TransferCode> parse(const QString &text);
|
||||
};
|
||||
|
||||
bool isLanAddress(const QHostAddress &address);
|
||||
QStringList localLanAddresses();
|
||||
QString localDeviceName();
|
||||
}
|
||||
|
||||
#endif // DEVICETRANSFERCODE_H
|
||||
@@ -0,0 +1,106 @@
|
||||
#include "deviceTransferPackage.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "core/utils/deviceTransfer/deviceTransferCode.h"
|
||||
#include "cryptoUtils.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr int nonceSize = 12;
|
||||
constexpr int aesKeySize = 32;
|
||||
constexpr int tagSize = 16;
|
||||
constexpr QLatin1String hkdfInfo("amnezia transfer v1");
|
||||
constexpr QLatin1String versionKey("v");
|
||||
constexpr QLatin1String configsKey("configs");
|
||||
|
||||
QByteArray deriveKey(const QByteArray &ownPrivateKey, const QByteArray &peerPublicKey,
|
||||
const QByteArray &senderPublicKey, const QByteArray &receiverPublicKey)
|
||||
{
|
||||
const QByteArray sharedSecret = CryptoUtils::x25519SharedSecret(ownPrivateKey, peerPublicKey);
|
||||
if (sharedSecret.isEmpty()) {
|
||||
return {};
|
||||
}
|
||||
return CryptoUtils::hkdfSha256(sharedSecret, senderPublicKey + receiverPublicKey, hkdfInfo.latin1(), aesKeySize);
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<deviceTransfer::KeyPair> deviceTransfer::KeyPair::generate()
|
||||
{
|
||||
KeyPair keys;
|
||||
if (!CryptoUtils::generateX25519KeyPair(keys.privateKey, keys.publicKey)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
QByteArray deviceTransfer::sealPackage(const QByteArray &receiverPublicKey, const QStringList &configs)
|
||||
{
|
||||
const auto senderKeys = KeyPair::generate();
|
||||
if (!senderKeys) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const QByteArray key = deriveKey(senderKeys->privateKey, receiverPublicKey, senderKeys->publicKey, receiverPublicKey);
|
||||
const QByteArray nonce = CryptoUtils::generateRandomBytes(nonceSize);
|
||||
if (key.isEmpty() || nonce.isEmpty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
QJsonObject package;
|
||||
package[versionKey] = protocolVersion;
|
||||
package[configsKey] = QJsonArray::fromStringList(configs);
|
||||
const QByteArray plainText = qCompress(QJsonDocument(package).toJson(QJsonDocument::Compact));
|
||||
|
||||
const QByteArray cipherText = CryptoUtils::encryptAes256Gcm(plainText, key, nonce, receiverPublicKey);
|
||||
if (cipherText.isEmpty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray sealed;
|
||||
sealed.append(static_cast<char>(protocolVersion));
|
||||
sealed.append(senderKeys->publicKey);
|
||||
sealed.append(nonce);
|
||||
sealed.append(cipherText);
|
||||
return sealed;
|
||||
}
|
||||
|
||||
std::optional<QStringList> deviceTransfer::openPackage(const KeyPair &receiverKeys, const QByteArray &sealed)
|
||||
{
|
||||
if (sealed.size() < 1 + publicKeySize + nonceSize + tagSize || sealed.at(0) != static_cast<char>(protocolVersion)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const QByteArray senderPublicKey = sealed.mid(1, publicKeySize);
|
||||
const QByteArray nonce = sealed.mid(1 + publicKeySize, nonceSize);
|
||||
const QByteArray cipherText = sealed.mid(1 + publicKeySize + nonceSize);
|
||||
|
||||
const QByteArray key = deriveKey(receiverKeys.privateKey, senderPublicKey, senderPublicKey, receiverKeys.publicKey);
|
||||
if (key.isEmpty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const QByteArray plainText = CryptoUtils::decryptAes256Gcm(cipherText, key, nonce, receiverKeys.publicKey);
|
||||
if (plainText.isEmpty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const QJsonObject package = QJsonDocument::fromJson(qUncompress(plainText)).object();
|
||||
if (package.value(versionKey).toInt() != protocolVersion) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
QStringList configs;
|
||||
for (const QJsonValue &value : package.value(configsKey).toArray()) {
|
||||
const QString config = value.toString();
|
||||
if (!config.isEmpty()) {
|
||||
configs.append(config);
|
||||
}
|
||||
}
|
||||
if (configs.isEmpty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return configs;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef DEVICETRANSFERPACKAGE_H
|
||||
#define DEVICETRANSFERPACKAGE_H
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QStringList>
|
||||
|
||||
namespace deviceTransfer
|
||||
{
|
||||
struct KeyPair
|
||||
{
|
||||
QByteArray privateKey;
|
||||
QByteArray publicKey;
|
||||
|
||||
static std::optional<KeyPair> generate();
|
||||
};
|
||||
|
||||
QByteArray sealPackage(const QByteArray &receiverPublicKey, const QStringList &configs);
|
||||
std::optional<QStringList> openPackage(const KeyPair &receiverKeys, const QByteArray &sealed);
|
||||
}
|
||||
|
||||
#endif // DEVICETRANSFERPACKAGE_H
|
||||
@@ -0,0 +1,161 @@
|
||||
#include "deviceTransferReceiver.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include <QTcpSocket>
|
||||
|
||||
#include "logger.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
Logger logger("DeviceTransferReceiver");
|
||||
|
||||
constexpr int maxHeaderSize = 8 * 1024;
|
||||
constexpr int maxBodySize = 16 * 1024 * 1024;
|
||||
constexpr QLatin1String transferPath("/transfer");
|
||||
constexpr QLatin1String contentLengthHeader("content-length:");
|
||||
|
||||
QByteArray reasonPhrase(int statusCode)
|
||||
{
|
||||
switch (statusCode) {
|
||||
case 200: return "OK";
|
||||
case 400: return "Bad Request";
|
||||
case 403: return "Forbidden";
|
||||
case 404: return "Not Found";
|
||||
case 410: return "Gone";
|
||||
case 413: return "Payload Too Large";
|
||||
default: return "Error";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DeviceTransferReceiver::DeviceTransferReceiver(QObject *parent) : QObject(parent)
|
||||
{
|
||||
connect(&m_server, &QTcpServer::newConnection, this, &DeviceTransferReceiver::handleNewConnection);
|
||||
}
|
||||
|
||||
bool DeviceTransferReceiver::start(const QStringList &addresses, const QString &deviceName)
|
||||
{
|
||||
stop();
|
||||
|
||||
m_keys = deviceTransfer::KeyPair::generate();
|
||||
if (!m_keys) {
|
||||
logger.error() << "key pair generation failed";
|
||||
return false;
|
||||
}
|
||||
if (addresses.isEmpty()) {
|
||||
logger.error() << "no local addresses to listen for";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!m_server.listen(QHostAddress::AnyIPv4, 0)) {
|
||||
logger.error() << "listen failed:" << m_server.errorString();
|
||||
return false;
|
||||
}
|
||||
|
||||
m_isPackageAccepted = false;
|
||||
m_code.deviceName = deviceName;
|
||||
m_code.addresses = addresses;
|
||||
m_code.port = m_server.serverPort();
|
||||
m_code.publicKey = m_keys->publicKey;
|
||||
return true;
|
||||
}
|
||||
|
||||
void DeviceTransferReceiver::stop()
|
||||
{
|
||||
m_server.close();
|
||||
const auto buffers = std::exchange(m_buffers, { });
|
||||
for (auto it = buffers.cbegin(); it != buffers.cend(); ++it) {
|
||||
it.key()->disconnect(this);
|
||||
it.key()->abort();
|
||||
it.key()->deleteLater();
|
||||
}
|
||||
m_keys.reset();
|
||||
m_code = { };
|
||||
}
|
||||
|
||||
deviceTransfer::TransferCode DeviceTransferReceiver::code() const
|
||||
{
|
||||
return m_code;
|
||||
}
|
||||
|
||||
void DeviceTransferReceiver::handleNewConnection()
|
||||
{
|
||||
while (QTcpSocket *socket = m_server.nextPendingConnection()) {
|
||||
m_buffers.insert(socket, { });
|
||||
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() { handleReadyRead(socket); });
|
||||
connect(socket, &QTcpSocket::disconnected, this, [this, socket]() {
|
||||
m_buffers.remove(socket);
|
||||
socket->deleteLater();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceTransferReceiver::handleReadyRead(QTcpSocket *socket)
|
||||
{
|
||||
if (!m_buffers.contains(socket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
QByteArray &buffer = m_buffers[socket];
|
||||
buffer.append(socket->readAll());
|
||||
|
||||
const int headerEnd = buffer.indexOf("\r\n\r\n");
|
||||
if (headerEnd < 0) {
|
||||
if (buffer.size() > maxHeaderSize) {
|
||||
respond(socket, 400);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const QList<QByteArray> headerLines = buffer.left(headerEnd).split('\n');
|
||||
const QList<QByteArray> requestLine = headerLines.first().trimmed().split(' ');
|
||||
if (requestLine.size() < 2 || requestLine.at(0) != "POST" || requestLine.at(1) != transferPath.latin1()) {
|
||||
respond(socket, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
qint64 contentLength = -1;
|
||||
for (const QByteArray &line : headerLines) {
|
||||
const QByteArray trimmedLine = line.trimmed();
|
||||
if (trimmedLine.toLower().startsWith(contentLengthHeader.latin1())) {
|
||||
contentLength = trimmedLine.mid(contentLengthHeader.size()).trimmed().toLongLong();
|
||||
}
|
||||
}
|
||||
if (contentLength <= 0 || contentLength > maxBodySize) {
|
||||
respond(socket, 413);
|
||||
return;
|
||||
}
|
||||
|
||||
const int bodyStart = headerEnd + 4;
|
||||
if (buffer.size() - bodyStart < contentLength) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_isPackageAccepted || !m_keys) {
|
||||
respond(socket, 410);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto configs = deviceTransfer::openPackage(*m_keys, buffer.mid(bodyStart, contentLength));
|
||||
if (!configs) {
|
||||
respond(socket, 403);
|
||||
return;
|
||||
}
|
||||
|
||||
m_isPackageAccepted = true;
|
||||
m_server.close();
|
||||
respond(socket, 200);
|
||||
emit packageReceived(*configs);
|
||||
}
|
||||
|
||||
void DeviceTransferReceiver::respond(QTcpSocket *socket, int statusCode)
|
||||
{
|
||||
m_buffers.remove(socket);
|
||||
socket->disconnect(this);
|
||||
connect(socket, &QTcpSocket::disconnected, socket, &QObject::deleteLater);
|
||||
|
||||
socket->write("HTTP/1.1 " + QByteArray::number(statusCode) + ' ' + reasonPhrase(statusCode)
|
||||
+ "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
socket->disconnectFromHost();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#ifndef DEVICETRANSFERRECEIVER_H
|
||||
#define DEVICETRANSFERRECEIVER_H
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include <QHash>
|
||||
#include <QObject>
|
||||
#include <QStringList>
|
||||
#include <QTcpServer>
|
||||
|
||||
#include "core/utils/deviceTransfer/deviceTransferCode.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferPackage.h"
|
||||
|
||||
class QTcpSocket;
|
||||
|
||||
class DeviceTransferReceiver : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit DeviceTransferReceiver(QObject *parent = nullptr);
|
||||
|
||||
bool start(const QStringList &addresses, const QString &deviceName);
|
||||
void stop();
|
||||
|
||||
deviceTransfer::TransferCode code() const;
|
||||
|
||||
signals:
|
||||
void packageReceived(const QStringList &configs);
|
||||
|
||||
private:
|
||||
void handleNewConnection();
|
||||
void handleReadyRead(QTcpSocket *socket);
|
||||
void respond(QTcpSocket *socket, int statusCode);
|
||||
|
||||
QTcpServer m_server;
|
||||
std::optional<deviceTransfer::KeyPair> m_keys;
|
||||
deviceTransfer::TransferCode m_code;
|
||||
QHash<QTcpSocket *, QByteArray> m_buffers;
|
||||
bool m_isPackageAccepted = false;
|
||||
};
|
||||
|
||||
#endif // DEVICETRANSFERRECEIVER_H
|
||||
@@ -0,0 +1,93 @@
|
||||
#include "deviceTransferSender.h"
|
||||
|
||||
#include <QNetworkProxy>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QUrl>
|
||||
|
||||
#include "logger.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
Logger logger("DeviceTransferSender");
|
||||
|
||||
constexpr int transferTimeoutMsecs = 10000;
|
||||
constexpr int httpOk = 200;
|
||||
constexpr int httpForbidden = 403;
|
||||
constexpr int httpGone = 410;
|
||||
}
|
||||
|
||||
DeviceTransferSender::DeviceTransferSender(QObject *parent) : QObject(parent)
|
||||
{
|
||||
m_networkManager.setProxy(QNetworkProxy::NoProxy);
|
||||
}
|
||||
|
||||
void DeviceTransferSender::send(const deviceTransfer::TransferCode &code, const QByteArray &sealedPackage)
|
||||
{
|
||||
cancel();
|
||||
m_isRefused = false;
|
||||
m_isRejected = false;
|
||||
|
||||
for (const QString &address : code.addresses) {
|
||||
QUrl url;
|
||||
url.setScheme(QStringLiteral("http"));
|
||||
url.setHost(address);
|
||||
url.setPort(code.port);
|
||||
url.setPath(QStringLiteral("/transfer"));
|
||||
|
||||
QNetworkRequest request(url);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/octet-stream"));
|
||||
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);
|
||||
request.setTransferTimeout(transferTimeoutMsecs);
|
||||
|
||||
QNetworkReply *reply = m_networkManager.post(request, sealedPackage);
|
||||
m_replies.append(reply);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() { handleReplyFinished(reply); });
|
||||
}
|
||||
|
||||
if (m_replies.isEmpty()) {
|
||||
logger.error() << "no addresses to send to";
|
||||
emit finished(amnezia::ErrorCode::DeviceTransferUnreachableError);
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceTransferSender::cancel()
|
||||
{
|
||||
const auto replies = m_replies;
|
||||
m_replies.clear();
|
||||
for (QNetworkReply *reply : replies) {
|
||||
reply->disconnect(this);
|
||||
reply->abort();
|
||||
reply->deleteLater();
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceTransferSender::handleReplyFinished(QNetworkReply *reply)
|
||||
{
|
||||
if (!m_replies.removeOne(reply)) {
|
||||
return;
|
||||
}
|
||||
reply->deleteLater();
|
||||
|
||||
const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (statusCode == httpOk) {
|
||||
cancel();
|
||||
emit finished(amnezia::ErrorCode::NoError);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warning() << reply->url().host() << "failed, http status" << QString::number(statusCode) << reply->error();
|
||||
|
||||
if (statusCode == httpForbidden || statusCode == httpGone) {
|
||||
m_isRefused = true;
|
||||
} else if (reply->error() == QNetworkReply::RemoteHostClosedError) {
|
||||
m_isRejected = true;
|
||||
}
|
||||
|
||||
if (m_replies.isEmpty()) {
|
||||
const amnezia::ErrorCode errorCode = m_isRefused ? amnezia::ErrorCode::DeviceTransferRefusedError
|
||||
: m_isRejected ? amnezia::ErrorCode::DeviceTransferRejectedError
|
||||
: amnezia::ErrorCode::DeviceTransferUnreachableError;
|
||||
emit finished(errorCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#ifndef DEVICETRANSFERSENDER_H
|
||||
#define DEVICETRANSFERSENDER_H
|
||||
|
||||
#include <QList>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QObject>
|
||||
|
||||
#include "core/utils/deviceTransfer/deviceTransferCode.h"
|
||||
#include "core/utils/errorCodes.h"
|
||||
|
||||
class QNetworkReply;
|
||||
|
||||
class DeviceTransferSender : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit DeviceTransferSender(QObject *parent = nullptr);
|
||||
|
||||
void send(const deviceTransfer::TransferCode &code, const QByteArray &sealedPackage);
|
||||
void cancel();
|
||||
|
||||
signals:
|
||||
void finished(amnezia::ErrorCode errorCode);
|
||||
|
||||
private:
|
||||
void handleReplyFinished(QNetworkReply *reply);
|
||||
|
||||
QNetworkAccessManager m_networkManager;
|
||||
QList<QNetworkReply *> m_replies;
|
||||
bool m_isRefused = false;
|
||||
bool m_isRejected = false;
|
||||
};
|
||||
|
||||
#endif // DEVICETRANSFERSENDER_H
|
||||
@@ -93,6 +93,11 @@ namespace amnezia
|
||||
ConfigFormatVersionNotSupportedError = 907,
|
||||
RestoreBackupUnsupportedConfigsSkipped = 908,
|
||||
ImportXraySettingsFileUseXrayPage = 909,
|
||||
DeviceTransferInvalidCodeError = 910,
|
||||
DeviceTransferUnreachableError = 911,
|
||||
DeviceTransferRefusedError = 912,
|
||||
DeviceTransferNoLocalNetworkError = 913,
|
||||
DeviceTransferRejectedError = 914,
|
||||
|
||||
// Android errors
|
||||
AndroidError = 1000,
|
||||
|
||||
@@ -105,6 +105,17 @@ QString errorString(ErrorCode code) {
|
||||
|
||||
case (ErrorCode::ImportInvalidConfigError): errorMessage = QObject::tr("The config does not contain any containers and credentials for connecting to the server"); break;
|
||||
case (ErrorCode::ImportBackupFileUseRestoreInstead): errorMessage = QObject::tr("Backup files cannot be imported here. Use 'Restore from backup' instead."); break;
|
||||
case (ErrorCode::DeviceTransferInvalidCodeError):
|
||||
errorMessage = QObject::tr(
|
||||
"This QR code is not for sending a configuration. Scan the code on the screen of the receiving device");
|
||||
break;
|
||||
case (ErrorCode::DeviceTransferRefusedError):
|
||||
errorMessage = QObject::tr("The device did not accept the configuration. Reopen the receiving screen on the "
|
||||
"device and scan the new code");
|
||||
break;
|
||||
case (ErrorCode::DeviceTransferNoLocalNetworkError):
|
||||
errorMessage = QObject::tr("Connect this device to a Wi-Fi or local network to receive a configuration");
|
||||
break;
|
||||
case (ErrorCode::ImportXraySettingsFileUseXrayPage): errorMessage = QObject::tr("This is an XRay settings file, not a connection config. Import it on the XRay Configurations page using 'Import settings'."); break;
|
||||
case (ErrorCode::RestoreBackupInvalidError): errorMessage = QObject::tr("Backup file is corrupted or has invalid format"); break;
|
||||
case (ErrorCode::LegacyApiV1NotSupportedError): errorMessage = QObject::tr("This legacy Amnezia subscription format is no longer supported"); break;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M18 1C18.552 1 19 1.448 19 2V6C19 7.44 18.218 8.197 17.707 8.707C17.218 9.197 17 9.44 17 10V20C17 20.796 16.684 21.558 16.121 22.121C15.558 22.684 14.796 23 14 23H10C9.204 23 8.442 22.684 7.879 22.121C7.316 21.558 7 20.796 7 20V10C7 9.44 6.782 9.197 6.293 8.707C5.782 8.197 5 7.44 5 6V2C5 1.448 5.448 1 6 1H18ZM7.426 7C7.507 7.089 7.6 7.186 7.707 7.293C8.218 7.803 9 8.56 9 10V20C9 20.265 9.105 20.519 9.293 20.707C9.481 20.895 9.735 21 10 21H14C14.265 21 14.519 20.895 14.707 20.707C14.895 20.519 15 20.265 15 20V10C15 8.56 15.782 7.803 16.293 7.293C16.4 7.186 16.493 7.089 16.574 7H7.426ZM7 5H17V3H7V5Z" fill="#09090B"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 735 B |
@@ -33,6 +33,7 @@
|
||||
<file>controls/external-link.svg</file>
|
||||
<file>controls/file-check-2.svg</file>
|
||||
<file>controls/file-cog-2.svg</file>
|
||||
<file>controls/flashlight.svg</file>
|
||||
<file>controls/folder-search-2.svg</file>
|
||||
<file>controls/gauge.svg</file>
|
||||
<file>controls/globe-2.svg</file>
|
||||
|
||||
@@ -74,6 +74,8 @@
|
||||
<true/>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>${CLIENT_APPLICATION_NAME} needs access to the camera for reading QR-codes.</string>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>${CLIENT_APPLICATION_NAME} uses the local network to send and receive connection settings between your devices.</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
|
||||
@@ -37,6 +37,8 @@
|
||||
<string>${BUILD_IOS_GROUP_IDENTIFIER}</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>${CLIENT_APPLICATION_NAME} needs access to the camera for reading QR-codes.</string>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>${CLIENT_APPLICATION_NAME} uses the local network to send and receive connection settings between your devices.</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
<true/>
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.server</key>
|
||||
<true/>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(DEVELOPMENT_TEAM).*</string>
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#include "android_controller.h"
|
||||
#include "android_utils.h"
|
||||
#include "ui/controllers/deviceTransferUiController.h"
|
||||
#include "ui/controllers/importUiController.h"
|
||||
|
||||
namespace
|
||||
@@ -101,6 +102,7 @@ bool AndroidController::initialize()
|
||||
{"onConfigImported", "(Ljava/lang/String;)V", reinterpret_cast<void *>(onConfigImported)},
|
||||
{"onAuthResult", "(Z)V", reinterpret_cast<void *>(onAuthResult)},
|
||||
{"decodeQrCode", "(Ljava/lang/String;)Z", reinterpret_cast<bool *>(decodeQrCode)},
|
||||
{"decodeDeviceTransferQrCode", "(Ljava/lang/String;)Z", reinterpret_cast<bool *>(decodeDeviceTransferQrCode)},
|
||||
{"onImeInsetsChanged", "(I)V", reinterpret_cast<void *>(onImeInsetsChanged)},
|
||||
{"onSystemBarsInsetsChanged", "(II)V", reinterpret_cast<void *>(onSystemBarsInsetsChanged)},
|
||||
{"onActivityPaused", "()V", reinterpret_cast<void *>(onActivityPaused)},
|
||||
@@ -267,6 +269,12 @@ void AndroidController::startQrReaderActivity()
|
||||
callActivityMethod("startQrCodeReader", "()V");
|
||||
}
|
||||
|
||||
void AndroidController::startDeviceTransferQrReaderActivity(const QString &title, const QString &hint)
|
||||
{
|
||||
callActivityMethod("startDeviceTransferQrCodeReader", "(Ljava/lang/String;Ljava/lang/String;)V",
|
||||
QJniObject::fromString(title).object<jstring>(), QJniObject::fromString(hint).object<jstring>());
|
||||
}
|
||||
|
||||
void AndroidController::setSaveLogs(bool enabled)
|
||||
{
|
||||
callActivityMethod("setSaveLogs", "(Z)V", enabled);
|
||||
@@ -667,6 +675,13 @@ bool AndroidController::decodeQrCode(JNIEnv *env, jobject thiz, jstring data)
|
||||
|
||||
return ImportUiController::decodeQrCode(AndroidUtils::convertJString(env, data));
|
||||
}
|
||||
|
||||
bool AndroidController::decodeDeviceTransferQrCode(JNIEnv *env, jobject thiz, jstring data)
|
||||
{
|
||||
Q_UNUSED(thiz);
|
||||
|
||||
return DeviceTransferUiController::decodeQrCode(AndroidUtils::convertJString(env, data));
|
||||
}
|
||||
// static
|
||||
void AndroidController::onImeInsetsChanged(JNIEnv *env, jobject thiz, jint heightDp)
|
||||
{
|
||||
|
||||
@@ -46,6 +46,7 @@ public:
|
||||
int getStatusBarHeight();
|
||||
int getNavigationBarHeight();
|
||||
void startQrReaderActivity();
|
||||
void startDeviceTransferQrReaderActivity(const QString &title, const QString &hint);
|
||||
void setSaveLogs(bool enabled);
|
||||
void setScreenshotsEnabled(bool enabled);
|
||||
void setNavigationBarColor(unsigned int color);
|
||||
@@ -120,6 +121,7 @@ private:
|
||||
static void onFileSaved(JNIEnv *env, jobject thiz, jboolean success, jboolean cancelled);
|
||||
static void onAuthResult(JNIEnv *env, jobject thiz, jboolean result);
|
||||
static bool decodeQrCode(JNIEnv *env, jobject thiz, jstring data);
|
||||
static bool decodeDeviceTransferQrCode(JNIEnv *env, jobject thiz, jstring data);
|
||||
static void onImeInsetsChanged(JNIEnv *env, jobject thiz, jint heightDp);
|
||||
static void onSystemBarsInsetsChanged(JNIEnv *env, jobject thiz, jint navBarHeightDp, jint statusBarHeightDp);
|
||||
static void onActivityPaused(JNIEnv *env, jobject thiz);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef IOSLOCALNETWORK_H
|
||||
#define IOSLOCALNETWORK_H
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include <QString>
|
||||
|
||||
namespace iosLocalNetwork
|
||||
{
|
||||
void checkAccess(const QString &host, quint16 port, std::function<void(bool isDenied)> onResult);
|
||||
void openSettings();
|
||||
}
|
||||
|
||||
#endif // IOSLOCALNETWORK_H
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "iosLocalNetwork.h"
|
||||
|
||||
#include <QByteArray>
|
||||
|
||||
#import <Network/Network.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr int64_t kCheckTimeoutMsecs = 3000;
|
||||
}
|
||||
|
||||
void iosLocalNetwork::checkAccess(const QString &host, quint16 port, std::function<void(bool isDenied)> onResult)
|
||||
{
|
||||
nw_endpoint_t endpoint = nw_endpoint_create_host(host.toUtf8().constData(), QByteArray::number(port).constData());
|
||||
nw_parameters_t parameters =
|
||||
nw_parameters_create_secure_tcp(NW_PARAMETERS_DISABLE_PROTOCOL, NW_PARAMETERS_DEFAULT_CONFIGURATION);
|
||||
nw_connection_t connection = nw_connection_create(endpoint, parameters);
|
||||
|
||||
__block bool isFinished = false;
|
||||
void (^finish)(bool) = ^(bool isDenied) {
|
||||
if (isFinished) {
|
||||
return;
|
||||
}
|
||||
isFinished = true;
|
||||
nw_connection_cancel(connection);
|
||||
onResult(isDenied);
|
||||
};
|
||||
|
||||
nw_connection_set_queue(connection, dispatch_get_main_queue());
|
||||
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t) {
|
||||
if (state == nw_connection_state_ready) {
|
||||
finish(false);
|
||||
} else if (state == nw_connection_state_waiting || state == nw_connection_state_failed) {
|
||||
nw_path_t path = nw_connection_copy_current_path(connection);
|
||||
finish(path && nw_path_get_unsatisfied_reason(path) == nw_path_unsatisfied_reason_local_network_denied);
|
||||
}
|
||||
});
|
||||
nw_connection_start(connection);
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kCheckTimeoutMsecs * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
|
||||
finish(false);
|
||||
});
|
||||
}
|
||||
|
||||
void iosLocalNetwork::openSettings()
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
|
||||
[UIApplication.sharedApplication openURL:url options:@{ } completionHandler:nil];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef IOSQRSCANNER_H
|
||||
#define IOSQRSCANNER_H
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include <QString>
|
||||
|
||||
namespace iosQrScanner
|
||||
{
|
||||
using CodeHandler = std::function<bool(const QString &code)>;
|
||||
using AccessDeniedHandler = std::function<void()>;
|
||||
|
||||
void present(const QString &title, const QString &hint, CodeHandler onCode, AccessDeniedHandler onAccessDenied);
|
||||
void dismiss();
|
||||
}
|
||||
|
||||
#endif // IOSQRSCANNER_H
|
||||
@@ -0,0 +1,471 @@
|
||||
#include "iosQrScanner.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QPainter>
|
||||
#include <QSvgRenderer>
|
||||
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr CGFloat kNavigationBarHeight = 56.0;
|
||||
constexpr CGFloat kNavigationBarSideInset = 4.0;
|
||||
constexpr CGFloat kActionButtonSize = 48.0;
|
||||
constexpr CGFloat kActionButtonRadius = 12.0;
|
||||
constexpr CGFloat kIconSize = 24.0;
|
||||
constexpr CGFloat kTitleFontSize = 18.0;
|
||||
constexpr CGFloat kHintFontSize = 16.0;
|
||||
constexpr CGFloat kHintLineHeight = 24.0;
|
||||
constexpr CGFloat kHintLetterSpacing = -0.4;
|
||||
constexpr CGFloat kContentInset = 16.0;
|
||||
constexpr CGFloat kFrameMaxSide = 290.0;
|
||||
constexpr CGFloat kFrameMargin = 50.0;
|
||||
constexpr CGFloat kFrameRadius = 14.0;
|
||||
constexpr CGFloat kFrameLineWidth = 4.0;
|
||||
constexpr CGFloat kFrameArmRatio = 79.5 / 290.0;
|
||||
constexpr CGFloat kPanelTopPadding = 16.0;
|
||||
constexpr CGFloat kHintToTorchSpacing = 26.0;
|
||||
|
||||
NSString *const kFontFamily = @"PT Root UI VF";
|
||||
|
||||
UIColor *colorFromRgb(uint32_t rgb, CGFloat alpha = 1.0)
|
||||
{
|
||||
return [UIColor colorWithRed:((rgb >> 16) & 0xFF) / 255.0
|
||||
green:((rgb >> 8) & 0xFF) / 255.0
|
||||
blue:(rgb & 0xFF) / 255.0
|
||||
alpha:alpha];
|
||||
}
|
||||
|
||||
UIColor *overlayColor()
|
||||
{
|
||||
return colorFromRgb(0x09090B, 0.5);
|
||||
}
|
||||
|
||||
UIColor *textSecondaryColor()
|
||||
{
|
||||
return colorFromRgb(0xE4E4E7);
|
||||
}
|
||||
|
||||
UIColor *hintColor()
|
||||
{
|
||||
return colorFromRgb(0xD4D4D8);
|
||||
}
|
||||
|
||||
UIColor *actionColor()
|
||||
{
|
||||
return colorFromRgb(0xE4E4E7);
|
||||
}
|
||||
|
||||
UIColor *textInvertedColor()
|
||||
{
|
||||
return colorFromRgb(0x09090B);
|
||||
}
|
||||
|
||||
UIFont *appFont(CGFloat size, UIFontWeight weight)
|
||||
{
|
||||
NSDictionary *traits = @{UIFontWeightTrait : @(weight)};
|
||||
UIFontDescriptor *descriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@ {
|
||||
UIFontDescriptorFamilyAttribute : kFontFamily,
|
||||
UIFontDescriptorTraitsAttribute : traits
|
||||
}];
|
||||
UIFont *font = [UIFont fontWithDescriptor:descriptor size:size];
|
||||
return [font.familyName isEqualToString:kFontFamily] ? font : [UIFont systemFontOfSize:size weight:weight];
|
||||
}
|
||||
|
||||
UIImage *templateIcon(const QString &resource)
|
||||
{
|
||||
const CGFloat scale = UIScreen.mainScreen.scale;
|
||||
const int side = qRound(kIconSize * scale);
|
||||
QImage image(side, side, QImage::Format_ARGB32_Premultiplied);
|
||||
image.fill(Qt::transparent);
|
||||
QPainter painter(&image);
|
||||
QSvgRenderer(resource).render(&painter);
|
||||
painter.end();
|
||||
|
||||
CGImageRef cgImage = image.toCGImage();
|
||||
UIImage *icon = [UIImage imageWithCGImage:cgImage scale:scale orientation:UIImageOrientationUp];
|
||||
CGImageRelease(cgImage);
|
||||
return [icon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
|
||||
}
|
||||
|
||||
UIBezierPath *frameCornersPath(CGRect frame)
|
||||
{
|
||||
const CGFloat r = kFrameRadius;
|
||||
const CGFloat arm = CGRectGetWidth(frame) * kFrameArmRatio;
|
||||
const CGFloat minX = CGRectGetMinX(frame);
|
||||
const CGFloat minY = CGRectGetMinY(frame);
|
||||
const CGFloat maxX = CGRectGetMaxX(frame);
|
||||
const CGFloat maxY = CGRectGetMaxY(frame);
|
||||
|
||||
UIBezierPath *path = [UIBezierPath bezierPath];
|
||||
|
||||
[path moveToPoint:CGPointMake(minX, minY + arm)];
|
||||
[path addArcWithCenter:CGPointMake(minX + r, minY + r)
|
||||
radius:r
|
||||
startAngle:M_PI
|
||||
endAngle:3 * M_PI_2
|
||||
clockwise:YES];
|
||||
[path addLineToPoint:CGPointMake(minX + arm, minY)];
|
||||
|
||||
[path moveToPoint:CGPointMake(maxX - arm, minY)];
|
||||
[path addArcWithCenter:CGPointMake(maxX - r, minY + r) radius:r startAngle:3 * M_PI_2 endAngle:0 clockwise:YES];
|
||||
[path addLineToPoint:CGPointMake(maxX, minY + arm)];
|
||||
|
||||
[path moveToPoint:CGPointMake(maxX, maxY - arm)];
|
||||
[path addArcWithCenter:CGPointMake(maxX - r, maxY - r) radius:r startAngle:0 endAngle:M_PI_2 clockwise:YES];
|
||||
[path addLineToPoint:CGPointMake(maxX - arm, maxY)];
|
||||
|
||||
[path moveToPoint:CGPointMake(minX + arm, maxY)];
|
||||
[path addArcWithCenter:CGPointMake(minX + r, maxY - r) radius:r startAngle:M_PI_2 endAngle:M_PI clockwise:YES];
|
||||
[path addLineToPoint:CGPointMake(minX, maxY - arm)];
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
UIWindowScene *activeWindowScene()
|
||||
{
|
||||
for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
|
||||
if (scene.activationState == UISceneActivationStateForegroundActive &&
|
||||
[scene isKindOfClass:UIWindowScene.class]) {
|
||||
return (UIWindowScene *)scene;
|
||||
}
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
@interface AmneziaQrScannerViewController : UIViewController <AVCaptureMetadataOutputObjectsDelegate>
|
||||
@property (nonatomic, copy) NSString *titleText;
|
||||
@property (nonatomic, copy) NSString *hintText;
|
||||
@property (nonatomic, copy) BOOL (^onCode)(NSString *code);
|
||||
@property (nonatomic, copy) void (^onBack)(void);
|
||||
- (void)stopCapture;
|
||||
@end
|
||||
|
||||
@implementation AmneziaQrScannerViewController {
|
||||
dispatch_queue_t _sessionQueue;
|
||||
AVCaptureSession *_session;
|
||||
AVCaptureMetadataOutput *_metadataOutput;
|
||||
AVCaptureDevice *_device;
|
||||
AVCaptureVideoPreviewLayer *_previewLayer;
|
||||
UIView *_overlayView;
|
||||
CAShapeLayer *_overlayMask;
|
||||
CAShapeLayer *_frameLayer;
|
||||
UIButton *_backButton;
|
||||
UILabel *_titleLabel;
|
||||
UILabel *_hintLabel;
|
||||
UIButton *_torchButton;
|
||||
CGRect _scanRect;
|
||||
BOOL _isTorchEnabled;
|
||||
BOOL _isFinished;
|
||||
}
|
||||
|
||||
- (UIStatusBarStyle)preferredStatusBarStyle
|
||||
{
|
||||
return UIStatusBarStyleLightContent;
|
||||
}
|
||||
|
||||
- (void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
self.view.backgroundColor = UIColor.blackColor;
|
||||
_sessionQueue = dispatch_queue_create("org.amnezia.vpn.qrscanner", DISPATCH_QUEUE_SERIAL);
|
||||
|
||||
_previewLayer = [AVCaptureVideoPreviewLayer layer];
|
||||
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
|
||||
[self.view.layer addSublayer:_previewLayer];
|
||||
|
||||
_overlayView = [[UIView alloc] init];
|
||||
_overlayView.backgroundColor = overlayColor();
|
||||
_overlayView.userInteractionEnabled = NO;
|
||||
_overlayMask = [CAShapeLayer layer];
|
||||
_overlayMask.fillRule = kCAFillRuleEvenOdd;
|
||||
_overlayView.layer.mask = _overlayMask;
|
||||
[self.view addSubview:_overlayView];
|
||||
|
||||
_frameLayer = [CAShapeLayer layer];
|
||||
_frameLayer.fillColor = nil;
|
||||
_frameLayer.strokeColor = UIColor.whiteColor.CGColor;
|
||||
_frameLayer.lineWidth = kFrameLineWidth;
|
||||
[self.view.layer addSublayer:_frameLayer];
|
||||
|
||||
_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
|
||||
[_backButton setImage:templateIcon(QStringLiteral(":/images/controls/arrow-left.svg"))
|
||||
forState:UIControlStateNormal];
|
||||
_backButton.tintColor = textSecondaryColor();
|
||||
[_backButton addTarget:self action:@selector(backTapped) forControlEvents:UIControlEventTouchUpInside];
|
||||
[self.view addSubview:_backButton];
|
||||
|
||||
_titleLabel = [[UILabel alloc] init];
|
||||
_titleLabel.text = self.titleText;
|
||||
_titleLabel.font = appFont(kTitleFontSize, UIFontWeightSemibold);
|
||||
_titleLabel.textColor = textSecondaryColor();
|
||||
_titleLabel.textAlignment = NSTextAlignmentCenter;
|
||||
[self.view addSubview:_titleLabel];
|
||||
|
||||
NSMutableParagraphStyle *hintParagraph = [[NSMutableParagraphStyle alloc] init];
|
||||
hintParagraph.alignment = NSTextAlignmentCenter;
|
||||
hintParagraph.minimumLineHeight = kHintLineHeight;
|
||||
hintParagraph.maximumLineHeight = kHintLineHeight;
|
||||
_hintLabel = [[UILabel alloc] init];
|
||||
_hintLabel.numberOfLines = 0;
|
||||
_hintLabel.attributedText =
|
||||
[[NSAttributedString alloc] initWithString:self.hintText ?: @""
|
||||
attributes:@{
|
||||
NSFontAttributeName : appFont(kHintFontSize, UIFontWeightRegular),
|
||||
NSForegroundColorAttributeName : hintColor(),
|
||||
NSKernAttributeName : @(kHintLetterSpacing),
|
||||
NSParagraphStyleAttributeName : hintParagraph
|
||||
}];
|
||||
[self.view addSubview:_hintLabel];
|
||||
|
||||
_torchButton = [UIButton buttonWithType:UIButtonTypeCustom];
|
||||
[_torchButton setImage:templateIcon(QStringLiteral(":/images/controls/flashlight.svg"))
|
||||
forState:UIControlStateNormal];
|
||||
_torchButton.tintColor = textInvertedColor();
|
||||
_torchButton.backgroundColor = actionColor();
|
||||
_torchButton.layer.cornerRadius = kActionButtonRadius;
|
||||
_torchButton.hidden = YES;
|
||||
[_torchButton addTarget:self action:@selector(torchTapped) forControlEvents:UIControlEventTouchUpInside];
|
||||
[self.view addSubview:_torchButton];
|
||||
|
||||
[self startCapture];
|
||||
}
|
||||
|
||||
- (void)viewDidLayoutSubviews
|
||||
{
|
||||
[super viewDidLayoutSubviews];
|
||||
|
||||
const CGRect bounds = self.view.bounds;
|
||||
const CGFloat width = CGRectGetWidth(bounds);
|
||||
const CGFloat navigationTop = self.view.safeAreaInsets.top;
|
||||
const CGFloat navigationBottom = navigationTop + kNavigationBarHeight;
|
||||
|
||||
_backButton.frame =
|
||||
CGRectMake(kNavigationBarSideInset, navigationTop + (kNavigationBarHeight - kActionButtonSize) / 2,
|
||||
kActionButtonSize, kActionButtonSize);
|
||||
const CGFloat titleInset = kNavigationBarSideInset + kActionButtonSize;
|
||||
_titleLabel.frame = CGRectMake(titleInset, navigationTop, width - 2 * titleInset, kNavigationBarHeight);
|
||||
|
||||
const CGFloat frameSide = MIN(kFrameMaxSide, width - 2 * kFrameMargin);
|
||||
const CGRect frame = CGRectMake((width - frameSide) / 2, navigationBottom + kFrameMargin, frameSide, frameSide);
|
||||
_scanRect = CGRectInset(frame, -kFrameLineWidth / 2, -kFrameLineWidth / 2);
|
||||
|
||||
UIBezierPath *overlayPath = [UIBezierPath bezierPathWithRect:bounds];
|
||||
[overlayPath appendPath:[UIBezierPath bezierPathWithRoundedRect:_scanRect
|
||||
cornerRadius:kFrameRadius + kFrameLineWidth / 2]];
|
||||
|
||||
[CATransaction begin];
|
||||
[CATransaction setDisableActions:YES];
|
||||
_previewLayer.frame = bounds;
|
||||
_overlayView.frame = bounds;
|
||||
_overlayMask.path = overlayPath.CGPath;
|
||||
_frameLayer.path = frameCornersPath(frame).CGPath;
|
||||
[CATransaction commit];
|
||||
|
||||
const CGFloat contentWidth = width - 2 * kContentInset;
|
||||
const CGFloat hintTop = CGRectGetMaxY(frame) + kFrameMargin + kPanelTopPadding;
|
||||
const CGFloat hintHeight = [_hintLabel sizeThatFits:CGSizeMake(contentWidth, CGFLOAT_MAX)].height;
|
||||
_hintLabel.frame = CGRectMake(kContentInset, hintTop, contentWidth, hintHeight);
|
||||
_torchButton.frame =
|
||||
CGRectMake((width - kActionButtonSize) / 2, CGRectGetMaxY(_hintLabel.frame) + kHintToTorchSpacing,
|
||||
kActionButtonSize, kActionButtonSize);
|
||||
|
||||
[self updateRectOfInterest];
|
||||
}
|
||||
|
||||
- (void)updateRectOfInterest
|
||||
{
|
||||
AVCaptureMetadataOutput *output = _metadataOutput;
|
||||
if (!output || CGRectIsEmpty(_scanRect)) {
|
||||
return;
|
||||
}
|
||||
const CGRect rectOfInterest = [_previewLayer metadataOutputRectOfInterestForRect:_scanRect];
|
||||
if (CGRectIsEmpty(rectOfInterest)) {
|
||||
return;
|
||||
}
|
||||
dispatch_async(_sessionQueue, ^{
|
||||
output.rectOfInterest = rectOfInterest;
|
||||
});
|
||||
}
|
||||
|
||||
- (void)startCapture
|
||||
{
|
||||
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
|
||||
AVCaptureDeviceInput *input = device ? [AVCaptureDeviceInput deviceInputWithDevice:device error:nil] : nil;
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
|
||||
AVCaptureSession *session = [[AVCaptureSession alloc] init];
|
||||
if (![session canAddInput:input]) {
|
||||
return;
|
||||
}
|
||||
[session addInput:input];
|
||||
|
||||
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
|
||||
if (![session canAddOutput:output]) {
|
||||
return;
|
||||
}
|
||||
[session addOutput:output];
|
||||
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
|
||||
output.metadataObjectTypes = @[ AVMetadataObjectTypeQRCode ];
|
||||
|
||||
_device = device;
|
||||
_session = session;
|
||||
_metadataOutput = output;
|
||||
_previewLayer.session = session;
|
||||
_torchButton.hidden = !device.hasTorch;
|
||||
|
||||
dispatch_async(_sessionQueue, ^{
|
||||
[session startRunning];
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self updateRectOfInterest];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stopCapture
|
||||
{
|
||||
_isFinished = YES;
|
||||
[self setTorchEnabled:NO];
|
||||
AVCaptureSession *session = _session;
|
||||
_session = nil;
|
||||
if (session) {
|
||||
dispatch_async(_sessionQueue, ^{
|
||||
[session stopRunning];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setTorchEnabled:(BOOL)enabled
|
||||
{
|
||||
if (!_device.hasTorch || ![_device lockForConfiguration:nil]) {
|
||||
return;
|
||||
}
|
||||
_device.torchMode = enabled ? AVCaptureTorchModeOn : AVCaptureTorchModeOff;
|
||||
[_device unlockForConfiguration];
|
||||
_isTorchEnabled = enabled;
|
||||
}
|
||||
|
||||
- (void)torchTapped
|
||||
{
|
||||
[self setTorchEnabled:!_isTorchEnabled];
|
||||
}
|
||||
|
||||
- (void)backTapped
|
||||
{
|
||||
if (self.onBack) {
|
||||
self.onBack();
|
||||
}
|
||||
}
|
||||
|
||||
- (void)captureOutput:(AVCaptureOutput *)output
|
||||
didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects
|
||||
fromConnection:(AVCaptureConnection *)connection
|
||||
{
|
||||
if (_isFinished || !self.onCode) {
|
||||
return;
|
||||
}
|
||||
for (AVMetadataObject *object in metadataObjects) {
|
||||
if (![object isKindOfClass:AVMetadataMachineReadableCodeObject.class]) {
|
||||
continue;
|
||||
}
|
||||
NSString *value = ((AVMetadataMachineReadableCodeObject *)object).stringValue;
|
||||
if (value.length > 0 && self.onCode(value)) {
|
||||
_isFinished = YES;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
namespace
|
||||
{
|
||||
UIWindow *scannerWindow = nil;
|
||||
|
||||
void dismissLater()
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
iosQrScanner::dismiss();
|
||||
});
|
||||
}
|
||||
|
||||
void showScanner(const QString &title, const QString &hint, iosQrScanner::CodeHandler onCode)
|
||||
{
|
||||
UIWindowScene *scene = activeWindowScene();
|
||||
if (!scene) {
|
||||
return;
|
||||
}
|
||||
|
||||
AmneziaQrScannerViewController *controller = [[AmneziaQrScannerViewController alloc] init];
|
||||
controller.titleText = title.toNSString();
|
||||
controller.hintText = hint.toNSString();
|
||||
controller.onCode = ^BOOL(NSString *code) {
|
||||
if (!onCode(QString::fromNSString(code))) {
|
||||
return NO;
|
||||
}
|
||||
dismissLater();
|
||||
return YES;
|
||||
};
|
||||
controller.onBack = ^{
|
||||
dismissLater();
|
||||
};
|
||||
|
||||
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
|
||||
window.windowLevel = UIWindowLevelNormal + 1;
|
||||
window.rootViewController = controller;
|
||||
scannerWindow = window;
|
||||
[window makeKeyAndVisible];
|
||||
}
|
||||
}
|
||||
|
||||
void iosQrScanner::present(const QString &title, const QString &hint, CodeHandler onCode,
|
||||
AccessDeniedHandler onAccessDenied)
|
||||
{
|
||||
dismiss();
|
||||
|
||||
switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
|
||||
case AVAuthorizationStatusAuthorized: showScanner(title, hint, std::move(onCode)); return;
|
||||
case AVAuthorizationStatusNotDetermined: {
|
||||
const QString titleCopy = title;
|
||||
const QString hintCopy = hint;
|
||||
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
|
||||
completionHandler:^(BOOL granted) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (granted) {
|
||||
showScanner(titleCopy, hintCopy, onCode);
|
||||
} else {
|
||||
onAccessDenied();
|
||||
}
|
||||
});
|
||||
}];
|
||||
return;
|
||||
}
|
||||
default: onAccessDenied(); return;
|
||||
}
|
||||
}
|
||||
|
||||
void iosQrScanner::dismiss()
|
||||
{
|
||||
UIWindow *window = scannerWindow;
|
||||
scannerWindow = nil;
|
||||
if (!window) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ([window.rootViewController isKindOfClass:AmneziaQrScannerViewController.class]) {
|
||||
[(AmneziaQrScannerViewController *)window.rootViewController stopCapture];
|
||||
}
|
||||
window.hidden = YES;
|
||||
window.rootViewController = nil;
|
||||
|
||||
for (UIWindow *candidate in window.windowScene.windows) {
|
||||
if (candidate != window && !candidate.hidden) {
|
||||
[candidate makeKeyWindow];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
Q_FORWARD_DECLARE_OBJC_CLASS(NSString);
|
||||
|
||||
class MacOSUtils final {
|
||||
public:
|
||||
static NSString* appId();
|
||||
|
||||
@@ -269,6 +269,15 @@ if(NOT ANDROID)
|
||||
test_common
|
||||
)
|
||||
|
||||
add_executable(test_device_transfer
|
||||
testDeviceTransfer.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(test_device_transfer PRIVATE
|
||||
Qt6::Test
|
||||
test_common
|
||||
)
|
||||
|
||||
add_executable(test_openssl_library
|
||||
testOpenSSLLibrary.cpp
|
||||
)
|
||||
@@ -492,6 +501,7 @@ if(NOT ANDROID)
|
||||
add_test(NAME ConnectionTest COMMAND test_connection)
|
||||
add_test(NAME OpenSSLLibraryTest COMMAND test_openssl_library)
|
||||
add_test(NAME LogsControllerTest COMMAND test_logs_controller)
|
||||
add_test(NAME DeviceTransferTest COMMAND test_device_transfer)
|
||||
endif()
|
||||
|
||||
# Android tests are executed on-device via androidtestrunner in CI (see .github/workflows/tests.yml).
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
#include <QHostAddress>
|
||||
#include <QSignalSpy>
|
||||
#include <QTest>
|
||||
|
||||
#include "core/utils/deviceTransfer/deviceTransferCode.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferPackage.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferReceiver.h"
|
||||
#include "core/utils/deviceTransfer/deviceTransferSender.h"
|
||||
#include "core/utils/errorCodes.h"
|
||||
|
||||
using namespace amnezia;
|
||||
|
||||
class TestDeviceTransfer : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private:
|
||||
static constexpr int networkTimeoutMsecs = 15000;
|
||||
|
||||
deviceTransfer::TransferCode loopbackCode(const DeviceTransferReceiver &receiver)
|
||||
{
|
||||
deviceTransfer::TransferCode code = receiver.code();
|
||||
code.addresses = { QStringLiteral("127.0.0.1") };
|
||||
return code;
|
||||
}
|
||||
|
||||
ErrorCode sendAndWait(DeviceTransferSender &sender, const deviceTransfer::TransferCode &code,
|
||||
const QByteArray &sealedPackage)
|
||||
{
|
||||
QSignalSpy finishedSpy(&sender, &DeviceTransferSender::finished);
|
||||
sender.send(code, sealedPackage);
|
||||
if (finishedSpy.isEmpty() && !finishedSpy.wait(networkTimeoutMsecs)) {
|
||||
return ErrorCode::InternalError;
|
||||
}
|
||||
return finishedSpy.first().first().value<ErrorCode>();
|
||||
}
|
||||
|
||||
private slots:
|
||||
void initTestCase()
|
||||
{
|
||||
qRegisterMetaType<ErrorCode>();
|
||||
}
|
||||
|
||||
void sealedPackageOpensWithReceiverKeys()
|
||||
{
|
||||
const auto receiverKeys = deviceTransfer::KeyPair::generate();
|
||||
QVERIFY(receiverKeys);
|
||||
|
||||
const QStringList configs = { QStringLiteral("vpn://first"), QStringLiteral("vpn://second") };
|
||||
const QByteArray sealed = deviceTransfer::sealPackage(receiverKeys->publicKey, configs);
|
||||
QVERIFY(!sealed.isEmpty());
|
||||
|
||||
const auto opened = deviceTransfer::openPackage(*receiverKeys, sealed);
|
||||
QVERIFY(opened);
|
||||
QCOMPARE(*opened, configs);
|
||||
}
|
||||
|
||||
void tamperedPackageIsRejected()
|
||||
{
|
||||
const auto receiverKeys = deviceTransfer::KeyPair::generate();
|
||||
QVERIFY(receiverKeys);
|
||||
|
||||
QByteArray sealed = deviceTransfer::sealPackage(receiverKeys->publicKey, { QStringLiteral("vpn://config") });
|
||||
sealed[sealed.size() - 20] = static_cast<char>(sealed.at(sealed.size() - 20) ^ 0x01);
|
||||
|
||||
QVERIFY(!deviceTransfer::openPackage(*receiverKeys, sealed));
|
||||
}
|
||||
|
||||
void packageSealedToAnotherKeyIsRejected()
|
||||
{
|
||||
const auto receiverKeys = deviceTransfer::KeyPair::generate();
|
||||
const auto otherKeys = deviceTransfer::KeyPair::generate();
|
||||
QVERIFY(receiverKeys && otherKeys);
|
||||
|
||||
const QByteArray sealed = deviceTransfer::sealPackage(otherKeys->publicKey, { QStringLiteral("vpn://config") });
|
||||
|
||||
QVERIFY(!deviceTransfer::openPackage(*receiverKeys, sealed));
|
||||
}
|
||||
|
||||
void codeSurvivesLinkRoundTrip()
|
||||
{
|
||||
const auto keys = deviceTransfer::KeyPair::generate();
|
||||
QVERIFY(keys);
|
||||
|
||||
deviceTransfer::TransferCode code;
|
||||
code.deviceName = QStringLiteral("Living room TV & Co = №1");
|
||||
code.addresses = { QStringLiteral("192.168.1.20"), QStringLiteral("10.0.0.5") };
|
||||
code.port = 50123;
|
||||
code.publicKey = keys->publicKey;
|
||||
|
||||
const auto parsed = deviceTransfer::TransferCode::parse(code.toLink());
|
||||
QVERIFY(parsed);
|
||||
QCOMPARE(parsed->deviceName, code.deviceName);
|
||||
QCOMPARE(parsed->addresses, code.addresses);
|
||||
QCOMPARE(parsed->port, code.port);
|
||||
QCOMPARE(parsed->publicKey, code.publicKey);
|
||||
}
|
||||
|
||||
void invalidCodesAreRejected_data()
|
||||
{
|
||||
QTest::addColumn<QString>("text");
|
||||
|
||||
const QString key = QString::fromLatin1(
|
||||
QByteArray(32, 'k').toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals));
|
||||
|
||||
QTest::newRow("vpn key") << QStringLiteral("vpn://AAAA");
|
||||
QTest::newRow("other scheme") << QStringLiteral("anoya://receive?v=1&n=tv&a=192.168.1.2&p=5000&k=%1").arg(key);
|
||||
QTest::newRow("unknown version") << QStringLiteral("amnezia://receive?v=2&n=tv&a=192.168.1.2&p=5000&k=%1").arg(key);
|
||||
QTest::newRow("public address") << QStringLiteral("amnezia://receive?v=1&n=tv&a=8.8.8.8&p=5000&k=%1").arg(key);
|
||||
QTest::newRow("loopback address")
|
||||
<< QStringLiteral("amnezia://receive?v=1&n=tv&a=127.0.0.1&p=5000&k=%1").arg(key);
|
||||
QTest::newRow("no port") << QStringLiteral("amnezia://receive?v=1&n=tv&a=192.168.1.2&k=%1").arg(key);
|
||||
QTest::newRow("short key") << QStringLiteral("amnezia://receive?v=1&n=tv&a=192.168.1.2&p=5000&k=AAAA");
|
||||
}
|
||||
|
||||
void invalidCodesAreRejected()
|
||||
{
|
||||
QFETCH(QString, text);
|
||||
QVERIFY(!deviceTransfer::TransferCode::parse(text));
|
||||
}
|
||||
|
||||
void onlyPrivateAddressesAreLan()
|
||||
{
|
||||
QVERIFY(deviceTransfer::isLanAddress(QHostAddress("10.1.2.3")));
|
||||
QVERIFY(deviceTransfer::isLanAddress(QHostAddress("172.16.0.1")));
|
||||
QVERIFY(deviceTransfer::isLanAddress(QHostAddress("172.31.255.254")));
|
||||
QVERIFY(deviceTransfer::isLanAddress(QHostAddress("192.168.0.10")));
|
||||
QVERIFY(!deviceTransfer::isLanAddress(QHostAddress("172.32.0.1")));
|
||||
QVERIFY(!deviceTransfer::isLanAddress(QHostAddress("127.0.0.1")));
|
||||
QVERIFY(!deviceTransfer::isLanAddress(QHostAddress("169.254.1.1")));
|
||||
QVERIFY(!deviceTransfer::isLanAddress(QHostAddress("8.8.8.8")));
|
||||
}
|
||||
|
||||
void receiverAcceptsOnePackageAndCloses()
|
||||
{
|
||||
DeviceTransferReceiver receiver;
|
||||
QVERIFY(receiver.start({ QStringLiteral("192.168.1.2") }, QStringLiteral("TV")));
|
||||
QSignalSpy receivedSpy(&receiver, &DeviceTransferReceiver::packageReceived);
|
||||
|
||||
const deviceTransfer::TransferCode code = loopbackCode(receiver);
|
||||
const QStringList configs = { QStringLiteral("vpn://config") };
|
||||
|
||||
DeviceTransferSender sender;
|
||||
QCOMPARE(sendAndWait(sender, code, deviceTransfer::sealPackage(code.publicKey, configs)), ErrorCode::NoError);
|
||||
QCOMPARE(receivedSpy.count(), 1);
|
||||
QCOMPARE(receivedSpy.first().first().toStringList(), configs);
|
||||
|
||||
QCOMPARE(sendAndWait(sender, code, deviceTransfer::sealPackage(code.publicKey, configs)),
|
||||
ErrorCode::DeviceTransferUnreachableError);
|
||||
QCOMPARE(receivedSpy.count(), 1);
|
||||
}
|
||||
|
||||
void packageForOldCodeIsRefusedAndCurrentCodeStillWorks()
|
||||
{
|
||||
const auto oldKeys = deviceTransfer::KeyPair::generate();
|
||||
QVERIFY(oldKeys);
|
||||
|
||||
DeviceTransferReceiver receiver;
|
||||
QVERIFY(receiver.start({ QStringLiteral("192.168.1.2") }, QStringLiteral("TV")));
|
||||
QSignalSpy receivedSpy(&receiver, &DeviceTransferReceiver::packageReceived);
|
||||
|
||||
const deviceTransfer::TransferCode code = loopbackCode(receiver);
|
||||
const QStringList configs = { QStringLiteral("vpn://config") };
|
||||
|
||||
DeviceTransferSender sender;
|
||||
QCOMPARE(sendAndWait(sender, code, deviceTransfer::sealPackage(oldKeys->publicKey, configs)),
|
||||
ErrorCode::DeviceTransferRefusedError);
|
||||
QCOMPARE(receivedSpy.count(), 0);
|
||||
|
||||
QCOMPARE(sendAndWait(sender, code, deviceTransfer::sealPackage(code.publicKey, configs)), ErrorCode::NoError);
|
||||
QCOMPARE(receivedSpy.count(), 1);
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TestDeviceTransfer)
|
||||
#include "testDeviceTransfer.moc"
|
||||
@@ -0,0 +1,150 @@
|
||||
#include "deviceTransferUiController.h"
|
||||
|
||||
#include "core/utils/qrCodeUtils.h"
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include "platforms/android/android_controller.h"
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_IOS
|
||||
#include "platforms/ios/iosLocalNetwork.h"
|
||||
#include "platforms/ios/iosQrScanner.h"
|
||||
#endif
|
||||
|
||||
#if defined Q_OS_ANDROID
|
||||
DeviceTransferUiController *DeviceTransferUiController::mInstance = nullptr;
|
||||
#endif
|
||||
|
||||
DeviceTransferUiController::DeviceTransferUiController(DeviceTransferController *deviceTransferController, QObject *parent)
|
||||
: QObject(parent), m_deviceTransferController(deviceTransferController)
|
||||
{
|
||||
#if defined Q_OS_ANDROID
|
||||
mInstance = this;
|
||||
#endif
|
||||
|
||||
connect(m_deviceTransferController, &DeviceTransferController::packageReceived, this, [this]() {
|
||||
m_receiveQrCode.clear();
|
||||
emit receiveQrCodeChanged();
|
||||
emit packageReceived();
|
||||
});
|
||||
connect(m_deviceTransferController, &DeviceTransferController::importFailed, this,
|
||||
&DeviceTransferUiController::errorOccurred);
|
||||
connect(m_deviceTransferController, &DeviceTransferController::sendFinished, this,
|
||||
&DeviceTransferUiController::handleSendFinished);
|
||||
}
|
||||
|
||||
QString DeviceTransferUiController::receiveQrCode() const
|
||||
{
|
||||
return m_receiveQrCode;
|
||||
}
|
||||
|
||||
QString DeviceTransferUiController::scannedDeviceName() const
|
||||
{
|
||||
return m_scannedCode ? m_scannedCode->deviceName : QString();
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::startReceiving()
|
||||
{
|
||||
const amnezia::ErrorCode errorCode = m_deviceTransferController->startReceiving();
|
||||
m_receiveQrCode = errorCode == amnezia::ErrorCode::NoError
|
||||
? qrCodeUtils::generatePlainQrCodeImage(m_deviceTransferController->receiveLink().toUtf8())
|
||||
: QString();
|
||||
emit receiveQrCodeChanged();
|
||||
|
||||
if (errorCode != amnezia::ErrorCode::NoError) {
|
||||
emit errorOccurred(errorCode);
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::stopReceiving()
|
||||
{
|
||||
m_deviceTransferController->stopReceiving();
|
||||
m_receiveQrCode.clear();
|
||||
emit receiveQrCodeChanged();
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::openNetworkAccessSettings()
|
||||
{
|
||||
#if defined Q_OS_IOS
|
||||
iosLocalNetwork::openSettings();
|
||||
#endif
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::startScanning(const QString &title, const QString &hint)
|
||||
{
|
||||
#if defined Q_OS_ANDROID
|
||||
AndroidController::instance()->startDeviceTransferQrReaderActivity(title, hint);
|
||||
#elif defined Q_OS_IOS
|
||||
iosQrScanner::present(
|
||||
title, hint, [this](const QString &code) { return processScannedCode(code); },
|
||||
[this]() { emit cameraAccessDenied(); });
|
||||
#else
|
||||
Q_UNUSED(title);
|
||||
Q_UNUSED(hint);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool DeviceTransferUiController::processScannedCode(const QString &code)
|
||||
{
|
||||
const auto transferCode = deviceTransfer::TransferCode::parse(code);
|
||||
if (!transferCode) {
|
||||
return false;
|
||||
}
|
||||
|
||||
m_scannedCode = transferCode;
|
||||
emit scannedDeviceNameChanged();
|
||||
emit codeScanned();
|
||||
return true;
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::send(const QString &serverId)
|
||||
{
|
||||
if (!m_scannedCode) {
|
||||
emit sendFailed(amnezia::ErrorCode::DeviceTransferInvalidCodeError);
|
||||
return;
|
||||
}
|
||||
m_deviceTransferController->send(*m_scannedCode, { serverId });
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::cancelSending()
|
||||
{
|
||||
m_deviceTransferController->cancelSending();
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::reportUnreachable()
|
||||
{
|
||||
#if defined Q_OS_IOS
|
||||
if (m_scannedCode && !m_scannedCode->addresses.isEmpty()) {
|
||||
iosLocalNetwork::checkAccess(m_scannedCode->addresses.first(), m_scannedCode->port, [this](bool isDenied) {
|
||||
if (isDenied) {
|
||||
emit localNetworkDenied();
|
||||
} else {
|
||||
emit deviceUnreachable();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
emit deviceUnreachable();
|
||||
}
|
||||
|
||||
void DeviceTransferUiController::handleSendFinished(amnezia::ErrorCode errorCode)
|
||||
{
|
||||
switch (errorCode) {
|
||||
case amnezia::ErrorCode::NoError: emit sent(); break;
|
||||
case amnezia::ErrorCode::DeviceTransferUnreachableError: reportUnreachable(); break;
|
||||
case amnezia::ErrorCode::DeviceTransferRejectedError: emit deviceRejected(); break;
|
||||
default: emit sendFailed(errorCode); break;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined Q_OS_ANDROID
|
||||
bool DeviceTransferUiController::decodeQrCode(const QString &code)
|
||||
{
|
||||
if (!mInstance || !deviceTransfer::TransferCode::parse(code)) {
|
||||
return false;
|
||||
}
|
||||
QMetaObject::invokeMethod(mInstance, [code]() { mInstance->processScannedCode(code); }, Qt::QueuedConnection);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,64 @@
|
||||
#ifndef DEVICETRANSFERUICONTROLLER_H
|
||||
#define DEVICETRANSFERUICONTROLLER_H
|
||||
|
||||
#include <optional>
|
||||
|
||||
#include <QObject>
|
||||
|
||||
#include "core/controllers/deviceTransferController.h"
|
||||
|
||||
class DeviceTransferUiController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
Q_PROPERTY(QString receiveQrCode READ receiveQrCode NOTIFY receiveQrCodeChanged)
|
||||
Q_PROPERTY(QString scannedDeviceName READ scannedDeviceName NOTIFY scannedDeviceNameChanged)
|
||||
|
||||
public:
|
||||
explicit DeviceTransferUiController(DeviceTransferController *deviceTransferController, QObject *parent = nullptr);
|
||||
|
||||
QString receiveQrCode() const;
|
||||
QString scannedDeviceName() const;
|
||||
|
||||
#if defined Q_OS_ANDROID
|
||||
static bool decodeQrCode(const QString &code);
|
||||
#endif
|
||||
|
||||
public slots:
|
||||
void startReceiving();
|
||||
void stopReceiving();
|
||||
void openNetworkAccessSettings();
|
||||
|
||||
void startScanning(const QString &title, const QString &hint);
|
||||
bool processScannedCode(const QString &code);
|
||||
void send(const QString &serverId);
|
||||
void cancelSending();
|
||||
|
||||
signals:
|
||||
void receiveQrCodeChanged();
|
||||
void scannedDeviceNameChanged();
|
||||
void codeScanned();
|
||||
void cameraAccessDenied();
|
||||
void packageReceived();
|
||||
void errorOccurred(amnezia::ErrorCode errorCode);
|
||||
void sent();
|
||||
void deviceUnreachable();
|
||||
void localNetworkDenied();
|
||||
void deviceRejected();
|
||||
void sendFailed(amnezia::ErrorCode errorCode);
|
||||
|
||||
private:
|
||||
void handleSendFinished(amnezia::ErrorCode errorCode);
|
||||
void reportUnreachable();
|
||||
|
||||
DeviceTransferController *m_deviceTransferController;
|
||||
|
||||
QString m_receiveQrCode;
|
||||
std::optional<deviceTransfer::TransferCode> m_scannedCode;
|
||||
|
||||
#if defined Q_OS_ANDROID
|
||||
static DeviceTransferUiController *mInstance;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif // DEVICETRANSFERUICONTROLLER_H
|
||||
@@ -50,6 +50,9 @@ QVariant ApiAccountInfoModel::data(const QModelIndex &index, int role) const
|
||||
}
|
||||
return tr("%1 out of %2").arg(m_accountInfoData.activeDeviceCount).arg(m_accountInfoData.maxDeviceCount);
|
||||
}
|
||||
case AvailableDeviceSlotsRole: {
|
||||
return qMax(0, m_accountInfoData.maxDeviceCount - m_accountInfoData.activeDeviceCount);
|
||||
}
|
||||
case ServiceDescriptionRole: {
|
||||
return m_accountInfoData.subscriptionDescription;
|
||||
}
|
||||
@@ -187,6 +190,7 @@ QHash<int, QByteArray> ApiAccountInfoModel::roleNames() const
|
||||
roles[SubscriptionStatusRole] = "subscriptionStatus";
|
||||
roles[EndDateRole] = "endDate";
|
||||
roles[ConnectedDevicesRole] = "connectedDevices";
|
||||
roles[AvailableDeviceSlotsRole] = "availableDeviceSlots";
|
||||
roles[ServiceDescriptionRole] = "serviceDescription";
|
||||
roles[IsComponentVisibleRole] = "isComponentVisible";
|
||||
roles[IsSubscriptionRenewalAvailableRole] = "isSubscriptionRenewalAvailable";
|
||||
|
||||
@@ -17,6 +17,7 @@ public:
|
||||
enum Roles {
|
||||
SubscriptionStatusRole = Qt::UserRole + 1,
|
||||
ConnectedDevicesRole,
|
||||
AvailableDeviceSlotsRole,
|
||||
ServiceDescriptionRole,
|
||||
EndDateRole,
|
||||
IsComponentVisibleRole,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import QtQuick
|
||||
|
||||
import PageEnum 1.0
|
||||
|
||||
import "../Controls2"
|
||||
|
||||
ListItemType {
|
||||
id: root
|
||||
|
||||
property bool isScanning: false
|
||||
|
||||
text: qsTr("Send to device")
|
||||
subtitle: qsTr("Via QR code on the device screen")
|
||||
trailingIconSource: "qrc:/images/controls/chevron-right.svg"
|
||||
|
||||
onClicked: {
|
||||
root.isScanning = true
|
||||
DeviceTransferController.startScanning(qsTr("Send to device"),
|
||||
qsTr("Point the camera at the QR code on the device screen. Your phone and the device must be on the same network"))
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: DeviceTransferController
|
||||
enabled: root.isScanning
|
||||
|
||||
function onCodeScanned() {
|
||||
root.isScanning = false
|
||||
PageController.goToPage(PageEnum.PageSendToDeviceConfirm)
|
||||
}
|
||||
|
||||
function onCameraAccessDenied() {
|
||||
root.isScanning = false
|
||||
PageController.showNotificationMessage(qsTr("Allow camera access for %1 in Settings to scan the code").arg(Qt.application.displayName))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
|
||||
import Style 1.0
|
||||
|
||||
import "./"
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
|
||||
PageType {
|
||||
id: root
|
||||
|
||||
readonly property string serverId: ServersUiController.processedServerId
|
||||
readonly property string deviceName: DeviceTransferController.scannedDeviceName
|
||||
|
||||
function send() {
|
||||
PageController.showBusyIndicator(true)
|
||||
DeviceTransferController.send(root.serverId)
|
||||
}
|
||||
|
||||
Component.onDestruction: DeviceTransferController.cancelSending()
|
||||
|
||||
Connections {
|
||||
target: DeviceTransferController
|
||||
|
||||
function onSent() {
|
||||
PageController.showBusyIndicator(false)
|
||||
PageController.showNotificationMessage(qsTr("Sent to “%1”").arg(root.deviceName))
|
||||
PageController.closePage()
|
||||
}
|
||||
|
||||
function onDeviceUnreachable() {
|
||||
deliveryFailedDialog.show(deliveryFailedDialog.reasonUnreachable)
|
||||
}
|
||||
|
||||
function onDeviceRejected() {
|
||||
deliveryFailedDialog.show(deliveryFailedDialog.reasonRejected)
|
||||
}
|
||||
|
||||
function onLocalNetworkDenied() {
|
||||
deliveryFailedDialog.show(deliveryFailedDialog.reasonLocalNetworkDenied)
|
||||
}
|
||||
|
||||
function onSendFailed(errorCode) {
|
||||
PageController.showBusyIndicator(false)
|
||||
PageController.showErrorMessage(errorCode)
|
||||
}
|
||||
}
|
||||
|
||||
FlickableType {
|
||||
id: flickable
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.bottom: bottomBar.top
|
||||
|
||||
contentHeight: content.implicitHeight
|
||||
|
||||
ColumnLayout {
|
||||
id: content
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
|
||||
spacing: 0
|
||||
|
||||
NavigationBarType {
|
||||
Layout.fillWidth: true
|
||||
|
||||
title: qsTr("Send to device")
|
||||
}
|
||||
|
||||
BodyTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
text: ServersUiController.isServerFromApi(root.serverId)
|
||||
? qsTr("Once connected, “%1” will take one device slot in your subscription. Slots left: %2")
|
||||
.arg(root.deviceName).arg(ApiAccountInfoModel.data("availableDeviceSlots"))
|
||||
: qsTr("“%1” will get full access to the server “%2”, including server management")
|
||||
.arg(root.deviceName).arg(ServersUiController.serverName(root.serverId))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BottomBarType {
|
||||
id: bottomBar
|
||||
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
|
||||
ButtonType {
|
||||
Layout.fillWidth: true
|
||||
|
||||
text: qsTr("Send")
|
||||
|
||||
onClicked: root.send()
|
||||
}
|
||||
|
||||
ButtonType {
|
||||
Layout.fillWidth: true
|
||||
|
||||
variant: ButtonType.Secondary
|
||||
text: qsTr("Cancel")
|
||||
|
||||
onClicked: PageController.closePage()
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialogType {
|
||||
id: deliveryFailedDialog
|
||||
|
||||
readonly property string reasonUnreachable: "unreachable"
|
||||
readonly property string reasonRejected: "rejected"
|
||||
readonly property string reasonLocalNetworkDenied: "localNetworkDenied"
|
||||
|
||||
property string reason: reasonUnreachable
|
||||
|
||||
function show(reason) {
|
||||
PageController.showBusyIndicator(false)
|
||||
deliveryFailedDialog.reason = reason
|
||||
deliveryFailedDialog.open()
|
||||
}
|
||||
|
||||
headerText: {
|
||||
switch (reason) {
|
||||
case reasonRejected: return qsTr("The device rejected the connection")
|
||||
case reasonLocalNetworkDenied: return qsTr("No access to the local network")
|
||||
default: return qsTr("Couldn't reach the device")
|
||||
}
|
||||
}
|
||||
descriptionText: {
|
||||
switch (reason) {
|
||||
case reasonRejected:
|
||||
return qsTr("Your phone found the device, but the device closed the connection. Its firewall may be blocking %1. Allow incoming connections for %1 on the device and try again")
|
||||
.arg(Qt.application.displayName)
|
||||
case reasonLocalNetworkDenied:
|
||||
return qsTr("%1 is not allowed to use the local network, so it can't reach the device. Turn on Local Network for %1 in Settings and try again")
|
||||
.arg(Qt.application.displayName)
|
||||
default:
|
||||
return qsTr("Make sure your phone and the device are on the same network. If your phone is connected to a VPN, disconnect and try again")
|
||||
}
|
||||
}
|
||||
cancelButtonText: qsTr("Close")
|
||||
confirmButtonText: reason === reasonLocalNetworkDenied ? qsTr("Open settings") : qsTr("Retry")
|
||||
|
||||
onConfirmed: {
|
||||
if (reason === reasonLocalNetworkDenied) {
|
||||
DeviceTransferController.openNetworkAccessSettings()
|
||||
} else {
|
||||
root.send()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,6 +313,12 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
SendToDeviceListItem {
|
||||
Layout.fillWidth: true
|
||||
|
||||
visible: root.isVisibleForAmneziaFree && SettingsController.isCameraPresent()
|
||||
}
|
||||
|
||||
ListItemType {
|
||||
Layout.fillWidth: true
|
||||
|
||||
|
||||
@@ -91,6 +91,14 @@ PageType {
|
||||
|
||||
spacing: 0
|
||||
|
||||
SendToDeviceListItem {
|
||||
Layout.fillWidth: true
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
visible: root.isServerWithWriteAccess && SettingsController.isCameraPresent()
|
||||
}
|
||||
|
||||
ListItemType {
|
||||
Layout.fillWidth: true
|
||||
Layout.leftMargin: 16
|
||||
|
||||
@@ -234,6 +234,22 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
BasicCardType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 12
|
||||
Layout.rightMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
|
||||
text: qsTr("Receive from phone")
|
||||
subtitle: qsTr("Via QR code on the same network")
|
||||
|
||||
icon.source: "qrc:/images/controls/monitor.svg"
|
||||
|
||||
enabled: !root.isRestoringBackup
|
||||
|
||||
onClicked: PageController.goToPage(PageEnum.PageSetupWizardReceiveFromPhone)
|
||||
}
|
||||
|
||||
BasicCardType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 12
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
|
||||
import Style 1.0
|
||||
|
||||
import "./"
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
import "../Components"
|
||||
|
||||
PageType {
|
||||
id: root
|
||||
|
||||
property bool isPackageReceived: false
|
||||
|
||||
function restartAfterFailedImport() {
|
||||
if (root.isPackageReceived) {
|
||||
root.isPackageReceived = false
|
||||
DeviceTransferController.startReceiving()
|
||||
}
|
||||
}
|
||||
|
||||
Component.onCompleted: DeviceTransferController.startReceiving()
|
||||
Component.onDestruction: DeviceTransferController.stopReceiving()
|
||||
|
||||
Connections {
|
||||
target: DeviceTransferController
|
||||
|
||||
function onPackageReceived() {
|
||||
root.isPackageReceived = true
|
||||
}
|
||||
|
||||
function onErrorOccurred(errorCode) {
|
||||
PageController.showErrorMessage(errorCode)
|
||||
root.restartAfterFailedImport()
|
||||
}
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: ImportController
|
||||
|
||||
function onImportFinished() {
|
||||
PageController.goToPageHome()
|
||||
}
|
||||
|
||||
function onImportErrorOccurred(error, goToPageHome) {
|
||||
root.restartAfterFailedImport()
|
||||
}
|
||||
}
|
||||
|
||||
FlickableType {
|
||||
id: flickable
|
||||
|
||||
anchors.fill: parent
|
||||
|
||||
contentHeight: content.implicitHeight + 24 + PageController.safeAreaBottomMargin
|
||||
|
||||
ColumnLayout {
|
||||
id: content
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
|
||||
spacing: 0
|
||||
|
||||
NavigationBarType {
|
||||
Layout.fillWidth: true
|
||||
|
||||
title: qsTr("Receive from phone")
|
||||
}
|
||||
|
||||
QrCodeCard {
|
||||
Layout.fillWidth: true
|
||||
Layout.maximumWidth: 360
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
Layout.topMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
visible: DeviceTransferController.receiveQrCode !== ""
|
||||
|
||||
source: DeviceTransferController.receiveQrCode
|
||||
}
|
||||
|
||||
BodyTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 24
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
text: qsTr("1. Connect your phone to the same network as this device\n2. On your phone, open the server settings and tap “Send to device”\n3. Point the camera at this code")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<file>Components/CascadeSettings.qml</file>
|
||||
<file>Components/ConfigContentSheet.qml</file>
|
||||
<file>Components/QrCodeCard.qml</file>
|
||||
<file>Components/SendToDeviceListItem.qml</file>
|
||||
<file>Components/ShareClientInfoSheet.qml</file>
|
||||
<file>Components/CountryListItem.qml</file>
|
||||
<file>Components/FavoriteButton.qml</file>
|
||||
@@ -174,6 +175,7 @@
|
||||
<file>Pages2/PageSetupWizardProtocols.qml</file>
|
||||
<file>Pages2/PageSetupWizardProtocolSettings.qml</file>
|
||||
<file>Pages2/PageSetupWizardQrReader.qml</file>
|
||||
<file>Pages2/PageSetupWizardReceiveFromPhone.qml</file>
|
||||
<file>Pages2/PageSetupWizardStart.qml</file>
|
||||
<file>Pages2/PageSetupWizardTextKey.qml</file>
|
||||
<file>Pages2/PageSetupWizardViewConfig.qml</file>
|
||||
@@ -191,6 +193,7 @@
|
||||
<file>Pages2/PageSettingsApiDevices.qml</file>
|
||||
<file>Components/AwgTextField.qml</file>
|
||||
<file>Pages2/PageSettingsApiSubscriptionKey.qml</file>
|
||||
<file>Pages2/PageSendToDeviceConfirm.qml</file>
|
||||
<file>Components/SmartScroll.qml</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -93,6 +93,9 @@ namespace PageLoader
|
||||
PageSettingsLanguage,
|
||||
|
||||
PageUpdate,
|
||||
|
||||
PageSetupWizardReceiveFromPhone,
|
||||
PageSendToDeviceConfirm,
|
||||
};
|
||||
Q_ENUM_NS(PageEnum)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <QDebug>
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/kdf.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/rand.h>
|
||||
|
||||
@@ -13,6 +14,8 @@ namespace
|
||||
constexpr int kAesKeySize = 32; // AES-256
|
||||
constexpr int kAesIvSize = 16; // CBC block size
|
||||
constexpr int kAesBlockSize = 16;
|
||||
constexpr int kX25519KeySize = 32;
|
||||
constexpr int kGcmTagSize = 16;
|
||||
|
||||
QByteArray lastOpenSslError()
|
||||
{
|
||||
@@ -178,3 +181,216 @@ QByteArray CryptoUtils::rsaEncrypt(const QByteArray &data, EVP_PKEY *publicKey,
|
||||
cipherText.resize(static_cast<int>(cipherTextLength));
|
||||
return cipherText;
|
||||
}
|
||||
|
||||
bool CryptoUtils::generateX25519KeyPair(QByteArray &privateKey, QByteArray &publicKey)
|
||||
{
|
||||
std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx { EVP_PKEY_CTX_new_id(EVP_PKEY_X25519, nullptr),
|
||||
EVP_PKEY_CTX_free };
|
||||
EVP_PKEY *rawKey = nullptr;
|
||||
if (!ctx || EVP_PKEY_keygen_init(ctx.get()) != 1 || EVP_PKEY_keygen(ctx.get(), &rawKey) != 1) {
|
||||
qCritical() << "CryptoUtils::generateX25519KeyPair keygen failed:" << lastOpenSslError();
|
||||
return false;
|
||||
}
|
||||
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key { rawKey, EVP_PKEY_free };
|
||||
|
||||
privateKey = QByteArray(kX25519KeySize, Qt::Uninitialized);
|
||||
publicKey = QByteArray(kX25519KeySize, Qt::Uninitialized);
|
||||
std::size_t privateKeyLength = kX25519KeySize;
|
||||
std::size_t publicKeyLength = kX25519KeySize;
|
||||
if (EVP_PKEY_get_raw_private_key(key.get(), reinterpret_cast<unsigned char *>(privateKey.data()), &privateKeyLength)
|
||||
!= 1
|
||||
|| EVP_PKEY_get_raw_public_key(key.get(), reinterpret_cast<unsigned char *>(publicKey.data()), &publicKeyLength)
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::generateX25519KeyPair raw key export failed:" << lastOpenSslError();
|
||||
privateKey.clear();
|
||||
publicKey.clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray CryptoUtils::x25519SharedSecret(const QByteArray &privateKey, const QByteArray &peerPublicKey)
|
||||
{
|
||||
if (privateKey.size() != kX25519KeySize || peerPublicKey.size() != kX25519KeySize) {
|
||||
qCritical() << "CryptoUtils::x25519SharedSecret invalid key size" << privateKey.size() << peerPublicKey.size();
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> ownKey {
|
||||
EVP_PKEY_new_raw_private_key(EVP_PKEY_X25519, nullptr,
|
||||
reinterpret_cast<const unsigned char *>(privateKey.constData()), privateKey.size()),
|
||||
EVP_PKEY_free
|
||||
};
|
||||
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> peerKey {
|
||||
EVP_PKEY_new_raw_public_key(EVP_PKEY_X25519, nullptr,
|
||||
reinterpret_cast<const unsigned char *>(peerPublicKey.constData()),
|
||||
peerPublicKey.size()),
|
||||
EVP_PKEY_free
|
||||
};
|
||||
if (!ownKey || !peerKey) {
|
||||
qCritical() << "CryptoUtils::x25519SharedSecret key load failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx { EVP_PKEY_CTX_new(ownKey.get(), nullptr),
|
||||
EVP_PKEY_CTX_free };
|
||||
if (!ctx || EVP_PKEY_derive_init(ctx.get()) != 1 || EVP_PKEY_derive_set_peer(ctx.get(), peerKey.get()) != 1) {
|
||||
qCritical() << "CryptoUtils::x25519SharedSecret derive init failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
std::size_t secretLength = 0;
|
||||
if (EVP_PKEY_derive(ctx.get(), nullptr, &secretLength) != 1) {
|
||||
qCritical() << "CryptoUtils::x25519SharedSecret couldn't determine secret length:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray secret(static_cast<int>(secretLength), Qt::Uninitialized);
|
||||
if (EVP_PKEY_derive(ctx.get(), reinterpret_cast<unsigned char *>(secret.data()), &secretLength) != 1) {
|
||||
qCritical() << "CryptoUtils::x25519SharedSecret derive failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
secret.resize(static_cast<int>(secretLength));
|
||||
return secret;
|
||||
}
|
||||
|
||||
QByteArray CryptoUtils::hkdfSha256(const QByteArray &secret, const QByteArray &salt, const QByteArray &info, int length)
|
||||
{
|
||||
if (secret.isEmpty() || length <= 0) {
|
||||
qCritical() << "CryptoUtils::hkdfSha256 invalid input" << secret.size() << length;
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx { EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr),
|
||||
EVP_PKEY_CTX_free };
|
||||
if (!ctx || EVP_PKEY_derive_init(ctx.get()) != 1 || EVP_PKEY_CTX_set_hkdf_md(ctx.get(), EVP_sha256()) != 1
|
||||
|| EVP_PKEY_CTX_set1_hkdf_salt(ctx.get(), reinterpret_cast<const unsigned char *>(salt.constData()), salt.size())
|
||||
!= 1
|
||||
|| EVP_PKEY_CTX_set1_hkdf_key(ctx.get(), reinterpret_cast<const unsigned char *>(secret.constData()),
|
||||
secret.size())
|
||||
!= 1
|
||||
|| EVP_PKEY_CTX_add1_hkdf_info(ctx.get(), reinterpret_cast<const unsigned char *>(info.constData()), info.size())
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::hkdfSha256 setup failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray output(length, Qt::Uninitialized);
|
||||
std::size_t outputLength = static_cast<std::size_t>(length);
|
||||
if (EVP_PKEY_derive(ctx.get(), reinterpret_cast<unsigned char *>(output.data()), &outputLength) != 1) {
|
||||
qCritical() << "CryptoUtils::hkdfSha256 derive failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
QByteArray CryptoUtils::encryptAes256Gcm(const QByteArray &data, const QByteArray &key, const QByteArray &nonce,
|
||||
const QByteArray &aad)
|
||||
{
|
||||
if (key.size() != kAesKeySize || nonce.isEmpty()) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm invalid key/nonce size" << key.size() << nonce.size();
|
||||
return {};
|
||||
}
|
||||
|
||||
std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> ctx { EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free };
|
||||
if (!ctx || EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr, nullptr, nullptr) != 1
|
||||
|| EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, nonce.size(), nullptr) != 1
|
||||
|| EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, reinterpret_cast<const unsigned char *>(key.constData()),
|
||||
reinterpret_cast<const unsigned char *>(nonce.constData()))
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm init failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
int length = 0;
|
||||
if (!aad.isEmpty()
|
||||
&& EVP_EncryptUpdate(ctx.get(), nullptr, &length, reinterpret_cast<const unsigned char *>(aad.constData()),
|
||||
aad.size())
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm aad failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray cipherText(data.size() + kGcmTagSize, Qt::Uninitialized);
|
||||
if (EVP_EncryptUpdate(ctx.get(), reinterpret_cast<unsigned char *>(cipherText.data()), &length,
|
||||
reinterpret_cast<const unsigned char *>(data.constData()), data.size())
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm EVP_EncryptUpdate failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
int cipherTextLength = length;
|
||||
|
||||
if (EVP_EncryptFinal_ex(ctx.get(), reinterpret_cast<unsigned char *>(cipherText.data()) + cipherTextLength, &length)
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm EVP_EncryptFinal_ex failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
cipherTextLength += length;
|
||||
|
||||
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kGcmTagSize, cipherText.data() + cipherTextLength) != 1) {
|
||||
qCritical() << "CryptoUtils::encryptAes256Gcm get tag failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
cipherText.resize(cipherTextLength + kGcmTagSize);
|
||||
return cipherText;
|
||||
}
|
||||
|
||||
QByteArray CryptoUtils::decryptAes256Gcm(const QByteArray &data, const QByteArray &key, const QByteArray &nonce,
|
||||
const QByteArray &aad)
|
||||
{
|
||||
if (key.size() != kAesKeySize || nonce.isEmpty() || data.size() < kGcmTagSize) {
|
||||
qWarning() << "CryptoUtils::decryptAes256Gcm invalid key/nonce/data size" << key.size() << nonce.size()
|
||||
<< data.size();
|
||||
return {};
|
||||
}
|
||||
|
||||
const QByteArray cipherText = data.left(data.size() - kGcmTagSize);
|
||||
QByteArray tag = data.right(kGcmTagSize);
|
||||
|
||||
std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> ctx { EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free };
|
||||
if (!ctx || EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr, nullptr, nullptr) != 1
|
||||
|| EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, nonce.size(), nullptr) != 1
|
||||
|| EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, reinterpret_cast<const unsigned char *>(key.constData()),
|
||||
reinterpret_cast<const unsigned char *>(nonce.constData()))
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::decryptAes256Gcm init failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
int length = 0;
|
||||
if (!aad.isEmpty()
|
||||
&& EVP_DecryptUpdate(ctx.get(), nullptr, &length, reinterpret_cast<const unsigned char *>(aad.constData()),
|
||||
aad.size())
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::decryptAes256Gcm aad failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray plainText(cipherText.size() + kAesBlockSize, Qt::Uninitialized);
|
||||
if (EVP_DecryptUpdate(ctx.get(), reinterpret_cast<unsigned char *>(plainText.data()), &length,
|
||||
reinterpret_cast<const unsigned char *>(cipherText.constData()), cipherText.size())
|
||||
!= 1) {
|
||||
qCritical() << "CryptoUtils::decryptAes256Gcm EVP_DecryptUpdate failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
int plainTextLength = length;
|
||||
|
||||
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagSize, tag.data()) != 1) {
|
||||
qCritical() << "CryptoUtils::decryptAes256Gcm set tag failed:" << lastOpenSslError();
|
||||
return {};
|
||||
}
|
||||
|
||||
if (EVP_DecryptFinal_ex(ctx.get(), reinterpret_cast<unsigned char *>(plainText.data()) + plainTextLength, &length)
|
||||
!= 1) {
|
||||
qWarning() << "CryptoUtils::decryptAes256Gcm authentication failed";
|
||||
return {};
|
||||
}
|
||||
plainTextLength += length;
|
||||
|
||||
plainText.resize(plainTextLength);
|
||||
return plainText;
|
||||
}
|
||||
@@ -30,6 +30,14 @@ namespace CryptoUtils
|
||||
|
||||
// RSA encryption with the given OpenSSL padding (e.g. RSA_PKCS1_PADDING).
|
||||
QByteArray rsaEncrypt(const QByteArray &data, EVP_PKEY *publicKey, int padding);
|
||||
|
||||
bool generateX25519KeyPair(QByteArray &privateKey, QByteArray &publicKey);
|
||||
QByteArray x25519SharedSecret(const QByteArray &privateKey, const QByteArray &peerPublicKey);
|
||||
QByteArray hkdfSha256(const QByteArray &secret, const QByteArray &salt, const QByteArray &info, int length);
|
||||
QByteArray encryptAes256Gcm(const QByteArray &data, const QByteArray &key, const QByteArray &nonce,
|
||||
const QByteArray &aad);
|
||||
QByteArray decryptAes256Gcm(const QByteArray &data, const QByteArray &key, const QByteArray &nonce,
|
||||
const QByteArray &aad);
|
||||
}
|
||||
|
||||
#endif // CRYPTOUTILS_H
|
||||
Reference in new issue
Block a user