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: LockedSyncSpoolStore5051 private val scope = CoroutineScope(SupervisorJob())5253 override fun onBind(intent: Intent?): IBinder? = null5455 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {56 57 58 if (vault.isUnlocked.value && vault.syncVaultId() == null) {59 stopSelf()60 return START_NOT_STICKY61 }62 63 64 65 66 67 68 if (!startOrReportBlocked(syncOutcomes::report) {69 startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))70 }71 ) {72 stopSelf()73 return START_NOT_STICKY74 }75 if (vault.isUnlocked.value) {76 scope.launch { runCatching { lockedSyncSpool.drainInto(vault) } }77 }78 val listenerStarted = startReconnectListener()79 80 81 82 83 84 85 86 cloudRelayListener.requestReconcile(87 refreshExisting = shouldRefreshExistingWaiters(listenerStarted),88 )89 90 91 92 return START_STICKY93 }9495 override fun onDestroy() {96 cloudRelayListener.stop()97 scope.cancel()98 super.onDestroy()99 }100101 102 private fun startReconnectListener(): Boolean {103 val master = vault.syncMasterKey()104 var credentials: ReconnectListenerCredentials? = null105 return try {106 credentials = if (master != null) {107 lockedSyncSpool.refresh(vault)108 deriveUnlockedListenerCredentials(109 credentials = loadOrCreateLocalIdentity(this),110 deviceName = getDeviceName(this),111 relayUrl = RelaySettingsStore.readRelayUrl(this),112 )113 } else {114 lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }115 ?: return false116 }117 cloudRelayListener.start(118 scope,119 credentials.keys.secretKey,120 credentials.keys.publicKey,121 credentials.identity,122 ) {123 124 125 126 when {127 vault.syncVaultId() == null -> throw CancellationException("decoy session")128 !vault.isUnlocked.value -> lockedSyncSpool.adapter()129 else -> {130 val credentials = loadOrCreateLocalIdentity(this)131 VaultSyncAdapter(132 repo = vault,133 ourDeviceId = credentials.deviceId,134 pairedDevices = deviceStore,135 pendingVouched = pendingVouchedStore,136 syncAlerts = syncAlertStore,137 localCredentials = credentials,138 )139 }140 }141 }142 } finally {143 master?.let(VaultCrypto::zero)144 credentials?.keys?.secretKey?.let(VaultCrypto::zero)145 }146 }147148 companion object {149 fun start(context: Context) {150 val intent = Intent(context, PeachSyncService::class.java)151 startOrReportBlocked({ context.reportSyncOutcome(it) }) {152 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {153 context.startForegroundService(intent)154 } else {155 context.startService(intent)156 }157 }158 }159160 fun stop(context: Context) {161 context.stopService(Intent(context, PeachSyncService::class.java))162 }163 }164}165166internal data class ReconnectListenerCredentials(167 val keys: SyncIdentityKeypair,168 val identity: LocalDeviceIdentity,169)170171internal fun deriveUnlockedListenerCredentials(172 credentials: LocalIdentityCredentials,173 deviceName: String,174 relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,175): ReconnectListenerCredentials {176 val keys = localSyncKeypair(credentials)177 val identity = LocalDeviceIdentity(178 deviceId = credentials.deviceId,179 deviceName = deviceName,180 deviceType = DeviceType.ANDROID,181 longTermPublicKeyHex = pubkeyToHex(keys.publicKey),182 signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),183 relayUrl = relayUrl,184 )185 return ReconnectListenerCredentials(keys, identity)186}187188internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted189190internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"191internal const val SYNC_NOTIFICATION_ID = 4201192internal const val ACTION_RESTORE_SYNC_NOTIFICATION =193 "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"194195internal fun buildSyncNotification(context: Context): Notification {196 val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager197 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {198 manager.createNotificationChannel(199 NotificationChannel(200 SYNC_NOTIFICATION_CHANNEL_ID,201 "Peach sync",202 NotificationManager.IMPORTANCE_LOW,203 ).apply {204 description = "Shown while Peach is reachable for encrypted device sync."205 setShowBadge(false)206 },207 )208 }209 val open = PendingIntent.getActivity(210 context,211 0,212 Intent(context, MainActivity::class.java),213 PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,214 )215 val restore = PendingIntent.getBroadcast(216 context,217 0,218 Intent(context, SyncNotificationDismissedReceiver::class.java)219 .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),220 PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,221 )222 return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)223 .setContentTitle("Peach sync is active")224 .setContentText("Your other devices can reach this phone for encrypted sync.")225 .setSmallIcon(R.drawable.ic_launcher_monochrome)226 .setOngoing(true)227 .setPriority(NotificationCompat.PRIORITY_LOW)228 .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)229 .setContentIntent(open)230 .setDeleteIntent(restore)231 .build()232 .also {233 234 235 236 237 it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR238 }239}240241internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =242 action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled243244245246247248249250class SyncNotificationDismissedReceiver : BroadcastReceiver() {251 override fun onReceive(context: Context, intent: Intent?) {252 if (!shouldRestoreSyncNotification(253 intent?.action,254 BackgroundSyncPreference.isEnabled(context),255 )256 ) {257 return258 }259 val manager =260 context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager261 manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))262 }263}264265266267268269270271272273274275276277internal fun startOrReportBlocked(278 report: (SyncOutcomeSummary) -> Unit,279 start: () -> Unit,280): Boolean = try {281 start()282 true283} catch (blocked: IllegalStateException) {284 report(285 SyncOutcomeSummary(286 reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,287 detail = blocked.message,288 ),289 )290 false291} catch (error: Exception) {292 293 294 report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))295 false296}297298299300301302303304private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {305 runCatching {306 EntryPointAccessors307 .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)308 .syncOutcomes()309 .report(summary)310 }311}312313@EntryPoint314@InstallIn(SingletonComponent::class)315internal interface SyncOutcomeEntryPoint {316 fun syncOutcomes(): SyncOutcomeStore317}