1package com.peachpasswords.sync23import android.app.Notification4import android.app.NotificationChannel5import android.app.NotificationManager6import android.app.PendingIntent7import android.app.Service8import android.content.BroadcastReceiver9import android.content.Context10import android.content.Intent11import android.os.Build12import android.os.IBinder13import androidx.core.app.NotificationCompat14import com.peachpasswords.MainActivity15import com.peachpasswords.R16import dagger.hilt.EntryPoint17import dagger.hilt.InstallIn18import dagger.hilt.android.AndroidEntryPoint19import dagger.hilt.android.EntryPointAccessors20import dagger.hilt.components.SingletonComponent21import com.peachpasswords.vault.VaultCrypto22import com.peachpasswords.vault.VaultRepository23import kotlinx.coroutines.CancellationException24import kotlinx.coroutines.CoroutineScope25import kotlinx.coroutines.SupervisorJob26import kotlinx.coroutines.cancel27import kotlinx.coroutines.launch28import java.security.MessageDigest29import javax.inject.Inject3031323334353637383940@AndroidEntryPoint41class PeachSyncService : Service() {4243 @Inject lateinit var cloudRelayListener: CloudRelayReconnectListener44 @Inject lateinit var vault: VaultRepository45 @Inject lateinit var deviceStore: PairedDeviceStore46 @Inject lateinit var pendingVouchedStore: PendingVouchedDeviceStore47 @Inject lateinit var syncAlertStore: SyncAlertStore48 @Inject lateinit var syncOutcomes: SyncOutcomeStore49 @Inject lateinit var lockedSyncSpool: LockedSyncSpoolStore50 @Inject lateinit var syncGeneration: SyncGenerationStore5152 private val scope = CoroutineScope(SupervisorJob())5354 override fun onBind(intent: Intent?): IBinder? = null5556 57585960 private fun syncRefusal(): SyncOutcomeSummary? =61 syncRefusalReason(syncGeneration, System.currentTimeMillis())62 ?.let { SyncOutcomeSummary(reason = it) }6364 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {65 66 67 if (vault.isUnlocked.value && vault.syncVaultId() == null) {68 stopSelf()69 return START_NOT_STICKY70 }71 72 73 74 75 76 77 if (!startOrReportBlocked(syncOutcomes::report) {78 startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))79 }80 ) {81 stopSelf()82 return START_NOT_STICKY83 }84 if (vault.isUnlocked.value) {85 scope.launch { runCatching { lockedSyncSpool.drainInto(vault) } }86 }87 val listenerStarted = startReconnectListener()88 89 90 91 92 93 94 95 cloudRelayListener.requestReconcile(96 refreshExisting = shouldRefreshExistingWaiters(listenerStarted),97 )98 99 100 101 return START_STICKY102 }103104 override fun onDestroy() {105 cloudRelayListener.stop()106 scope.cancel()107 super.onDestroy()108 }109110 111 private fun startReconnectListener(): Boolean {112 val master = vault.syncMasterKey()113 var credentials: ReconnectListenerCredentials? = null114 return try {115 credentials = if (master != null) {116 lockedSyncSpool.refresh(vault)117 deriveUnlockedListenerCredentials(118 credentials = loadOrCreateLocalIdentity(this),119 deviceName = getDeviceName(this),120 relayUrl = RelaySettingsStore.readRelayUrl(this),121 )122 } else {123 lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }124 ?: return false125 }126 cloudRelayListener.start(127 scope,128 credentials.keys.secretKey,129 credentials.keys.publicKey,130 credentials.identity,131 ) {132 133 134 135 when {136 vault.syncVaultId() == null -> throw CancellationException("decoy session")137 138 139 140 141 else -> syncRefusal()?.let { refusal ->142 syncOutcomes.report(refusal)143 null144 } ?: if (!vault.isUnlocked.value) {145 lockedSyncSpool.adapter()146 } else {147 val credentials = loadOrCreateLocalIdentity(this)148 VaultSyncAdapter(149 repo = vault,150 ourDeviceId = credentials.deviceId,151 pairedDevices = deviceStore,152 pendingVouched = pendingVouchedStore,153 syncAlerts = syncAlertStore,154 localCredentials = credentials,155 )156 }157 }158 }159 } finally {160 master?.let(VaultCrypto::zero)161 credentials?.keys?.secretKey?.let(VaultCrypto::zero)162 }163 }164165 companion object {166 fun start(context: Context) {167 val intent = Intent(context, PeachSyncService::class.java)168 startOrReportBlocked({ context.reportSyncOutcome(it) }) {169 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {170 context.startForegroundService(intent)171 } else {172 context.startService(intent)173 }174 }175 }176177 fun stop(context: Context) {178 context.stopService(Intent(context, PeachSyncService::class.java))179 }180 }181}182183internal data class ReconnectListenerCredentials(184 val keys: SyncIdentityKeypair,185 val identity: LocalDeviceIdentity,186)187188internal fun deriveUnlockedListenerCredentials(189 credentials: LocalIdentityCredentials,190 deviceName: String,191 relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,192): ReconnectListenerCredentials {193 val keys = localSyncKeypair(credentials)194 val identity = LocalDeviceIdentity(195 deviceId = credentials.deviceId,196 deviceName = deviceName,197 deviceType = DeviceType.ANDROID,198 longTermPublicKeyHex = pubkeyToHex(keys.publicKey),199 signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),200 relayUrl = relayUrl,201 )202 return ReconnectListenerCredentials(keys, identity)203}204205internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted206207internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"208internal const val SYNC_NOTIFICATION_ID = 4201209internal const val ACTION_RESTORE_SYNC_NOTIFICATION =210 "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"211212internal fun buildSyncNotification(context: Context): Notification {213 val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager214 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {215 manager.createNotificationChannel(216 NotificationChannel(217 SYNC_NOTIFICATION_CHANNEL_ID,218 "Peach sync",219 NotificationManager.IMPORTANCE_LOW,220 ).apply {221 description = "Shown while Peach is reachable for encrypted device sync."222 setShowBadge(false)223 },224 )225 }226 val open = PendingIntent.getActivity(227 context,228 0,229 Intent(context, MainActivity::class.java),230 PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,231 )232 val restore = PendingIntent.getBroadcast(233 context,234 0,235 Intent(context, SyncNotificationDismissedReceiver::class.java)236 .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),237 PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,238 )239 return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)240 .setContentTitle("Peach sync is active")241 .setContentText("Your other devices can reach this phone for encrypted sync.")242 .setSmallIcon(R.drawable.ic_launcher_monochrome)243 .setOngoing(true)244 .setPriority(NotificationCompat.PRIORITY_LOW)245 .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)246 .setContentIntent(open)247 .setDeleteIntent(restore)248 .build()249 .also {250 251 252 253 254 it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR255 }256}257258internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =259 action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled260261262263264265266267class SyncNotificationDismissedReceiver : BroadcastReceiver() {268 override fun onReceive(context: Context, intent: Intent?) {269 if (!shouldRestoreSyncNotification(270 intent?.action,271 BackgroundSyncPreference.isEnabled(context),272 )273 ) {274 return275 }276 val manager =277 context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager278 manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))279 }280}281282283284285286287288289290291292293294internal fun startOrReportBlocked(295 report: (SyncOutcomeSummary) -> Unit,296 start: () -> Unit,297): Boolean = try {298 start()299 true300} catch (blocked: IllegalStateException) {301 report(302 SyncOutcomeSummary(303 reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,304 detail = blocked.message,305 ),306 )307 false308} catch (error: Exception) {309 310 311 report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))312 false313}314315316317318319320321private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {322 runCatching {323 EntryPointAccessors324 .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)325 .syncOutcomes()326 .report(summary)327 }328}329330@EntryPoint331@InstallIn(SingletonComponent::class)332internal interface SyncOutcomeEntryPoint {333 fun syncOutcomes(): SyncOutcomeStore334}