Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ public static HotspotMode of(Context context, HotspotHolders.Holder holder, Mode
}, initial);
}

/**
* The first choice of a sharing screen: the Wi-Fi network the phone is already on, else the
* hotspot. A Wi-Fi Direct group started for nothing can break a direct Wi-Fi link (TDLS)
* between the two phones on the same network (K2GO-587).
*/
public static Mode initialFor(boolean onWifiNetwork) {
return onWifiNetwork ? Mode.WIFI : Mode.HOTSPOT;
}

public Mode mode() {
return mode;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,9 @@ private void setSide(Side sd) {
// a phone with a system is the natural source for both the app and the system.)
systemPresent = org.appdevforall.k2go.SystemStateEvaluator.isSystemInstalled(requireContext());
page = Page.PREPARE;
if (systemPresent) setMode(Mode.HOTSPOT); else render(); // ADFA-4785: enter Send at step 1
// ADFA-4785: enter Send at step 1. K2GO-587: on the phone's Wi-Fi network when it is on one.
if (systemPresent) setMode(HotspotMode.initialFor(CloneLinkRows.onWifiNetwork(requireContext())));
else render();
return;
}
rStage = RStage.JOIN; pasteCode.collapse();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ public interface Opener {
private volatile long lastRx; // last bytes from the cable, or the end of local work
private volatile boolean peerPings; // the peer runs the keepalive (an older K2Go does not)
private volatile boolean busy; // the read thread writes to a local socket
private static final long PING_MS = 2_000;

public CableMux(UsbLink link, Opener opener, Listener listener) {
this.link = link;
Expand Down Expand Up @@ -234,13 +233,13 @@ private void handle(CableFrame f) throws IOException {

/**
* A peer that dies (app killed, phone off) does not always end our blocked USB read, so the
* link would look alive forever. Each side sends PING every PING_MS; PeerAlive decides when
* silence closes the link.
* link would look alive forever. Each side sends PING every PeerAlive.PING_MS; PeerAlive
* decides when silence closes the link.
*/
private void keepAlive() {
try {
while (!closed) {
Thread.sleep(PING_MS);
Thread.sleep(PeerAlive.PING_MS);
if (closed) return;
if (PeerAlive.isDead(peerPings, busy, System.currentTimeMillis() - lastRx)) {
Log.w(TAG, "nothing from the peer for " + PeerAlive.DEAD_MS + " ms: link closed");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* ============================================================================
* Name : SenderReach.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Does the sender answer on its rsync port over Wi-Fi (K2GO-587)?
* Two phones on one Wi-Fi network set up a direct link (TDLS) by
* themselves under heavy traffic. When the sender then starts a
* Wi-Fi Direct group, some drivers end their side of that link
* without telling the receiver, which keeps sending into the dead
* link until Wi-Fi restarts. DirectLinkRepair decides when this
* phone drops the link and tries once more, through the router.
* https://developer.android.com/reference/android/net/wifi/WifiManager#setTdlsEnabled(java.net.InetAddress,%20boolean)
* ============================================================================
*/
package org.appdevforall.k2go.sync.cable.data;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.util.Log;

import org.appdevforall.k2go.sync.cable.domain.DirectLinkRepair;
import org.appdevforall.k2go.sync.cable.domain.DirectLinkRepair.Outcome;

import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public final class SenderReach {

private static final String TAG = "SenderReach";

/** One check: does the sender answer, did this check use the repair, and why not, for the log. */
public static final class Result {
public final boolean answers;
public final boolean repaired;
public final String why; // the last connect error, null when the sender answers

Result(boolean answers, boolean repaired, String why) {
this.answers = answers;
this.repaired = repaired;
this.why = why;
}
}

/** One connect: its outcome and the error text. */
private static final class Try {
final Outcome outcome;
final String why;

Try(Outcome outcome, String why) {
this.outcome = outcome;
this.why = why;
}
}

private SenderReach() {
}

/**
* Connects to {@code host:port}. The caller owns the run of failed checks: {@code triedInThisRun}
* comes from DirectLinkRepair.triedAfter, or false for a check that starts its own run.
*/
public static Result connect(Context c, String host, int port, int timeoutMs, boolean triedInThisRun) {
if (host == null) return new Result(false, false, "no address");
Try first = attempt(host, port, timeoutMs);
if (first.outcome == Outcome.ANSWERS) return new Result(true, false, null);
WifiManager wm = (WifiManager) c.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (!DirectLinkRepair.shouldRepair(first.outcome, host.equals(gateway(wm)), triedInThisRun)
|| !dropDirectLink(wm, host)) {
return new Result(false, false, first.why);
}
Try second = attempt(host, port, timeoutMs);
return new Result(second.outcome == Outcome.ANSWERS, true, second.why);
}

/** The Wi-Fi gateway (a router, or the sender on its own hotspot), or null with no DHCP lease. */
@SuppressWarnings("deprecation") // getDhcpInfo: no permission needed for the gateway
public static String gateway(WifiManager wm) {
int le = wm != null ? wm.getDhcpInfo().gateway : 0;
if (le == 0) return null;
return (le & 0xFF) + "." + ((le >> 8) & 0xFF) + "." + ((le >> 16) & 0xFF) + "." + ((le >> 24) & 0xFF);
}

private static Try attempt(String host, int port, int timeoutMs) {
try (Socket s = new Socket()) {
s.connect(new InetSocketAddress(host, port), timeoutMs);
return new Try(Outcome.ANSWERS, null);
} catch (Exception e) {
// No log here: before pairing the receiver checks the router every few seconds.
// Android reports a refusal as ConnectException "... ECONNREFUSED (Connection refused)".
String why = String.valueOf(e.getMessage());
boolean refused = e instanceof ConnectException && why.contains("ECONNREFUSED");
return new Try(refused ? Outcome.REFUSED : Outcome.NO_ANSWER, why);
}
}

/** False on a phone without TDLS: then there is no link to drop. */
private static boolean dropDirectLink(WifiManager wm, String host) {
if (wm == null || !wm.isTdlsSupported()) return false;
try {
wm.setTdlsEnabled(InetAddress.getByName(host), false); // a literal address: no DNS
Log.i(TAG, "dropped the direct Wi-Fi link to " + host);
return true;
} catch (Exception e) {
Log.w(TAG, "could not drop the direct Wi-Fi link: " + e.getMessage());
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* ============================================================================
* Name : DirectLinkRepair.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : When does the receiver drop the direct Wi-Fi link (TDLS) to
* the sender and try once more (K2GO-587)? Pure JVM.
* Only a connect with no answer points to a dead direct link: a
* refusal proves that packets reach the sender. The gateway (a
* router, or the sender's own hotspot) has no direct link. One
* repair per run of failed checks; an answer ends the run.
* ============================================================================
*/
package org.appdevforall.k2go.sync.cable.domain;

public final class DirectLinkRepair {

/** The result of one connect to the sender. */
public enum Outcome { ANSWERS, REFUSED, NO_ANSWER }

private DirectLinkRepair() {
}

/** Drop the direct link and connect once more? */
public static boolean shouldRepair(Outcome first, boolean hostIsGateway, boolean triedInThisRun) {
return first == Outcome.NO_ANSWER && !hostIsGateway && !triedInThisRun;
}

/** Is a repair already used in this run, after a check that {@code repaired} and got {@code answers}? */
public static boolean triedAfter(boolean tried, boolean repaired, boolean answers) {
return !answers && (tried || repaired);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

public final class PeerAlive {

/** Each side sends PING every 2 s; three missed PINGs mean the peer is gone. */
public static final long DEAD_MS = 6_000;
/** Each side sends PING this often (K2GO-587). */
public static final long PING_MS = 1_000;

/** Three missed PINGs mean the peer is gone. */
public static final long DEAD_MS = 3 * PING_MS;

private PeerAlive() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@
import org.appdevforall.k2go.R;
import org.appdevforall.k2go.hotspot.LocalHotspotManager;
import org.appdevforall.k2go.sync.cable.data.CableSession;
import org.appdevforall.k2go.sync.cable.data.SenderReach;
import org.appdevforall.k2go.sync.cable.data.ShareLogWatch;
import org.appdevforall.k2go.sync.cable.data.UsbPresence;
import org.appdevforall.k2go.sync.cable.domain.DirectLinkRepair;
import org.appdevforall.k2go.sync.cable.domain.LinkRule;
import org.appdevforall.k2go.sync.cable.domain.ShareSessions;
import org.appdevforall.k2go.sync.cable.domain.WifiLink;
import org.appdevforall.k2go.util.AppExecutors;

import java.net.InetSocketAddress;
import java.net.Socket;

public final class CloneLinkRows {

Expand All @@ -63,6 +63,7 @@ public final class CloneLinkRows {
/** The sender's address from its pairing data (QR or cable), or null before pairing. */
private volatile String senderHost;
private volatile boolean probeOnce;
private volatile boolean repairTried; // DirectLinkRepair.triedAfter: the run of "no" used its repair
private boolean inFlight; // main thread only: one check at a time
private final Runnable check = this::checkWifi;

Expand Down Expand Up @@ -160,8 +161,9 @@ public void showSender(boolean hotspotMode, LocalHotspotManager.State hs) {

/**
* Receiver: checks the Wi-Fi every few seconds until stopChecks(). With {@code probeSender}
* false (during a transfer) it does not connect to the sender's daemon, which allows only a few
* connections; it keeps the last answer and still follows Wi-Fi on/off and the band.
* false (during a transfer) it keeps a "yes" without a new connection, because the sender's
* daemon allows only a few; a "no" is checked again until its repair is used (a failed connect
* takes no connection). It still follows Wi-Fi on/off and the band.
*/
public void startChecks(int senderRsyncPort, boolean probeSender) {
senderSide = false;
Expand All @@ -180,6 +182,7 @@ public void setSenderHost(String host) {
if (host == null ? senderHost == null : host.equals(senderHost)) return;
senderHost = host;
probeOnce = host != null;
repairTried = false; // a new sender gets its own repair
}

public void stopChecks() {
Expand All @@ -197,13 +200,22 @@ private void checkWifi() {
WifiManager wm = (WifiManager) app.getSystemService(Context.WIFI_SERVICE);
boolean on = wm != null && wm.isWifiEnabled();
int freq = on ? wm.getConnectionInfo().getFrequency() : -1;
boolean probeNow = probeSender || probeOnce;
probeOnce = false;
String host = senderHost;
String gw = on ? gateway(wm.getDhcpInfo().gateway) : null;
// During a transfer a "no" is checked again only while its repair is unused.
boolean probeNow = probeSender || probeOnce || (host != null && !lastAnswers && !repairTried);
probeOnce = false;
String gw = on ? SenderReach.gateway(wm) : null;
boolean viaHotspot = host == null || host.equals(gw); // the hotspot gateway is the sender
String target = host != null ? host : gw;
boolean answers = on && (probeNow ? senderAnswers(target, port) : lastAnswers);
boolean answers = lastAnswers;
if (probeNow && on) {
// Phone to phone through a home router can take over a second (K2GO-576 tests).
SenderReach.Result r = SenderReach.connect(app, target, port, 3000, repairTried);
answers = r.answers;
repairTried = DirectLinkRepair.triedAfter(repairTried, r.repaired, r.answers);
} else if (!on) {
answers = false;
}
lastAnswers = answers;
if (probeNow) lastProbed = on ? target : null;
if (probeNow) CableSession.get().reportWifi(answers); // the sender shows the same verdict
Expand All @@ -218,10 +230,9 @@ private void checkWifi() {
});
}

/** The hotspot gateway (the sender on its own hotspot), or null with no DHCP lease. */
private static String gateway(int le) {
if (le == 0) return null;
return (le & 0xFF) + "." + ((le >> 8) & 0xFF) + "." + ((le >> 16) & 0xFF) + "." + ((le >> 24) & 0xFF);
/** The phone is on a Wi-Fi network: the same signal that shows the band in the Wi-Fi row. */
public static boolean onWifiNetwork(Context c) {
return WifiLink.band(ownFrequency(c)) != WifiLink.Band.NONE;
}

@SuppressWarnings("deprecation")
Expand All @@ -235,17 +246,6 @@ private static String rate(long bytesPerSec) {
return String.format(java.util.Locale.ROOT, "%.1fMB/s", bytesPerSec / 1e6);
}

private static boolean senderAnswers(String host, int port) {
if (host == null) return false;
try (Socket s = new Socket()) {
// Phone to phone through a home router can take over a second (K2GO-576 tests).
s.connect(new InetSocketAddress(host, port), 3000);
return true;
} catch (Exception e) {
return false;
}
}

/**
* Receiver, during a pull: what each path carries. A Wi-Fi path that moves data is proof that
* the sender answers on Wi-Fi, so the row shows it even while the daemon probe is paused.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@
import org.appdevforall.k2go.hotspot.LocalHotspotManager;
import org.appdevforall.k2go.sync.cable.data.CableSession;
import org.appdevforall.k2go.sync.cable.data.ChunkedPull;
import org.appdevforall.k2go.sync.cable.data.SenderReach;
import org.appdevforall.k2go.sync.domain.ShareConfig;
import org.appdevforall.k2go.sync.transport.NetworkInterfaces;
import org.appdevforall.k2go.sync.transport.TransportEngine;
import org.appdevforall.k2go.sync.transport.WifiNetworkBinder;
import org.appdevforall.k2go.util.AppExecutors;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SyncStateViewModel extends ViewModel {

Expand Down Expand Up @@ -112,15 +111,10 @@ public void startProbe(Context appCtx, ShareConfig shareConfig, SyncHandshakeHel
// (Wi-Fi/hotspot) is flagged "no internet" and Android gives the app no default network.
WifiNetworkBinder.bindToHostNetwork(appCtx, creds.ip);

boolean reachable = false;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(creds.ip, creds.port), 2000);
socket.close();
reachable = true;
} catch (Exception e) {
Log.w(TAG, "Reachability probe to " + creds.ip + ":" + creds.port + " failed", e);
}
// A pull start is its own run of checks: it may use one direct-link repair (K2GO-587).
SenderReach.Result reach = SenderReach.connect(appCtx, creds.ip, creds.port, 2000, false);
boolean reachable = reach.answers;
if (!reachable) Log.w(TAG, "Reachability probe to " + creds.ip + ":" + creds.port + " failed: " + reach.why);
// K2GO-576: no Wi-Fi path, but a cable link: the dry-run goes over the cable.
String probeHost = creds.ip;
int probePort = creds.port;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ private static final class FakePort implements HotspotMode.Port {
@Override public boolean releaseDropsClients() { return dropsClients; }
}

@Test
public void startsOnTheWifiNetworkOnlyWhenThePhoneIsOnOne() {
assertEquals(HotspotMode.Mode.WIFI, HotspotMode.initialFor(true));
assertEquals(HotspotMode.Mode.HOTSPOT, HotspotMode.initialFor(false));
}

@Test
public void hotspotHoldsAndWifiReleases() {
FakePort port = new FakePort();
Expand Down
Loading
Loading