<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <title>Churan&apos;s Blog</title>
  <subtitle>Welcome to Churan&apos;s blog</subtitle>
  <link href="https://www.churan.online/" rel="alternate" type="text/html"/>
  <link href="https://www.churan.online/atom.xml" rel="self" type="application/atom+xml"/>
  <id>https://www.churan.online/</id>
  <updated>2026-11-14T00:00:00.000Z</updated>
  <entry>
    <title>zako3.19 update instructions: two real root causes of wireless debugging pairing/activation</title>
    <link href="https://www.churan.online/en/posts/zako319/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/zako319/</id>
    <published>2026-11-14T00:00:00.000Z</published>
    <updated>2026-11-14T00:00:00.000Z</updated>
    <summary></summary>
    <content type="html"><![CDATA[<p><code>zako3.19</code> only does one main thing: <strong>really repair the activation link of "wireless debugging"</strong>.</p>
<p>Starting from zako3.16, users have been reporting the same phenomenon: <strong>Root can be activated normally, but wireless debugging cannot</strong>. After entering the pairing code, it is either stuck at "Unable to connect to the wireless debugging service", or the pairing is successful but the service cannot be started. In this version, both root causes were dug out and repaired, and this time it was not based on guesswork - the entire link was run through in the Android virtual machine, and every step was documented with logs.</p>
<h2>0. What has been changed in this version?</h2>
<table>
<thead>
<tr>
<th>Category</th>
<th>Content</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fix</td>
<td>Pairing connection port masked as <code>0</code> by Kotlin receiver, connecting every time to <code>127.0.0.1:0</code></td>
</tr>
<tr>
<td>Fix</td>
<td>The service subprocess was killed by adbd's <code>SIGHUP</code> between <code>fork()</code> and <code>setsid()</code>, resulting in "pairing successful but service cannot start"</td>
</tr>
<tr>
<td>Fix</td>
<td>The old service process cleanup logic never takes effect (<code>--nice-name</code> rewrites cmdline into a nickname), and two <code>shizako_server</code> may appear after the upgrade</td>
</tr>
<tr>
<td>Optimization</td>
<td>Changed to "Start the service on the available port first, and then try to switch to TCP 5555", switching failure will no longer block activation</td>
</tr>
<tr>
<td>Optimization</td>
<td>When the paired port expires, it automatically switches to the latest mDNS port and retries; mDNS discovery window 3s → 6s; LAN cover is changed to all non-loopback IPv4</td>
</tr>
<tr>
<td>Remove</td>
<td>Home page "Diagnostic Log" test function (only appears in <code>-PlogBuild</code> troubleshooting package), source code and release package no longer include</td>
</tr>
<tr>
<td>Version</td>
<td><code>versionCode 319</code> / <code>zako3.19</code>, signature fingerprint remains unchanged</td>
</tr>
</tbody>
</table>
<h2>1. First explain why the two activation paths behave differently.</h2>
<p>The root activation method is <code>su -c</code>: after getting the root, directly use <code>app_process</code> to start the service without going through any ADB link.</p>
<p>Wireless debugging activation is a completely different link:</p>
<ol>
<li>The system "Wireless Debugging" is turned on, and <code>adbd</code> monitors the pairing service on a random port (<code>_adb-tls-pairing._tcp</code>);</li>
<li>The App uses the 6-digit pairing code to perform TLS + SPAKE2 pairing with adbd (native layer <code>adb_pairing.cpp</code>);</li>
<li>After successful pairing, the App executes the command through the <code>shell:</code> service and pulls up <code>libshizuku.so</code> as a service.</li>
</ol>
<p>**Root will not touch any step in 1, 2, and 3. ** So as long as the bug occurs in these three steps, the phenomenon must be "Root works, but wireless debugging does not work." The two root causes found this time happened to be one in step 2 and one in step 3.</p>
<h2>2. Root cause 1: <code>Socket.apply</code> swallowed the paired port into <code>0</code></h2>
<p>In the paired client <code>AdbPairingClient</code>, establishing a TLS connection was originally written like this (changed from <code>Socket(host, port)</code> in order to add connection timeout):</p>
<pre><code>socket = java.net.Socket().apply {
    tcpNoDelay = true
    connect(java.net.InetSocketAddress(host, port), CONNECT_TIMEOUT_MS)
}
</code></pre>
<p>It looks like <code>port</code> is the field used to construct <code>InetSocketAddress</code>. In fact - the <strong>receiver of <code>apply</code> is <code>Socket</code></strong>, and <code>Socket</code> has one of its own <code>getPort()</code> (always <code>0</code> when not connected). In Kotlin's implicit receiver priority, the closer <code>Socket.getPort()</code> will cover the class field <code>port</code>. So what each pairing actually performs is:</p>
<pre><code>connect(InetSocketAddress(host, 0), timeout)
</code></pre>
<p>The field log looks like this (before repair):</p>
<pre><code>AdbPairClient: pairing start: hosts=[127.0.0.1, 10.0.2.16, 10.0.2.15] port=34939
AdbPairClient: tcp connect -&gt; 127.0.0.1:0
AdbPairClient: tcp connect -&gt; 10.0.2.16:0
AdbPairClient: tcp connect -&gt; 10.0.2.15:0
java.net.ConnectException: failed to connect to /127.0.0.1 (port 0) ... ECONNREFUSED
</code></pre>
<p>The pairing service is alive and the mDNS port is correct, but the client always tries to connect to port 0 - which of course fails every time. What the user sees is "Unable to connect to the wireless debugging service."</p>
<p>The fix is ​​straightforward: first put the port into a local variable, and then connect it outside <code>apply</code> so that the variable name no longer participates in receiver resolution.</p>
<pre><code>val remotePort = port
val address = java.net.InetSocketAddress(host, remotePort)
socket = java.net.Socket().apply { tcpNoDelay = true }
socket.connect(address, CONNECT_TIMEOUT_MS)
</code></pre>
<p>Log after repair:</p>
<pre><code>AdbPairClient: tcp connect -&gt; 127.0.0.1:44047
AdbPairClient: Handshake succeeded via 127.0.0.1:44047
AdbPairingService: Pair succeed
</code></pre>
<p>The lesson of this bug is not a "Kotlin pit", but: <strong>As long as the scope of the variable and the object member have the same name, lambdas with receivers such as <code>apply</code> / <code>run</code> / <code>with</code> may quietly change their pointers</strong>. The compiler will not warn when the construction parameters, member attributes, and receiver members have the same names.</p>
<h2>3. Root cause two: the shot after <code>fork()</code> and before <code>setsid()</code> <code>SIGHUP</code></h2>
<p>After the port was repaired, pairing was successful, but a new phenomenon occurred: <strong>Pairing was successful, but the service could not start</strong>. There are only two lines in logcat:</p>
<pre><code>D/Shizuku ( 3899): start_server
D/Shizuku ( 3900): child
D/Shizuku ( 3900): exec app_process
I/init    (    0): Untracked pid 3608 received signal 1
W/AdbPairingService: Service did not come up after pairing
</code></pre>
<p><code>signal 1</code> is <code>SIGHUP</code>. The problem lies in the startup sequence of <code>starter.cpp</code>:</p>
<ol>
<li><code>fork()</code> exits the service sub-process;</li>
<li>The child process has not had time to <code>setsid()</code>;</li>
<li>At this time, the ADB shell command ends, <code>adbd</code> closes pty, and sends <code>SIGHUP</code> to the <strong>foreground process group</strong>;</li>
<li>The child process happened to fall in that window and was killed by the hang-up signal. It did not even reach <code>exec</code>.</li>
</ol>
<p>Why is the Root path okay? Because <code>su -c</code> does not pass through pty, there will be no such signal.</p>
<p>The fix is ​​only three lines long, but the position is extremely critical - <strong>must come before <code>fork()</code></strong>:</p>
<pre><code>signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);

pid_t pid = fork();
</code></pre>
<p><code>SIG_IGN</code> will be inherited by the child process, and will continue to be valid across <code>exec</code>, so the forked child process is naturally immune to this signal, and the race window is completely filled. After repairing:</p>
<pre><code>D/Shizuku ( 4607): start_server
D/Shizuku ( 4608): child
D/Shizuku ( 4608): exec app_process
info: shizako_server pid is 4608
info: shizako_starter exit with 0
</code></pre>
<p>This lesson is more general: <strong>"setid immediately after fork" is a classic safe zone habit, but signals belong to the type of state that "takes effect immediately after fork"</strong>. Anything that wants to survive between fork and exec must set up signal processing before fork.</p>
<h2>4. Digged out by accident: Cleaning up old service processes has never taken effect.</h2>
<p>When repairing SIGHUP, I checked the logic of "cleaning up old services before starting" and found that it was always a decoration.</p>
<p>The original judgment was "cmdline contains package name + service class name". But the startup parameter of <code>app_process</code> contains <code>--nice-name=shizako_server</code>, <strong>it will rewrite <code>/proc/&lt;pid&gt;/cmdline</code> to only the nickname</strong>. Therefore, the match will never be successful. After the upgrade, two <code>shizako_server</code> may appear trying to register the same binder.</p>
<p>The current judgment is changed to two steps:</p>
<ol>
<li>cmdline is equal to <code>shizako_server</code> → considered to be the service of this application;</li>
<li>If it is equal to the old nickname <code>shizuku_server</code>, read <code>/proc/&lt;pid&gt;/maps</code> again and make sure it contains the name of the application package before proceeding.</li>
</ol>
<p>In this way, you can clear out the old processes left behind before upgrading, and you will not accidentally kill the official Shizuku server.</p>
<h2>5. Remove "optional optimization" from the activation path</h2>
<p>The previous order was "cut <code>tcpip:5555</code> first, and then start the service." However, switching TCP is only for the optimization of "avoiding direct network connection in the future" and should not in turn become a prerequisite for activation - failure to switch (some ROM restrictions, abnormal adbd status) will directly block the entire activation.</p>
<p>Now the order of <code>AdbStarter</code> is:</p>
<ol>
<li>First pull up the service on the <strong>currently available port</strong> given by the caller;</li>
<li>Try your best to switch to fixed TCP 5555;</li>
<li>If the switch fails, only the log will be recorded and the existing services will not be affected.</li>
</ol>
<p>Several other aspects of pairing robustness:</p>
<ul>
<li>Automatically switch to the latest mDNS port and try again when the connection is rejected (paired port expiration is a high-frequency operation);</li>
<li>Split-screen pairing also covers <code>ConnectException</code> (originally only retrying <code>SSLException</code> in the handshake phase);</li>
<li><code>_adb-tls-connect._tcp</code> discovery window relaxed from 3s to 6s;</li>
<li>The LAN IP address has been changed from "First IPv4" to "All non-loopback IPv4, Wi-Fi first", and devices with multiple network cards will no longer pick the wrong network card;</li>
<li>Give a <strong>visible notification</strong> when pairing is successful but the service is not up, instead of just leaving a line in logcat.</li>
</ul>
<h2>6. Remove the "Diagnostic Log" test function on the homepage</h2>
<p>In order to troubleshoot on-site problems before, I added a homepage card that only appears in the <code>-PlogBuild</code> troubleshooting package: logcat is recorded upon startup, and the homepage provides recording switches, exporting, and copying. It is positioned as "temporarily distributed to individual users to troubleshoot problems and will not be released." However, since the root cause of wireless debugging has fallen into specific lines of code, there is no need for this debugging function to remain in the source code.</p>
<p>This version deletes the entire chain:</p>
<ul>
<li><code>diag/DiagLog.kt</code> (recorder), <code>home/DiagLogViewHolder.kt</code> (card), <code>res/layout/home_diag_log.xml</code> (layout);</li>
<li>Card mounting in <code>HomeAdapter</code>, recording on startup in <code>ShizukuApplication</code>;</li>
<li><code>-PlogBuild</code> switch, <code>LOG_BUILD</code> compile-time field, version name <code>-log</code> suffix;</li>
<li>All <code>diag_log_*</code> copywriting in <code>values/</code>, <code>values-b+zh+Hans/</code>, <code>values-b+zh+Hant/</code>.</li>
</ul>
<p>In the future, there will no longer be a situation where "the troubleshooting package contains an extra card", and the source code on GitHub does not include this test code.</p>
<h2>7. How to verify</h2>
<p>The complete process was run on the Android 12 (API 31, x86_64) virtual machine: System "Wireless Debugging" → "Pair the device using the pairing code" → Enter the 6-digit pairing code in the notification bar → Automatic activation.</p>
<p>Key log:</p>
<pre><code>AdbPairClient: tcp connect -&gt; 127.0.0.1:44047
AdbPairClient: Handshake succeeded via 127.0.0.1:44047
AdbPairingService: Pair succeed
AdbClient: A_OPEN ... shell:.../lib/x86_64/libshizuku.so --apk=...
info: shizako_server pid is 4608
info: shizako_starter exit with 0
</code></pre>
<p>Process and status:</p>
<pre><code>$ adb shell ps -A -o USER,PID,PPID,NAME | grep shizako
u0_a105       4303   333 com.churan.shizako
shell         4608     1 shizako_server
</code></pre>
<p>The service runs as <code>shell</code>(2000), and there is only one; 5555 in <code>/proc/net/tcp6</code> has been monitored by adbd; the App activation page status is <strong>Running (adb)</strong>.</p>
<p>In addition, "Start directly after pairing" has returned: after killing the service, click "Start service", you can restart <code>shizako_server</code>, and the interface returns to Running (adb).</p>
<h2>8. Versions and products</h2>
<ul>
<li><code>versionCode 319</code> / <code>versionName zako3.19</code>;</li>
<li>The signature fingerprint remains unchanged: <code>515BAF0C…9F9C8A</code>, which can be directly overwritten and installed;</li>
<li>GitHub Release has attached <code>shizako-zako3.19-release.apk</code> signed with the same key.</li>
</ul>
<h2>9. For those who are also stuck in wireless debugging</h2>
<p>If you are writing something similar, it is recommended to check the sequence according to the link stage. Don’t doubt the certificate at the first glance:</p>
<ol>
<li><strong>Discovery</strong>: Did mDNS resolve <code>_adb-tls-pairing._tcp</code> and the port is correct?</li>
<li><strong>Connect</strong>: Print <code>host:port</code>, confirm it is not <code>0</code>, and it is not an expired port;</li>
<li><strong>Handshake</strong>: Whether SPAKE2 + TLS is successful (failure is usually a pairing code/protocol issue);</li>
<li><strong>Startup</strong>: Whether the process started with <code>shell:</code> after successful pairing is taken away by signal/permission/timing issues.</li>
</ol>
<p>This time the two root causes fall on steps 2 and 4 respectively - and what they have in common is: the root path does not pass through any one. So "root works" never proves that the wireless link is OK.</p>
<p>above. See zako3.19.</p>
]]></content>
    <author><name>Churan</name></author>
    <category term="Open source projects"/>
  </entry>
  <entry>
    <title>zako3.16 update instructions</title>
    <link href="https://www.churan.online/en/posts/zako316/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/zako316/</id>
    <published>2026-10-17T00:00:00.000Z</published>
    <updated>2026-10-17T00:00:00.000Z</updated>
    <summary></summary>
    <content type="html"><![CDATA[<p><code>zako3.16</code> deals with something more troublesome than a bug: <strong>Someone is impersonating me</strong>.</p>
<p>The cause of the matter was that someone in the community reminded me that there were some renamed and repackaged versions of "Shizako+" circulating out there, with messy signatures. Following this clue, the thing that made me shiver the most was not what those people outside had done, but—<strong>my own GitHub version of the APK, which looked a lot like a counterfeit after unpacking</strong>.</p>
<p>This edition is aimed at "complete solution". In addition, the old problem of watchdog "retrying three times and then giving up forever" has also been fixed.</p>
<h2>0. What has been changed in this version?</h2>
<table>
<thead>
<tr>
<th>Category</th>
<th>Content</th>
</tr>
</thead>
<tbody>
<tr>
<td>Governance</td>
<td>GitHub version has stopped issuing the upstream identity placeholder package (an empty sub-package occupying the upstream package name <code>moe.shizuku.privileged.api</code> and the application name "Shizuku")</td>
</tr>
<tr>
<td>Newly added</td>
<td>In-app signature self-test: Compare signature certificate fingerprints at startup, and warn and guide verification if inconsistencies occur (only warns, does not block)</td>
</tr>
<tr>
<td>New</td>
<td>"Settings → About" displays the complete signature fingerprint and verification status of the current installation package, click Copy</td>
</tr>
<tr>
<td>Reinforcement</td>
<td>The watchdog disconnection and reconnection strategy is changed to a three-level strategy: 3 seconds fast retry ×3 → low-frequency recovery every 5 minutes until successful</td>
</tr>
<tr>
<td>Reinforcement</td>
<td>Cold recovery: When the binder is never reported after booting, it will actively detect and start the service according to the last activation method</td>
</tr>
<tr>
<td>Repair</td>
<td>"Stop service" with the keep-alive point enabled, and the service is pulled up by the watchdog after 3 seconds</td>
</tr>
<tr>
<td>Repair</td>
<td>Permanent notifications truthfully display "low-frequency retrying" and "stopped as requested by the owner" and no longer pretend to be on duty</td>
</tr>
</tbody>
</table>
<p>The first three are for anti-counterfeiting, and the last three are for stability. The text is told in this order.</p>
<hr />
<h2>1. Counterfeiting outside and my own problems</h2>
<p>Let’s talk about the external environment first. Shizuku's README on GitHub clearly states: <strong>forks are prohibited from using the "Shizuku" name</strong> (Apache-2.0 §6 Additional Terms). My project has followed the rules from the beginning: I use my own <code>com.churan.shizako</code> for the package name, my own permission name, my own provider authority, and I have never touched the upstream package name and application name.</p>
<p>But after being reminded by the community, I searched around and found that some people are indeed dumping various renamed and repackaged versions on third-party sites, with signatures such as "SILENT KILLER". I have no control over what is on these sites - only the users themselves can verify what they have installed. <strong>What I can do is to make "verification" extremely simple on the user side</strong>: a signature fingerprint that cannot be copied.</p>
<p>What really made me sit still was when the other half discovered: <strong>My own GitHub version of APK has an <code>assets/shizako-stub.apk</code></strong> embedded in it. Unpacking it, the output of <code>aapt2 dump badging</code> is like this:</p>
<pre><code>package: name='moe.shizuku.privileged.api'
application-label: 'Shizuku'
</code></pre>
<p>An empty shell package occupying the <strong>upstream package name</strong> and application name <strong>"Shizuku"</strong> is lying in my own release product. The historical mission of this thing is to please those third-party clients who spell out old package names - but it literally violates the additional terms of upstream Apache-2.0 §6. What's even worse is the <strong>perception</strong>: Anyone who unpacks my official APK and runs <code>aapt2 dump badging</code> will see a sub-package called "Shizuku" with the package name <code>moe.shizuku.privileged.api</code>. From the outside, this is indistinguishable from a counterfeit product that has been downloaded with Shizuko, repackaged and renamed.</p>
<p>I was slapping myself in the face. The F-Droid version has turned it off a long time ago (not including the <code>:stub</code> module + deleting the APK when building), but the GitHub version has always kept it. This is the origin of the first change in this version.</p>
<h2>2. Stop issuing placeholder packages: uproot them</h2>
<p>This is not a matter of deleting a file, you have to unplug the entire chain:</p>
<ul>
<li><strong><code>settings.gradle</code></strong>: Originally include <code>:stub</code> module under <code>-Pfdroid</code> condition. Now any variant no longer builds the stub, the module itself (<code>stub/</code> directory) is deleted entirely;</li>
<li><strong><code>manager/build.gradle</code></strong>: <code>COMPAT_STUB_PACKAGE</code> This BuildConfig field is always an empty string; <code>compatAuthority</code> only retains its own authority <code>com.churan.shizako.shizuku</code>; <code>copyStubApk</code> / <code>removeStubApk</code> two build tasks and the ones hanging on them <code>preBuild</code> Dependencies are deleted together;</li>
<li><strong>Runtime</strong>: <code>StubManager.kt</code> (aggregation logic of three installation channels) is deleted, the stub status display in the laboratory page, and all <code>lab_stub_*</code> strings in <code>strings_lab.xml</code> are deleted;</li>
<li><strong>starter side</strong>: There is a secret in <code>ServiceStarter.java</code> - when the manager package name is empty, it falls back to <code>"moe.shizuku.privileged.api"</code>. All the placeholder packages are gone. This rollback is a landmine. Delete it.</li>
</ul>
<p>After deleting it, I checked: there is no embedded APK in the new APK, all provider authorities are <code>com.churan.shizako.*</code>, and the package name, permissions and label of <code>moe.shizuku</code> can no longer be found in <code>aapt2 dump badging</code>.</p>
<p><strong>Document Synchronization</strong>: All old descriptions of "compatibility bridge / provider authority / cannot coexist" in README, README_EN, NOTICE, and compiled documents have been rewritten, and a new section "Officially built signature fingerprint" has been added.</p>
<h2>3. In-app signature self-check: the dimension that cannot be copied</h2>
<p>After the placeholder package was removed, the second question emerged: **How do users know whether the APK in their hands was sent by me? **</p>
<p>Counterfeiters can copy my interface, my package name, and even my version number - but there is one thing they cannot copy: the private key of the issuing certificate. Signature fingerprints are the only hard obstacle for counterfeiters, because repackaging requires re-signing and the fingerprints must be different. Before that, this fingerprint only lay in my notes, and there was no way to verify it on the user side.</p>
<p>So with <code>security/SignatureGuard.kt</code>, the logic is very straightforward:</p>
<ol>
<li>Read the signature certificate of the current installation package when starting, and calculate SHA-256;</li>
<li>Compare with the officially released fingerprint <code>515BAF0C…9F9C8A</code> (the same one announced in the README, measured and read from the officially released APK using <code>apksigner verify --print-certs</code>);</li>
<li>Inconsistency → Pop-up warning: Show your fingerprint, open the official release page for verification with one click, and copy your own fingerprint for comparison with one click.</li>
</ol>
<p>Several deliberate design decisions:</p>
<ul>
<li><strong>Only warn, not block</strong>. This is my clear choice: false positives (such as a user-signed compilation with a debug certificate) should not brick the software. Warning + guidance verification, returning the right of judgment to users;</li>
<li><strong>F-Droid version does not play</strong>. It is inevitable for F-Droid to re-sign with its own key. The fingerprint must be different from the official one and cannot be predicted within the application - popping a warning against it is like crying wolf. For the F-Droid version, just mark "F-Droid signature" on the about page;</li>
<li><strong>Only play once per process</strong>. Playing it once is enough to explain the problem, there is no need to play it again and again.</li>
</ul>
<p>A new signature fingerprint card is added to the "Settings → About" page: status logo (official signature / F-Droid signature / unconfirmable) + complete 64-bit fingerprint displayed in segments in monospaced font, tap to copy. The user takes the copied string and README as a pair, and it takes three seconds.</p>
<p>To be honest: the deterrent power of this line of defense does not lie in how many counterfeit installation packages it blocks - what really matters is the channels and user habits. Its significance is to reduce the cost of "verifying officialness" to nearly zero, so that everyone who installs my software can confirm for themselves: What I installed is the one issued by the developer.</p>
<h2>4. Watchdog: From "retry three times and then give up" to level three reconnection</h2>
<p>After talking about anti-counterfeiting, let’s talk about stability. The cause of this line was two holes seen when reviewing the keepalive logic.</p>
<p>**Hole 1: Fail three times and give up permanently. ** This is how the watchdog handles service crashes: binder dies → quickly retry after 3 seconds, up to 3 times → do nothing after that and wait for binder to come back on its own. But why does binder come back on his own? Wireless debugging is turned off, adbd is restarted, the service process is frozen - in these scenarios it will never come back on its own. What the user sees is this: the notification says "Crashed 3 times, will try again..." and then spins around forever. The so-called retry means that it will never happen again.</p>
<p>**Hole 2: No one bothered to provide services after the computer was turned on. ** After the phone restarts, the watchdog itself will be pulled up by the alarm clock or the shell watchdog - but at this time the binder ** has never been reported ** and the death callback will not be triggered at all. The entire mechanism of "waiting for the binder to die before rescuing it" in the old logic is completely ineffective in the cold start scenario. The service just sits there, unattended.</p>
<p>Current three-level strategy:</p>
<ol>
<li>
<p><strong>Quick retry</strong>: binder dies → pull up after 3 seconds, try 3 times in a row (retain original behavior);</p>
</li>
<li>
<p><strong>Low frequency recovery</strong>: Failed 3 times → Enter recovery mode, detect and pull up every 5 minutes, <strong>do not exit until successful</strong>. Choosing a frequency of 5 minutes is a compromise between power consumption and response speed - each round of the watchdog requires forking the process and reading <code>/proc</code>, which cannot be as intensive as fast retries;</p>
<blockquote>
<p><strong>Additional note (zako3.16hp)</strong>: This paragraph was accurate when it was published, but it was quickly discovered that there was a hole in it - <strong>If there is no available pull-up method at all</strong> (the last time was wireless debugging activation, 5555 failed, and did not get the permission to automatically turn on wireless debugging), the recovery loop will do nothing but wake up every 5 minutes, and the notification still says "Retrying". The so-called "until success" presupposes "there is a way to go". This point has been fixed in <code>zako3.16hp</code>, please see the supplement at the end of the article for details.</p>
</blockquote>
</li>
<li>
<p><strong>Cold recovery</strong>: When the watchdog itself is pulled up, if it is detected that the service is not running, and has been successfully activated before (mode has been recorded), and the owner has not just manually stopped it - after 5 seconds, press the last activation method (root/adb) to actively pull up. What needs to be filled is the boot hole.</p>
</li>
</ol>
<p>By the way, a more basic bug has been fixed: <strong>When you click "Stop Service" when keep-alive is enabled, the service is pulled up by the watchdog after 3 seconds</strong>. The reason is simple - <code>Shizuku.exit()</code> triggers the binder death callback, and the watchdog treats it as a crash and schedules a restart. The master's clear operation is overturned by his own keep-alive logic, which is a logical contradiction. Now the four stop entrances (homepage status card, homepage dialog box, shortcut tile, Tasker) will all adjust <code>WatchdogService.noteIntentionalStop()</code> first: not only letting go of the following death callback, but also suppressing automatic reconnection for 30 minutes. If the owner still ignores it after 30 minutes, the keep-alive operation will continue - this is in line with the semantics of the word "watchdog".
The notification bar can finally speak human language: two new states are added: "Low-frequency retry for the Nth time" and "Keep stopped as requested by the owner". It no longer displays "Crashed, will try again..." regardless of the actual situation.</p>
<h2>5. Construction and verification</h2>
<ul>
<li>Both GitHub version and F-Droid version double variant <code>assembleRelease</code> passed;</li>
<li>APK in-core verification: complete trilingual copywriting (English/Simplified Chinese/Traditional Chinese), official fingerprint constants in DEX, permission table and package name tags without upstream residue;</li>
<li>Version numbers <code>versionCode 316</code> / <code>zako3.16</code>, update logs, development documents (<code>docs/dev/changelog.html</code> generated by <code>tools/md2html.py</code>) are synchronized.</li>
</ul>
<h2>6. What I want to say</h2>
<p>This project started as a "repackaged and renamed Fork" (the legal one), and now it spends a whole page to make itself look like it can be verified from any angle - identity, signature, fingerprint disclosure, self-examination - in a sense, it is a reincarnation.</p>
<p>To those who have installed this software, I only have one thing to say: <strong>Fingerprint verification only takes three seconds</strong>. Settings → About, click Copy, and compare it with the line <code>515BAF0C…</code> in the GitHub README. Sorry, what you have is not from me. This action is worth making a habit of—not just for me, but for every critical piece of software you install.</p>
<p>When it comes to service and survival, it’s still the same sentence: The meaning of her existence is that you don’t need to worry about her. It will save you when it is dead, and it will come back on its own when it is turned on. If you ask her to stop, she will stop honestly.</p>
<p>above. See zako3.16.</p>
<hr />
<h2>Supplementary note: zako3.16hp</h2>
<p>After the article was published, I went back and reviewed the link between pairing and activation, and came up with two questions, one of which was exactly what I said in Section 4 above - <strong>I said "don't quit until you succeed", but I didn't make it clear "what happens if there is no way out"</strong>.</p>
<ul>
<li><strong>Low frequency recovery will idle</strong>: When wireless debugging was activated last time, 5555 was blocked, and there was no permission to automatically turn on wireless debugging, the recovery logic did nothing, but still woke up every 5 minutes, never waiting for success, and the notification kept showing "Retrying". Now it will stop the clock and truthfully say "Automatic reconnection aborted - please start the service manually (or re-authorize/use Root instead)", with an additional try limit of about 1 hour. <strong>This version fixes "Notice to stop claiming something that cannot be done"</strong>, which is the same problem as the signature self-examination in Section 3: the interface should not speak for the facts.</li>
<li><strong>Pairing leaks resources on every attempt</strong>: The pairing client is closeable, but both call paths never close it. So every pairing attempt - including every failed retry - will miss two file descriptors and a piece of native memory, where a copy of the SPAKE2 key is stored. Retrying on failure is exactly the intended high-frequency operation of the pairing design.</li>
</ul>
<p><code>zako3.16hp</code> Released: <a href="https://github.com/cr1437/Shizako/releases/tag/zako3.16hp">github.com/cr1437/Shizako/releases/tag/zako3.16hp</a>.
<code>versionCode</code> is still 316, only <code>versionName</code> has the <code>hp</code> suffix added, and can directly overwrite and install zako3.16; the signature fingerprint remains unchanged and is still <code>515BAF0C…9F9C8A</code>.</p>
<p>There is one thing worth writing down separately, because it is the most valuable part of this edition: <strong>The two questions above were too superficially looked at by me during the first round of review, and they were discovered only after "checking again"</strong>. The most critical part of the review is not to read the code, but to actually compile the changes - <code>WatchdogService</code>. One <code>import</code> was missed when adding the log, which cannot be seen at all by simply reading the code. In an earlier round, I was almost fooled by Gradle's <code>FROM-CACHE</code>, thinking that "clean and passed" would count as passed.</p>
<p>So in Section 6, I would like to add another sentence to the sentence "Verifying a fingerprint only takes three seconds": **It's worth reading the code again. **</p>
]]></content>
    <author><name>Churan</name></author>
    <category term="Open source projects"/>
  </entry>
  <entry>
    <title>zako3.15 update instructions</title>
    <link href="https://www.churan.online/en/posts/zako315/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/zako315/</id>
    <published>2026-10-16T00:00:00.000Z</published>
    <updated>2026-10-16T00:00:00.000Z</updated>
    <summary></summary>
    <content type="html"><![CDATA[<p><code>zako3.15</code> is the second version I posted today.</p>
<p>The previous <code>zako3.14</code> solves the problem of "no matching service automatically discovered": when mDNS is blocked by the system or VPN, the pairing dialog box only has a circle left, and the port and pairing code input boxes do not appear at all. Just a few hours after that problem was fixed, I received the following feedback.</p>
<h2>0. What has been changed in this version?</h2>
<table>
<thead>
<tr>
<th>Category</th>
<th>Content</th>
</tr>
</thead>
<tbody>
<tr>
<td>Repair</td>
<td>After pairing fails, the interface falsely reports "paired" - the key is changed to <strong>Pairing is successful only</strong></td>
</tr>
<tr>
<td>Fix</td>
<td>There is no prompt when pairing fails - instead a named exception is thrown, distinguishing three reasons for failure</td>
</tr>
<tr>
<td>Fix</td>
<td>When pairing in the notification bar fails to generate a key, it will always stop at "Pairing"</td>
</tr>
<tr>
<td>Repair</td>
<td>Users who upgraded from the old version will automatically rewrite the pairing record without having to re-pair</td>
</tr>
<tr>
<td>Repair</td>
<td>"Forgot pairing" clears the success record at the same time and no longer remains</td>
</tr>
<tr>
<td>i18n</td>
<td>There is a Chinese word "jiang" mixed into the English activation page copy</td>
</tr>
<tr>
<td>Build</td>
<td>F-Droid version no longer declares <code>REQUEST_INSTALL_PACKAGES</code> without any consumer</td>
</tr>
</tbody>
</table>
<p>The first two items are the main text. They all look like "the interface status display is wrong", but the real culprit is one in the key placement timing and the other in the delivery method of the failure information.</p>
<hr />
<h2>1. Report</h2>
<blockquote>
<p>I can't pair with the code. Any idea? And after it failed to pair, it displayed that it has been paired.</p>
</blockquote>
<p>The person who said this is linsui, the maintainer of F-Droid. He is reviewing the MR that I mentioned about F-Droid. There are actually <strong>two independent questions</strong> in this passage:</p>
<ol>
<li><strong>Not a match</strong> - It may be an operational problem (such as filling in the wrong pairing port), or it may be a device compatibility problem;</li>
<li><strong>Pairing failed, but it shows that it has been paired</strong> - There is no excuse for this, it must be my bug.</li>
</ol>
<p>The second one is much more serious than the first. The only basis for the user to judge "whether it can be used" is the status of that line; once the status lies, the user has no feedback available - he does not know what he did wrong, nor does he know whether to try again or change the activation method.</p>
<p>So I started with the second one.</p>
<hr />
<h2>2. Forensic A: Why does a failed pairing leave the key?</h2>
<p>The first step in pairing is to construct <code>AdbKey</code>:</p>
<pre><code>val key = AdbKey(PreferenceAdbKeyStore(ShizukuSettings.getPreferences()), "shizuku")
</code></pre>
<p>And the constructor of <code>AdbKey</code> will be adjusted all the way to <code>getOrCreatePrivateKey()</code>:</p>
<pre><code>private fun getOrCreatePrivateKey(): RSAPrivateKey {
    var privateKey: RSAPrivateKey? = null
    val aad = ByteArray(16)
    "adbkey".toByteArray().copyInto(aad)

    var ciphertext = adbKeyStore.get()
    if (ciphertext != null) {
        // 仓库里已经有密钥：解密后直接复用
        val plaintext = decrypt(ciphertext, aad)
        privateKey = keyFactory.generatePrivate(PKCS8EncodedKeySpec(plaintext)) as RSAPrivateKey
    }
    if (privateKey == null) {
        // 仓库是空的：现在生成一对新密钥，并且**立刻写进仓库**
        val keyPair = keyPairGenerator.generateKeyPair()
        privateKey = keyPair.private as RSAPrivateKey

        ciphertext = encrypt(privateKey.encoded, aad)
        if (ciphertext != null) {
            adbKeyStore.put(ciphertext)      // ← 落盘在这里，而不是在配对成功之后
        }
    }
    return privateKey
}
</code></pre>
<p>The key is the last one <code>put</code>: **The key is placed in the "Constructing Object" step and has nothing to do with whether the pairing is successful. **</p>
<p>The action sequence of pairing is "first construct <code>AdbKey</code> → then connect to the pairing service" - so if the pairing code is entered incorrectly, the port is blocked, the user closes the system dialog box midway, or even the process is killed during the pairing process, a key that <strong>adbd has never seen</strong> will be quietly left locally.</p>
<hr />
<h2>3. Evidence B: The interface shows "the keystore is not empty" as the pairing is successful.</h2>
<p>Let’s look at the judgment end again. The activation page uses this line to determine "whether it has been paired":</p>
<pre><code>/** 本地是否已经存了配对用的 adb 私钥（配对过一次就一直有） */
private fun hasPairingKey(): Boolean =
    PreferenceAdbKeyStore(ShizukuSettings.getPreferences()).get() != null
</code></pre>
<p>The comment says "It is always there after pairing once", but combined with the previous section, we can see that its actual semantics is "<strong>There is something in the local warehouse</strong>" - and a failed pairing will also leave something in the warehouse.</p>
<p>When the two problems are multiplied, it becomes the phenomenon that users see: <strong>As long as the pairing button is clicked once, the activation page will permanently display "Paired"</strong>, regardless of whether the pairing is successful or failed.</p>
<p>Basically, a concept has been merged: <code>本地有一把密钥</code> and <code>设备信任这把密钥</code> are two different things, but they are represented by the same expression in the code. The authoritative information about whether the device trusts it or not is on the device side (in the authorization list of adbd). The only thing that can be truly confirmed locally is "I successfully ran a pairing."</p>
<hr />
<h2>4. Forensic C: Failure is silent</h2>
<p>The root cause of the "unworthy" half lies on the client side. The original <code>start()</code> looks like this:</p>
<pre><code>fun start(): Boolean {
    setupTlsConnection()

    state = State.ExchangingMsgs
    if (!doExchangeMsgs()) {
        state = State.Stopped
        return false
    }

    state = State.ExchangingPeerInfo
    if (!doExchangePeerInfo()) {
        state = State.Stopped
        return false
    }

    state = State.Stopped
    return true
}
</code></pre>
<p>There are <strong>7 <code>return false</code></strong> hidden in the two sending and receiving functions:</p>
<table>
<thead>
<tr>
<th>Location</th>
<th>Trigger Condition</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>doExchangeMsgs</code></td>
<td>Unable to read peer's <code>SPAKE2_MSG</code> header</td>
</tr>
<tr>
<td><code>doExchangeMsgs</code></td>
<td>Packet type is not <code>SPAKE2_MSG</code></td>
</tr>
<tr>
<td><code>doExchangeMsgs</code></td>
<td><code>initCipher()</code> returns false</td>
</tr>
<tr>
<td><code>doExchangePeerInfo</code></td>
<td><code>encrypt()</code> returns null</td>
</tr>
<tr>
<td><code>doExchangePeerInfo</code></td>
<td>Unable to read peer's <code>PEER_INFO</code> header</td>
</tr>
<tr>
<td><code>doExchangePeerInfo</code></td>
<td>Packet type is not <code>PEER_INFO</code></td>
</tr>
<tr>
<td><code>doExchangePeerInfo</code></td>
<td>The length after decryption does not match</td>
</tr>
</tbody>
</table>
<p>The caller (pairing dialog box) handles it like this:</p>
<pre><code>result.onSuccess { success -&gt;
    if (success) {
        onPairSuccess()
    }
    // success 为 false 时：什么都不做
}
</code></pre>
<p><strong>The wrong pairing code is entered in item 3</strong> ——The codes calculated on both sides of SPAKE2 are inconsistent, <code>initCipher()</code> returns false. In other words, the mistake that users are most likely to make happens to fall on a "silent return" path.</p>
<p>Net effect: **The user clicks OK, spins around, and then nothing. ** No error, no prompt, I don’t know whether to change the pairing code or restart the LAN debugging.</p>
<p>There is another problem with the same problem: when the pairing path in the notification bar encounters a key generation failure, it directly <code>return@launch</code>, and the notification will always stop at "Pairing", and the user cannot wait for any results.</p>
<hr />
<h2>5. How did I change it?</h2>
<h3>5.1 Delayed key placement</h3>
<p>A separate layer of warehouse packaging is added to the matching scene:</p>
<pre><code>class DeferredAdbKeyStore(private val delegate: AdbKeyStore) : AdbKeyStore {

    private var pending: ByteArray? = null

    /** 配对期间只进内存，不碰磁盘。 */
    override fun put(bytes: ByteArray) {
        pending = bytes
    }

    /** 读优先拿内存里的，否则回落到真正的仓库（复用上次配对留下的密钥）。 */
    override fun get(): ByteArray? = pending ?: delegate.get()

    /** 配对成功：这一刻才把暂存的密钥写进真正的仓库。 */
    fun commit() {
        pending?.let { delegate.put(it) }
    }
}
</code></pre>
<p>Both pairing entrances (dialog box, notification bar service) use it instead, only at the moment of success <code>commit()</code>.</p>
<p><strong>Why not "delete the newly written key when it fails"</strong>: That way of writing relies on failure processing to be executed - but if the user directly closes the dialog box and the process is recycled by the system, the cleanup will be skipped, and the dirty key will still remain on the disk. Delayed placement means "no writing at all" and there is no window that needs to be cleared. By the way, there is a benefit: if the user has successfully paired before, <code>AdbKey</code> will reuse the old key and will not trigger <code>put</code> at all. This failed attempt will not touch the key in use.</p>
<h3>5.2 Record "successful matching" as an independent fact</h3>
<pre><code>object AdbPairingState {

    private const val KEY_PAIRED_AT = "adb_paired_at"

    /** 配对成功的时间戳；0 表示没有成功记录。 */
    fun pairedAt(preferences: SharedPreferences): Long = preferences.getLong(KEY_PAIRED_AT, 0L)

    fun isPaired(preferences: SharedPreferences): Boolean = pairedAt(preferences) &gt; 0L

    fun markPaired(preferences: SharedPreferences) {
        preferences.edit { putLong(KEY_PAIRED_AT, System.currentTimeMillis()) }
    }

    fun clear(preferences: SharedPreferences) {
        preferences.edit { remove(KEY_PAIRED_AT) }
    }
}
</code></pre>
<p>From this point on, "pairing successful" is a fact of its own, and is only written after <code>AdbPairingClient</code> actually runs the entire process. Change the "Paired" on the activation page and boot page to read it, and no longer check whether the keystore is empty or not.</p>
<h3>5.3 Failure is no longer a <code>false</code></h3>
<p><code>start()</code> is changed to return <code>Unit</code>, and an exception will be thrown if it fails:</p>
<pre><code>/**
 * 跑完整个配对流程；失败一律抛异常。
 */
fun start() {
    setupTlsConnection()

    state = State.ExchangingMsgs
    doExchangeMsgs()

    state = State.ExchangingPeerInfo
    doExchangePeerInfo()

    state = State.Stopped
}
</code></pre>
<p>The most important one has changed from "silent" to "named":</p>
<pre><code>// SPAKE2 的密码校验不过 = 两边算出来的配对码不一致：
// 输错了，或者那个配对码已经作废（系统配对对话框一关，码就失效）。
if (!pairingContext.initCipher(theirMessage)) {
    throw AdbInvalidPairingCodeException()
}
</code></pre>
<p>The newly added <code>AdbPairingFailedException(reason)</code> (<code>reason</code> only enters the log and does not echo to the user) is thrown uniformly for issues on the protocol layer and encryption layer; <code>java.net.ConnectException</code> and <code>javax.net.ssl.SSLException</code> are thrown up as they are - they are semantically different things, and the caller needs to be able to distinguish them. After the modification, not a single <code>return false</code> is left in the entire matching process.</p>
<h3>5.4 Interface: Give "errors unrelated to the input box" a separate place</h3>
<p>It turns out that all exceptions are stuffed under the port input box:</p>
<pre><code>else -&gt; {
    portError = err.message ?: context.getString(R.string.cannot_connect_port)
}
</code></pre>
<p>This will mislead users to change the port repeatedly. Now it is divided into three levels, and a new one <code>generalError</code> is displayed:</p>
<table>
<thead>
<tr>
<th>Exception type</th>
<th>Prompt copy</th>
<th>Next step for the user</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>AdbInvalidPairingCodeException</code></td>
<td>The pairing code is wrong or expired.</td>
<td>Look again at the 6-digit code in the system dialog box</td>
</tr>
<tr>
<td><code>SSLException</code></td>
<td>Unable to establish an encrypted connection with the pairing service: the port or pairing code may have expired</td>
<td>Reopen the system "Pair device using pairing code" dialog box</td>
</tr>
<tr>
<td><code>AdbPairingFailedException</code></td>
<td>Pairing was interrupted by the device</td>
<td>Same as above, try again</td>
</tr>
</tbody>
</table>
<p>The path in the notification bar is processed synchronously: key generation failure is changed to normal reporting (originally it was a silent exit). The cause of the failure is also distinguished in the notification text. If the reason is unknown, a prompt is given to follow the instructions instead of dumping the stack to the user.</p>
<h3>5.5 Allow users of old versions to automatically restore</h3>
<p>Changing the judgment criteria will definitely hurt old users: they have local keys available, but the newly added "success record" is empty. After upgrading, they will be prompted with "no record of successful pairing."</p>
<p>So a step of self-healing was added - once the service is successfully started, it means that the key is indeed trusted by the device, and the record is filled in on the spot:</p>
<pre><code>val running = Shizuku.pingBinder()
val hasKey = hasPairingKey()
// 服务跑起来了，说明这把密钥确实被设备信任 —— 顺手补一笔配对记录。
// 旧版本没有这份记录，升级上来的用户靠这一步自动恢复正常显示。
if (running &amp;&amp; hasKey &amp;&amp; !AdbPairingState.isPaired(preferences)) {
    AdbPairingState.markPaired(preferences)
}
</code></pre>
<p>On the contrary, "Forgot Pairing" will now clear <code>adbkey</code> and the success record together - only the key will be deleted and the record will be left. The interface will continue to display "Paired", which is equivalent to committing this bug again in a different direction.</p>
<hr />
<h2>6. A little methodology</h2>
<p>What these two bugs have in common is the old saying:</p>
<blockquote>
<p>**Wherever "the writing end has written one step earlier, but the reading end regards it as final state evidence", the interface will start to make up facts for the user. **</p>
</blockquote>
<p>The order of investigation is also very fixed:</p>
<ol>
<li>First distinguish the "status seen by the user" is calculated from <strong>which piece of data</strong> - in this case, "whether there is a local key";</li>
<li>Ask again at what moment and by whom this data was written - in this case "when the object is constructed", not "when the operation is successful";</li>
<li>Once you find this time difference, the problem will emerge by itself.</li>
</ol>
<p>The other half (silent failure) is another example: using a return value to express failure without assigning any semantics to the failure. <code>Boolean</code> can only explain "it didn't work", but cannot tell "why it didn't work"; when the only thing the caller can do is "do nothing", writing an extra <code>return false</code> is equivalent to leaving the user where they are. Putting a type on failure is the lowest cost to let the interface speak.</p>
<hr />
<h2>7. Versions and products</h2>
<table>
<thead>
<tr>
<th>item</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>versionCode / versionName</td>
<td><code>315</code> / <code>zako3.15</code> (GitHub version), <code>zako3.15-f</code> (F-Droid version)</td>
</tr>
<tr>
<td>Build stack</td>
<td>AGP 8.10.1 / Kotlin 2.2.21 / compileSdk 36 / minSdk 24 / JVM 21</td>
</tr>
<tr>
<td>Signature</td>
<td><code>CN=Shizako, OU=Churan</code> (same certificate as the old version, can be directly overwritten and installed)</td>
</tr>
<tr>
<td>Product</td>
<td><code>shizako-zako3.15-release.apk</code>, 8,253,481 bytes, MD5 <code>a043afb432bcaffefb6fc91cee52b224</code></td>
</tr>
<tr>
<td>Corresponding submission</td>
<td><code>ee4c2f1</code> (tag <code>zako3.15</code>)</td>
</tr>
</tbody>
</table>
<hr />
<h2>8. Attachment: A really useful troubleshooting tip</h2>
<p>The port used for pairing is not the port shown at the top of the "Wireless Debugging" page.</p>
<p>What you need to get is the one in the system's "<strong>Pair device with pairing code</strong>" dialog box (formed like the part after the colon of <code>192.168.1.5:37241</code>), and the port will change every time you open this dialog box. The performance of filling in the wrong port is "immediate pairing failure", which can easily be mistaken as a broken function - half of the problems encountered by linsui are likely to be here.</p>
<blockquote>
<p>[!TIP]</p>
<ul>
<li>In the pairing dialog box, you can now enter the port manually under any circumstances (changed from <code>zako3.14</code>), without waiting for the result to be automatically discovered.</li>
<li>When automatic discovery (mDNS) fails, a clear prompt will appear: The system, VPN or firewall may be blocking multicast.</li>
<li>The pairing code is only valid when the system dialog box is kept open, and will be invalid when it is closed - this will be written directly in the error text now.</li>
</ul>
</blockquote>
<hr />
<h2>Attached: Submission timeline</h2>
<pre><code>2026-10-16 01:43  1db9619  fix(activation): 自动发现不到配对服务时改为手动输入端口   （zako3.14）
2026-10-16 01:43  40a159f  chore(release): zako3.14
2026-10-16 01:47  7f14103  docs(site): 官网更新到 zako3.14
2026-10-16 02:08  e8a412a  fix(pairing): 配对失败不再谎报「已配对」，失败原因可见
2026-10-16 02:08  ee4c2f1  chore(release): zako3.15
2026-10-16 02:09  05efdd3  docs(site): 官网更新到 zako3.15
2026-10-16 02:36  ca6a34e  fix(i18n): 英文激活页文案误混入中文「酱」
2026-10-16 02:40  41f3681  docs(fastlane): 补 315 的更新日志
2026-10-16 02:44  3af09ed  docs(fdroid): 本地 recipe 与 MR 现状对齐
2026-10-16 02:56  f1a8e59  fix(fdroid): F-Droid 版不再声明未使用的 REQUEST_INSTALL_PACKAGES
2026-10-16 02:57  6bfa50d  docs(fdroid): recipe 副本跟进 MR（pin f1a8e59、补权限说明）
</code></pre>
]]></content>
    <author><name>Churan</name></author>
    <category term="Open source projects"/>
  </entry>
  <entry>
    <title>Guidelines for minors to apply for a Bilibili co-branded debit card</title>
    <link href="https://www.churan.online/en/posts/20261011-113709/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/20261011-113709/</id>
    <published>2026-10-11T00:00:00.000Z</published>
    <updated>2026-10-11T00:00:00.000Z</updated>
    <summary></summary>
    <content type="html"><![CDATA[<h1>Guidelines for minors to apply for Bilibili co-branded debit cards</h1>
<h1>Guide for those under 18 years old (over 16 years old) to apply for a Bilibili co-branded debit card</h1>
<blockquote>
<p>Applicable objects: minors aged 16 and above and under 18.<br />
Currently, the more common choices are Bank of China’s Bilibili co-branded card and China Merchants Bank’s Bilibili co-branded card.</p>
</blockquote>
<hr />
<h2>1. Bank of China · Bilibili Co-branded Debit Card</h2>
<h3>Required materials</h3>
<ul>
<li>Household register</li>
<li>Personal ID card</li>
<li>Guardian ID card</li>
<li>A guardian must be present at the venue</li>
</ul>
<h3>Process</h3>
<ol>
<li>Accompanied by a guardian, bring the above materials to a Bank of China branch.</li>
<li>Register at the branch and explain to the staff that you want to apply for a "Bilibili co-branded debit card".</li>
<li>If the staff does not know the card, they can directly say "card linked to Bilibili" to facilitate the other party to find it in the system.</li>
<li>Apply for a co-branded debit card according to the requirements of the outlet. The specific card collection and activation methods are subject to the actual guidelines of the outlet.</li>
</ol>
<h3>Notes</h3>
<ul>
<li>Minors usually cannot apply directly through online channels and need to go to offline counters.</li>
<li>It is recommended to call the branch in advance to confirm whether the co-branded card is available to avoid a wasted trip.</li>
<li>The implementation details of different branches may be different, and the requirements of the local Bank of China branch shall prevail.</li>
</ul>
<hr />
<h2>2. China Merchants Bank · Bilibili Co-branded Debit Card</h2>
<h3>Required materials</h3>
<ul>
<li>Personal ID card</li>
<li>My real name mobile phone number</li>
<li>If the mobile phone card is not under your real name, you need to bring your household registration book (you can take photos, but you don’t need to bring the original)</li>
</ul>
<p>The application at China Merchants Bank is relatively simple and does not require a guardian to accompany you.</p>
<h3>Process</h3>
<h4>Step 1: Apply online</h4>
<ol>
<li>Download the "China Merchants Bank" APP on your mobile phone.</li>
<li>After registering and logging in, search for "Bilibili Debit Card" in the APP.</li>
<li>Find the application entrance, fill in the information as prompted and submit the online application.</li>
</ol>
<h4>Step 2: Offline card collection and activation</h4>
<ol>
<li>After applying online, go to the China Merchants Bank branch you selected when applying.</li>
<li>Note: The card collection outlet must be consistent with the outlet selected when applying.</li>
<li>Bring your ID card to the branch.</li>
<li>If the mobile phone number is not my real name, prepare the household registration photo.</li>
<li>The staff will assist you with card collection and activation.</li>
</ol>
<h3>Notes</h3>
<ul>
<li>China Merchants Bank does not require a guardian to accompany you.</li>
<li>The card collection outlet must be consistent with the outlet selected during online application.</li>
<li>If your mobile phone number is not your real name, you can take a photo of your household registration book without bringing the original.</li>
<li>The specific rights and redemption methods are subject to the activity page of China Merchants Bank APP.</li>
</ul>
<hr />
<h2>3. General reminder</h2>
<ol>
<li>Debit cards issued by those under the age of 18 usually have limited functions. For example, online banking or some electronic channel functions may not be available. For details, please refer to the instructions of the bank outlet.</li>
<li>The implementation details may be different in different regions and different outlets. It is recommended to call the target outlet before departure.</li>
<li>Bilibili co-branded cards usually come with relevant rights and interests of Bilibili. The specific collection method, time limit and conditions are subject to the bank's activity page.</li>
<li>Please bring your identity documents and required materials when applying to avoid being unable to apply due to incomplete materials.</li>
</ol>
]]></content>
    <author><name>Churan</name></author>
    <category term="Tutorial"/>
  </entry>
  <entry>
    <title>zako3.13 update instructions</title>
    <link href="https://www.churan.online/en/posts/20261011-120000/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/20261011-120000/</id>
    <published>2026-10-11T00:00:00.000Z</published>
    <updated>2026-10-11T00:00:00.000Z</updated>
    <summary></summary>
    <content type="html"><![CDATA[<h2>0. What has been changed in this version?</h2>
<table>
<thead>
<tr>
<th>Category</th>
<th>Content</th>
</tr>
</thead>
<tbody>
<tr>
<td>New</td>
<td>F-Droid special variant (version name with <code>-f</code>), has been put on the shelves MR</td>
</tr>
<tr>
<td>Repair</td>
<td>After root is activated, the application is authorized and disappears from the list after refreshing</td>
</tr>
<tr>
<td>Fix</td>
<td>Applications built with official <code>dev.rikka.shizuku:api</code> cannot grant/revoke permissions normally</td>
</tr>
<tr>
<td>Repair</td>
<td>The startup service page will crash if you return manually before automatically closing the window in 3 seconds</td>
</tr>
<tr>
<td>Repair</td>
<td>About page "Based on Shizako" self-referential copywriting</td>
</tr>
<tr>
<td>Build</td>
<td>Groovy fails to retrieve git, causing the configuration phase to hang directly</td>
</tr>
<tr>
<td>CI</td>
<td><code>gradlew</code> Executable bit missing, product glob or upstream package name</td>
</tr>
<tr>
<td>Official website</td>
<td>The data card is changed to real-time value + three-level fallback, and the competition between animation and real-time data is eliminated</td>
</tr>
</tbody>
</table>
<p>The most valuable of them are the first two - they are both "lost as soon as refreshed", which looks like front-end state management phenomena, but the real culprits are in the persistent records on the server side.</p>
<hr />
<h2>1. Core fix A: After root activation, the authorized application disappears after refreshing</h2>
<h3>1.1 Phenomenon</h3>
<p>After activating the Shizako service with root privileges:</p>
<ol>
<li>Enter "Application Management" and turn on the authorization switch for an application;</li>
<li>Pull down to refresh the list;</li>
<li>**This application has completely disappeared from the authorized list. **</li>
</ol>
<p>Note that it is not "the switch is turned off", but <strong>the entire record is not displayed</strong>. This difference is very important: the loss of the switch status is a problem of flags, and the disappearance of the entire switch is a problem of list filtering.</p>
<h3>1.2 Positioning</h3>
<p>The data in the "Application Management" list comes from <code>ShizukuService.getApplications()</code> on the server side. The list side (<code>AppsFragment</code> / <code>AppsAdapter</code>) is just rendering without filtering, so look at the server side first.</p>
<p>Find this paragraph in <code>getApplications()</code>:</p>
<pre><code>for (String packageName : PackageManagerApis.getPackagesForUidNoThrow(uid)) {
    PackageInfo pi = ...;
    int flags = 0;
    ShizukuConfig.PackageEntry entry = configManager.find(uid);
    if (entry != null) {
        if (entry.packages != null &amp;&amp; !entry.packages.contains(pi.packageName))
            continue;                       // ← 就是这里被跳过的
        flags = entry.flags &amp; ConfigManager.MASK_PERMISSION;
    }
    ...
}
</code></pre>
<p>The semantics of this <code>continue</code> is: <strong>"The record of this uid states that it only counts certain packages, and the current package is not in the list, so skip it"</strong>.</p>
<p>The question then becomes: Who wrote a record that does not contain the application but has the authorization bit in <code>packages</code>?</p>
<h3>1.3 Root cause: an empty record written by <code>update(uid, null, …)</code></h3>
<p>The link taken by the authorization switch is: Manager <code>Shizuku.updateFlagsForUid(uid, MASK_PERMISSION, FLAG_ALLOWED)</code> → Server <code>ShizukuService.updateFlagsForUid()</code>, and its <strong>last line</strong> is:</p>
<pre><code>configManager.update(uid, null, mask, value);
//                        ^^^^ 包名传的是 null
</code></pre>
<p>Look at the constructors of <code>updateLocked()</code> and <code>PackageEntry</code>:</p>
<pre><code>private void updateLocked(int uid, List&lt;String&gt; packages, int mask, int values) {
    ShizukuConfig.PackageEntry entry = findLocked(uid);
    if (entry == null) {
        entry = new ShizukuConfig.PackageEntry(uid, mask &amp; values);  // 新建
        config.packages.add(entry);
    } else {
        ...
    }
    if (packages != null) {          // ← null 就整段跳过
        for (String packageName : packages) { ... }
    }
    scheduleWriteLocked();
}

public PackageEntry(int uid, int flags) {
    this.uid = uid;
    this.flags = flags;
    this.packages = new ArrayList&lt;&gt;();   // ← 关键：是空 List，不是 null
}
</code></pre>
<p>So when there is no record for this uid at that time, an authorization will write one:</p>
<ul>
<li><code>flags</code> has authorization bit (<code>MASK_PERMISSION &amp; FLAG_ALLOWED</code>)</li>
<li><code>packages</code> is an <strong>empty ArrayList</strong> (<code>packages == null</code> allows writing to be skipped, and the constructor gives an empty list)</li>
</ul>
<p>The judgment in <code>getApplications()</code> is <code>entry.packages != null &amp;&amp; !entry.packages.contains(...)</code> - the empty table satisfies <code>!= null</code>, so <code>!contains(pkg)</code> is established and the <strong>application is eliminated</strong>.</p>
<p>**This is the complete causal chain: a call that was thought to be "unlimited package name" actually wrote a record of "limited to zero packages". **</p>
<p>A record represents both "does it have permissions" and "which headers does this permission count for?" The two semantics are squeezed into one field group, and only half of them are included when writing. This contradictory persistence state is bound to occur.</p>
<h3>1.4 Why does root reappear stably?</h3>
<p>The same code path cannot be seen when activated by ADB. The difference lies in the <strong>service life cycle</strong>:</p>
<ul>
<li>The service activated by <strong>root</strong> is permanent (with a watchdog to keep it alive). A round of scanning was done at the moment the service was started, and records were created for all applications that had been installed and had declared permissions at that time; but <strong>newly installed applications after that were not recorded at all</strong>. When you authorize it, <code>find(uid)</code> returns null, so go to the "New" branch and write down the empty package name record → it will disappear after refreshing.</li>
<li><strong>ADB activation</strong> requires restarting the service and re-running a startup scan every time. The package name is already included in the record, and <code>packages</code> is not empty and contains the package, so no problem can be seen.</li>
</ul>
<p>The same bug is half covered by the life cycle difference between the two activation methods - this type of bug is the most difficult to report and reproduce.</p>
<h3>1.5 fixes (three places)</h3>
<p><strong>① <code>getApplications()</code>: Empty package name records are regarded as "unlimited package names"</strong></p>
<pre><code>-                if (entry.packages != null &amp;&amp; !entry.packages.contains(pi.packageName))
+                if (entry.packages != null &amp;&amp; !entry.packages.isEmpty()
+                        &amp;&amp; !entry.packages.contains(pi.packageName))
                     continue;
</code></pre>
<p>The "package name is not in the list" will be eliminated only if it is <strong>non-empty</strong>. This article is also a <strong>backwards compatible hemostasis</strong>: there is no need to clear the bad records that have been written into <code>shizuku.json</code> in the old version, and the user does not need to re-authorize. It will be normal immediately after the upgrade.</p>
<p><strong>② <code>updateFlagsForUid()</code>: Write the actual package name</strong></p>
<pre><code>List&lt;String&gt; packages = new ArrayList&lt;&gt;();
// ...
for (String packageName : PackageManagerApis.getPackagesForUidNoThrow(uid)) {
    PackageInfo pi = ...;
    if (pi == null || pi.requestedPermissions == null) continue;

    // 用官方 dev.rikka.shizuku:api 构建的应用只声明上游权限名，
    // 授/撤运行时权限必须用它实际声明的那一个，否则会抛异常。
    String permission;
    if (ArraysKt.contains(pi.requestedPermissions, PERMISSION)) {
        permission = PERMISSION;
    } else if (ArraysKt.contains(pi.requestedPermissions, PERMISSION_UPSTREAM_API)) {
        permission = PERMISSION_UPSTREAM_API;
    } else {
        continue;
    }

    packages.add(packageName);

    try {
        if (allowed) {
            PermissionManagerApis.grantRuntimePermission(packageName, permission, userId);
        } else {
            PermissionManagerApis.revokeRuntimePermission(packageName, permission, userId);
        }
    } catch (Throwable e) {
        // 单个包失败不能中断整轮：否则下面的配置写入也被跳过，
        // 结果就是授权记录压根没落下。
        LOGGER.w(e, "updateFlagsForUid: " + (allowed ? "grant " : "revoke ") + packageName);
    }
}
// ...
configManager.update(uid, packages.isEmpty() ? null : packages, mask, value);
</code></pre>
<p>There are three layers to consider here:</p>
<ul>
<li><code>packages</code> is no longer always <code>null</code> - "Grant/revoke permissions based on the actual declaration of the package" has also been fixed (originally, the application of the upstream permission name would directly throw an exception);</li>
<li>With the addition of <code>try/catch</code>, <strong>single packet failure will no longer interrupt the entire round</strong> - otherwise the following <code>configManager.update(...)</code> will be skipped together, and the record will not be placed on the disk at all, forming the third bad state of "authorized but the record does not exist";</li>
<li>Only return <code>null</code> when no package is matched.</li>
</ul>
<p><strong>③ <code>ShizukuConfigManager</code> starts scanning + <code>getFlagsForUidInternal()</code>: also recognizes the upstream permission name</strong></p>
<p>When starting the scan, it originally only recognized its own <code>PERMISSION</code>:</p>
<pre><code>-                if (pi == null || pi.applicationInfo == null
-                        || pi.requestedPermissions == null
-                        || !ArraysKt.contains(pi.requestedPermissions, PERMISSION)) {
+                if (pi == null || pi.applicationInfo == null
+                        || pi.requestedPermissions == null) {
+                    continue;
+                }
+                String permission;
+                if (ArraysKt.contains(pi.requestedPermissions, PERMISSION)) {
+                    permission = PERMISSION;
+                } else if (ArraysKt.contains(pi.requestedPermissions, PERMISSION_UPSTREAM_API)) {
+                    permission = PERMISSION_UPSTREAM_API;
+                } else {
                     continue;
                 }
</code></pre>
<p>Semantically, the judgment of "who counts as our application" is relaxed from <strong>only looking at own permission names</strong> to <strong>own or upstream permission names</strong>, aligned with <code>getApplications()</code> (that is, those applications actually displayed in the list). If they are not aligned, this entire type of application will never be able to take the path of "recording at startup" and can only rely on creation at the moment of authorization - and the record created at that moment is the hotbed of the empty package name bug above.</p>
<h3>1.6 Summary</h3>
<p>A <code>null</code> parameter connects three different levels of issues: list filtering, permission granting, and startup scanning. If you only change the deletion logic of <code>getApplications()</code> during repair, the symptoms will disappear, but the bad configuration will still be written every time you authorize it, and it will explode again next time you read it from another place. Therefore, the correct correction method is: **Block the writing source, and at the same time make the reading end tolerant to historical dirty data. **</p>
<hr />
<h2>2. Core fix B: The startup page crashes when the window automatically closes in 3 seconds.</h2>
<h3>2.1 The crash log is obfuscated</h3>
<p>The stack received online looks like this (after R8 obfuscation):</p>
<pre><code>java.lang.IllegalStateException: Fragment StarterFragment{...} not associated with a fragment manager
    at rikka.shizuku.Ax.k(...)
    at rikka.shizuku.Xz.o(...)
    at rikka.shizuku.k3.run(...)
    at android.os.Handler.handleCallback(Handler.java:...)
    at android.os.Handler.dispatchMessage(Handler.java:...)
    at android.os.Looper.loopOnce(Looper.java:...)
    ...
</code></pre>
<p>The class names are all gone, but there is a <strong>local asset</strong> that can be directly restored: <code>out/mapping/mapping-zako3.12.txt</code> produced by the same release build. Check it:</p>
<table>
<thead>
<tr>
<th>Obfuscated name</th>
<th>After restoration</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>rikka.shizuku.Ax</code></td>
<td><code>androidx.fragment.app.Fragment</code></td>
</tr>
<tr>
<td><code>rikka.shizuku.Xz</code></td>
<td><code>androidx.navigation.NavHostFragment</code></td>
</tr>
<tr>
<td><code>rikka.shizuku.k3</code></td>
<td>That layer is inlined/synthesized by R8 <code>Runnable</code></td>
</tr>
</tbody>
</table>
<p>So the true meaning of the stack is:</p>
<pre><code>Fragment.getParentFragmentManager()   ←
NavHostFragment.findNavController(Fragment)   ←
Runnable.run()  （主线程 Handler）
</code></pre>
<p><strong>Keeping the mapping file is the root cause of the five-minute positioning this time</strong> - it's worthless, but without it, this stack can only be guessed.</p>
<h3>2.2 Root cause</h3>
<p><code>StarterFragment</code> will <strong>delay 3 seconds to automatically close the window</strong> after the service is started:</p>
<pre><code>view?.postDelayed({
    findNavController().navigateUp()
}, 3000)
</code></pre>
<p>There are two questions, stacked together:</p>
<ol>
<li>This is a deferred task on the main thread Handler. It belongs to <code>view</code>, but once <code>postDelayed</code> joins the team, as long as it does not actively call <code>removeCallbacks</code>, it will still run if the view is torn down;</li>
<li>The first thing inside <code>findNavController()</code> is <code>getParentFragmentManager()</code>. If the user presses return within these 3 seconds, or the page is destroyed, the Fragment has left the FragmentManager, and this line directly throws <code>IllegalStateException</code>.</li>
</ol>
<p>In other words: **The premise of "the page is still there" is written into a callback that does not guarantee that the page is still there. **</p>
<h3>2.3 Fix</h3>
<pre><code>/** 服务起来后延迟关窗用的回调。必须能在视图销毁时撤掉 */
private val navigateUpRunnable = Runnable {
    if (!isAdded || isRemoving) return@Runnable
    val nav = runCatching { findNavController() }.getOrNull() ?: return@Runnable
    runCatching { nav.navigateUp() }
}

/** 等服务的监听器，销毁时要摘掉，否则会留到下一次 binder 事件上 */
private var binderReceivedListener: Shizuku.OnBinderReceivedListener? = null

private var autoCloseArmed = false
</code></pre>
<p>Three supporting facilities:</p>
<ul>
<li><code>removeCallbacks</code>** in **<code>onDestroyView()</code> and remove the listener - this is the root cause, the callback no longer has a chance to be executed after the page disappears;</li>
<li><strong>Execute the prejudgment <code>!isAdded || isRemoving</code></strong>, and add <code>runCatching</code> to hide the bottom line - the second layer of defense;</li>
<li><strong><code>autoCloseArmed</code> One-time protection</strong> - It turns out that every time <code>observe</code> is triggered, it may <strong>re-register a binder listener</strong>. Once the service is ready, multiple callbacks will be triggered, superimposing multiple <code>navigateUp()</code>.</li>
</ul>
<p>By the way, the listener was changed to hold a reference (<code>binderReceivedListener</code>) instead of the anonymous object directly <code>remove(this)</code>. This is also because the original writing method can only remove the last registered one when registering repeatedly, and all the previous ones will be leaked to the next binder event.</p>
<hr />
<h2>3. F-Droid launched: one project, two variants</h2>
<h3>3.1 Why not use <code>productFlavors</code></h3>
<p>Gradle's flavor will change the product path to <code>apk/&lt;flavor&gt;/release/</code>, and the existing release script, official website download link, and CI product glob are all hard-coded to <code>apk/release/</code>. So use <strong>build properties</strong> instead:</p>
<pre><code>def fdroidBuild = project.hasProperty('fdroid')

versionName rootProject.ext.versionName + (fdroidBuild ? '-f' : '')
buildConfigField "boolean", "FDROID_BUILD", "${fdroidBuild}"
</code></pre>
<pre><code>./gradlew :manager:assembleRelease              # GitHub 版 → zako3.13
./gradlew :manager:assembleRelease -Pfdroid     # F-Droid 版 → zako3.13-f
</code></pre>
<p>"Two variants, one source code" can also be achieved, but <strong>no existing paths</strong> will be left unchanged. There is no need to make two copies of the project - the two copies will drift separately, and one bug needs to be corrected twice.</p>
<h3>3.2 Four switches + placeholder package, concentrated in <code>FdroidBuild.kt</code></h3>
<p>The business code only references <code>FdroidBuild</code> and does not directly read <code>BuildConfig.FDROID_BUILD</code>. During the review, you can see clearly at a glance "what is disabled in the F-Droid version and why":</p>
<pre><code>object FdroidBuild {
    val isFdroid: Boolean get() = BuildConfig.FDROID_BUILD

    /** 自更新：F-Droid 用自己的密钥签名，换签名安装必然失败，且绕过商店分发 */
    val allowSelfUpdate: Boolean get() = !isFdroid

    /** 更新检查里的第三方 GitHub 反代（gh-proxy / ghfast / ghproxy） */
    val allowUpdateMirrors: Boolean get() = !isFdroid

    /** 一键注入：下载并安装第三方 APK */
    val allowOneClickInject: Boolean get() = !isFdroid

    /** AI 解释：内置多家专有服务商入口，关掉即可不申报 NonFreeNet */
    val allowAiExplain: Boolean get() = !isFdroid

    /** 兼容性占位包：applicationId 为上游 moe.shizuku.privileged.api 的空壳 */
    val allowCompatStub: Boolean get() = !isFdroid
}
</code></pre>
<p>Among them, the placeholder package is the most subtle: its function is to install an empty shell with an applicationId equal to <strong>upstream package name</strong>, so that third-party applications that have the upstream package name written into the code can "see" this application. The FORBIDDEN clause of the upstream README explicitly prohibits fork from using the application id - so the F-Droid version not only does not install it, but also does not even enter the package name into DEX:</p>
<pre><code>buildConfigField "String", "COMPAT_PACKAGE",
        fdroidBuild ? '""' : '"moe.shizuku.privileged.api"'
</code></pre>
<h3>3.3 stub APK is changed to be generated during build</h3>
<p><code>manager/src/main/assets/shizako-stub.apk</code> Remove tracking from git and change it to build-time products. This step exposes a Gradle 8 problem that only occurs on <strong>fresh clones</strong>: the task once declared its output as input (<code>inputs.file(stubApkFile).optional()</code>), and Gradle 8 performs input existence verification before execution - the cloned file does not exist, and the task directly refuses to execute. Just delete that line of input declaration. "Rerun after the file is deleted" is naturally guaranteed by <code>outputs.file</code> (the declared output is deemed expired if it is missing).</p>
<h3>3.4 Making the Linux build machine work: Kill <code>java.io.tmpdir</code></h3>
<p><code>gradle.properties</code> originally contained:</p>
<pre><code>org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8 -Djava.io.tmpdir=E:/tmp
</code></pre>
<p>This is a development machine-specific path. The GitHub CI side has only covered the workflow in the past, but <strong>F-Droid's build machine is also Linux and directly executes the recipe's gradle</strong> - the warehouse file is not changed, and the MR will fail in the same way within a few seconds as soon as it is mentioned:</p>
<pre><code>IOException: java.io.tmpdir is set to a directory that doesn't exist
</code></pre>
<p>Root fix: Completely remove this parameter from <code>org.gradle.jvmargs</code>, and add a comment stating "<strong>Never add it back, and the correct approach when this machine really needs it</strong>". By the way, I confirmed that the directory junction was used to solve the path problem. This tmpdir has long been unable to bear the load.</p>
<h3>3.5 recipe and naming</h3>
<ul>
<li><code>tools/fdroid/com.churan.shizako.yml</code>: <code>versionName: zako3.13-f</code>, <code>output: manager/build/outputs/apk/release/shizako-zako3.13-f-release.apk</code>, <code>gradle:</code> plus <code>-Pfdroid</code></li>
<li>NDK corrected to <code>29.0.14206865</code>, consistent with root <code>build.gradle</code></li>
<li>Because the AI entrance is closed, there is no need to declare <code>NonFreeNet</code> anti-features</li>
<li><code>settings.gradle</code> automatically closes all Alibaba Cloud images when <code>-Pfdroid</code> is detected, and changes to <code>google()</code> / <code>mavenCentral()</code> / <code>gradlePluginPortal()</code>; the GitHub build behavior without parameters remains completely unchanged</li>
</ul>
<hr />
<h2>4. Build and CI hardening: four pitfalls</h2>
<h3>4.1 <code>gradlew</code> Loses the executable bit — and secondary damage to Windows</h3>
<p>CI has a long-term red light. The root cause is that the git file mode of <code>gradlew</code> has changed to <code>100644</code>:</p>
<pre><code>./gradlew: Permission denied      (exit 126)
</code></pre>
<p>The fix is ​​<code>git update-index --chmod=+x gradlew</code>. But <strong>the first repair failed</strong>: the mode changed back to <code>100644</code> after Git submission. The reason is that the local <code>core.filemode=false</code> (Windows normal), the newly set mode in the index is overwritten by the subsequent <code>git add -A</code> with the <strong>actual mode on the disk</strong> (always <code>100644</code> on Windows). The second time only the index content is submitted and no longer <code>add</code> will take effect.</p>
<blockquote>
<p>Lesson: When changing the file mode on Windows, be sure to submit it separately, do not let it go into <code>git add -A</code> with other changes.</p>
</blockquote>
<h3>4.2 The product glob of workflow also contains the upstream package name</h3>
<pre><code>- shizuku*-v*-release.apk
+ shizako*-release.apk
</code></pre>
<p>After the fork, the product name has been changed long ago, and the glob can never be matched. <code>ls</code> directly aborts the step under <code>bash -e</code>. This explains why even pure docs submissions have a red light.</p>
<h3>4.3 Empty environment of Groovy <code>'cmd'.execute([], dir)</code></h3>
<p>When building natively (Windows) I get:</p>
<pre><code>Where: build.gradle line: 29
&gt; For input string: ""
</code></pre>
<p><code>build.gradle</code> contains:</p>
<pre><code>def gitCommitId = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def gitCommitCount = Integer.parseInt('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())
</code></pre>
<p>The first parameter of <code>String.execute(envp, dir)</code> is <strong>child process environment variable array</strong> - passing <code>[]</code> (empty array) does not "inherit the current environment", but <strong>gives an empty environment to the child process</strong>, <code>PATH</code> is lost accordingly, so <code>git</code> cannot be found, and an empty string is output, <code>Integer.parseInt("")</code> Let the entire root project hang during the <strong>configuration phase</strong>.</p>
<p>These two variables are not referenced anywhere in the project (versionCode / versionName are hard-coded). Change to fault tolerance:</p>
<pre><code>def gitCommitId = ''
def gitCommitCount = 0
try {
    def id = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
    if (id) gitCommitId = id
    def count = 'git rev-list --count HEAD'.execute([], project.rootDir).text.trim()
    if (count) gitCommitCount = Integer.parseInt(count)
} catch (Throwable ignored) {
    // 环境里没有可用的 git：保持默认值，不影响构建
}
</code></pre>
<p>By the way, remember a version number agreement: <code>versionCode</code> follows <code>versionName</code> instead of following the git submission number - <code>3.01 → 301</code>. In this way, you only need to change <code>versionName</code> every time a version is released, and the upgrade judgment will naturally be established.</p>
<hr />
<h2>5. Official website data card: three-level fallback and animation competition</h2>
<p>The technical point of this piece is not "getting the data", but the <strong>data arrival order</strong>.</p>
<p>In the first version of the implementation, the first screen card number comes from the same source <code>stats.json</code>, and it is refreshed only once every 6 hours by <code>badges.yml</code>. What's worse is the entry animation: it first rolls over the bottom value hard-coded in the HTML and marks it as "counted", and then skips <code>stats.json</code> when it arrives - so the old number hard-coded in the HTML is displayed on the page for a long time.</p>
<p>Change to third-level data source:</p>
<ol>
<li><strong>HTML guaranteed value</strong> - always exists, worst case scenario;</li>
<li><strong>Same source <code>stats.json</code></strong> —— <code>badges.yml</code> is refreshed regularly and can be read forever, which is protected by weak network;</li>
<li><strong><code>api.github.com</code> Real-time query</strong> - Overwrite as soon as you get it, refresh the page to get the latest one.</li>
</ol>
<p>If this path fails in real time (domestic DNS interception / 403 current limit / timeout), it will be <strong>silent</strong> and keep the previous level number. Fix two race conditions at the same time:</p>
<ul>
<li>"Latest data is skipped": <code>renderStat</code> unified rendering, the new value must be overwritten, but the animation will not be replayed;</li>
<li>"Animation rolls back the new value": <code>countUp</code> Added <code>alive</code> callback, which will stop as soon as new data arrives. Otherwise, the old target animation of 900ms will cover up the real-time numbers frame by frame - the actual measurement shows that when the motion effect is turned on, it finally stops at the lowest value, and it works normally when the motion effect is turned off. This is equivalent to "the more users who care about the motion effect, the less they can see the real-time numbers."</li>
</ul>
<p>The package changes <code>badges.yml</code> from 6 hours to <strong>every hour</strong>, so that the weak network can keep the bottom for up to one hour (no submission will occur if the number does not change).</p>
<p>The verification method is to load the real <code>site.js</code> (minimum DOM stub + interception <code>fetch</code>) in the Node fixture and run four scenarios - live / blocked / offline / live-anim full PASS, and then use real Chrome headless end-to-end confirmation: after deliberately writing the bottom value and <code>stats.json</code> into wrong old values, the final DOM of the page Displayed are real-time values.</p>
<hr />
<h2>6. Versions and products</h2>
<table>
<thead>
<tr>
<th>item</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>versionCode</td>
<td><code>313</code></td>
</tr>
<tr>
<td>versionName</td>
<td><code>zako3.13</code> (GitHub version) / <code>zako3.13-f</code> (F-Droid version)</td>
</tr>
<tr>
<td>Build stack</td>
<td>AGP 8.10.x / Kotlin 2.1.21 / jvmTarget 21 / material 1.12.0</td>
</tr>
<tr>
<td>Signature</td>
<td><code>CN=Shizako, OU=Churan</code> (same certificate as the old version, can be directly overwritten and installed)</td>
</tr>
<tr>
<td>Product</td>
<td><code>shizako-zako3.13-release.apk</code> (GitHub Release attachment name convention is <code>shizako-vzako3.13-release.apk</code>)</td>
</tr>
</tbody>
</table>
<hr />
<h2>6.5 A little methodology</h2>
<p>This time the three pieces of work - two business bugs, a variant, and a bunch of CIs - have only one sentence in common:</p>
<blockquote>
<p>**Anywhere where "the writing end writes less than half, and the reading end reads as written as full" will develop into a bug that looks like front-end state management like "refresh and then lose it." **</p>
</blockquote>
<p>And the order of locating it, with almost no exceptions:</p>
<ol>
<li>First check whether the phenomenon is <strong>status error</strong> or <strong>entire missing</strong> - the latter must be the filtering/query logic, not the data itself;</li>
<li>Find the <strong>only persistence entry</strong> and see what is written in it;</li>
<li>Follow the reading and see if there is any coincidence like "the default value is exactly equal to the semantically empty set" - in this case, <code>new ArrayList&lt;&gt;()</code> is exactly equivalent to "limited to zero packets", which is the most terrible coincidence.</li>
</ol>
<p>The second bug is another typical one: <strong>writing a premise (the page is still there) into a callback that does not guarantee that the premise is true</strong>. The law is always "whoever creates it is responsible for destroying it" - <code>removeCallbacks</code> in <code>onDestroyView</code>.</p>
<hr />
<h2>Attachment: Submission timeline (removing badge robots)</h2>
<pre><code>2026-10-01  9dc6c99  chore(release): zako3.13（versionCode 313）
2026-10-01  a65c92c  build: 移除 gradle.properties 里会炸 Linux 构建机的 java.io.tmpdir
2026-10-01  539f1a3  ci: 恢复 gradlew 的 git 可执行位（100755）
2026-10-01  503a4d9  ci: 修复 App workflow 长期红灯的两个根因
2026-10-01  2c07873  site: 数据卡片的下载量与 Star 改为实时显示（GitHub API + 三级回退）
2026-10-01  654ef4c  fix(about): 去掉「二次开发」措辞，并修掉「基于 Shizako」这个自指 bug
2026-10-02  77beb7e  feat(fastlane): 加入 F-Droid 应用商店元数据（en-US + zh-CN）
2026-10-03  9160569  feat(fdroid): F-Droid 版不再打包兼容性占位包，并清掉产物里的上游包名
2026-10-11  1ecca5f  fix(server): 授权记录漏写包名，root 激活后授权应用刷新即从列表消失
2026-10-11  565cc56  fix(manager): 启动页延迟关窗在 Fragment 销毁后仍执行，导致崩溃
2026-10-11  e63772d  fix(build): 取不到 git 时不再让整个构建在配置阶段失败
2026-10-11  749aba6  docs(site): 官网更新到 zako3.13
</code></pre>
]]></content>
    <author><name>Churan</name></author>
    <category term="Open source projects"/>
  </entry>
  <entry>
    <title>🔒 Watching gbc again, it’s still so touching</title>
    <link href="https://www.churan.online/en/posts/gbc/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/gbc/</id>
    <published>2026-10-09T00:00:00.000Z</published>
    <updated>2026-10-09T00:00:00.000Z</updated>
    <summary>This post is password-protected.</summary>
    <content type="html"><![CDATA[<p><em>🔒 This post is encrypted. Please visit the website and enter the password to read the full article.</em></p>]]></content>
    <author><name>Churan</name></author>
    <category term="daily"/>
  </entry>
  <entry>
    <title>🔒 Can&apos;t Sleep</title>
    <link href="https://www.churan.online/en/posts/20261008-041237/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/20261008-041237/</id>
    <published>2026-10-08T00:00:00.000Z</published>
    <updated>2026-10-08T00:00:00.000Z</updated>
    <summary>This post is password-protected.</summary>
    <content type="html"><![CDATA[<p><em>🔒 This post is encrypted. Please visit the website and enter the password to read the full article.</em></p>]]></content>
    <author><name>Churan</name></author>
    <category term="Daily"/>
  </entry>
  <entry>
    <title>Introducing my open-source project: Shizako</title>
    <link href="https://www.churan.online/en/posts/shizako/" rel="alternate" type="text/html"/>
    <id>https://www.churan.online/en/posts/shizako/</id>
    <published>2026-10-07T00:00:00.000Z</published>
    <updated>2026-10-07T00:00:00.000Z</updated>
    <summary>Shizako is an Android tool I built: use privileged system APIs without Root, compatible with the Shizuku-API ecosystem. A quick introduction.</summary>
    <content type="html"><![CDATA[<p>This is a small Android tool I made, called <strong>Shizako</strong> (<a href="https://github.com/cr1437/Shizako">GitHub</a> | <a href="https://cr1437.github.io/Shizako/">Website</a>).</p>
<p>The reason is simple: Android actually has plenty of useful system-level features — silent installs, freezing apps, changing permissions, reading system settings — but normal apps can't call them. To use them comfortably you usually need Root — which is risky, and not everyone wants it.</p>
<p>So Shizako took a different approach: start a small privileged process via Wireless Debugging, PC ADB or Root (any one of them), and let it lend permissions to the apps you authorize. Every app needs your manual confirmation on first connection, and you can revoke access at any time.</p>
<h2>What it can do</h2>
<ul>
<li><strong>No Root needed</strong>: activate via Wireless Debugging / ADB, no flashing</li>
<li><strong>Permission management</strong>: authorize each app individually; the allowlist is stored locally and revocable anytime</li>
<li><strong>Shizuku-API compatible</strong>: apps built with the official Shizuku SDK work without any code change or recompilation</li>
<li><strong>Dhizuku mode</strong>: set Shizako as Device Owner — after one activation, no Root and no Wireless Debugging needed</li>
<li><strong>Four activation methods</strong>: Wireless Debugging / PC ADB / Root / Dhizuku</li>
<li><strong>And more</strong>: Tasker broadcast intents, API auditing, auto-update, crash logs</li>
</ul>
<h2>How to use it</h2>
<p>::: steps</p>
<ol>
<li>Download the latest APK from <a href="https://github.com/cr1437/Shizako/releases">Releases</a> and install it.</li>
<li>Choose an activation method:
<ul>
<li><strong>Wireless Debugging</strong> (Android 11+): turn it on, scan the QR / pair;</li>
<li><strong>PC ADB</strong>: run the command shown in the app on your computer;</li>
<li><strong>Root</strong>: launch directly if you have a Root environment;</li>
<li><strong>Dhizuku</strong>: run the command below to set it as Device Owner (no accounts allowed on the device), then Wireless Debugging is no longer needed.</li>
</ul>
<pre><code>adb shell dpm set-device-owner com.churan.shizako/.dhizuku.DhizukuAdminReceiver
</code></pre>
</li>
<li>Open the app you want to authorize and tap allow in the dialog.
:::</li>
</ol>
<h2>Notes</h2>
<ul>
<li>Under the hood it uses Shizuku's API (the <code>api/</code> directory is the Shizuku-API source); the protocol and calling conventions match upstream exactly;</li>
<li>Apps built with the official SDK (like MT Manager, Ice Box, SystemUI Tuner) connect directly without recompiling;</li>
<li>One caveat: the built-in compatibility bridge occupies the official provider authority, so <strong>Shizako cannot be installed alongside official Shizuku</strong> — pick one;</li>
<li>The project is open source under Apache-2.0. Have fun.</li>
</ul>
<p>::github{repo="cr1437/Shizako"}</p>
<h2>About the mascot</h2>
<p>Shizako's mascot is <strong>Shizako-chan</strong>: white hair, cat ears, a crescent-moon hair ornament — a "cat-girl system assistant hugging a terminal". The app icon, copy and promo materials are all built around her.</p>
<p>If you find her cute, feel free to use her as a sticker — just don't do anything bad with her.</p>
<ul>
<li><strong>Website</strong>: <a href="https://cr1437.github.io/Shizako/">https://cr1437.github.io/Shizako/</a></li>
<li><strong>Repository</strong>: <a href="https://github.com/cr1437/Shizako">https://github.com/cr1437/Shizako</a></li>
<li><strong>Download</strong>: <a href="https://github.com/cr1437/Shizako/releases">Releases</a></li>
</ul>
]]></content>
    <author><name>Churan</name></author>
    <category term="Open Source"/>
  </entry>
</feed>
