diff --git a/src/dae/ruleText.test.ts b/src/dae/ruleText.test.ts index 2495fb22..4772ac9b 100644 --- a/src/dae/ruleText.test.ts +++ b/src/dae/ruleText.test.ts @@ -187,10 +187,36 @@ it('appends to a DNS list that writes no fallback, before the line closing its b const tabbed = 'dns {\n\trouting {\n\t\trequest {\n\t\t}\n\t}\n}\n'; const end = dnsListEnd([{...source, content: tabbed}], 'request')!; expect(addRule(tabbed, end.anchor, 'qtype(A)', 'reject', false)).toBe('dns {\n\trouting {\n\t\trequest {\n\t\t\tqtype(A) -> reject\n\t\t}\n\t}\n}\n'); - // No block, a block closed on a line that holds more, a read-only source, or two blocks to choose between: no end. - expect(dnsListEnd([{...source, content: 'dns {\n routing {\n }\n}\n'}], 'request')).toBeNull(); + // A block closed on a line that holds more, a read-only source, or two blocks to choose between: no end. expect(dnsListEnd([{...source, content: 'dns {\n routing {\n request {}\n }\n}\n'}], 'request')).toBeNull(); expect(dnsListEnd([{...source, writable: false}], 'request')).toBeNull(); expect(dnsListEnd([source, {...source, id: 'other'}], 'request')).toBeNull(); expect(dnsListEnd([{...source, content: undefined}], 'request')).toBeNull(); }); + +it('creates an absent DNS list block at the end of the dns routing block', () => { + const text = 'dns {\n routing {\n request {\n fallback: asis\n }\n }\n}\n'; + const source = {id: 'dns', content: text, writable: true} as ConfigSource; + const response = dnsListEnd([source], 'response')!; + expect(response.source).toBe(source); + expect(addRule(text, response.anchor, 'ip(geoip: private)', 'reject', false)).toBe( + 'dns {\n routing {\n request {\n fallback: asis\n }\n response {\n ip(geoip: private) -> reject\n }\n }\n}\n' + ); + // No fallback is written: honk gives a created list the fallback an absent one has (request: default, response: accept). + // honk-config's parser reads both results with no diagnostics. + const withUpstream = + "dns {\n upstream {\n alidns: 'udp://223.5.5.5:53'\n }\n routing {\n response {\n upstream(alidns) -> accept\n }\n }\n}\n"; + const request = dnsListEnd([{...source, content: withUpstream}], 'request')!; + expect(addRule(withUpstream, request.anchor, 'qname(suffix: cn)', 'alidns', false)).toBe( + "dns {\n upstream {\n alidns: 'udp://223.5.5.5:53'\n }\n routing {\n response {\n upstream(alidns) -> accept\n }\n request {\n qname(suffix: cn) -> alidns\n }\n }\n}\n" + ); + // An empty routing block indented with tabs nests one tab per level. + const tabbed = 'dns {\n\trouting {\n\t}\n}\n'; + const end = dnsListEnd([{...source, content: tabbed}], 'response')!; + expect(addRule(tabbed, end.anchor, 'qtype(A)', 'accept', false)).toBe('dns {\n\trouting {\n\t\tresponse {\n\t\t\tqtype(A) -> accept\n\t\t}\n\t}\n}\n'); + // No routing block, one closed on a line that holds more, a read-only source, or two to choose between: no end. + expect(dnsListEnd([{...source, content: 'dns {\n upstream {\n }\n}\n'}], 'response')).toBeNull(); + expect(dnsListEnd([{...source, content: 'dns {\n routing {}\n}\n'}], 'response')).toBeNull(); + expect(dnsListEnd([{...source, writable: false}], 'response')).toBeNull(); + expect(dnsListEnd([source, {...source, id: 'other'}], 'response')).toBeNull(); +}); diff --git a/src/dae/ruleText.ts b/src/dae/ruleText.ts index ff8eab5c..cba1e3f9 100644 --- a/src/dae/ruleText.ts +++ b/src/dae/ruleText.ts @@ -8,7 +8,8 @@ export function sourceFor(list: ConfigSource[], source: RuleSource | null | unde } // `target` spans what a listed rule writes after its arrow or fallback colon, with the space before it. -export type RuleAnchor = {from: number; to: number; indent: string; text: string; target?: {from: number; to: number}}; +// `open` and `close` wrap an added rule in a block the text does not have yet. +export type RuleAnchor = {from: number; to: number; indent: string; text: string; target?: {from: number; to: number}; open?: string; close?: string}; // A listed rule as the anchor reads it: where it is, whether it is the fallback, and the target written after the // arrow (an outbound, a DNS upstream or action). type Listed = {kind: 'rule' | 'fallback'; expression: string; source: RuleSource | null}; @@ -93,19 +94,34 @@ export function dnsRuleAnchor(source: ConfigSource, rule: DnsRoutingRule, list: } // Where a rule goes at the end of a DNS list that writes no fallback: before the line closing the list's block, indented // as its rules are. Only a list written as one block, in a writable source, whose closing brace starts its line qualifies. +// A list with no block at all gets a new one, `open` and `close` around the rule, at the end of the one +// `dns { routing { … } }` block under the same conditions; honk reads an absent list as empty. export function dnsListEnd(sources: ConfigSource[], list: DnsRuleListId): {source: ConfigSource; anchor: RuleAnchor} | null { - const found = sources.flatMap(source => - source.content === undefined ? [] : dnsListBlocks(scanConfig(source.content).blocks, list).map(block => ({source, text: source.content!, block})) - ); - if (found.length !== 1 || !found[0].source.writable) return null; - const {source, text, block} = found[0]; + const blocks = (within: (blocks: TextBlock[]) => TextBlock[]) => + sources.flatMap(source => (source.content === undefined ? [] : within(scanConfig(source.content).blocks).map(block => ({source, block})))); + const lists = blocks(scanned => dnsListBlocks(scanned, list)); + if (lists.length) { + const end = lists.length === 1 ? blockEnd(lists[0].source, lists[0].block) : null; + return end && {source: end.source, anchor: end.anchor}; + } + const routings = blocks(scanned => named(scanned, 'dns').flatMap(dns => named(dns.children, 'routing'))); + const end = routings.length === 1 ? blockEnd(routings[0].source, routings[0].block) : null; + if (!end) return null; + const {closing, anchor} = end; + const {indent} = anchor; + const step = indent.startsWith(closing) && indent.length > closing.length ? indent.slice(closing.length) : ' '; + return {source: end.source, anchor: {...anchor, indent: indent + step, open: `${indent}${list} {\n`, close: `${indent}}\n`}}; +} +function blockEnd(source: ConfigSource, block: TextBlock): {source: ConfigSource; anchor: RuleAnchor; closing: string} | null { + const text = source.content!; + if (!source.writable) return null; const from = text.lastIndexOf('\n', block.close - 1) + 1; - const indent = text.slice(from, block.close); - if (from <= block.open || !/^[ \t]*$/.test(indent)) return null; + const closing = text.slice(from, block.close); + if (from <= block.open || !/^[ \t]*$/.test(closing)) return null; const newline = text.indexOf('\n', block.close); const to = newline === -1 ? text.length : newline + 1; - const inner = text.slice(block.open + 1, block.close).match(/\n([ \t]+)\S/)?.[1] ?? indent + (indent.slice(0, indent.length / block.depth) || ' '); - return {source, anchor: {from, to, indent: inner, text: text.slice(from, to)}}; + const inner = text.slice(block.open + 1, block.close).match(/\n([ \t]+)\S/)?.[1] ?? closing + (closing.slice(0, closing.length / block.depth) || ' '); + return {source, anchor: {from, to, indent: inner, text: text.slice(from, to)}, closing}; } // The upstream names `dns { upstream { … } }` defines, in the order written and with their quotes: honk keeps a key's // quotes in its name, so `->` must repeat the key verbatim. @@ -124,7 +140,11 @@ export const ruleOutbounds = (groups: Array<{name: string}>) => [...groups.map(g export function addRule(text: string, anchor: RuleAnchor, condition: string, outbound: string, must: boolean): string | null { return text.slice(anchor.from, anchor.to) === anchor.text - ? text.slice(0, anchor.from) + `${anchor.indent}${ruleLine(condition, outbound, must)}\n` + text.slice(anchor.from) + ? text.slice(0, anchor.from) + + (anchor.open ?? '') + + `${anchor.indent}${ruleLine(condition, outbound, must)}\n` + + (anchor.close ?? '') + + text.slice(anchor.from) : null; } diff --git a/src/features/rules/view.test.ts b/src/features/rules/view.test.ts index d284df8d..01084e84 100644 --- a/src/features/rules/view.test.ts +++ b/src/features/rules/view.test.ts @@ -330,6 +330,12 @@ it('appends DNS rules inside the list block when the fallback is not written, an }); const request = dnsDictionaryView('request', [fallback('asis')], 'g', sources, t, 'en'); expect(request.positions.map(position => position.id)).toEqual(['end']); + expect(request.positions[0]).toEqual({id: 'end', label: t('rule.positionEnd')}); + // A list with no block offers the end of the dns routing block, where the add writes a new one. + const absent = [{...base, content: content.replace(" response {\n qtype(A) -> 'my dns'\n }\n", ''), writable: true}]; + expect(dnsDictionaryView('response', [fallback('accept')], 'g', absent, t, 'en').positions).toEqual([ + {id: 'end', label: t('rule.dns.positionNew', {name: 'response'}), desc: t('rule.dns.positionNewHelp', {name: 'response'})} + ]); expect(request.outbounds.map(({id, label}) => ({id, label}))).toEqual([ {id: "'my dns'", label: 'my dns'}, {id: '"other dns"', label: 'other dns'}, diff --git a/src/features/rules/view.ts b/src/features/rules/view.ts index 75b37e89..4d8ea046 100644 --- a/src/features/rules/view.ts +++ b/src/features/rules/view.ts @@ -134,7 +134,8 @@ function listedRows( fields: (rule: R) => {outbound: string; must: boolean; hits: string; expression?: string}, t: Translator, lang: Lang, - end = false + // The end position of a list whose fallback is not written, when it has one. + end: {id: 'end'; label: string; desc?: string} | null = null ): Pick { const locale = LOCALE[lang]; const byId = new Map(config.map(source => [source.id, source])); @@ -166,7 +167,7 @@ function listedRows( return { rows, positions: [ - ...((fallback?.source ? anchored(fallback) : end) ? [{id: 'end', label: t('rule.positionEnd')}] : []), + ...(fallback?.source ? (anchored(fallback) ? [{id: 'end', label: t('rule.positionEnd')}] : []) : end ? [end] : []), ...rules .filter((_, i) => rows[i].removable) .map(rule => ({id: rule.rule_id, label: t('rule.positionBefore', {n: rule.index + 1}), desc: rule.expression})) @@ -233,6 +234,7 @@ export function dnsDictionaryView( lang: Lang ): DictionaryView { const defined = config.flatMap(source => (source.content === undefined ? [] : dnsUpstreamNames(source.content))); + const end = dnsListEnd(config, list); const known = new Set(defined.map(name => name.toLowerCase())); const named = rules.flatMap(rule => (rule.upstream && !known.has(rule.upstream.toLowerCase()) ? [rule.upstream] : [])); return { @@ -243,7 +245,10 @@ export function dnsDictionaryView( rule => ({expression: dnsCondition(rule), outbound: unquote(dnsRuleTarget(rule)), must: false, hits: '—'}), t, lang, - dnsListEnd(config, list) !== null + end && + (end.anchor.open + ? {id: 'end', label: t('rule.dns.positionNew', {name: list}), desc: t('rule.dns.positionNewHelp', {name: list})} + : {id: 'end', label: t('rule.positionEnd')}) ), caption: generation !== undefined ? t('rule.dictionaryCaption', {n: rules.length, generation}) : null, outbounds: dnsActions(list, [...new Set([...defined, ...named])], t) diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index ac6dbaed..2e019bb5 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1309,6 +1309,8 @@ "rule.dns.kind.keyword": "Domain keyword", "rule.dns.kind.qtype": "Query type", "rule.dns.kind.upstream": "Answering upstream", + "rule.dns.positionNew": "First rule of a new {name} block", + "rule.dns.positionNewHelp": "The dns routing section has no {name} block yet; it is created when the rule is written.", "rule.dns.request": "Request rules", "rule.dns.requestNote": "Checked in order to decide how each query is handled; the fallback applies when no rule matches.", "rule.dns.response": "Response rules", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 8ea3106b..f678390b 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1120,6 +1120,8 @@ "rule.dns.kind.keyword": "域名关键字", "rule.dns.kind.qtype": "查询类型", "rule.dns.kind.upstream": "提供应答的上游", + "rule.dns.positionNew": "新 {name} 区段的第一条规则", + "rule.dns.positionNewHelp": "dns routing 区段尚无 {name} 区段,写入规则时会一并创建。", "rule.dns.request": "请求规则", "rule.dns.requestNote": "按顺序匹配,决定如何处理每个查询;没有规则匹配时使用 fallback。", "rule.dns.response": "应答规则", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 6cf474b2..999d8206 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -1120,6 +1120,8 @@ "rule.dns.kind.keyword": "網域關鍵字", "rule.dns.kind.qtype": "查詢類型", "rule.dns.kind.upstream": "提供回答的上游", + "rule.dns.positionNew": "新 {name} 區段的第一條規則", + "rule.dns.positionNewHelp": "dns routing 區段尚無 {name} 區段,寫入規則時會一併建立。", "rule.dns.request": "請求規則", "rule.dns.requestNote": "依序比對,決定如何處理每個查詢;沒有規則符合時使用 fallback。", "rule.dns.response": "回答規則",