| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package system |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "net" |
| 20 | "os/exec" |
| 21 | "strings" |
| 22 | "time" |
| 23 | ) |
| 24 |
| 25 | func EnableCompatibilityMode() { |
| 26 | fixTimezone() |
| 27 | fixDNSResolver() |
| 28 | } |
| 29 |
| 30 | // fixTimezone is used to try our best to fix timezone issue on some Android devices. |
| 31 | func fixTimezone() { |
| 32 | out, err := exec.Command("/system/bin/getprop", "persist.sys.timezone").Output() |
| 33 | if err != nil { |
| 34 | return |
| 35 | } |
| 36 | loc, err := time.LoadLocation(strings.TrimSpace(string(out))) |
| 37 | if err != nil { |
| 38 | return |
| 39 | } |
| 40 | time.Local = loc |
| 41 | } |
| 42 |
| 43 | // fixDNSResolver will first attempt to resolve google.com to check if the current DNS is available. |
| 44 | // If it is not available, it will default to using 8.8.8.8 as the DNS server. |
| 45 | // This is a workaround for the issue that golang can't get the default DNS servers on Android. |
| 46 | func fixDNSResolver() { |
| 47 | // First, we attempt to resolve a domain. If resolution is successful, no modifications are necessary. |
| 48 | // In real-world scenarios, users may have already configured /etc/resolv.conf, or compiled directly |
| 49 | // in the Android environment instead of using cross-platform compilation, so this issue does not arise. |
| 50 | if net.DefaultResolver != nil { |
| 51 | timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 52 | defer cancel() |
| 53 | _, err := net.DefaultResolver.LookupHost(timeoutCtx, "google.com") |
| 54 | if err == nil { |
| 55 | return |
| 56 | } |
| 57 | } |
| 58 | // If the resolution fails, use 8.8.8.8 as the DNS server. |
| 59 | // Note: If there are other methods to obtain the default DNS servers, the default DNS servers should be used preferentially. |
| 60 | net.DefaultResolver = &net.Resolver{ |
| 61 | PreferGo: true, |
| 62 | Dial: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 63 | if addr == "127.0.0.1:53" || addr == "[::1]:53" { |
| 64 | addr = "8.8.8.8:53" |
| 65 | } |
| 66 | var d net.Dialer |
| 67 | return d.DialContext(ctx, network, addr) |
| 68 | }, |
| 69 | } |
| 70 | } |