Merge pull request #2058 from wywywywycloud/feat/subscription-update-modes

feat: add per-subscription update policies and recovery
This commit is contained in:
Markson Hon authored and GitHub committed 2026-11-15 22:02:46 +08:00
commit b0299f138c
55 files changed
+3125 -454

No files matched your search

+12 -3
View File
@@ -42,7 +42,12 @@ export const deleteTouch = (touches: Which[]) =>
// The editor sends `which: null` for a new node, as the old page did; the
// key stays in the body. Saving one node has no time limit, a batch has.
export const postImport = (
body: { url: string; kind?: string; which?: Which | null },
body: {
url: string;
kind?: string;
which?: Which | null;
bypassProxy?: boolean;
},
timeout: number = timeouts.import,
) =>
call<TouchResponse>({ url: "import", method: "post", data: body, timeout });
@@ -52,8 +57,12 @@ export const getSharingAddress = (touch: Which) =>
method: "get",
params: { touch },
});
export const putSubscription = (which: Which) =>
call<TouchResponse>({ url: "subscription", method: "put", data: which });
export const putSubscription = (which: Which, bypassProxy = false) =>
call<TouchResponse>({
url: "subscription",
method: "put",
data: bypassProxy ? { ...which, bypassProxy: true } : which,
});
export const patchSubscription = (body: Record<string, unknown>) =>
call<TouchResponse>({ url: "subscription", method: "patch", data: body });
export const getPingLatency = (whiches: Which[]) =>
+4
View File
@@ -40,6 +40,10 @@ export interface TouchSubscription {
info: string;
servers: TouchServer[];
autoSelect: boolean;
updateMode?: "disabled" | "on_start" | "at_interval" | "interval_failsafe";
updateIntervalMinutes?: number;
failureIntervalMinutes?: number;
allowDirectRecovery?: boolean;
}
/** touch.Touch */
+1
View File
@@ -18,3 +18,4 @@ export { useTraffic } from "./useTraffic";
export { useOutboundGroups } from "./useOutboundGroups";
export { useUnsavedGuard } from "./useUnsavedGuard";
export { useHotkeys, focusInput } from "./useHotkeys";
export { useSubscriptionBypass } from "./useSubscriptionBypass";
@@ -0,0 +1,125 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { defineComponent, h } from "vue";
import { flushPromises, type VueWrapper } from "@vue/test-utils";
import type * as Api from "@/api";
import { getSetting } from "@/api";
import ConfirmDialog from "@/components/hosts/ConfirmDialog.vue";
import { mountWithApp } from "@/test/mount";
import { useAppStore, type Running } from "@/stores/app";
import { closeAllDialogs, closeDialog, dialogState } from "./useDialog";
import { useSubscriptionBypass } from "./useSubscriptionBypass";
vi.mock("@/api", async (original) => ({
...(await original<typeof Api>()),
getSetting: vi.fn(),
}));
let wrapper: VueWrapper;
let chooseBypass: (all?: boolean) => Promise<boolean | null>;
const Probe = defineComponent({
setup() {
chooseBypass = useSubscriptionBypass();
return () => h("div");
},
});
function setting(proxyModeWhenSubscribe?: string) {
return {
setting: {
transparent: "close",
transparentType: "tproxy",
pacMode: "whitelist",
logLevel: "info",
proxyModeWhenSubscribe,
},
localGFWListVersion: "",
localGeositeVersion: "",
};
}
beforeEach(() => {
vi.clearAllMocks();
closeAllDialogs();
wrapper = mountWithApp(Probe);
});
afterEach(() => {
wrapper.unmount();
closeAllDialogs();
});
describe("useSubscriptionBypass", () => {
test.each<Running>(["checking", "running", "paused"])(
"uses the configured route without loading settings while the core is %s",
async (running) => {
useAppStore().setRunning(running);
await expect(chooseBypass()).resolves.toBe(false);
expect(getSetting).not.toHaveBeenCalled();
expect(dialogState.stack).toHaveLength(0);
},
);
test("uses direct mode without asking when the core is stopped", async () => {
useAppStore().setRunning("stopped");
vi.mocked(getSetting).mockResolvedValue(setting("direct"));
await expect(chooseBypass()).resolves.toBe(false);
expect(getSetting).toHaveBeenCalledOnce();
expect(dialogState.stack).toHaveLength(0);
});
test.each(["proxy", "pac"])(
"returns true after confirmation for stopped-core %s mode",
async (mode) => {
useAppStore().setRunning("stopped");
vi.mocked(getSetting).mockResolvedValue(setting(mode));
const result = chooseBypass();
await flushPromises();
const dialog = dialogState.stack.at(-1)!;
expect(dialog.component).toBe(ConfirmDialog);
expect(dialog.props).toMatchObject({
message: "The core is stopped. Update without the proxy?",
confirmText: "Yes",
cancelText: "No",
});
closeDialog(dialog.id, true);
await expect(result).resolves.toBe(true);
},
);
test("returns null when direct access is declined", async () => {
useAppStore().setRunning("stopped");
vi.mocked(getSetting).mockResolvedValue(setting("proxy"));
const result = chooseBypass();
await flushPromises();
closeDialog(dialogState.stack.at(-1)!.id, false);
await expect(result).resolves.toBeNull();
});
test("words the confirmation for every subscription when asked for all", async () => {
useAppStore().setRunning("stopped");
vi.mocked(getSetting).mockResolvedValue(setting("proxy"));
const result = chooseBypass(true);
await flushPromises();
const dialog = dialogState.stack.at(-1)!;
expect(dialog.component).toBe(ConfirmDialog);
expect(dialog.props).toMatchObject({
message: "The core is stopped. Update all subscriptions without the proxy?",
confirmText: "Yes",
cancelText: "No",
});
closeDialog(dialog.id, true);
await expect(result).resolves.toBe(true);
});
});
@@ -0,0 +1,26 @@
import { getSetting } from "@/api";
import { useAppStore } from "@/stores/app";
import { useI18n } from "vue-i18n";
import { useConfirm } from "./useConfirm";
/** Returns true for a confirmed one-request direct fetch, false for the configured route, and null on cancel. */
export function useSubscriptionBypass() {
const store = useAppStore();
const confirm = useConfirm();
const { t } = useI18n();
return async (all = false): Promise<boolean | null> => {
if (store.running !== "stopped") return false;
const mode = (await getSetting()).setting.proxyModeWhenSubscribe;
if (mode !== "proxy" && mode !== "pac") return false;
return (await confirm({
message: all
? t("subscription.coreStoppedDirectAll")
: t("subscription.coreStoppedDirect"),
confirmText: t("operations.yes"),
cancelText: t("operations.no"),
}))
? true
: null;
};
}
+90
View File
@@ -0,0 +1,90 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { flushPromises, type VueWrapper } from "@vue/test-utils";
import type * as Api from "@/api";
import { getSetting, postImport } from "@/api";
import {
closeAllDialogs,
closeDialog,
dialogState,
} from "@/composables/useDialog";
import { closeAllNotices } from "@/composables/useNotify";
import { useAppStore } from "@/stores/app";
import { mountWithApp } from "@/test/mount";
import ImportDialog from "./Import.vue";
vi.mock("@/api", async (original) => ({
...(await original<typeof Api>()),
getSetting: vi.fn(),
postImport: vi.fn(),
}));
let wrapper: VueWrapper;
const address = "https://subscription.example/list";
beforeEach(() => {
vi.clearAllMocks();
closeAllDialogs();
closeAllNotices();
vi.mocked(getSetting).mockResolvedValue({
setting: {
transparent: "close",
transparentType: "tproxy",
pacMode: "whitelist",
logLevel: "info",
proxyModeWhenSubscribe: "proxy",
},
localGFWListVersion: "",
localGeositeVersion: "",
});
vi.mocked(postImport).mockResolvedValue({} as never);
wrapper = mountWithApp(ImportDialog, {
props: { kind: "subscription" },
});
useAppStore().setRunning("stopped");
});
afterEach(() => {
wrapper.unmount();
closeAllDialogs();
closeAllNotices();
});
async function submit() {
await wrapper.get("textarea").setValue(address);
await wrapper
.findAll("button")
.find((button) => button.text() === "Import")!
.trigger("click");
await flushPromises();
}
describe("subscription import with a stopped core", () => {
test("sends one explicit proxy bypass after Yes", async () => {
await submit();
expect(postImport).not.toHaveBeenCalled();
closeDialog(dialogState.stack.at(-1)!.id, true);
await flushPromises();
expect(postImport).toHaveBeenCalledExactlyOnceWith({
url: address,
kind: "subscription",
bypassProxy: true,
});
expect(wrapper.emitted("close")).toEqual([[true]]);
});
test("keeps the import open and sends nothing after No", async () => {
await submit();
closeDialog(dialogState.stack.at(-1)!.id, false);
await flushPromises();
expect(postImport).not.toHaveBeenCalled();
expect(wrapper.emitted("close")).toBeUndefined();
expect(wrapper.get<HTMLTextAreaElement>("textarea").element.value).toBe(
address,
);
});
});
+10 -1
View File
@@ -9,6 +9,7 @@ import { postImport } from "@/api";
import { ApiError } from "@/api/client";
import { errorText } from "@/api/errors";
import { useNotify } from "@/composables/useNotify";
import { useSubscriptionBypass } from "@/composables/useSubscriptionBypass";
defineOptions({ name: "ImportDialog" });
const props = defineProps<{
@@ -18,6 +19,7 @@ const props = defineProps<{
const emit = defineEmits<{ close: [imported?: boolean] }>();
const { t } = useI18n();
const notify = useNotify();
const subscriptionBypass = useSubscriptionBypass();
const kind = ref<"server" | "subscription">(props.kind ?? "server");
const text = ref("");
@@ -28,7 +30,14 @@ async function submit(url = text.value.trim()) {
if (!url || importing.value) return;
importing.value = true;
try {
await postImport({ url, kind: kind.value });
const bypassProxy =
kind.value === "subscription" ? await subscriptionBypass() : false;
if (bypassProxy === null) return;
await postImport({
url,
kind: kind.value,
...(bypassProxy ? { bypassProxy: true } : {}),
});
notify.success(t("import.success"));
emit("close", true);
} catch (err) {
+174
View File
@@ -0,0 +1,174 @@
// @vitest-environment happy-dom
import { afterEach, expect, test, vi } from "vitest";
import { flushPromises, type VueWrapper } from "@vue/test-utils";
import { VSelect, VSwitch } from "vuetify/components";
import type * as Api from "@/api";
import type { TouchSubscription } from "@/api/types";
import { patchSubscription } from "@/api";
import { mountWithApp } from "@/test/mount";
import Subscription from "./Subscription.vue";
vi.mock("@/api", async (original) => ({
...(await original<typeof Api>()),
patchSubscription: vi.fn().mockResolvedValue(undefined),
}));
let wrapper: VueWrapper;
afterEach(() => {
wrapper?.unmount();
vi.clearAllMocks();
});
const subscription = {
id: 1,
_type: "subscription" as const,
host: "example.test",
status: "",
info: "",
address: "https://example.test/sub",
remarks: "keep",
servers: [],
autoSelect: false,
updateMode: "disabled" as const,
updateIntervalMinutes: 0,
failureIntervalMinutes: 1,
};
test("offers four modes and only shows fields required by the mode", async () => {
wrapper = mountWithApp(Subscription, { props: { subscription } });
const mode = wrapper.findComponent(VSelect);
expect(mode.props("items")).toHaveLength(4);
expect(wrapper.findAll('input[type="number"]')).toHaveLength(0);
expect(wrapper.findAllComponents(VSwitch)).toHaveLength(1);
expect(
wrapper
.findAllComponents(VSwitch)
.some(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
),
).toBe(false);
mode.vm.$emit("update:modelValue", "at_interval");
await flushPromises();
expect(wrapper.findAll('input[type="number"]')).toHaveLength(1);
expect(
wrapper
.findAllComponents(VSwitch)
.some(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
),
).toBe(false);
mode.vm.$emit("update:modelValue", "interval_failsafe");
await flushPromises();
const inputs = wrapper.findAll('input[type="number"]');
expect(inputs).toHaveLength(2);
expect(
wrapper
.findAllComponents(VSwitch)
.find(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
)!
.props("modelValue"),
).toBe(false);
await inputs[0].setValue("15");
await inputs[1].setValue("2");
await wrapper
.findAll("button")
.find((button) => button.text() === "Save and Apply")!
.trigger("click");
await flushPromises();
expect(patchSubscription).toHaveBeenCalledWith({
subscription: {
...subscription,
updateMode: "interval_failsafe",
updateIntervalMinutes: 15,
failureIntervalMinutes: 2,
allowDirectRecovery: false,
},
});
});
test("persists explicit direct-recovery consent and restores it when reopening", async () => {
wrapper = mountWithApp(Subscription, {
props: {
subscription: {
...subscription,
updateMode: "interval_failsafe",
updateIntervalMinutes: 15,
},
},
});
wrapper
.findAllComponents(VSwitch)
.find(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
)!
.vm.$emit("update:modelValue", true);
await flushPromises();
await wrapper
.findAll("button")
.find((button) => button.text() === "Save and Apply")!
.trigger("click");
await flushPromises();
const saved = vi.mocked(patchSubscription).mock.calls[0][0]
.subscription as TouchSubscription;
expect(saved.allowDirectRecovery).toBe(true);
wrapper.unmount();
wrapper = mountWithApp(Subscription, { props: { subscription: saved } });
expect(
wrapper
.findAllComponents(VSwitch)
.find(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
)!
.props("modelValue"),
).toBe(true);
wrapper
.findAllComponents(VSwitch)
.find(
(control) =>
control.props("label") ===
"Ignore subscription download routing during recovery",
)!
.vm.$emit("update:modelValue", false);
await flushPromises();
await wrapper
.findAll("button")
.find((button) => button.text() === "Save and Apply")!
.trigger("click");
await flushPromises();
expect(vi.mocked(patchSubscription).mock.calls[1][0].subscription).toEqual(
expect.objectContaining({ allowDirectRecovery: false }),
);
});
test.each(["", "0", "0.5"])(
"rejects invalid regular interval %s",
async (value) => {
wrapper = mountWithApp(Subscription, {
props: {
subscription: {
...subscription,
updateMode: "at_interval" as const,
},
},
});
await wrapper.find('input[type="number"]').setValue(value);
await wrapper
.findAll("button")
.find((button) => button.text() === "Save and Apply")!
.trigger("click");
await flushPromises();
expect(patchSubscription).not.toHaveBeenCalled();
},
);
+115 -21
View File
@@ -1,8 +1,6 @@
<script setup lang="ts">
// Edit a subscription: its address, remarks and whether new nodes are
// connected automatically after an update. Saves with PATCH
// /subscription and resolves true.
import { reactive, ref } from "vue";
// Subscription refresh policy and the existing PROXY auto-selection option.
import { computed, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { patchSubscription } from "@/api";
import { errorText } from "@/api/errors";
@@ -16,11 +14,58 @@ const { t } = useI18n();
const notify = useNotify();
// the old page sent the row with its servers emptied
const form = reactive({ ...props.subscription, servers: [] });
const form = reactive({
updateMode: "disabled" as NonNullable<TouchSubscription["updateMode"]>,
updateIntervalMinutes: 0,
failureIntervalMinutes: 1,
allowDirectRecovery: false,
...props.subscription,
servers: [],
});
const updateModes = computed(() => [
{ value: "disabled", title: t("subscription.updateModes.disabled") },
{ value: "on_start", title: t("subscription.updateModes.onStart") },
{ value: "at_interval", title: t("subscription.updateModes.interval") },
{
value: "interval_failsafe",
title: t("subscription.updateModes.intervalFailsafe"),
},
]);
const needsRegularInterval = computed(
() =>
form.updateMode === "at_interval" ||
form.updateMode === "interval_failsafe",
);
const needsFailureInterval = computed(
() => form.updateMode === "interval_failsafe",
);
const updateModeHelp = computed(() => {
switch (form.updateMode) {
case "on_start":
return t("subscription.updateModeHelp.onStart");
case "at_interval":
return t("subscription.updateModeHelp.interval");
case "interval_failsafe":
return t("subscription.updateModeHelp.intervalFailsafe");
default:
return t("subscription.updateModeHelp.disabled");
}
});
const saving = ref(false);
const validation = ref<{ validate(): Promise<{ valid: boolean }> } | null>(
null,
);
const intervalRule = (minimum: number) => (v: unknown) =>
(v !== "" &&
v !== null &&
Number.isInteger(Number(v)) &&
Number(v) >= minimum &&
Number(v) <= 525600) ||
t("subscription.intervalInvalid", { minimum });
async function save() {
if (saving.value) return;
if (!(await validation.value?.validate())?.valid) return;
saving.value = true;
try {
await patchSubscription({ subscription: form });
@@ -42,22 +87,71 @@ async function save() {
</v-card-title>
</v-card-item>
<v-card-text class="px-6">
<v-textarea
v-model="form.address"
:label="t('subscription.subscription')"
rows="2"
auto-grow
dir="ltr"
@keydown.enter="
(e: KeyboardEvent) => (e.ctrlKey || e.metaKey) && save()
"
/>
<v-text-field v-model="form.remarks" :label="t('subscription.remarks')" />
<v-switch
v-model="form.autoSelect"
:label="t('subscription.autoSelect')"
hide-details
/>
<v-form ref="validation" @submit.prevent="save">
<v-textarea
v-model="form.address"
:label="t('subscription.subscription')"
rows="2"
auto-grow
dir="ltr"
@keydown.enter="
(e: KeyboardEvent) => (e.ctrlKey || e.metaKey) && save()
"
/>
<v-text-field
v-model="form.remarks"
:label="t('subscription.remarks')"
/>
<v-select
v-model="form.updateMode"
:items="updateModes"
:label="t('subscription.updateMode')"
/>
<p class="md3-body-large mb-4">
{{ updateModeHelp }}
</p>
<div v-if="needsRegularInterval" style="padding-bottom: 28px">
<v-text-field
v-model.number="form.updateIntervalMinutes"
type="number"
min="1"
max="525600"
step="1"
:label="t('subscription.updateIntervalMinutes')"
:rules="[intervalRule(1)]"
:hint="t('subscription.regularHelp')"
persistent-hint
/>
</div>
<div v-if="needsFailureInterval" style="padding-bottom: 16px">
<v-text-field
v-model.number="form.failureIntervalMinutes"
type="number"
min="1"
max="525600"
step="1"
:label="t('subscription.failureIntervalMinutes')"
:rules="[intervalRule(1)]"
:hint="t('subscription.failureHelp')"
persistent-hint
/>
</div>
<div v-if="needsFailureInterval">
<v-switch
v-model="form.allowDirectRecovery"
:label="t('subscription.allowDirectRecovery')"
hide-details
/>
<p class="md3-body-small text-medium-emphasis mb-4">
{{ t("subscription.recoveryRouteHelp") }}
</p>
</div>
<v-switch
v-model="form.autoSelect"
:label="t('subscription.autoSelect')"
hide-details
/>
</v-form>
</v-card-text>
<v-card-actions class="px-6 pb-4">
<v-spacer />
+6 -31
View File
@@ -38,44 +38,19 @@ beforeEach(async () => {
await flushPromises();
});
afterEach(() => wrapper.unmount());
test("loads subscription values and saves all three changes without losing other settings", async () => {
test("only configures download transport; schedules belong to individual subscriptions", async () => {
const selects = wrapper.findAllComponents(VSelect);
expect(selects[0].props("modelValue")).toBe("auto_update");
expect(selects[1].props("modelValue")).toBe("pac");
selects[0].vm.$emit("update:modelValue", "auto_update_at_intervals");
await flushPromises();
expect(
(wrapper.get('input[type="number"]').element as HTMLInputElement).value,
).toBe("6");
await wrapper.get('input[type="number"]').setValue("12");
selects[1].vm.$emit("update:modelValue", "proxy");
expect(selects).toHaveLength(1);
expect(selects[0].props("modelValue")).toBe("pac");
expect(wrapper.findAll('input[type="number"]')).toHaveLength(0);
selects[0].vm.$emit("update:modelValue", "proxy");
await wrapper
.findAll("button")
.find((b) => b.text() === "Save")!
.trigger("click");
await flushPromises();
expect(putSetting).toHaveBeenCalledWith(
{
...loaded,
subscriptionAutoUpdateMode: "auto_update_at_intervals",
subscriptionAutoUpdateIntervalHour: 12,
proxyModeWhenSubscribe: "proxy",
},
{ ...loaded, proxyModeWhenSubscribe: "proxy" },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
expect(wrapper.emitted("close")).toEqual([[true]]);
});
test("does not save an empty or nonpositive update interval", async () => {
wrapper
.findAllComponents(VSelect)[0]
.vm.$emit("update:modelValue", "auto_update_at_intervals");
await flushPromises();
await wrapper.get('input[type="number"]').setValue("0");
await wrapper
.findAll("button")
.find((b) => b.text() === "Save")!
.trigger("click");
await flushPromises();
expect(putSetting).not.toHaveBeenCalled();
expect(wrapper.emitted("close")).toBeUndefined();
});
+1 -30
View File
@@ -3,12 +3,8 @@ import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { errorText } from "@/api/errors";
import { useNotify } from "@/composables";
import { required } from "@/dialogs/Server/forms/parts/rules";
import { useSettings } from "@/views/settings/model";
import {
subscriptionUpdateModes,
updateProxyModes,
} from "@/views/settings/options";
import { updateProxyModes } from "@/views/settings/options";
defineOptions({ name: "SubscriptionSettingsDialog" });
const emit = defineEmits<{ close: [saved?: boolean] }>();
@@ -21,7 +17,6 @@ const validation = ref<{ validate(): Promise<{ valid: boolean }> } | null>(
);
const saving = ref(false);
const loadError = ref("");
const modes = computed(() => subscriptionUpdateModes(t));
const proxyModes = computed(() =>
updateProxyModes(t, form.transparent === "close"),
);
@@ -71,30 +66,6 @@ async function save() {
:disabled="!ready || saving"
@submit.prevent="save"
>
<v-select
v-model="form.subscriptionAutoUpdateMode"
:label="t('setting.autoUpdateSub')"
:items="modes"
/>
<v-expand-transition>
<v-text-field
v-if="
form.subscriptionAutoUpdateMode === 'auto_update_at_intervals'
"
v-model.number="form.subscriptionAutoUpdateIntervalHour"
type="number"
min="1"
step="1"
dir="ltr"
:label="t('setting.options.updateSubAtIntervals')"
:rules="[
required,
(v) =>
(Number.isInteger(Number(v)) && Number(v) >= 1) ||
t('configureServer.required'),
]"
/>
</v-expand-transition>
<v-select
v-model="form.proxyModeWhenSubscribe"
:label="t('setting.preferModeWhenUpdate')"
+19
View File
@@ -54,3 +54,22 @@ The ports are changed under **Settings → Address and Ports**; 0 closes an inbo
- Logs: `Home`, `End`, `PgUp`, `PgDn` move through the log once it has focus.
On macOS `Cmd` stands for `Ctrl`.
## Automatic subscription updates
Each subscription has its own update mode:
- **Disabled:** update only when requested manually.
- **On service start:** update once whenever v2rayA starts.
- **At an interval:** update on startup and then after the configured number of minutes.
- **At an interval with fail-safe recovery:** use the regular schedule and also check the saved servers at the failure interval. When none works, refresh at that interval until at least one becomes available.
Failed or empty downloads keep the saved server list. A failure retry does not postpone the regular schedule, and a slow pass never overlaps another pass. On Linux, permitted recovery downloads outside the proxy use marked sockets so transparent proxying cannot route them back into a failed proxy. This bypass is not guaranteed for TUN mode on macOS or Windows. Candidate checks may start temporary core processes. With the legacy **Auto-select** option disabled, automatic updates leave a manually stopped main core stopped. In this release, enabling legacy **Auto-select** can still start the main core after an update; automatic group membership in the follow-up change removes this legacy behavior.
On upgrade, the previous global **update on start** mode is assigned to every existing subscription as **On service start**. The previous interval mode becomes **At an interval** with the same interval converted from hours to minutes. Fail-safe recovery is never enabled during migration; select it explicitly where needed.
An enabled schedule restarts immediately when the subscription address, update mode or intervals change. In particular, selecting **On service start** while v2rayA is running performs one update immediately, then waits until the next service start. Changing only the remarks does not reset the schedule.
Manual imports, manual updates and scheduled updates follow **Mode when updating subscriptions**. The saved proxy/PAC route never changes silently. If proxy/PAC is selected while the main core is stopped, a manual import or update asks whether to bypass the proxy and download directly for that request only; declining cancels the request. Scheduled updates keep the configured route. Only a fail-safe recovery attempt after an all-server outage can retry directly if the configured download route fails. Every such bypass is logged; the network can see the subscription service address. This requires the separate **Ignore subscription download routing during recovery** switch, which defaults to off for new and upgraded subscriptions. With it off, recovery keeps retrying through the configured proxy/PAC. With it on, the exception applies only to the subscription download, not to other traffic.
Plugin-managed candidates cannot be checked safely by the isolated probe worker. If any saved candidate cannot be probed, its health is unknown: fail-safe recovery is suspended for that subscription and a warning is logged once until the catalog becomes probeable again. Regular updates continue. Cancelling a health check or recovery request leaves a future deadline, so a dashboard latency test does not disable recovery.
+19
View File
@@ -54,3 +54,22 @@ v2raya --reset-password
- گزارش‌ها: پس از تمرکز، `Home`، `End`، `PgUp` و `PgDn` در گزارش حرکت می‌کنند.
در macOS، `Cmd` جای `Ctrl` را می‌گیرد.
## به‌روزرسانی خودکار اشتراک‌ها
برای هر اشتراک می‌توان حالت به‌روزرسانی جداگانه‌ای انتخاب کرد:
- **غیرفعال:** فقط با درخواست دستی به‌روزرسانی شود.
- **هنگام شروع سرویس:** با هر بار شروع v2rayA یک بار به‌روزرسانی شود.
- **در بازهٔ زمانی:** هنگام شروع و سپس پس از تعداد دقیقهٔ تعیین‌شده به‌روزرسانی شود.
- **در بازهٔ زمانی همراه با بازیابی خطا:** علاوه بر برنامهٔ منظم، سرورهای ذخیره‌شده در بازهٔ خطا بررسی شوند. اگر هیچ‌کدام کار نکند، اشتراک با همان بازه تازه‌سازی می‌شود تا دست‌کم یک سرور در دسترس باشد.
در صورت خطا یا دریافت پاسخ خالی، فهرست ذخیره‌شدهٔ سرورها حفظ می‌شود. تلاش‌های بازیابی برنامهٔ منظم را عقب نمی‌اندازند و یک بررسی طولانی با بررسی بعدی هم‌پوشانی ندارد. در Linux دریافت بازیابیِ مجاز بدون پراکسی از اتصال علامت‌گذاری‌شده استفاده می‌کند تا پراکسی شفاف آن را دوباره وارد پراکسی خراب نکند. این دور زدن برای حالت TUN در macOS یا Windows تضمین نمی‌شود. بررسی سرورها ممکن است هسته‌های موقت اجرا کند. وقتی گزینهٔ قدیمی **انتخاب خودکار** غیرفعال است، به‌روزرسانی هستهٔ اصلی متوقف‌شده را اجرا نمی‌کند. در این نسخه فعال بودن آن گزینه هنوز می‌تواند پس از به‌روزرسانی هسته را اجرا کند؛ تغییر بعدیِ عضویت خودکار گروه این رفتار قدیمی را حذف می‌کند.
پس از ارتقا، حالت سراسری قدیمی «به‌روزرسانی هنگام شروع» برای همهٔ اشتراک‌های موجود به حالت **هنگام شروع سرویس** تبدیل می‌شود. حالت بازه‌ای قدیمی به **در بازهٔ زمانی** تبدیل و ساعت به دقیقه تبدیل می‌شود. بازیابی خطا هنگام مهاجرت فعال نمی‌شود و باید در صورت نیاز دستی انتخاب شود.
تغییر نشانی اشتراک، حالت یا بازه‌ها برنامهٔ فعال را بلافاصله از نو شروع می‌کند. انتخاب **هنگام شروع سرویس** در حین اجرای v2rayA یک به‌روزرسانی فوری انجام می‌دهد و سپس تا شروع بعدی سرویس منتظر می‌ماند. تغییر توضیحات به‌تنهایی زمان‌بندی را عوض نمی‌کند.
وارد کردن و به‌روزرسانی دستی یا برنامه‌ریزی‌شده همیشه **حالت دریافت اشتراک** را رعایت می‌کنند و مسیر ذخیره‌شدهٔ proxy/PAC پنهانی تغییر نمی‌کند. اگر proxy/PAC انتخاب شده و هسته متوقف باشد، وارد کردن یا به‌روزرسانی دستی می‌پرسد آیا فقط برای همان درخواست، پراکسی دور زده و دریافت مستقیم انجام شود؛ پاسخ منفی درخواست را لغو می‌کند. به‌روزرسانی‌های برنامه‌ریزی‌شده همچنان از مسیر تعیین‌شده استفاده می‌کنند. فقط بازیابی پس از قطع همهٔ سرورها در صورت خرابی مسیر دریافت می‌تواند مستقیم دوباره تلاش کند. هر دور زدن گزارش می‌شود و شبکه نشانی سرویس اشتراک را می‌بیند. این کار به گزینهٔ جداگانهٔ **نادیده گرفتن مسیر دریافت اشتراک هنگام بازیابی** نیاز دارد که برای اشتراک‌های جدید و ارتقایافته پیش‌فرض غیرفعال است. بدون آن بازیابی از proxy/PAC تعیین‌شده دوباره تلاش می‌کند. با فعال بودن آن، استثنا فقط برای دریافت اشتراک است، نه ترافیک دیگر.
بررسی جداگانهٔ سرورهای مدیریت‌شده با افزونه امن نیست. اگر هر سرور ذخیره‌شده قابل بررسی نباشد، وضعیت نامعلوم است: بازیابی آن اشتراک متوقف و تا قابل بررسی شدن دوبارهٔ فهرست، یک هشدار ثبت می‌شود. به‌روزرسانی منظم ادامه دارد. لغو بررسی یا درخواست بازیابی موعد بعدی را حفظ می‌کند؛ پس آزمون تأخیر در داشبورد بازیابی را غیرفعال نمی‌کند.
+19
View File
@@ -54,3 +54,22 @@ TLS를 사용하는 VLESS 링크의 `ech` 매개변수는 가져오기, 편집
- 로그: 포커스가 있으면 `Home`, `End`, `PgUp`, `PgDn`으로 이동합니다.
macOS에서는 `Cmd`가 `Ctrl`을 대신합니다.
## 구독 자동 업데이트
각 구독마다 업데이트 모드를 선택할 수 있습니다.
- **사용 안 함:** 수동으로 요청할 때만 업데이트합니다.
- **서비스 시작 시:** v2rayA가 시작될 때마다 한 번 업데이트합니다.
- **주기적으로:** 시작할 때 업데이트한 뒤 설정한 분 간격으로 업데이트합니다.
- **주기적 업데이트 및 장애 복구:** 정기 일정에 더해 장애 간격으로 저장된 서버를 확인합니다. 모든 서버를 사용할 수 없으면 하나 이상 복구될 때까지 해당 간격으로 구독을 새로 고칩니다.
다운로드가 실패하거나 빈 응답을 받으면 저장된 서버 목록을 유지합니다. 장애 재시도는 정기 업데이트를 미루지 않으며, 오래 걸리는 확인 작업은 다음 작업과 겹쳐 실행되지 않습니다. Linux에서는 허용된 프록시 우회 복구 다운로드가 표시된 소켓을 사용하므로 투명 프록시가 요청을 고장 난 프록시로 다시 보내지 않습니다. macOS 또는 Windows의 TUN 모드에서는 이 우회가 보장되지 않습니다. 서버 확인은 임시 코어를 실행할 수 있습니다. 기존 **자동 선택**을 끄면 자동 업데이트가 수동으로 중지한 주 코어를 시작하지 않습니다. 이 버전에서 기존 **자동 선택**을 켜면 업데이트 후 주 코어가 시작될 수 있습니다. 후속 자동 그룹 구성 변경에서 이 동작이 제거됩니다.
업그레이드 시 기존 전역 “시작할 때 업데이트” 설정은 모든 기존 구독의 **서비스 시작 시** 모드로 이전됩니다. 기존 주기 모드는 시간을 분으로 변환한 **주기적으로** 모드가 됩니다. 장애 복구는 자동으로 활성화되지 않으므로 필요한 구독에서 직접 선택해야 합니다.
구독 주소, 업데이트 모드 또는 간격을 바꾸면 활성 일정이 즉시 다시 시작됩니다. 따라서 v2rayA 실행 중 **서비스 시작 시**를 선택하면 즉시 한 번 업데이트하고 다음 서비스 시작까지 기다립니다. 설명만 바꾸면 일정은 유지됩니다.
수동 가져오기, 수동 및 정기 업데이트는 **구독 업데이트 모드**를 따르며 저장된 proxy/PAC 경로는 몰래 바뀌지 않습니다. proxy/PAC를 선택한 상태에서 주 코어가 중지되면 수동 가져오기 또는 업데이트 시 해당 요청에 한해서만 프록시를 우회해 직접 다운로드할지 묻습니다. 거부하면 요청을 취소합니다. 정기 업데이트는 설정된 경로를 계속 사용합니다. 모든 서버가 중단된 뒤 장애 복구를 시도할 때만 설정된 다운로드 경로의 실패 후 직접 연결로 재시도할 수 있습니다. 각 우회는 기록되며 네트워크는 구독 서비스 주소를 볼 수 있습니다. 별도의 **장애 복구 중 구독 다운로드 경로 규칙 무시** 확인란이 필요하며 새 구독과 업그레이드된 구독 모두 기본값은 꺼짐입니다. 끄면 설정된 proxy/PAC로 복구를 계속 시도합니다. 켜면 예외가 구독 다운로드에만 적용되며 다른 트래픽에는 적용되지 않습니다.
플러그인 관리 노드는 격리된 검사로 안전하게 확인할 수 없습니다. 저장된 노드 중 하나라도 검사할 수 없으면 상태가 불명확하므로 해당 구독의 장애 복구를 중단하고 목록을 다시 검사할 수 있을 때까지 한 번 경고합니다. 정기 업데이트는 계속됩니다. 검사나 복구 요청을 취소해도 다음 실행 시각을 보존하므로 대시보드 지연 검사로 복구가 꺼지지 않습니다.
+19
View File
@@ -54,3 +54,22 @@ As portas são alteradas em **Configurações → Endereços e portas**; 0 fecha
- Registros: com foco, `Home`, `End`, `PgUp` e `PgDn` percorrem o registro.
No macOS, `Cmd` corresponde a `Ctrl`.
## Atualização automática de assinaturas
Cada assinatura tem seu próprio modo de atualização:
- **Desativada:** atualizar somente quando solicitado manualmente.
- **Ao iniciar o serviço:** atualizar uma vez sempre que o v2rayA iniciar.
- **Em um intervalo:** atualizar ao iniciar e depois do número de minutos configurado.
- **Em um intervalo com recuperação de falha:** seguir a programação regular e também verificar os servidores salvos no intervalo de falha. Quando nenhum funcionar, atualizar a assinatura nesse intervalo até que pelo menos um fique disponível.
Downloads com erro ou vazios preservam a lista de servidores salva. Uma tentativa de recuperação não adia a programação regular, e uma execução demorada nunca ocorre em paralelo com a próxima. No Linux, os downloads de recuperação autorizados fora do proxy usam conexões marcadas para que o proxy transparente não os encaminhe de volta ao proxy com falha. Esse desvio não é garantido no modo TUN do macOS ou Windows. As verificações podem iniciar núcleos temporários. Com a opção antiga **Seleção automática** desativada, as atualizações mantêm o núcleo principal parado manualmente. Nesta versão, ativar essa opção antiga ainda pode iniciar o núcleo após uma atualização; a mudança posterior de membros automáticos do grupo remove esse comportamento.
Na atualização, o modo global antigo **ao iniciar** é atribuído a todas as assinaturas existentes como **Ao iniciar o serviço**. O modo antigo por intervalo passa a **Em um intervalo**, com as horas convertidas em minutos. A recuperação de falha nunca é ativada pela migração; selecione-a manualmente onde for necessária.
Alterar o endereço, o modo ou os intervalos reinicia imediatamente uma programação ativa. Selecionar **Ao iniciar o serviço** com o v2rayA em execução atualiza uma vez imediatamente e depois aguarda o próximo início do serviço. Alterar apenas as observações não reinicia a programação.
Importações e atualizações manuais ou programadas seguem o **Modo ao atualizar assinaturas**; a rota proxy/PAC salva nunca muda silenciosamente. Se proxy/PAC estiver selecionado enquanto o núcleo estiver parado, uma importação ou atualização manual perguntará se deve ignorar o proxy e baixar diretamente somente nessa solicitação; recusar cancela a solicitação. As atualizações programadas mantêm a rota configurada. Somente uma tentativa de recuperação após a falha de todos os servidores pode repetir diretamente se a rota de download falhar. Cada desvio é registrado; a rede pode ver o endereço do serviço de assinatura. Isso exige a opção separada **Ignorar a rota de download da assinatura durante a recuperação**, desativada por padrão para assinaturas novas e atualizadas. Sem ela, a recuperação continua tentando pelo proxy/PAC configurado. Com ela, a exceção vale apenas para baixar a assinatura, não para outro tráfego.
Candidatos gerenciados por plugins não podem ser verificados com segurança pelo processo isolado. Se algum candidato salvo não puder ser verificado, a saúde é desconhecida: a recuperação da assinatura é suspensa e um aviso é registrado uma vez até que o catálogo possa ser verificado novamente. As atualizações regulares continuam. Cancelar uma verificação ou download de recuperação preserva um prazo futuro; o teste de latência do painel não desativa a recuperação.
+19
View File
@@ -54,3 +54,22 @@ v2raya --reset-password
- Журнал: при фокусе `Home`, `End`, `PgUp`, `PgDn` листают журнал.
В macOS вместо `Ctrl` — `Cmd`.
## Автоматическое обновление подписок
Для каждой подписки отдельно выбирается режим обновления:
- **Выключено:** обновлять только вручную.
- **При запуске службы:** обновлять один раз при каждом запуске v2rayA.
- **По интервалу:** обновлять при запуске, затем через заданное число минут.
- **По интервалу с аварийным восстановлением:** работать по обычному расписанию и дополнительно проверять сохранённые серверы по аварийному интервалу. Если не работает ни один, обновлять подписку с этим интервалом, пока не появится хотя бы один доступный сервер.
При ошибке или пустом ответе сохранённый список серверов не удаляется. Аварийные попытки не откладывают плановое обновление, а медленная проверка не запускается параллельно со следующей. В Linux разрешённое аварийное обновление мимо прокси использует помеченные соединения, поэтому прозрачный прокси не направляет его обратно в неисправную группу. Для режима TUN в macOS и Windows такой обход не гарантируется. Проверка серверов может запускать временные процессы ядра. При выключенном старом параметре **Автоматический выбор** автообновление оставляет остановленное вручную основное ядро остановленным. Если старый параметр включён, обновление пока может запустить основное ядро; последующее изменение с автонаполнением групп убирает это поведение.
При обновлении старый глобальный режим **при запуске** назначается всем существующим подпискам как **При запуске службы**. Старый режим по интервалу становится режимом **По интервалу**, а часы переводятся в минуты. Аварийное восстановление миграция не включает — его нужно выбрать вручную для нужных подписок.
Изменение адреса подписки, режима или интервалов сразу перезапускает включённое расписание. В частности, выбор **При запуске службы** при работающей v2rayA вызывает одно обновление сразу, затем следующее — при новом запуске службы. Изменение только примечаний не сбрасывает таймер.
Импорт, ручные и плановые обновления соблюдают **Режим при обновлении подписок**. Сохранённый маршрут proxy/PAC никогда не меняется незаметно. Если выбран proxy/PAC, а основное ядро остановлено, перед ручным импортом или обновлением появляется вопрос, обновить ли подписку мимо прокси: согласие отправляет только этот запрос напрямую, отказ отменяет его. Плановые обновления продолжают использовать выбранный маршрут. Только аварийное восстановление после отказа всех серверов может повторить обновление мимо прокси, если выбранный путь не работает. Каждый обход записывается в журнал; сети становится виден адрес сервиса подписки. Для этого нужна отдельная галочка **Игнорировать правило обновления подписки при аварийном обновлении**; у новых и обновлённых подписок она выключена по умолчанию. Без неё восстановление продолжает попытки через выбранный proxy/PAC. С ней исключение касается только скачивания подписки, а не остального трафика.
Серверы внешних плагинов нельзя безопасно проверить изолированным worker. Если хотя бы один сохранённый сервер нельзя проверить, его состояние неизвестно: аварийное восстановление этой подписки приостанавливается, а предупреждение выводится один раз до возвращения проверяемого состава. Плановые обновления продолжаются. Отмена проверки или загрузки оставляет будущий таймер, поэтому проверка задержки с панели не отключает восстановление.
+19
View File
@@ -54,3 +54,22 @@ v2raya --reset-password
- 日志页获得焦点后 `Home`、`End`、`PgUp`、`PgDn` 翻动日志。
macOS 上 `Cmd` 对应 `Ctrl`。
## 自动更新订阅
每个订阅都可以单独选择更新模式:
- **关闭:** 仅在手动操作时更新。
- **服务启动时:** 每次 v2rayA 启动时更新一次。
- **按间隔:** 启动时更新一次,之后按设定的分钟间隔更新。
- **按间隔并启用故障恢复:** 按正常计划更新,并按故障间隔检查已保存的服务器。全部不可用时,按该间隔刷新订阅,直到至少一个服务器恢复可用。
下载失败或返回空内容时会保留已保存的服务器列表。故障重试不会推迟定时更新,耗时较长的一轮检查也不会与下一轮并行。在 Linux 上,获准绕过代理的恢复下载使用带标记的连接,透明代理不会把请求重新送入故障代理。macOS 或 Windows 的 TUN 模式不保证这种绕过方式。服务器检查可能启动临时核心进程。关闭旧的**自动选择**选项时,自动更新不会启动手动停止的主核心。在本版本中,启用旧的**自动选择**仍可能在更新后启动主核心;后续的自动分组成员功能将移除此旧行为。
升级时,旧的全局“启动时更新”会迁移为每个现有订阅的**服务启动时**模式;旧的定时模式会迁移为**按间隔**,并把小时换算为分钟。迁移不会自动启用故障恢复,需要时请手动选择。
修改订阅地址、更新模式或间隔会立即重新启动已启用的计划。因此,在 v2rayA 运行时选择**服务启动时**会立即更新一次,然后等待下次服务启动。仅修改备注不会重置计划。
手动导入、手动更新和定时更新始终遵循**更新订阅时的模式**,保存的 proxy/PAC 路由不会暗中更改。如果选择了 proxy/PAC 而主核心已停止,手动导入或更新会询问是否仅为本次请求绕过代理并直连下载;拒绝则取消请求。定时更新仍使用指定路由。只有在全部服务器不可用后的故障恢复尝试中,指定下载路径失败时才可改为直连。每次绕过都会记录日志;网络提供商可以看到订阅服务地址。必须单独勾选**故障恢复时忽略订阅下载路由规则**,新建和升级的订阅默认关闭。关闭时,恢复继续通过指定 proxy/PAC 重试。开启时,此例外仅用于订阅下载,不影响其他流量。
隔离检查无法安全检测插件管理的节点。只要有一个已保存节点无法检查,其状态即为未知:暂停该订阅的故障恢复,并记录一次警告,直到节点列表重新可检查。定时更新继续运行。取消检查或恢复请求会保留下一次执行时间,因此仪表盘延迟测试不会禁用恢复。
+28
View File
@@ -123,6 +123,34 @@ export default {
saveFailed: "Failed to save server: {message}",
},
subscription: {
updateMode: "Automatic subscription update",
updateModes: {
disabled: "Disabled",
onStart: "On service start",
interval: "At an interval",
intervalFailsafe: "At an interval with fail-safe recovery",
},
updateModeHelp: {
disabled: "The subscription changes only when you update it manually.",
onStart:
"Updates once whenever v2rayA starts and once immediately when you change the address or update policy.",
interval: "Updates on startup and then at the configured interval.",
intervalFailsafe:
"Updates on startup and at the regular interval. If every server becomes unavailable, retries at the failure interval until one works.",
},
allowDirectRecovery: "Ignore subscription download routing during recovery",
recoveryRouteHelp:
"Allows a direct download if recovery through the configured proxy fails. Manual and regular updates keep their selected route. Direct attempts are logged; your network can see the subscription service address.",
updateIntervalMinutes: "Regular interval (minutes)",
regularHelp: "Required. Enter a whole number of minutes, at least 1.",
failureIntervalMinutes: "Failure retry (minutes)",
failureHelp:
"Required, at least 1 minute. Refreshes while all servers are unavailable; stops retrying when one works.",
intervalInvalid: "Enter a whole number from {minimum} to 525600.",
coreStoppedDirect: "The core is stopped. Update without the proxy?",
coreStoppedDirectAll:
"The core is stopped. Update all subscriptions without the proxy?",
settingsTitle: "Subscription updates",
remarks: "Remarks",
numberServers: "Number of Servers",
+29 -1
View File
@@ -122,12 +122,40 @@ export default {
saveFailed: "ذخیره سرور ناموفق بود: {message}",
},
subscription: {
updateMode: "به‌روزرسانی خودکار اشتراک",
updateModes: {
disabled: "غیرفعال",
onStart: "هنگام شروع سرویس",
interval: "در بازهٔ زمانی",
intervalFailsafe: "در بازهٔ زمانی همراه با بازیابی خطا",
},
updateModeHelp: {
disabled: "اشتراک فقط با به‌روزرسانی دستی تغییر می‌کند.",
onStart:
"با هر شروع v2rayA و یک بار بلافاصله پس از تغییر نشانی یا سیاست به‌روزرسانی، اشتراک به‌روز می‌شود.",
interval: "هنگام شروع و سپس در بازهٔ زمانی تعیین‌شده به‌روزرسانی می‌شود.",
intervalFailsafe:
"هنگام شروع و در بازهٔ منظم به‌روزرسانی می‌شود. اگر همهٔ سرورهای اشتراک قطع باشند، تا زمان کار کردن یک سرور در بازهٔ خطا دوباره تلاش می‌کند.",
},
allowDirectRecovery: "نادیده گرفتن مسیر دریافت اشتراک هنگام بازیابی",
recoveryRouteHelp:
"اگر بازیابی از پراکسی تعیین‌شده شکست بخورد، دریافت مستقیم مجاز است. مسیر به‌روزرسانی دستی و منظم تغییر نمی‌کند. تلاش مستقیم گزارش می‌شود و شبکه نشانی سرویس اشتراک را می‌بیند.",
updateIntervalMinutes: "به‌روزرسانی منظم (دقیقه)",
regularHelp: "الزامی است. تعداد صحیحی از دقیقه، حداقل ۱، وارد کنید.",
failureIntervalMinutes: "تلاش پس از خطا (دقیقه)",
failureHelp:
"الزامی، حداقل ۱ دقیقه. وقتی همهٔ سرورها قطع هستند به‌روز می‌کند؛ با اتصال یک سرور تکرار متوقف می‌شود.",
intervalInvalid: "عددی صحیح از {minimum} تا 525600 وارد کنید.",
coreStoppedDirect: "هسته متوقف است. بدون پراکسی به‌روزرسانی شود؟",
coreStoppedDirectAll:
"هسته متوقف است. همهٔ اشتراک‌ها بدون پراکسی به‌روزرسانی شوند؟",
settingsTitle: "به‌روزرسانی اشتراک‌ها",
remarks: "توضیحات",
numberServers: "تعداد سرورها",
subscription: "اشتراک",
autoSelect:
"پس از به‌روزرسانی خودکار اشتراک، به‌طور خودکار به سرورهای جدید آن متصل شوید",
"پس از به‌روزرسانی خودکار اشتراک، به سرورهای جدید آن به‌طور خودکار متصل شود",
autoSelectLabel: "انتخاب خودکار",
updated: "اشتراک به‌روزرسانی شد",
saved: "اشتراک ذخیره شد",
+30 -1
View File
@@ -121,11 +121,40 @@ export default {
saveFailed: "서버 저장 실패: {message}",
},
subscription: {
updateMode: "구독 자동 업데이트",
updateModes: {
disabled: "사용 안 함",
onStart: "서비스 시작 시",
interval: "주기적으로",
intervalFailsafe: "주기적 업데이트 및 장애 복구",
},
updateModeHelp: {
disabled: "수동으로 업데이트할 때만 구독이 변경됩니다.",
onStart:
"v2rayA가 시작될 때마다 한 번, 주소나 업데이트 정책을 변경하면 즉시 한 번 업데이트합니다.",
interval: "시작할 때 한 번 업데이트한 뒤 설정된 주기로 업데이트합니다.",
intervalFailsafe:
"시작 시와 정기 주기에 업데이트합니다. 구독의 모든 서버가 사용할 수 없으면 하나가 복구될 때까지 장애 주기로 다시 시도합니다.",
},
allowDirectRecovery: "장애 복구 중 구독 다운로드 경로 규칙 무시",
recoveryRouteHelp:
"설정된 프록시를 통한 복구가 실패하면 직접 다운로드를 허용합니다. 수동 및 정기 업데이트 경로는 유지됩니다. 직접 시도는 기록되며 네트워크에 구독 서비스 주소가 노출됩니다.",
updateIntervalMinutes: "정기 간격 (분)",
regularHelp: "필수입니다. 1 이상의 정수(분)를 입력하세요.",
failureIntervalMinutes: "실패 재시도 (분)",
failureHelp:
"필수, 최소 1분. 모든 서버가 불가능할 때 갱신하며 하나가 복구되면 재시도를 중지합니다.",
intervalInvalid: "{minimum}부터 525600까지의 정수를 입력하세요.",
coreStoppedDirect:
"코어가 중지되었습니다. 프록시를 거치지 않고 업데이트하시겠습니까?",
coreStoppedDirectAll:
"코어가 중지되었습니다. 모든 구독을 프록시를 거치지 않고 업데이트하시겠습니까?",
settingsTitle: "구독 업데이트",
remarks: "별칭",
numberServers: "서버 수",
subscription: "구독",
autoSelect: "구독이 자동 업데이트된 후 구독의 새 서버에 자동으로 연결",
autoSelect: "구독 자동 업데이트 후 새 서버에 자동으로 연결",
autoSelectLabel: "자동 선택",
updated: "구독 업데이트됨",
saved: "구독 저장됨",
+31 -1
View File
@@ -123,12 +123,42 @@ export default {
saveFailed: "Falha ao salvar o servidor: {message}",
},
subscription: {
updateMode: "Atualização automática da assinatura",
updateModes: {
disabled: "Desativada",
onStart: "Ao iniciar o serviço",
interval: "Em um intervalo",
intervalFailsafe: "Em um intervalo com recuperação de falha",
},
updateModeHelp: {
disabled: "A assinatura muda apenas quando você a atualiza manualmente.",
onStart:
"Atualiza uma vez a cada início do v2rayA e imediatamente ao alterar o endereço ou a política de atualização.",
interval: "Atualiza ao iniciar e depois no intervalo configurado.",
intervalFailsafe:
"Atualiza ao iniciar e no intervalo regular. Se todos os servidores da assinatura ficarem indisponíveis, repete no intervalo de falha até que um funcione.",
},
allowDirectRecovery:
"Ignorar a rota de download da assinatura durante a recuperação",
recoveryRouteHelp:
"Permite download direto se a recuperação pelo proxy configurado falhar. Atualizações manuais e regulares mantêm a rota escolhida. Tentativas diretas são registradas; a rede pode ver o endereço do serviço de assinatura.",
updateIntervalMinutes: "Intervalo regular (minutos)",
regularHelp:
"Obrigatório. Digite um número inteiro de minutos, no mínimo 1.",
failureIntervalMinutes: "Repetir na falha (minutos)",
failureHelp:
"Obrigatório, mínimo de 1 minuto. Atualiza enquanto todos os servidores estão indisponíveis; para quando um funcionar.",
intervalInvalid: "Insira um inteiro de {minimum} a 525600.",
coreStoppedDirect: "O núcleo está parado. Atualizar sem o proxy?",
coreStoppedDirectAll:
"O núcleo está parado. Atualizar todas as assinaturas sem o proxy?",
settingsTitle: "Atualização de assinaturas",
remarks: "Observações",
numberServers: "Número de servidores",
subscription: "Assinatura",
autoSelect:
"Conectar automaticamente aos novos servidores da assinatura após uma atualização automática",
"Conectar automaticamente a novos servidores da assinatura após uma atualização automática",
autoSelectLabel: "Seleção automática",
updated: "Assinatura atualizada",
saved: "Assinatura salva",
+30
View File
@@ -123,6 +123,36 @@ export default {
saveFailed: "Не удалось сохранить сервер: {message}",
},
subscription: {
updateMode: "Автоматическое обновление подписки",
updateModes: {
disabled: "Выключено",
onStart: "При запуске службы",
interval: "По интервалу",
intervalFailsafe: "По интервалу с аварийным восстановлением",
},
updateModeHelp: {
disabled: "Подписка изменяется только при ручном обновлении.",
onStart:
"Обновляет при каждом запуске v2rayA, а также один раз сразу после изменения адреса или режима обновления.",
interval:
"Подписка обновляется при запуске, затем через заданный интервал.",
intervalFailsafe:
"Подписка обновляется при запуске и по плановому интервалу. Если все её серверы недоступны, обновление повторяется по аварийному интервалу, пока не заработает хотя бы один.",
},
allowDirectRecovery:
"Игнорировать правило обновления подписки при аварийном обновлении",
recoveryRouteHelp:
"Разрешает обновление подписки мимо прокси, если аварийное обновление через выбранный прокси не удалось. Не влияет на ручные и плановые обновления. Попытки обновления мимо прокси записываются в журнал; сети виден адрес сервиса подписки.",
updateIntervalMinutes: "Плановый интервал (минуты)",
regularHelp: "Обязательное поле. Укажите целое число минут, не меньше 1.",
failureIntervalMinutes: "При сбоях (минуты)",
failureHelp:
"Обязательно, минимум 1 минута. Обновляет, пока все серверы недоступны; прекращает попытки, когда заработает хотя бы один.",
intervalInvalid: "Введите целое число от {minimum} до 525600.",
coreStoppedDirect: "Ядро выключено. Обновить мимо прокси?",
coreStoppedDirectAll:
"Ядро выключено. Обновить все подписки мимо прокси?",
settingsTitle: "Обновление подписок",
remarks: "Примечания",
numberServers: "Количество серверов",
+28 -1
View File
@@ -119,11 +119,38 @@ export default {
saveFailed: "无法保存节点:{message}",
},
subscription: {
updateMode: "自动更新订阅",
updateModes: {
disabled: "关闭",
onStart: "服务启动时",
interval: "按间隔",
intervalFailsafe: "按间隔并启用故障恢复",
},
updateModeHelp: {
disabled: "仅在手动更新时更改订阅。",
onStart:
"每次 v2rayA 启动时更新一次;修改订阅地址或更新策略后也会立即更新一次。",
interval: "启动时更新一次,之后按设定的间隔更新。",
intervalFailsafe:
"启动时及按固定间隔更新。如果该订阅的所有服务器都不可用,则按故障间隔重试,直到至少一个恢复可用。",
},
allowDirectRecovery: "故障恢复时忽略订阅下载路由规则",
recoveryRouteHelp:
"若通过指定代理恢复失败,允许直接下载。手动及定时更新仍使用所选路径。直接下载会记录日志,网络可以看到订阅服务地址。",
updateIntervalMinutes: "定时更新(分钟)",
regularHelp: "必填。请输入不小于 1 的整数分钟数。",
failureIntervalMinutes: "故障重试(分钟)",
failureHelp:
"必填,至少 1 分钟。所有服务器不可用时更新;任一服务器恢复后停止重试。",
intervalInvalid: "请输入 {minimum} 到 525600 之间的整数。",
coreStoppedDirect: "核心已停止。是否绕过代理更新?",
coreStoppedDirectAll: "核心已停止。是否绕过代理更新所有订阅?",
settingsTitle: "订阅更新",
remarks: "别名",
numberServers: "节点数",
subscription: "订阅",
autoSelect: "订阅自动更新后自动连接其中的新节点",
autoSelect: "自动更新订阅后,自动连接该订阅中的新节点",
autoSelectLabel: "自动选择",
updated: "订阅已更新",
saved: "订阅已保存",
+71 -1
View File
@@ -19,7 +19,11 @@ import { watchConnected } from "@/api/connect";
import type { TouchResponse, TouchServer } from "@/api/types";
import { loadingState } from "@/composables/useLoading";
import { closeAllNotices, noticeState } from "@/composables/useNotify";
import { closeAllDialogs } from "@/composables/useDialog";
import {
closeAllDialogs,
closeDialog,
dialogState,
} from "@/composables/useDialog";
import DialogHost from "@/components/hosts/DialogHost.vue";
import GroupMembersDialog from "./GroupMembers.vue";
import { useAppStore } from "@/stores/app";
@@ -416,4 +420,70 @@ describe("dashboard", () => {
expect(noticeState.current?.text).toContain("Subscription unavailable");
expect(button("Update all").attributes("disabled")).toBeUndefined();
});
test("asks once and bypasses the proxy for every subscription in Update all", async () => {
const data = response();
data.touch.subscriptions.push({
...data.touch.subscriptions[0],
id: 2,
host: "second.example",
});
vi.mocked(getTouch).mockResolvedValue(data);
vi.mocked(getSetting).mockResolvedValue({
setting: {
transparent: "close",
transparentType: "tproxy",
pacMode: "routingA",
logLevel: "info",
proxyModeWhenSubscribe: "proxy",
},
localGFWListVersion: "",
localGeositeVersion: "",
});
vi.mocked(putSubscription).mockResolvedValue(data);
wrapper = mountWithApp(DashboardView);
await flushPromises();
await button("Update all").trigger("click");
await flushPromises();
expect(putSubscription).not.toHaveBeenCalled();
expect(dialogState.stack).toHaveLength(1);
expect(dialogState.stack[0].props).toMatchObject({
message: "The core is stopped. Update all subscriptions without the proxy?",
});
closeDialog(dialogState.stack[0].id, true);
await flushPromises();
expect(vi.mocked(putSubscription).mock.calls).toEqual([
[{ _type: "subscription", id: 1 }, true],
[{ _type: "subscription", id: 2 }, true],
]);
expect(dialogState.stack).toHaveLength(0);
});
test("reports a failed bypass check and does not start Update all", async () => {
vi.mocked(getSetting)
.mockResolvedValueOnce({
setting: {
transparent: "close",
transparentType: "tproxy",
pacMode: "routingA",
logLevel: "info",
},
localGFWListVersion: "",
localGeositeVersion: "",
})
.mockRejectedValueOnce(new Error("settings unavailable"));
wrapper = mountWithApp(DashboardView);
await flushPromises();
await button("Update all").trigger("click");
await flushPromises();
expect(noticeState.current?.text).toContain("settings unavailable");
expect(putSubscription).not.toHaveBeenCalled();
expect(dialogState.stack).toHaveLength(0);
expect(button("Update all").attributes("disabled")).toBeUndefined();
});
});
+28 -5
View File
@@ -20,7 +20,13 @@ import type {
TouchServer,
Which,
} from "@/api/types";
import { openLoading, useConfirm, useDialog, useNotify } from "@/composables";
import {
openLoading,
useConfirm,
useDialog,
useNotify,
useSubscriptionBypass,
} from "@/composables";
import ImportDialog from "@/dialogs/Import.vue";
import SharingDialog from "@/dialogs/Sharing.vue";
import SubscriptionDialog from "@/dialogs/Subscription.vue";
@@ -57,6 +63,7 @@ export function useDashboard() {
const store = useAppStore();
const { t, locale } = useI18n();
const notify = useNotify();
const subscriptionBypass = useSubscriptionBypass();
const settings = useSettings();
const touch = shallowRef<Touch>();
const loading = ref(true);
@@ -329,10 +336,12 @@ export function useDashboard() {
}
}
async function refreshSubscription(id: number) {
async function refreshSubscription(id: number, bypassProxy = false) {
updating.value = id;
try {
apply(await putSubscription({ _type: "subscription", id }));
apply(
await putSubscription({ _type: "subscription", id }, bypassProxy),
);
measured.value.clear();
} catch (err) {
notify.warning(errorText(err));
@@ -390,14 +399,28 @@ export function useDashboard() {
async function updateSubscription(id: number) {
if (subscriptionsBusy.value) return;
await refreshSubscription(id);
updating.value = id;
try {
const bypassProxy = await subscriptionBypass();
if (bypassProxy === null) return;
await refreshSubscription(id, bypassProxy);
} catch (err) {
notify.warning(errorText(err));
} finally {
updating.value = undefined;
}
}
async function updateAll() {
if (subscriptionsBusy.value) return;
updatingAll.value = true;
try {
for (const { id } of subscriptions.value) await refreshSubscription(id);
const bypassProxy = await subscriptionBypass(true);
if (bypassProxy === null) return;
for (const { id } of subscriptions.value)
await refreshSubscription(id, bypassProxy);
} catch (err) {
notify.warning(errorText(err));
} finally {
updatingAll.value = false;
}
+10 -2
View File
@@ -5,7 +5,12 @@ import { errorText } from "@/api/errors";
import { copyText } from "@/lib/clipboard";
import { exportName, saveText } from "@/lib/download";
import type { Touch, TouchSubscription, Which } from "@/api/types";
import { useConfirm, useDialog, useNotify } from "@/composables";
import {
useConfirm,
useDialog,
useNotify,
useSubscriptionBypass,
} from "@/composables";
import ImportDialog from "@/dialogs/Import.vue";
import ServerDialog from "@/dialogs/Server/index.vue";
import SharingDialog from "@/dialogs/Sharing.vue";
@@ -46,6 +51,7 @@ export function useProxies() {
const { t } = useI18n();
const notify = useNotify();
const confirm = useConfirm();
const subscriptionBypass = useSubscriptionBypass();
const { open } = useDialog();
const query = ref("");
const source = ref(localStorage.getItem("proxiesSource") ?? "all");
@@ -347,7 +353,9 @@ export function useProxies() {
return;
}
if (action === "update") {
await subscriptionsModel.update(subscription);
const bypassProxy = await subscriptionBypass();
if (bypassProxy === null) return;
await subscriptionsModel.update(subscription, bypassProxy);
notify.success(t("subscription.updated"));
}
if (
+5 -2
View File
@@ -27,8 +27,11 @@ export function useSubscriptions() {
}
}
async function update(subscription: TouchSubscription) {
await putSubscription(whichOf(subscription));
async function update(
subscription: TouchSubscription,
bypassProxy = false,
) {
await putSubscription(whichOf(subscription), bypassProxy);
await sync();
}
+14
View File
@@ -0,0 +1,14 @@
package httpClient
import (
"net/http"
"time"
)
func DirectSubscriptionClient(mark bool) *http.Client {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
transport.DialContext = DirectDialer(10*time.Second, mark).DialContext
transport.DisableKeepAlives = true
return &http.Client{Transport: transport, Timeout: 30 * time.Second}
}
+4 -5
View File
@@ -5,11 +5,10 @@ import (
)
var (
Version = "debug"
FoundNew = false
RemoteVersion = ""
TickerUpdateGFWList *time.Ticker
TickerUpdateSubscription *time.Ticker
Version = "debug"
FoundNew = false
RemoteVersion = ""
TickerUpdateGFWList *time.Ticker
)
func IsDebug() bool {
+6
View File
@@ -2,6 +2,7 @@ package configure
type (
AutoUpdateMode string
SubscriptionUpdateMode string
ProxyMode string
RulePortMode string
PacRuleType string
@@ -35,6 +36,11 @@ const (
AutoUpdate = AutoUpdateMode("auto_update")
AutoUpdateAtIntervals = AutoUpdateMode("auto_update_at_intervals")
SubscriptionUpdateDisabled = SubscriptionUpdateMode("disabled")
SubscriptionUpdateOnStart = SubscriptionUpdateMode("on_start")
SubscriptionUpdateAtInterval = SubscriptionUpdateMode("at_interval")
SubscriptionUpdateIntervalFailsafe = SubscriptionUpdateMode("interval_failsafe")
ProxyModeDirect = ProxyMode("direct")
ProxyModePac = ProxyMode("pac")
ProxyModeProxy = ProxyMode("proxy")
+12 -7
View File
@@ -13,16 +13,21 @@ type ServerRaw struct {
}
type SubscriptionRaw struct {
Remarks string `json:"remarks,omitempty"`
Address string `json:"address"`
Status string `json:"status"` //update time, error info, etc.
Servers []ServerRaw `json:"servers"`
Info string `json:"info"` // maybe include some info from provider
AutoSelect bool `json:"autoSelect"`
DatabaseID int64 `json:"databaseId"`
UpdateMode SubscriptionUpdateMode `json:"updateMode"`
UpdateIntervalMinutes int `json:"updateIntervalMinutes"`
FailureIntervalMinutes int `json:"failureIntervalMinutes"`
AllowDirectRecovery bool `json:"allowDirectRecovery"`
Remarks string `json:"remarks,omitempty"`
Address string `json:"address"`
Status string `json:"status"` //update time, error info, etc.
Servers []ServerRaw `json:"servers"`
Info string `json:"info"` // maybe include some info from provider
AutoSelect bool `json:"autoSelect"`
}
func Bytes2SubscriptionRaw(b []byte) (*SubscriptionRaw, error) {
var s SubscriptionRaw
s := SubscriptionRaw{UpdateMode: SubscriptionUpdateDisabled, FailureIntervalMinutes: 1}
rawList := gjson.GetBytes(b, "servers").Array()
for _, raw := range rawList {
var obj serverObj.ServerObj
+37 -20
View File
@@ -73,14 +73,18 @@ func setSubscription(tx *sql.Tx, index int, parsed gjson.Result) error {
if parsed.Get("autoSelect").Bool() {
autoSelect = 1
}
updateMode := parsed.Get("updateMode").String()
if updateMode == "" {
updateMode = "disabled"
}
// The first statement writes, so the transaction takes the write lock
// up front under busy_timeout instead of upgrading a read snapshot that
// another connection's commit may have made stale (SQLITE_BUSY_SNAPSHOT).
var subID int64
err := tx.QueryRow(
"UPDATE subscriptions SET address = ?, remarks = ?, status = ?, info = ?, auto_select = ?, updated_at = CURRENT_TIMESTAMP WHERE sort = ? RETURNING id",
address, remarks, status, info, autoSelect, index,
"UPDATE subscriptions SET address = ?, remarks = ?, status = ?, info = ?, auto_select = ?, update_mode = ?, update_interval_minutes = ?, failure_interval_minutes = ?, allow_direct_recovery = ?, updated_at = CURRENT_TIMESTAMP WHERE sort = ? RETURNING id",
address, remarks, status, info, autoSelect, updateMode, parsed.Get("updateIntervalMinutes").Int(), max(1, parsed.Get("failureIntervalMinutes").Int()), parsed.Get("allowDirectRecovery").Bool(), index,
).Scan(&subID)
if err == sql.ErrNoRows {
return fmt.Errorf("ListSet: subscription at index %d not found", index)
@@ -136,10 +140,12 @@ func SubscriptionsGet(index int) ([]byte, error) {
db := GetDB()
var subID int64
var address, remarks, status, info string
var autoSelectInt int
var autoSelectInt, regularInt, failureInt int
var allowDirectRecovery bool
var updateMode string
err := db.QueryRow(
"SELECT id, address, remarks, status, info, auto_select FROM subscriptions WHERE sort = ?", index,
).Scan(&subID, &address, &remarks, &status, &info, &autoSelectInt)
"SELECT id, address, remarks, status, info, auto_select, update_mode, update_interval_minutes, failure_interval_minutes, allow_direct_recovery FROM subscriptions WHERE sort = ?", index,
).Scan(&subID, &address, &remarks, &status, &info, &autoSelectInt, &updateMode, &regularInt, &failureInt, &allowDirectRecovery)
if err == sql.ErrNoRows {
return nil, fmt.Errorf("ListGet: can't get element from an empty list")
}
@@ -166,7 +172,7 @@ func SubscriptionsGet(index int) ([]byte, error) {
servers = append(servers, s)
}
return subscriptionJSON(remarks, address, status, info, servers, autoSelectInt != 0)
return subscriptionJSON(subID, remarks, address, status, info, servers, autoSelectInt != 0, updateMode, regularInt, failureInt, allowDirectRecovery)
}
// ListAppend appends values to a list.
@@ -234,10 +240,14 @@ func SubscriptionsAppend(val interface{}) (err error) {
if item.Get("autoSelect").Bool() {
autoSelect = 1
}
updateMode := item.Get("updateMode").String()
if updateMode == "" {
updateMode = "disabled"
}
res, err := db.Exec(
"INSERT INTO subscriptions (address, remarks, status, info, auto_select, sort) VALUES (?, ?, ?, ?, ?, (SELECT COALESCE(MAX(sort), -1) + 1 FROM subscriptions))",
address, remarks, status, info, autoSelect,
"INSERT INTO subscriptions (address, remarks, status, info, auto_select, update_mode, update_interval_minutes, failure_interval_minutes, allow_direct_recovery, sort) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(sort), -1) + 1 FROM subscriptions))",
address, remarks, status, info, autoSelect, updateMode, item.Get("updateIntervalMinutes").Int(), max(1, item.Get("failureIntervalMinutes").Int()), item.Get("allowDirectRecovery").Bool(),
)
if err != nil {
return err
@@ -291,7 +301,7 @@ func ServersGetAll() (list [][]byte, err error) {
func SubscriptionsGetAll() (list [][]byte, err error) {
db := GetDB()
rows, err := db.Query("SELECT id, address, remarks, status, info, auto_select FROM subscriptions ORDER BY sort")
rows, err := db.Query("SELECT id, address, remarks, status, info, auto_select, update_mode, update_interval_minutes, failure_interval_minutes, allow_direct_recovery FROM subscriptions ORDER BY sort")
if err != nil {
return nil, err
}
@@ -300,8 +310,10 @@ func SubscriptionsGetAll() (list [][]byte, err error) {
for rows.Next() {
var id int64
var address, remarks, status, info string
var autoSelectInt int
if err := rows.Scan(&id, &address, &remarks, &status, &info, &autoSelectInt); err != nil {
var autoSelectInt, regularInt, failureInt int
var allowDirectRecovery bool
var updateMode string
if err := rows.Scan(&id, &address, &remarks, &status, &info, &autoSelectInt, &updateMode, &regularInt, &failureInt, &allowDirectRecovery); err != nil {
return nil, err
}
@@ -324,7 +336,7 @@ func SubscriptionsGetAll() (list [][]byte, err error) {
}
serverRows.Close()
result, err := subscriptionJSON(remarks, address, status, info, servers, autoSelectInt != 0)
result, err := subscriptionJSON(id, remarks, address, status, info, servers, autoSelectInt != 0, updateMode, regularInt, failureInt, allowDirectRecovery)
if err != nil {
return nil, err
}
@@ -462,17 +474,22 @@ func SubscriptionsLen() (length int, err error) {
// server rows are already JSON; the scalar columns are user- or
// provider-supplied text and must be escaped, otherwise a remark with a
// quote made the whole subscription unreadable.
func subscriptionJSON(remarks, address, status, info string, servers []string, autoSelect bool) ([]byte, error) {
func subscriptionJSON(databaseID int64, remarks, address, status, info string, servers []string, autoSelect bool, updateMode string, regular, failure int, allowDirectRecovery bool) ([]byte, error) {
raw := make([]jsoniter.RawMessage, 0, len(servers))
for _, s := range servers {
raw = append(raw, jsoniter.RawMessage(s))
}
return jsoniter.Marshal(struct {
Remarks string `json:"remarks"`
Address string `json:"address"`
Status string `json:"status"`
Info string `json:"info"`
Servers []jsoniter.RawMessage `json:"servers"`
AutoSelect bool `json:"autoSelect"`
}{remarks, address, status, info, raw, autoSelect})
DatabaseID int64 `json:"databaseId"`
Remarks string `json:"remarks"`
Address string `json:"address"`
Status string `json:"status"`
Info string `json:"info"`
Servers []jsoniter.RawMessage `json:"servers"`
AutoSelect bool `json:"autoSelect"`
UpdateMode string `json:"updateMode"`
UpdateIntervalMinutes int `json:"updateIntervalMinutes"`
FailureIntervalMinutes int `json:"failureIntervalMinutes"`
AllowDirectRecovery bool `json:"allowDirectRecovery"`
}{databaseID, remarks, address, status, info, raw, autoSelect, updateMode, regular, failure, allowDirectRecovery})
}
+11 -3
View File
@@ -127,6 +127,10 @@ func MigrateFromBoltDB() error {
_ = tx.Rollback()
return fmt.Errorf("failed to migrate outbounds bucket: %w", err)
}
if err := migrateSubscriptionUpdatePolicy(tx); err != nil {
_ = tx.Rollback()
return fmt.Errorf("failed to migrate subscription update policy: %w", err)
}
// Commit transaction
if err := tx.Commit(); err != nil {
@@ -347,8 +351,8 @@ func migrateSubscriptions(data []byte, tx *sql.Tx) error {
}
subStmt, err := tx.Prepare(`
INSERT INTO subscriptions (address, remarks, status, info, auto_select, sort)
VALUES (?, ?, ?, ?, ?, ?)
INSERT INTO subscriptions (address, remarks, status, info, auto_select, update_mode, update_interval_minutes, failure_interval_minutes, allow_direct_recovery, sort)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
if err != nil {
return err
@@ -373,8 +377,12 @@ func migrateSubscriptions(data []byte, tx *sql.Tx) error {
if r.Get("autoSelect").Bool() {
autoSelect = 1
}
updateMode := r.Get("updateMode").String()
if updateMode == "" {
updateMode = "disabled"
}
res, err := subStmt.Exec(address, remarks, status, info, autoSelect, i)
res, err := subStmt.Exec(address, remarks, status, info, autoSelect, updateMode, r.Get("updateIntervalMinutes").Int(), max(1, r.Get("failureIntervalMinutes").Int()), r.Get("allowDirectRecovery").Bool(), i)
if err != nil {
return fmt.Errorf("failed to insert subscription %d: %w", i, err)
}
+30 -10
View File
@@ -40,6 +40,10 @@ CREATE TABLE IF NOT EXISTS subscriptions (
status TEXT NOT NULL DEFAULT '',
info TEXT DEFAULT '',
auto_select INTEGER NOT NULL DEFAULT 0,
update_mode TEXT NOT NULL DEFAULT 'disabled',
update_interval_minutes INTEGER NOT NULL DEFAULT 0,
failure_interval_minutes INTEGER NOT NULL DEFAULT 1,
allow_direct_recovery INTEGER NOT NULL DEFAULT 0,
filter TEXT DEFAULT '',
group_id TEXT DEFAULT '',
sort INTEGER NOT NULL DEFAULT 0,
@@ -89,19 +93,35 @@ func MigrateSchema(db *sql.DB) error {
}
}
// Check if auto_select column exists (added after initial schema)
err = db.QueryRow("SELECT COUNT(*) FROM pragma_table_info('subscriptions') WHERE name = 'auto_select'").Scan(&count)
if err != nil {
return fmt.Errorf("failed to check for auto_select column: %w", err)
columns := []struct{ name, definition string }{
{"auto_select", "INTEGER NOT NULL DEFAULT 0"},
{"update_mode", "TEXT NOT NULL DEFAULT 'disabled'"},
{"update_interval_minutes", "INTEGER NOT NULL DEFAULT 0"},
{"failure_interval_minutes", "INTEGER NOT NULL DEFAULT 1"},
{"allow_direct_recovery", "INTEGER NOT NULL DEFAULT 0"},
}
if count == 0 {
log.Info("Adding auto_select column to subscriptions table")
if _, err := db.Exec("ALTER TABLE subscriptions ADD COLUMN auto_select INTEGER NOT NULL DEFAULT 0"); err != nil {
return fmt.Errorf("failed to add auto_select column: %w", err)
for _, column := range columns {
if err := db.QueryRow("SELECT COUNT(*) FROM pragma_table_info('subscriptions') WHERE name = ?", column.name).Scan(&count); err != nil {
return err
}
if count == 0 {
if _, err := db.Exec("ALTER TABLE subscriptions ADD COLUMN " + column.name + " " + column.definition); err != nil {
return err
}
}
}
return migrateLegacyOutboundTables(db)
if err := migrateLegacyOutboundTables(db); err != nil {
return err
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if err := migrateSubscriptionUpdatePolicy(tx); err != nil {
return err
}
return tx.Commit()
}
// migrateLegacyOutboundTables copies what the first SQLite migration wrote
@@ -0,0 +1,181 @@
package db
import (
"database/sql"
"path/filepath"
"strings"
"testing"
"github.com/tidwall/gjson"
"go.etcd.io/bbolt"
)
func TestSQLiteSubscriptionUpdatePolicyMigration(t *testing.T) {
tests := []struct {
legacy, want string
minutes int
}{
{"none", "disabled", 0},
{"auto_update", "on_start", 0},
{"auto_update_at_intervals", "at_interval", 420},
}
for _, test := range tests {
t.Run(test.legacy, func(t *testing.T) {
database, err := sql.Open(sqliteDriverName, ":memory:")
if err != nil {
t.Fatal(err)
}
defer database.Close()
database.SetMaxOpenConns(1)
if _, err := database.Exec(`
CREATE TABLE system_config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE subscriptions (id INTEGER PRIMARY KEY, address TEXT, remarks TEXT, auto_select INTEGER);
INSERT INTO subscriptions VALUES (7, 'https://example.test/sub', 'keep me', 1);
INSERT INTO system_config VALUES ('system:setting', ?)
`, `{"subscriptionAutoUpdateMode":"`+test.legacy+`","subscriptionAutoUpdateIntervalHour":7}`); err != nil {
t.Fatal(err)
}
if err := MigrateSchema(database); err != nil {
t.Fatal(err)
}
assertSubscriptionPolicy(t, database, test.want, test.minutes, 1)
if _, err := database.Exec("UPDATE subscriptions SET update_mode='interval_failsafe', update_interval_minutes=11, failure_interval_minutes=2"); err != nil {
t.Fatal(err)
}
if err := MigrateSchema(database); err != nil {
t.Fatal(err)
}
assertSubscriptionPolicyValues(t, database, "interval_failsafe", 11, 2, 1)
})
}
}
func TestBoltImportMigratesAllSubscriptionUpdateModes(t *testing.T) {
for _, legacy := range []string{"none", "auto_update", "auto_update_at_intervals"} {
t.Run(legacy, func(t *testing.T) {
boltPath := filepath.Join(t.TempDir(), "bolt.db")
bolt, err := bbolt.Open(boltPath, 0600, nil)
if err != nil {
t.Fatal(err)
}
if err := bolt.Update(func(tx *bbolt.Tx) error {
system, err := tx.CreateBucket([]byte("system"))
if err != nil {
return err
}
if err := system.Put([]byte("setting"), []byte(`{"subscriptionAutoUpdateMode":"`+legacy+`","subscriptionAutoUpdateIntervalHour":7}`)); err != nil {
return err
}
touch, err := tx.CreateBucket([]byte("touch"))
if err != nil {
return err
}
return touch.Put([]byte("subscriptions"), []byte(`[{"address":"https://example.test/sub","autoSelect":true,"servers":[]}]`))
}); err != nil {
t.Fatal(err)
}
defer bolt.Close()
database, err := sql.Open(sqliteDriverName, ":memory:")
if err != nil {
t.Fatal(err)
}
defer database.Close()
database.SetMaxOpenConns(1)
if err := InitSchema(database); err != nil {
t.Fatal(err)
}
tx, err := database.Begin()
if err != nil {
t.Fatal(err)
}
if err := migrateSystemBucket(bolt, tx); err != nil {
t.Fatal(err)
}
if err := migrateTouchBucket(bolt, tx); err != nil {
t.Fatal(err)
}
if err := migrateSubscriptionUpdatePolicy(tx); err != nil {
t.Fatal(err)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
want, minutes := "disabled", 0
if legacy == "auto_update" {
want = "on_start"
} else if legacy == "auto_update_at_intervals" {
want, minutes = "at_interval", 420
}
assertSubscriptionPolicy(t, database, want, minutes, 1)
var setting string
if err := database.QueryRow("SELECT value FROM system_config WHERE key='system:setting'").Scan(&setting); err != nil {
t.Fatal(err)
}
if got := gjson.Get(setting, "subscriptionAutoUpdateMode").String(); got != "none" {
t.Fatalf("legacy mode was not reset: %q", got)
}
})
}
}
func assertSubscriptionPolicy(t *testing.T, database *sql.DB, mode string, minutes, autoSelect int) {
assertSubscriptionPolicyValues(t, database, mode, minutes, 1, autoSelect)
var direct bool
if err := database.QueryRow("SELECT allow_direct_recovery FROM subscriptions").Scan(&direct); err != nil {
t.Fatal(err)
}
if direct {
t.Fatal("legacy migration enabled direct downloads without consent")
}
}
func TestDirectRecoveryMigrationDoesNotChangeExistingPolicy(t *testing.T) {
database, err := sql.Open(sqliteDriverName, ":memory:")
if err != nil {
t.Fatal(err)
}
defer database.Close()
database.SetMaxOpenConns(1)
oldSchema := strings.Replace(schemaSQL, " allow_direct_recovery INTEGER NOT NULL DEFAULT 0,\n", "", 1)
if _, err := database.Exec(oldSchema); err != nil {
t.Fatal(err)
}
if _, err := database.Exec("INSERT INTO subscriptions (address, update_mode, update_interval_minutes, failure_interval_minutes) VALUES ('https://example.test/sub', 'interval_failsafe', 10, 2)"); err != nil {
t.Fatal(err)
}
if _, err := database.Exec("INSERT INTO system_config (key, value) VALUES (?, '1')", subscriptionUpdateMigrationKey); err != nil {
t.Fatal(err)
}
if err := MigrateSchema(database); err != nil {
t.Fatal(err)
}
assertSubscriptionPolicyValues(t, database, "interval_failsafe", 10, 2, 0)
var allowed bool
if err := database.QueryRow("SELECT allow_direct_recovery FROM subscriptions").Scan(&allowed); err != nil || allowed {
t.Fatalf("upgrade opted in to direct recovery: allowed=%v err=%v", allowed, err)
}
if _, err := database.Exec("UPDATE subscriptions SET allow_direct_recovery = 1"); err != nil {
t.Fatal(err)
}
if err := MigrateSchema(database); err != nil {
t.Fatal(err)
}
if err := database.QueryRow("SELECT allow_direct_recovery FROM subscriptions").Scan(&allowed); err != nil || !allowed {
t.Fatalf("restart reset explicit consent: allowed=%v err=%v", allowed, err)
}
}
func assertSubscriptionPolicyValues(t *testing.T, database *sql.DB, mode string, minutes, failure, autoSelect int) {
t.Helper()
var gotMode string
var gotMinutes, gotFailure, gotAutoSelect int
if err := database.QueryRow("SELECT update_mode, update_interval_minutes, failure_interval_minutes, auto_select FROM subscriptions").Scan(&gotMode, &gotMinutes, &gotFailure, &gotAutoSelect); err != nil {
t.Fatal(err)
}
if gotMode != mode || gotMinutes != minutes || gotFailure != failure || gotAutoSelect != autoSelect {
t.Fatalf("policy = %s/%d/%d, autoSelect=%d; want %s/%d/%d, autoSelect=%d", gotMode, gotMinutes, gotFailure, gotAutoSelect, mode, minutes, failure, autoSelect)
}
}
@@ -0,0 +1,65 @@
package db
import (
"database/sql"
"fmt"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
const subscriptionUpdateMigrationKey = "migration:subscription_update_policy_v1"
type subscriptionPolicyStore interface {
Exec(query string, args ...interface{}) (sql.Result, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
func migrateSubscriptionUpdatePolicy(store subscriptionPolicyStore) error {
var migrated int
if err := store.QueryRow("SELECT COUNT(*) FROM system_config WHERE key = ?", subscriptionUpdateMigrationKey).Scan(&migrated); err != nil {
return err
}
if migrated != 0 {
return nil
}
var setting string
err := store.QueryRow("SELECT value FROM system_config WHERE key = 'system:setting'").Scan(&setting)
if err != nil && err != sql.ErrNoRows {
return err
}
legacyMode := gjson.Get(setting, "subscriptionAutoUpdateMode").String()
hours := int(gjson.Get(setting, "subscriptionAutoUpdateIntervalHour").Int())
mode, minutes := "", 0
switch legacyMode {
case "auto_update":
mode = "on_start"
case "auto_update_at_intervals":
mode = "at_interval"
if hours <= 0 {
hours = 1
}
minutes = hours * 60
}
if mode != "" {
if _, err := store.Exec("UPDATE subscriptions SET update_mode = ?, update_interval_minutes = ? WHERE update_mode = 'disabled'", mode, minutes); err != nil {
return err
}
}
if setting != "" {
setting, err = sjson.Set(setting, "subscriptionAutoUpdateMode", "none")
if err != nil {
return fmt.Errorf("reset legacy subscription update mode: %w", err)
}
if _, err := store.Exec("UPDATE system_config SET value = ? WHERE key = 'system:setting'", setting); err != nil {
return err
}
}
if _, err := store.Exec("INSERT INTO system_config (key, value) VALUES (?, '1')", subscriptionUpdateMigrationKey); err != nil {
return err
}
log.Info("Migrated legacy subscription update mode %q to per-subscription policies", legacyMode)
return nil
}
+26 -17
View File
@@ -28,15 +28,19 @@ type Server struct {
PingLatency string `json:"pingLatency"`
}
type Subscription struct {
Remarks string `json:"remarks,omitempty"`
ID int `json:"id"`
TYPE configure.TouchType `json:"_type"`
Host string `json:"host"`
Address string `json:"address"`
Status SubscriptionStatus `json:"status"`
Info string `json:"info"`
Servers []Server `json:"servers"`
AutoSelect bool `json:"autoSelect"`
UpdateMode *configure.SubscriptionUpdateMode `json:"updateMode,omitempty"`
UpdateIntervalMinutes *int `json:"updateIntervalMinutes"`
FailureIntervalMinutes *int `json:"failureIntervalMinutes"`
AllowDirectRecovery *bool `json:"allowDirectRecovery,omitempty"`
AutoSelect bool `json:"autoSelect"`
Remarks string `json:"remarks,omitempty"`
ID int `json:"id"`
TYPE configure.TouchType `json:"_type"`
Host string `json:"host"`
Address string `json:"address"`
Status SubscriptionStatus `json:"status"`
Info string `json:"info"`
Servers []Server `json:"servers"`
}
// NewUpdateStatus stamps a subscription update. RFC 3339 carries the zone, so
@@ -74,6 +78,7 @@ func GenerateTouch() (t Touch) {
subscriptions := configure.GetSubscriptions()
t.Subscriptions = make([]Subscription, len(subscriptions))
for i, v := range subscriptions {
updateMode := v.UpdateMode
u, err := url.Parse(v.Address)
if err != nil {
// it may is OOCv1
@@ -91,14 +96,18 @@ func GenerateTouch() (t Touch) {
}
}
t.Subscriptions[i] = Subscription{
Remarks: v.Remarks,
ID: i + 1,
Host: u.Host,
Address: v.Address,
Status: SubscriptionStatus(v.Status),
Servers: serverRawsToServers(v.Servers),
Info: v.Info,
AutoSelect: v.AutoSelect,
Remarks: v.Remarks,
UpdateMode: &updateMode,
UpdateIntervalMinutes: &v.UpdateIntervalMinutes,
FailureIntervalMinutes: &v.FailureIntervalMinutes,
AllowDirectRecovery: &v.AllowDirectRecovery,
AutoSelect: v.AutoSelect,
ID: i + 1,
Host: u.Host,
Address: v.Address,
Status: SubscriptionStatus(v.Status),
Servers: serverRawsToServers(v.Servers),
Info: v.Info,
}
}
t.ConnectedServers = configure.GetConnectedServers().ToWhiches()
@@ -0,0 +1,47 @@
package v2ray
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestBackupAndRestoreResolvSymlink(t *testing.T) {
dir := t.TempDir()
resolv := filepath.Join(dir, "resolv.conf")
backup := filepath.Join(dir, "resolv.conf.backup")
withPaths(t, resolv, backup)
stub := filepath.Join(dir, "stub-resolv.conf")
if err := os.WriteFile(stub, []byte("nameserver 127.0.0.53\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(stub, resolv); err != nil {
t.Fatal(err)
}
hij := &ResolvHijacker{}
if err := hij.HijackResolv(); err != nil {
t.Fatalf("hijack: %v", err)
}
// The hijack must replace the link, not write through it into the
// resolver's own file.
if b, err := os.ReadFile(stub); err != nil || string(b) != "nameserver 127.0.0.53\n" {
t.Fatalf("the link target was overwritten: %q (err %v)", b, err)
}
saved, err := os.ReadFile(backup)
if err != nil || !strings.HasPrefix(string(saved), symlinkMarker) {
t.Fatalf("the link target was not saved: %q (err %v)", saved, err)
}
if !restoreResolv() {
t.Fatal("restore reported failure")
}
fi, err := os.Lstat(resolv)
if err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Fatalf("the symlink is not back: %v (err %v)", fi, err)
}
target, err := os.Readlink(resolv)
if err != nil || target != stub {
t.Fatalf("link points at %q, want %q (err %v)", target, stub, err)
}
}
-40
View File
@@ -4,7 +4,6 @@ import (
"github.com/v2rayA/v2rayA/db/configure"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
@@ -43,45 +42,6 @@ func TestBackupAndRestoreResolv(t *testing.T) {
}
}
func TestBackupAndRestoreResolvSymlink(t *testing.T) {
dir := t.TempDir()
resolv := filepath.Join(dir, "resolv.conf")
backup := filepath.Join(dir, "resolv.conf.backup")
withPaths(t, resolv, backup)
stub := filepath.Join(dir, "stub-resolv.conf")
if err := os.WriteFile(stub, []byte("nameserver 127.0.0.53\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(stub, resolv); err != nil {
t.Fatal(err)
}
hij := &ResolvHijacker{}
if err := hij.HijackResolv(); err != nil {
t.Fatalf("hijack: %v", err)
}
// The hijack must replace the link, not write through it into the
// resolver's own file.
if b, err := os.ReadFile(stub); err != nil || string(b) != "nameserver 127.0.0.53\n" {
t.Fatalf("the link target was overwritten: %q (err %v)", b, err)
}
saved, err := os.ReadFile(backup)
if err != nil || !strings.HasPrefix(string(saved), symlinkMarker) {
t.Fatalf("the link target was not saved: %q (err %v)", saved, err)
}
if !restoreResolv() {
t.Fatal("restore reported failure")
}
fi, err := os.Lstat(resolv)
if err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Fatalf("the symlink is not back: %v (err %v)", fi, err)
}
target, err := os.Readlink(resolv)
if err != nil || target != stub {
t.Fatalf("link points at %q, want %q (err %v)", target, stub, err)
}
}
func TestRestoreResolvWithoutBackup(t *testing.T) {
dir := t.TempDir()
withPaths(t, filepath.Join(dir, "resolv.conf"), filepath.Join(dir, "resolv.conf.backup"))
+3
View File
@@ -55,7 +55,9 @@ func run() error {
}
log.Info("migrated the OpenWrt TPROXY exclusions to include LAN bridge traffic")
}
stopAutomation := func() {}
cleanup := func() {
stopAutomation()
fmt.Println("Quitting...")
v2ray.ProcessManager.CheckAndStopTransparentProxy(nil)
v2ray.ProcessManager.Stop(false)
@@ -106,6 +108,7 @@ func run() error {
log.Error("failed to start v2ray-core: %v", err)
}
}
stopAutomation = service.StartAutomation()
//w := configure.GetConnectedServers()
//log.Println(err, ", which:", w)
//_ = configure.ClearConnected()
-64
View File
@@ -2,7 +2,6 @@ package main
import (
"errors"
"sync"
"time"
"github.com/v2rayA/v2rayA/conf"
@@ -12,57 +11,8 @@ import (
"github.com/v2rayA/v2rayA/server/service"
)
func updateSubscriptions() {
subs := configure.GetSubscriptions()
lenSubs := len(subs)
control := make(chan struct{}, 2) // concurrency limit: update 2 subscriptions at a time
// Disconnect from subscriptions before auto-selecting servers from them
// to limit the number of connected servers and avoid hitting the limit
shouldDisconnect := true
err := service.AutoSelectServersFromSubscriptions(shouldDisconnect)
if err != nil {
log.Error("[AutoSelect] Failed to disconnect servers from subscriptions -- err: %v", err)
}
wg := new(sync.WaitGroup)
for i := 0; i < lenSubs; i++ {
wg.Add(1)
go func(i int) {
control <- struct{}{}
defer wg.Done()
defer func() { <-control }()
runSubscriptionUpdate(i, func() {
err := service.UpdateSubscription(i, false)
if err != nil {
log.Info("[AutoUpdate] Subscriptions: Failed to update subscription -- ID: %d, err: %v", i, err)
} else {
log.Info("[AutoUpdate] Subscriptions: Complete updating subscription -- ID: %d, Address: %s", i, subs[i].Address)
}
})
}(i)
}
wg.Wait()
shouldDisconnect = false
err2 := service.AutoSelectServersFromSubscriptions(shouldDisconnect)
if err2 != nil {
log.Error("[AutoSelect] Failed to auto-select servers from subscriptions -- err: %v", err2)
}
}
func runSubscriptionUpdate(index int, update func()) (panicked bool) {
defer func() {
if recovered := recover(); recovered != nil {
log.Error("[AutoUpdate] subscription %d: panic: %v", index, recovered)
panicked = true
}
}()
update()
return false
}
func initUpdatingTicker() {
conf.TickerUpdateGFWList = time.NewTicker(24 * time.Hour * 365 * 100)
conf.TickerUpdateSubscription = time.NewTicker(24 * time.Hour * 365 * 100)
go func() {
for range conf.TickerUpdateGFWList.C {
version, err := dat.CheckAndUpdateGFWList("")
@@ -74,11 +24,6 @@ func initUpdatingTicker() {
}
}
}()
go func() {
for range conf.TickerUpdateSubscription.C {
updateSubscriptions()
}
}()
go func() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
@@ -135,15 +80,6 @@ func checkUpdate() {
}
}
// check for subscription updates
if setting.SubscriptionAutoUpdateMode == configure.AutoUpdate ||
setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals {
if setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals {
conf.TickerUpdateSubscription.Reset(configure.IntervalHours(setting.SubscriptionAutoUpdateIntervalHour))
}
go updateSubscriptions()
}
// check for server updates
go func() {
f := func() {
-9
View File
@@ -1,9 +0,0 @@
package main
import "testing"
func TestRunSubscriptionUpdateRecoversPanic(t *testing.T) {
if !runSubscriptionUpdate(3, func() { panic("malformed plugin") }) {
t.Fatal("panic was not recovered")
}
}
+19 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/server/service"
)
var (
@@ -25,7 +26,24 @@ func beginMutation(ctx *gin.Context) (release func(), ok bool) {
defer timer.Stop()
select {
case mutation <- struct{}{}:
return func() { <-mutation }, true
service.CancelAutomation()
for !service.ConfigurationMu.TryLock() {
select {
case <-timer.C:
<-mutation
common.ResponseError(ctx, processingErr)
return nil, false
case <-ctx.Request.Context().Done():
<-mutation
return nil, false
case <-time.After(10 * time.Millisecond):
}
}
return func() {
service.ConfigurationMu.Unlock()
service.NotifyAutomation()
<-mutation
}, true
case <-timer.C:
common.ResponseError(ctx, processingErr)
return nil, false
+6 -2
View File
@@ -22,6 +22,10 @@ func PostImport(ctx *gin.Context) {
// say, and the scheme of URL decides.
Kind string `json:"kind"`
Which interface{} `json:"which"`
// BypassProxy selects a direct route for this one subscription fetch.
// It records the user's consent to go direct; the server does not
// check that the proxy route is actually unavailable.
BypassProxy bool `json:"bypassProxy"`
}
if err := ctx.ShouldBindJSON(&body); err != nil {
common.ResponseError(ctx, badRequest("import", fmt.Sprintf("request body must be a JSON object with \"url\" (string) and optional \"kind\" and \"which\": %v", err)))
@@ -43,9 +47,9 @@ func PostImport(ctx *gin.Context) {
case "server":
err = service.ImportServer(body.URL, which)
case "subscription":
err = service.ImportSubscription(body.URL)
err = service.ImportSubscriptionWithOptions(body.URL, service.SubscriptionFetchOptions{BypassProxy: body.BypassProxy})
case "":
err = service.Import(body.URL, which)
err = service.ImportWithOptions(body.URL, which, service.SubscriptionFetchOptions{BypassProxy: body.BypassProxy})
default:
common.ResponseError(ctx, common.Coded("INVALID_KIND", logError(fmt.Sprintf("kind %q is not valid; expected \"server\" or \"subscription\"", body.Kind)), map[string]interface{}{"kind": body.Kind}))
return
@@ -33,16 +33,12 @@ func storedDnsMode(t *testing.T) (configure.DnsMode, configure.DefaultYesNo) {
func resetSetting(t *testing.T) {
t.Helper()
t.Cleanup(func() { _ = configure.SetSetting(configure.NewSetting()) })
// A saved setting restarts the auto-update tickers, which only the
// service's own start creates.
// A saved setting restarts the GFWList ticker, which only the service's
// own start creates.
if conf.TickerUpdateGFWList == nil {
conf.TickerUpdateGFWList = time.NewTicker(time.Hour)
t.Cleanup(conf.TickerUpdateGFWList.Stop)
}
if conf.TickerUpdateSubscription == nil {
conf.TickerUpdateSubscription = time.NewTicker(time.Hour)
t.Cleanup(conf.TickerUpdateSubscription.Stop)
}
}
// putSetting expects body to be accepted and reports what the store then
+8 -2
View File
@@ -42,14 +42,20 @@ func PutSubscription(ctx *gin.Context) {
}
defer release()
var data configure.NodeRef
var data struct {
configure.NodeRef
// BypassProxy selects a direct route for this one subscription fetch.
// It records the user's consent to go direct; the server does not
// check that the proxy route is actually unavailable.
BypassProxy bool `json:"bypassProxy"`
}
err := ctx.ShouldBindJSON(&data)
index := data.ID - 1
if err != nil || data.TYPE != configure.SubscriptionType || index < 0 || index >= configure.GetLenSubscriptions() {
common.ResponseError(ctx, badRequest("subscription", "request body must be a subscription item with _type \"subscription\" and an existing positive id"))
return
}
err = service.UpdateSubscription(index, false)
err = service.UpdateSubscriptionWithOptions(index, false, service.SubscriptionFetchOptions{BypassProxy: data.BypassProxy})
if err != nil {
common.ResponseError(ctx, logError(err))
return
+379
View File
@@ -0,0 +1,379 @@
package service
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/serverObj"
"github.com/v2rayA/v2rayA/kernel/v2ray"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
var (
automationCancelMu sync.Mutex
automationCancel context.CancelFunc
automationWake = make(chan struct{}, 1)
)
func CancelAutomation() {
automationCancelMu.Lock()
defer automationCancelMu.Unlock()
if automationCancel != nil {
automationCancel()
}
}
func NotifyAutomation() {
select {
case automationWake <- struct{}{}:
default:
}
}
type subscriptionSchedule struct {
signature string
nextUpdate, nextHealth, nextRetry time.Time
// retryFromOutage records that the reserved nextRetry was armed by an
// actual all-unavailable health result. A retry reserved before a regular
// fetch, or re-armed after its cancellation, must not grant the direct
// fallback: no outage was detected for it.
retryFromOutage bool
warnedUnprobeable bool
}
type subscriptionFetcher func(context.Context, string, bool) ([]serverObj.ServerObj, string, error)
type automation struct {
subscriptions map[int64]*subscriptionSchedule
now func() time.Time
probe func(context.Context, []serverObj.ServerObj, string) []subscriptionProbeResult
fetch subscriptionFetcher
}
func newAutomation() *automation {
return &automation{
subscriptions: map[int64]*subscriptionSchedule{},
now: time.Now,
probe: probeSubscriptionWithContext,
fetch: fetchSubscriptionForAutomation,
}
}
func subscriptionPolicySignature(sub *configure.SubscriptionRaw) string {
b, _ := json.Marshal(struct {
ID int64
Address string
Mode configure.SubscriptionUpdateMode
Regular int
AllowDirect bool
Failsafe int
}{sub.DatabaseID, sub.Address, sub.UpdateMode, sub.UpdateIntervalMinutes, sub.AllowDirectRecovery, sub.FailureIntervalMinutes})
return string(b)
}
func fetchSubscriptionForAutomation(ctx context.Context, address string, allowDirectFallback bool) ([]serverObj.ServerObj, string, error) {
client, err := subscriptionHTTPClient()
var nodes []serverObj.ServerObj
var info string
if err == nil {
nodes, info, err = resolveSubscriptionWithContext(ctx, address, client)
}
if err != nil && allowDirectFallback && ctx.Err() == nil && configure.GetSettingNotNil().ProxyModeWhenSubscribe != configure.ProxyModeDirect {
log.Warn("[Subscriptions] Fail-safe recovery for %s: configured download route failed; retrying directly", subscriptionHost(address))
return resolveSubscriptionWithContext(ctx, address, directSubscriptionClient())
}
return nodes, info, err
}
func findSubscriptionByDatabaseID(id int64) (int, *configure.SubscriptionRaw) {
subscriptions := configure.GetSubscriptions()
for index := range subscriptions {
if subscriptions[index].DatabaseID == id {
return index, &subscriptions[index]
}
}
return -1, nil
}
func (a *automation) applyUpdate(ctx context.Context, observed *configure.SubscriptionRaw, nodes []serverObj.ServerObj, info string) (*configure.SubscriptionRaw, error) {
ConfigurationMu.Lock()
defer ConfigurationMu.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
index, current := findSubscriptionByDatabaseID(observed.DatabaseID)
if current == nil || subscriptionPolicySignature(current) != subscriptionPolicySignature(observed) {
return nil, fmt.Errorf("subscription changed during update")
}
if current.AutoSelect {
if err := SelectServersFromSubscription(index, true); err != nil {
return nil, err
}
}
if err := storeSubscriptionUpdate(index, current, nodes, info, false); err != nil {
if current.AutoSelect {
_ = SelectServersFromSubscription(index, false)
}
return nil, err
}
if current.AutoSelect {
if err := SelectServersFromSubscription(index, false); err != nil {
return nil, err
}
}
_, updated := findSubscriptionByDatabaseID(observed.DatabaseID)
return updated, nil
}
func subscriptionNodes(sub *configure.SubscriptionRaw) []serverObj.ServerObj {
nodes := make([]serverObj.ServerObj, len(sub.Servers))
for i := range sub.Servers {
nodes[i] = sub.Servers[i].ServerObj
}
return nodes
}
func anyHealthy(results []subscriptionProbeResult) bool {
for _, result := range results {
if result.err == nil {
return true
}
}
return false
}
func isIntervalMode(mode configure.SubscriptionUpdateMode) bool {
return mode == configure.SubscriptionUpdateAtInterval || mode == configure.SubscriptionUpdateIntervalFailsafe
}
func (a *automation) subscriptionUnavailable(ctx context.Context, sub *configure.SubscriptionRaw, probeURL string, state *subscriptionSchedule) (bool, error) {
nodes := cloneProbeNodes(subscriptionNodes(sub))
for _, node := range nodes {
if node == nil {
if !state.warnedUnprobeable {
log.Warn("[Subscriptions] Subscription %d contains candidates that cannot be probed in isolation; fail-safe recovery is suspended, regular updates remain enabled", sub.DatabaseID)
state.warnedUnprobeable = true
}
// An unsupported probe is unknown health, not evidence that every
// candidate is down. Do not repeatedly download plugin subscriptions.
return false, ctx.Err()
}
}
state.warnedUnprobeable = false
results := a.probe(ctx, nodes, probeURL)
return !anyHealthy(results), ctx.Err()
}
func (a *automation) process(ctx context.Context, sub *configure.SubscriptionRaw, probeURL string) (err error) {
now := a.now()
signature := subscriptionPolicySignature(sub)
state := a.subscriptions[sub.DatabaseID]
if state == nil || state.signature != signature {
state = &subscriptionSchedule{signature: signature, nextUpdate: now}
a.subscriptions[sub.DatabaseID] = state
}
regularDue := !state.nextUpdate.IsZero() && !now.Before(state.nextUpdate)
retryDue := !state.nextRetry.IsZero() && !now.Before(state.nextRetry)
healthDue := !state.nextHealth.IsZero() && !now.Before(state.nextHealth)
interval := time.Duration(sub.FailureIntervalMinutes) * time.Minute
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("subscription update panicked: %v", recovered)
finished := a.now()
// A failed job must not leave an expired deadline spinning the worker.
if regularDue {
state.nextUpdate = time.Time{}
if isIntervalMode(sub.UpdateMode) {
state.nextUpdate = finished.Add(time.Duration(sub.UpdateIntervalMinutes) * time.Minute)
}
}
if !state.nextHealth.IsZero() {
state.nextHealth = finished.Add(interval)
}
if !state.nextRetry.IsZero() {
state.nextRetry = finished.Add(interval)
}
}
}()
if healthDue && !regularDue && !retryDue {
state.nextHealth = now.Add(interval)
unavailable, err := a.subscriptionUnavailable(ctx, sub, probeURL, state)
if err != nil {
state.nextHealth = a.now().Add(interval)
return err
}
if !unavailable {
state.nextHealth = a.now().Add(time.Duration(sub.FailureIntervalMinutes) * time.Minute)
return nil
}
retryDue = true
state.retryFromOutage = true
state.nextHealth = time.Time{}
}
if !regularDue && !retryDue {
return nil
}
if sub.UpdateMode == configure.SubscriptionUpdateIntervalFailsafe {
// Reserve a retry before cancellable work; a dashboard mutation must
// not consume the only deadline that can resume recovery. The
// reservation never touches retryFromOutage: only an actual
// all-unavailable health result arms the direct fallback, and a
// cancelled regular fetch therefore never promotes itself into a
// direct recovery attempt when its retry is re-armed below.
state.nextHealth = time.Time{}
state.nextRetry = a.now().Add(interval)
if regularDue {
state.nextUpdate = a.now().Add(time.Duration(sub.UpdateIntervalMinutes) * time.Minute)
}
defer func() {
if ctx.Err() != nil {
state.nextRetry = a.now().Add(interval)
if regularDue {
state.nextUpdate = a.now().Add(time.Duration(sub.UpdateIntervalMinutes) * time.Minute)
}
}
}()
}
nodes, info, err := a.fetch(ctx, sub.Address, retryDue && state.retryFromOutage && sub.AllowDirectRecovery)
if ctx.Err() != nil {
return ctx.Err()
}
if err == nil {
updated, applyErr := a.applyUpdate(ctx, sub, nodes, info)
if applyErr == nil {
sub = updated
v2ray.ApiFeed.ProductMessage("catalog_changed", nil)
} else {
err = applyErr
}
}
if err != nil {
log.Warn("[Subscriptions] Update %d failed; saved candidates retained: %v", sub.DatabaseID, err)
}
finished := a.now()
if regularDue {
state.nextUpdate = time.Time{}
if isIntervalMode(sub.UpdateMode) {
state.nextUpdate = finished.Add(time.Duration(sub.UpdateIntervalMinutes) * time.Minute)
}
}
if sub.UpdateMode != configure.SubscriptionUpdateIntervalFailsafe {
state.nextHealth, state.nextRetry = time.Time{}, time.Time{}
state.retryFromOutage = false
return nil
}
unavailable, err := a.subscriptionUnavailable(ctx, sub, probeURL, state)
if err != nil {
return err
}
state.nextHealth, state.nextRetry = time.Time{}, time.Time{}
state.retryFromOutage = false
if !unavailable {
state.nextHealth = a.now().Add(interval)
} else {
state.nextRetry = a.now().Add(interval)
state.retryFromOutage = true
}
return nil
}
func (a *automation) nextDeadline() time.Time {
var next time.Time
for _, state := range a.subscriptions {
for _, candidate := range []time.Time{state.nextUpdate, state.nextHealth, state.nextRetry} {
if !candidate.IsZero() && (next.IsZero() || candidate.Before(next)) {
next = candidate
}
}
}
return next
}
// step runs due jobs serially. If a pass takes longer than its interval, a
// second pass is never started in parallel; the next deadline starts at the
// completion time.
func (a *automation) step(parent context.Context) time.Time {
ctx, cancel := context.WithCancel(parent)
automationCancelMu.Lock()
automationCancel = cancel
automationCancelMu.Unlock()
defer func() {
cancel()
automationCancelMu.Lock()
automationCancel = nil
automationCancelMu.Unlock()
}()
ConfigurationMu.Lock()
subs := configure.GetSubscriptions()
probeURL := configure.GetOutboundSetting(configure.DefaultOutboundName).ProbeURL
ConfigurationMu.Unlock()
if probeURL == "" {
probeURL = HttpTestURL
}
active := map[int64]bool{}
for index := range subs {
sub := &subs[index]
if sub.UpdateMode == configure.SubscriptionUpdateDisabled {
continue
}
active[sub.DatabaseID] = true
if err := a.process(ctx, sub, probeURL); err != nil {
if ctx.Err() != nil {
return a.nextDeadline()
}
log.Warn("[Subscriptions] automation failed for %d: %v", sub.DatabaseID, err)
}
}
for id := range a.subscriptions {
if !active[id] {
delete(a.subscriptions, id)
}
}
return a.nextDeadline()
}
func StartAutomation() func() {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
worker := newAutomation()
for {
next := worker.step(ctx)
if ctx.Err() != nil {
return
}
var timer *time.Timer
var timerC <-chan time.Time
if !next.IsZero() {
delay := time.Until(next)
if delay < 0 {
delay = 0
}
timer = time.NewTimer(delay)
timerC = timer.C
}
select {
case <-ctx.Done():
if timer != nil {
timer.Stop()
}
return
case <-automationWake:
if timer != nil {
timer.Stop()
}
case <-timerC:
}
}
}()
return func() { cancel(); <-done }
}
+464
View File
@@ -0,0 +1,464 @@
package service
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/serverObj"
"github.com/v2rayA/v2rayA/kernel/touch"
)
func testAutomation(t *testing.T, mode configure.SubscriptionUpdateMode, regular, failure int) (*automation, *int, *bool) {
t.Helper()
resetSubscription(t)
sub := configure.GetSubscription(0)
sub.UpdateMode, sub.UpdateIntervalMinutes, sub.FailureIntervalMinutes = mode, regular, failure
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
a := newAutomation()
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
requests := 0
healthy := true
a.fetch = func(context.Context, string, bool) ([]serverObj.ServerObj, string, error) {
requests++
return []serverObj.ServerObj{testServer(t, 10001)}, "", nil
}
a.probe = func(_ context.Context, nodes []serverObj.ServerObj, _ string) []subscriptionProbeResult {
results := make([]subscriptionProbeResult, len(nodes))
if !healthy {
for i := range results {
results[i].err = errors.New("unavailable")
}
}
return results
}
return a, &requests, &healthy
}
func TestSubscriptionUpdateModes(t *testing.T) {
t.Run("disabled", func(t *testing.T) {
a, requests, _ := testAutomation(t, configure.SubscriptionUpdateDisabled, 0, 1)
a.step(context.Background())
if *requests != 0 || !a.nextDeadline().IsZero() {
t.Fatal("disabled subscription scheduled work")
}
})
t.Run("on-start", func(t *testing.T) {
a, requests, _ := testAutomation(t, configure.SubscriptionUpdateOnStart, 0, 1)
a.step(context.Background())
a.step(context.Background())
if *requests != 1 || !a.nextDeadline().IsZero() {
t.Fatalf("on-start requests=%d, next=%v", *requests, a.nextDeadline())
}
})
t.Run("interval", func(t *testing.T) {
a, requests, _ := testAutomation(t, configure.SubscriptionUpdateAtInterval, 3, 1)
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
a.step(context.Background())
now = now.Add(2 * time.Minute)
a.step(context.Background())
now = now.Add(time.Minute)
a.step(context.Background())
if *requests != 2 {
t.Fatalf("interval requests=%d", *requests)
}
})
t.Run("interval-failsafe", func(t *testing.T) {
a, requests, healthy := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 1)
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
*healthy = false
a.step(context.Background())
now = now.Add(time.Minute)
a.step(context.Background())
*healthy = true
now = now.Add(time.Minute)
a.step(context.Background())
now = now.Add(time.Minute)
a.step(context.Background())
if *requests != 3 {
t.Fatalf("failsafe requests=%d", *requests)
}
})
}
func TestSubscriptionScheduleUsesDatabaseIDAndPolicyFieldsOnly(t *testing.T) {
resetSubscription(t)
first := configure.GetSubscription(0)
first.UpdateMode, first.UpdateIntervalMinutes = configure.SubscriptionUpdateAtInterval, 60
if err := configure.SetSubscription(0, first); err != nil {
t.Fatal(err)
}
second := &configure.SubscriptionRaw{
Address: "https://second.invalid", UpdateMode: configure.SubscriptionUpdateAtInterval,
UpdateIntervalMinutes: 60, FailureIntervalMinutes: 1,
Servers: []configure.ServerRaw{{ServerObj: testServer(t, 10002)}},
}
if err := configure.AppendSubscriptions([]*configure.SubscriptionRaw{second}); err != nil {
t.Fatal(err)
}
second = configure.GetSubscription(1)
a := newAutomation()
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
requests := map[int]bool{}
a.fetch = func(_ context.Context, address string, _ bool) ([]serverObj.ServerObj, string, error) {
if address == second.Address {
requests[2] = true
} else {
requests[1] = true
}
return []serverObj.ServerObj{testServer(t, 10003)}, "", nil
}
a.step(context.Background())
delete(requests, 2)
second = configure.GetSubscription(1)
second.Status = "changed"
second.Servers[0].Latency = "12ms"
if err := configure.SetSubscription(1, second); err != nil {
t.Fatal(err)
}
if err := configure.RemoveSubscriptions([]int{0}); err != nil {
t.Fatal(err)
}
now = now.Add(time.Minute)
a.step(context.Background())
if requests[2] {
t.Fatal("latency change or index shift reset the later subscription timer")
}
}
func TestSubscriptionPatchWithoutPolicyKeepsPolicy(t *testing.T) {
resetSubscription(t)
sub := configure.GetSubscription(0)
sub.UpdateMode, sub.UpdateIntervalMinutes, sub.FailureIntervalMinutes = configure.SubscriptionUpdateIntervalFailsafe, 15, 2
sub.AllowDirectRecovery = true
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
request := touch.Subscription{ID: 1, Address: sub.Address, Remarks: "cached client", AutoSelect: sub.AutoSelect}
if err := ModifySubscriptionRemark(request); err != nil {
t.Fatal(err)
}
got := configure.GetSubscription(0)
if got.UpdateMode != configure.SubscriptionUpdateIntervalFailsafe || got.UpdateIntervalMinutes != 15 || got.FailureIntervalMinutes != 2 || !got.AllowDirectRecovery {
t.Fatalf("cached PATCH changed policy: %+v", got)
}
}
func TestDirectRecoveryRequiresOptInAndOutage(t *testing.T) {
for _, allowed := range []bool{false, true} {
t.Run(fmt.Sprintf("allowed=%v", allowed), func(t *testing.T) {
a, _, healthy := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 1)
sub := configure.GetSubscription(0)
sub.AllowDirectRecovery = allowed
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
var permissions []bool
fetch := a.fetch
a.fetch = func(ctx context.Context, address string, allowDirect bool) ([]serverObj.ServerObj, string, error) {
permissions = append(permissions, allowDirect)
return fetch(ctx, address, allowDirect)
}
a.step(context.Background())
*healthy = false
now = a.subscriptions[sub.DatabaseID].nextHealth
a.step(context.Background())
if len(permissions) != 2 || permissions[0] || permissions[1] != allowed {
t.Fatalf("direct download permissions = %v; want [false %v]", permissions, allowed)
}
if got := configure.GetSubscriptions()[0].AllowDirectRecovery; got != allowed {
t.Fatal("refresh or list read changed direct-download consent")
}
})
}
}
func TestSubscriptionPatchCanRevokeDirectRecovery(t *testing.T) {
sub := resetSubscription(t)
if sub.AllowDirectRecovery {
t.Fatal("new subscription enabled direct recovery")
}
allow := true
request := touch.Subscription{ID: 1, Address: sub.Address, AllowDirectRecovery: &allow}
if err := ModifySubscriptionRemark(request); err != nil {
t.Fatal(err)
}
generated := touch.GenerateTouch().Subscriptions[0]
if generated.AllowDirectRecovery == nil || !*generated.AllowDirectRecovery {
t.Fatal("saved opt-in was not returned to the GUI")
}
allow = false
if err := ModifySubscriptionRemark(request); err != nil {
t.Fatal(err)
}
if configure.GetSubscription(0).AllowDirectRecovery {
t.Fatal("explicit false did not revoke direct-download consent")
}
}
func TestFailsafeProbeCannotMutateStoredNode(t *testing.T) {
resetSubscription(t)
node, err := ResolveURL("vless://00000000-0000-0000-0000-000000000001@example.com:443?type=raw&security=none#raw")
if err != nil {
t.Fatal(err)
}
sub := configure.GetSubscription(0)
sub.UpdateMode, sub.UpdateIntervalMinutes, sub.FailureIntervalMinutes = configure.SubscriptionUpdateIntervalFailsafe, 10, 1
sub.Servers = []configure.ServerRaw{{ServerObj: node}}
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
want := configure.GetSubscription(0).Servers[0].ServerObj.ExportToURL()
a := newAutomation()
a.fetch = func(context.Context, string, bool) ([]serverObj.ServerObj, string, error) {
return []serverObj.ServerObj{node}, "", nil
}
a.probe = func(_ context.Context, nodes []serverObj.ServerObj, _ string) []subscriptionProbeResult {
if v, ok := nodes[0].(*serverObj.V2Ray); ok {
v.Net = "tcp"
}
return make([]subscriptionProbeResult, len(nodes))
}
a.step(context.Background())
if got := configure.GetSubscription(0).Servers[0].ServerObj.ExportToURL(); got != want {
t.Fatalf("probe mutated stored node: %q != %q", got, want)
}
}
func TestFailsafeCancellationKeepsDeadline(t *testing.T) {
for _, phase := range []string{"health-probe", "recovery-fetch", "post-update-probe", "regular-fetch"} {
t.Run(phase, func(t *testing.T) {
a, requests, healthy := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 2)
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
a.step(context.Background())
sub := configure.GetSubscription(0)
state := a.subscriptions[sub.DatabaseID]
regularDeadline := state.nextUpdate
now = state.nextHealth
if phase == "regular-fetch" {
now = state.nextUpdate
}
*healthy = false
fetch, probe := a.fetch, a.probe
probeCalls := 0
a.fetch = func(ctx context.Context, address string, recovery bool) ([]serverObj.ServerObj, string, error) {
if phase == "recovery-fetch" || phase == "regular-fetch" {
// Cancellation after a slow request must back off from completion.
now = now.Add(3 * time.Minute)
CancelAutomation()
return nil, "", ctx.Err()
}
return fetch(ctx, address, recovery)
}
a.probe = func(ctx context.Context, nodes []serverObj.ServerObj, url string) []subscriptionProbeResult {
probeCalls++
if phase == "health-probe" || (phase == "post-update-probe" && probeCalls == 2) {
CancelAutomation()
}
return probe(ctx, nodes, url)
}
next := a.step(context.Background())
if next.IsZero() || !next.After(now) || next.After(now.Add(2*time.Minute)) {
t.Fatalf("cancelled %s lost the worker deadline: now=%v, next=%v, state=%+v", phase, now, next, state)
}
if phase != "regular-fetch" && state.nextUpdate != regularDeadline {
t.Fatal("cancellation postponed the regular deadline")
}
a.fetch, a.probe = fetch, probe
now = next
before := *requests
a.step(context.Background())
if *requests != before+1 {
t.Fatal("recovery did not resume at the retained deadline")
}
})
}
}
func TestFailsafeDoesNotTreatUnprobeableNodesAsAnOutage(t *testing.T) {
for _, mixed := range []bool{false, true} {
t.Run(fmt.Sprintf("mixed=%v", mixed), func(t *testing.T) {
a, _, _ := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 2)
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
nodes := []serverObj.ServerObj{&serverObj.Plugin{Protocol: serverObj.PluginManagerScheme, Link: "plugin://fixture"}}
if mixed {
nodes = append(nodes, testServer(t, 10002))
}
requests := 0
a.fetch = func(_ context.Context, _ string, recovery bool) ([]serverObj.ServerObj, string, error) {
requests++
if recovery {
t.Fatal("unprobeable candidates triggered recovery")
}
return nodes, "", nil
}
a.probe = func(context.Context, []serverObj.ServerObj, string) []subscriptionProbeResult {
t.Fatal("unprobeable subscription started candidate cores")
return nil
}
a.step(context.Background())
for range 5 {
now = now.Add(2 * time.Minute)
a.step(context.Background())
}
if requests != 2 {
t.Fatalf("requests=%d, want startup and regular update only", requests)
}
})
}
}
func TestSwitchingToOnStartUpdatesOnceImmediately(t *testing.T) {
a, requests, _ := testAutomation(t, configure.SubscriptionUpdateAtInterval, 10, 1)
a.step(context.Background())
sub := configure.GetSubscription(0)
sub.UpdateMode = configure.SubscriptionUpdateOnStart
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
a.step(context.Background())
a.step(context.Background())
if *requests != 2 || !a.nextDeadline().IsZero() {
t.Fatalf("on-start after policy edit: requests=%d, next=%v", *requests, a.nextDeadline())
}
}
func TestCancelledRegularFetchDoesNotGainDirectPermission(t *testing.T) {
a, _, _ := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 1)
sub := configure.GetSubscription(0)
sub.AllowDirectRecovery = true
if err := configure.SetSubscription(0, sub); err != nil {
t.Fatal(err)
}
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
var direct []bool
a.fetch = func(_ context.Context, _ string, allow bool) ([]serverObj.ServerObj, string, error) {
direct = append(direct, allow)
return []serverObj.ServerObj{testServer(t, 10001)}, "", nil
}
// A dashboard mutation cancels the regular fetch mid-flight, like
// CancelAutomation does for a latency test.
cancelled, cancel := context.WithCancel(context.Background())
cancel()
a.step(cancelled)
// The re-armed retry is due while the regular deadline is not; no outage
// was detected, so neither fetch may carry direct permission.
now = now.Add(2 * time.Minute)
a.step(context.Background())
if len(direct) != 2 {
t.Fatalf("fetches=%d, want the regular fetch and its reserved retry", len(direct))
}
if direct[0] || direct[1] {
t.Fatalf("direct permission=%v, want no direct fetch without a detected outage", direct)
}
}
type panickingSubscriptionNode struct {
serverObj.ServerObj
}
func (panickingSubscriptionNode) ExportToURL() string { panic("apply failed") }
func TestAutomationContinuesAfterSubscriptionPanic(t *testing.T) {
for _, mode := range []configure.SubscriptionUpdateMode{
configure.SubscriptionUpdateOnStart,
configure.SubscriptionUpdateAtInterval,
configure.SubscriptionUpdateIntervalFailsafe,
} {
for _, phase := range []string{"fetch", "apply"} {
t.Run(string(mode)+"/"+phase, func(t *testing.T) {
a, _, _ := testAutomation(t, mode, 10, 2)
first := configure.GetSubscription(0)
first.AllowDirectRecovery = true
if err := configure.SetSubscription(0, first); err != nil {
t.Fatal(err)
}
second := *first
second.DatabaseID, second.Address = 0, "https://second.invalid"
if err := configure.AppendSubscriptions([]*configure.SubscriptionRaw{&second}); err != nil {
t.Fatal(err)
}
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
requests := 0
a.fetch = func(_ context.Context, address string, direct bool) ([]serverObj.ServerObj, string, error) {
requests++
if direct {
t.Fatal("panic granted direct permission without a detected outage")
}
if address == first.Address {
now = now.Add(3 * time.Minute)
if phase == "fetch" {
panic("fetch failed")
}
return []serverObj.ServerObj{panickingSubscriptionNode{}}, "", nil
}
return []serverObj.ServerObj{testServer(t, 10003)}, "updated", nil
}
next := a.step(context.Background())
if requests != 2 || configure.GetSubscription(1).Info != "updated" {
t.Fatal("panic stopped the next subscription's update")
}
if got := configure.GetSubscription(0).Servers[0].ServerObj.ExportToURL(); got != first.Servers[0].ServerObj.ExportToURL() {
t.Fatal("failed update changed the saved candidate")
}
if mode == configure.SubscriptionUpdateOnStart {
if !next.IsZero() {
t.Fatalf("on-start panic scheduled repeated work: %v", next)
}
} else {
interval := 10 * time.Minute
if mode == configure.SubscriptionUpdateIntervalFailsafe {
interval = 2 * time.Minute
}
if !next.Equal(now.Add(interval)) {
t.Fatalf("deadline = %v, want completion + %v", next, interval)
}
}
a.step(context.Background())
if requests != 2 {
t.Fatal("panic left an immediately due update")
}
if !next.IsZero() {
now = next
a.step(context.Background())
if requests <= 2 {
t.Fatal("worker did not resume at the next deadline")
}
}
})
}
}
}
func TestAutomationHealthPanicKeepsDeadline(t *testing.T) {
a, requests, _ := testAutomation(t, configure.SubscriptionUpdateIntervalFailsafe, 10, 2)
now := time.Unix(1000, 0)
a.now = func() time.Time { return now }
a.step(context.Background())
state := a.subscriptions[configure.GetSubscription(0).DatabaseID]
regular := state.nextUpdate
now = state.nextHealth
a.probe = func(context.Context, []serverObj.ServerObj, string) []subscriptionProbeResult {
now = now.Add(3 * time.Minute)
panic("health probe failed")
}
next := a.step(context.Background())
if !next.Equal(now.Add(2*time.Minute)) || state.nextUpdate != regular || state.retryFromOutage || *requests != 1 {
t.Fatalf("health panic changed the recovery policy: next=%v, state=%+v, requests=%d", next, state, *requests)
}
}
+20 -4
View File
@@ -10,7 +10,6 @@ import (
"github.com/v2rayA/v2rayA/pkg/util/log"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/common/httpClient"
"github.com/v2rayA/v2rayA/common/resolv"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/serverObj"
@@ -40,6 +39,11 @@ func subscriptionHost(source string) string {
// ImportServer or ImportSubscription instead; this wrapper only exists for
// clients that predate the "kind" field of POST /api/import.
func Import(url string, which *configure.NodeRef) (err error) {
return ImportWithOptions(url, which, SubscriptionFetchOptions{})
}
// ImportWithOptions imports a link and applies options if it is a subscription.
func ImportWithOptions(url string, which *configure.NodeRef, options SubscriptionFetchOptions) (err error) {
log.Trace("Import: received url=%v, which=%+v", url, which)
url = strings.TrimSpace(url)
if lines := strings.Split(url, "\n"); len(lines) >= 2 || strings.HasPrefix(url, "{") {
@@ -64,7 +68,7 @@ func Import(url string, which *configure.NodeRef) (err error) {
if isBareHttpProxyLink(url) {
return ImportServer(url, which)
}
return ImportSubscription(url)
return ImportSubscriptionWithOptions(url, options)
}
// isBareHttpProxyLink recognises the one http(s) URL shape that cannot be a
@@ -182,6 +186,11 @@ func ImportServer(url string, which *configure.NodeRef) (err error) {
// ImportSubscription fetches url (or the base64 payload of a sub:// link),
// parses the server list it returns and stores it as a new subscription.
func ImportSubscription(url string) (err error) {
return ImportSubscriptionWithOptions(url, SubscriptionFetchOptions{})
}
// ImportSubscriptionWithOptions imports a subscription with one-shot download options.
func ImportSubscriptionWithOptions(url string, options SubscriptionFetchOptions) (err error) {
resolv.CheckResolvConf()
url = strings.TrimSpace(url)
{
@@ -207,13 +216,20 @@ func ImportSubscription(url string) (err error) {
source = u.String()
}
}
c := httpClient.GetHttpClientAutomatically()
client, e := subscriptionHTTPClientWithOptions(SubscriptionFetchOptions{
BypassProxy: options.BypassProxy,
Host: subscriptionHost(source),
})
if e != nil {
return e
}
c := *client
c.Timeout = 90 * time.Second
// assign, do not redeclare: a shadowed err here made the
// AppendSubscriptions failure below vanish behind a nil return
var infos []serverObj.ServerObj
var status string
infos, status, err = ResolveSubscriptionWithClient(source, c)
infos, status, err = ResolveSubscriptionWithClient(source, &c)
if err != nil {
return fmt.Errorf("could not fetch subscription from %s: %w", subscriptionHost(source), err)
}
-5
View File
@@ -86,10 +86,5 @@ func UpdateSetting(setting *configure.Setting) (err error) {
} else {
conf.TickerUpdateGFWList.Reset(24 * time.Hour * 365 * 100)
}
if setting.SubscriptionAutoUpdateMode == configure.AutoUpdateAtIntervals {
conf.TickerUpdateSubscription.Reset(configure.IntervalHours(setting.SubscriptionAutoUpdateIntervalHour))
} else {
conf.TickerUpdateSubscription.Reset(24 * time.Hour * 365 * 100)
}
return
}
+201 -159
View File
@@ -2,6 +2,7 @@ package service
import (
"bytes"
"context"
"errors"
"fmt"
"io"
@@ -16,6 +17,7 @@ import (
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/common/httpClient"
"github.com/v2rayA/v2rayA/common/resolv"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/ipforward"
"github.com/v2rayA/v2rayA/kernel/serverObj"
@@ -43,6 +45,10 @@ type SIP008 struct {
} `json:"servers"`
}
var directSubscriptionClient = func() *http.Client {
return httpClient.DirectSubscriptionClient(v2ray.IsTransparentOn(configure.GetSettingNotNil()))
}
const maxSubscriptionDocumentSize int64 = 32 << 20
func readSubscriptionBody(resp *http.Response) ([]byte, error) {
@@ -186,6 +192,10 @@ func trapBOM(fileBytes []byte) []byte {
return trimmedBytes
}
func ResolveSubscriptionWithClient(source string, client *http.Client) (infos []serverObj.ServerObj, status string, err error) {
return resolveSubscriptionWithContext(context.Background(), source, client)
}
func resolveSubscriptionWithContext(ctx context.Context, source string, client *http.Client) (infos []serverObj.ServerObj, status string, err error) {
defer func() {
if err != nil {
var coded *common.CodedError
@@ -203,7 +213,12 @@ func ResolveSubscriptionWithClient(source string, client *http.Client) (infos []
c.Timeout = 30 * time.Second
}
res, err := httpClient.HttpGetUsingSpecificClient(&c, source)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, source, nil)
if err != nil {
return nil, "", err
}
req.Header.Set("User-Agent", fmt.Sprintf("v2rayA/%s WebRequestHelper", conf.Version))
res, err := c.Do(req)
if err != nil {
return nil, "", err
}
@@ -263,135 +278,115 @@ func getDataUsageStatus(bytesUsed, bytesRemaining uint64) (status string) {
return
}
// SubscriptionFetchOptions controls routing for one subscription download.
type SubscriptionFetchOptions struct {
// BypassProxy uses a direct client without changing the saved download route.
// It is a one-request user consent: callers must only set it after the user
// confirmed a direct download (the GUI asks when the proxy route is
// unavailable), and the server does not verify that itself. The flag only
// selects the direct route the user could also choose in settings.
BypassProxy bool
// SubscriptionID is the 1-based subscription ID shown to the user, used for
// logging consented bypasses. It is 0 for manual imports, which have no ID yet.
SubscriptionID int
// Host is the subscription host for logging; the full address is never logged.
Host string
}
func UpdateSubscription(index int, disconnectIfNecessary bool) (err error) {
return UpdateSubscriptionWithOptions(index, disconnectIfNecessary, SubscriptionFetchOptions{})
}
// UpdateSubscriptionWithOptions updates a subscription with one-shot download options.
func UpdateSubscriptionWithOptions(index int, disconnectIfNecessary bool, options SubscriptionFetchOptions) (err error) {
subscription := configure.GetSubscription(index)
if subscription == nil {
return common.Coded("SUBSCRIPTION_NOT_FOUND", fmt.Errorf("subscription #%d no longer exists; reload the page", index+1), map[string]interface{}{"id": index + 1})
}
addr := subscription.Address
c := httpClient.GetHttpClientAutomatically()
c, err := subscriptionHTTPClientWithOptions(SubscriptionFetchOptions{
BypassProxy: options.BypassProxy,
SubscriptionID: index + 1,
Host: subscriptionHost(addr),
})
if err != nil {
return err
}
resolv.CheckResolvConf()
subscriptionInfos, status, err := ResolveSubscriptionWithClient(addr, c)
if err != nil {
log.Warn("Subscription fetch failed: %v", err)
return fmt.Errorf("could not fetch subscription from %s: %w", subscriptionHost(addr), err)
}
infoServerRaws := make([]configure.ServerRaw, len(subscriptionInfos))
css := configure.GetConnectedServers()
cssAfter := css.Get()
// serverObj.ServerObj is a pointer(interface), and shouldn't be as a key
link2Raw := make(map[string]*configure.ServerRaw)
connectedVmessInfo2CssIndex := make(map[string][]int)
loc := configure.NewLocator()
for i, cs := range css.Get() {
if cs.TYPE == configure.SubscriptionServerType && cs.Sub == index {
if sRaw, err := loc.Locate(cs); err != nil {
return err
} else {
if sRaw.ServerObj == nil {
log.Warn("UpdateSubscription: skipping connected server with nil ServerObj (Sub=%d, ID=%d)", cs.Sub, cs.ID)
continue
}
link := sRaw.ServerObj.ExportToURL()
link2Raw[link] = sRaw
connectedVmessInfo2CssIndex[link] = append(connectedVmessInfo2CssIndex[link], i)
}
}
return storeSubscriptionUpdate(index, subscription, subscriptionInfos, status, disconnectIfNecessary)
}
func storeSubscriptionUpdate(index int, old *configure.SubscriptionRaw, nodes []serverObj.ServerObj, info string, disconnect bool) error {
next := *old
next.Servers = make([]configure.ServerRaw, len(nodes))
for i, node := range nodes {
next.Servers[i].ServerObj = node
}
// Replace list with new one, and find one with the same server value as the current connection, set it as Connected; if none, disconnect
for i, info := range subscriptionInfos {
infoServerRaw := configure.ServerRaw{
ServerObj: info,
}
link := infoServerRaw.ServerObj.ExportToURL()
if cssIndexes, ok := connectedVmessInfo2CssIndex[link]; ok {
for _, cssIndex := range cssIndexes {
cssAfter[cssIndex].ID = i + 1
}
delete(connectedVmessInfo2CssIndex, link)
}
infoServerRaws[i] = infoServerRaw
}
// Fallback: subscription providers often rename nodes (traffic/expiry counters in
// names) while keeping the same endpoint. Remap remaining connected servers to new
// servers with the same protocol, hostname and port.
looseKey := func(obj serverObj.ServerObj) string {
return obj.GetProtocol() + "://" + net.JoinHostPort(obj.GetHostname(), strconv.Itoa(obj.GetPort()))
}
loose2Index := make(map[string]int)
for i, info := range subscriptionInfos {
k := looseKey(info)
if _, ok := loose2Index[k]; !ok {
loose2Index[k] = i
}
}
var connectedServerChanged bool
for link, cssIndexes := range connectedVmessInfo2CssIndex {
if i, ok := loose2Index[looseKey(link2Raw[link].ServerObj)]; ok {
for _, cssIndex := range cssIndexes {
cssAfter[cssIndex].ID = i + 1
}
connectedServerChanged = true
log.Info("UpdateSubscription: remapped connected server %v to %v by endpoint match",
link2Raw[link].ServerObj.GetName(), subscriptionInfos[i].GetName())
delete(connectedVmessInfo2CssIndex, link)
}
}
// Last fallback: some providers keep node names stable but rotate IPs, which
// defeats the endpoint match. Remap by name, but only when the name maps to
// exactly one server on each side to avoid connecting to a different node.
name2Index := make(map[string]int)
nameCount := make(map[string]int)
for i, info := range subscriptionInfos {
nameCount[info.GetName()]++
name2Index[info.GetName()] = i
}
oldNameCount := make(map[string]int)
for link := range connectedVmessInfo2CssIndex {
oldNameCount[link2Raw[link].ServerObj.GetName()]++
}
for link, cssIndexes := range connectedVmessInfo2CssIndex {
name := link2Raw[link].ServerObj.GetName()
if nameCount[name] != 1 || oldNameCount[name] != 1 {
next.Status, next.Info = string(touch.NewUpdateStatus()), info
previous := configure.GetConnectedServers()
affected := false
updated := configure.NewNodeRefs(nil)
previousRefs := previous.Get()
mappedIDs := map[int]int{}
exactMatches := map[int]bool{}
fallbackClaims := map[int]int{}
for _, ref := range previousRefs {
if ref.TYPE != configure.SubscriptionServerType || ref.Sub != index || ref.ID <= 0 || ref.ID > len(old.Servers) {
continue
}
i := name2Index[name]
for _, cssIndex := range cssIndexes {
cssAfter[cssIndex].ID = i + 1
if _, seen := mappedIDs[ref.ID]; seen {
continue
}
mappedIDs[ref.ID], exactMatches[ref.ID] = remapSubscriptionNodeDetailed(old.Servers[ref.ID-1].ServerObj, nodes)
if mappedIDs[ref.ID] != 0 && !exactMatches[ref.ID] {
fallbackClaims[mappedIDs[ref.ID]]++
}
connectedServerChanged = true
log.Info("UpdateSubscription: remapped connected server %v (%v -> %v) by unique name match",
name, link2Raw[link].ServerObj.GetHostname(), subscriptionInfos[i].GetHostname())
delete(connectedVmessInfo2CssIndex, link)
}
for link, cssIndexes := range connectedVmessInfo2CssIndex {
for _, cssIndex := range cssIndexes {
if disconnectIfNecessary {
err = Disconnect(*css.Get()[cssIndex], false)
if err != nil {
return fmt.Errorf("could not disconnect the server that left the subscription: %w", err)
retainedIDs := map[int]int{}
for _, ref := range previousRefs {
copy := *ref
if ref.TYPE == configure.SubscriptionServerType && ref.Sub == index {
if ref.ID <= 0 || ref.ID > len(old.Servers) {
return fmt.Errorf("invalid connected server reference")
}
raw := old.Servers[ref.ID-1]
copy.ID = mappedIDs[ref.ID]
if !exactMatches[ref.ID] && fallbackClaims[copy.ID] > 1 {
copy.ID = 0
}
if copy.ID == 0 {
if disconnect {
affected = true
continue
}
} else {
// Append previously connected node
infoServerRaws = append(infoServerRaws, *link2Raw[link])
cssAfter[cssIndex].ID = len(infoServerRaws)
copy.ID = retainedIDs[ref.ID]
if copy.ID == 0 {
next.Servers = append(next.Servers, raw)
copy.ID = len(next.Servers)
retainedIDs[ref.ID] = copy.ID
}
}
if copy.ID != ref.ID || next.Servers[copy.ID-1].ServerObj.ExportToURL() != raw.ServerObj.ExportToURL() {
affected = true
}
}
updated.Add(copy)
}
subscription = configure.GetSubscription(index)
if subscription == nil {
return common.Coded("SUBSCRIPTION_NOT_FOUND", fmt.Errorf("subscription #%d no longer exists; reload the page", index+1), map[string]interface{}{"id": index + 1})
if !affected {
return configure.SetSubscriptionAndConnects(index, &next, updated)
}
subscription.Servers = infoServerRaws
subscription.Status = string(touch.NewUpdateStatus())
subscription.Info = status
if err := configure.SetSubscriptionAndConnects(index, subscription, configure.NewNodeRefs(cssAfter)); err != nil {
if err := configure.SetSubscriptionAndConnects(index, &next, updated); err != nil {
return err
}
// A remapped connection may point at a server whose config differs from the old
// one; the running core keeps using the old config until it is regenerated.
if connectedServerChanged && v2ray.ProcessManager.Running() {
if v2ray.ProcessManager.Running() {
if err := v2ray.UpdateV2RayConfig(); err != nil {
_ = configure.SetSubscriptionAndConnects(index, old, previous)
_ = v2ray.UpdateV2RayConfig()
return subscriptionCoreApplyError(err)
}
}
@@ -402,29 +397,105 @@ func subscriptionCoreApplyError(err error) error {
return fmt.Errorf("subscription stored, but the core could not apply it: %w", err)
}
func ModifySubscriptionRemark(subscription touch.Subscription) (err error) {
// Prefer full identity; accept a renamed/rotated endpoint only when its match
// is unambiguous. In particular, two accounts on one endpoint are not interchangeable.
func remapSubscriptionNodeDetailed(old serverObj.ServerObj, nodes []serverObj.ServerObj) (int, bool) {
if old == nil {
return 0, false
}
for i, node := range nodes {
if node.ExportToURL() == old.ExportToURL() {
return i + 1, true
}
}
for _, match := range []func(serverObj.ServerObj) bool{
func(n serverObj.ServerObj) bool {
return n.GetProtocol() == old.GetProtocol() && n.GetHostname() == old.GetHostname() && n.GetPort() == old.GetPort()
},
func(n serverObj.ServerObj) bool {
return old.GetName() != "" && n.GetName() == old.GetName() && n.GetProtocol() == old.GetProtocol()
},
} {
found := 0
for i, node := range nodes {
if match(node) {
if found != 0 {
found = -1
break
}
found = i + 1
}
}
if found > 0 {
return found, false
}
}
return 0, false
}
func ModifySubscriptionRemark(subscription touch.Subscription) error {
raw := configure.GetSubscription(subscription.ID - 1)
if raw == nil {
return common.Coded("SUBSCRIPTION_NOT_FOUND", fmt.Errorf("subscription #%d does not exist; reload the page", subscription.ID), map[string]interface{}{"id": subscription.ID})
return common.Coded("SUBSCRIPTION_NOT_FOUND", fmt.Errorf("subscription #%d does not exist", subscription.ID), map[string]interface{}{"id": subscription.ID})
}
raw.Remarks = subscription.Remarks
raw.Address = subscription.Address
mode := raw.UpdateMode
if subscription.UpdateMode != nil {
mode = *subscription.UpdateMode
}
regular, failure := raw.UpdateIntervalMinutes, raw.FailureIntervalMinutes
if subscription.UpdateIntervalMinutes != nil {
regular = *subscription.UpdateIntervalMinutes
}
if subscription.FailureIntervalMinutes != nil {
failure = *subscription.FailureIntervalMinutes
}
if failure == 0 && mode != configure.SubscriptionUpdateIntervalFailsafe {
failure = 1
}
switch mode {
case configure.SubscriptionUpdateDisabled, configure.SubscriptionUpdateOnStart:
case configure.SubscriptionUpdateAtInterval:
if (subscription.UpdateMode != nil && subscription.UpdateIntervalMinutes == nil) || regular < 1 || regular > 525600 {
return fmt.Errorf("update interval must be 1–525600 minutes")
}
case configure.SubscriptionUpdateIntervalFailsafe:
if (subscription.UpdateMode != nil && (subscription.UpdateIntervalMinutes == nil || subscription.FailureIntervalMinutes == nil)) || regular < 1 || regular > 525600 || failure < 1 || failure > 525600 {
return fmt.Errorf("regular and failure intervals must be 1–525600 minutes")
}
default:
return fmt.Errorf("unknown subscription update mode %q", mode)
}
raw.Remarks, raw.Address = subscription.Remarks, subscription.Address
raw.AutoSelect = subscription.AutoSelect
raw.UpdateMode, raw.UpdateIntervalMinutes, raw.FailureIntervalMinutes = mode, regular, failure
if subscription.AllowDirectRecovery != nil {
raw.AllowDirectRecovery = *subscription.AllowDirectRecovery
}
return configure.SetSubscription(subscription.ID-1, raw)
}
func SelectServersFromSubscription(index int, shouldDisconnect bool) (err error) {
var subscriptionServer configure.NodeRef
subscriptionServer.TYPE = "subscriptionServer"
subscriptionServer.Sub = index // Subscription IDs start with 0
subscriptionServer.Outbound = "proxy"
func subscriptionHTTPClient() (*http.Client, error) {
// Do not use the automatic client: it silently selects a direct route
// when the main core is stopped or transparent proxying is enabled.
switch configure.GetSettingNotNil().ProxyModeWhenSubscribe {
case configure.ProxyModeProxy:
return httpClient.GetHttpClientWithv2rayAProxy()
case configure.ProxyModePac:
return httpClient.GetHttpClientWithv2rayAPac()
default:
return directSubscriptionClient(), nil
}
}
func SelectServersFromSubscription(index int, shouldDisconnect bool) error {
const outbound = "proxy"
if shouldDisconnect {
connections := configure.GetConnectedServersByOutbound(subscriptionServer.Outbound)
connections := configure.GetConnectedServersByOutbound(outbound)
if connections == nil {
return nil
}
remaining := make([]configure.NodeRef, 0, connections.Len())
var found bool
found := false
for _, connected := range connections.Get() {
if connected.TYPE == configure.SubscriptionServerType && connected.Sub == index {
found = true
@@ -435,16 +506,14 @@ func SelectServersFromSubscription(index int, shouldDisconnect bool) (err error)
if !found {
return nil
}
return ReplaceOutboundConnections(subscriptionServer.Outbound, remaining)
return ReplaceOutboundConnections(outbound, remaining)
}
// One replacement for the whole subscription: connecting the members one
// by one restarted the core once per node.
sub := configure.GetSubscription(index)
if sub == nil {
return common.Coded("SUBSCRIPTION_NOT_FOUND", fmt.Errorf("subscription #%d no longer exists", index+1), map[string]interface{}{"id": index + 1})
}
backup := configure.GetConnectedServersByOutbound(subscriptionServer.Outbound)
backup := configure.GetConnectedServersByOutbound(outbound)
var existing []*configure.NodeRef
if backup != nil {
existing = backup.Get()
@@ -453,27 +522,23 @@ func SelectServersFromSubscription(index int, shouldDisconnect bool) (err error)
if len(members) == len(existing) {
return nil
}
// What Connect did once per node: the asset check and the ip forward
// reconciliation, then the store, then the core.
if err := checkSupport(nil); err != nil {
return err
}
if setting := GetSetting(); setting.IpForward != ipforward.IsIpForwardOn() {
if e := ipforward.WriteIpForward(setting.IpForward); e != nil {
log.Warn("[AutoSelect] %v", e)
if err := ipforward.WriteIpForward(setting.IpForward); err != nil {
log.Warn("[AutoSelect] %v", err)
}
}
if err := ReplaceOutboundConnections(subscriptionServer.Outbound, members); err != nil {
if err := ReplaceOutboundConnections(outbound, members); err != nil {
return err
}
// Connect started the core for a selection made while it was stopped,
// and dropped the selection when that failed.
if !v2ray.ProcessManager.Running() {
if err := v2ray.UpdateV2RayConfig(); err != nil {
if backup != nil && backup.Len() > 0 {
_ = configure.OverwriteConnects(backup)
} else {
_ = configure.ClearConnects(subscriptionServer.Outbound)
_ = configure.ClearConnects(outbound)
}
return err
}
@@ -481,8 +546,6 @@ func SelectServersFromSubscription(index int, shouldDisconnect bool) (err error)
return nil
}
// autoSelectMembers appends every supported node of the subscription to the
// members already in the proxy group.
func autoSelectMembers(index int, sub *configure.SubscriptionRaw, existing []*configure.NodeRef) []configure.NodeRef {
members := make([]configure.NodeRef, 0, len(existing)+len(sub.Servers))
for _, connected := range existing {
@@ -490,45 +553,24 @@ func autoSelectMembers(index int, sub *configure.SubscriptionRaw, existing []*co
}
for i, server := range sub.Servers {
if server.ServerObj == nil {
log.Warn("[AutoSelect] Skipping server %d in subscription %d: nil ServerObj", i+1, index)
continue
}
serverName := server.ServerObj.GetName()
// Workaround for partial SS support in v2fly and xray
if supported, _ := isSupportedObj(server.ServerObj); !supported {
log.Info("[AutoSelect] Skipping unsupported server %v", serverName)
continue
}
members = append(members, configure.NodeRef{TYPE: configure.SubscriptionServerType, ID: i + 1, Sub: index, Outbound: "proxy"})
log.Info("[AutoSelect] Automatically selected server: %v", serverName)
}
return members
}
func AutoSelectServersFromSubscriptions(shouldDisconnect bool) (err error) {
for i := 0; i < configure.GetLenSubscriptions(); i++ {
subscription := configure.GetSubscription(i)
if subscription == nil {
log.Warn("[AutoSelect] Failed to read subscription at index %d, skipping", i)
continue
}
if subscription.AutoSelect {
if shouldDisconnect {
log.Info("[AutoSelect] Automatically disconnecting servers from subscription: %v", subscription.Address)
err := SelectServersFromSubscription(i, true)
if err != nil {
log.Error("[AutoSelect] Failed to disconnect servers from subscription: %v", subscription.Address)
return err
}
} else {
log.Info("[AutoSelect] Automatically selecting servers from subscription: %v", subscription.Address)
err := SelectServersFromSubscription(i, false)
if err != nil {
log.Error("[AutoSelect] Failed to select servers from subscription: %v", subscription.Address)
return err
}
}
func subscriptionHTTPClientWithOptions(options SubscriptionFetchOptions) (*http.Client, error) {
if options.BypassProxy {
if options.SubscriptionID > 0 {
log.Info("[Subscriptions] Consented direct download for subscription %d from %s", options.SubscriptionID, options.Host)
} else {
log.Info("[Subscriptions] Consented direct download for manual import from %s", options.Host)
}
return directSubscriptionClient(), nil
}
return nil
return subscriptionHTTPClient()
}
@@ -0,0 +1,187 @@
package service
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"sync"
"time"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/coreObj"
"github.com/v2rayA/v2rayA/kernel/serverObj"
"github.com/v2rayA/v2rayA/kernel/v2ray"
"github.com/v2rayA/v2rayA/kernel/v2ray/asset"
"github.com/v2rayA/v2rayA/kernel/v2ray/where"
)
const subscriptionProbeTimeout = 5 * time.Second
func probeSubscription(servers []serverObj.ServerObj, probeURL string) []subscriptionProbeResult {
return probeSubscriptionWithContext(context.Background(), servers, probeURL)
}
func probeSubscriptionWithContext(ctx context.Context, servers []serverObj.ServerObj, probeURL string) []subscriptionProbeResult {
servers = cloneProbeNodes(servers)
results := make([]subscriptionProbeResult, len(servers))
// Limit extra core processes on routers; still wait for the entire subscription.
jobs := make(chan int)
var wg sync.WaitGroup
for worker := 0; worker < 2; worker++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i].latency, results[i].err = probeSubscriptionServerWithContext(ctx, servers[i], probeURL, subscriptionProbeTimeout)
}
}()
}
for i := range servers {
jobs <- i
}
close(jobs)
wg.Wait()
return results
}
// Configuration normalises some protocols in place. Probes therefore receive
// objects reconstructed from their links instead of pointers stored in the
// catalog. Plugin-managed nodes are deliberately left nil: configuring one can
// run an external process that cannot be cancelled by this worker.
func cloneProbeNodes(servers []serverObj.ServerObj) []serverObj.ServerObj {
clones := make([]serverObj.ServerObj, len(servers))
for i, server := range servers {
if server == nil {
continue
}
if _, plugin := server.(*serverObj.Plugin); plugin {
continue
}
clone, err := ResolveURL(server.ExportToURL())
if err == nil {
clones[i] = clone
}
}
return clones
}
func probeSubscriptionServer(server serverObj.ServerObj, probeURL string, timeout time.Duration) (time.Duration, error) {
return probeSubscriptionServerWithContext(context.Background(), server, probeURL, timeout)
}
func probeSubscriptionServerWithContext(parent context.Context, server serverObj.ServerObj, probeURL string, timeout time.Duration) (time.Duration, error) {
if err := parent.Err(); err != nil {
return 0, err
}
u, err := url.Parse(probeURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return 0, fmt.Errorf("invalid HTTP probe URL")
}
if server == nil {
return 0, fmt.Errorf("server requires an external plugin and cannot be probed in isolation")
}
bin, err := where.GetV2rayBinPath()
if err != nil {
return 0, err
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
defer listener.Close()
port := listener.Addr().(*net.TCPAddr).Port
tmpl := v2ray.NewEmptyTemplate(configure.GetSettingNotNil())
defer tmpl.Close()
if err := tmpl.InsertMappingOutbound(server, strconv.Itoa(port), false, 0, "http"); err != nil {
return 0, err
}
tmpl.Inbounds[0].Listen = "127.0.0.1"
// Candidate connections must not be intercepted by the main group's
// transparent proxy, especially while that group is empty and blocking.
tmpl.SetOutboundSockopt()
tmpl.Routing.DomainStrategy = "AsIs"
tmpl.Log = &coreObj.Log{Access: "none", Error: "none", Loglevel: "none"}
file, err := os.CreateTemp("", "v2raya-subscription-*.json")
if err != nil {
return 0, err
}
defer os.Remove(file.Name())
if _, err = file.Write(tmpl.ToConfigBytes()); err != nil {
file.Close()
return 0, err
}
if err = file.Close(); err != nil {
return 0, err
}
startupTimeout := time.Duration(conf.GetEnvironmentConfig().CoreStartupTimeout) * time.Second
if startupTimeout <= 0 {
startupTimeout = 15 * time.Second
}
ctx, cancel := context.WithTimeout(parent, startupTimeout+timeout)
defer cancel()
cmd := exec.CommandContext(ctx, bin, "run", "--config="+file.Name())
cmd.Env = append(os.Environ(), "XRAY_LOCATION_ASSET="+asset.GetV2rayLocationAssetOverride(), "V2RAY_CONF_GEOLOADER=memconservative")
listener.Close()
if err = cmd.Start(); err != nil {
return 0, err
}
done := make(chan struct{})
go func() {
_ = cmd.Wait()
close(done)
}()
defer func() {
cancel()
<-done
}()
readyCtx, readyCancel := context.WithTimeout(ctx, startupTimeout)
defer readyCancel()
address := net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
ticker := time.NewTicker(25 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-done:
return 0, fmt.Errorf("probe core exited before becoming ready")
case <-readyCtx.Done():
return 0, fmt.Errorf("probe core startup timeout")
case <-ticker.C:
conn, e := net.DialTimeout("tcp", address, 100*time.Millisecond)
if e == nil {
conn.Close()
return probeHTTP(ctx, address, probeURL, timeout)
}
}
}
}
func probeHTTP(ctx context.Context, proxyAddress, probeURL string, timeout time.Duration) (time.Duration, error) {
transport := &http.Transport{Proxy: http.ProxyURL(&url.URL{Scheme: "http", Host: proxyAddress})}
defer transport.CloseIdleConnections()
client := &http.Client{
Transport: transport,
Timeout: timeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, probeURL, nil)
if err != nil {
return 0, err
}
req.Header.Set("Cache-Control", "no-cache")
start := time.Now()
resp, err := client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return 0, fmt.Errorf("probe returned HTTP %d", resp.StatusCode)
}
return time.Since(start), nil
}
@@ -0,0 +1,410 @@
package service
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/kernel/serverObj"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
func testServer(t *testing.T, port int) serverObj.ServerObj {
t.Helper()
s, err := ResolveURL(fmt.Sprintf("http-proxy://127.0.0.1:%d#server-%d", port, port))
if err != nil {
t.Fatal(err)
}
return s
}
func namedTestServer(t *testing.T, port int, name string) serverObj.ServerObj {
t.Helper()
s, err := ResolveURL(fmt.Sprintf("http-proxy://127.0.0.1:%d#%s", port, name))
if err != nil {
t.Fatal(err)
}
return s
}
func resetSubscription(t *testing.T) *configure.SubscriptionRaw {
t.Helper()
t.Cleanup(func() {
for _, out := range configure.GetOutbounds() {
_ = configure.ClearConnects(out)
}
ids := make([]int, configure.GetLenSubscriptions())
for i := range ids {
ids[i] = i
}
if len(ids) > 0 {
_ = configure.RemoveSubscriptions(ids)
}
_ = configure.SetRunning(false)
_ = configure.SetLastKernelExitStatus(configure.LastKernelExitStopped)
})
for _, out := range configure.GetOutbounds() {
if err := configure.ClearConnects(out); err != nil {
t.Fatal(err)
}
}
indexes := make([]int, configure.GetLenSubscriptions())
for i := range indexes {
indexes[i] = i
}
if len(indexes) > 0 {
if err := configure.RemoveSubscriptions(indexes); err != nil {
t.Fatal(err)
}
}
_ = configure.SetOutboundSetting("proxy", configure.DefaultOutboundSetting())
cfg := configure.New()
sub := &configure.SubscriptionRaw{Address: "http://subscription.invalid", FailureIntervalMinutes: 1,
Servers: []configure.ServerRaw{{ServerObj: testServer(t, 10001)}}}
cfg.Subscriptions = []*configure.SubscriptionRaw{sub}
if err := configure.SetConfigure(cfg); err != nil {
t.Fatal(err)
}
if err := configure.AddConnect(configure.NodeRef{TYPE: configure.SubscriptionServerType, Sub: 0, ID: 1, Outbound: "proxy"}); err != nil {
t.Fatal(err)
}
return configure.GetSubscription(0)
}
func TestSubscriptionDownloadFailuresPreserveState(t *testing.T) {
for _, tc := range []struct {
name, body string
status int
}{
{"http-error", base64.StdEncoding.EncodeToString([]byte("http-proxy://127.0.0.1:9999")), 503},
{"empty", "", 200}, {"invalid", "not a subscription", 200},
} {
t.Run(tc.name, func(t *testing.T) {
old := resetSubscription(t)
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(tc.status); fmt.Fprint(w, tc.body) }))
defer s.Close()
old.Address = s.URL
if err := configure.SetSubscription(0, old); err != nil {
t.Fatal(err)
}
before := configure.GetConnectedServers()
if err := UpdateSubscription(0, false); err == nil {
t.Fatal("expected failure")
}
if !reflect.DeepEqual(old, configure.GetSubscription(0)) || !reflect.DeepEqual(before, configure.GetConnectedServers()) {
t.Fatal("download failure changed state")
}
})
}
}
func TestSubscriptionInvalidIndex(t *testing.T) {
resetSubscription(t)
for _, index := range []int{-1, 99} {
if err := UpdateSubscription(index, false); err == nil {
t.Fatal("expected invalid index error")
}
}
}
func TestSubscriptionNameFallbackDoesNotCollapseTwoSelections(t *testing.T) {
old := resetSubscription(t)
old.Servers = []configure.ServerRaw{
{ServerObj: namedTestServer(t, 10001, "same")},
{ServerObj: namedTestServer(t, 10002, "same")},
}
if err := configure.SetSubscription(0, old); err != nil {
t.Fatal(err)
}
if err := configure.ClearConnects("proxy"); err != nil {
t.Fatal(err)
}
for id := 1; id <= 2; id++ {
if err := configure.AddConnect(configure.NodeRef{TYPE: configure.SubscriptionServerType, Sub: 0, ID: id, Outbound: "proxy"}); err != nil {
t.Fatal(err)
}
}
old = configure.GetSubscription(0)
if err := storeSubscriptionUpdate(0, old, []serverObj.ServerObj{namedTestServer(t, 10003, "same")}, "", false); err != nil {
t.Fatal(err)
}
refs := configure.GetConnectedServersByOutbound("proxy").Get()
if len(refs) != 2 || refs[0].ID == refs[1].ID {
t.Fatalf("ambiguous name fallback collapsed selections: %+v", refs)
}
}
func TestSubscriptionRemapsOneNodeInMultipleGroups(t *testing.T) {
for _, rotated := range []bool{false, true} {
t.Run(fmt.Sprintf("rotated=%v", rotated), func(t *testing.T) {
old := resetSubscription(t)
const secondGroup = "second"
if err := configure.AddOutbound(secondGroup); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = configure.RemoveOutbound(secondGroup) })
if err := configure.AddConnect(configure.NodeRef{TYPE: configure.SubscriptionServerType, Sub: 0, ID: 1, Outbound: secondGroup}); err != nil {
t.Fatal(err)
}
name := "unrelated"
if rotated {
name = old.Servers[0].ServerObj.GetName()
}
replacement := namedTestServer(t, 10002, name)
if err := storeSubscriptionUpdate(0, old, []serverObj.ServerObj{replacement}, "", false); err != nil {
t.Fatal(err)
}
wantID, wantNodes := 2, 2
if rotated {
wantID, wantNodes = 1, 1
}
if got := len(configure.GetSubscription(0).Servers); got != wantNodes {
t.Fatalf("stored %d nodes, want %d", got, wantNodes)
}
for _, group := range []string{"proxy", secondGroup} {
refs := configure.GetConnectedServersByOutbound(group).Get()
if len(refs) != 1 || refs[0].ID != wantID {
t.Fatalf("%s references = %+v, want ID %d", group, refs, wantID)
}
}
})
}
}
type subscriptionRoundTripper func(*http.Request) (*http.Response, error)
func (f subscriptionRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func TestSubscriptionDownloadsRespectProxyMode(t *testing.T) {
for _, mode := range []configure.ProxyMode{configure.ProxyModeProxy, configure.ProxyModePac} {
for _, transparent := range []configure.TransparentMode{configure.TransparentClose, configure.TransparentProxy} {
t.Run(fmt.Sprintf("%s/transparent=%s", mode, transparent), func(t *testing.T) {
old := resetSubscription(t)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
if err := configure.SetPorts(&configure.Ports{Socks5: port, HttpWithPac: port}); err != nil {
t.Fatal(err)
}
setting := configure.GetSettingNotNil()
setting.ProxyModeWhenSubscribe, setting.Transparent = mode, transparent
if err := configure.SetSetting(setting); err != nil {
t.Fatal(err)
}
var directRequests atomic.Int32
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
directRequests.Add(1)
fmt.Fprint(w, base64.StdEncoding.EncodeToString([]byte("http-proxy://127.0.0.1:1234#test")))
}))
defer provider.Close()
originalDirect := directSubscriptionClient
directSubscriptionClient = func() *http.Client { return provider.Client() }
t.Cleanup(func() { directSubscriptionClient = originalDirect })
old.Address = provider.URL
old.AllowDirectRecovery = true
if err := configure.SetSubscription(0, old); err != nil {
t.Fatal(err)
}
if err := UpdateSubscription(0, false); err == nil {
t.Fatal("manual update bypassed the failed proxy")
}
if err := ImportSubscription(provider.URL); err == nil {
t.Fatal("import bypassed the failed proxy")
}
if _, _, err := fetchSubscriptionForAutomation(context.Background(), provider.URL, false); err == nil {
t.Fatal("scheduled update bypassed the failed proxy")
}
if got := directRequests.Load(); got != 0 {
t.Fatalf("non-recovery downloads made %d direct requests", got)
}
options := SubscriptionFetchOptions{BypassProxy: true}
if err := UpdateSubscriptionWithOptions(0, false, options); err != nil {
t.Fatalf("confirmed direct update failed: %v", err)
}
if err := ImportSubscriptionWithOptions(provider.URL, options); err != nil {
t.Fatalf("confirmed direct import failed: %v", err)
}
if got := directRequests.Load(); got != 2 {
t.Fatalf("confirmed direct downloads made %d requests, want 2", got)
}
if got := configure.GetSettingNotNil().ProxyModeWhenSubscribe; got != mode {
t.Fatalf("confirmed direct downloads changed route to %q, want %q", got, mode)
}
if err := UpdateSubscription(0, false); err == nil {
t.Fatal("one-shot bypass changed the saved subscription route")
}
if err := ImportSubscription(provider.URL); err == nil {
t.Fatal("one-shot bypass affected a later import")
}
if got := directRequests.Load(); got != 2 {
t.Fatalf("later configured-route downloads made %d direct requests, want 2", got)
}
})
}
}
}
func TestSubscriptionRecoveryFallbackKeepsTimeout(t *testing.T) {
resetSubscription(t)
setting := configure.GetSettingNotNil()
setting.ProxyModeWhenSubscribe = configure.ProxyModeProxy
if err := configure.SetSetting(setting); err != nil {
t.Fatal(err)
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
if err := configure.SetPorts(&configure.Ports{Socks5: port}); err != nil {
t.Fatal(err)
}
originalDirect := directSubscriptionClient
t.Cleanup(func() { directSubscriptionClient = originalDirect })
fallbackAttempts := 0
client := &http.Client{Transport: subscriptionRoundTripper(func(r *http.Request) (*http.Response, error) {
fallbackAttempts++
deadline, ok := r.Context().Deadline()
if !ok || time.Until(deadline) > 30*time.Second {
t.Fatal("download attempt has no bounded timeout")
}
if !strings.Contains(r.UserAgent(), "WebRequestHelper") {
t.Fatal("missing subscription user agent")
}
body := base64.StdEncoding.EncodeToString([]byte("http-proxy://127.0.0.1:1234#fallback"))
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
})}
directSubscriptionClient = func() *http.Client { return client }
servers, _, err := fetchSubscriptionForAutomation(context.Background(), "http://subscription.invalid", true)
if err != nil || len(servers) != 1 || fallbackAttempts != 1 {
t.Fatalf("fallback failed: %v, %d servers, attempts %d", err, len(servers), fallbackAttempts)
}
if client.Timeout != 0 {
t.Fatal("download modified a shared HTTP client")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, _, err := fetchSubscriptionForAutomation(ctx, "http://subscription.invalid", true); !errors.Is(err, context.Canceled) || fallbackAttempts != 1 {
t.Fatalf("cancelled fetch retried: %v, attempts %d", err, fallbackAttempts)
}
}
func TestProbeWithCurrentCore(t *testing.T) {
if os.Getenv("V2RAYA_V2RAY_BIN") == "" {
t.Skip("set V2RAYA_V2RAY_BIN to run real-core tests")
}
resetSubscription(t)
for _, status := range []int{204, 302, 503} {
t.Run(fmt.Sprint(status), func(t *testing.T) {
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Hostname() != "probe.invalid" {
t.Errorf("request did not traverse proxy: %s", r.URL)
}
conn, rw, err := w.(http.Hijacker).Hijack()
if err != nil {
return
}
defer conn.Close()
fmt.Fprint(rw, "HTTP/1.1 200 Connection established\r\n\r\n")
rw.Flush()
if _, err = http.ReadRequest(rw.Reader); err != nil {
return
}
fmt.Fprintf(rw, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", status, http.StatusText(status))
rw.Flush()
}))
defer proxy.Close()
port := proxy.Listener.Addr().(*net.TCPAddr).Port
_, err := probeSubscriptionServer(testServer(t, port), "http://probe.invalid/check", time.Second)
if (err == nil) != (status == 204) {
t.Fatalf("status %d: %v", status, err)
}
})
}
t.Run("closed", func(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
if _, err := probeSubscriptionServer(testServer(t, port), "http://probe.invalid/check", time.Second); err == nil {
t.Fatal("closed port reported healthy")
}
})
t.Run("blackhole", func(t *testing.T) {
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
defer proxy.Close()
start := time.Now()
_, err := probeSubscriptionServer(testServer(t, proxy.Listener.Addr().(*net.TCPAddr).Port), "http://probe.invalid/check", 200*time.Millisecond)
if err == nil || time.Since(start) > 3*time.Second {
t.Fatalf("unbounded blackhole: %v", err)
}
})
}
func TestConsentedBypassLogsIDAndHost(t *testing.T) {
old := resetSubscription(t)
setting := configure.GetSettingNotNil()
setting.ProxyModeWhenSubscribe = configure.ProxyModeProxy
if err := configure.SetSetting(setting); err != nil {
t.Fatal(err)
}
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, base64.StdEncoding.EncodeToString([]byte("http-proxy://127.0.0.1:1234#test")))
}))
defer provider.Close()
originalDirect := directSubscriptionClient
directSubscriptionClient = func() *http.Client { return provider.Client() }
t.Cleanup(func() { directSubscriptionClient = originalDirect })
old.Address = provider.URL
if err := configure.SetSubscription(0, old); err != nil {
t.Fatal(err)
}
_ = log.Log.SetLogger("memory", "")
log.SetLogLevel("info")
t.Cleanup(func() { log.SetLogLevel("warning") })
_, start := log.ReadMemory(1 << 60)
options := SubscriptionFetchOptions{BypassProxy: true}
if err := UpdateSubscriptionWithOptions(0, false, options); err != nil {
t.Fatalf("confirmed direct update failed: %v", err)
}
if err := ImportSubscriptionWithOptions(provider.URL, options); err != nil {
t.Fatalf("confirmed direct import failed: %v", err)
}
tail := ""
deadline := time.Now().Add(5 * time.Second)
for {
data, _ := log.ReadMemory(start)
tail = string(data)
if strings.Contains(tail, "subscription 1 from 127.0.0.1") &&
strings.Contains(tail, "manual import from 127.0.0.1") {
break
}
if time.Now().After(deadline) {
t.Fatalf("consented bypass not logged with ID and host, tail:\n%s", tail)
}
time.Sleep(50 * time.Millisecond)
}
if strings.Contains(tail, provider.URL) {
t.Fatalf("log leaks the full subscription address:\n%s", tail)
}
}
@@ -0,0 +1,13 @@
package service
import (
"sync"
"time"
)
var ConfigurationMu sync.Mutex
type subscriptionProbeResult struct {
latency time.Duration
err error
}
@@ -7,8 +7,20 @@ import (
"strings"
"testing"
"time"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/kernel/touch"
)
func TestModifyMissingSubscriptionIncludesID(t *testing.T) {
resetSubscription(t)
err := ModifySubscriptionRemark(touch.Subscription{ID: 42})
var coded *common.CodedError
if !errors.As(err, &coded) || coded.Code != "SUBSCRIPTION_NOT_FOUND" || coded.Params["id"] != 42 {
t.Fatalf("error = %#v, want SUBSCRIPTION_NOT_FOUND with id=42", err)
}
}
func TestSubscriptionBodyOverLimitIsRejected(t *testing.T) {
client := &http.Client{Transport: updateTransport(func(*http.Request) (*http.Response, error) {
return &http.Response{